@duckcodeailabs/dql-cli 1.5.0 → 1.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/apps-api.d.ts +71 -4
- package/dist/apps-api.d.ts.map +1 -1
- package/dist/apps-api.js +540 -19
- package/dist/apps-api.js.map +1 -1
- package/dist/apps-api.test.js +45 -2
- package/dist/apps-api.test.js.map +1 -1
- package/dist/assets/dql-notebook/assets/index-BZX1UCr2.js +863 -0
- package/dist/assets/dql-notebook/index.html +1 -1
- package/dist/block-studio-import.d.ts +53 -2
- package/dist/block-studio-import.d.ts.map +1 -1
- package/dist/block-studio-import.js +165 -22
- package/dist/block-studio-import.js.map +1 -1
- package/dist/block-studio-import.test.js +64 -2
- package/dist/block-studio-import.test.js.map +1 -1
- package/dist/commands/app.d.ts.map +1 -1
- package/dist/commands/app.js +6 -0
- package/dist/commands/app.js.map +1 -1
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +8 -5
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/init.test.js +84 -24
- package/dist/commands/init.test.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/local-runtime.d.ts.map +1 -1
- package/dist/local-runtime.js +587 -89
- package/dist/local-runtime.js.map +1 -1
- package/package.json +11 -11
- package/dist/assets/dql-notebook/assets/index-mlfOQ2me.js +0 -857
|
@@ -1,857 +0,0 @@
|
|
|
1
|
-
import{r as Yi,a as hp,g as Wi}from"./react-CRB3T2We.js";import{S as $i,g as Ap,E as Rt,s as Tm,a as je,b as Ip,c as fm,P as pm,d as Sm,e as Rm,F as hm,f as Am,h as mp,V as Im,D as Mn,R as mm,i as Om,C as ln,j as Op,k as et,r as Nm,H as gm,t as xe,l as xm,m as ym,u as Cm,n as Lm,o as _m,p as bm,q as Dm,v as Mm,w as vm,x as Pm,y as wm,z as hs,A as Um,B as Bm,G as Fm,I as km,J as jm,K as Gm,L as Hm,M as Ym,N as Wm,O as $m}from"./codemirror-DJYUkPr1.js";function Vm(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const o in r)if(o!=="default"&&!(o in e)){const i=Object.getOwnPropertyDescriptor(r,o);i&&Object.defineProperty(e,o,i.get?i:{enumerable:!0,get:()=>r[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Va={exports:{}},Qr={};/**
|
|
2
|
-
* @license React
|
|
3
|
-
* react-jsx-runtime.production.min.js
|
|
4
|
-
*
|
|
5
|
-
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
6
|
-
*
|
|
7
|
-
* This source code is licensed under the MIT license found in the
|
|
8
|
-
* LICENSE file in the root directory of this source tree.
|
|
9
|
-
*/var IE;function Xm(){if(IE)return Qr;IE=1;var e=Yi(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function a(l,c,d){var E,u={},T=null,p=null;d!==void 0&&(T=""+d),c.key!==void 0&&(T=""+c.key),c.ref!==void 0&&(p=c.ref);for(E in c)r.call(c,E)&&!i.hasOwnProperty(E)&&(u[E]=c[E]);if(l&&l.defaultProps)for(E in c=l.defaultProps,c)u[E]===void 0&&(u[E]=c[E]);return{$$typeof:t,type:l,key:T,ref:p,props:u,_owner:o.current}}return Qr.Fragment=n,Qr.jsx=a,Qr.jsxs=a,Qr}var mE;function zm(){return mE||(mE=1,Va.exports=Xm()),Va.exports}var s=zm(),As={},OE;function Km(){if(OE)return As;OE=1;var e=hp();return As.createRoot=e.createRoot,As.hydrateRoot=e.hydrateRoot,As}var qm=Km(),f=Yi();const _e=Wi(f),Np=Vm({__proto__:null,default:_e},[f]),Ie={gray0:"#ffffff",gray50:"#f6f8fa",gray100:"#eaeef2",gray200:"#d0d7de",gray300:"#afb8c1",gray400:"#8c959f",gray600:"#57606a",gray900:"#24292f",gray950:"#1c2128",gray975:"#161b22",gray1000:"#0d1117",blue400:"#58a6ff",blue500:"#388bfd",blue600:"#0969da",blue700:"#0550ae",green500:"#56d364",green600:"#1f883d",red500:"#f85149",red600:"#cf222e",yellow500:"#e3b341",yellow600:"#9a6700"},me={1:"4px",2:"8px",3:"12px",4:"16px"},In={sm:"4px",md:"6px",lg:"8px"},Ge={xs:"11px",sm:"12px",md:"14px"},nd={medium:"500",semibold:"600"},fo={overlay:1e3,modal:1100,popover:1200,tooltip:1300},Xa={surfaceBase:Ie.gray1000,surfaceRaised:Ie.gray975,surfaceElevated:Ie.gray950,surfaceOverlay:"rgba(0,0,0,0.7)",surfaceHover:Ie.gray900,surfaceActive:"#1f2d3d",surfaceSunken:Ie.gray1000,borderSubtle:"#21262d",borderDefault:"#30363d",borderStrong:"#484f58",borderFocus:Ie.blue500,textPrimary:"#e6edf3",textSecondary:"#8b949e",textMuted:"#484f58",textDisabled:"#32383f",textInverse:Ie.gray1000,accent:Ie.blue500,accentHover:Ie.blue400,accentMuted:"rgba(56,139,253,0.15)",accentContrast:"#ffffff",success:Ie.green500,warning:Ie.yellow500,danger:Ie.red500,info:Ie.blue400,shadowSm:"0 1px 2px rgba(0,0,0,0.4)",shadowMd:"0 4px 10px rgba(0,0,0,0.45)",shadowLg:"0 12px 28px rgba(0,0,0,0.55)"},Is={surfaceBase:Ie.gray0,surfaceRaised:Ie.gray50,surfaceElevated:Ie.gray0,surfaceOverlay:"rgba(0,0,0,0.4)",surfaceHover:Ie.gray100,surfaceActive:"#dbeafe",surfaceSunken:Ie.gray50,borderSubtle:Ie.gray100,borderDefault:Ie.gray200,borderStrong:Ie.gray300,borderFocus:Ie.blue600,textPrimary:"#1f2328",textSecondary:Ie.gray600,textMuted:Ie.gray400,textDisabled:Ie.gray300,textInverse:Ie.gray0,accent:Ie.blue600,accentHover:Ie.blue700,accentMuted:"rgba(9,105,218,0.12)",accentContrast:"#ffffff",success:Ie.green600,warning:Ie.yellow600,danger:Ie.red600,info:Ie.blue600,shadowSm:"0 1px 2px rgba(31,35,40,0.08)",shadowMd:"0 4px 10px rgba(31,35,40,0.1)",shadowLg:"0 12px 28px rgba(31,35,40,0.15)"},Jm={obsidian:Xa,paper:Is,white:Is,dark:Xa,light:Is,midnight:Xa,arctic:Is};function gp(e){return`--dql-${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function NE(e){const t={};for(const[n,r]of Object.entries(e))t[gp(n)]=r;return t}function Se(e){return`var(${gp(e)})`}const Qm=f.createContext(null);function Zm({theme:e,defaultTheme:t="dark",onThemeChange:n,applyGlobal:r=!1,children:o}){const[i,a]=f.useState(t),l=e??i,c=Jm[l],d=f.useCallback(T=>{e===void 0&&a(T),n==null||n(T)},[e,n]);f.useEffect(()=>{if(!r)return;const T=NE(c),p=document.documentElement;for(const[h,A]of Object.entries(T))p.style.setProperty(h,A);return p.setAttribute("data-theme",l),()=>{for(const h of Object.keys(T))p.style.removeProperty(h);p.removeAttribute("data-theme")}},[r,l,c]);const E=f.useMemo(()=>({theme:l,tokens:c,setTheme:d}),[l,c,d]),u=r?void 0:NE(c);return s.jsx(Qm.Provider,{value:E,children:s.jsx("div",{"data-theme":l,style:u,children:o})})}function ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function gE(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Vi(...e){return t=>{let n=!1;const r=e.map(o=>{const i=gE(o,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){const i=r[o];typeof i=="function"?i():gE(e[o],null)}}}}function be(...e){return f.useCallback(Vi(...e),e)}function eO(e,t){const n=f.createContext(t),r=i=>{const{children:a,...l}=i,c=f.useMemo(()=>l,Object.values(l));return s.jsx(n.Provider,{value:c,children:a})};r.displayName=e+"Provider";function o(i){const a=f.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return[r,o]}function mn(e,t=[]){let n=[];function r(i,a){const l=f.createContext(a),c=n.length;n=[...n,a];const d=u=>{var R;const{scope:T,children:p,...h}=u,A=((R=T==null?void 0:T[e])==null?void 0:R[c])||l,S=f.useMemo(()=>h,Object.values(h));return s.jsx(A.Provider,{value:S,children:p})};d.displayName=i+"Provider";function E(u,T){var A;const p=((A=T==null?void 0:T[e])==null?void 0:A[c])||l,h=f.useContext(p);if(h)return h;if(a!==void 0)return a;throw new Error(`\`${u}\` must be used within \`${i}\``)}return[d,E]}const o=()=>{const i=n.map(a=>f.createContext(a));return function(l){const c=(l==null?void 0:l[e])||i;return f.useMemo(()=>({[`__scope${e}`]:{...l,[e]:c}}),[l,c])}};return o.scopeName=e,[r,tO(o,...t)]}function tO(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){const a=r.reduce((l,{useScope:c,scopeName:d})=>{const u=c(i)[`__scope${d}`];return{...l,...u}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}var rd=hp();const nO=Wi(rd);function Nr(e){const t=rO(e),n=f.forwardRef((r,o)=>{const{children:i,...a}=r,l=f.Children.toArray(i),c=l.find(sO);if(c){const d=c.props.children,E=l.map(u=>u===c?f.Children.count(d)>1?f.Children.only(null):f.isValidElement(d)?d.props.children:null:u);return s.jsx(t,{...a,ref:o,children:f.isValidElement(d)?f.cloneElement(d,void 0,E):null})}return s.jsx(t,{...a,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function rO(e){const t=f.forwardRef((n,r)=>{const{children:o,...i}=n;if(f.isValidElement(o)){const a=aO(o),l=iO(i,o.props);return o.type!==f.Fragment&&(l.ref=r?Vi(r,a):a),f.cloneElement(o,l)}return f.Children.count(o)>1?f.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var xp=Symbol("radix.slottable");function oO(e){const t=({children:n})=>s.jsx(s.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=xp,t}function sO(e){return f.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===xp}function iO(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{const c=i(...l);return o(...l),c}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function aO(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var lO=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ce=lO.reduce((e,t)=>{const n=Nr(`Primitive.${t}`),r=f.forwardRef((o,i)=>{const{asChild:a,...l}=o,c=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),s.jsx(c,{...l,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function yp(e,t){e&&rd.flushSync(()=>e.dispatchEvent(t))}function Tn(e){const t=f.useRef(e);return f.useEffect(()=>{t.current=e}),f.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function cO(e,t=globalThis==null?void 0:globalThis.document){const n=Tn(e);f.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var dO="DismissableLayer",Rc="dismissableLayer.update",EO="dismissableLayer.pointerDownOutside",uO="dismissableLayer.focusOutside",xE,Cp=f.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),wo=f.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:a,onDismiss:l,...c}=e,d=f.useContext(Cp),[E,u]=f.useState(null),T=(E==null?void 0:E.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=f.useState({}),h=be(t,g=>u(g)),A=Array.from(d.layers),[S]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),R=A.indexOf(S),m=E?A.indexOf(E):-1,I=d.layersWithOutsidePointerEventsDisabled.size>0,O=m>=R,N=pO(g=>{const C=g.target,y=[...d.branches].some(w=>w.contains(C));!O||y||(o==null||o(g),a==null||a(g),g.defaultPrevented||l==null||l())},T),x=SO(g=>{const C=g.target;[...d.branches].some(w=>w.contains(C))||(i==null||i(g),a==null||a(g),g.defaultPrevented||l==null||l())},T);return cO(g=>{m===d.layers.size-1&&(r==null||r(g),!g.defaultPrevented&&l&&(g.preventDefault(),l()))},T),f.useEffect(()=>{if(E)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(xE=T.body.style.pointerEvents,T.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(E)),d.layers.add(E),yE(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(T.body.style.pointerEvents=xE)}},[E,T,n,d]),f.useEffect(()=>()=>{E&&(d.layers.delete(E),d.layersWithOutsidePointerEventsDisabled.delete(E),yE())},[E,d]),f.useEffect(()=>{const g=()=>p({});return document.addEventListener(Rc,g),()=>document.removeEventListener(Rc,g)},[]),s.jsx(Ce.div,{...c,ref:h,style:{pointerEvents:I?O?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,x.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,x.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,N.onPointerDownCapture)})});wo.displayName=dO;var TO="DismissableLayerBranch",fO=f.forwardRef((e,t)=>{const n=f.useContext(Cp),r=f.useRef(null),o=be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),s.jsx(Ce.div,{...e,ref:o})});fO.displayName=TO;function pO(e,t=globalThis==null?void 0:globalThis.document){const n=Tn(e),r=f.useRef(!1),o=f.useRef(()=>{});return f.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let c=function(){Lp(EO,n,d,{discrete:!0})};const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=c,t.addEventListener("click",o.current,{once:!0})):c()}else t.removeEventListener("click",o.current);r.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function SO(e,t=globalThis==null?void 0:globalThis.document){const n=Tn(e),r=f.useRef(!1);return f.useEffect(()=>{const o=i=>{i.target&&!r.current&&Lp(uO,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function yE(){const e=new CustomEvent(Rc);document.dispatchEvent(e)}function Lp(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?yp(o,i):o.dispatchEvent(i)}var fn=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{},RO=Np[" useId ".trim().toString()]||(()=>{}),hO=0;function lo(e){const[t,n]=f.useState(RO());return fn(()=>{n(r=>r??String(hO++))},[e]),t?`radix-${t}`:""}const AO=["top","right","bottom","left"],pn=Math.min,Ke=Math.max,di=Math.round,ms=Math.floor,Lt=e=>({x:e,y:e}),IO={left:"right",right:"left",bottom:"top",top:"bottom"};function hc(e,t,n){return Ke(e,pn(t,n))}function jt(e,t){return typeof e=="function"?e(t):e}function Gt(e){return e.split("-")[0]}function Fr(e){return e.split("-")[1]}function od(e){return e==="x"?"y":"x"}function sd(e){return e==="y"?"height":"width"}function yt(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function id(e){return od(yt(e))}function mO(e,t,n){n===void 0&&(n=!1);const r=Fr(e),o=id(e),i=sd(o);let a=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(a=Ei(a)),[a,Ei(a)]}function OO(e){const t=Ei(e);return[Ac(e),t,Ac(t)]}function Ac(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const CE=["left","right"],LE=["right","left"],NO=["top","bottom"],gO=["bottom","top"];function xO(e,t,n){switch(e){case"top":case"bottom":return n?t?LE:CE:t?CE:LE;case"left":case"right":return t?NO:gO;default:return[]}}function yO(e,t,n,r){const o=Fr(e);let i=xO(Gt(e),n==="start",r);return o&&(i=i.map(a=>a+"-"+o),t&&(i=i.concat(i.map(Ac)))),i}function Ei(e){const t=Gt(e);return IO[t]+e.slice(t.length)}function CO(e){return{top:0,right:0,bottom:0,left:0,...e}}function _p(e){return typeof e!="number"?CO(e):{top:e,right:e,bottom:e,left:e}}function ui(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function _E(e,t,n){let{reference:r,floating:o}=e;const i=yt(t),a=id(t),l=sd(a),c=Gt(t),d=i==="y",E=r.x+r.width/2-o.width/2,u=r.y+r.height/2-o.height/2,T=r[l]/2-o[l]/2;let p;switch(c){case"top":p={x:E,y:r.y-o.height};break;case"bottom":p={x:E,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:u};break;case"left":p={x:r.x-o.width,y:u};break;default:p={x:r.x,y:r.y}}switch(Fr(t)){case"start":p[a]-=T*(n&&d?-1:1);break;case"end":p[a]+=T*(n&&d?-1:1);break}return p}async function LO(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:i,rects:a,elements:l,strategy:c}=e,{boundary:d="clippingAncestors",rootBoundary:E="viewport",elementContext:u="floating",altBoundary:T=!1,padding:p=0}=jt(t,e),h=_p(p),S=l[T?u==="floating"?"reference":"floating":u],R=ui(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(S)))==null||n?S:S.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(l.floating)),boundary:d,rootBoundary:E,strategy:c})),m=u==="floating"?{x:r,y:o,width:a.floating.width,height:a.floating.height}:a.reference,I=await(i.getOffsetParent==null?void 0:i.getOffsetParent(l.floating)),O=await(i.isElement==null?void 0:i.isElement(I))?await(i.getScale==null?void 0:i.getScale(I))||{x:1,y:1}:{x:1,y:1},N=ui(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:m,offsetParent:I,strategy:c}):m);return{top:(R.top-N.top+h.top)/O.y,bottom:(N.bottom-R.bottom+h.bottom)/O.y,left:(R.left-N.left+h.left)/O.x,right:(N.right-R.right+h.right)/O.x}}const _O=50,bO=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:a}=n,l=a.detectOverflow?a:{...a,detectOverflow:LO},c=await(a.isRTL==null?void 0:a.isRTL(t));let d=await a.getElementRects({reference:e,floating:t,strategy:o}),{x:E,y:u}=_E(d,r,c),T=r,p=0;const h={};for(let A=0;A<i.length;A++){const S=i[A];if(!S)continue;const{name:R,fn:m}=S,{x:I,y:O,data:N,reset:x}=await m({x:E,y:u,initialPlacement:r,placement:T,strategy:o,middlewareData:h,rects:d,platform:l,elements:{reference:e,floating:t}});E=I??E,u=O??u,h[R]={...h[R],...N},x&&p<_O&&(p++,typeof x=="object"&&(x.placement&&(T=x.placement),x.rects&&(d=x.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:o}):x.rects),{x:E,y:u}=_E(d,T,c)),A=-1)}return{x:E,y:u,placement:T,strategy:o,middlewareData:h}},DO=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:a,elements:l,middlewareData:c}=t,{element:d,padding:E=0}=jt(e,t)||{};if(d==null)return{};const u=_p(E),T={x:n,y:r},p=id(o),h=sd(p),A=await a.getDimensions(d),S=p==="y",R=S?"top":"left",m=S?"bottom":"right",I=S?"clientHeight":"clientWidth",O=i.reference[h]+i.reference[p]-T[p]-i.floating[h],N=T[p]-i.reference[p],x=await(a.getOffsetParent==null?void 0:a.getOffsetParent(d));let g=x?x[I]:0;(!g||!await(a.isElement==null?void 0:a.isElement(x)))&&(g=l.floating[I]||i.floating[h]);const C=O/2-N/2,y=g/2-A[h]/2-1,w=pn(u[R],y),v=pn(u[m],y),B=w,b=g-A[h]-v,L=g/2-A[h]/2+C,D=hc(B,L,b),M=!c.arrow&&Fr(o)!=null&&L!==D&&i.reference[h]/2-(L<B?w:v)-A[h]/2<0,U=M?L<B?L-B:L-b:0;return{[p]:T[p]+U,data:{[p]:D,centerOffset:L-D-U,...M&&{alignmentOffset:U}},reset:M}}}),MO=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:i,rects:a,initialPlacement:l,platform:c,elements:d}=t,{mainAxis:E=!0,crossAxis:u=!0,fallbackPlacements:T,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:h="none",flipAlignment:A=!0,...S}=jt(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const R=Gt(o),m=yt(l),I=Gt(l)===l,O=await(c.isRTL==null?void 0:c.isRTL(d.floating)),N=T||(I||!A?[Ei(l)]:OO(l)),x=h!=="none";!T&&x&&N.push(...yO(l,A,h,O));const g=[l,...N],C=await c.detectOverflow(t,S),y=[];let w=((r=i.flip)==null?void 0:r.overflows)||[];if(E&&y.push(C[R]),u){const L=mO(o,a,O);y.push(C[L[0]],C[L[1]])}if(w=[...w,{placement:o,overflows:y}],!y.every(L=>L<=0)){var v,B;const L=(((v=i.flip)==null?void 0:v.index)||0)+1,D=g[L];if(D&&(!(u==="alignment"?m!==yt(D):!1)||w.every(P=>yt(P.placement)===m?P.overflows[0]>0:!0)))return{data:{index:L,overflows:w},reset:{placement:D}};let M=(B=w.filter(U=>U.overflows[0]<=0).sort((U,P)=>U.overflows[1]-P.overflows[1])[0])==null?void 0:B.placement;if(!M)switch(p){case"bestFit":{var b;const U=(b=w.filter(P=>{if(x){const _=yt(P.placement);return _===m||_==="y"}return!0}).map(P=>[P.placement,P.overflows.filter(_=>_>0).reduce((_,F)=>_+F,0)]).sort((P,_)=>P[1]-_[1])[0])==null?void 0:b[0];U&&(M=U);break}case"initialPlacement":M=l;break}if(o!==M)return{reset:{placement:M}}}return{}}}};function bE(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function DE(e){return AO.some(t=>e[t]>=0)}const vO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:o="referenceHidden",...i}=jt(e,t);switch(o){case"referenceHidden":{const a=await r.detectOverflow(t,{...i,elementContext:"reference"}),l=bE(a,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:DE(l)}}}case"escaped":{const a=await r.detectOverflow(t,{...i,altBoundary:!0}),l=bE(a,n.floating);return{data:{escapedOffsets:l,escaped:DE(l)}}}default:return{}}}}},bp=new Set(["left","top"]);async function PO(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),a=Gt(n),l=Fr(n),c=yt(n)==="y",d=bp.has(a)?-1:1,E=i&&c?-1:1,u=jt(t,e);let{mainAxis:T,crossAxis:p,alignmentAxis:h}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return l&&typeof h=="number"&&(p=l==="end"?h*-1:h),c?{x:p*E,y:T*d}:{x:T*d,y:p*E}}const wO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:i,placement:a,middlewareData:l}=t,c=await PO(t,e);return a===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:o+c.x,y:i+c.y,data:{...c,placement:a}}}}},UO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o,platform:i}=t,{mainAxis:a=!0,crossAxis:l=!1,limiter:c={fn:R=>{let{x:m,y:I}=R;return{x:m,y:I}}},...d}=jt(e,t),E={x:n,y:r},u=await i.detectOverflow(t,d),T=yt(Gt(o)),p=od(T);let h=E[p],A=E[T];if(a){const R=p==="y"?"top":"left",m=p==="y"?"bottom":"right",I=h+u[R],O=h-u[m];h=hc(I,h,O)}if(l){const R=T==="y"?"top":"left",m=T==="y"?"bottom":"right",I=A+u[R],O=A-u[m];A=hc(I,A,O)}const S=c.fn({...t,[p]:h,[T]:A});return{...S,data:{x:S.x-n,y:S.y-r,enabled:{[p]:a,[T]:l}}}}}},BO=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:a}=t,{offset:l=0,mainAxis:c=!0,crossAxis:d=!0}=jt(e,t),E={x:n,y:r},u=yt(o),T=od(u);let p=E[T],h=E[u];const A=jt(l,t),S=typeof A=="number"?{mainAxis:A,crossAxis:0}:{mainAxis:0,crossAxis:0,...A};if(c){const I=T==="y"?"height":"width",O=i.reference[T]-i.floating[I]+S.mainAxis,N=i.reference[T]+i.reference[I]-S.mainAxis;p<O?p=O:p>N&&(p=N)}if(d){var R,m;const I=T==="y"?"width":"height",O=bp.has(Gt(o)),N=i.reference[u]-i.floating[I]+(O&&((R=a.offset)==null?void 0:R[u])||0)+(O?0:S.crossAxis),x=i.reference[u]+i.reference[I]+(O?0:((m=a.offset)==null?void 0:m[u])||0)-(O?S.crossAxis:0);h<N?h=N:h>x&&(h=x)}return{[T]:p,[u]:h}}}},FO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:i,platform:a,elements:l}=t,{apply:c=()=>{},...d}=jt(e,t),E=await a.detectOverflow(t,d),u=Gt(o),T=Fr(o),p=yt(o)==="y",{width:h,height:A}=i.floating;let S,R;u==="top"||u==="bottom"?(S=u,R=T===(await(a.isRTL==null?void 0:a.isRTL(l.floating))?"start":"end")?"left":"right"):(R=u,S=T==="end"?"top":"bottom");const m=A-E.top-E.bottom,I=h-E.left-E.right,O=pn(A-E[S],m),N=pn(h-E[R],I),x=!t.middlewareData.shift;let g=O,C=N;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(C=I),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(g=m),x&&!T){const w=Ke(E.left,0),v=Ke(E.right,0),B=Ke(E.top,0),b=Ke(E.bottom,0);p?C=h-2*(w!==0||v!==0?w+v:Ke(E.left,E.right)):g=A-2*(B!==0||b!==0?B+b:Ke(E.top,E.bottom))}await c({...t,availableWidth:C,availableHeight:g});const y=await a.getDimensions(l.floating);return h!==y.width||A!==y.height?{reset:{rects:!0}}:{}}}};function Xi(){return typeof window<"u"}function kr(e){return Dp(e)?(e.nodeName||"").toLowerCase():"#document"}function Je(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Dt(e){var t;return(t=(Dp(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dp(e){return Xi()?e instanceof Node||e instanceof Je(e).Node:!1}function ht(e){return Xi()?e instanceof Element||e instanceof Je(e).Element:!1}function Wt(e){return Xi()?e instanceof HTMLElement||e instanceof Je(e).HTMLElement:!1}function ME(e){return!Xi()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Je(e).ShadowRoot}function Uo(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=At(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&o!=="inline"&&o!=="contents"}function kO(e){return/^(table|td|th)$/.test(kr(e))}function zi(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const jO=/transform|translate|scale|rotate|perspective|filter/,GO=/paint|layout|strict|content/,yn=e=>!!e&&e!=="none";let za;function ad(e){const t=ht(e)?At(e):e;return yn(t.transform)||yn(t.translate)||yn(t.scale)||yn(t.rotate)||yn(t.perspective)||!ld()&&(yn(t.backdropFilter)||yn(t.filter))||jO.test(t.willChange||"")||GO.test(t.contain||"")}function HO(e){let t=Sn(e);for(;Wt(t)&&!gr(t);){if(ad(t))return t;if(zi(t))return null;t=Sn(t)}return null}function ld(){return za==null&&(za=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),za}function gr(e){return/^(html|body|#document)$/.test(kr(e))}function At(e){return Je(e).getComputedStyle(e)}function Ki(e){return ht(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Sn(e){if(kr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||ME(e)&&e.host||Dt(e);return ME(t)?t.host:t}function Mp(e){const t=Sn(e);return gr(t)?e.ownerDocument?e.ownerDocument.body:e.body:Wt(t)&&Uo(t)?t:Mp(t)}function po(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Mp(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),a=Je(o);if(i){const l=Ic(a);return t.concat(a,a.visualViewport||[],Uo(o)?o:[],l&&n?po(l):[])}else return t.concat(o,po(o,[],n))}function Ic(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function vp(e){const t=At(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Wt(e),i=o?e.offsetWidth:n,a=o?e.offsetHeight:r,l=di(n)!==i||di(r)!==a;return l&&(n=i,r=a),{width:n,height:r,$:l}}function cd(e){return ht(e)?e:e.contextElement}function Sr(e){const t=cd(e);if(!Wt(t))return Lt(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=vp(t);let a=(i?di(n.width):n.width)/r,l=(i?di(n.height):n.height)/o;return(!a||!Number.isFinite(a))&&(a=1),(!l||!Number.isFinite(l))&&(l=1),{x:a,y:l}}const YO=Lt(0);function Pp(e){const t=Je(e);return!ld()||!t.visualViewport?YO:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function WO(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Je(e)?!1:t}function Bn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=cd(e);let a=Lt(1);t&&(r?ht(r)&&(a=Sr(r)):a=Sr(e));const l=WO(i,n,r)?Pp(i):Lt(0);let c=(o.left+l.x)/a.x,d=(o.top+l.y)/a.y,E=o.width/a.x,u=o.height/a.y;if(i){const T=Je(i),p=r&&ht(r)?Je(r):r;let h=T,A=Ic(h);for(;A&&r&&p!==h;){const S=Sr(A),R=A.getBoundingClientRect(),m=At(A),I=R.left+(A.clientLeft+parseFloat(m.paddingLeft))*S.x,O=R.top+(A.clientTop+parseFloat(m.paddingTop))*S.y;c*=S.x,d*=S.y,E*=S.x,u*=S.y,c+=I,d+=O,h=Je(A),A=Ic(h)}}return ui({width:E,height:u,x:c,y:d})}function qi(e,t){const n=Ki(e).scrollLeft;return t?t.left+n:Bn(Dt(e)).left+n}function wp(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-qi(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function $O(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const i=o==="fixed",a=Dt(r),l=t?zi(t.floating):!1;if(r===a||l&&i)return n;let c={scrollLeft:0,scrollTop:0},d=Lt(1);const E=Lt(0),u=Wt(r);if((u||!u&&!i)&&((kr(r)!=="body"||Uo(a))&&(c=Ki(r)),u)){const p=Bn(r);d=Sr(r),E.x=p.x+r.clientLeft,E.y=p.y+r.clientTop}const T=a&&!u&&!i?wp(a,c):Lt(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-c.scrollLeft*d.x+E.x+T.x,y:n.y*d.y-c.scrollTop*d.y+E.y+T.y}}function VO(e){return Array.from(e.getClientRects())}function XO(e){const t=Dt(e),n=Ki(e),r=e.ownerDocument.body,o=Ke(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=Ke(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+qi(e);const l=-n.scrollTop;return At(r).direction==="rtl"&&(a+=Ke(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:a,y:l}}const vE=25;function zO(e,t){const n=Je(e),r=Dt(e),o=n.visualViewport;let i=r.clientWidth,a=r.clientHeight,l=0,c=0;if(o){i=o.width,a=o.height;const E=ld();(!E||E&&t==="fixed")&&(l=o.offsetLeft,c=o.offsetTop)}const d=qi(r);if(d<=0){const E=r.ownerDocument,u=E.body,T=getComputedStyle(u),p=E.compatMode==="CSS1Compat"&&parseFloat(T.marginLeft)+parseFloat(T.marginRight)||0,h=Math.abs(r.clientWidth-u.clientWidth-p);h<=vE&&(i-=h)}else d<=vE&&(i+=d);return{width:i,height:a,x:l,y:c}}function KO(e,t){const n=Bn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Wt(e)?Sr(e):Lt(1),a=e.clientWidth*i.x,l=e.clientHeight*i.y,c=o*i.x,d=r*i.y;return{width:a,height:l,x:c,y:d}}function PE(e,t,n){let r;if(t==="viewport")r=zO(e,n);else if(t==="document")r=XO(Dt(e));else if(ht(t))r=KO(t,n);else{const o=Pp(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return ui(r)}function Up(e,t){const n=Sn(e);return n===t||!ht(n)||gr(n)?!1:At(n).position==="fixed"||Up(n,t)}function qO(e,t){const n=t.get(e);if(n)return n;let r=po(e,[],!1).filter(l=>ht(l)&&kr(l)!=="body"),o=null;const i=At(e).position==="fixed";let a=i?Sn(e):e;for(;ht(a)&&!gr(a);){const l=At(a),c=ad(a);!c&&l.position==="fixed"&&(o=null),(i?!c&&!o:!c&&l.position==="static"&&!!o&&(o.position==="absolute"||o.position==="fixed")||Uo(a)&&!c&&Up(e,a))?r=r.filter(E=>E!==a):o=l,a=Sn(a)}return t.set(e,r),r}function JO(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const a=[...n==="clippingAncestors"?zi(t)?[]:qO(t,this._c):[].concat(n),r],l=PE(t,a[0],o);let c=l.top,d=l.right,E=l.bottom,u=l.left;for(let T=1;T<a.length;T++){const p=PE(t,a[T],o);c=Ke(p.top,c),d=pn(p.right,d),E=pn(p.bottom,E),u=Ke(p.left,u)}return{width:d-u,height:E-c,x:u,y:c}}function QO(e){const{width:t,height:n}=vp(e);return{width:t,height:n}}function ZO(e,t,n){const r=Wt(t),o=Dt(t),i=n==="fixed",a=Bn(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const c=Lt(0);function d(){c.x=qi(o)}if(r||!r&&!i)if((kr(t)!=="body"||Uo(o))&&(l=Ki(t)),r){const p=Bn(t,!0,i,t);c.x=p.x+t.clientLeft,c.y=p.y+t.clientTop}else o&&d();i&&!r&&o&&d();const E=o&&!r&&!i?wp(o,l):Lt(0),u=a.left+l.scrollLeft-c.x-E.x,T=a.top+l.scrollTop-c.y-E.y;return{x:u,y:T,width:a.width,height:a.height}}function Ka(e){return At(e).position==="static"}function wE(e,t){if(!Wt(e)||At(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Dt(e)===n&&(n=n.ownerDocument.body),n}function Bp(e,t){const n=Je(e);if(zi(e))return n;if(!Wt(e)){let o=Sn(e);for(;o&&!gr(o);){if(ht(o)&&!Ka(o))return o;o=Sn(o)}return n}let r=wE(e,t);for(;r&&kO(r)&&Ka(r);)r=wE(r,t);return r&&gr(r)&&Ka(r)&&!ad(r)?n:r||HO(e)||n}const eN=async function(e){const t=this.getOffsetParent||Bp,n=this.getDimensions,r=await n(e.floating);return{reference:ZO(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function tN(e){return At(e).direction==="rtl"}const nN={convertOffsetParentRelativeRectToViewportRelativeRect:$O,getDocumentElement:Dt,getClippingRect:JO,getOffsetParent:Bp,getElementRects:eN,getClientRects:VO,getDimensions:QO,getScale:Sr,isElement:ht,isRTL:tN};function Fp(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function rN(e,t){let n=null,r;const o=Dt(e);function i(){var l;clearTimeout(r),(l=n)==null||l.disconnect(),n=null}function a(l,c){l===void 0&&(l=!1),c===void 0&&(c=1),i();const d=e.getBoundingClientRect(),{left:E,top:u,width:T,height:p}=d;if(l||t(),!T||!p)return;const h=ms(u),A=ms(o.clientWidth-(E+T)),S=ms(o.clientHeight-(u+p)),R=ms(E),I={rootMargin:-h+"px "+-A+"px "+-S+"px "+-R+"px",threshold:Ke(0,pn(1,c))||1};let O=!0;function N(x){const g=x[0].intersectionRatio;if(g!==c){if(!O)return a();g?a(!1,g):r=setTimeout(()=>{a(!1,1e-7)},1e3)}g===1&&!Fp(d,e.getBoundingClientRect())&&a(),O=!1}try{n=new IntersectionObserver(N,{...I,root:o.ownerDocument})}catch{n=new IntersectionObserver(N,I)}n.observe(e)}return a(!0),i}function oN(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,d=cd(e),E=o||i?[...d?po(d):[],...t?po(t):[]]:[];E.forEach(R=>{o&&R.addEventListener("scroll",n,{passive:!0}),i&&R.addEventListener("resize",n)});const u=d&&l?rN(d,n):null;let T=-1,p=null;a&&(p=new ResizeObserver(R=>{let[m]=R;m&&m.target===d&&p&&t&&(p.unobserve(t),cancelAnimationFrame(T),T=requestAnimationFrame(()=>{var I;(I=p)==null||I.observe(t)})),n()}),d&&!c&&p.observe(d),t&&p.observe(t));let h,A=c?Bn(e):null;c&&S();function S(){const R=Bn(e);A&&!Fp(A,R)&&n(),A=R,h=requestAnimationFrame(S)}return n(),()=>{var R;E.forEach(m=>{o&&m.removeEventListener("scroll",n),i&&m.removeEventListener("resize",n)}),u==null||u(),(R=p)==null||R.disconnect(),p=null,c&&cancelAnimationFrame(h)}}const sN=wO,iN=UO,aN=MO,lN=FO,cN=vO,UE=DO,dN=BO,EN=(e,t,n)=>{const r=new Map,o={platform:nN,...n},i={...o.platform,_c:r};return bO(e,t,{...o,platform:i})};var uN=typeof document<"u",TN=function(){},Ks=uN?f.useLayoutEffect:TN;function Ti(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Ti(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Ti(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function kp(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function BE(e,t){const n=kp(e);return Math.round(t*n)/n}function qa(e){const t=f.useRef(e);return Ks(()=>{t.current=e}),t}function fN(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:a}={},transform:l=!0,whileElementsMounted:c,open:d}=e,[E,u]=f.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[T,p]=f.useState(r);Ti(T,r)||p(r);const[h,A]=f.useState(null),[S,R]=f.useState(null),m=f.useCallback(P=>{P!==x.current&&(x.current=P,A(P))},[]),I=f.useCallback(P=>{P!==g.current&&(g.current=P,R(P))},[]),O=i||h,N=a||S,x=f.useRef(null),g=f.useRef(null),C=f.useRef(E),y=c!=null,w=qa(c),v=qa(o),B=qa(d),b=f.useCallback(()=>{if(!x.current||!g.current)return;const P={placement:t,strategy:n,middleware:T};v.current&&(P.platform=v.current),EN(x.current,g.current,P).then(_=>{const F={..._,isPositioned:B.current!==!1};L.current&&!Ti(C.current,F)&&(C.current=F,rd.flushSync(()=>{u(F)}))})},[T,t,n,v,B]);Ks(()=>{d===!1&&C.current.isPositioned&&(C.current.isPositioned=!1,u(P=>({...P,isPositioned:!1})))},[d]);const L=f.useRef(!1);Ks(()=>(L.current=!0,()=>{L.current=!1}),[]),Ks(()=>{if(O&&(x.current=O),N&&(g.current=N),O&&N){if(w.current)return w.current(O,N,b);b()}},[O,N,b,w,y]);const D=f.useMemo(()=>({reference:x,floating:g,setReference:m,setFloating:I}),[m,I]),M=f.useMemo(()=>({reference:O,floating:N}),[O,N]),U=f.useMemo(()=>{const P={position:n,left:0,top:0};if(!M.floating)return P;const _=BE(M.floating,E.x),F=BE(M.floating,E.y);return l?{...P,transform:"translate("+_+"px, "+F+"px)",...kp(M.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:_,top:F}},[n,l,M.floating,E.x,E.y]);return f.useMemo(()=>({...E,update:b,refs:D,elements:M,floatingStyles:U}),[E,b,D,M,U])}const pN=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?UE({element:r.current,padding:o}).fn(n):{}:r?UE({element:r,padding:o}).fn(n):{}}}},SN=(e,t)=>{const n=sN(e);return{name:n.name,fn:n.fn,options:[e,t]}},RN=(e,t)=>{const n=iN(e);return{name:n.name,fn:n.fn,options:[e,t]}},hN=(e,t)=>({fn:dN(e).fn,options:[e,t]}),AN=(e,t)=>{const n=aN(e);return{name:n.name,fn:n.fn,options:[e,t]}},IN=(e,t)=>{const n=lN(e);return{name:n.name,fn:n.fn,options:[e,t]}},mN=(e,t)=>{const n=cN(e);return{name:n.name,fn:n.fn,options:[e,t]}},ON=(e,t)=>{const n=pN(e);return{name:n.name,fn:n.fn,options:[e,t]}};var NN="Arrow",jp=f.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...i}=e;return s.jsx(Ce.svg,{...i,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:s.jsx("polygon",{points:"0,0 30,0 15,10"})})});jp.displayName=NN;var gN=jp;function xN(e){const[t,n]=f.useState(void 0);return fn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let a,l;if("borderBoxSize"in i){const c=i.borderBoxSize,d=Array.isArray(c)?c[0]:c;a=d.inlineSize,l=d.blockSize}else a=e.offsetWidth,l=e.offsetHeight;n({width:a,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var dd="Popper",[Gp,jr]=mn(dd),[yN,Hp]=Gp(dd),Yp=e=>{const{__scopePopper:t,children:n}=e,[r,o]=f.useState(null);return s.jsx(yN,{scope:t,anchor:r,onAnchorChange:o,children:n})};Yp.displayName=dd;var Wp="PopperAnchor",$p=f.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=Hp(Wp,n),a=f.useRef(null),l=be(t,a),c=f.useRef(null);return f.useEffect(()=>{const d=c.current;c.current=(r==null?void 0:r.current)||a.current,d!==c.current&&i.onAnchorChange(c.current)}),r?null:s.jsx(Ce.div,{...o,ref:l})});$p.displayName=Wp;var Ed="PopperContent",[CN,LN]=Gp(Ed),Vp=f.forwardRef((e,t)=>{var Y,G,J,te,re,oe;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:i="center",alignOffset:a=0,arrowPadding:l=0,avoidCollisions:c=!0,collisionBoundary:d=[],collisionPadding:E=0,sticky:u="partial",hideWhenDetached:T=!1,updatePositionStrategy:p="optimized",onPlaced:h,...A}=e,S=Hp(Ed,n),[R,m]=f.useState(null),I=be(t,V=>m(V)),[O,N]=f.useState(null),x=xN(O),g=(x==null?void 0:x.width)??0,C=(x==null?void 0:x.height)??0,y=r+(i!=="center"?"-"+i:""),w=typeof E=="number"?E:{top:0,right:0,bottom:0,left:0,...E},v=Array.isArray(d)?d:[d],B=v.length>0,b={padding:w,boundary:v.filter(bN),altBoundary:B},{refs:L,floatingStyles:D,placement:M,isPositioned:U,middlewareData:P}=fN({strategy:"fixed",placement:y,whileElementsMounted:(...V)=>oN(...V,{animationFrame:p==="always"}),elements:{reference:S.anchor},middleware:[SN({mainAxis:o+C,alignmentAxis:a}),c&&RN({mainAxis:!0,crossAxis:!1,limiter:u==="partial"?hN():void 0,...b}),c&&AN({...b}),IN({...b,apply:({elements:V,rects:le,availableWidth:Te,availableHeight:de})=>{const{width:ne,height:Re}=le.reference,Oe=V.floating.style;Oe.setProperty("--radix-popper-available-width",`${Te}px`),Oe.setProperty("--radix-popper-available-height",`${de}px`),Oe.setProperty("--radix-popper-anchor-width",`${ne}px`),Oe.setProperty("--radix-popper-anchor-height",`${Re}px`)}}),O&&ON({element:O,padding:l}),DN({arrowWidth:g,arrowHeight:C}),T&&mN({strategy:"referenceHidden",...b})]}),[_,F]=Kp(M),k=Tn(h);fn(()=>{U&&(k==null||k())},[U,k]);const H=(Y=P.arrow)==null?void 0:Y.x,Q=(G=P.arrow)==null?void 0:G.y,q=((J=P.arrow)==null?void 0:J.centerOffset)!==0,[$,Z]=f.useState();return fn(()=>{R&&Z(window.getComputedStyle(R).zIndex)},[R]),s.jsx("div",{ref:L.setFloating,"data-radix-popper-content-wrapper":"",style:{...D,transform:U?D.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:$,"--radix-popper-transform-origin":[(te=P.transformOrigin)==null?void 0:te.x,(re=P.transformOrigin)==null?void 0:re.y].join(" "),...((oe=P.hide)==null?void 0:oe.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:s.jsx(CN,{scope:n,placedSide:_,onArrowChange:N,arrowX:H,arrowY:Q,shouldHideArrow:q,children:s.jsx(Ce.div,{"data-side":_,"data-align":F,...A,ref:I,style:{...A.style,animation:U?void 0:"none"}})})})});Vp.displayName=Ed;var Xp="PopperArrow",_N={top:"bottom",right:"left",bottom:"top",left:"right"},zp=f.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,i=LN(Xp,r),a=_N[i.placedSide];return s.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:s.jsx(gN,{...o,ref:n,style:{...o.style,display:"block"}})})});zp.displayName=Xp;function bN(e){return e!==null}var DN=e=>({name:"transformOrigin",options:e,fn(t){var S,R,m;const{placement:n,rects:r,middlewareData:o}=t,a=((S=o.arrow)==null?void 0:S.centerOffset)!==0,l=a?0:e.arrowWidth,c=a?0:e.arrowHeight,[d,E]=Kp(n),u={start:"0%",center:"50%",end:"100%"}[E],T=(((R=o.arrow)==null?void 0:R.x)??0)+l/2,p=(((m=o.arrow)==null?void 0:m.y)??0)+c/2;let h="",A="";return d==="bottom"?(h=a?u:`${T}px`,A=`${-c}px`):d==="top"?(h=a?u:`${T}px`,A=`${r.floating.height+c}px`):d==="right"?(h=`${-c}px`,A=a?u:`${p}px`):d==="left"&&(h=`${r.floating.width+c}px`,A=a?u:`${p}px`),{data:{x:h,y:A}}}});function Kp(e){const[t,n="center"]=e.split("-");return[t,n]}var MN=Yp,Ji=$p,ud=Vp,Td=zp,vN="Portal",Bo=f.forwardRef((e,t)=>{var l;const{container:n,...r}=e,[o,i]=f.useState(!1);fn(()=>i(!0),[]);const a=n||o&&((l=globalThis==null?void 0:globalThis.document)==null?void 0:l.body);return a?nO.createPortal(s.jsx(Ce.div,{...r,ref:t}),a):null});Bo.displayName=vN;function PN(e,t){return f.useReducer((n,r)=>t[n][r]??n,e)}var ot=e=>{const{present:t,children:n}=e,r=wN(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),i=be(r.ref,UN(o));return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:i}):null};ot.displayName="Presence";function wN(e){const[t,n]=f.useState(),r=f.useRef(null),o=f.useRef(e),i=f.useRef("none"),a=e?"mounted":"unmounted",[l,c]=PN(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const d=Os(r.current);i.current=l==="mounted"?d:"none"},[l]),fn(()=>{const d=r.current,E=o.current;if(E!==e){const T=i.current,p=Os(d);e?c("MOUNT"):p==="none"||(d==null?void 0:d.display)==="none"?c("UNMOUNT"):c(E&&T!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),fn(()=>{if(t){let d;const E=t.ownerDocument.defaultView??window,u=p=>{const A=Os(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&A&&(c("ANIMATION_END"),!o.current)){const S=t.style.animationFillMode;t.style.animationFillMode="forwards",d=E.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=S)})}},T=p=>{p.target===t&&(i.current=Os(r.current))};return t.addEventListener("animationstart",T),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{E.clearTimeout(d),t.removeEventListener("animationstart",T),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:f.useCallback(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function Os(e){return(e==null?void 0:e.animationName)||"none"}function UN(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var BN=Np[" useInsertionEffect ".trim().toString()]||fn;function fd({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,i,a]=FN({defaultProp:t,onChange:n}),l=e!==void 0,c=l?e:o;{const E=f.useRef(e!==void 0);f.useEffect(()=>{const u=E.current;u!==l&&console.warn(`${r} is changing from ${u?"controlled":"uncontrolled"} to ${l?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),E.current=l},[l,r])}const d=f.useCallback(E=>{var u;if(l){const T=kN(E)?E(e):E;T!==e&&((u=a.current)==null||u.call(a,T))}else i(E)},[l,e,i,a]);return[c,d]}function FN({defaultProp:e,onChange:t}){const[n,r]=f.useState(e),o=f.useRef(n),i=f.useRef(t);return BN(()=>{i.current=t},[t]),f.useEffect(()=>{var a;o.current!==n&&((a=i.current)==null||a.call(i,n),o.current=n)},[n,o]),[n,r,i]}function kN(e){return typeof e=="function"}var jN=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),GN="VisuallyHidden",qp=f.forwardRef((e,t)=>s.jsx(Ce.span,{...e,ref:t,style:{...jN,...e.style}}));qp.displayName=GN;var HN=qp,[Qi]=mn("Tooltip",[jr]),Zi=jr(),Jp="TooltipProvider",YN=700,mc="tooltip.open",[WN,pd]=Qi(Jp),Qp=e=>{const{__scopeTooltip:t,delayDuration:n=YN,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,a=f.useRef(!0),l=f.useRef(!1),c=f.useRef(0);return f.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),s.jsx(WN,{scope:t,isOpenDelayedRef:a,delayDuration:n,onOpen:f.useCallback(()=>{window.clearTimeout(c.current),a.current=!1},[]),onClose:f.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>a.current=!0,r)},[r]),isPointerInTransitRef:l,onPointerInTransitChange:f.useCallback(d=>{l.current=d},[]),disableHoverableContent:o,children:i})};Qp.displayName=Jp;var So="Tooltip",[$N,Fo]=Qi(So),Zp=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o,onOpenChange:i,disableHoverableContent:a,delayDuration:l}=e,c=pd(So,e.__scopeTooltip),d=Zi(t),[E,u]=f.useState(null),T=lo(),p=f.useRef(0),h=a??c.disableHoverableContent,A=l??c.delayDuration,S=f.useRef(!1),[R,m]=fd({prop:r,defaultProp:o??!1,onChange:g=>{g?(c.onOpen(),document.dispatchEvent(new CustomEvent(mc))):c.onClose(),i==null||i(g)},caller:So}),I=f.useMemo(()=>R?S.current?"delayed-open":"instant-open":"closed",[R]),O=f.useCallback(()=>{window.clearTimeout(p.current),p.current=0,S.current=!1,m(!0)},[m]),N=f.useCallback(()=>{window.clearTimeout(p.current),p.current=0,m(!1)},[m]),x=f.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{S.current=!0,m(!0),p.current=0},A)},[A,m]);return f.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),s.jsx(MN,{...d,children:s.jsx($N,{scope:t,contentId:T,open:R,stateAttribute:I,trigger:E,onTriggerChange:u,onTriggerEnter:f.useCallback(()=>{c.isOpenDelayedRef.current?x():O()},[c.isOpenDelayedRef,x,O]),onTriggerLeave:f.useCallback(()=>{h?N():(window.clearTimeout(p.current),p.current=0)},[N,h]),onOpen:O,onClose:N,disableHoverableContent:h,children:n})})};Zp.displayName=So;var Oc="TooltipTrigger",eS=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Fo(Oc,n),i=pd(Oc,n),a=Zi(n),l=f.useRef(null),c=be(t,l,o.onTriggerChange),d=f.useRef(!1),E=f.useRef(!1),u=f.useCallback(()=>d.current=!1,[]);return f.useEffect(()=>()=>document.removeEventListener("pointerup",u),[u]),s.jsx(Ji,{asChild:!0,...a,children:s.jsx(Ce.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...r,ref:c,onPointerMove:ue(e.onPointerMove,T=>{T.pointerType!=="touch"&&!E.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),E.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),E.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{o.open&&o.onClose(),d.current=!0,document.addEventListener("pointerup",u,{once:!0})}),onFocus:ue(e.onFocus,()=>{d.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})})});eS.displayName=Oc;var Sd="TooltipPortal",[VN,XN]=Qi(Sd,{forceMount:void 0}),tS=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:o}=e,i=Fo(Sd,t);return s.jsx(VN,{scope:t,forceMount:n,children:s.jsx(ot,{present:n||i.open,children:s.jsx(Bo,{asChild:!0,container:o,children:r})})})};tS.displayName=Sd;var xr="TooltipContent",nS=f.forwardRef((e,t)=>{const n=XN(xr,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,a=Fo(xr,e.__scopeTooltip);return s.jsx(ot,{present:r||a.open,children:a.disableHoverableContent?s.jsx(rS,{side:o,...i,ref:t}):s.jsx(zN,{side:o,...i,ref:t})})}),zN=f.forwardRef((e,t)=>{const n=Fo(xr,e.__scopeTooltip),r=pd(xr,e.__scopeTooltip),o=f.useRef(null),i=be(t,o),[a,l]=f.useState(null),{trigger:c,onClose:d}=n,E=o.current,{onPointerInTransitChange:u}=r,T=f.useCallback(()=>{l(null),u(!1)},[u]),p=f.useCallback((h,A)=>{const S=h.currentTarget,R={x:h.clientX,y:h.clientY},m=ZN(R,S.getBoundingClientRect()),I=eg(R,m),O=tg(A.getBoundingClientRect()),N=rg([...I,...O]);l(N),u(!0)},[u]);return f.useEffect(()=>()=>T(),[T]),f.useEffect(()=>{if(c&&E){const h=S=>p(S,E),A=S=>p(S,c);return c.addEventListener("pointerleave",h),E.addEventListener("pointerleave",A),()=>{c.removeEventListener("pointerleave",h),E.removeEventListener("pointerleave",A)}}},[c,E,p,T]),f.useEffect(()=>{if(a){const h=A=>{const S=A.target,R={x:A.clientX,y:A.clientY},m=(c==null?void 0:c.contains(S))||(E==null?void 0:E.contains(S)),I=!ng(R,a);m?T():I&&(T(),d())};return document.addEventListener("pointermove",h),()=>document.removeEventListener("pointermove",h)}},[c,E,a,d,T]),s.jsx(rS,{...e,ref:i})}),[KN,qN]=Qi(So,{isInside:!1}),JN=oO("TooltipContent"),rS=f.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:a,...l}=e,c=Fo(xr,n),d=Zi(n),{onClose:E}=c;return f.useEffect(()=>(document.addEventListener(mc,E),()=>document.removeEventListener(mc,E)),[E]),f.useEffect(()=>{if(c.trigger){const u=T=>{const p=T.target;p!=null&&p.contains(c.trigger)&&E()};return window.addEventListener("scroll",u,{capture:!0}),()=>window.removeEventListener("scroll",u,{capture:!0})}},[c.trigger,E]),s.jsx(wo,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:u=>u.preventDefault(),onDismiss:E,children:s.jsxs(ud,{"data-state":c.stateAttribute,...d,...l,ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[s.jsx(JN,{children:r}),s.jsx(KN,{scope:n,isInside:!0,children:s.jsx(HN,{id:c.contentId,role:"tooltip",children:o||r})})]})})});nS.displayName=xr;var oS="TooltipArrow",QN=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Zi(n);return qN(oS,n).isInside?null:s.jsx(Td,{...o,...r,ref:t})});QN.displayName=oS;function ZN(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function eg(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function tg(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function ng(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,a=t.length-1;i<t.length;a=i++){const l=t[i],c=t[a],d=l.x,E=l.y,u=c.x,T=c.y;E>r!=T>r&&n<(u-d)*(r-E)/(T-E)+d&&(o=!o)}return o}function rg(e){const t=e.slice();return t.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),og(t)}function og(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const o=e[r];for(;t.length>=2;){const i=t[t.length-1],a=t[t.length-2];if((i.x-a.x)*(o.y-a.y)>=(i.y-a.y)*(o.x-a.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const i=n[n.length-1],a=n[n.length-2];if((i.x-a.x)*(o.y-a.y)>=(i.y-a.y)*(o.x-a.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var sg=Qp,ig=Zp,ag=eS,lg=tS,cg=nS;function sS({content:e,children:t,side:n="right",align:r="center",sideOffset:o=6,delayMs:i=200,container:a}){return s.jsxs(ig,{delayDuration:i,children:[s.jsx(ag,{asChild:!0,children:t}),s.jsx(lg,{container:a,children:s.jsx(cg,{side:n,align:r,sideOffset:o,style:{background:Se("surfaceElevated"),color:Se("textPrimary"),border:`1px solid ${Se("borderDefault")}`,borderRadius:In.sm,padding:`${me[1]} ${me[2]}`,fontSize:Ge.sm,boxShadow:Se("shadowMd"),zIndex:fo.tooltip,userSelect:"none"},children:e})})]})}const dg=sg;var Ja="focusScope.autoFocusOnMount",Qa="focusScope.autoFocusOnUnmount",FE={bubbles:!1,cancelable:!0},Eg="FocusScope",ea=f.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...a}=e,[l,c]=f.useState(null),d=Tn(o),E=Tn(i),u=f.useRef(null),T=be(t,A=>c(A)),p=f.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;f.useEffect(()=>{if(r){let A=function(I){if(p.paused||!l)return;const O=I.target;l.contains(O)?u.current=O:on(u.current,{select:!0})},S=function(I){if(p.paused||!l)return;const O=I.relatedTarget;O!==null&&(l.contains(O)||on(u.current,{select:!0}))},R=function(I){if(document.activeElement===document.body)for(const N of I)N.removedNodes.length>0&&on(l)};document.addEventListener("focusin",A),document.addEventListener("focusout",S);const m=new MutationObserver(R);return l&&m.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",A),document.removeEventListener("focusout",S),m.disconnect()}}},[r,l,p.paused]),f.useEffect(()=>{if(l){jE.add(p);const A=document.activeElement;if(!l.contains(A)){const R=new CustomEvent(Ja,FE);l.addEventListener(Ja,d),l.dispatchEvent(R),R.defaultPrevented||(ug(Rg(iS(l)),{select:!0}),document.activeElement===A&&on(l))}return()=>{l.removeEventListener(Ja,d),setTimeout(()=>{const R=new CustomEvent(Qa,FE);l.addEventListener(Qa,E),l.dispatchEvent(R),R.defaultPrevented||on(A??document.body,{select:!0}),l.removeEventListener(Qa,E),jE.remove(p)},0)}}},[l,d,E,p]);const h=f.useCallback(A=>{if(!n&&!r||p.paused)return;const S=A.key==="Tab"&&!A.altKey&&!A.ctrlKey&&!A.metaKey,R=document.activeElement;if(S&&R){const m=A.currentTarget,[I,O]=Tg(m);I&&O?!A.shiftKey&&R===O?(A.preventDefault(),n&&on(I,{select:!0})):A.shiftKey&&R===I&&(A.preventDefault(),n&&on(O,{select:!0})):R===m&&A.preventDefault()}},[n,r,p.paused]);return s.jsx(Ce.div,{tabIndex:-1,...a,ref:T,onKeyDown:h})});ea.displayName=Eg;function ug(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(on(r,{select:t}),document.activeElement!==n)return}function Tg(e){const t=iS(e),n=kE(t,e),r=kE(t.reverse(),e);return[n,r]}function iS(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function kE(e,t){for(const n of e)if(!fg(n,{upTo:t}))return n}function fg(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function pg(e){return e instanceof HTMLInputElement&&"select"in e}function on(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&pg(e)&&t&&e.select()}}var jE=Sg();function Sg(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=GE(e,t),e.unshift(t)},remove(t){var n;e=GE(e,t),(n=e[0])==null||n.resume()}}}function GE(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Rg(e){return e.filter(t=>t.tagName!=="A")}var Za=0;function Rd(){f.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??HE()),document.body.insertAdjacentElement("beforeend",e[1]??HE()),Za++,()=>{Za===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Za--}},[])}function HE(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var xt=function(){return xt=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},xt.apply(this,arguments)};function aS(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function hg(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))}var qs="right-scroll-bar-position",Js="width-before-scroll-bar",Ag="with-scroll-bars-hidden",Ig="--removed-body-scroll-bar-size";function el(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function mg(e,t){var n=f.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Og=typeof window<"u"?f.useLayoutEffect:f.useEffect,YE=new WeakMap;function Ng(e,t){var n=mg(null,function(r){return e.forEach(function(o){return el(o,r)})});return Og(function(){var r=YE.get(n);if(r){var o=new Set(r),i=new Set(e),a=n.current;o.forEach(function(l){i.has(l)||el(l,null)}),i.forEach(function(l){o.has(l)||el(l,a)})}YE.set(n,e)},[e]),n}function gg(e){return e}function xg(e,t){t===void 0&&(t=gg);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(i){var a=t(i,r);return n.push(a),function(){n=n.filter(function(l){return l!==a})}},assignSyncMedium:function(i){for(r=!0;n.length;){var a=n;n=[],a.forEach(i)}n={push:function(l){return i(l)},filter:function(){return n}}},assignMedium:function(i){r=!0;var a=[];if(n.length){var l=n;n=[],l.forEach(i),a=n}var c=function(){var E=a;a=[],E.forEach(i)},d=function(){return Promise.resolve().then(c)};d(),n={push:function(E){a.push(E),d()},filter:function(E){return a=a.filter(E),n}}}};return o}function yg(e){e===void 0&&(e={});var t=xg(null);return t.options=xt({async:!0,ssr:!1},e),t}var lS=function(e){var t=e.sideCar,n=aS(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return f.createElement(r,xt({},n))};lS.isSideCarExport=!0;function Cg(e,t){return e.useMedium(t),lS}var cS=yg(),tl=function(){},ta=f.forwardRef(function(e,t){var n=f.useRef(null),r=f.useState({onScrollCapture:tl,onWheelCapture:tl,onTouchMoveCapture:tl}),o=r[0],i=r[1],a=e.forwardProps,l=e.children,c=e.className,d=e.removeScrollBar,E=e.enabled,u=e.shards,T=e.sideCar,p=e.noRelative,h=e.noIsolation,A=e.inert,S=e.allowPinchZoom,R=e.as,m=R===void 0?"div":R,I=e.gapMode,O=aS(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),N=T,x=Ng([n,t]),g=xt(xt({},O),o);return f.createElement(f.Fragment,null,E&&f.createElement(N,{sideCar:cS,removeScrollBar:d,shards:u,noRelative:p,noIsolation:h,inert:A,setCallbacks:i,allowPinchZoom:!!S,lockRef:n,gapMode:I}),a?f.cloneElement(f.Children.only(l),xt(xt({},g),{ref:x})):f.createElement(m,xt({},g,{className:c,ref:x}),l))});ta.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};ta.classNames={fullWidth:Js,zeroRight:qs};var Lg=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function _g(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Lg();return t&&e.setAttribute("nonce",t),e}function bg(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Dg(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Mg=function(){var e=0,t=null;return{add:function(n){e==0&&(t=_g())&&(bg(t,n),Dg(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},vg=function(){var e=Mg();return function(t,n){f.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},dS=function(){var e=vg(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Pg={left:0,top:0,right:0,gap:0},nl=function(e){return parseInt(e||"",10)||0},wg=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[nl(n),nl(r),nl(o)]},Ug=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Pg;var t=wg(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Bg=dS(),Rr="data-scroll-locked",Fg=function(e,t,n,r){var o=e.left,i=e.top,a=e.right,l=e.gap;return n===void 0&&(n="margin"),`
|
|
10
|
-
.`.concat(Ag,` {
|
|
11
|
-
overflow: hidden `).concat(r,`;
|
|
12
|
-
padding-right: `).concat(l,"px ").concat(r,`;
|
|
13
|
-
}
|
|
14
|
-
body[`).concat(Rr,`] {
|
|
15
|
-
overflow: hidden `).concat(r,`;
|
|
16
|
-
overscroll-behavior: contain;
|
|
17
|
-
`).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&`
|
|
18
|
-
padding-left: `.concat(o,`px;
|
|
19
|
-
padding-top: `).concat(i,`px;
|
|
20
|
-
padding-right: `).concat(a,`px;
|
|
21
|
-
margin-left:0;
|
|
22
|
-
margin-top:0;
|
|
23
|
-
margin-right: `).concat(l,"px ").concat(r,`;
|
|
24
|
-
`),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),`
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
.`).concat(qs,` {
|
|
28
|
-
right: `).concat(l,"px ").concat(r,`;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
.`).concat(Js,` {
|
|
32
|
-
margin-right: `).concat(l,"px ").concat(r,`;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
.`).concat(qs," .").concat(qs,` {
|
|
36
|
-
right: 0 `).concat(r,`;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
.`).concat(Js," .").concat(Js,` {
|
|
40
|
-
margin-right: 0 `).concat(r,`;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
body[`).concat(Rr,`] {
|
|
44
|
-
`).concat(Ig,": ").concat(l,`px;
|
|
45
|
-
}
|
|
46
|
-
`)},WE=function(){var e=parseInt(document.body.getAttribute(Rr)||"0",10);return isFinite(e)?e:0},kg=function(){f.useEffect(function(){return document.body.setAttribute(Rr,(WE()+1).toString()),function(){var e=WE()-1;e<=0?document.body.removeAttribute(Rr):document.body.setAttribute(Rr,e.toString())}},[])},jg=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;kg();var i=f.useMemo(function(){return Ug(o)},[o]);return f.createElement(Bg,{styles:Fg(i,!t,o,n?"":"!important")})},Nc=!1;if(typeof window<"u")try{var Ns=Object.defineProperty({},"passive",{get:function(){return Nc=!0,!0}});window.addEventListener("test",Ns,Ns),window.removeEventListener("test",Ns,Ns)}catch{Nc=!1}var nr=Nc?{passive:!1}:!1,Gg=function(e){return e.tagName==="TEXTAREA"},ES=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Gg(e)&&n[t]==="visible")},Hg=function(e){return ES(e,"overflowY")},Yg=function(e){return ES(e,"overflowX")},$E=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=uS(e,r);if(o){var i=TS(e,r),a=i[1],l=i[2];if(a>l)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Wg=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},$g=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},uS=function(e,t){return e==="v"?Hg(t):Yg(t)},TS=function(e,t){return e==="v"?Wg(t):$g(t)},Vg=function(e,t){return e==="h"&&t==="rtl"?-1:1},Xg=function(e,t,n,r,o){var i=Vg(e,window.getComputedStyle(t).direction),a=i*r,l=n.target,c=t.contains(l),d=!1,E=a>0,u=0,T=0;do{if(!l)break;var p=TS(e,l),h=p[0],A=p[1],S=p[2],R=A-S-i*h;(h||R)&&uS(e,l)&&(u+=R,T+=h);var m=l.parentNode;l=m&&m.nodeType===Node.DOCUMENT_FRAGMENT_NODE?m.host:m}while(!c&&l!==document.body||c&&(t.contains(l)||t===l));return(E&&Math.abs(u)<1||!E&&Math.abs(T)<1)&&(d=!0),d},gs=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},VE=function(e){return[e.deltaX,e.deltaY]},XE=function(e){return e&&"current"in e?e.current:e},zg=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Kg=function(e){return`
|
|
47
|
-
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
48
|
-
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
49
|
-
`)},qg=0,rr=[];function Jg(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(qg++)[0],i=f.useState(dS)[0],a=f.useRef(e);f.useEffect(function(){a.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var A=hg([e.lockRef.current],(e.shards||[]).map(XE),!0).filter(Boolean);return A.forEach(function(S){return S.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),A.forEach(function(S){return S.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=f.useCallback(function(A,S){if("touches"in A&&A.touches.length===2||A.type==="wheel"&&A.ctrlKey)return!a.current.allowPinchZoom;var R=gs(A),m=n.current,I="deltaX"in A?A.deltaX:m[0]-R[0],O="deltaY"in A?A.deltaY:m[1]-R[1],N,x=A.target,g=Math.abs(I)>Math.abs(O)?"h":"v";if("touches"in A&&g==="h"&&x.type==="range")return!1;var C=window.getSelection(),y=C&&C.anchorNode,w=y?y===x||y.contains(x):!1;if(w)return!1;var v=$E(g,x);if(!v)return!0;if(v?N=g:(N=g==="v"?"h":"v",v=$E(g,x)),!v)return!1;if(!r.current&&"changedTouches"in A&&(I||O)&&(r.current=N),!N)return!0;var B=r.current||N;return Xg(B,S,A,B==="h"?I:O)},[]),c=f.useCallback(function(A){var S=A;if(!(!rr.length||rr[rr.length-1]!==i)){var R="deltaY"in S?VE(S):gs(S),m=t.current.filter(function(N){return N.name===S.type&&(N.target===S.target||S.target===N.shadowParent)&&zg(N.delta,R)})[0];if(m&&m.should){S.cancelable&&S.preventDefault();return}if(!m){var I=(a.current.shards||[]).map(XE).filter(Boolean).filter(function(N){return N.contains(S.target)}),O=I.length>0?l(S,I[0]):!a.current.noIsolation;O&&S.cancelable&&S.preventDefault()}}},[]),d=f.useCallback(function(A,S,R,m){var I={name:A,delta:S,target:R,should:m,shadowParent:Qg(R)};t.current.push(I),setTimeout(function(){t.current=t.current.filter(function(O){return O!==I})},1)},[]),E=f.useCallback(function(A){n.current=gs(A),r.current=void 0},[]),u=f.useCallback(function(A){d(A.type,VE(A),A.target,l(A,e.lockRef.current))},[]),T=f.useCallback(function(A){d(A.type,gs(A),A.target,l(A,e.lockRef.current))},[]);f.useEffect(function(){return rr.push(i),e.setCallbacks({onScrollCapture:u,onWheelCapture:u,onTouchMoveCapture:T}),document.addEventListener("wheel",c,nr),document.addEventListener("touchmove",c,nr),document.addEventListener("touchstart",E,nr),function(){rr=rr.filter(function(A){return A!==i}),document.removeEventListener("wheel",c,nr),document.removeEventListener("touchmove",c,nr),document.removeEventListener("touchstart",E,nr)}},[]);var p=e.removeScrollBar,h=e.inert;return f.createElement(f.Fragment,null,h?f.createElement(i,{styles:Kg(o)}):null,p?f.createElement(jg,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Qg(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Zg=Cg(cS,Jg);var na=f.forwardRef(function(e,t){return f.createElement(ta,xt({},e,{ref:t,sideCar:Zg}))});na.classNames=ta.classNames;var ex=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},or=new WeakMap,xs=new WeakMap,ys={},rl=0,fS=function(e){return e&&(e.host||fS(e.parentNode))},tx=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=fS(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},nx=function(e,t,n,r){var o=tx(t,Array.isArray(e)?e:[e]);ys[n]||(ys[n]=new WeakMap);var i=ys[n],a=[],l=new Set,c=new Set(o),d=function(u){!u||l.has(u)||(l.add(u),d(u.parentNode))};o.forEach(d);var E=function(u){!u||c.has(u)||Array.prototype.forEach.call(u.children,function(T){if(l.has(T))E(T);else try{var p=T.getAttribute(r),h=p!==null&&p!=="false",A=(or.get(T)||0)+1,S=(i.get(T)||0)+1;or.set(T,A),i.set(T,S),a.push(T),A===1&&h&&xs.set(T,!0),S===1&&T.setAttribute(n,"true"),h||T.setAttribute(r,"true")}catch(R){console.error("aria-hidden: cannot operate on ",T,R)}})};return E(t),l.clear(),rl++,function(){a.forEach(function(u){var T=or.get(u)-1,p=i.get(u)-1;or.set(u,T),i.set(u,p),T||(xs.has(u)||u.removeAttribute(r),xs.delete(u)),p||u.removeAttribute(n)}),rl--,rl||(or=new WeakMap,or=new WeakMap,xs=new WeakMap,ys={})}},hd=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=ex(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),nx(r,o,n,"aria-hidden")):function(){return null}},ra="Dialog",[pS]=mn(ra),[rx,It]=pS(ra),SS=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:a=!0}=e,l=f.useRef(null),c=f.useRef(null),[d,E]=fd({prop:r,defaultProp:o??!1,onChange:i,caller:ra});return s.jsx(rx,{scope:t,triggerRef:l,contentRef:c,contentId:lo(),titleId:lo(),descriptionId:lo(),open:d,onOpenChange:E,onOpenToggle:f.useCallback(()=>E(u=>!u),[E]),modal:a,children:n})};SS.displayName=ra;var RS="DialogTrigger",ox=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=It(RS,n),i=be(t,o.triggerRef);return s.jsx(Ce.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":md(o.open),...r,ref:i,onClick:ue(e.onClick,o.onOpenToggle)})});ox.displayName=RS;var Ad="DialogPortal",[sx,hS]=pS(Ad,{forceMount:void 0}),AS=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=It(Ad,t);return s.jsx(sx,{scope:t,forceMount:n,children:f.Children.map(r,a=>s.jsx(ot,{present:n||i.open,children:s.jsx(Bo,{asChild:!0,container:o,children:a})}))})};AS.displayName=Ad;var fi="DialogOverlay",IS=f.forwardRef((e,t)=>{const n=hS(fi,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=It(fi,e.__scopeDialog);return i.modal?s.jsx(ot,{present:r||i.open,children:s.jsx(ax,{...o,ref:t})}):null});IS.displayName=fi;var ix=Nr("DialogOverlay.RemoveScroll"),ax=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=It(fi,n);return s.jsx(na,{as:ix,allowPinchZoom:!0,shards:[o.contentRef],children:s.jsx(Ce.div,{"data-state":md(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Fn="DialogContent",mS=f.forwardRef((e,t)=>{const n=hS(Fn,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=It(Fn,e.__scopeDialog);return s.jsx(ot,{present:r||i.open,children:i.modal?s.jsx(lx,{...o,ref:t}):s.jsx(cx,{...o,ref:t})})});mS.displayName=Fn;var lx=f.forwardRef((e,t)=>{const n=It(Fn,e.__scopeDialog),r=f.useRef(null),o=be(t,n.contentRef,r);return f.useEffect(()=>{const i=r.current;if(i)return hd(i)},[]),s.jsx(OS,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var a;i.preventDefault(),(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const a=i.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0;(a.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())})}),cx=f.forwardRef((e,t)=>{const n=It(Fn,e.__scopeDialog),r=f.useRef(!1),o=f.useRef(!1);return s.jsx(OS,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var a,l;(a=e.onCloseAutoFocus)==null||a.call(e,i),i.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),i.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:i=>{var c,d;(c=e.onInteractOutside)==null||c.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const a=i.target;((d=n.triggerRef.current)==null?void 0:d.contains(a))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}})}),OS=f.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...a}=e,l=It(Fn,n),c=f.useRef(null),d=be(t,c);return Rd(),s.jsxs(s.Fragment,{children:[s.jsx(ea,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:s.jsx(wo,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":md(l.open),...a,ref:d,onDismiss:()=>l.onOpenChange(!1)})}),s.jsxs(s.Fragment,{children:[s.jsx(ux,{titleId:l.titleId}),s.jsx(fx,{contentRef:c,descriptionId:l.descriptionId})]})]})}),Id="DialogTitle",NS=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=It(Id,n);return s.jsx(Ce.h2,{id:o.titleId,...r,ref:t})});NS.displayName=Id;var gS="DialogDescription",dx=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=It(gS,n);return s.jsx(Ce.p,{id:o.descriptionId,...r,ref:t})});dx.displayName=gS;var xS="DialogClose",Ex=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=It(xS,n);return s.jsx(Ce.button,{type:"button",...r,ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))})});Ex.displayName=xS;function md(e){return e?"open":"closed"}var yS="DialogTitleWarning",[S5,CS]=eO(yS,{contentName:Fn,titleName:Id,docsSlug:"dialog"}),ux=({titleId:e})=>{const t=CS(yS),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
50
|
-
|
|
51
|
-
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
52
|
-
|
|
53
|
-
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return f.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},Tx="DialogDescriptionWarning",fx=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${CS(Tx).contentName}}.`;return f.useEffect(()=>{var i;const o=(i=e.current)==null?void 0:i.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},px=SS,Sx=AS,Rx=IS,hx=mS,Ax=NS;function LS(e){const t=e+"CollectionProvider",[n,r]=mn(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),a=A=>{const{scope:S,children:R}=A,m=_e.useRef(null),I=_e.useRef(new Map).current;return s.jsx(o,{scope:S,itemMap:I,collectionRef:m,children:R})};a.displayName=t;const l=e+"CollectionSlot",c=Nr(l),d=_e.forwardRef((A,S)=>{const{scope:R,children:m}=A,I=i(l,R),O=be(S,I.collectionRef);return s.jsx(c,{ref:O,children:m})});d.displayName=l;const E=e+"CollectionItemSlot",u="data-radix-collection-item",T=Nr(E),p=_e.forwardRef((A,S)=>{const{scope:R,children:m,...I}=A,O=_e.useRef(null),N=be(S,O),x=i(E,R);return _e.useEffect(()=>(x.itemMap.set(O,{ref:O,...I}),()=>void x.itemMap.delete(O))),s.jsx(T,{[u]:"",ref:N,children:m})});p.displayName=E;function h(A){const S=i(e+"CollectionConsumer",A);return _e.useCallback(()=>{const m=S.collectionRef.current;if(!m)return[];const I=Array.from(m.querySelectorAll(`[${u}]`));return Array.from(S.itemMap.values()).sort((x,g)=>I.indexOf(x.ref.current)-I.indexOf(g.ref.current))},[S.collectionRef,S.itemMap])}return[{Provider:a,Slot:d,ItemSlot:p},h,r]}var Ix=f.createContext(void 0);function mx(e){const t=f.useContext(Ix);return e||t||"ltr"}var ol="rovingFocusGroup.onEntryFocus",Ox={bubbles:!1,cancelable:!0},ko="RovingFocusGroup",[gc,_S,Nx]=LS(ko),[gx,bS]=mn(ko,[Nx]),[xx,yx]=gx(ko),DS=f.forwardRef((e,t)=>s.jsx(gc.Provider,{scope:e.__scopeRovingFocusGroup,children:s.jsx(gc.Slot,{scope:e.__scopeRovingFocusGroup,children:s.jsx(Cx,{...e,ref:t})})}));DS.displayName=ko;var Cx=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:a,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:c,onEntryFocus:d,preventScrollOnEntryFocus:E=!1,...u}=e,T=f.useRef(null),p=be(t,T),h=mx(i),[A,S]=fd({prop:a,defaultProp:l??null,onChange:c,caller:ko}),[R,m]=f.useState(!1),I=Tn(d),O=_S(n),N=f.useRef(!1),[x,g]=f.useState(0);return f.useEffect(()=>{const C=T.current;if(C)return C.addEventListener(ol,I),()=>C.removeEventListener(ol,I)},[I]),s.jsx(xx,{scope:n,orientation:r,dir:h,loop:o,currentTabStopId:A,onItemFocus:f.useCallback(C=>S(C),[S]),onItemShiftTab:f.useCallback(()=>m(!0),[]),onFocusableItemAdd:f.useCallback(()=>g(C=>C+1),[]),onFocusableItemRemove:f.useCallback(()=>g(C=>C-1),[]),children:s.jsx(Ce.div,{tabIndex:R||x===0?-1:0,"data-orientation":r,...u,ref:p,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{N.current=!0}),onFocus:ue(e.onFocus,C=>{const y=!N.current;if(C.target===C.currentTarget&&y&&!R){const w=new CustomEvent(ol,Ox);if(C.currentTarget.dispatchEvent(w),!w.defaultPrevented){const v=O().filter(M=>M.focusable),B=v.find(M=>M.active),b=v.find(M=>M.id===A),D=[B,b,...v].filter(Boolean).map(M=>M.ref.current);PS(D,E)}}N.current=!1}),onBlur:ue(e.onBlur,()=>m(!1))})})}),MS="RovingFocusGroupItem",vS=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,children:a,...l}=e,c=lo(),d=i||c,E=yx(MS,n),u=E.currentTabStopId===d,T=_S(n),{onFocusableItemAdd:p,onFocusableItemRemove:h,currentTabStopId:A}=E;return f.useEffect(()=>{if(r)return p(),()=>h()},[r,p,h]),s.jsx(gc.ItemSlot,{scope:n,id:d,focusable:r,active:o,children:s.jsx(Ce.span,{tabIndex:u?0:-1,"data-orientation":E.orientation,...l,ref:t,onMouseDown:ue(e.onMouseDown,S=>{r?E.onItemFocus(d):S.preventDefault()}),onFocus:ue(e.onFocus,()=>E.onItemFocus(d)),onKeyDown:ue(e.onKeyDown,S=>{if(S.key==="Tab"&&S.shiftKey){E.onItemShiftTab();return}if(S.target!==S.currentTarget)return;const R=bx(S,E.orientation,E.dir);if(R!==void 0){if(S.metaKey||S.ctrlKey||S.altKey||S.shiftKey)return;S.preventDefault();let I=T().filter(O=>O.focusable).map(O=>O.ref.current);if(R==="last")I.reverse();else if(R==="prev"||R==="next"){R==="prev"&&I.reverse();const O=I.indexOf(S.currentTarget);I=E.loop?Dx(I,O+1):I.slice(O+1)}setTimeout(()=>PS(I))}}),children:typeof a=="function"?a({isCurrentTabStop:u,hasTabStop:A!=null}):a})})});vS.displayName=MS;var Lx={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function _x(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function bx(e,t,n){const r=_x(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Lx[r]}function PS(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Dx(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Mx=DS,vx=vS,xc=["Enter"," "],Px=["ArrowDown","PageUp","Home"],wS=["ArrowUp","PageDown","End"],wx=[...Px,...wS],Ux={ltr:[...xc,"ArrowRight"],rtl:[...xc,"ArrowLeft"]},Bx={ltr:["ArrowLeft"],rtl:["ArrowRight"]},oa="Menu",[Ro,Fx,kx]=LS(oa),[$n,US]=mn(oa,[kx,jr,bS]),Od=jr(),BS=bS(),[R5,Vn]=$n(oa),[h5,jo]=$n(oa),jx="MenuAnchor",Nd=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=Od(n);return s.jsx(Ji,{...o,...r,ref:t})});Nd.displayName=jx;var gd="MenuPortal",[Gx,FS]=$n(gd,{forceMount:void 0}),kS=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Vn(gd,t);return s.jsx(Gx,{scope:t,forceMount:n,children:s.jsx(ot,{present:n||i.open,children:s.jsx(Bo,{asChild:!0,container:o,children:r})})})};kS.displayName=gd;var rt="MenuContent",[Hx,xd]=$n(rt),jS=f.forwardRef((e,t)=>{const n=FS(rt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Vn(rt,e.__scopeMenu),a=jo(rt,e.__scopeMenu);return s.jsx(Ro.Provider,{scope:e.__scopeMenu,children:s.jsx(ot,{present:r||i.open,children:s.jsx(Ro.Slot,{scope:e.__scopeMenu,children:a.modal?s.jsx(Yx,{...o,ref:t}):s.jsx(Wx,{...o,ref:t})})})})}),Yx=f.forwardRef((e,t)=>{const n=Vn(rt,e.__scopeMenu),r=f.useRef(null),o=be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return hd(i)},[]),s.jsx(yd,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),Wx=f.forwardRef((e,t)=>{const n=Vn(rt,e.__scopeMenu);return s.jsx(yd,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),$x=Nr("MenuContent.ScrollLock"),yd=f.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:l,onEntryFocus:c,onEscapeKeyDown:d,onPointerDownOutside:E,onFocusOutside:u,onInteractOutside:T,onDismiss:p,disableOutsideScroll:h,...A}=e,S=Vn(rt,n),R=jo(rt,n),m=Od(n),I=BS(n),O=Fx(n),[N,x]=f.useState(null),g=f.useRef(null),C=be(t,g,S.onContentChange),y=f.useRef(0),w=f.useRef(""),v=f.useRef(0),B=f.useRef(null),b=f.useRef("right"),L=f.useRef(0),D=h?na:f.Fragment,M=h?{as:$x,allowPinchZoom:!0}:void 0,U=_=>{var Y,G;const F=w.current+_,k=O().filter(J=>!J.disabled),H=document.activeElement,Q=(Y=k.find(J=>J.ref.current===H))==null?void 0:Y.textValue,q=k.map(J=>J.textValue),$=ry(q,F,Q),Z=(G=k.find(J=>J.textValue===$))==null?void 0:G.ref.current;(function J(te){w.current=te,window.clearTimeout(y.current),te!==""&&(y.current=window.setTimeout(()=>J(""),1e3))})(F),Z&&setTimeout(()=>Z.focus())};f.useEffect(()=>()=>window.clearTimeout(y.current),[]),Rd();const P=f.useCallback(_=>{var k,H;return b.current===((k=B.current)==null?void 0:k.side)&&sy(_,(H=B.current)==null?void 0:H.area)},[]);return s.jsx(Hx,{scope:n,searchRef:w,onItemEnter:f.useCallback(_=>{P(_)&&_.preventDefault()},[P]),onItemLeave:f.useCallback(_=>{var F;P(_)||((F=g.current)==null||F.focus(),x(null))},[P]),onTriggerLeave:f.useCallback(_=>{P(_)&&_.preventDefault()},[P]),pointerGraceTimerRef:v,onPointerGraceIntentChange:f.useCallback(_=>{B.current=_},[]),children:s.jsx(D,{...M,children:s.jsx(ea,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,_=>{var F;_.preventDefault(),(F=g.current)==null||F.focus({preventScroll:!0})}),onUnmountAutoFocus:a,children:s.jsx(wo,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:E,onFocusOutside:u,onInteractOutside:T,onDismiss:p,children:s.jsx(Mx,{asChild:!0,...I,dir:R.dir,orientation:"vertical",loop:r,currentTabStopId:N,onCurrentTabStopIdChange:x,onEntryFocus:ue(c,_=>{R.isUsingKeyboardRef.current||_.preventDefault()}),preventScrollOnEntryFocus:!0,children:s.jsx(ud,{role:"menu","aria-orientation":"vertical","data-state":nR(S.open),"data-radix-menu-content":"",dir:R.dir,...m,...A,ref:C,style:{outline:"none",...A.style},onKeyDown:ue(A.onKeyDown,_=>{const k=_.target.closest("[data-radix-menu-content]")===_.currentTarget,H=_.ctrlKey||_.altKey||_.metaKey,Q=_.key.length===1;k&&(_.key==="Tab"&&_.preventDefault(),!H&&Q&&U(_.key));const q=g.current;if(_.target!==q||!wx.includes(_.key))return;_.preventDefault();const Z=O().filter(Y=>!Y.disabled).map(Y=>Y.ref.current);wS.includes(_.key)&&Z.reverse(),ty(Z)}),onBlur:ue(e.onBlur,_=>{_.currentTarget.contains(_.target)||(window.clearTimeout(y.current),w.current="")}),onPointerMove:ue(e.onPointerMove,ho(_=>{const F=_.target,k=L.current!==_.clientX;if(_.currentTarget.contains(F)&&k){const H=_.clientX>L.current?"right":"left";b.current=H,L.current=_.clientX}}))})})})})})})});jS.displayName=rt;var Vx="MenuGroup",Cd=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(Ce.div,{role:"group",...r,ref:t})});Cd.displayName=Vx;var Xx="MenuLabel",GS=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(Ce.div,{...r,ref:t})});GS.displayName=Xx;var pi="MenuItem",zE="menu.itemSelect",sa=f.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=f.useRef(null),a=jo(pi,e.__scopeMenu),l=xd(pi,e.__scopeMenu),c=be(t,i),d=f.useRef(!1),E=()=>{const u=i.current;if(!n&&u){const T=new CustomEvent(zE,{bubbles:!0,cancelable:!0});u.addEventListener(zE,p=>r==null?void 0:r(p),{once:!0}),yp(u,T),T.defaultPrevented?d.current=!1:a.onClose()}};return s.jsx(HS,{...o,ref:c,disabled:n,onClick:ue(e.onClick,E),onPointerDown:u=>{var T;(T=e.onPointerDown)==null||T.call(e,u),d.current=!0},onPointerUp:ue(e.onPointerUp,u=>{var T;d.current||(T=u.currentTarget)==null||T.click()}),onKeyDown:ue(e.onKeyDown,u=>{const T=l.searchRef.current!=="";n||T&&u.key===" "||xc.includes(u.key)&&(u.currentTarget.click(),u.preventDefault())})})});sa.displayName=pi;var HS=f.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,a=xd(pi,n),l=BS(n),c=f.useRef(null),d=be(t,c),[E,u]=f.useState(!1),[T,p]=f.useState("");return f.useEffect(()=>{const h=c.current;h&&p((h.textContent??"").trim())},[i.children]),s.jsx(Ro.ItemSlot,{scope:n,disabled:r,textValue:o??T,children:s.jsx(vx,{asChild:!0,...l,focusable:!r,children:s.jsx(Ce.div,{role:"menuitem","data-highlighted":E?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:d,onPointerMove:ue(e.onPointerMove,ho(h=>{r?a.onItemLeave(h):(a.onItemEnter(h),h.defaultPrevented||h.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:ue(e.onPointerLeave,ho(h=>a.onItemLeave(h))),onFocus:ue(e.onFocus,()=>u(!0)),onBlur:ue(e.onBlur,()=>u(!1))})})})}),zx="MenuCheckboxItem",YS=f.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return s.jsx(zS,{scope:e.__scopeMenu,checked:n,children:s.jsx(sa,{role:"menuitemcheckbox","aria-checked":Si(n)?"mixed":n,...o,ref:t,"data-state":_d(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(Si(n)?!0:!n),{checkForDefaultPrevented:!1})})})});YS.displayName=zx;var WS="MenuRadioGroup",[Kx,qx]=$n(WS,{value:void 0,onValueChange:()=>{}}),$S=f.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,i=Tn(r);return s.jsx(Kx,{scope:e.__scopeMenu,value:n,onValueChange:i,children:s.jsx(Cd,{...o,ref:t})})});$S.displayName=WS;var VS="MenuRadioItem",XS=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=qx(VS,e.__scopeMenu),i=n===o.value;return s.jsx(zS,{scope:e.__scopeMenu,checked:i,children:s.jsx(sa,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":_d(i),onSelect:ue(r.onSelect,()=>{var a;return(a=o.onValueChange)==null?void 0:a.call(o,n)},{checkForDefaultPrevented:!1})})})});XS.displayName=VS;var Ld="MenuItemIndicator",[zS,Jx]=$n(Ld,{checked:!1}),KS=f.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=Jx(Ld,n);return s.jsx(ot,{present:r||Si(i.checked)||i.checked===!0,children:s.jsx(Ce.span,{...o,ref:t,"data-state":_d(i.checked)})})});KS.displayName=Ld;var Qx="MenuSeparator",qS=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(Ce.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});qS.displayName=Qx;var Zx="MenuArrow",JS=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=Od(n);return s.jsx(Td,{...o,...r,ref:t})});JS.displayName=Zx;var ey="MenuSub",[A5,QS]=$n(ey),ro="MenuSubTrigger",ZS=f.forwardRef((e,t)=>{const n=Vn(ro,e.__scopeMenu),r=jo(ro,e.__scopeMenu),o=QS(ro,e.__scopeMenu),i=xd(ro,e.__scopeMenu),a=f.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:c}=i,d={__scopeMenu:e.__scopeMenu},E=f.useCallback(()=>{a.current&&window.clearTimeout(a.current),a.current=null},[]);return f.useEffect(()=>E,[E]),f.useEffect(()=>{const u=l.current;return()=>{window.clearTimeout(u),c(null)}},[l,c]),s.jsx(Nd,{asChild:!0,...d,children:s.jsx(HS,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":nR(n.open),...e,ref:Vi(t,o.onTriggerChange),onClick:u=>{var T;(T=e.onClick)==null||T.call(e,u),!(e.disabled||u.defaultPrevented)&&(u.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,ho(u=>{i.onItemEnter(u),!u.defaultPrevented&&!e.disabled&&!n.open&&!a.current&&(i.onPointerGraceIntentChange(null),a.current=window.setTimeout(()=>{n.onOpenChange(!0),E()},100))})),onPointerLeave:ue(e.onPointerLeave,ho(u=>{var p,h;E();const T=(p=n.content)==null?void 0:p.getBoundingClientRect();if(T){const A=(h=n.content)==null?void 0:h.dataset.side,S=A==="right",R=S?-5:5,m=T[S?"left":"right"],I=T[S?"right":"left"];i.onPointerGraceIntentChange({area:[{x:u.clientX+R,y:u.clientY},{x:m,y:T.top},{x:I,y:T.top},{x:I,y:T.bottom},{x:m,y:T.bottom}],side:A}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(u),u.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,u=>{var p;const T=i.searchRef.current!=="";e.disabled||T&&u.key===" "||Ux[r.dir].includes(u.key)&&(n.onOpenChange(!0),(p=n.content)==null||p.focus(),u.preventDefault())})})})});ZS.displayName=ro;var eR="MenuSubContent",tR=f.forwardRef((e,t)=>{const n=FS(rt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Vn(rt,e.__scopeMenu),a=jo(rt,e.__scopeMenu),l=QS(eR,e.__scopeMenu),c=f.useRef(null),d=be(t,c);return s.jsx(Ro.Provider,{scope:e.__scopeMenu,children:s.jsx(ot,{present:r||i.open,children:s.jsx(Ro.Slot,{scope:e.__scopeMenu,children:s.jsx(yd,{id:l.contentId,"aria-labelledby":l.triggerId,...o,ref:d,align:"start",side:a.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:E=>{var u;a.isUsingKeyboardRef.current&&((u=c.current)==null||u.focus()),E.preventDefault()},onCloseAutoFocus:E=>E.preventDefault(),onFocusOutside:ue(e.onFocusOutside,E=>{E.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,E=>{a.onClose(),E.preventDefault()}),onKeyDown:ue(e.onKeyDown,E=>{var p;const u=E.currentTarget.contains(E.target),T=Bx[a.dir].includes(E.key);u&&T&&(i.onOpenChange(!1),(p=l.trigger)==null||p.focus(),E.preventDefault())})})})})})});tR.displayName=eR;function nR(e){return e?"open":"closed"}function Si(e){return e==="indeterminate"}function _d(e){return Si(e)?"indeterminate":e?"checked":"unchecked"}function ty(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function ny(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function ry(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let a=ny(e,Math.max(i,0));o.length===1&&(a=a.filter(d=>d!==n));const c=a.find(d=>d.toLowerCase().startsWith(o.toLowerCase()));return c!==n?c:void 0}function oy(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,a=t.length-1;i<t.length;a=i++){const l=t[i],c=t[a],d=l.x,E=l.y,u=c.x,T=c.y;E>r!=T>r&&n<(u-d)*(r-E)/(T-E)+d&&(o=!o)}return o}function sy(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return oy(n,t)}function ho(e){return t=>t.pointerType==="mouse"?e(t):void 0}var iy=Nd,ay=kS,ly=jS,cy=Cd,dy=GS,Ey=sa,uy=YS,Ty=$S,fy=XS,py=KS,Sy=qS,Ry=JS,hy=ZS,Ay=tR,rR="DropdownMenu",[Iy]=mn(rR,[US]),We=US(),[I5,oR]=Iy(rR),sR="DropdownMenuTrigger",my=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=oR(sR,n),a=We(n);return s.jsx(iy,{asChild:!0,...a,children:s.jsx(Ce.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...o,ref:Vi(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});my.displayName=sR;var Oy="DropdownMenuPortal",iR=e=>{const{__scopeDropdownMenu:t,...n}=e,r=We(t);return s.jsx(ay,{...r,...n})};iR.displayName=Oy;var aR="DropdownMenuContent",lR=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=oR(aR,n),i=We(n),a=f.useRef(!1);return s.jsx(ly,{id:o.contentId,"aria-labelledby":o.triggerId,...i,...r,ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var c;a.current||(c=o.triggerRef.current)==null||c.focus(),a.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const c=l.detail.originalEvent,d=c.button===0&&c.ctrlKey===!0,E=c.button===2||d;(!o.modal||E)&&(a.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});lR.displayName=aR;var Ny="DropdownMenuGroup",gy=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=We(n);return s.jsx(cy,{...o,...r,ref:t})});gy.displayName=Ny;var xy="DropdownMenuLabel",cR=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=We(n);return s.jsx(dy,{...o,...r,ref:t})});cR.displayName=xy;var yy="DropdownMenuItem",dR=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=We(n);return s.jsx(Ey,{...o,...r,ref:t})});dR.displayName=yy;var Cy="DropdownMenuCheckboxItem",Ly=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=We(n);return s.jsx(uy,{...o,...r,ref:t})});Ly.displayName=Cy;var _y="DropdownMenuRadioGroup",by=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=We(n);return s.jsx(Ty,{...o,...r,ref:t})});by.displayName=_y;var Dy="DropdownMenuRadioItem",My=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=We(n);return s.jsx(fy,{...o,...r,ref:t})});My.displayName=Dy;var vy="DropdownMenuItemIndicator",Py=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=We(n);return s.jsx(py,{...o,...r,ref:t})});Py.displayName=vy;var wy="DropdownMenuSeparator",ER=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=We(n);return s.jsx(Sy,{...o,...r,ref:t})});ER.displayName=wy;var Uy="DropdownMenuArrow",By=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=We(n);return s.jsx(Ry,{...o,...r,ref:t})});By.displayName=Uy;var Fy="DropdownMenuSubTrigger",ky=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=We(n);return s.jsx(hy,{...o,...r,ref:t})});ky.displayName=Fy;var jy="DropdownMenuSubContent",Gy=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=We(n);return s.jsx(Ay,{...o,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Gy.displayName=jy;var Hy=iR,Yy=lR,Wy=cR,$y=dR,Vy=ER;const Xy=f.forwardRef(({container:e,style:t,sideOffset:n=4,...r},o)=>s.jsx(Hy,{container:e,children:s.jsx(Yy,{ref:o,sideOffset:n,style:{minWidth:180,background:Se("surfaceElevated"),color:Se("textPrimary"),border:`1px solid ${Se("borderDefault")}`,borderRadius:In.md,boxShadow:Se("shadowMd"),padding:me[1],zIndex:fo.popover,...t},...r})}));Xy.displayName="DropdownMenuContent";const zy=f.forwardRef(({style:e,...t},n)=>s.jsx($y,{ref:n,style:{display:"flex",alignItems:"center",gap:me[2],padding:`${me[1]} ${me[2]}`,fontSize:Ge.sm,borderRadius:In.sm,cursor:"default",outline:"none",userSelect:"none",...e},...t}));zy.displayName="DropdownMenuItem";const Ky=f.forwardRef(({style:e,...t},n)=>s.jsx(Vy,{ref:n,style:{height:1,background:Se("borderSubtle"),margin:`${me[1]} 0`,...e},...t}));Ky.displayName="DropdownMenuSeparator";const qy=f.forwardRef(({style:e,...t},n)=>s.jsx(Wy,{ref:n,style:{padding:`${me[1]} ${me[2]}`,fontSize:Ge.xs,color:Se("textMuted"),textTransform:"uppercase",letterSpacing:"0.04em",...e},...t}));qy.displayName="DropdownMenuLabel";var uR="Popover",[TR]=mn(uR,[jr]),ia=jr(),[m5,On]=TR(uR),fR="PopoverAnchor",Jy=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=On(fR,n),i=ia(n),{onCustomAnchorAdd:a,onCustomAnchorRemove:l}=o;return f.useEffect(()=>(a(),()=>l()),[a,l]),s.jsx(Ji,{...i,...r,ref:t})});Jy.displayName=fR;var pR="PopoverTrigger",Qy=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=On(pR,n),i=ia(n),a=be(t,o.triggerRef),l=s.jsx(Ce.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":IR(o.open),...r,ref:a,onClick:ue(e.onClick,o.onOpenToggle)});return o.hasCustomAnchor?l:s.jsx(Ji,{asChild:!0,...i,children:l})});Qy.displayName=pR;var bd="PopoverPortal",[Zy,eC]=TR(bd,{forceMount:void 0}),SR=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=On(bd,t);return s.jsx(Zy,{scope:t,forceMount:n,children:s.jsx(ot,{present:n||i.open,children:s.jsx(Bo,{asChild:!0,container:o,children:r})})})};SR.displayName=bd;var yr="PopoverContent",RR=f.forwardRef((e,t)=>{const n=eC(yr,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=On(yr,e.__scopePopover);return s.jsx(ot,{present:r||i.open,children:i.modal?s.jsx(nC,{...o,ref:t}):s.jsx(rC,{...o,ref:t})})});RR.displayName=yr;var tC=Nr("PopoverContent.RemoveScroll"),nC=f.forwardRef((e,t)=>{const n=On(yr,e.__scopePopover),r=f.useRef(null),o=be(t,r),i=f.useRef(!1);return f.useEffect(()=>{const a=r.current;if(a)return hd(a)},[]),s.jsx(na,{as:tC,allowPinchZoom:!0,children:s.jsx(hR,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,a=>{var l;a.preventDefault(),i.current||(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,a=>{const l=a.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,d=l.button===2||c;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),rC=f.forwardRef((e,t)=>{const n=On(yr,e.__scopePopover),r=f.useRef(!1),o=f.useRef(!1);return s.jsx(hR,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var a,l;(a=e.onCloseAutoFocus)==null||a.call(e,i),i.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),i.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:i=>{var c,d;(c=e.onInteractOutside)==null||c.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const a=i.target;((d=n.triggerRef.current)==null?void 0:d.contains(a))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}})}),hR=f.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:E,...u}=e,T=On(yr,n),p=ia(n);return Rd(),s.jsx(ea,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:s.jsx(wo,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:E,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>T.onOpenChange(!1),children:s.jsx(ud,{"data-state":IR(T.open),role:"dialog",id:T.contentId,...p,...u,ref:t,style:{...u.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),AR="PopoverClose",oC=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=On(AR,n);return s.jsx(Ce.button,{type:"button",...r,ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))})});oC.displayName=AR;var sC="PopoverArrow",iC=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=ia(n);return s.jsx(Td,{...o,...r,ref:t})});iC.displayName=sC;function IR(e){return e?"open":"closed"}var aC=SR,lC=RR;const cC=f.forwardRef(({container:e,style:t,sideOffset:n=6,...r},o)=>s.jsx(aC,{container:e,children:s.jsx(lC,{ref:o,sideOffset:n,style:{background:Se("surfaceElevated"),color:Se("textPrimary"),border:`1px solid ${Se("borderDefault")}`,borderRadius:In.md,boxShadow:Se("shadowMd"),padding:me[3],zIndex:fo.popover,minWidth:220,...t},...r})}));cC.displayName="PopoverContent";function Ht({icon:e,eyebrow:t,title:n,subtitle:r,status:o,actions:i,toolbar:a,bodyPadding:l=14,children:c}){return s.jsxs("div",{className:"panel-frame",children:[s.jsxs("div",{className:"panel-frame-header",children:[s.jsxs("div",{className:"panel-frame-heading",children:[e&&s.jsx("span",{className:"panel-frame-icon",children:e}),s.jsxs("div",{className:"panel-frame-title-col",children:[t&&s.jsx("div",{className:"panel-frame-eyebrow",children:t}),s.jsxs("div",{className:"panel-frame-title-row",children:[n&&s.jsx("h2",{className:"panel-frame-title",children:n}),o&&s.jsx("span",{className:"panel-frame-status",children:o})]}),r&&s.jsx("div",{className:"panel-frame-subtitle",children:r})]})]}),i&&s.jsx("div",{className:"panel-frame-actions",children:i})]}),a&&s.jsx("div",{className:"panel-frame-toolbar",children:a}),s.jsx("div",{className:"panel-frame-body",style:{padding:l},children:c})]})}function Dd({tone:e="neutral",icon:t,children:n,className:r="",...o}){return s.jsxs("span",{className:`status-pill tone-${e} ${r}`,...o,children:[t&&s.jsx("span",{className:"status-pill-icon",children:t}),n]})}function kt({icon:e,title:t,description:n,action:r}){return s.jsxs("div",{className:"panel-empty",children:[e&&s.jsx("span",{className:"panel-empty-icon",children:e}),t&&s.jsx("p",{className:"panel-empty-title",children:t}),n&&s.jsx("p",{className:"panel-empty-desc",children:n}),r]})}function Go({left:e,right:t,children:n,className:r=""}){return s.jsxs("div",{className:`panel-toolbar ${r}`,children:[e&&s.jsx("div",{className:"panel-toolbar-left",children:e}),n&&s.jsx("div",{className:"panel-toolbar-center",children:n}),t&&s.jsx("div",{className:"panel-toolbar-right",children:t})]})}function mR({typeLabel:e,typeColor:t,accent:n,idleBorder:r,background:o,headerBackground:i,active:a=!1,title:l,status:c,actions:d,toolbar:E,subheader:u,footer:T,children:p,onMouseEnter:h,onMouseLeave:A,onClick:S,gutter:R,className:m,style:I}){const O=t??"var(--color-accent-blue, #388bfd)",N=n??r??"var(--color-border-subtle, rgba(148,163,184,0.18))",x=r??"var(--color-border-subtle, rgba(148,163,184,0.18))",g=o??"var(--color-bg-1, rgba(22,27,34,0.5))",C=i??"transparent";return s.jsxs("div",{onMouseEnter:h,onMouseLeave:A,onClick:S,className:m,style:{display:"flex",gap:0,marginBottom:2,...I},children:[R!==void 0&&R,s.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${a?N:x}`,background:g,overflow:"hidden",transition:"border-color 0.2s, box-shadow 0.2s",boxShadow:a?`0 0 0 3px ${O}14, 0 1px 2px rgba(0,0,0,0.04)`:"0 1px 2px rgba(0,0,0,0.02)"},children:[s.jsxs("div",{style:{minHeight:32,display:"flex",alignItems:"center",padding:"8px 14px",gap:8,background:C},children:[s.jsx("span",{"aria-hidden":!0,style:{width:6,height:6,borderRadius:999,background:O,flexShrink:0}}),s.jsx("span",{style:{fontSize:11,fontWeight:500,letterSpacing:"0.2px",color:"var(--color-text-secondary, #4a4a52)",flexShrink:0,whiteSpace:"nowrap"},children:e}),l!==void 0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{color:"var(--color-text-tertiary, #8a8d96)",fontSize:11},children:"·"}),l]}),E!==void 0&&E,s.jsx("span",{style:{flex:1}}),c!==void 0&&c,d!==void 0&&d]}),u!==void 0&&u,p,T!==void 0&&T]})]})}function dC({shortcut:e,children:t,style:n,...r}){return s.jsx("kbd",{...r,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:18,height:18,padding:`0 ${me[1]}px`,borderRadius:In.sm,border:`1px solid ${Se("borderSubtle")}`,background:Se("surfaceRaised"),color:Se("textSecondary"),fontFamily:"var(--dql-font-mono, monospace)",fontSize:Ge.xs,fontWeight:nd.medium,lineHeight:1,whiteSpace:"nowrap",...n},children:e??t})}const KE=e=>{let t;const n=new Set,r=(d,E)=>{const u=typeof d=="function"?d(t):d;if(!Object.is(u,t)){const T=t;t=E??(typeof u!="object"||u===null)?u:Object.assign({},t,u),n.forEach(p=>p(t,T))}},o=()=>t,l={setState:r,getState:o,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=e(r,o,l);return l},EC=(e=>e?KE(e):KE),uC=e=>e;function TC(e,t=uC){const n=_e.useSyncExternalStore(e.subscribe,_e.useCallback(()=>t(e.getState()),[e,t]),_e.useCallback(()=>t(e.getInitialState()),[e,t]));return _e.useDebugValue(n),n}const qE=e=>{const t=EC(e),n=r=>TC(t,r);return Object.assign(n,t),n},fC=(e=>e?qE(e):qE),JE=e=>Symbol.iterator in e,QE=e=>"entries"in e,ZE=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(const[o,i]of n)if(!r.has(o)||!Object.is(i,r.get(o)))return!1;return!0},pC=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let o=n.next(),i=r.next();for(;!o.done&&!i.done;){if(!Object.is(o.value,i.value))return!1;o=n.next(),i=r.next()}return!!o.done&&!!i.done};function SC(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:JE(e)&&JE(t)?QE(e)&&QE(t)?ZE(e,t):pC(e,t):ZE({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function RC(e){const t=_e.useRef(void 0);return n=>{const r=e(n);return SC(t.current,r)?t.current:t.current=r}}function hC(){var e;if(typeof window<"u")try{(e=window.localStorage)==null||e.removeItem("dql-app-mode")}catch{}return"studio"}function AC(){var t;if(typeof window>"u")return"paper";const e=(t=window.localStorage)==null?void 0:t.getItem("dql-theme");return e==="obsidian"||e==="paper"||e==="white"?e:e==="midnight"||e==="dark"?"obsidian":e==="arctic"?"white":"paper"}const IC={mainView:"notebook",themeMode:AC(),appMode:hC(),sidebarPanel:"files",sidebarOpen:!0,files:[],filesLoading:!1,activeFile:null,cells:[],notebookTitle:"",notebookMetadata:{},notebookDirty:!1,schemaTables:[],schemaLoading:!1,semanticLayer:{available:!1,provider:null,metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[],domains:[],tags:[],favorites:[],recentlyUsed:[],loading:!1,lastSyncTime:null},devPanelOpen:!1,devPanelTab:"logs",queryLog:[],newNotebookModalOpen:!1,newBlockModalOpen:!1,autoSave:!1,executionCounter:0,savingFile:!1,lineageFullscreen:!1,lineageFocusNodeId:null,lineageDrawerOpen:!1,lineageDrawerNodeId:null,dashboardMode:!1,activeBlockPath:null,blockStudioDraft:"",blockStudioDirty:!1,blockStudioPreview:null,blockStudioValidation:null,blockStudioMetadata:null,blockStudioCatalog:null,blockStudioCatalogLoading:!1,inspectorOpen:!1,inspectorContext:null,apps:[],appsLoading:!1,activeAppId:null,activeDashboardId:null,activePersona:null};function mC(e,t){var n,r,o,i,a,l;switch(t.type){case"SET_MAIN_VIEW":return{...e,mainView:t.view,lineageFullscreen:!1,lineageFocusNodeId:null};case"SET_THEME":{if(typeof document<"u"){const c=t.mode==="dark"||t.mode==="midnight"?"obsidian":t.mode==="light"?"paper":t.mode==="arctic"?"white":t.mode;document.documentElement.setAttribute("data-theme",c);try{(n=window.localStorage)==null||n.setItem("dql-theme",t.mode)}catch{}}return{...e,themeMode:t.mode}}case"SET_APP_MODE":{if(typeof window<"u")try{(r=window.localStorage)==null||r.removeItem("dql-app-mode")}catch{}return{...e,appMode:"studio"}}case"SET_SIDEBAR_PANEL":{const c=["connection","reference","git","apps","settings"],d=t.panel!==null&&c.includes(t.panel);return{...e,sidebarPanel:t.panel,sidebarOpen:t.panel!==null&&!d,lineageFullscreen:!1,lineageFocusNodeId:null,mainView:t.panel==="connection"?"connection":t.panel==="reference"?"reference":t.panel==="git"?"git":t.panel==="apps"?"apps":t.panel==="settings"?"settings":((o=e.activeFile)==null?void 0:o.type)==="block"?"block_studio":"notebook"}}case"TOGGLE_SIDEBAR":return{...e,sidebarOpen:!e.sidebarOpen};case"SET_FILES":return{...e,files:t.files};case"SET_FILES_LOADING":return{...e,filesLoading:t.loading};case"OPEN_FILE":return{...e,activeFile:t.file,cells:t.cells,notebookTitle:t.title,notebookMetadata:t.metadata??{},notebookDirty:!1,mainView:t.file.type==="block"?"block_studio":"notebook",activeBlockPath:t.file.type==="block"?t.file.path:null,blockStudioDraft:t.file.type==="block"?e.blockStudioDraft:"",blockStudioDirty:!1,blockStudioPreview:t.file.type==="block"?e.blockStudioPreview:null,blockStudioValidation:t.file.type==="block"?e.blockStudioValidation:null,blockStudioMetadata:t.file.type==="block"?e.blockStudioMetadata:null,lineageFullscreen:!1,lineageFocusNodeId:null};case"OPEN_BLOCK_STUDIO":return{...e,activeFile:t.file,cells:[],notebookTitle:t.payload.metadata.name,notebookDirty:!1,mainView:"block_studio",dashboardMode:!1,activeBlockPath:t.payload.path,blockStudioDraft:t.payload.source,blockStudioDirty:!1,blockStudioPreview:null,blockStudioValidation:t.payload.validation,blockStudioMetadata:t.payload.metadata,lineageFullscreen:!1,lineageFocusNodeId:(i=t.payload.metadata)!=null&&i.name?`block:${t.payload.metadata.name}`:null};case"SET_CELLS":return{...e,cells:t.cells,notebookDirty:!0};case"UPDATE_NOTEBOOK_METADATA":{const c=e.notebookMetadata;let d=!1;for(const E of Object.keys(t.updates))if(c[E]!==t.updates[E]){d=!0;break}return d?{...e,notebookMetadata:{...c,...t.updates},notebookDirty:!0}:e}case"ADD_CELL":{if(!t.afterId)return{...e,cells:[...e.cells,t.cell],notebookDirty:!0};const c=e.cells.findIndex(E=>E.id===t.afterId);if(c===-1)return{...e,cells:[...e.cells,t.cell],notebookDirty:!0};const d=[...e.cells];return d.splice(c+1,0,t.cell),{...e,cells:d,notebookDirty:!0}}case"UPDATE_CELL":{const c=e.cells.map(E=>E.id===t.id?{...E,...t.updates}:E),d=t.updates.executionCount!==void 0?e.executionCounter+1:e.executionCounter;return{...e,cells:c,notebookDirty:!0,executionCounter:d}}case"DELETE_CELL":return{...e,cells:e.cells.filter(c=>c.id!==t.id),notebookDirty:!0};case"MOVE_CELL":{const c=e.cells.findIndex(E=>E.id===t.id);if(c===-1)return e;const d=[...e.cells];return t.direction==="up"&&c>0?[d[c-1],d[c]]=[d[c],d[c-1]]:t.direction==="down"&&c<d.length-1&&([d[c],d[c+1]]=[d[c+1],d[c]]),{...e,cells:d,notebookDirty:!0}}case"REORDER_CELL":{const{fromIndex:c,toIndex:d}=t;if(c===d||c<0||d<0||c>=e.cells.length||d>=e.cells.length)return e;const E=[...e.cells],[u]=E.splice(c,1);return E.splice(d,0,u),{...e,cells:E,notebookDirty:!0}}case"SET_SCHEMA":return{...e,schemaTables:t.tables};case"SET_SCHEMA_LOADING":return{...e,schemaLoading:t.loading};case"TOGGLE_SCHEMA_TABLE":return{...e,schemaTables:e.schemaTables.map(c=>c.name===t.tableName?{...c,expanded:!c.expanded}:c)};case"TOGGLE_DEV_PANEL":return{...e,devPanelOpen:!e.devPanelOpen};case"SET_DEV_PANEL_TAB":return{...e,devPanelTab:t.tab};case"APPEND_QUERY_LOG":return{...e,queryLog:[...e.queryLog,t.entry]};case"OPEN_NEW_NOTEBOOK_MODAL":return{...e,newNotebookModalOpen:!0};case"CLOSE_NEW_NOTEBOOK_MODAL":return{...e,newNotebookModalOpen:!1};case"OPEN_NEW_BLOCK_MODAL":return{...e,newBlockModalOpen:!0};case"CLOSE_NEW_BLOCK_MODAL":return{...e,newBlockModalOpen:!1};case"SET_AUTO_SAVE":return{...e,autoSave:t.enabled};case"SET_NOTEBOOK_DIRTY":return{...e,notebookDirty:t.dirty};case"SET_SAVING":return{...e,savingFile:t.saving};case"FILE_ADDED":return{...e,files:[...e.files,t.file]};case"SET_TABLE_COLUMNS":return{...e,schemaTables:e.schemaTables.map(c=>c.name===t.tableName?{...c,columns:t.columns}:c)};case"SET_PARAM_VALUE":return{...e,cells:e.cells.map(c=>c.id===t.id?{...c,paramValue:t.value}:c),notebookDirty:!0};case"SET_SEMANTIC_LAYER":return{...e,semanticLayer:{...t.layer,loading:!1}};case"SET_SEMANTIC_LOADING":return{...e,semanticLayer:{...e.semanticLayer,loading:t.loading}};case"SET_SEMANTIC_FAVORITES":return{...e,semanticLayer:{...e.semanticLayer,favorites:t.favorites}};case"ADD_SEMANTIC_RECENT":{const c=[t.name,...e.semanticLayer.recentlyUsed.filter(d=>d!==t.name)].slice(0,12);return{...e,semanticLayer:{...e.semanticLayer,recentlyUsed:c}}}case"SET_SEMANTIC_DOMAINS":return{...e,semanticLayer:{...e.semanticLayer,domains:t.domains,tags:t.tags,lastSyncTime:t.lastSyncTime??e.semanticLayer.lastSyncTime}};case"TOGGLE_LINEAGE_FULLSCREEN":return{...e,lineageFullscreen:!e.lineageFullscreen};case"SET_LINEAGE_FOCUS":return{...e,lineageFocusNodeId:t.nodeId};case"OPEN_LINEAGE_DRAWER":return{...e,lineageDrawerOpen:!0,lineageDrawerNodeId:t.nodeId};case"CLOSE_LINEAGE_DRAWER":return{...e,lineageDrawerOpen:!1,lineageDrawerNodeId:null};case"TOGGLE_DASHBOARD_MODE":return{...e,dashboardMode:!e.dashboardMode};case"SET_BLOCK_STUDIO_DRAFT":return{...e,blockStudioDraft:t.draft,blockStudioDirty:!0};case"SET_BLOCK_STUDIO_DIRTY":return{...e,blockStudioDirty:t.dirty};case"SET_BLOCK_STUDIO_PREVIEW":return{...e,blockStudioPreview:t.preview};case"SET_BLOCK_STUDIO_VALIDATION":return{...e,blockStudioValidation:t.validation};case"SET_BLOCK_STUDIO_METADATA":return{...e,blockStudioMetadata:t.metadata,notebookTitle:t.metadata.name,blockStudioDirty:!0};case"SET_BLOCK_STUDIO_CATALOG":return{...e,blockStudioCatalog:t.catalog};case"SET_BLOCK_STUDIO_CATALOG_LOADING":return{...e,blockStudioCatalogLoading:t.loading};case"TOGGLE_INSPECTOR":return{...e,inspectorOpen:!e.inspectorOpen};case"SET_INSPECTOR":return{...e,inspectorOpen:t.open,inspectorContext:t.context===void 0?e.inspectorContext:t.context};case"SET_INSPECTOR_CONTEXT":return{...e,inspectorContext:t.context,inspectorOpen:t.context!==null?!0:e.inspectorOpen};case"SET_APPS":return{...e,apps:t.apps};case"SET_APPS_LOADING":return{...e,appsLoading:t.loading};case"OPEN_APP":{const c=e.apps.find(E=>E.id===t.appId)??null,d=t.dashboardId!==void 0?t.dashboardId:((a=c==null?void 0:c.homepage)==null?void 0:a.type)==="dashboard"?c.homepage.id:((l=c==null?void 0:c.dashboards[0])==null?void 0:l.id)??null;return{...e,mainView:"apps",activeAppId:t.appId,activeDashboardId:d}}case"OPEN_DASHBOARD":return{...e,activeDashboardId:t.dashboardId};case"SET_ACTIVE_PERSONA":return{...e,activePersona:t.persona};default:return e}}const yc=fC((e,t)=>({...IC,dispatch:n=>{const r=mC(t(),n);e(r)}})),OC=f.createContext(null);function NC({children:e}){return _e.useEffect(()=>{const t=n=>{if(n.key!=="dql-theme"||!n.newValue)return;const r=n.newValue;(r==="obsidian"||r==="paper"||r==="white"||r==="midnight"||r==="arctic"||r==="dark"||r==="light")&&yc.getState().dispatch({type:"SET_THEME",mode:r})};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]),s.jsx(s.Fragment,{children:e})}function fe(){const e=yc(RC(r=>{const{dispatch:o,...i}=r;return i})),t=yc(r=>r.dispatch);return f.useContext(OC)??{state:e,dispatch:t}}function ut(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function ze(e,t=""){const n={id:ut(),type:e,content:t,status:"idle"};return e==="param"&&(n.content="",n.paramConfig={paramType:"text",label:"Parameter",defaultValue:"",options:[]}),e==="chart"&&(n.chartConfig={chart:"bar"}),e==="filter"&&(n.filterConfig={mode:"keep",groups:[{id:`g_${Math.random().toString(36).slice(2,8)}`,combinator:"and",rules:[]}]}),e==="pivot"&&(n.pivotConfig={rows:[],columns:[],values:[]}),e==="single_value"&&(n.singleValueConfig={aggregation:"count",format:"number"}),e==="table"&&(n.tableConfig={}),e==="chat"&&(n.chatConfig={history:[]}),n}/**
|
|
54
|
-
* @license lucide-react v0.563.0 - ISC
|
|
55
|
-
*
|
|
56
|
-
* This source code is licensed under the ISC license.
|
|
57
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
58
|
-
*/const NR=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();/**
|
|
59
|
-
* @license lucide-react v0.563.0 - ISC
|
|
60
|
-
*
|
|
61
|
-
* This source code is licensed under the ISC license.
|
|
62
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
63
|
-
*/const gC=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
|
|
64
|
-
* @license lucide-react v0.563.0 - ISC
|
|
65
|
-
*
|
|
66
|
-
* This source code is licensed under the ISC license.
|
|
67
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
68
|
-
*/const xC=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());/**
|
|
69
|
-
* @license lucide-react v0.563.0 - ISC
|
|
70
|
-
*
|
|
71
|
-
* This source code is licensed under the ISC license.
|
|
72
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
73
|
-
*/const eu=e=>{const t=xC(e);return t.charAt(0).toUpperCase()+t.slice(1)};/**
|
|
74
|
-
* @license lucide-react v0.563.0 - ISC
|
|
75
|
-
*
|
|
76
|
-
* This source code is licensed under the ISC license.
|
|
77
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
78
|
-
*/var yC={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
|
|
79
|
-
* @license lucide-react v0.563.0 - ISC
|
|
80
|
-
*
|
|
81
|
-
* This source code is licensed under the ISC license.
|
|
82
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
83
|
-
*/const CC=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};/**
|
|
84
|
-
* @license lucide-react v0.563.0 - ISC
|
|
85
|
-
*
|
|
86
|
-
* This source code is licensed under the ISC license.
|
|
87
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
88
|
-
*/const LC=f.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:a,...l},c)=>f.createElement("svg",{ref:c,...yC,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:NR("lucide",o),...!i&&!CC(l)&&{"aria-hidden":"true"},...l},[...a.map(([d,E])=>f.createElement(d,E)),...Array.isArray(i)?i:[i]]));/**
|
|
89
|
-
* @license lucide-react v0.563.0 - ISC
|
|
90
|
-
*
|
|
91
|
-
* This source code is licensed under the ISC license.
|
|
92
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
93
|
-
*/const pe=(e,t)=>{const n=f.forwardRef(({className:r,...o},i)=>f.createElement(LC,{ref:i,iconNode:t,className:NR(`lucide-${gC(eu(e))}`,`lucide-${e}`,r),...o}));return n.displayName=eu(e),n};/**
|
|
94
|
-
* @license lucide-react v0.563.0 - ISC
|
|
95
|
-
*
|
|
96
|
-
* This source code is licensed under the ISC license.
|
|
97
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
98
|
-
*/const _C=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],bC=pe("activity",_C);/**
|
|
99
|
-
* @license lucide-react v0.563.0 - ISC
|
|
100
|
-
*
|
|
101
|
-
* This source code is licensed under the ISC license.
|
|
102
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
103
|
-
*/const DC=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],gR=pe("arrow-down",DC);/**
|
|
104
|
-
* @license lucide-react v0.563.0 - ISC
|
|
105
|
-
*
|
|
106
|
-
* This source code is licensed under the ISC license.
|
|
107
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
108
|
-
*/const MC=[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]],vC=pe("arrow-right-left",MC);/**
|
|
109
|
-
* @license lucide-react v0.563.0 - ISC
|
|
110
|
-
*
|
|
111
|
-
* This source code is licensed under the ISC license.
|
|
112
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
113
|
-
*/const PC=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],xR=pe("arrow-up",PC);/**
|
|
114
|
-
* @license lucide-react v0.563.0 - ISC
|
|
115
|
-
*
|
|
116
|
-
* This source code is licensed under the ISC license.
|
|
117
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
118
|
-
*/const wC=[["path",{d:"M10 22V7a1 1 0 0 0-1-1H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5a1 1 0 0 0-1-1H2",key:"1ah6g2"}],["rect",{x:"14",y:"2",width:"8",height:"8",rx:"1",key:"88lufb"}]],UC=pe("blocks",wC);/**
|
|
119
|
-
* @license lucide-react v0.563.0 - ISC
|
|
120
|
-
*
|
|
121
|
-
* This source code is licensed under the ISC license.
|
|
122
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
123
|
-
*/const BC=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],yR=pe("book-open",BC);/**
|
|
124
|
-
* @license lucide-react v0.563.0 - ISC
|
|
125
|
-
*
|
|
126
|
-
* This source code is licensed under the ISC license.
|
|
127
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
128
|
-
*/const FC=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],kC=pe("check",FC);/**
|
|
129
|
-
* @license lucide-react v0.563.0 - ISC
|
|
130
|
-
*
|
|
131
|
-
* This source code is licensed under the ISC license.
|
|
132
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
133
|
-
*/const jC=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],GC=pe("chevron-down",jC);/**
|
|
134
|
-
* @license lucide-react v0.563.0 - ISC
|
|
135
|
-
*
|
|
136
|
-
* This source code is licensed under the ISC license.
|
|
137
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
138
|
-
*/const HC=[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]],YC=pe("chevrons-left",HC);/**
|
|
139
|
-
* @license lucide-react v0.563.0 - ISC
|
|
140
|
-
*
|
|
141
|
-
* This source code is licensed under the ISC license.
|
|
142
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
143
|
-
*/const WC=[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]],$C=pe("chevrons-right",WC);/**
|
|
144
|
-
* @license lucide-react v0.563.0 - ISC
|
|
145
|
-
*
|
|
146
|
-
* This source code is licensed under the ISC license.
|
|
147
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
148
|
-
*/const VC=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],XC=pe("circle-question-mark",VC);/**
|
|
149
|
-
* @license lucide-react v0.563.0 - ISC
|
|
150
|
-
*
|
|
151
|
-
* This source code is licensed under the ISC license.
|
|
152
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
153
|
-
*/const zC=[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]],KC=pe("command",zC);/**
|
|
154
|
-
* @license lucide-react v0.563.0 - ISC
|
|
155
|
-
*
|
|
156
|
-
* This source code is licensed under the ISC license.
|
|
157
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
158
|
-
*/const qC=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],CR=pe("database",qC);/**
|
|
159
|
-
* @license lucide-react v0.563.0 - ISC
|
|
160
|
-
*
|
|
161
|
-
* This source code is licensed under the ISC license.
|
|
162
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
163
|
-
*/const JC=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],QC=pe("external-link",JC);/**
|
|
164
|
-
* @license lucide-react v0.563.0 - ISC
|
|
165
|
-
*
|
|
166
|
-
* This source code is licensed under the ISC license.
|
|
167
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
168
|
-
*/const ZC=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],eL=pe("eye-off",ZC);/**
|
|
169
|
-
* @license lucide-react v0.563.0 - ISC
|
|
170
|
-
*
|
|
171
|
-
* This source code is licensed under the ISC license.
|
|
172
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
173
|
-
*/const tL=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],nL=pe("eye",tL);/**
|
|
174
|
-
* @license lucide-react v0.563.0 - ISC
|
|
175
|
-
*
|
|
176
|
-
* This source code is licensed under the ISC license.
|
|
177
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
178
|
-
*/const rL=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m9 15 2 2 4-4",key:"1grp1n"}]],oL=pe("file-check",rL);/**
|
|
179
|
-
* @license lucide-react v0.563.0 - ISC
|
|
180
|
-
*
|
|
181
|
-
* This source code is licensed under the ISC license.
|
|
182
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
183
|
-
*/const sL=[["path",{d:"M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34",key:"o6klzx"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z",key:"zhnas1"}]],iL=pe("file-pen",sL);/**
|
|
184
|
-
* @license lucide-react v0.563.0 - ISC
|
|
185
|
-
*
|
|
186
|
-
* This source code is licensed under the ISC license.
|
|
187
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
188
|
-
*/const aL=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],LR=pe("file-plus",aL);/**
|
|
189
|
-
* @license lucide-react v0.563.0 - ISC
|
|
190
|
-
*
|
|
191
|
-
* This source code is licensed under the ISC license.
|
|
192
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
193
|
-
*/const lL=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],cL=pe("file-question-mark",lL);/**
|
|
194
|
-
* @license lucide-react v0.563.0 - ISC
|
|
195
|
-
*
|
|
196
|
-
* This source code is licensed under the ISC license.
|
|
197
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
198
|
-
*/const dL=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],_R=pe("file-text",dL);/**
|
|
199
|
-
* @license lucide-react v0.563.0 - ISC
|
|
200
|
-
*
|
|
201
|
-
* This source code is licensed under the ISC license.
|
|
202
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
203
|
-
*/const EL=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m14.5 12.5-5 5",key:"b62r18"}],["path",{d:"m9.5 12.5 5 5",key:"1rk7el"}]],uL=pe("file-x",EL);/**
|
|
204
|
-
* @license lucide-react v0.563.0 - ISC
|
|
205
|
-
*
|
|
206
|
-
* This source code is licensed under the ISC license.
|
|
207
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
208
|
-
*/const TL=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8",key:"14sh0y"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z",key:"1970lx"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1",key:"l4dndm"}]],fL=pe("files",TL);/**
|
|
209
|
-
* @license lucide-react v0.563.0 - ISC
|
|
210
|
-
*
|
|
211
|
-
* This source code is licensed under the ISC license.
|
|
212
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
213
|
-
*/const pL=[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]],Gr=pe("git-branch",pL);/**
|
|
214
|
-
* @license lucide-react v0.563.0 - ISC
|
|
215
|
-
*
|
|
216
|
-
* This source code is licensed under the ISC license.
|
|
217
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
218
|
-
*/const SL=[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]],bR=pe("git-commit-horizontal",SL);/**
|
|
219
|
-
* @license lucide-react v0.563.0 - ISC
|
|
220
|
-
*
|
|
221
|
-
* This source code is licensed under the ISC license.
|
|
222
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
223
|
-
*/const RL=[["circle",{cx:"12",cy:"18",r:"3",key:"1mpf1b"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["path",{d:"M18 9v2c0 .6-.4 1-1 1H7c-.6 0-1-.4-1-1V9",key:"1uq4wg"}],["path",{d:"M12 12v3",key:"158kv8"}]],hL=pe("git-fork",RL);/**
|
|
224
|
-
* @license lucide-react v0.563.0 - ISC
|
|
225
|
-
*
|
|
226
|
-
* This source code is licensed under the ISC license.
|
|
227
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
228
|
-
*/const AL=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],IL=pe("grip-vertical",AL);/**
|
|
229
|
-
* @license lucide-react v0.563.0 - ISC
|
|
230
|
-
*
|
|
231
|
-
* This source code is licensed under the ISC license.
|
|
232
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
233
|
-
*/const mL=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],OL=pe("layout-dashboard",mL);/**
|
|
234
|
-
* @license lucide-react v0.563.0 - ISC
|
|
235
|
-
*
|
|
236
|
-
* This source code is licensed under the ISC license.
|
|
237
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
238
|
-
*/const NL=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],DR=pe("maximize-2",NL);/**
|
|
239
|
-
* @license lucide-react v0.563.0 - ISC
|
|
240
|
-
*
|
|
241
|
-
* This source code is licensed under the ISC license.
|
|
242
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
243
|
-
*/const gL=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],xL=pe("minimize-2",gL);/**
|
|
244
|
-
* @license lucide-react v0.563.0 - ISC
|
|
245
|
-
*
|
|
246
|
-
* This source code is licensed under the ISC license.
|
|
247
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
248
|
-
*/const yL=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],CL=pe("network",yL);/**
|
|
249
|
-
* @license lucide-react v0.563.0 - ISC
|
|
250
|
-
*
|
|
251
|
-
* This source code is licensed under the ISC license.
|
|
252
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
253
|
-
*/const LL=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],_L=pe("package",LL);/**
|
|
254
|
-
* @license lucide-react v0.563.0 - ISC
|
|
255
|
-
*
|
|
256
|
-
* This source code is licensed under the ISC license.
|
|
257
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
258
|
-
*/const bL=[["path",{d:"M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z",key:"e79jfc"}],["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}]],DL=pe("palette",bL);/**
|
|
259
|
-
* @license lucide-react v0.563.0 - ISC
|
|
260
|
-
*
|
|
261
|
-
* This source code is licensed under the ISC license.
|
|
262
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
263
|
-
*/const ML=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],vL=pe("panel-left",ML);/**
|
|
264
|
-
* @license lucide-react v0.563.0 - ISC
|
|
265
|
-
*
|
|
266
|
-
* This source code is licensed under the ISC license.
|
|
267
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
268
|
-
*/const PL=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],MR=pe("plug",PL);/**
|
|
269
|
-
* @license lucide-react v0.563.0 - ISC
|
|
270
|
-
*
|
|
271
|
-
* This source code is licensed under the ISC license.
|
|
272
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
273
|
-
*/const wL=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],UL=pe("plus",wL);/**
|
|
274
|
-
* @license lucide-react v0.563.0 - ISC
|
|
275
|
-
*
|
|
276
|
-
* This source code is licensed under the ISC license.
|
|
277
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
278
|
-
*/const BL=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],vR=pe("refresh-cw",BL);/**
|
|
279
|
-
* @license lucide-react v0.563.0 - ISC
|
|
280
|
-
*
|
|
281
|
-
* This source code is licensed under the ISC license.
|
|
282
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
283
|
-
*/const FL=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],kL=pe("search",FL);/**
|
|
284
|
-
* @license lucide-react v0.563.0 - ISC
|
|
285
|
-
*
|
|
286
|
-
* This source code is licensed under the ISC license.
|
|
287
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
288
|
-
*/const jL=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],GL=pe("settings",jL);/**
|
|
289
|
-
* @license lucide-react v0.563.0 - ISC
|
|
290
|
-
*
|
|
291
|
-
* This source code is licensed under the ISC license.
|
|
292
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
293
|
-
*/const HL=[["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 19a2 2 0 0 1-2 2",key:"1j7049"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M3 14v1",key:"vnatye"}],["path",{d:"M21 14v1",key:"169vum"}]],YL=pe("square-dashed",HL);/**
|
|
294
|
-
* @license lucide-react v0.563.0 - ISC
|
|
295
|
-
*
|
|
296
|
-
* This source code is licensed under the ISC license.
|
|
297
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
298
|
-
*/const WL=[["path",{d:"M12 3v18",key:"108xh3"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}]],$L=pe("table",WL);/**
|
|
299
|
-
* @license lucide-react v0.563.0 - ISC
|
|
300
|
-
*
|
|
301
|
-
* This source code is licensed under the ISC license.
|
|
302
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
303
|
-
*/const VL=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],XL=pe("terminal",VL);/**
|
|
304
|
-
* @license lucide-react v0.563.0 - ISC
|
|
305
|
-
*
|
|
306
|
-
* This source code is licensed under the ISC license.
|
|
307
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
308
|
-
*/const zL=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],KL=pe("trash-2",zL);/**
|
|
309
|
-
* @license lucide-react v0.563.0 - ISC
|
|
310
|
-
*
|
|
311
|
-
* This source code is licensed under the ISC license.
|
|
312
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
313
|
-
*/const qL=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Md=pe("x",qL);function JL(e,t){if(!t)return 1;const n=(e.label+" "+e.group+" "+(e.keywords||"")).toLowerCase(),r=t.toLowerCase();if(n.includes(r))return 100-n.indexOf(r);let o=0;for(const i of n)if(i===r[o]&&o++,o===r.length)return 10;return 0}function QL(e,t){const n=e.mode??"both";return n==="both"||n===t}function ZL({open:e,onClose:t}){const{state:n,dispatch:r}=fe(),[o,i]=f.useState(""),[a,l]=f.useState(0),c=f.useRef(null);f.useEffect(()=>{e&&(i(""),l(0))},[e]);const d=f.useMemo(()=>{const p=O=>r(O),h=()=>t(),A=O=>()=>{O(),h()},S=[["Files","files",fL],["Schema","schema",CR],["Lineage","lineage",hL],["Git","git",Gr],["Block Library","block_library",UC],["Apps","apps",CL],["Connections","connection",MR],["Reference","reference",yR]],R=[{mode:"obsidian",label:"Obsidian"},{mode:"paper",label:"Paper"},{mode:"white",label:"White"}],m=[];m.push({id:"sidebar.toggle",label:n.sidebarOpen?"Hide sidebar":"Show sidebar",group:"View",icon:vL,shortcut:"⌘B",mode:"studio",run:A(()=>p({type:"TOGGLE_SIDEBAR"}))},{id:"inspector.toggle",label:n.inspectorOpen?"Hide inspector":"Show inspector",group:"View",icon:n.inspectorOpen?eL:nL,shortcut:"⌘⇧I",mode:"studio",run:A(()=>p({type:"TOGGLE_INSPECTOR"}))},{id:"dashboard.toggle",label:n.dashboardMode?"Exit dashboard mode":"Enter dashboard mode",group:"View",icon:OL,shortcut:"⌘D",run:A(()=>p({type:"TOGGLE_DASHBOARD_MODE"}))},{id:"dev.toggle",label:"Toggle dev panel",group:"View",icon:XL,shortcut:"⌘J",mode:"studio",run:A(()=>p({type:"TOGGLE_DEV_PANEL"}))},{id:"lineage.fullscreen",label:n.lineageFullscreen?"Exit full-screen lineage":"Open full-screen lineage",group:"Lineage",icon:bC,keywords:"graph dag",run:A(()=>p({type:"TOGGLE_LINEAGE_FULLSCREEN"}))});for(const[O,N,x]of S)m.push({id:`panel.${N}`,label:`Go to ${O}`,group:"Navigate",icon:x,mode:"studio",run:A(()=>{p({type:"SET_SIDEBAR_PANEL",panel:N}),n.sidebarOpen||p({type:"TOGGLE_SIDEBAR"})})});m.push({id:"notebook.new",label:"New notebook…",group:"Create",icon:LR,mode:"studio",run:A(()=>p({type:"OPEN_NEW_NOTEBOOK_MODAL"}))},{id:"block.new",label:"New block…",group:"Create",icon:YL,mode:"studio",run:A(()=>p({type:"OPEN_NEW_BLOCK_MODAL"}))});const I=n.themeMode==="dark"||n.themeMode==="midnight"?"obsidian":n.themeMode==="light"?"paper":n.themeMode==="arctic"?"white":n.themeMode;for(const O of R)O.mode!==I&&m.push({id:`theme.${O.mode}`,label:`Switch to ${O.label}`,group:"Theme",icon:DL,keywords:"appearance color",run:A(()=>p({type:"SET_THEME",mode:O.mode}))});return m},[n.sidebarOpen,n.inspectorOpen,n.themeMode,n.dashboardMode,n.lineageFullscreen,n.appMode,n.sidebarPanel,r,t]),E=f.useMemo(()=>{const h=d.filter(A=>QL(A,n.appMode)).map(A=>({a:A,s:JL(A,o)})).filter(A=>A.s>0);return h.sort((A,S)=>S.s-A.s),h.map(A=>A.a)},[d,o,n.appMode]);f.useEffect(()=>{l(0)},[o]),f.useEffect(()=>{var h;const p=(h=c.current)==null?void 0:h.querySelector(`[data-palette-idx="${a}"]`);p==null||p.scrollIntoView({block:"nearest"})},[a]);const u=p=>{var h;p.key==="ArrowDown"?(p.preventDefault(),l(A=>Math.min(E.length-1,A+1))):p.key==="ArrowUp"?(p.preventDefault(),l(A=>Math.max(0,A-1))):p.key==="Enter"&&(p.preventDefault(),(h=E[a])==null||h.run())};let T="";return s.jsx(px,{open:e,onOpenChange:p=>!p&&t(),children:s.jsxs(Sx,{children:[s.jsx(Rx,{style:{position:"fixed",inset:0,background:Se("surfaceOverlay"),zIndex:fo.overlay}}),s.jsxs(hx,{"aria-label":"Command palette",style:{position:"fixed",top:"18vh",left:"50%",transform:"translateX(-50%)",width:"92vw",maxWidth:620,background:Se("surfaceRaised"),color:Se("textPrimary"),border:`1px solid ${Se("borderDefault")}`,borderRadius:In.lg,boxShadow:Se("shadowLg"),zIndex:fo.modal,display:"flex",flexDirection:"column",overflow:"hidden"},onKeyDown:u,children:[s.jsx(Ax,{style:{position:"absolute",left:-9999},children:"Command palette"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:me[2],padding:`${me[3]}px ${me[4]}px`,borderBottom:`1px solid ${Se("borderSubtle")}`},children:[s.jsx(KC,{size:14,strokeWidth:1.75,color:Se("textMuted")}),s.jsx("input",{autoFocus:!0,value:o,onChange:p=>i(p.target.value),placeholder:"Type a command…",style:{flex:1,border:"none",outline:"none",background:"transparent",color:Se("textPrimary"),fontSize:Ge.md}})]}),s.jsxs("div",{ref:c,style:{maxHeight:360,overflowY:"auto",padding:`${me[1]}px 0`},children:[E.length===0&&s.jsx("div",{style:{padding:me[4],fontSize:Ge.sm,color:Se("textMuted"),textAlign:"center"},children:"No matching commands"}),E.map((p,h)=>{const A=p.group!==T;T=p.group;const S=h===a,R=p.icon;return s.jsxs(_e.Fragment,{children:[A&&s.jsx("div",{style:{padding:`${me[2]}px ${me[4]}px ${me[1]}px`},children:s.jsx(Dd,{tone:"neutral",children:p.group})}),s.jsxs("div",{"data-palette-idx":h,role:"option","aria-selected":S,onMouseEnter:()=>l(h),onMouseDown:m=>{m.preventDefault(),p.run()},style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:me[3],padding:`${me[2]}px ${me[4]}px`,fontSize:Ge.sm,cursor:"pointer",background:S?Se("surfaceHover"):"transparent",color:Se("textPrimary")},children:[s.jsxs("span",{style:{display:"flex",alignItems:"center",gap:me[2],minWidth:0,flex:1},children:[R&&s.jsx(R,{size:14,strokeWidth:1.75}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p.label})]}),p.shortcut&&s.jsx(dC,{shortcut:p.shortcut})]})]},p.id)})]})]})]})})}const PR=window.location.origin;async function ee(e,t){const n=await fetch(`${PR}${e}`,{headers:{"Content-Type":"application/json"},...t});if(!n.ok){const r=await n.text().catch(()=>n.statusText);throw new Error(r||`HTTP ${n.status}`)}if(n.status!==204)return n.json()}function tu(e){var r;const t=Array.isArray(e==null?void 0:e.columns)?e.columns.map(o=>typeof o=="string"?o:typeof(o==null?void 0:o.name)=="string"?o.name:String(o)):[],n=e!=null&&e.semanticRefs&&typeof e.semanticRefs=="object"?{metrics:Array.isArray(e.semanticRefs.metrics)?e.semanticRefs.metrics.map(String):[],dimensions:Array.isArray(e.semanticRefs.dimensions)?e.semanticRefs.dimensions.map(String):[]}:void 0;return{columns:t,rows:Array.isArray(e==null?void 0:e.rows)?e.rows:[],rowCount:(e==null?void 0:e.rowCount)??((r=e==null?void 0:e.rows)==null?void 0:r.length)??0,executionTime:(e==null?void 0:e.executionTime)??(e==null?void 0:e.executionTimeMs)??0,...n?{semanticRefs:n}:{}}}const z={async getSettingsEnvStatus(){try{return await ee("/api/settings/env-status")}catch{return{groups:[]}}},async getProviderSettings(){try{return await ee("/api/settings/providers")}catch{return{providers:[]}}},async saveProviderSettings(e){return ee("/api/settings/providers",{method:"POST",body:JSON.stringify(e)})},async testProviderSettings(e){return ee("/api/settings/providers/test",{method:"POST",body:JSON.stringify({id:e})})},async listAgentMemory(e){const t=e?`?scope=${encodeURIComponent(e)}`:"";try{return await ee(`/api/agent/memory${t}`)}catch{return{memories:[]}}},async saveAgentMemory(e){return ee("/api/agent/memory",{method:"POST",body:JSON.stringify(e)})},async deleteAgentMemory(e){return ee(`/api/agent/memory?id=${encodeURIComponent(e)}`,{method:"DELETE"})},async ensureAgentMemoryFiles(){return ee("/api/agent/memory/default-files",{method:"POST"})},async listNotebooks(){try{return await ee("/api/notebooks")}catch{return[]}},async readNotebook(e){return ee(`/api/notebook-content?path=${encodeURIComponent(e)}`)},async createNotebook(e,t){return ee("/api/notebooks",{method:"POST",body:JSON.stringify({name:e,template:t})})},async createBlock(e){return ee("/api/blocks",{method:"POST",body:JSON.stringify({name:e})})},async getBlockLibrary(){try{return await ee("/api/blocks/library")}catch{return{blocks:[]}}},async getApps(){try{return await ee("/api/apps")}catch{return{apps:[]}}},async updateBlockStatus(e,t){return ee("/api/blocks/status",{method:"POST",body:JSON.stringify({path:e,newStatus:t})})},async getBlockHistory(e){try{return await ee(`/api/blocks/history?path=${encodeURIComponent(e)}`)}catch{return{entries:[]}}},async runBlockTests(e,t){return ee("/api/blocks/run-tests",{method:"POST",body:JSON.stringify({source:e,path:t})})},async getBlockStudioCatalog(){return ee("/api/block-studio/catalog")},async openBlockStudio(e){return ee(`/api/block-studio/open?path=${encodeURIComponent(e)}`)},async getBlockBody(e){return ee(`/api/blocks/body?path=${encodeURIComponent(e)}`)},async validateBlockStudio(e,t){return ee("/api/block-studio/validate",{method:"POST",body:JSON.stringify({source:e,path:t})})},async runBlockStudio(e,t){return ee("/api/block-studio/run",{method:"POST",body:JSON.stringify({source:e,path:t})})},async saveBlockStudio(e){return ee("/api/block-studio/save",{method:"POST",body:JSON.stringify(e)})},async previewBlockStudioImport(e){return ee("/api/block-studio/import/preview",{method:"POST",body:JSON.stringify(e)})},async getBlockStudioImport(e){return ee(`/api/block-studio/imports/${encodeURIComponent(e)}`)},async updateBlockStudioImportCandidate(e,t,n){return ee(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})},async runBlockStudioImportCandidate(e,t){return ee(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/run`,{method:"POST"})},async saveBlockStudioImportCandidate(e,t){return ee(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/save`,{method:"POST"})},async saveAsBlock(e){return ee("/api/blocks/save-from-cell",{method:"POST",body:JSON.stringify(e)})},async getBlockTemplates(){try{return(await ee("/api/blocks/templates")).templates}catch{return[]}},async listBlocks(e){try{return(await ee("/api/notebooks")).filter(n=>n.type==="block"&&(!e||n.path.startsWith(`blocks/${e}/`)))}catch{return[]}},async saveNotebook(e,t){return ee("/api/notebook-content",{method:"PUT",body:JSON.stringify({path:e,content:t})})},async executeQuery(e,t){const n=await ee("/api/query",{method:"POST",body:JSON.stringify({sql:e}),signal:t});return tu(n)},async executeNotebookCell(e,t){const n=await ee("/api/notebook/execute",{method:"POST",body:JSON.stringify({cell:{id:e.id,type:e.type,source:e.content,title:e.name,config:e.chartConfig}}),signal:t});return{cellType:String((n==null?void 0:n.cellType)??e.type),title:typeof(n==null?void 0:n.title)=="string"?n.title:void 0,blockName:typeof(n==null?void 0:n.blockName)=="string"?n.blockName:void 0,blockPath:typeof(n==null?void 0:n.blockPath)=="string"?n.blockPath:void 0,chartConfig:n!=null&&n.chartConfig&&typeof n.chartConfig=="object"?n.chartConfig:void 0,tests:Array.isArray(n==null?void 0:n.tests)?n.tests:void 0,result:n!=null&&n.result?tu(n.result):null}},async getSchema(){try{const e=await fetch(`${PR}/api/schema`);if(e.ok)return await e.json();const t=await e.json().catch(()=>null);return t!=null&&t.error&&console.warn(`[dql] schema introspection failed: ${t.error}`),(t==null?void 0:t.fallback)??[]}catch(e){return console.warn("[dql] getSchema request failed",e),[]}},async getConnections(){try{return await ee("/api/connections")}catch{return{default:"unknown",connections:{}}}},async saveConnections(e){return ee("/api/connections",{method:"PUT",body:JSON.stringify({connections:e})})},async testConnection(){try{return await ee("/api/test-connection",{method:"POST",body:JSON.stringify({})})}catch(e){return{ok:!1,message:e.message??"Connection failed"}}},async getSemanticLayer(){try{return await ee("/api/semantic-layer")}catch{return{available:!1,provider:null,metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[],domains:[],tags:[],favorites:[],recentlyUsed:[],lastSyncTime:null}}},async getSemanticTree(){return(await ee("/api/semantic-layer/tree")).tree},async getSemanticObject(e){return ee(`/api/semantic-layer/object/${encodeURIComponent(e)}`)},async importSemanticLayer(e){return ee("/api/semantic-layer/import",{method:"POST",body:JSON.stringify(e)})},async syncSemanticLayer(){return ee("/api/semantic-layer/sync",{method:"POST",body:JSON.stringify({})})},async previewSemanticImport(e){return ee("/api/semantic-layer/import-preview",{method:"POST",body:JSON.stringify(e)})},async previewSyncDiff(){return ee("/api/semantic-layer/sync-preview",{method:"POST",body:JSON.stringify({})})},async searchSemanticLayer(e){const t=new URLSearchParams;e.query&&t.set("q",e.query),e.domain&&t.set("domain",e.domain),e.tag&&t.set("tag",e.tag),e.type&&t.set("type",e.type);try{return await ee(`/api/semantic-layer/search?${t.toString()}`)}catch{return{metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[]}}},async getFavorites(){try{return(await ee("/api/user-prefs/favorites")).favorites}catch{return[]}},async toggleFavorite(e){return(await ee("/api/user-prefs/favorites",{method:"POST",body:JSON.stringify({name:e})})).favorites},async getRecentlyUsed(){try{return(await ee("/api/user-prefs/recent")).recentlyUsed}catch{return[]}},async trackUsage(e){try{return(await ee("/api/user-prefs/recent",{method:"POST",body:JSON.stringify({name:e})})).recentlyUsed}catch{return[]}},async getCompatibleDimensions(e){const t=new URLSearchParams;e.length>0&&t.set("metrics",e.join(","));try{return(await ee(`/api/semantic-layer/compatible-dims?${t.toString()}`)).dimensions}catch{return[]}},async composeQuery(e,t,n){try{return await ee("/api/semantic-query",{method:"POST",body:JSON.stringify({metrics:e,dimensions:t,timeDimension:n})})}catch(r){return{error:r.message??"Failed to compose query"}}},async previewSemanticBuilder(e){try{return await ee("/api/semantic-builder/preview",{method:"POST",body:JSON.stringify(e)})}catch(t){return{error:t.message??"Failed to preview semantic block"}}},async saveSemanticBuilder(e){return ee("/api/semantic-builder/save",{method:"POST",body:JSON.stringify(e)})},async createMetric(e){try{return await ee("/api/semantic-layer/metric",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t.message??"Failed to create metric"}}},async describeTable(e){const t=e.split("."),n=t.length>1?t[t.length-1]:e,r=t.length>1?t.slice(0,-1).join("."):"",o=new URLSearchParams({table:n});r&&o.set("schema",r);try{return await ee(`/api/describe-table?${o.toString()}`)}catch{return[]}},async fetchLineage(){try{return await ee("/api/lineage")}catch{return{nodes:[],edges:[]}}},async searchLineage(e){try{return await ee(`/api/lineage/search?q=${encodeURIComponent(e)}`)}catch{return{matches:[]}}},async queryLineage(e){var n;const t=new URLSearchParams;e.focus&&t.set("focus",e.focus),e.search&&t.set("search",e.search),(n=e.types)!=null&&n.length&&t.set("types",e.types.join(",")),e.domain&&t.set("domain",e.domain),e.upstreamDepth!==void 0&&t.set("upstreamDepth",String(e.upstreamDepth)),e.downstreamDepth!==void 0&&t.set("downstreamDepth",String(e.downstreamDepth));try{return await ee(`/api/lineage/query?${t.toString()}`)}catch{return{graph:{nodes:[],edges:[]},matches:[]}}},async fetchLineageNode(e){try{return await ee(`/api/lineage/node/${encodeURIComponent(e)}`)}catch{return null}},async fetchBlockLineage(e){try{return await ee(`/api/lineage/block/${encodeURIComponent(e)}`)}catch{return null}},async fetchImpactAnalysis(e){try{return await ee(`/api/lineage/impact/${encodeURIComponent(e)}`)}catch{return null}},async fetchLineagePaths(e,t){try{const n=new URLSearchParams;t!=null&&t.maxDepth&&n.set("maxDepth",String(t.maxDepth)),t!=null&&t.maxPaths&&n.set("maxPaths",String(t.maxPaths));const r=n.toString(),o=`/api/lineage/paths/${encodeURIComponent(e)}${r?`?${r}`:""}`;return await ee(o)}catch{return null}},async fetchGitStatus(){try{return await ee("/api/git/status")}catch{return{inRepo:!1,branch:null,ahead:0,behind:0,changes:[]}}},async fetchGitLog(e=20){try{return await ee(`/api/git/log?limit=${e}`)}catch{return{inRepo:!1,commits:[]}}},async fetchRunSnapshot(e){try{return await ee(`/api/run-snapshot?path=${encodeURIComponent(e)}`)}catch{return{found:!1,snapshot:null}}},async saveRunSnapshot(e,t){await ee("/api/run-snapshot",{method:"PUT",body:JSON.stringify({path:e,snapshot:t})})},async fetchGitDiff(e,t){try{const n=new URLSearchParams;e&&n.set("path",e),t&&n.set("staged","true");const r=n.toString();return await ee(`/api/git/diff${r?`?${r}`:""}`)}catch{return{inRepo:!1,diff:"",before:null,after:null,diffReport:null}}},async fetchGitBranches(){try{return await ee("/api/git/branches")}catch{return{inRepo:!1,current:null,branches:[]}}},async fetchGitRemote(){try{return await ee("/api/git/remote")}catch{return{inRepo:!1,url:null,name:null}}},async gitStage(e){try{return await ee("/api/git/stage",{method:"POST",body:JSON.stringify({paths:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitUnstage(e){try{return await ee("/api/git/unstage",{method:"POST",body:JSON.stringify({paths:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitDiscard(e){try{return await ee("/api/git/discard",{method:"POST",body:JSON.stringify({paths:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitCommit(e,t=!1){try{return await ee("/api/git/commit",{method:"POST",body:JSON.stringify({message:e,stageAll:t})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async gitPush(){try{return await ee("/api/git/push",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitPull(){try{return await ee("/api/git/pull",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitCreateBranch(e,t=!0){try{return await ee("/api/git/branch",{method:"POST",body:JSON.stringify({name:e,checkout:t})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async gitCheckout(e){try{return await ee("/api/git/checkout",{method:"POST",body:JSON.stringify({name:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async listApps(){try{const{apps:e}=await ee("/api/apps");return e}catch{return[]}},async recommendAppBlocks(e){try{const{blocks:t}=await ee("/api/apps/recommend-blocks",{method:"POST",body:JSON.stringify(e)});return t}catch{return[]}},async createApp(e){return ee("/api/apps",{method:"POST",body:JSON.stringify(e)})},async getApp(e){try{return await ee(`/api/apps/${encodeURIComponent(e)}`)}catch{return null}},async getDashboard(e,t){try{return await ee(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}`)}catch{return null}},async getAppEditorCatalog(e,t){try{const n=new URLSearchParams;t!=null&&t.domain&&n.set("domain",t.domain),(t==null?void 0:t.certifiedOnly)===!1&&n.set("certifiedOnly","false");const r=n.toString();return await ee(`/api/apps/${encodeURIComponent(e)}/editor/catalog${r?`?${r}`:""}`)}catch{return null}},async createAppDashboard(e,t){try{return await ee(`/api/apps/${encodeURIComponent(e)}/dashboards`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async patchDashboardLayout(e,t,n){try{return await ee(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/layout`,{method:"PATCH",body:JSON.stringify({layout:n})})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async createAiPin(e,t){try{return await ee(`/api/apps/${encodeURIComponent(e)}/ai-pins`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async refreshAiPin(e,t){try{return await ee(`/api/apps/${encodeURIComponent(e)}/ai-pins/${encodeURIComponent(t)}/refresh`,{method:"POST"})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async promoteAiPin(e,t){try{return await ee(`/api/apps/${encodeURIComponent(e)}/ai-pins/${encodeURIComponent(t)}/promote`,{method:"POST"})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async fetchScopedLineage(e){try{const t=new URLSearchParams;return e.domain&&t.set("domain",e.domain),e.appId&&t.set("appId",e.appId),e.dashboardId&&t.set("dashboardId",e.dashboardId),e.blockId&&t.set("blockId",e.blockId),await ee(`/api/lineage/scope?${t.toString()}`)}catch{return null}},async runDashboard(e,t,n){try{return await ee(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:n??{}})})}catch{return null}},async saveDashboard(e,t,n){try{return{ok:!!(await ee(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify(n)})).ok}}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async getPersona(){try{const{persona:e}=await ee("/api/persona");return e}catch{return null}},async setPersona(e,t){try{const{persona:n}=await ee("/api/persona",{method:"POST",body:JSON.stringify({userId:e,appId:t})});return n}catch{return null}},async clearPersona(){try{await ee("/api/persona",{method:"DELETE"})}catch{}}};function e_(){const{state:e,dispatch:t}=fe(),n=e.inspectorContext;return s.jsxs("aside",{"aria-label":"Inspector",style:{width:320,borderLeft:`1px solid ${Se("borderSubtle")}`,background:Se("surfaceBase"),color:Se("textPrimary"),display:"flex",flexDirection:"column",overflow:"hidden",flexShrink:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:`${me[3]}px ${me[4]}px`,borderBottom:`1px solid ${Se("borderSubtle")}`},children:[s.jsx("div",{style:{fontSize:Ge.sm,fontWeight:nd.semibold},children:n?t_(n):"Inspector"}),s.jsx("button",{onClick:()=>t({type:"SET_INSPECTOR",open:!1}),"aria-label":"Close inspector",style:{background:"transparent",border:"none",color:Se("textMuted"),cursor:"pointer",fontSize:Ge.md,padding:2,borderRadius:In.sm},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"auto",padding:me[4]},children:n?s.jsx(n_,{context:n}):s.jsx(i_,{})})]})}function t_(e){switch(e.kind){case"cell":return"Cell";case"lineage-node":return"Lineage node";case"metric":return"Metric"}}function n_({context:e}){return e.kind==="cell"?s.jsx(r_,{cellId:e.cellId}):e.kind==="lineage-node"?s.jsx(o_,{nodeId:e.nodeId}):s.jsx(s_,{name:e.name})}function r_({cellId:e}){const{state:t}=fe(),n=t.cells.find(r=>r.id===e);return n?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:me[3],fontSize:Ge.sm},children:[s.jsx(Xe,{label:"Type",children:n.type}),s.jsx(Xe,{label:"ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:n.id})}),s.jsxs(Xe,{label:"Length",children:[n.content.length," chars"]}),n.status&&s.jsx(Xe,{label:"Status",children:n.status})]}):s.jsx(Ri,{children:"No matching cell in the active notebook."})}function o_({nodeId:e}){const[t,n]=f.useState(null),[r,o]=f.useState(!0);if(f.useEffect(()=>{let a=!1;return o(!0),z.fetchLineageNode(e).then(l=>{a||(n(l),o(!1))}).catch(()=>{a||o(!1)}),()=>{a=!0}},[e]),r)return s.jsx(Ri,{children:"Loading node…"});if(!t||!t.node)return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:me[3]},children:[s.jsx(Xe,{label:"Node ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:e})}),s.jsx(Ri,{children:"No metadata available for this node."})]});const i=t.node;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:me[3]},children:[s.jsx(Xe,{label:"Name",children:i.name??e}),s.jsx(Xe,{label:"Type",children:i.type}),i.domain&&s.jsx(Xe,{label:"Domain",children:i.domain}),i.layer&&s.jsx(Xe,{label:"Layer",children:i.layer}),s.jsx(Xe,{label:"Upstream",children:t.incoming.length}),s.jsx(Xe,{label:"Downstream",children:t.outgoing.length}),i.path&&s.jsx(Xe,{label:"Path",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)",fontSize:Ge.xs},children:i.path})})]})}function s_({name:e}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:me[3]},children:[s.jsx(Xe,{label:"Metric",children:e}),s.jsx(Ri,{children:"Definition, dimensions, and governance surface will render here."})]})}function Xe({label:e,children:t}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[s.jsx("div",{style:{fontSize:Ge.xs,color:Se("textMuted"),textTransform:"uppercase",letterSpacing:.5,fontWeight:nd.medium},children:e}),s.jsx("div",{style:{fontSize:Ge.sm,color:Se("textPrimary")},children:t})]})}function Ri({children:e}){return s.jsx("div",{style:{fontSize:Ge.sm,color:Se("textSecondary"),lineHeight:1.5,background:Se("surfaceSunken"),border:`1px solid ${Se("borderSubtle")}`,borderRadius:In.md,padding:me[3]},children:e})}function i_(){return s.jsx("div",{style:{fontSize:Ge.sm,color:Se("textMuted"),lineHeight:1.5},children:"Select a cell, lineage node, or metric to inspect its details here."})}const oo={appBg:"--color-bg-primary",sidebarBg:"--color-bg-secondary",activityBarBg:"--color-bg-sunken",headerBg:"--color-bg-toolbar",headerBorder:"--color-border-primary",cellBg:"--color-bg-card",cellBorder:"--color-border-subtle",cellBorderActive:"--color-accent-blue",cellBorderRunning:"--color-status-success",textPrimary:"--color-text-primary",textSecondary:"--color-text-secondary",textMuted:"--color-text-tertiary",editorBg:"--color-bg-surface",editorBorder:"--color-border-subtle",tableBorder:"--color-border-subtle",tableHeaderBg:"--color-bg-secondary",tableRowHover:"--color-bg-hover",accent:"--color-accent-blue",accentHover:"--color-accent-blue",success:"--color-status-success",error:"--color-status-error",warning:"--color-status-warning",btnBg:"--color-bg-tertiary",btnBorder:"--color-border-primary",btnHover:"--color-bg-hover",sidebarItemHover:"--color-bg-hover",sidebarItemActive:"--color-bg-active",scrollbarThumb:"--color-border-secondary",modalBg:"--color-bg-secondary",modalOverlay:"--color-bg-overlay",inputBg:"--color-bg-sunken",inputBorder:"--color-border-subtle",pillBg:"--color-bg-tertiary",font:"--font-ui",fontMono:"--font-mono",fontSerif:"--font-ui"},nu={appBg:"#fbfaf7",sidebarBg:"#fbfaf7",activityBarBg:"#ffffff",headerBg:"#ffffff",headerBorder:"#e9e6e0",cellBg:"#ffffff",cellBorder:"#e9e6e0",cellBorderActive:"#6b5dd3",cellBorderRunning:"#2e8b57",textPrimary:"#1a1a1a",textSecondary:"#4a4a52",textMuted:"#8a8d96",editorBg:"#fbfaf7",editorBorder:"#e9e6e0",tableBorder:"#f0eee9",tableHeaderBg:"#faf9f7",tableRowHover:"#f3f0ea",accent:"#6b5dd3",accentHover:"#5c4fc2",success:"#2e8b57",error:"#c14545",warning:"#b26b1f",btnBg:"#ffffff",btnBorder:"#e9e6e0",btnHover:"#f3f0ea",sidebarItemHover:"#f3f0ea",sidebarItemActive:"#f3f0fb",scrollbarThumb:"#d9d5cc",modalBg:"#ffffff",modalOverlay:"rgba(26,26,26,0.40)",inputBg:"#fbfaf7",inputBorder:"#e9e6e0",pillBg:"#f3f0ea",font:"'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontMono:"'JetBrains Mono', ui-monospace, 'SFMono-Regular', Menlo, Monaco, Consolas, monospace",fontSerif:"'Inter', -apple-system, BlinkMacSystemFont, sans-serif"};function ru(e){if(typeof document>"u")return nu[e];const t=oo[e];return getComputedStyle(document.documentElement).getPropertyValue(t).trim()||nu[e]}function a_(){return new Proxy({},{get(e,t){if(typeof t=="string"&&t in oo)return ru(t)},has(e,t){return typeof t=="string"&&t in oo},ownKeys(){return Object.keys(oo)},getOwnPropertyDescriptor(e,t){if(!(typeof t!="string"||!(t in oo)))return{enumerable:!0,configurable:!0,value:ru(t)}}})}const Cn=a_(),ie={obsidian:Cn,paper:Cn,white:Cn,dark:Cn,light:Cn,midnight:Cn,arctic:Cn};function st(e,t="0 0 24 24"){return function({size:r=16,strokeWidth:o=1.75,...i}){return s.jsx("svg",{width:r,height:r,viewBox:t,fill:"none",stroke:"currentColor",strokeWidth:o,strokeLinecap:"round",strokeLinejoin:"round",...i,children:e})}}const wR=st(s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1.5"}),s.jsx("rect",{x:"13",y:"3",width:"8",height:"8",rx:"1.5"}),s.jsx("rect",{x:"3",y:"13",width:"8",height:"8",rx:"1.5"}),s.jsx("rect",{x:"13",y:"13",width:"8",height:"8",rx:"1.5"})]}));st(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 2l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V5l8-3z"}),s.jsx("path",{d:"M9 12l2 2 4-4"})]}));const l_=st(s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"5",cy:"12",r:"2"}),s.jsx("circle",{cx:"19",cy:"5",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("path",{d:"M7 12l10-6M7 12l10 6"})]})),c_=st(s.jsxs(s.Fragment,{children:[s.jsx("ellipse",{cx:"12",cy:"5",rx:"8",ry:"3"}),s.jsx("path",{d:"M4 5v6c0 1.66 3.58 3 8 3s8-1.34 8-3V5"}),s.jsx("path",{d:"M4 11v6c0 1.66 3.58 3 8 3s8-1.34 8-3v-6"})]}));st(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 4h8a8 8 0 010 16H4z"}),s.jsx("path",{d:"M16 20l4 4"})]}));const d_=st(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M3 3v18h18"}),s.jsx("path",{d:"M7 15l4-4 4 4 5-7"})]})),E_=st(s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("path",{d:"M3 9h18M9 3v18"})]})),u_=st(s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),s.jsx("path",{d:"M8 12h8M12 8v8"})]})),T_=st(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 7h16M4 12h16M4 17h10"}),s.jsx("circle",{cx:"18",cy:"17",r:"2"})]})),f_=st(s.jsx(s.Fragment,{children:s.jsx("path",{d:"M3 5h18l-7 9v5l-4-2v-3L3 5z"})}));st(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 4h10l6 6v10H4z"}),s.jsx("path",{d:"M14 4v6h6"}),s.jsx("path",{d:"M8 14l3 3 5-5"})]}));const p_=st(s.jsx(s.Fragment,{children:s.jsx("path",{d:"M21 12a8 8 0 01-11.5 7.2L4 21l1.8-5.5A8 8 0 1121 12z"})})),UR=44,BR=188,FR="dql-activitybar-expanded";function S_(){var e;if(typeof window>"u")return!1;try{return((e=window.localStorage)==null?void 0:e.getItem(FR))==="1"}catch{return!1}}function R_(e){var t;try{(t=window.localStorage)==null||t.setItem(FR,e?"1":"0")}catch{}}function ou({title:e,icon:t,active:n,expanded:r,onClick:o,t:i}){const[a,l]=f.useState(!1),c=s.jsxs("button",{"aria-label":e,onClick:o,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{width:r?BR-12:UR-8,height:32,display:"flex",alignItems:"center",justifyContent:r?"flex-start":"center",gap:10,padding:r?"0 10px":0,marginLeft:r?6:4,marginRight:r?6:4,background:n?i.accent+"1f":a?i.textPrimary+"0f":"transparent",border:"none",borderRadius:6,cursor:"pointer",color:n?i.accent:a?i.textPrimary:i.textSecondary,transition:"background 0.15s, color 0.15s",fontFamily:i.font,fontSize:13,fontWeight:n?500:400,textAlign:"left",overflow:"hidden",whiteSpace:"nowrap"},children:[s.jsx("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,width:18,height:18},children:t}),r&&s.jsx("span",{style:{flex:1,textOverflow:"ellipsis",overflow:"hidden"},children:e})]});return r?c:s.jsx(sS,{content:e,side:"right",children:c})}function h_(){const{state:e,dispatch:t}=fe(),n=ie[e.themeMode],[r,o]=f.useState(S_);f.useEffect(()=>{R_(r)},[r]);function i(c){if(c==="lineage"){if(e.lineageFullscreen&&e.sidebarPanel==="lineage"&&e.sidebarOpen){t({type:"TOGGLE_LINEAGE_FULLSCREEN"}),t({type:"TOGGLE_SIDEBAR"});return}t({type:"SET_SIDEBAR_PANEL",panel:"lineage"}),t({type:"TOGGLE_LINEAGE_FULLSCREEN"});return}if(c==="connection"||c==="reference"||c==="git"||c==="apps"||c==="settings"){t({type:"SET_SIDEBAR_PANEL",panel:c});return}e.sidebarPanel===c&&e.sidebarOpen?t({type:"TOGGLE_SIDEBAR"}):t({type:"SET_SIDEBAR_PANEL",panel:c})}const a=[{key:"apps",title:"Apps",icon:s.jsx(_L,{size:16,strokeWidth:1.75}),active:e.mainView==="apps"},{key:"files",title:"Notebooks",icon:s.jsx(_R,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="files"&&e.sidebarOpen},{key:"schema",title:"Schema",icon:s.jsx(CR,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="schema"&&e.sidebarOpen},{key:"block_library",title:"Block Library",icon:s.jsx(wR,{size:16}),active:e.sidebarPanel==="block_library"&&e.sidebarOpen},{key:"lineage",title:"Lineage",icon:s.jsx(l_,{size:16}),active:e.lineageFullscreen},{key:"git",title:"Source control",icon:s.jsx(Gr,{size:16,strokeWidth:1.75}),active:e.mainView==="git"},{key:"connection",title:"Connections",icon:s.jsx(MR,{size:16,strokeWidth:1.75}),active:e.mainView==="connection"}],l=[{key:"reference",title:"Reference",icon:s.jsx(yR,{size:16,strokeWidth:1.75}),active:e.mainView==="reference",onClick:()=>i("reference")},{key:"help",title:"Help",icon:s.jsx(XC,{size:16,strokeWidth:1.75}),active:!1,onClick:()=>i("reference")},{key:"settings",title:"Settings",icon:s.jsx(GL,{size:16,strokeWidth:1.75}),active:e.mainView==="settings",onClick:()=>i("settings")}];return s.jsxs("div",{style:{width:r?BR:UR,flexShrink:0,background:n.activityBarBg,borderRight:`1px solid ${n.headerBorder}`,display:"flex",flexDirection:"column",paddingTop:6,paddingBottom:6,gap:2,userSelect:"none",transition:"width 0.18s ease",overflow:"hidden"},children:[s.jsx("div",{style:{display:"flex",justifyContent:r?"flex-end":"center",paddingLeft:r?6:0,paddingRight:r?6:0,marginBottom:4},children:s.jsx(sS,{content:r?"Collapse":"Expand",side:"right",children:s.jsx("button",{"aria-label":r?"Collapse sidebar rail":"Expand sidebar rail",onClick:()=>o(c=>!c),style:{width:28,height:26,display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",borderRadius:5,cursor:"pointer",color:n.textMuted,padding:0},onMouseEnter:c=>{c.currentTarget.style.color=n.textPrimary,c.currentTarget.style.background=n.textPrimary+"0f"},onMouseLeave:c=>{c.currentTarget.style.color=n.textMuted,c.currentTarget.style.background="transparent"},children:r?s.jsx(YC,{size:14,strokeWidth:2}):s.jsx($C,{size:14,strokeWidth:2})})})}),a.map(c=>s.jsx(ou,{title:c.title,icon:c.icon,active:c.active,expanded:r,onClick:()=>i(c.key),t:n},c.key)),s.jsx("div",{style:{flex:1}}),l.map(c=>s.jsx(ou,{title:c.title,icon:c.icon,active:c.active,expanded:r,onClick:c.onClick,t:n},c.key))]})}const sl={notebooks:"Notebooks",blocks:"Blocks",dashboards:"Dashboards"},A_={notebooks:!1,blocks:!1,dashboards:!0};function I_({type:e}){switch(e){case"notebook":return s.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M0 1.75A.75.75 0 0 1 .75 1h4.253c1.227 0 2.317.59 3 1.501A3.743 3.743 0 0 1 11.006 1h4.245a.75.75 0 0 1 .75.75v10.5a.75.75 0 0 1-.75.75h-4.507a2.25 2.25 0 0 0-1.591.659l-.622.621a.75.75 0 0 1-1.063 0L7.597 13.66A2.25 2.25 0 0 0 6.007 13H.75a.75.75 0 0 1-.75-.75Zm7.251 10.324.004-5.073-.002-2.253A2.25 2.25 0 0 0 5.003 2.5H1.5v9h4.507c.656 0 1.287.169 1.744.324Zm1.499.004c.457-.155 1.088-.324 1.744-.324H15v-9h-3.495a2.25 2.25 0 0 0-2.252 2.247l-.002 9.077Z"})});case"block":return s.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M10.5 0l5.25 4-5.25 4V6H9.25A1.75 1.75 0 0 0 7.5 7.75v2.5A1.75 1.75 0 0 0 9.25 12h1.25v8H9v-6.5A3.25 3.25 0 0 1 5.75 10h-2A3.25 3.25 0 0 1 .5 6.75v-2.5A3.25 3.25 0 0 1 3.75 1h2A3.25 3.25 0 0 1 9 4.5V6h1.5V0z"})});default:return s.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M.24 2.375C.24 1.064 1.225.001 2.409.001h6.451a1.17 1.17 0 0 1 .828.344l3.311 3.312a1.17 1.17 0 0 1 .344.828v9.14c0 1.31-.985 2.374-2.169 2.374H2.41C1.225 16 .24 14.937.24 13.625Zm2.169-1a.846.846 0 0 0-.844.86v11.39c0 .47.38.86.844.86h8.774a.847.847 0 0 0 .844-.86V5.157L8.688 1.373H2.41Z"})})}}function m_({expanded:e}){return s.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:e?s.jsx("path",{d:"M1.75 2.5a.25.25 0 0 0-.25.25v10.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V4.25a.25.25 0 0 0-.25-.25H7.5A1.75 1.75 0 0 1 5.75 2.5h-4ZM0 2.75C0 1.784.784 1 1.75 1h4c.966 0 1.75.784 1.75 1.75H14.25c.966 0 1.75.784 1.75 1.75v8.5A1.75 1.75 0 0 1 14.25 14H1.75A1.75 1.75 0 0 1 0 12.25Z"}):s.jsx("path",{d:"M1.75 2.5a.25.25 0 0 0-.25.25v10.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V4.25a.25.25 0 0 0-.25-.25H7.5A1.75 1.75 0 0 1 5.75 2.5h-4ZM0 2.75C0 1.784.784 1 1.75 1h4c.966 0 1.75.784 1.75 1.75H14.25c.966 0 1.75.784 1.75 1.75v8.5A1.75 1.75 0 0 1 14.25 14H1.75A1.75 1.75 0 0 1 0 12.25Z"})})}function Cc(e){return e.name.replace(/\.(dqlnb|dql)$/,"")}function O_({onOpenFile:e}){const{state:t,dispatch:n}=fe(),r=ie[t.themeMode],[o,i]=f.useState({notebooks:!0,blocks:!1,dashboards:!1}),[a,l]=f.useState(!1),c={notebooks:[],blocks:[],dashboards:[]};for(const u of t.files){const T=u.folder.toLowerCase();T in c&&c[T].push(u)}const d=u=>{i(T=>({...T,[u]:!T[u]}))},E=s.jsx("div",{style:{padding:"0 8px 8px"},children:s.jsxs("button",{onClick:()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{width:"100%",height:30,background:"transparent",border:`1px dashed ${a?r.accent:r.cellBorder}`,borderRadius:6,color:a?r.accent:r.textSecondary,cursor:"pointer",fontSize:12,fontFamily:r.font,fontWeight:500,display:"flex",alignItems:"center",justifyContent:"center",gap:6,transition:"border-color 0.15s, color 0.15s"},children:[s.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"New Notebook"]})});return s.jsxs(Ht,{title:"Files",bodyPadding:0,children:[E,t.filesLoading&&s.jsx("div",{style:{padding:"8px 14px",color:r.textMuted,fontSize:12,fontFamily:r.font},children:"Loading files…"}),Object.keys(sl).map(u=>{const T=c[u];if(A_[u]&&T.length===0)return null;const p=o[u],h=u==="notebooks"?()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}):u==="blocks"?()=>n({type:"OPEN_NEW_BLOCK_MODAL"}):void 0;return s.jsxs("div",{children:[s.jsx(N_,{label:sl[u],count:T.length,expanded:p,onToggle:()=>d(u),onAdd:h,t:r}),p&&s.jsx("div",{children:T.length===0?s.jsxs("div",{style:{padding:"4px 14px 4px 32px",fontSize:12,color:r.textMuted,fontFamily:r.font,fontStyle:"italic"},children:["No ",sl[u].toLowerCase()]}):T.map(A=>{var S;return s.jsx(g_,{file:A,active:((S=t.activeFile)==null?void 0:S.path)===A.path,onClick:()=>e(A),onShowLineage:()=>n({type:"OPEN_LINEAGE_DRAWER",nodeId:Cc(A)}),t:r},A.path)})})]},u)})]})}function N_({label:e,count:t,expanded:n,onToggle:r,onAdd:o,t:i}){const[a,l]=f.useState(!1),[c,d]=f.useState(!1);return s.jsxs("div",{onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{display:"flex",alignItems:"center",background:a?i.sidebarItemHover:"transparent",transition:"background 0.1s"},children:[s.jsxs("button",{onClick:r,style:{flex:1,display:"flex",alignItems:"center",gap:6,padding:"3px 0 3px 10px",background:"transparent",border:"none",cursor:"pointer",color:i.textSecondary,fontSize:11,fontWeight:600,fontFamily:i.font,letterSpacing:"0.04em",textTransform:"uppercase",textAlign:"left"},children:[s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:n?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s",flexShrink:0},children:s.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),s.jsx(m_,{expanded:n}),s.jsx("span",{style:{flex:1},children:e}),t>0&&s.jsx("span",{style:{background:i.pillBg,color:i.textMuted,borderRadius:10,padding:"0 5px",fontSize:10,fontWeight:500},children:t})]}),o&&a&&s.jsx("button",{onClick:E=>{E.stopPropagation(),o()},onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),title:`New ${e.slice(0,-1)}`,style:{background:c?i.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:c?i.accent:i.textMuted,fontSize:14,lineHeight:1,padding:"2px 8px",marginRight:4,flexShrink:0,transition:"color 0.1s"},children:"+"})]})}function g_({file:e,active:t,onClick:n,onShowLineage:r,t:o}){const[i,a]=f.useState(!1),[l,c]=f.useState(!1),d=e.type==="notebook"||e.type==="block"||e.type==="dashboard";return s.jsxs("div",{onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{position:"relative",display:"flex",alignItems:"center",background:t?o.sidebarItemActive:i?o.sidebarItemHover:"transparent",borderLeft:t?`2px solid ${o.accent}`:"2px solid transparent",transition:"background 0.1s"},children:[s.jsxs("button",{onClick:n,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:6,padding:"4px 8px 4px 24px",background:"transparent",border:"none",cursor:"pointer",color:t||i?o.textPrimary:o.textSecondary,fontSize:13,fontFamily:o.font,textAlign:"left",transition:"color 0.1s",overflow:"hidden"},children:[s.jsx("span",{style:{flexShrink:0,color:t?o.accent:o.textMuted},children:s.jsx(I_,{type:e.type})}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:Cc(e)}),e.isNew&&s.jsx("span",{style:{fontSize:9,fontWeight:600,color:o.accent,background:o.sidebarItemActive,borderRadius:4,padding:"1px 4px",flexShrink:0},children:"NEW"})]}),i&&d&&r&&s.jsx("button",{onClick:E=>{E.stopPropagation(),r()},onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),"aria-label":`Show lineage for ${Cc(e)}`,title:"Show lineage",style:{position:"absolute",right:6,top:"50%",transform:"translateY(-50%)",width:22,height:22,display:"inline-flex",alignItems:"center",justifyContent:"center",background:l?o.btnHover:"transparent",border:"none",borderRadius:4,color:l?o.accent:o.textMuted,cursor:"pointer"},children:s.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("circle",{cx:"6",cy:"6",r:"2.5"}),s.jsx("circle",{cx:"18",cy:"6",r:"2.5"}),s.jsx("circle",{cx:"12",cy:"18",r:"2.5"}),s.jsx("path",{d:"M6 8.5v2A2.5 2.5 0 0 0 8.5 13h7A2.5 2.5 0 0 0 18 10.5v-2"}),s.jsx("path",{d:"M12 13v2.5"})]})})]})}const x_={varchar:"#388bfd",text:"#388bfd",string:"#388bfd",char:"#388bfd",integer:"#56d364",int:"#56d364",bigint:"#56d364",smallint:"#56d364",float:"#56d364",double:"#56d364",decimal:"#56d364",numeric:"#56d364",real:"#56d364",date:"#e3b341",timestamp:"#e3b341",datetime:"#e3b341",time:"#e3b341",boolean:"#f778ba",bool:"#f778ba",json:"#79c0ff",jsonb:"#79c0ff",uuid:"#d2a8ff",bytea:"#ffa657",binary:"#ffa657"};function kR(e,t){const n=e.toLowerCase().split("(")[0].trim();return x_[n]??t}function y_({t:e}){return s.jsxs("div",{style:{padding:"8px 12px",display:"flex",flexDirection:"column",gap:8},children:[[1,2,3].map(t=>s.jsx("div",{style:{height:28,borderRadius:4,background:e.pillBg,opacity:.6,animation:"pulse 1.5s ease-in-out infinite"}},t)),s.jsx("style",{children:"@keyframes pulse { 0%,100%{opacity:.6} 50%{opacity:.3} }"})]})}function C_(){const{state:e,dispatch:t}=fe(),n=ie[e.themeMode],[r,o]=f.useState(!1),[i,a]=f.useState(""),l=async()=>{t({type:"SET_SCHEMA_LOADING",loading:!0});try{const h=await z.getSchema();t({type:"SET_SCHEMA",tables:h})}catch(h){console.error("Schema refresh failed:",h)}finally{t({type:"SET_SCHEMA_LOADING",loading:!1})}},c=f.useMemo(()=>{const h=i.trim().toLowerCase();return h?e.schemaTables.filter(A=>{const S=[A.name,A.path,A.objectType].filter(m=>!!m).some(m=>m.toLowerCase().includes(h)),R=A.columns.some(m=>m.name.toLowerCase().includes(h)||m.type.toLowerCase().includes(h));return S||R}):e.schemaTables},[i,e.schemaTables]),d=f.useMemo(()=>{const h=new Map;for(const A of c){const[S,...R]=A.name.split("."),m=R.length>0?S:A.source==="file"?"files":"default",I=h.get(m)??[];I.push(A),h.set(m,I)}return Array.from(h.entries()).sort((A,S)=>A[0].localeCompare(S[0]))},[c]),E={schemas:d.length,tables:e.schemaTables.length,columns:e.schemaTables.reduce((h,A)=>h+A.columns.length,0)},u={width:"100%",background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:6,color:n.textPrimary,fontSize:12,fontFamily:n.font,padding:"7px 10px",outline:"none",boxSizing:"border-box"},T=s.jsxs("button",{onClick:l,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),title:"Refresh schema",style:{background:r?n.btnHover:"transparent",border:`1px solid ${n.btnBorder}`,borderRadius:6,cursor:"pointer",color:r?n.textSecondary:n.textMuted,fontSize:11,fontFamily:n.font,padding:"6px 8px",display:"flex",alignItems:"center",gap:4,transition:"all 0.15s"},children:[s.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M1.705 8.005a.75.75 0 0 1 .834.656 5.5 5.5 0 0 0 9.592 2.97l-1.204-1.204a.25.25 0 0 1 .177-.427h3.646a.25.25 0 0 1 .25.25v3.646a.25.25 0 0 1-.427.177l-1.38-1.38A7.002 7.002 0 0 1 1.05 8.84a.75.75 0 0 1 .656-.834ZM8 2.5a5.487 5.487 0 0 0-4.131 1.869l1.204 1.204A.25.25 0 0 1 4.896 6H1.25A.25.25 0 0 1 1 5.75V2.104a.25.25 0 0 1 .427-.177l1.38 1.38A7.002 7.002 0 0 1 14.95 7.16a.75.75 0 0 1-1.49.178A5.5 5.5 0 0 0 8 2.5Z"})}),"Refresh"]}),p=s.jsx(Go,{children:s.jsx("input",{value:i,onChange:h=>a(h.target.value),placeholder:"Search schemas, tables, columns...",style:{...u,flex:1,minWidth:100}})});return s.jsxs(Ht,{title:"Data Catalog",subtitle:"Schemas, tables, views, and columns from the active connection.",actions:T,toolbar:p,bodyPadding:0,children:[s.jsx(L_,{stats:E,t:n}),e.schemaLoading?s.jsx(y_,{t:n}):e.schemaTables.length===0?s.jsx(kt,{title:"No tables found",description:"Connect a data source to explore schema."}):c.length===0?s.jsx(kt,{title:"No matches",description:"No database objects match the current search."}):s.jsx("div",{style:{overflow:"auto",flex:1},children:d.map(([h,A])=>s.jsx(__,{name:h,tables:A,defaultExpanded:d.length<=2||i.trim().length>0,t:n},h))})]})}function L_({stats:e,t}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"8px 12px",borderBottom:`1px solid ${t.headerBorder}`,fontSize:11,fontFamily:t.font,color:t.textMuted},children:[s.jsx(il,{label:"schemas",value:e.schemas,t}),s.jsx("span",{style:{color:t.headerBorder},children:"·"}),s.jsx(il,{label:"tables",value:e.tables,t}),s.jsx("span",{style:{color:t.headerBorder},children:"·"}),s.jsx(il,{label:"columns",value:e.columns,t})]})}function il({label:e,value:t,t:n}){return s.jsxs("span",{style:{display:"inline-flex",alignItems:"baseline",gap:4},children:[s.jsx("span",{style:{color:n.textPrimary,fontWeight:600,fontSize:12},children:t}),s.jsx("span",{children:e})]})}function __({name:e,tables:t,defaultExpanded:n,t:r}){const[o,i]=f.useState(n),[a,l]=f.useState(!1);return s.jsxs("div",{children:[s.jsxs("button",{onClick:()=>i(c=>!c),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),"aria-expanded":o,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"6px 12px",background:a?r.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:r.textSecondary,fontSize:11,fontWeight:700,fontFamily:r.font,textTransform:"uppercase",letterSpacing:"0.05em",textAlign:"left",transition:"background 0.1s",position:"sticky",top:0,zIndex:1,backdropFilter:"blur(6px)"},children:[s.jsx("svg",{width:"9",height:"9",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:o?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s",color:r.textMuted,flexShrink:0},children:s.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),s.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",style:{color:r.textMuted,flexShrink:0},children:s.jsx("path",{d:"M1 3.5c0-1.865 2.91-3 6-3s6 1.135 6 3v9c0 1.865-2.91 3-6 3s-6-1.135-6-3Zm1.5.5c.484.85 2.28 1.5 4.5 1.5s4.016-.65 4.5-1.5V6c-.484.85-2.28 1.5-4.5 1.5S2.984 6.85 2.5 6Zm0 4c.484.85 2.28 1.5 4.5 1.5s4.016-.65 4.5-1.5v2c-.484.85-2.28 1.5-4.5 1.5S2.984 10.85 2.5 10Z"})}),s.jsx("span",{style:{flex:1},children:e}),s.jsx("span",{style:{background:r.pillBg,color:r.textMuted,borderRadius:10,padding:"0 6px",fontSize:10,fontWeight:500},children:t.length})]}),o&&t.map(c=>s.jsx(b_,{table:c,t:r},c.name))]})}function b_({table:e,t}){var u,T;const{dispatch:n}=fe(),[r,o]=f.useState(!1),[i,a]=f.useState(!1),l=async()=>{if(n({type:"TOGGLE_SCHEMA_TABLE",tableName:e.name}),!e.expanded&&e.columns.length===0){a(!0);try{const p=await z.describeTable(e.path);p.length>0&&n({type:"SET_TABLE_COLUMNS",tableName:e.name,columns:p})}catch(p){console.error("describeTable failed:",p)}finally{a(!1)}}},c=((u=e.objectType)==null?void 0:u.toLowerCase().includes("view"))??!1,d=c?"view":"table",E=c?"#d2a8ff":t.accent;return s.jsxs("div",{children:[s.jsxs("button",{onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onClick:l,style:{width:"100%",display:"flex",alignItems:"center",gap:7,padding:"6px 12px 6px 22px",background:r?t.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:t.textPrimary,fontSize:12.5,fontFamily:t.font,fontWeight:500,textAlign:"left",transition:"background 0.1s"},children:[s.jsx("svg",{width:"9",height:"9",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:e.expanded?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s",flexShrink:0,color:t.textMuted},children:s.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),c?s.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:E,flexShrink:0},children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}):s.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:E,flexShrink:0},children:[s.jsx("ellipse",{cx:"12",cy:"5",rx:"9",ry:"3"}),s.jsx("path",{d:"M3 5v14a9 3 0 0 0 18 0V5"}),s.jsx("path",{d:"M3 12a9 3 0 0 0 18 0"})]}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name.includes(".")?e.name.split(".").slice(1).join("."):e.name}),s.jsx("span",{style:{fontSize:9,fontFamily:t.fontMono,color:E,background:`${E}1f`,borderRadius:3,padding:"1px 5px",flexShrink:0,fontWeight:600,letterSpacing:"0.04em"},children:d}),((T=e.governance)==null?void 0:T.status)&&s.jsx(P_,{status:e.governance.status,t}),e.columns.length>0&&s.jsx("span",{style:{fontSize:10,color:t.textMuted,background:t.pillBg,borderRadius:8,padding:"1px 6px",flexShrink:0,fontVariantNumeric:"tabular-nums"},title:`${e.columns.length} columns`,children:e.columns.length})]}),e.expanded&&s.jsxs("div",{style:{paddingLeft:26},children:[e.governance&&(e.governance.owner||e.governance.domain)&&s.jsxs("div",{style:{padding:"3px 10px",display:"flex",gap:8,flexWrap:"wrap"},children:[e.governance.domain&&s.jsxs("span",{style:{fontSize:9,fontFamily:t.font,color:t.textMuted},children:[s.jsx("span",{style:{fontWeight:600},children:"domain:"})," ",e.governance.domain]}),e.governance.owner&&s.jsxs("span",{style:{fontSize:9,fontFamily:t.font,color:t.textMuted},children:[s.jsx("span",{style:{fontWeight:600},children:"owner:"})," ",e.governance.owner]})]}),i?s.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:"..."}):e.columns.length===0?s.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:"No columns"}):e.columns.map(p=>s.jsx(D_,{col:p,t},p.name))]})]})}function D_({col:e,t}){const[n,r]=f.useState(!1),[o,i]=f.useState(!1),a=kR(e.type,t.accent),l=async c=>{c.stopPropagation();try{await navigator.clipboard.writeText(e.name),i(!0),setTimeout(()=>i(!1),1200)}catch{}};return s.jsxs("div",{onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),style:{display:"flex",alignItems:"center",gap:8,padding:"4px 12px 4px 44px",background:n?t.sidebarItemHover:"transparent",cursor:"default",transition:"background 0.1s"},children:[s.jsx("span",{"aria-hidden":!0,style:{flexShrink:0,width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:3,background:`${a}1a`,color:a,fontFamily:t.fontMono,fontSize:9,fontWeight:700,letterSpacing:0},title:e.type,children:M_(e.type)}),s.jsx("span",{style:{flex:1,fontSize:11.5,fontFamily:t.fontMono,color:t.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.name,children:e.name}),s.jsx("span",{style:{fontSize:10,fontFamily:t.fontMono,color:a,background:`${a}1a`,borderRadius:3,padding:"1px 5px",flexShrink:0,fontWeight:500},children:e.type.toLowerCase()}),n&&s.jsx("button",{onClick:l,"aria-label":`Copy column name ${e.name}`,title:o?"Copied!":"Copy column name",style:{flexShrink:0,width:20,height:20,display:"inline-flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",borderRadius:3,color:o?"#56d364":t.textMuted,cursor:"pointer"},children:o?s.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("polyline",{points:"20 6 9 17 4 12"})}):s.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]})}function M_(e){const t=e.toLowerCase();return/(int|long|short|byte|number|numeric|decimal|float|double|real)/.test(t)?"#":/(bool)/.test(t)?"B":/(date|time|timestamp)/.test(t)?"⌚":/(json|map|struct|object|variant)/.test(t)?"{}":/(array|list)/.test(t)?"[]":/(uuid|guid)/.test(t)?"U":/(char|text|string|varchar)/.test(t)?"A":"·"}const v_={certified:{color:"#56d364",label:"Certified",icon:"✓"},review:{color:"#e3b341",label:"In Review",icon:"◎"},draft:{color:"#8b949e",label:"Draft",icon:"○"},deprecated:{color:"#f85149",label:"Deprecated",icon:"✗"},pending_recertification:{color:"#ffa657",label:"Re-cert",icon:"↻"}};function P_({status:e,t}){const n=v_[e];return n?s.jsxs("span",{title:n.label,style:{fontSize:8,fontWeight:700,fontFamily:t.font,color:n.color,background:`${n.color}18`,border:`1px solid ${n.color}40`,borderRadius:3,padding:"0 4px",flexShrink:0,letterSpacing:"0.04em",lineHeight:"14px"},children:[n.icon," ",n.label.toUpperCase()]}):null}const Ot=(e,t)=>`https://cdn.simpleicons.org/${e}/${t}`,sr=(e,t)=>`https://cdn.jsdelivr.net/gh/devicons/devicon@latest/icons/${e}/${e}-${t}.svg`,w_={duckdb:[Ot("duckdb","FFF000")],file:[Ot("duckdb","FFF000")],postgres:[Ot("postgresql","4169E1")],mysql:[Ot("mysql","4479A1"),sr("mysql","original")],sqlite:[Ot("sqlite","003B57"),sr("sqlite","original")],mssql:[sr("microsoftsqlserver","original")],redshift:[],snowflake:[Ot("snowflake","29B5E8")],bigquery:[Ot("googlebigquery","4285F4"),sr("googlecloud","plain")],databricks:[Ot("databricks","FF3621")],clickhouse:[Ot("clickhouse","FFCC01")],trino:[Ot("trino","DD00A1")],athena:[sr("amazonwebservices","plain-wordmark")],fabric:[sr("azure","original")]},U_={duckdb:"#f4bc00",file:"#f4bc00",postgres:"#336791",bigquery:"#4285f4",snowflake:"#29b5e8",sqlite:"#003b57",mysql:"#00758f",mssql:"#cc2927",redshift:"#8c4fff",databricks:"#ff3621",clickhouse:"#ffcc00",athena:"#ff9900",trino:"#dd00a1",fabric:"#0078d4"};function B_({size:e,color:t}){return s.jsx("span",{"aria-hidden":!0,style:{width:e,height:e,borderRadius:3,background:t,flexShrink:0,display:"inline-block"}})}function al({driver:e,size:t=16,fallbackColor:n}){const r=w_[e]??[],o=n??U_[e]??"#888",[i,a]=f.useState(0);return r.length===0||i>=r.length?s.jsx(B_,{size:t,color:o}):s.jsx("img",{src:r[i],alt:`${e} logo`,width:t,height:t,loading:"lazy",onError:()=>a(i+1),style:{flexShrink:0,display:"block",objectFit:"contain"}})}const Lc={duckdb:"DuckDB",file:"Local File / DuckDB",postgres:"PostgreSQL",bigquery:"BigQuery",snowflake:"Snowflake",sqlite:"SQLite",mysql:"MySQL",mssql:"SQL Server",redshift:"Amazon Redshift",databricks:"Databricks",clickhouse:"ClickHouse",athena:"Amazon Athena",trino:"Trino",fabric:"Microsoft Fabric"},su={duckdb:"#f4bc00",file:"#f4bc00",postgres:"#336791",bigquery:"#4285f4",snowflake:"#29b5e8",sqlite:"#003b57",mysql:"#00758f",mssql:"#cc2927",redshift:"#8c4fff",databricks:"#ff3621",clickhouse:"#ffcc00",athena:"#ff9900",trino:"#dd00a1",fabric:"#0078d4"},F_={duckdb:"In-process analytical database",file:"Local CSV / Parquet via DuckDB",postgres:"Open-source relational warehouse",bigquery:"Google Cloud serverless warehouse",snowflake:"Cloud data platform",sqlite:"Embedded SQL database",mysql:"Open-source relational database",mssql:"Microsoft SQL Server",redshift:"AWS cloud data warehouse",databricks:"Lakehouse platform",clickhouse:"Columnar OLAP database",athena:"AWS serverless S3 query engine",trino:"Distributed SQL query engine",fabric:"Microsoft unified analytics"},k_={duckdb:["filepath"],postgres:["host","port","database","user","password"],mysql:["host","port","database","user","password"],bigquery:["project","dataset","keyFilename"],snowflake:["account","warehouse","database","schema","username","password"],mssql:["server","port","database","user","password"],redshift:["host","port","database","user","password"],sqlite:["filepath"],databricks:["host","path","token"],clickhouse:["host","port","database","user","password"],athena:["region","database","outputLocation"],trino:["host","port","catalog","schema","user"],fabric:["server","database","authentication"]},j_=[{name:"default",label:"Local DuckDB",description:"In-memory DuckDB — no configuration needed",config:{driver:"duckdb",filepath:":memory:"}},{name:"postgres",label:"PostgreSQL",description:"Connect to a local PostgreSQL instance",config:{driver:"postgres",host:"localhost",port:5432,database:"postgres",user:"postgres",password:""}},{name:"snowflake",label:"Snowflake",description:"Connect to your Snowflake data warehouse",config:{driver:"snowflake",account:"",warehouse:"",database:"",schema:"PUBLIC",username:"",password:""}}];function jR(){const{state:e}=fe(),t=ie[e.themeMode],[n,r]=f.useState(null),[o,i]=f.useState(!1),[a,l]=f.useState(null),[c,d]=f.useState(null),[E,u]=f.useState(!1),[T,p]=f.useState(!1),[h,A]=f.useState(null),[S,R]=f.useState(""),[m,I]=f.useState("duckdb"),[O,N]=f.useState({});f.useEffect(()=>{z.getConnections().then(M=>{r(M),Object.keys(M.connections).length>0&&z.testConnection().then(l)})},[]);const x=async()=>{i(!0),l(null);const M=await z.testConnection();l(M),i(!1)},g=(M,U)=>{d(M),u(!1),R(M),I((U==null?void 0:U.driver)??"duckdb");const P={};Object.entries(U??{}).forEach(([_,F])=>{_!=="driver"&&_!=="type"&&(P[_]=String(F??""))}),N(P)},C=()=>{u(!0),d(null),R(""),I("duckdb"),N({})},y=()=>{d(null),u(!1)},w=async()=>{if(!n)return;p(!0),A(null);const M=S.trim()||(c??"default"),U={driver:m};Object.entries(O).forEach(([_,F])=>{F.trim()&&(_==="port"&&!isNaN(Number(F))?U[_]=Number(F):U[_]=F)});const P={...n.connections};c&&c!==M&&delete P[c],P[M]=U;try{await z.saveConnections(P);const _=await z.getConnections();r(_),A("Saved"),setTimeout(()=>A(null),2e3),d(null),u(!1);try{i(!0);const F=await z.testConnection();l(F)}catch{}finally{i(!1)}}catch(_){A(`Error: ${_.message}`)}finally{p(!1)}},v=async M=>{if(!n)return;const U={...n.connections};delete U[M],p(!0);try{await z.saveConnections(U);const P=await z.getConnections();r(P),d(null)}finally{p(!1)}},B={fontSize:10,fontWeight:600,letterSpacing:"0.07em",textTransform:"uppercase",color:t.textMuted,fontFamily:t.font,marginBottom:6},b={background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:7,padding:"10px 12px",marginBottom:10},L=(n==null?void 0:n.connections)??{},D=(n==null?void 0:n.default)??"";return s.jsxs(Ht,{title:"Connections",bodyPadding:12,children:[s.jsx("div",{style:B,children:"Connections"}),n===null?s.jsx("div",{style:{fontSize:12,color:t.textMuted,fontFamily:t.font},children:"Loading…"}):Object.entries(L).map(([M,U])=>{const P=(U==null?void 0:U.driver)??(U==null?void 0:U.type)??"unknown",_=M===D||Object.keys(L).length===1,F=su[P]??t.accent;return c===M?s.jsx(iu,{t,editName:S,setEditName:R,editDriver:m,setEditDriver:I,editFields:O,setEditFields:N,onSave:w,onCancel:y,onDelete:()=>v(M),saving:T,isNew:!1},M):s.jsxs("div",{style:{...b,borderLeft:_?`3px solid ${F}`:`1px solid ${t.cellBorder}`},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[s.jsx(al,{driver:P,size:18,fallbackColor:F}),s.jsx("span",{style:{fontSize:12,fontWeight:600,color:t.textPrimary,fontFamily:t.font},children:Lc[P]??P}),s.jsx("span",{style:{fontSize:11,fontFamily:t.fontMono,color:t.textMuted},children:M}),_&&(a==null?void 0:a.ok)&&s.jsx("span",{title:"Connected","aria-label":"Connected",style:{width:7,height:7,borderRadius:"50%",background:t.success,flexShrink:0,boxShadow:`0 0 0 2px ${t.success}25`}}),_&&a&&!a.ok&&s.jsx("span",{title:a.message,"aria-label":"Disconnected",style:{width:7,height:7,borderRadius:"50%",background:t.error,flexShrink:0,boxShadow:`0 0 0 2px ${t.error}25`}}),_&&s.jsx("span",{style:{fontSize:9,color:t.accent,fontFamily:t.font,fontWeight:600,letterSpacing:"0.05em"},children:"DEFAULT"}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:()=>g(M,U),style:{background:"transparent",border:`1px solid ${t.btnBorder}`,borderRadius:3,cursor:"pointer",color:t.textMuted,fontSize:10,fontFamily:t.font,padding:"1px 6px",transition:"all 0.15s"},children:"Edit"})]}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:3},children:Object.entries(U??{}).filter(([k])=>k!=="driver"&&k!=="type").map(([k,H])=>s.jsxs("div",{style:{display:"flex",gap:6,alignItems:"baseline"},children:[s.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.fontMono,minWidth:70,flexShrink:0},children:k}),s.jsx("span",{style:{fontSize:11,color:t.textSecondary,fontFamily:t.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k.toLowerCase().includes("password")||k.toLowerCase().includes("token")?"••••••••":String(H)})]},k))})]},M)}),!E&&!c&&Object.keys(L).length===0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...B,marginTop:8},children:"Quick Connect"}),s.jsx("div",{style:{display:"grid",gap:6,marginBottom:12},children:j_.map(M=>s.jsxs("button",{onClick:async()=>{p(!0);try{const U={...L,[M.name]:M.config};await z.saveConnections(U);const P=await z.getConnections();r(P),i(!0);const _=await z.testConnection();l(_),i(!1)}finally{p(!1)}},disabled:T,style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:7,cursor:T?"not-allowed":"pointer",textAlign:"left",transition:"border-color 0.15s"},children:[s.jsx(al,{driver:M.config.driver,size:18}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:12,fontWeight:600,color:t.textPrimary,fontFamily:t.font},children:M.label}),s.jsx("div",{style:{fontSize:10,color:t.textMuted,fontFamily:t.font},children:M.description})]})]},M.name))})]}),E?s.jsx(iu,{t,editName:S,setEditName:R,editDriver:m,setEditDriver:I,editFields:O,setEditFields:N,onSave:w,onCancel:y,saving:T,isNew:!0}):s.jsxs("button",{onClick:C,style:{width:"100%",padding:"7px 0",borderRadius:6,border:`1px dashed ${t.cellBorder}`,background:"transparent",color:t.textSecondary,fontSize:12,fontFamily:t.font,fontWeight:500,cursor:"pointer",marginBottom:12,display:"flex",alignItems:"center",justifyContent:"center",gap:6,transition:"border-color 0.15s, color 0.15s"},children:[s.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"Add Connection"]}),h&&s.jsx("div",{style:{fontSize:11,fontFamily:t.font,padding:"4px 10px",borderRadius:4,marginBottom:8,color:h.startsWith("Error")?t.error:t.success,background:h.startsWith("Error")?`${t.error}12`:`${t.success}12`},children:h}),s.jsx("button",{onClick:x,disabled:o,style:{width:"100%",padding:"7px 0",borderRadius:6,border:`1px solid ${t.btnBorder}`,background:t.btnBg,color:t.textSecondary,fontSize:12,fontFamily:t.font,fontWeight:500,cursor:o?"not-allowed":"pointer",marginBottom:8,opacity:o?.7:1,transition:"all 0.15s"},children:o?"Testing…":"Test Connection"}),a&&s.jsxs("div",{style:{fontSize:12,fontFamily:t.font,color:a.ok?t.success:t.error,background:a.ok?`${t.success}12`:`${t.error}12`,border:`1px solid ${a.ok?t.success:t.error}40`,borderRadius:6,padding:"7px 10px",marginBottom:12},children:[a.ok?"✓ ":"✗ ",a.message]}),s.jsx("div",{style:{...B,marginTop:4},children:"Catalog"}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(160px, 1fr))",gap:8,marginBottom:12},children:Object.entries(Lc).map(([M,U])=>{const P=su[M]??t.accent,_=F_[M]??"";return s.jsxs("div",{style:{background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:8,padding:"10px 12px",display:"flex",flexDirection:"column",gap:4,minHeight:76,position:"relative",transition:"border-color 0.15s"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx(al,{driver:M,size:18,fallbackColor:P}),s.jsx("span",{style:{fontSize:12,fontWeight:600,color:t.textPrimary,fontFamily:t.font},children:U})]}),s.jsx("div",{style:{fontSize:10,color:t.textMuted,fontFamily:t.font,lineHeight:1.35},children:_}),s.jsx("code",{style:{fontSize:9,color:t.textMuted,fontFamily:t.fontMono,marginTop:"auto"},children:M})]},M)})})]})}function iu({t:e,editName:t,setEditName:n,editDriver:r,setEditDriver:o,editFields:i,setEditFields:a,onSave:l,onCancel:c,onDelete:d,saving:E,isNew:u}){const T=k_[r]??[],p={background:e.inputBg,border:`1px solid ${e.inputBorder}`,borderRadius:4,color:e.textPrimary,fontSize:11,fontFamily:e.fontMono,padding:"4px 8px",outline:"none",width:"100%"},h={fontSize:9,fontWeight:600,color:e.textMuted,fontFamily:e.font,letterSpacing:"0.05em",textTransform:"uppercase",marginBottom:2};return s.jsxs("div",{style:{background:e.cellBg,border:`1px solid ${e.accent}40`,borderRadius:7,padding:"10px 12px",marginBottom:10},children:[s.jsx("div",{style:{fontSize:11,fontWeight:600,color:e.accent,fontFamily:e.font,marginBottom:8},children:u?"New Connection":"Edit Connection"}),s.jsxs("div",{style:{marginBottom:6},children:[s.jsx("div",{style:h,children:"Name"}),s.jsx("input",{style:p,value:t,onChange:A=>n(A.target.value),placeholder:"e.g. production"})]}),s.jsxs("div",{style:{marginBottom:6},children:[s.jsx("div",{style:h,children:"Driver"}),s.jsx("select",{style:{...p,fontFamily:e.font},value:r,onChange:A=>{o(A.target.value),a({})},children:Object.entries(Lc).map(([A,S])=>s.jsx("option",{value:A,children:S},A))})]}),T.map(A=>s.jsxs("div",{style:{marginBottom:6},children:[s.jsx("div",{style:h,children:A}),s.jsx("input",{style:p,type:A.toLowerCase().includes("password")||A.toLowerCase().includes("token")?"password":"text",value:i[A]??"",placeholder:A==="port"?"5432":A==="filepath"?":memory:":"",onChange:S=>a({...i,[A]:S.target.value})})]},A)),s.jsxs("div",{style:{display:"flex",gap:6,marginTop:8},children:[s.jsx("button",{onClick:l,disabled:E,style:{flex:1,padding:"5px 0",borderRadius:5,border:"none",background:e.accent,color:"#fff",fontSize:11,fontFamily:e.font,fontWeight:600,cursor:E?"not-allowed":"pointer",opacity:E?.6:1},children:E?"Saving…":"Save"}),s.jsx("button",{onClick:c,style:{padding:"5px 12px",borderRadius:5,border:`1px solid ${e.btnBorder}`,background:"transparent",color:e.textSecondary,fontSize:11,fontFamily:e.font,cursor:"pointer"},children:"Cancel"}),d&&!u&&s.jsx("button",{onClick:d,style:{padding:"5px 12px",borderRadius:5,border:`1px solid ${e.error}40`,background:"transparent",color:e.error,fontSize:11,fontFamily:e.font,cursor:"pointer"},children:"Delete"})]})]})}function wt({title:e,defaultOpen:t=!1,children:n,t:r}){const[o,i]=f.useState(t),[a,l]=f.useState(!1);return s.jsxs("div",{style:{borderBottom:`1px solid ${r.headerBorder}`},children:[s.jsxs("button",{onClick:()=>i(c=>!c),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{width:"100%",padding:"7px 12px",display:"flex",alignItems:"center",gap:6,background:a?r.sidebarItemHover:"transparent",border:"none",cursor:"pointer",textAlign:"left",transition:"background 0.1s"},children:[s.jsx("span",{style:{fontSize:9,color:r.textMuted,display:"inline-block",transition:"transform 0.15s",transform:o?"rotate(90deg)":"rotate(0deg)",lineHeight:1},children:"▶"}),s.jsx("span",{style:{fontSize:11,fontWeight:600,fontFamily:r.font,color:r.textSecondary,letterSpacing:"0.04em"},children:e})]}),o&&s.jsx("div",{style:{padding:"4px 12px 10px"},children:n})]})}function G_({code:e,t}){const[n,r]=f.useState(!1);async function o(){try{await navigator.clipboard.writeText(e)}catch{const i=document.createElement("textarea");i.value=e,document.body.appendChild(i),i.select(),document.execCommand("copy"),document.body.removeChild(i)}r(!0),setTimeout(()=>r(!1),1500)}return s.jsx("button",{onClick:o,title:"Copy to clipboard",style:{position:"absolute",top:6,right:6,padding:"2px 6px",fontSize:10,fontFamily:t.font,background:n?`${t.success}20`:t.btnBg,border:`1px solid ${n?t.success+"50":t.btnBorder}`,borderRadius:4,cursor:"pointer",color:n?t.success:t.textMuted,transition:"all 0.15s"},children:n?"✓":"Copy"})}function Ue({code:e,t}){return s.jsxs("div",{style:{position:"relative",marginTop:6},children:[s.jsx("pre",{style:{margin:0,padding:"8px 10px",paddingRight:52,background:t.editorBg,border:`1px solid ${t.cellBorder}`,borderRadius:6,fontFamily:t.fontMono,fontSize:11,color:t.textPrimary,lineHeight:1.6,whiteSpace:"pre",overflowX:"auto"},children:e}),s.jsx(G_,{code:e,t})]})}function au({rows:e,t}){return s.jsx("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11,fontFamily:t.font,marginTop:6},children:s.jsx("tbody",{children:e.map(([n,r],o)=>s.jsxs("tr",{style:{borderBottom:`1px solid ${t.tableBorder}`},children:[s.jsx("td",{style:{padding:"5px 6px 5px 0",fontFamily:t.fontMono,fontSize:11,color:t.accent,whiteSpace:"nowrap",verticalAlign:"top",width:"45%"},children:n}),s.jsx("td",{style:{padding:"5px 0",color:t.textSecondary,verticalAlign:"top",lineHeight:1.5},children:r})]},o))})})}const H_=`block "Revenue by Channel" {
|
|
314
|
-
domain = "revenue"
|
|
315
|
-
type = "custom"
|
|
316
|
-
description = "Revenue grouped by sales channel"
|
|
317
|
-
owner = "data-team"
|
|
318
|
-
tags = ["revenue"]
|
|
319
|
-
|
|
320
|
-
params {
|
|
321
|
-
period = "current_quarter"
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
query = """
|
|
325
|
-
SELECT channel,
|
|
326
|
-
SUM(order_total) AS revenue
|
|
327
|
-
FROM read_csv_auto('data/orders.csv')
|
|
328
|
-
WHERE fiscal_period = \${period}
|
|
329
|
-
GROUP BY channel
|
|
330
|
-
ORDER BY revenue DESC
|
|
331
|
-
"""
|
|
332
|
-
|
|
333
|
-
visualization {
|
|
334
|
-
chart = "bar"
|
|
335
|
-
x = channel
|
|
336
|
-
y = revenue
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
tests {
|
|
340
|
-
assert row_count > 0
|
|
341
|
-
}
|
|
342
|
-
}`,Y_=`# semantic-layer/metrics/total_revenue.yaml
|
|
343
|
-
name: total_revenue
|
|
344
|
-
label: Total Revenue
|
|
345
|
-
description: Sum of all recognized revenue.
|
|
346
|
-
domain: finance
|
|
347
|
-
sql: SUM(amount)
|
|
348
|
-
type: sum # sum|count|count_distinct|avg|min|max|custom
|
|
349
|
-
table: fct_revenue
|
|
350
|
-
tags:
|
|
351
|
-
- revenue
|
|
352
|
-
- kpi`,W_=`# semantic-layer/dimensions/segment.yaml
|
|
353
|
-
name: segment
|
|
354
|
-
label: Customer Segment
|
|
355
|
-
description: Customer segment tier.
|
|
356
|
-
sql: segment_tier
|
|
357
|
-
type: string # string|number|date|boolean
|
|
358
|
-
table: fct_revenue`,$_=`# semantic-layer/hierarchies/time.yaml
|
|
359
|
-
name: fiscal_time
|
|
360
|
-
label: Fiscal Time
|
|
361
|
-
description: Drill from year to quarter.
|
|
362
|
-
domain: finance
|
|
363
|
-
levels:
|
|
364
|
-
- name: fiscal_year
|
|
365
|
-
dimension: fiscal_year
|
|
366
|
-
order: 1
|
|
367
|
-
- name: fiscal_quarter
|
|
368
|
-
dimension: fiscal_quarter
|
|
369
|
-
order: 2
|
|
370
|
-
defaultRollup: sum`,V_=`# semantic-layer/cubes/revenue_cube.yaml
|
|
371
|
-
name: revenue
|
|
372
|
-
label: Revenue Cube
|
|
373
|
-
table: fct_revenue
|
|
374
|
-
domain: finance
|
|
375
|
-
|
|
376
|
-
measures:
|
|
377
|
-
- name: total_revenue
|
|
378
|
-
sql: SUM(amount)
|
|
379
|
-
type: sum
|
|
380
|
-
- name: deal_count
|
|
381
|
-
sql: COUNT(*)
|
|
382
|
-
type: count
|
|
383
|
-
|
|
384
|
-
dimensions:
|
|
385
|
-
- name: segment_tier
|
|
386
|
-
sql: segment_tier
|
|
387
|
-
type: string
|
|
388
|
-
|
|
389
|
-
time_dimensions:
|
|
390
|
-
- name: recognized_at
|
|
391
|
-
sql: recognized_at
|
|
392
|
-
primary_time: true
|
|
393
|
-
granularities: [day, month, quarter, year]
|
|
394
|
-
|
|
395
|
-
joins:
|
|
396
|
-
- name: customers
|
|
397
|
-
type: left
|
|
398
|
-
sql: "\${left}.customer_id = \${right}.id"`,X_=`{
|
|
399
|
-
"semanticLayer": {
|
|
400
|
-
"provider": "dql"
|
|
401
|
-
}
|
|
402
|
-
}`,z_=`{
|
|
403
|
-
"semanticLayer": {
|
|
404
|
-
"provider": "dbt",
|
|
405
|
-
"projectPath": "/path/to/your/dbt-project"
|
|
406
|
-
}
|
|
407
|
-
}`,K_=`{
|
|
408
|
-
"semanticLayer": {
|
|
409
|
-
"provider": "cubejs",
|
|
410
|
-
"projectPath": "/path/to/your/cube-project"
|
|
411
|
-
}
|
|
412
|
-
}`,q_=`{
|
|
413
|
-
"defaultConnection": {
|
|
414
|
-
"driver": "file",
|
|
415
|
-
"filepath": ":memory:"
|
|
416
|
-
}
|
|
417
|
-
}`,J_=`{
|
|
418
|
-
"defaultConnection": {
|
|
419
|
-
"driver": "snowflake",
|
|
420
|
-
"account": "acme.snowflakecomputing.com",
|
|
421
|
-
"username": "your_user",
|
|
422
|
-
"password": "\${SNOWFLAKE_PASSWORD}",
|
|
423
|
-
"database": "ANALYTICS",
|
|
424
|
-
"schema": "PUBLIC",
|
|
425
|
-
"warehouse": "COMPUTE_WH",
|
|
426
|
-
"role": "ANALYST"
|
|
427
|
-
}
|
|
428
|
-
}`,Q_=`{
|
|
429
|
-
"defaultConnection": {
|
|
430
|
-
"driver": "bigquery",
|
|
431
|
-
"project": "your-gcp-project-id",
|
|
432
|
-
"dataset": "analytics",
|
|
433
|
-
"keyFilename": "./service-account.json"
|
|
434
|
-
}
|
|
435
|
-
}`,Z_=`{
|
|
436
|
-
"defaultConnection": {
|
|
437
|
-
"driver": "postgres",
|
|
438
|
-
"host": "localhost",
|
|
439
|
-
"port": 5432,
|
|
440
|
-
"database": "analytics",
|
|
441
|
-
"username": "your_user",
|
|
442
|
-
"password": "\${POSTGRES_PASSWORD}"
|
|
443
|
-
}
|
|
444
|
-
}`,e0=`-- Primary workflow: use Compose Query in the Semantic Layer panel
|
|
445
|
-
-- 1. Pick metrics + dimensions (+ optional time dimension)
|
|
446
|
-
-- 2. Click "Compose SQL"
|
|
447
|
-
-- 3. Click "+ Insert as Cell" → edit and run
|
|
448
|
-
|
|
449
|
-
-- Advanced: reference metrics inline in any SQL cell
|
|
450
|
-
-- DQL resolves @metric() and @dim() at query time
|
|
451
|
-
SELECT
|
|
452
|
-
@dim(segment_tier),
|
|
453
|
-
@metric(total_revenue)
|
|
454
|
-
FROM fct_revenue
|
|
455
|
-
GROUP BY @dim(segment_tier)
|
|
456
|
-
ORDER BY @metric(total_revenue) DESC`,t0=`{
|
|
457
|
-
"semanticLayer": {
|
|
458
|
-
"provider": "snowflake",
|
|
459
|
-
"projectPath": "MY_DATABASE"
|
|
460
|
-
}
|
|
461
|
-
}`;function GR({themeMode:e}){const t=ie[e];return s.jsxs(Ht,{title:"Reference",subtitle:"Quick syntax, operators, and cell reference.",bodyPadding:0,children:[s.jsx(wt,{title:"SQL Essentials",defaultOpen:!0,t,children:s.jsx(Ue,{t,code:`-- Basic select
|
|
462
|
-
SELECT col1, col2
|
|
463
|
-
FROM table_name
|
|
464
|
-
WHERE condition
|
|
465
|
-
ORDER BY col1 DESC
|
|
466
|
-
LIMIT 100
|
|
467
|
-
|
|
468
|
-
-- GROUP BY
|
|
469
|
-
SELECT col, COUNT(*), SUM(val)
|
|
470
|
-
FROM table_name
|
|
471
|
-
GROUP BY col
|
|
472
|
-
|
|
473
|
-
-- JOIN
|
|
474
|
-
SELECT a.*, b.col
|
|
475
|
-
FROM table_a AS a
|
|
476
|
-
JOIN table_b AS b ON a.id = b.id
|
|
477
|
-
|
|
478
|
-
-- CTE (WITH)
|
|
479
|
-
WITH cte AS (
|
|
480
|
-
SELECT * FROM table_name WHERE val > 0
|
|
481
|
-
)
|
|
482
|
-
SELECT * FROM cte
|
|
483
|
-
|
|
484
|
-
-- Window function
|
|
485
|
-
SELECT *,
|
|
486
|
-
ROW_NUMBER() OVER (
|
|
487
|
-
PARTITION BY group_col
|
|
488
|
-
ORDER BY val DESC
|
|
489
|
-
) AS rank
|
|
490
|
-
FROM table_name`})}),s.jsx(wt,{title:"DuckDB Functions",defaultOpen:!1,t,children:s.jsx(au,{t,rows:[["read_csv_auto(path)","Auto-detect CSV schema and load"],["read_parquet(path)","Load a Parquet file"],["strftime(date, fmt)","Format date as string (e.g. '%Y-%m')"],["date_trunc(part, date)","Truncate date to part ('month', 'year'…)"],["CURRENT_DATE","Today's date"],["epoch_ms(ts)","Convert epoch milliseconds to timestamp"],["array_agg(col)","Aggregate column values into an array"],["string_agg(col, sep)","Concatenate values with separator"]]})}),s.jsxs(wt,{title:"DQL Block Structure",defaultOpen:!0,t,children:[s.jsx(Ue,{t,code:H_}),s.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.6},children:["Run ",s.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql certify <file> --connection duckdb"})," to execute ",s.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"tests {}"})," assertions against live data. Use ",s.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"--skip-tests"})," to check governance fields only."]})]}),s.jsxs(wt,{title:"DQL Chart Types",defaultOpen:!1,t,children:[s.jsx(au,{t,rows:[["table","Tabular data grid (default)"],["bar","Bar chart — use x and y fields"],["line","Line chart — use x (date) and y (value)"],["pie","Pie/donut chart — use x (label) and y (value)"],["kpi","Single big-number KPI card (dql preview)"]]}),s.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.6},children:["Set chart type inside the"," ",s.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:'visualization { chart = "pie"; x = label_col; y = value_col }'})," ","block."]})]}),s.jsxs(wt,{title:"Semantic Layer Usage",defaultOpen:!1,t,children:[s.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:6},children:["Primary workflow: open the ",s.jsx("strong",{children:"Semantic Layer"})," panel → Compose Query → pick metrics and dimensions → Compose SQL → + Insert as Cell. Advanced: use ",s.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"@metric(name)"})," and ",s.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"@dim(name)"})," refs directly in any SQL cell."]}),s.jsx(Ue,{t,code:e0})]}),s.jsxs(wt,{title:"Semantic Layer",defaultOpen:!1,t,children:[s.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Define reusable metrics, dimensions, and hierarchies in YAML. They appear in the"," ",s.jsx("strong",{style:{color:t.textPrimary},children:"Semantic Layer"})," sidebar panel."]}),s.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"10px 0 4px",letterSpacing:"0.03em"},children:"Directory Structure"}),s.jsx(Ue,{t,code:`my-project/
|
|
491
|
-
├── dql.config.json
|
|
492
|
-
└── semantic-layer/
|
|
493
|
-
├── metrics/ ← one YAML per metric
|
|
494
|
-
├── dimensions/ ← one YAML per dimension
|
|
495
|
-
├── hierarchies/ ← optional drill paths
|
|
496
|
-
└── cubes/ ← optional (groups all into one)`}),s.jsxs("div",{style:{marginTop:8,padding:"6px 8px",background:`${t.accent}10`,border:`1px solid ${t.accent}30`,borderRadius:4,fontSize:11,color:t.textSecondary,fontFamily:t.font,lineHeight:1.6},children:[s.jsx("strong",{style:{color:t.textPrimary},children:"Recommended:"})," For multi-table projects, use a ",s.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"cubes/"})," file — it keeps metrics, dimensions, and joins together. Use standalone ",s.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"metrics/"})," and ",s.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dimensions/"})," files only for simple single-table projects."]}),s.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Metric YAML"}),s.jsx(Ue,{t,code:Y_}),s.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Dimension YAML"}),s.jsx(Ue,{t,code:W_}),s.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Hierarchy YAML"}),s.jsx(Ue,{t,code:$_}),s.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Cube YAML (advanced — multi-table with joins)"}),s.jsx(Ue,{t,code:V_})]}),s.jsxs(wt,{title:"Semantic Layer Providers",defaultOpen:!1,t,children:[s.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Add to your ",s.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"})," to connect a semantic layer provider."]}),s.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"10px 0 4px",letterSpacing:"0.03em"},children:"DQL Native (YAML files in semantic-layer/)"}),s.jsx(Ue,{t,code:X_}),s.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"dbt (reads models/**/*.yml)"}),s.jsx(Ue,{t,code:z_}),s.jsxs("div",{style:{marginTop:4,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Point to your dbt project root (directory with ",s.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dbt_project.yml"}),"). Reads ",s.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"semantic_models"})," and"," ",s.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"metrics"})," blocks (dbt 1.6+)."]}),s.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Cube.js (reads model/ or schema/)"}),s.jsx(Ue,{t,code:K_}),s.jsxs("div",{style:{marginTop:4,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Point to your Cube.js project root. Reads"," ",s.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"cubes:"})," blocks from YAML schema files."]}),s.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Snowflake Semantic Views (requires live connection)"}),s.jsx(Ue,{t,code:t0}),s.jsxs("div",{style:{marginTop:4,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Introspects Snowflake semantic views via"," ",s.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"SHOW SEMANTIC VIEWS"}),". Set ",s.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"projectPath"})," to your database name to scope discovery. Requires a Snowflake connection in ",s.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"defaultConnection"}),"."]})]}),s.jsxs(wt,{title:"Connection Setup",defaultOpen:!1,t,children:[s.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Configure ",s.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"defaultConnection"})," in"," ",s.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"}),"."]}),s.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"10px 0 4px",letterSpacing:"0.03em"},children:"DuckDB (in-memory — default)"}),s.jsx(Ue,{t,code:q_}),s.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Snowflake"}),s.jsx(Ue,{t,code:J_}),s.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"BigQuery"}),s.jsx(Ue,{t,code:Q_}),s.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"PostgreSQL"}),s.jsx(Ue,{t,code:Z_}),s.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Use ",s.jsxs("code",{style:{fontFamily:t.fontMono,fontSize:10},children:["$","${ENV_VAR}"]})," syntax for secrets. Run ",s.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dql doctor"})," to verify your connection."]})]}),s.jsxs(wt,{title:"Variable References",defaultOpen:!1,t,children:[s.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Use"," ",s.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"{{cell_name}}"})," ","to reference other cells:",s.jsxs("ul",{style:{margin:"6px 0 0",paddingLeft:18},children:[s.jsxs("li",{children:[s.jsx("strong",{children:"Param cell"})," → substituted as a SQL literal value"]}),s.jsxs("li",{children:[s.jsx("strong",{children:"SQL cell"})," → injected as a CTE"]})]})]}),s.jsx(Ue,{t,code:`-- Param cell named "start_date" holds '2024-01-01'
|
|
497
|
-
SELECT *
|
|
498
|
-
FROM read_csv_auto('data/sales.csv')
|
|
499
|
-
WHERE date >= {{start_date}}
|
|
500
|
-
|
|
501
|
-
-- SQL cell named "base_query" used as CTE
|
|
502
|
-
SELECT segment, SUM(revenue) AS total
|
|
503
|
-
FROM {{base_query}}
|
|
504
|
-
GROUP BY segment`})]})]})}const we={source_table:"#8b949e",dbt_model:"#ff7b72",dbt_source:"#79c0ff",block:"#56d364",metric:"#388bfd",dimension:"#e3b341",domain:"#d2a8ff",chart:"#f778ba",notebook:"#bc8cff",dashboard:"#a371f7",app:"#db6d28"},aa={source_table:"TBL",dbt_model:"DBT",dbt_source:"SRC",block:"BLK",metric:"MET",dimension:"DIM",domain:"DOM",chart:"CHT",notebook:"NB",dashboard:"DASH",app:"APP"},la={source_table:"Source Table",dbt_model:"dbt Model",dbt_source:"dbt Source",block:"DQL Block",metric:"Metric",dimension:"Dimension",domain:"Domain",chart:"Chart",notebook:"Notebook",dashboard:"Dashboard",app:"App"},co={reads_from:"#8b949e",feeds_into:"#56d364",aggregates:"#388bfd",visualizes:"#f778ba",depends_on:"#ff7b72",contains:"#d2a8ff",crosses_domain:"#d2a8ff"},n0={reads_from:"reads from",feeds_into:"feeds into",aggregates:"aggregates into",visualizes:"visualizes",depends_on:"dbt depends on",contains:"contains",crosses_domain:"crosses domain"},r0={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},lu={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"},hi=["source","transform","answer","consumption"];function vd(e){if(e.layer)return e.layer;switch(e.type){case"source_table":case"dbt_source":return"source";case"dbt_model":return"transform";case"block":case"metric":case"dimension":case"domain":return"answer";case"chart":case"notebook":case"dashboard":case"app":return"consumption";default:return"answer"}}function o0({type:e}){const t=we[e]??"#8b949e";return s.jsx("span",{style:{color:t,fontSize:10,fontWeight:700,textTransform:"uppercase",minWidth:34},title:la[e]??e,children:aa[e]??e.slice(0,4).toUpperCase()})}function s0({value:e,onChange:t,placeholder:n,t:r}){return s.jsx("input",{value:e,onChange:o=>t(o.target.value),placeholder:n,style:{width:"100%",padding:"8px 10px",borderRadius:6,border:`1px solid ${r.headerBorder}`,background:r.sidebarBg,color:r.textPrimary,fontSize:12,outline:"none"}})}function HR({node:e,t,onClick:n,secondary:r}){return s.jsxs("button",{onClick:n,style:{width:"100%",textAlign:"left",background:"transparent",border:"none",borderRadius:6,padding:"6px 8px",cursor:"pointer",color:t.textPrimary},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx(o0,{type:e.type}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},title:e.name,children:e.name})]}),(r||e.domain)&&s.jsx("div",{style:{marginLeft:40,marginTop:2,color:t.textMuted,fontSize:11},children:r??e.domain})]})}const i0=30,ll=200;function Ln({title:e,nodes:t,t:n,onSelect:r}){const o=t.length>i0,[i,a]=f.useState(!o),[l,c]=f.useState(ll);if(t.length===0)return null;const d=i?Math.min(l,t.length):0,E=Math.max(0,t.length-d);return s.jsxs("div",{style:{padding:"8px 0",borderTop:`1px solid ${n.headerBorder}`},children:[s.jsxs("button",{onClick:()=>a(u=>!u),"aria-expanded":i,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"0 8px 6px",color:n.textMuted,fontSize:11,fontWeight:700,textTransform:"uppercase",background:"transparent",border:"none",cursor:"pointer",textAlign:"left"},children:[s.jsx("span",{style:{display:"inline-block",width:10},children:i?"▾":"▸"}),s.jsx("span",{children:e}),s.jsx("span",{style:{marginLeft:"auto",fontWeight:500},children:t.length})]}),i&&t.slice(0,d).map(u=>s.jsx(HR,{node:u,t:n,onClick:()=>r(u)},u.id)),i&&E>0&&s.jsxs("button",{onClick:()=>c(u=>u+ll),style:{width:"100%",margin:"4px 0 0",padding:"6px 8px",background:"transparent",border:"none",color:n.textMuted,fontSize:11,cursor:"pointer",textAlign:"left"},children:["Show ",Math.min(ll,E)," more (",E," hidden)"]})]})}function a0(){const{state:e,dispatch:t}=fe(),n=ie[e.themeMode],[r,o]=f.useState(!0),[i,a]=f.useState([]),[,l]=f.useState([]),[c,d]=f.useState(""),[E,u]=f.useState([]),T=f.useCallback(async()=>{o(!0);const I=await z.fetchLineage();a(I.nodes??[]),l(I.edges??[]),o(!1)},[]);f.useEffect(()=>{T()},[T]),f.useEffect(()=>{let I=!1;if(c.trim().length<2){u([]);return}return z.searchLineage(c.trim()).then(O=>{I||u(O.matches??[])}),()=>{I=!0}},[c]);const p=f.useCallback(I=>{t({type:"SET_LINEAGE_FOCUS",nodeId:I.id}),t({type:"OPEN_LINEAGE_DRAWER",nodeId:I.id})},[t]),[h,A]=f.useState("type"),S=f.useMemo(()=>({dashboards:i.filter(I=>I.type==="dashboard"),blocks:i.filter(I=>I.type==="block"),dbtModels:i.filter(I=>I.type==="dbt_model"),dbtSources:i.filter(I=>I.type==="dbt_source"),tables:i.filter(I=>I.type==="source_table"),domains:i.filter(I=>I.type==="domain")}),[i]),R=f.useMemo(()=>{const I={source:[],transform:[],answer:[],consumption:[]};for(const O of i){const N=vd(O);I[N].push(O)}return I},[i]);if(r)return s.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"Loading lineage..."});if(i.length===0)return s.jsx(Ht,{title:"Lineage",bodyPadding:0,children:s.jsx(kt,{title:"No lineage data",description:"Run `dql compile` or add notebooks/blocks first."})});const m=s.jsx(Go,{children:s.jsx(s0,{value:c,onChange:d,placeholder:"Search blocks, tables, dbt models, notebooks...",t:n})});return s.jsxs(Ht,{title:"Lineage",toolbar:m,bodyPadding:0,children:[s.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[s.jsx("button",{onClick:()=>t({type:"TOGGLE_LINEAGE_FULLSCREEN"}),style:{width:"100%",padding:"8px 10px",borderRadius:6,border:`1px solid ${e.lineageFullscreen?"#388bfd":n.headerBorder}`,background:e.lineageFullscreen?"#388bfd":"transparent",color:e.lineageFullscreen?"#fff":n.textPrimary,fontSize:12,fontWeight:600,cursor:"pointer"},children:e.lineageFullscreen?"Close Graph View":"Open Graph View"}),s.jsx("div",{style:{marginTop:8,color:n.textMuted,fontSize:11,lineHeight:1.5},children:"Search across source tables, dbt sources/models, DQL blocks, metrics, and notebooks. Selecting any item opens a focused lineage path instead of the full graph."})]}),s.jsxs("div",{style:{flex:1,overflow:"auto"},children:[c.trim().length>=2&&E.length>0&&s.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[s.jsx("div",{style:{color:n.textMuted,fontSize:11,fontWeight:700,textTransform:"uppercase",marginBottom:6},children:"Search Results"}),E.slice(0,8).map(I=>s.jsx(HR,{node:I.node,t:n,onClick:()=>p(I.node),secondary:I.node.domain},I.node.id))]}),s.jsxs("div",{style:{padding:"6px 8px",display:"flex",gap:8,flexWrap:"wrap",borderBottom:`1px solid ${n.headerBorder}`},children:[hi.map(I=>{const O=R[I].length;return O===0?null:s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:10,color:n.textMuted},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:2,background:r0[I],display:"inline-block"}}),lu[I],": ",O]},I)}),s.jsx("span",{style:{flex:1}}),s.jsxs("div",{style:{display:"flex",borderRadius:4,border:`1px solid ${n.headerBorder}`,overflow:"hidden"},children:[s.jsx("button",{onClick:()=>A("type"),style:{padding:"2px 6px",fontSize:9,fontWeight:700,border:"none",cursor:"pointer",background:h==="type"?`${n.headerBorder}`:"transparent",color:h==="type"?n.textPrimary:n.textMuted},children:"Type"}),s.jsx("button",{onClick:()=>A("layer"),style:{padding:"2px 6px",fontSize:9,fontWeight:700,border:"none",cursor:"pointer",borderLeft:`1px solid ${n.headerBorder}`,background:h==="layer"?`${n.headerBorder}`:"transparent",color:h==="layer"?n.textPrimary:n.textMuted},children:"Layer"})]})]}),h==="type"?s.jsxs(s.Fragment,{children:[s.jsx(Ln,{title:"Notebooks",nodes:S.dashboards,t:n,onSelect:p}),s.jsx(Ln,{title:"DQL Blocks",nodes:S.blocks,t:n,onSelect:p}),s.jsx(Ln,{title:"dbt Models",nodes:S.dbtModels,t:n,onSelect:p}),s.jsx(Ln,{title:"dbt Sources",nodes:S.dbtSources,t:n,onSelect:p}),s.jsx(Ln,{title:"Source Tables",nodes:S.tables,t:n,onSelect:p}),s.jsx(Ln,{title:"Business Domains",nodes:S.domains,t:n,onSelect:p})]}):s.jsx(s.Fragment,{children:hi.map(I=>s.jsx(Ln,{title:lu[I],nodes:R[I],t:n,onSelect:p},I))})]})]})}const l0={certified:"success",published:"success",deprecated:"error",draft:"warning",pending:"warning",review:"accent"};function c0(){const{state:e,dispatch:t}=fe(),n=ie[e.themeMode],[r,o]=f.useState([]),[i,a]=f.useState(!0),[l,c]=f.useState(""),[d,E]=f.useState(""),[u,T]=f.useState("");f.useEffect(()=>{a(!0),z.getBlockLibrary().then(g=>o(g.blocks)).finally(()=>a(!1))},[]);const p=[...new Set(r.map(g=>g.domain))].sort(),h=[...new Set(r.map(g=>g.status))].sort(),A=r.filter(g=>!(l&&!g.name.toLowerCase().includes(l.toLowerCase())&&!g.description.toLowerCase().includes(l.toLowerCase())||d&&g.domain!==d||u&&g.status!==u)),S=g=>{const C={name:g.path.split("/").pop()??g.name,path:g.path,type:"block",folder:"blocks"};e.files.some(y=>y.path===g.path)||t({type:"FILE_ADDED",file:C}),z.openBlockStudio(g.path).then(y=>{t({type:"OPEN_BLOCK_STUDIO",file:C,payload:y})})},R=()=>{a(!0),z.getBlockLibrary().then(g=>o(g.blocks)).finally(()=>a(!1))},m={background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:6,color:n.textPrimary,fontSize:11,fontFamily:n.font,padding:"6px 10px",outline:"none"},I=`data:image/svg+xml;utf8,${encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 10 10'><path fill='none' stroke='${n.textMuted}' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round' d='M2 4l3 3 3-3'/></svg>`)}`,O={...m,appearance:"none",WebkitAppearance:"none",MozAppearance:"none",backgroundImage:`url("${I}")`,backgroundRepeat:"no-repeat",backgroundPosition:"right 8px center",paddingRight:24,cursor:"pointer"},N=s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>t({type:"OPEN_NEW_BLOCK_MODAL"}),style:{background:n.accent,border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:10,fontWeight:600,fontFamily:n.font,padding:"3px 10px"},children:"+ New"}),s.jsx("button",{onClick:R,style:{background:"transparent",border:`1px solid ${n.cellBorder}`,borderRadius:4,color:n.textSecondary,cursor:"pointer",fontSize:10,fontFamily:n.font,padding:"3px 8px"},children:"Refresh"})]}),x=s.jsxs(Go,{children:[s.jsx("input",{value:l,onChange:g=>c(g.target.value),placeholder:"Search blocks...",style:{...m,flex:1,minWidth:100}}),s.jsxs("select",{value:d,onChange:g=>E(g.target.value),style:O,children:[s.jsx("option",{value:"",children:"All domains"}),p.map(g=>s.jsx("option",{value:g,children:g},g))]}),s.jsxs("select",{value:u,onChange:g=>T(g.target.value),style:O,children:[s.jsx("option",{value:"",children:"All statuses"}),h.map(g=>s.jsx("option",{value:g,children:g},g))]})]});return s.jsx(Ht,{title:"Blocks",status:s.jsx("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:A.length}),actions:N,toolbar:x,bodyPadding:0,children:i?s.jsx(kt,{title:"Loading blocks…"}):A.length===0?s.jsx(kt,{title:r.length===0?"No blocks yet":"No matches",description:r.length===0?"Create your first block to get started.":"No blocks match your filters."}):A.map(g=>s.jsxs("button",{onClick:()=>S(g),style:{display:"block",width:"100%",textAlign:"left",background:"transparent",border:"none",borderBottom:`1px solid ${n.cellBorder}`,cursor:"pointer",padding:"10px 12px",transition:"background 0.1s"},onMouseEnter:C=>{C.currentTarget.style.background=`${n.accent}0a`},onMouseLeave:C=>{C.currentTarget.style.background="transparent"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[s.jsx("span",{style:{fontSize:12,fontWeight:600,color:n.textPrimary,fontFamily:n.font},children:g.name}),s.jsx(Dd,{tone:l0[g.status]??"neutral",children:g.status})]}),g.description&&s.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font,lineHeight:1.3,marginBottom:4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.description}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:n.textMuted,fontFamily:n.font},children:[s.jsx("span",{style:{background:n.pillBg,padding:"1px 6px",borderRadius:4},children:g.domain}),g.owner&&s.jsxs("span",{children:["by ",g.owner]}),g.llmContext&&s.jsx("span",{title:g.llmContext,style:{color:n.accent,fontWeight:600,letterSpacing:"0.04em"},children:"AI"}),s.jsx("span",{style:{marginLeft:"auto"},children:new Date(g.lastModified).toLocaleDateString()})]})]},g.path))})}function d0({diff:e,diffReport:t,activeFilePath:n,diffPath:r,onScopeToFile:o,onClearScope:i,t:a}){const l=t!==null&&!t.identical,c=e.trim()!=="";return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{display:"flex",gap:6,fontSize:11},children:[s.jsx("button",{onClick:i,style:du(r==null,a),children:"All"}),n&&s.jsx("button",{onClick:o,style:du(r===n,a),children:"Active file"}),r&&s.jsx("span",{style:{color:a.textMuted,fontSize:10,alignSelf:"center",fontFamily:a.fontMono},children:r})]}),l&&s.jsx(E0,{report:t,t:a}),!l&&c&&s.jsx(f0,{diff:e,t:a}),!l&&!c&&s.jsx("div",{style:{color:a.textMuted},children:t&&t.identical?"No semantic changes.":"No unstaged changes."})]})}function E0({report:e,t}){return s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.changes.map((n,r)=>s.jsx(u0,{change:n,t},r))})}function u0({change:e,t}){const{marker:n,color:r,label:o}=p0(e),i="fields"in e?e.fields:null;return s.jsxs("div",{style:{border:`1px solid ${t.editorBorder}`,borderRadius:6,padding:"6px 10px",background:t.editorBg},children:[s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"baseline"},children:[s.jsx("span",{style:{color:r,fontFamily:t.fontMono,fontWeight:700,width:14},children:n}),s.jsx("span",{style:{color:t.textPrimary,fontSize:12,fontFamily:t.fontMono},children:o})]}),i&&i.length>0&&s.jsx("div",{style:{marginTop:4,display:"flex",flexDirection:"column",gap:2},children:i.map((a,l)=>s.jsx(T0,{field:a,t},l))})]})}function T0({field:e,t}){return s.jsxs("div",{style:{fontSize:11,fontFamily:t.fontMono,color:t.textPrimary,paddingLeft:22},children:[s.jsx("span",{style:{color:t.accent},children:e.path}),s.jsx("span",{style:{color:t.textMuted},children:": "}),s.jsx("span",{style:{color:t.error,textDecoration:"line-through"},children:cu(e.before)}),s.jsx("span",{style:{color:t.textMuted},children:" → "}),s.jsx("span",{style:{color:t.success},children:cu(e.after)})]})}function f0({diff:e,t}){return s.jsx("pre",{style:{fontFamily:t.fontMono,fontSize:11,margin:0,padding:8,background:t.editorBg,border:`1px solid ${t.editorBorder}`,borderRadius:6,overflow:"auto",whiteSpace:"pre",color:t.textPrimary},children:e.split(`
|
|
505
|
-
`).map((n,r)=>s.jsx("div",{style:{color:S0(n,t)},children:n||" "},r))})}function p0(e){const t={marker:"+",color:"#3cb371"},n={marker:"-",color:"#e06060"},r={marker:"~",color:"#d4a24c"};switch(e.kind){case"block-added":return{...t,label:`block "${e.name}"`};case"block-removed":return{...n,label:`block "${e.name}"`};case"block-changed":return{...r,label:`block "${e.name}"`};case"dashboard-added":return{...t,label:`dashboard "${e.title}"`};case"dashboard-removed":return{...n,label:`dashboard "${e.title}"`};case"dashboard-changed":return{...r,label:`dashboard "${e.title}"`};case"workbook-added":return{...t,label:`workbook "${e.title}"`};case"workbook-removed":return{...n,label:`workbook "${e.title}"`};case"workbook-changed":return{...r,label:`workbook "${e.title}"`};case"cell-added":return{...t,label:`cell ${cl(e.id,e.name)} [${e.cellType}]`};case"cell-removed":return{...n,label:`cell ${cl(e.id,e.name)} [${e.cellType}]`};case"cell-changed":return{...r,label:`cell ${cl(e.id,e.name)}`};case"notebook-changed":return{...r,label:"notebook"}}}function cl(e,t){return t?`"${t}" (${e.slice(0,8)})`:e.slice(0,8)}function cu(e,t=60){if(e==null)return"∅";const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}…`:n}function du(e,t){return{background:e?t.btnHover:"transparent",color:e?t.textPrimary:t.textMuted,border:`1px solid ${t.headerBorder}`,padding:"2px 8px",borderRadius:4,fontSize:11,cursor:"pointer"}}function S0(e,t){return e.startsWith("+++")||e.startsWith("---")?t.textMuted:e.startsWith("+")?t.success:e.startsWith("-")?t.error:e.startsWith("@@")?t.accent:t.textPrimary}const R0=2e3,h0={modified:{label:"Modified",color:e=>e.warning,Icon:iL},added:{label:"Added",color:e=>e.success,Icon:LR},deleted:{label:"Deleted",color:e=>e.error,Icon:uL},renamed:{label:"Renamed",color:e=>e.accent,Icon:vC},untracked:{label:"Untracked",color:e=>e.textMuted,Icon:cL}},Eu=["modified","added","renamed","deleted","untracked"];function A0(e){const t=e.trim();return t==="??"?"untracked":t.startsWith("R")?"renamed":t.includes("D")?"deleted":t.includes("A")?"added":"modified"}function I0(){var x;const{state:e}=fe(),t=ie[e.themeMode],[n,r]=f.useState("status"),[o,i]=f.useState(null),[a,l]=f.useState(null),[c,d]=f.useState(""),[E,u]=f.useState(null),[T,p]=f.useState(null),[h,A]=f.useState(!1),[S,R]=f.useState(!1),m=f.useCallback(async()=>{A(!0),R(!0);try{if(n==="status")i(await z.fetchGitStatus());else if(n==="log")l(await z.fetchGitLog(30));else{const g=await z.fetchGitDiff(T??void 0);d(g.diff),u(g.diffReport)}}finally{A(!1),window.setTimeout(()=>R(!1),400)}},[n,T]);f.useEffect(()=>{m()},[m]),f.useEffect(()=>{if(n!=="status")return;const g=window.setInterval(()=>{z.fetchGitStatus().then(C=>{i(y=>m0(y,C)?y:C)})},R0);return()=>window.clearInterval(g)},[n]);const I=((x=e.activeFile)==null?void 0:x.path)??null,O=s.jsxs("button",{onClick:()=>void m(),title:"Refresh","aria-label":"Refresh",style:{background:"transparent",border:`1px solid ${t.btnBorder}`,cursor:"pointer",color:t.textMuted,padding:"3px 6px",borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center"},children:[s.jsx(vR,{size:12,strokeWidth:1.75,style:{animation:S?"dql-spin 0.6s linear":void 0}}),s.jsx("style",{children:"@keyframes dql-spin { to { transform: rotate(360deg); } }"})]}),N=s.jsxs(Go,{children:[s.jsx(dl,{t,active:n==="status",onClick:()=>r("status"),children:"Status"}),s.jsx(dl,{t,active:n==="log",onClick:()=>r("log"),children:"History"}),s.jsx(dl,{t,active:n==="diff",onClick:()=>r("diff"),children:"Diff"})]});return s.jsxs(Ht,{title:"Git",actions:O,toolbar:N,bodyPadding:12,children:[h&&!o&&!a&&s.jsx(kt,{title:"Loading…"}),n==="status"&&o&&s.jsx(O0,{status:o,t}),n==="log"&&a&&s.jsx(C0,{log:a,t}),n==="diff"&&s.jsx(d0,{diff:c,diffReport:E,activeFilePath:I,diffPath:T,onScopeToFile:()=>p(I),onClearScope:()=>p(null),t})]})}function m0(e,t){if(!e||e.inRepo!==t.inRepo||e.branch!==t.branch||e.ahead!==t.ahead||e.behind!==t.behind||e.changes.length!==t.changes.length)return!1;const n=e.changes.map(o=>`${o.path}\0${o.status}`).sort(),r=t.changes.map(o=>`${o.path}\0${o.status}`).sort();for(let o=0;o<n.length;o++)if(n[o]!==r[o])return!1;return!0}function O0({status:e,t}){const n=f.useMemo(()=>{const r={modified:[],added:[],deleted:[],renamed:[],untracked:[]};for(const o of e.changes)r[A0(o.status)].push(o);for(const o of Eu)r[o].sort((i,a)=>i.path.localeCompare(a.path));return r},[e.changes]);return e.inRepo?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[s.jsx(N0,{status:e,t}),e.changes.length===0?s.jsx(g0,{t}):Eu.map(r=>{const o=n[r];return o.length===0?null:s.jsx(x0,{group:r,items:o,t},r)})]}):s.jsx(YR,{t})}function N0({status:e,t}){const n=e.ahead??0,r=e.behind??0;return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 12px",background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderLeft:`3px solid ${t.accent}`,borderRadius:7},children:[s.jsx(Gr,{size:16,strokeWidth:1.75,color:t.accent}),s.jsx("span",{style:{fontSize:13,fontWeight:600,color:t.textPrimary,fontFamily:t.fontMono},children:e.branch??"detached"}),s.jsx("div",{style:{flex:1}}),n>0&&s.jsxs("span",{title:`${n} commit(s) ahead of upstream`,style:El(t.success,t),children:[s.jsx(xR,{size:11,strokeWidth:2})," ",n]}),r>0&&s.jsxs("span",{title:`${r} commit(s) behind upstream`,style:El(t.warning,t),children:[s.jsx(gR,{size:11,strokeWidth:2})," ",r]}),n===0&&r===0&&s.jsx("span",{style:{...El(t.textMuted,t),opacity:.7},children:"up to date"})]})}function g0({t:e}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"14px 12px",background:e.cellBg,border:`1px solid ${e.cellBorder}`,borderRadius:7,color:e.textMuted,fontSize:12,fontFamily:e.font},children:[s.jsx(oL,{size:14,strokeWidth:1.75,color:e.success}),"Working tree clean"]})}function YR({t:e}){return s.jsx("div",{style:{padding:"14px 12px",background:e.cellBg,border:`1px solid ${e.cellBorder}`,borderRadius:7,color:e.textMuted,fontSize:12,fontFamily:e.font},children:"Not a git repository"})}function x0({group:e,items:t,t:n}){const r=h0[e],o=r.color(n),i=r.Icon;return s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,fontSize:10,fontWeight:600,letterSpacing:"0.07em",textTransform:"uppercase",color:n.textMuted,fontFamily:n.font},children:[s.jsx(i,{size:11,strokeWidth:1.75}),s.jsx("span",{children:r.label}),s.jsx("span",{style:{marginLeft:2,padding:"0 5px",borderRadius:8,background:`${o}1a`,color:o,fontWeight:700,fontSize:9,letterSpacing:"0.04em"},children:t.length})]}),s.jsx("div",{style:{display:"flex",flexDirection:"column",background:n.cellBg,border:`1px solid ${n.cellBorder}`,borderRadius:7,overflow:"hidden"},children:t.map((a,l)=>s.jsx(y0,{change:a,t:n,color:o,divider:l<t.length-1},a.path))})]})}function y0({change:e,t,color:n,divider:r}){const o=e.status.trim()||"??";return s.jsxs("div",{title:e.path,style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:r?`1px solid ${t.cellBorder}`:"none",fontFamily:t.fontMono,fontSize:11},children:[s.jsx("span",{style:{width:22,textAlign:"center",flexShrink:0,color:n,fontWeight:700,fontSize:10,letterSpacing:"0.02em"},children:o}),s.jsx("span",{style:{color:t.textPrimary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:e.path})]})}function C0({log:e,t}){return e.inRepo?e.commits.length===0?s.jsx("div",{style:{padding:"14px 12px",background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:7,color:t.textMuted,fontSize:12,fontFamily:t.font},children:"No commits yet"}):s.jsx("div",{style:{display:"flex",flexDirection:"column",background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:7,overflow:"hidden"},children:e.commits.map((n,r)=>s.jsxs("div",{style:{display:"flex",gap:10,padding:"8px 12px",borderBottom:r<e.commits.length-1?`1px solid ${t.cellBorder}`:"none"},children:[s.jsx(bR,{size:13,strokeWidth:1.75,color:t.accent,style:{flexShrink:0,marginTop:2}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{color:t.textPrimary,fontSize:12,fontFamily:t.font,fontWeight:500,lineHeight:1.35,wordBreak:"break-word"},children:n.subject}),s.jsxs("div",{style:{color:t.textMuted,fontSize:10,marginTop:3,display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[s.jsx("span",{style:{fontFamily:t.fontMono,color:t.accent},children:n.hash.slice(0,7)}),s.jsx("span",{children:"·"}),s.jsx("span",{style:{fontFamily:t.font},children:n.author}),s.jsx("span",{children:"·"}),s.jsx("span",{style:{fontFamily:t.fontMono},children:n.date})]})]})]},n.hash))}):s.jsx(YR,{t})}function dl({active:e,onClick:t,children:n,t:r}){return s.jsx("button",{onClick:t,style:{background:e?r.btnHover:"transparent",color:e?r.textPrimary:r.textMuted,border:"none",padding:"4px 12px",borderRadius:4,fontSize:11,fontWeight:600,letterSpacing:"0.02em",cursor:"pointer",fontFamily:r.font,transition:"background 0.15s, color 0.15s"},children:n})}function El(e,t){return{display:"inline-flex",alignItems:"center",gap:3,padding:"1px 7px",fontSize:10,fontWeight:600,letterSpacing:"0.02em",borderRadius:10,background:`${e}1a`,color:e,fontFamily:t.font}}function L0(e){const{state:t,dispatch:n}=fe(),r=ie[t.themeMode],[o,i]=f.useState([]),[a,l]=f.useState(!0),[c,d]=f.useState(""),[E,u]=f.useState(""),[T,p]=f.useState(new Set),h=()=>{l(!0),z.listApps().then(x=>i(x)).finally(()=>l(!1))};f.useEffect(()=>{h()},[]);const A=[...new Set(o.map(x=>x.domain))].sort(),S=o.filter(x=>{const g=c.toLowerCase();return!(g&&!x.name.toLowerCase().includes(g)&&!(x.description??"").toLowerCase().includes(g)||E&&x.domain!==E)}),R=x=>{p(g=>{const C=new Set(g);return C.has(x)?C.delete(x):C.add(x),C})},m=(x,g)=>{n({type:"OPEN_APP",appId:x.id,dashboardId:g})},I={background:r.inputBg,border:`1px solid ${r.inputBorder}`,borderRadius:4,color:r.textPrimary,fontSize:11,fontFamily:r.font,padding:"4px 6px",outline:"none"},O=s.jsx("button",{onClick:h,style:{background:"transparent",border:`1px solid ${r.cellBorder}`,borderRadius:4,color:r.textSecondary,cursor:"pointer",fontSize:10,fontFamily:r.font,padding:"3px 8px"},children:"Refresh"}),N=s.jsxs(Go,{children:[s.jsx("input",{value:c,onChange:x=>d(x.target.value),placeholder:"Search apps...",style:{...I,flex:1,minWidth:100}}),s.jsxs("select",{value:E,onChange:x=>u(x.target.value),style:I,children:[s.jsx("option",{value:"",children:"All domains"}),A.map(x=>s.jsx("option",{value:x,children:x},x))]})]});return s.jsx(Ht,{title:"Apps",status:s.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:S.length}),actions:O,toolbar:N,bodyPadding:0,children:a?s.jsx(kt,{title:"Loading apps…"}):S.length===0?o.length===0?s.jsx(kt,{title:"No apps yet",description:s.jsxs(s.Fragment,{children:["Create one from the CLI:",s.jsx("br",{}),s.jsx("code",{style:{display:"inline-block",marginTop:6,padding:"2px 6px",background:r.inputBg,borderRadius:3,fontSize:10},children:"dql app new <name> --domain <domain>"})]})}):s.jsx(kt,{title:"No matches",description:"No apps match your filters."}):S.map(x=>{const g=T.has(x.id);return s.jsxs("div",{style:{borderBottom:`1px solid ${r.cellBorder}`},children:[s.jsxs("button",{onClick:()=>R(x.id),style:{display:"block",width:"100%",textAlign:"left",background:"transparent",border:"none",cursor:"pointer",padding:"10px 12px",transition:"background 0.1s"},onMouseEnter:C=>{C.currentTarget.style.background=`${r.accent}0a`},onMouseLeave:C=>{C.currentTarget.style.background="transparent"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[s.jsx("span",{style:{fontSize:10,color:r.textMuted,fontFamily:r.font,width:10},children:g?"▾":"▸"}),s.jsx("span",{style:{fontSize:12,fontWeight:600,color:r.textPrimary,fontFamily:r.font},children:x.name}),s.jsx(Dd,{tone:"accent",children:x.domain})]}),x.description&&s.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,lineHeight:1.3,marginBottom:4,marginLeft:16},children:x.description}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:r.textMuted,fontFamily:r.font,marginLeft:16},children:[x.owners[0]&&s.jsxs("span",{children:["by ",x.owners[0]]}),s.jsxs("span",{children:[x.dashboards.length," dashboard",x.dashboards.length===1?"":"s"]}),s.jsxs("span",{children:[x.members," member",x.members===1?"":"s"]})]})]}),g&&s.jsxs("div",{style:{padding:"4px 0 10px 28px",background:`${r.accent}04`},children:[x.dashboards.length===0&&s.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,padding:"4px 0"},children:"(empty app scaffold)"}),x.dashboards.map(C=>s.jsx("button",{onClick:()=>m(x,C.id),style:{display:"block",width:"100%",textAlign:"left",background:"transparent",border:"none",padding:"3px 12px",cursor:"pointer",fontSize:11,color:r.textSecondary,fontFamily:r.font},children:C.title},C.id))]})]},x.id)})})}const _0={files:"Explorer",schema:"Schema",block_library:"Block Library",lineage:"Lineage",connection:"Connection",reference:"Quick Reference",git:"Git",apps:"Apps"};function b0({onOpenFile:e}){const{state:t,dispatch:n}=fe(),r=ie[t.themeMode],[o,i]=f.useState(!1),[a,l]=f.useState(240),[c,d]=f.useState(!1),E=f.useRef(a),u=t.sidebarPanel,T=p=>{p.preventDefault();const h=p.clientX,A=E.current;d(!0);const S=m=>{const I=Math.min(560,Math.max(180,A+(m.clientX-h)));E.current=I,l(I)},R=()=>{d(!1),window.removeEventListener("mousemove",S),window.removeEventListener("mouseup",R)};window.addEventListener("mousemove",S),window.addEventListener("mouseup",R)};return s.jsxs("div",{style:{width:a,flexShrink:0,background:r.sidebarBg,borderRight:`1px solid ${r.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:[s.jsxs("div",{style:{height:36,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 10px 0 14px",borderBottom:`1px solid ${r.headerBorder}`},children:[s.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",color:r.textSecondary,fontFamily:r.font},children:_0[u??""]??""}),s.jsx("button",{title:"Collapse sidebar",onClick:()=>n({type:"TOGGLE_SIDEBAR"}),onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:"transparent",border:"none",cursor:"pointer",color:o?r.textPrimary:r.textMuted,padding:"2px 4px",borderRadius:4,fontSize:14,lineHeight:1,transition:"color 0.15s",display:"flex",alignItems:"center"},children:"‹"})]}),s.jsxs("div",{style:{flex:1,overflow:"hidden",display:"flex",flexDirection:"column"},children:[u==="files"&&s.jsx(O_,{onOpenFile:e}),u==="schema"&&s.jsx(C_,{}),u==="block_library"&&s.jsx(c0,{}),u==="lineage"&&s.jsx(a0,{}),u==="connection"&&s.jsx(jR,{}),u==="reference"&&s.jsx(GR,{themeMode:t.themeMode}),u==="git"&&s.jsx(I0,{}),u==="apps"&&s.jsx(L0,{onOpenFile:e})]}),s.jsx("div",{onMouseDown:T,title:"Drag to resize",style:{position:"absolute",top:0,right:-3,width:6,height:"100%",cursor:"col-resize",background:c?r.accent:"transparent",zIndex:10,transition:c?"none":"background 0.15s"},onMouseEnter:p=>{c||(p.currentTarget.style.background=`${r.accent}40`)},onMouseLeave:p=>{c||(p.currentTarget.style.background="transparent")}})]})}var uu;(function(e){e.Program="Program",e.Workbook="Workbook",e.Page="Page",e.Dashboard="Dashboard",e.ChartCall="ChartCall",e.FilterCall="FilterCall",e.VariableDecl="VariableDecl",e.ParamDecl="ParamDecl",e.ImportDecl="ImportDecl",e.UseDecl="UseDecl",e.LayoutBlock="LayoutBlock",e.LayoutRow="LayoutRow",e.Decorator="Decorator",e.SQLQuery="SQLQuery",e.NamedArg="NamedArg",e.StringLiteral="StringLiteral",e.NumberLiteral="NumberLiteral",e.BooleanLiteral="BooleanLiteral",e.ArrayLiteral="ArrayLiteral",e.Identifier="Identifier",e.BinaryExpr="BinaryExpr",e.IntervalExpr="IntervalExpr",e.FunctionCall="FunctionCall",e.TemplateString="TemplateString",e.BlockDecl="BlockDecl",e.BlockParams="BlockParams",e.BlockVisualization="BlockVisualization",e.BlockTest="BlockTest",e.Digest="Digest",e.Narrative="Narrative"})(uu||(uu={}));var Tu;(function(e){e.Error="error",e.Warning="warning",e.Info="info"})(Tu||(Tu={}));var he;(function(e){e.StringLiteral="StringLiteral",e.NumberLiteral="NumberLiteral",e.BooleanLiteral="BooleanLiteral",e.Identifier="Identifier",e.DashboardKeyword="DashboardKeyword",e.WorkbookKeyword="WorkbookKeyword",e.PageKeyword="PageKeyword",e.LetKeyword="LetKeyword",e.ParamKeyword="ParamKeyword",e.ChartKeyword="ChartKeyword",e.FilterKeyword="FilterKeyword",e.IntervalKeyword="IntervalKeyword",e.ImportKeyword="ImportKeyword",e.FromKeyword="FromKeyword",e.UseKeyword="UseKeyword",e.LayoutKeyword="LayoutKeyword",e.RowKeyword="RowKeyword",e.BlockKeyword="BlockKeyword",e.DomainKeyword="DomainKeyword",e.TypeKeyword="TypeKeyword",e.DescriptionKeyword="DescriptionKeyword",e.TagsKeyword="TagsKeyword",e.OwnerKeyword="OwnerKeyword",e.QueryKeyword="QueryKeyword",e.VisualizationKeyword="VisualizationKeyword",e.TestsKeyword="TestsKeyword",e.ParamsKeyword="ParamsKeyword",e.AssertKeyword="AssertKeyword",e.VarKeyword="VarKeyword",e.DefaultKeyword="DefaultKeyword",e.MetricKeyword="MetricKeyword",e.MetricsKeyword="MetricsKeyword",e.DigestKeyword="DigestKeyword",e.NarrativeKeyword="NarrativeKeyword",e.ColonToken="ColonToken",e.TripleQuoteString="TripleQuoteString",e.GreaterThan="GreaterThan",e.LessThan="LessThan",e.GreaterThanOrEqual="GreaterThanOrEqual",e.LessThanOrEqual="LessThanOrEqual",e.DoubleEquals="DoubleEquals",e.NotEquals="NotEquals",e.InKeyword="InKeyword",e.SQLFragment="SQLFragment",e.AtSign="AtSign",e.LeftParen="LeftParen",e.RightParen="RightParen",e.LeftBrace="LeftBrace",e.RightBrace="RightBrace",e.LeftBracket="LeftBracket",e.RightBracket="RightBracket",e.Comma="Comma",e.Dot="Dot",e.Equals="Equals",e.Plus="Plus",e.Minus="Minus",e.Star="Star",e.Comment="Comment",e.Newline="Newline",e.EOF="EOF"})(he||(he={}));he.DashboardKeyword,he.WorkbookKeyword,he.PageKeyword,he.LetKeyword,he.ParamKeyword,he.ChartKeyword,he.FilterKeyword,he.BooleanLiteral,he.BooleanLiteral,he.IntervalKeyword,he.ImportKeyword,he.FromKeyword,he.UseKeyword,he.LayoutKeyword,he.RowKeyword,he.BlockKeyword,he.DomainKeyword,he.TypeKeyword,he.DescriptionKeyword,he.TagsKeyword,he.OwnerKeyword,he.QueryKeyword,he.VisualizationKeyword,he.TestsKeyword,he.ParamsKeyword,he.AssertKeyword,he.VarKeyword,he.DefaultKeyword,he.InKeyword,he.MetricKeyword,he.MetricsKeyword,he.DigestKeyword,he.NarrativeKeyword;const WR=1;function D0(e,t={}){const n=t.version??WR,r=JSON.parse(e),{dqlnbVersion:o,...i}=r,a={dqlnbVersion:n,...i};return JSON.stringify(a,M0(),2)+`
|
|
506
|
-
`}function M0(){return function(t,n){if(n===null||typeof n!="object"||Array.isArray(n))return n;const r=n,o=Object.keys(r);o.sort((a,l)=>{const c=fu[a],d=fu[l];return c!==void 0&&d!==void 0?c-d:c!==void 0?-1:d!==void 0?1:a<l?-1:a>l?1:0});const i={};for(const a of o)i[a]=r[a];return i}}const fu={dqlnbVersion:0,version:1,title:2,metadata:3,cells:4,id:10,type:11,name:12,content:13};function v0(e){try{const t=e.match(/workbook\s+"([^"]+)"/i),n=t?t[1]:"Untitled Workbook",r=[],o=/page\s+"([^"]+)"\s*\{([\s\S]*?)\}/gi;let i;for(;(i=o.exec(e))!==null;){const a=i[1],l=i[2].trim();r.push({id:ut(),type:"markdown",content:`# ${a}`,status:"idle"}),l&&r.push({id:ut(),type:"dql",name:a.toLowerCase().replace(/\s+/g,"_"),content:l,status:"idle"})}return r.length===0&&r.push({id:ut(),type:"dql",content:e.trim(),status:"idle"}),{title:n,cells:r}}catch(t){return console.warn("parse-workbook: falling back after error",t),{title:"Untitled Workbook",cells:[{id:ut(),type:"dql",content:e.trim(),status:"idle"}]}}}function P0(e){var t;try{const n=JSON.parse(e),r=n.title||((t=n.metadata)==null?void 0:t.title)||"Untitled",o=(n.cells||[]).map(l=>({id:l.id||ut(),type:l.type||"sql",content:l.content??l.source??"",name:l.name||l.title,status:"idle",...l.paramConfig?{paramConfig:l.paramConfig}:{},...l.paramValue!==void 0?{paramValue:l.paramValue}:{},...l.chartConfig?{chartConfig:l.chartConfig}:{},...l.filterConfig?{filterConfig:l.filterConfig}:{},...l.pivotConfig?{pivotConfig:l.pivotConfig}:{},...l.singleValueConfig?{singleValueConfig:l.singleValueConfig}:{},...l.tableConfig?{tableConfig:l.tableConfig}:{},...l.upstream?{upstream:l.upstream}:{},...l.blockBinding?{blockBinding:l.blockBinding}:{}})),{title:i,...a}=n.metadata??{};return{title:r,cells:o,metadata:a}}catch(n){return console.warn("parse-workbook: falling back after error",n),{title:"Untitled",cells:[{id:ut(),type:"sql",content:e,status:"idle"}]}}}function w0(e,t,n){const r={dqlnbVersion:WR,version:1,title:e,metadata:{...n,modifiedAt:new Date().toISOString(),...n!=null&&n.createdAt?{}:{createdAt:new Date().toISOString()}},cells:t.map(o=>({id:o.id,type:o.type,content:o.content,...o.name?{name:o.name}:{},...o.paramConfig?{paramConfig:o.paramConfig}:{},...o.paramValue!==void 0?{paramValue:o.paramValue}:{},...o.chartConfig?{chartConfig:o.chartConfig}:{},...o.filterConfig?{filterConfig:o.filterConfig}:{},...o.pivotConfig?{pivotConfig:o.pivotConfig}:{},...o.singleValueConfig?{singleValueConfig:o.singleValueConfig}:{},...o.tableConfig?{tableConfig:o.tableConfig}:{},...o.upstream?{upstream:o.upstream}:{},...o.blockBinding?{blockBinding:o.blockBinding}:{}}))};return D0(JSON.stringify(r))}function U0(e,t){return e.endsWith(".dql")?v0(t):P0(t)}const $R=/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g;function B0(e){const t=new Set;for(const n of e.matchAll($R))t.add(n[1]);return[...t]}function F0(e,t){if(!t.columns.length||!t.rows.length)return`${e} AS (SELECT 1 WHERE 1=0)`;const n=t.columns,o=t.rows.slice(0,5e3).map(a=>`(${n.map(c=>{const d=a[c];return d==null?"NULL":typeof d=="number"?String(d):typeof d=="boolean"?d?"TRUE":"FALSE":`'${String(d).replace(/'/g,"''")}'`}).join(", ")})`).join(`,
|
|
507
|
-
`),i=n.map(a=>`"${a.replace(/"/g,'""')}"`).join(", ");return`${e} AS (
|
|
508
|
-
SELECT * FROM (VALUES
|
|
509
|
-
${o}
|
|
510
|
-
) AS _t(${i})
|
|
511
|
-
)`}function k0(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function j0(){const{state:e}=fe();return{substituteVariables:f.useCallback(n=>{var d;const r=[...n.matchAll($R)];if(r.length===0)return{sql:n,substituted:[]};const o=[],i=[];let a=n;const l=new Map,c=new Map;for(const E of e.cells){const u=(d=E.name)==null?void 0:d.trim();u&&(E.type==="param"?l.set(u,E):E.status==="success"&&E.result&&c.set(u,E.result))}for(const E of r){const u=E[1];if(l.has(u)){const T=l.get(u),p=T.paramConfig,h=T.paramValue??(p==null?void 0:p.defaultValue)??"",A=(p==null?void 0:p.paramType)??"text",S=k0(h,A);a=a.replace(E[0],S),o.push(u)}else c.has(u)&&(i.push(F0(u,c.get(u))),a=a.replace(E[0],`"${u}"`),o.push(u))}if(i.length===0&&o.length===0)return{sql:n,substituted:[]};if(i.length>0){const E=a.trimStart();/^WITH\s+/i.test(E)?a=a.replace(/^(\s*WITH\s+)/i,`$1${i.join(`,
|
|
512
|
-
`)},
|
|
513
|
-
`):a=`WITH ${i.join(`,
|
|
514
|
-
`)}
|
|
515
|
-
${a}`}return{sql:a,substituted:o}},[e.cells])}}function G0(e){var i;const t=e.match(/visualization\s*\{([^}]+)\}/is);if(!t)return;const n=t[1],r=a=>{var l;return(l=n.match(new RegExp(`\\b${a}\\s*=\\s*["']?([\\w-]+)["']?`,"i")))==null?void 0:l[1]},o=r("chart");if(o)return{chart:o,x:r("x"),y:r("y"),color:r("color"),title:(i=n.match(/\btitle\s*=\s*"([^"]+)"/i))==null?void 0:i[1]}}function Pd(e){const t=e.trim();if(!t)return null;const n=t.match(/query\s*=\s*"""([\s\S]*?)"""/i);if(n)return n[1].trim()||null;const r=t.match(/"""([\s\S]*?)"""/);if(r)return r[1].trim()||null;if(/^\s*(dashboard|workbook)\s+"/i.test(t))return null;const o=t.match(/\b(SELECT|WITH|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|SHOW|DESCRIBE|EXPLAIN)\b([\s\S]*)/i);if(o){let i=o[0];const a=i.search(/\b(visualization|tests|block)\s*\{/i);return a>0&&(i=i.slice(0,a)),i=H0(i),i.trim()||null}return null}function H0(e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];if(r==="("){t++;continue}if(r===")"){t>0&&t--;continue}if(r==="'"||r==='"'){for(n++;n<e.length&&e[n]!==r;)e[n]==="\\"&&n++,n++;continue}if(r===","&&t===0){let o=n+1;for(;o<e.length&&/\s/.test(e[o]);)o++;if(o<e.length&&/[a-zA-Z_]/.test(e[o])){for(;o<e.length&&/[a-zA-Z0-9_]/.test(e[o]);)o++;let i=o;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="="&&e[i+1]!=="=")return e.slice(0,n)}}}return e}function pu(e){const t=Xn(e);return t?{name:t.name,domain:t.domain,owner:t.owner,description:t.description,blockType:t.blockType,tags:t.tags}:null}function ul(e,t,n){const r=Xn(e);if(!r){const i=n.replace(/"/g,'\\"'),a=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return a.test(e)?e.replace(a,`$1"${i}"`):wd(e,` ${t} = "${i}"`)}const o={...r};return t==="domain"&&(o.domain=n),t==="owner"&&(o.owner=n),t==="description"&&(o.description=n),t==="type"&&(o.blockType=n),Hr(o)}function VR(e,t){const n=Xn(e);if(!n){const r=t.replace(/"/g,'\\"');return/^\s*block\s+"/i.test(e)?e.replace(/^(\s*block\s+)"[^"]+"/i,`$1"${r}"`):e}return Hr({...n,name:t})}function Y0(e,t){const n=Xn(e);if(!n){const r=t.map(i=>`"${i.replace(/"/g,'\\"')}"`).join(", "),o=/(\btags\s*=\s*)\[[^\]]*\]/i;return o.test(e)?e.replace(o,`$1[${r}]`):wd(e,` tags = [${r}]`)}return Hr({...n,tags:t})}function W0(e,t){const n=Xn(e),r=z0(t);return n?Hr({...n,visualization:r}):/visualization\s*\{[\s\S]*?\n\s*\}/i.test(e)?e.replace(/visualization\s*\{[\s\S]*?\n\s*\}/i,r):wd(e,` ${r.replace(/\n/g,`
|
|
516
|
-
`)}`,!0)}function $0(e,t){return e==="metric"?`@metric(${t})`:`@dim(${t})`}function V0(e,t){const n=Xn(e);if(!n||n.blockType!=="semantic")return e;const r={...n,metrics:[...n.metrics],dimensions:[...n.dimensions]};if(t.kind==="metric"){const o=new Set;r.metric&&o.add(r.metric);for(const a of r.metrics)o.add(a);o.add(t.name);const i=Array.from(o);r.metric=i.length===1?i[0]:"",r.metrics=i.length>1?i:[]}else r.dimensions.includes(t.name)||(r.dimensions=[...r.dimensions,t.name]);return Hr(r)}function X0(e,t){const n=Xn(e);if(!n||n.blockType!=="custom")return`${e.trimEnd()}
|
|
517
|
-
${t}
|
|
518
|
-
`;const r=n.query.trimEnd(),o=r?`${r}
|
|
519
|
-
${t}`:t;return Hr({...n,query:o})}function Xn(e){var i,a;if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=l=>{var c;return((c=e.match(new RegExp(`\\b${l}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:c[1])??""},n=((i=e.match(/^\s*block\s+"([^"]+)"/i))==null?void 0:i[1])??"",r=e.match(/\btags\s*=\s*\[([^\]]*)\]/i),o=e.match(/query\s*=\s*"""([\s\S]*?)"""/i);return{name:n,domain:t("domain"),owner:t("owner"),description:t("description"),blockType:(t("type")||"custom").toLowerCase()==="semantic"?"semantic":"custom",tags:r?(r[1].match(/"([^"]*)"/g)??[]).map(l=>l.slice(1,-1)):[],metric:t("metric"),metrics:Su(e,"metrics"),dimensions:Su(e,"dimensions"),timeDimension:t("time_dimension"),granularity:t("granularity"),query:((a=o==null?void 0:o[1])==null?void 0:a.trim())??"",visualization:Ru(e,"visualization"),tests:Ru(e,"tests")}}function Su(e,t){const n=e.match(new RegExp(`\\b${t}\\s*=\\s*\\[([\\s\\S]*?)\\]`,"i"));return n?(n[1].match(/"([^"]*)"/g)??[]).map(r=>r.slice(1,-1)).filter(Boolean):[]}function Ru(e,t){const n=new RegExp(`\\b${t}\\s*\\{`,"i").exec(e);if(!n||n.index==null)return"";let r=0,o=-1;for(let i=n.index;i<e.length;i++){const a=e[i];if(a==="{")r===0&&(o=i),r++;else if(a==="}"&&(r--,r===0&&o>=0))return e.slice(n.index,i+1).trim()}return""}function Hr(e){const t=[`block "${ct(e.name||"New Block")}" {`,` domain = "${ct(e.domain||"uncategorized")}"`,` type = "${e.blockType}"`,` description = "${ct(e.description)}"`,` owner = "${ct(e.owner)}"`,` tags = [${e.tags.map(n=>`"${ct(n)}"`).join(", ")}]`];if(e.blockType==="semantic"){const n=e.metrics.length>0?Array.from(new Set(e.metrics)):e.metric?[e.metric]:[];n.length===1?t.push(` metric = "${ct(n[0])}"`):n.length>1&&t.push(` metrics = [${n.map(r=>`"${ct(r)}"`).join(", ")}]`),e.dimensions.length>0&&t.push(` dimensions = [${Array.from(new Set(e.dimensions)).map(r=>`"${ct(r)}"`).join(", ")}]`),e.timeDimension&&t.push(` time_dimension = "${ct(e.timeDimension)}"`),e.granularity&&t.push(` granularity = "${ct(e.granularity)}"`)}return e.blockType==="custom"&&(t.push(""),t.push(' query = """'),t.push(...K0(e.query.trim(),4)),t.push(' """')),e.visualization&&(t.push(""),t.push(...hu(e.visualization,2))),e.tests&&(t.push(""),t.push(...hu(e.tests,2))),t.push("}"),t.join(`
|
|
520
|
-
`)+`
|
|
521
|
-
`}function z0(e){const t=[];return t.push("visualization {"),t.push(` chart = "${e.chart??"table"}"`),e.x&&t.push(` x = ${e.x}`),e.y&&t.push(` y = ${e.y}`),e.color&&t.push(` color = ${e.color}`),e.title&&t.push(` title = "${ct(e.title)}"`),t.push("}"),t.join(`
|
|
522
|
-
`)}function K0(e,t){const n=" ".repeat(t);return(e?e.split(`
|
|
523
|
-
`):[""]).map(o=>`${n}${o}`)}function hu(e,t){const n=" ".repeat(t);return e.split(`
|
|
524
|
-
`).map(r=>`${n}${r.trimEnd()}`)}function ct(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function wd(e,t,n=!1){const r=e.trimEnd();if(!/^\s*block\s+"/i.test(r))return`${r}
|
|
525
|
-
${t}
|
|
526
|
-
`;const o=n?`
|
|
527
|
-
|
|
528
|
-
${t}
|
|
529
|
-
`:`
|
|
530
|
-
${t}`;return r.replace(/\n\}\s*$/,`${o}
|
|
531
|
-
}`)}const Zt=new Map;function q0(e){if(e.type==="markdown"||e.type==="param")return null;if(e.type==="sql")return e.content.trim()||null;const t=e.content.trim();return t?Pd(t):null}function J0(e){if(!e||typeof e!="object")return;const t=e;return{...typeof t.chart=="string"?{chart:t.chart}:{},...typeof t.x=="string"?{x:t.x}:{},...typeof t.y=="string"?{y:t.y}:{},...typeof t.color=="string"?{color:t.color}:{},...typeof t.title=="string"?{title:t.title}:{}}}function ca(){const{state:e,dispatch:t}=fe(),{substituteVariables:n}=j0(),r=f.useCallback(async l=>{const c=e.cells.find(h=>h.id===l);if(!c)return;if(c.type==="dql"){const h=Date.now(),A=Zt.get(l);A&&A.abort();const S=new AbortController;Zt.set(l,S),t({type:"UPDATE_CELL",id:l,updates:{status:"running",error:void 0,result:void 0,fromSnapshot:!1}});try{const R=await z.executeNotebookCell(c,S.signal);if(!R.result)throw new Error("DQL cell produced no executable result.");const m=Date.now()-h,I=(c.executionCount??0)+1,O=J0(R.chartConfig)??G0(c.content);t({type:"UPDATE_CELL",id:l,updates:{status:"success",result:{...R.result,executionTime:R.result.executionTime??m,rowCount:R.result.rowCount??R.result.rows.length},...O?{chartConfig:O}:{},executionCount:I}}),t({type:"APPEND_QUERY_LOG",entry:{id:ut(),cellName:R.blockName??c.name??c.id,rows:R.result.rowCount??R.result.rows.length,time:R.result.executionTime??m,ts:new Date}}),setTimeout(()=>{t({type:"UPDATE_CELL",id:l,updates:{status:"idle"}})},2e3)}catch(R){if(S.signal.aborted){t({type:"UPDATE_CELL",id:l,updates:{status:"idle",error:void 0}});return}const m=Date.now()-h,I=R instanceof Error?R.message:String(R);t({type:"UPDATE_CELL",id:l,updates:{status:"error",error:I,executionCount:(c.executionCount??0)+1}}),t({type:"APPEND_QUERY_LOG",entry:{id:ut(),cellName:c.name??c.id,rows:0,time:m,ts:new Date,error:I}})}finally{Zt.delete(l)}return}const d=q0(c);if(!d)return;const{sql:E}=n(d),u=Date.now(),T=Zt.get(l);T&&T.abort();const p=new AbortController;Zt.set(l,p),t({type:"UPDATE_CELL",id:l,updates:{status:"running",error:void 0,result:void 0,fromSnapshot:!1}});try{const h=await z.executeQuery(E,p.signal),A=Date.now()-u,S=(c.executionCount??0)+1;t({type:"UPDATE_CELL",id:l,updates:{status:"success",result:{...h,executionTime:h.executionTime??A,rowCount:h.rowCount??h.rows.length},executionCount:S}}),t({type:"APPEND_QUERY_LOG",entry:{id:ut(),cellName:c.name??c.id,rows:h.rowCount??h.rows.length,time:h.executionTime??A,ts:new Date}}),setTimeout(()=>{t({type:"UPDATE_CELL",id:l,updates:{status:"idle"}})},2e3)}catch(h){if(p.signal.aborted){t({type:"UPDATE_CELL",id:l,updates:{status:"idle",error:void 0}});return}const A=Date.now()-u,S=h instanceof Error?h.message:String(h);t({type:"UPDATE_CELL",id:l,updates:{status:"error",error:S,executionCount:(c.executionCount??0)+1}}),t({type:"APPEND_QUERY_LOG",entry:{id:ut(),cellName:c.name??c.id,rows:0,time:A,ts:new Date,error:S}})}finally{Zt.delete(l)}},[e.cells,t]),o=f.useCallback(async()=>{for(const l of e.cells)l.type!=="markdown"&&await r(l.id)},[e.cells,r]),i=f.useCallback(async l=>{if(!l)return;const c=`{{${l}}}`;for(const d of e.cells)d.type==="markdown"||d.type==="param"||d.content.includes(c)&&await r(d.id)},[e.cells,r]),a=f.useCallback(l=>{const c=Zt.get(l);c&&(c.abort(),Zt.delete(l)),t({type:"UPDATE_CELL",id:l,updates:{status:"idle"}})},[t]);return{executeCell:r,executeAll:o,executeDependents:i,cancelCell:a}}function He(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Q0(e){return typeof e=="number"?Math.abs(e)>=1e6?`${(e/1e6).toFixed(1)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1)}K`:Number.isInteger(e)?String(e):e.toFixed(2):""}function Z0(e){const t=e.split(`
|
|
532
|
-
`),n=[];let r=!1,o=!1;for(const i of t){const a=i;if(a.startsWith("```")){o&&(n.push("</ul>"),o=!1),r?(n.push("</code></pre>"),r=!1):(n.push("<pre><code>"),r=!0);continue}if(r){n.push(He(a));continue}if(a.startsWith("### ")){o&&(n.push("</ul>"),o=!1),n.push(`<h3>${He(a.slice(4))}</h3>`);continue}if(a.startsWith("## ")){o&&(n.push("</ul>"),o=!1),n.push(`<h2>${He(a.slice(3))}</h2>`);continue}if(a.startsWith("# ")){o&&(n.push("</ul>"),o=!1),n.push(`<h1>${He(a.slice(2))}</h1>`);continue}if(a.startsWith("> ")){o&&(n.push("</ul>"),o=!1),n.push(`<blockquote><p>${He(a.slice(2))}</p></blockquote>`);continue}if(a.startsWith("- ")||a.startsWith("* ")){o||(n.push("<ul>"),o=!0),n.push(`<li>${Au(a.slice(2))}</li>`);continue}if(o&&(n.push("</ul>"),o=!1),a.trim()===""){n.push("<br>");continue}n.push(`<p>${Au(a)}</p>`)}return o&&n.push("</ul>"),r&&n.push("</code></pre>"),n.join(`
|
|
533
|
-
`)}function Au(e){return He(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>")}function eb(e){const{columns:t,rows:n}=e,r=n.slice(0,200),o=n.length>200,i=t.map(l=>`<th>${He(l)}</th>`).join(""),a=r.map(l=>`<tr>${t.map(d=>{const E=l[d],u=typeof E=="number",T=E==null?"—":String(E);return`<td${u?' class="num"':""}>${He(T)}</td>`}).join("")}</tr>`).join("");return`
|
|
534
|
-
<div class="table-wrap">
|
|
535
|
-
<table>
|
|
536
|
-
<thead><tr>${i}</tr></thead>
|
|
537
|
-
<tbody>${a}</tbody>
|
|
538
|
-
</table>
|
|
539
|
-
${o?`<p class="truncated">Showing first 200 of ${n.length.toLocaleString()} rows</p>`:""}
|
|
540
|
-
</div>`}function tb(e){const{columns:t,rows:n}=e;if(t.length<2||n.length===0)return null;const r=t.find(i=>typeof n[0][i]=="number"),o=t.find(i=>i!==r);return!r||!o?null:{labelCol:o,valueCol:r}}function nb(e){const t=tb(e);if(!t)return null;const n=e.rows.slice(0,20).map(E=>({label:String(E[t.labelCol]??""),value:Number(E[t.valueCol]??0)})),r=Math.max(...n.map(E=>E.value),1),o=28,i=6,a=140,l=440,c=n.length*(o+i)+40,d=n.map((E,u)=>{const T=u*(o+i)+20,p=Math.max(E.value/r*l,2);return`
|
|
541
|
-
<text x="${a-6}" y="${T+o/2+4}" text-anchor="end" font-size="11" fill="#8b949e">${He(E.label.slice(0,20))}</text>
|
|
542
|
-
<rect x="${a}" y="${T}" width="${p}" height="${o}" rx="3" fill="#388bfd" />
|
|
543
|
-
<text x="${a+p+5}" y="${T+o/2+4}" font-size="11" fill="#e6edf3">${Q0(E.value)}</text>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" width="${a+l+80}" height="${c}" style="max-width:100%">${d}</svg>`}function rb(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${Z0(r.content)}</section>`;const o=r.name?`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span><span class="cell-name">${He(r.name)}</span></div>`:`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span></div>`,i=`<pre class="cell-code"><code>${He(r.content)}</code></pre>`;let a="";if(r.result&&r.result.rows.length>0){const l=nb(r.result),c=eb(r.result);a=`<div class="cell-output">${`<div class="output-meta">${r.result.rows.length.toLocaleString()} rows${r.result.executionTime?` · ${r.result.executionTime}ms`:""}</div>`}${l??""}${l?"":c}</div>`}else r.error&&(a=`<div class="cell-error">⚠ ${He(r.error)}</div>`);return`<section class="cell sql-cell">${o}${i}${a}</section>`}).join(`
|
|
544
|
-
`);return`<!DOCTYPE html>
|
|
545
|
-
<html lang="en">
|
|
546
|
-
<head>
|
|
547
|
-
<meta charset="UTF-8">
|
|
548
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
549
|
-
<title>${He(e)}</title>
|
|
550
|
-
<style>
|
|
551
|
-
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
|
552
|
-
body {
|
|
553
|
-
font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
554
|
-
background: #0d1117; color: #e6edf3;
|
|
555
|
-
line-height: 1.6; padding: 0;
|
|
556
|
-
}
|
|
557
|
-
.page-header {
|
|
558
|
-
background: #161b22; border-bottom: 1px solid #21262d;
|
|
559
|
-
padding: 16px 32px; display: flex; align-items: center; gap: 12px;
|
|
560
|
-
}
|
|
561
|
-
.logo {
|
|
562
|
-
width: 28px; height: 28px; border-radius: 6px;
|
|
563
|
-
background: linear-gradient(135deg, #388bfd, #1f6feb);
|
|
564
|
-
display: flex; align-items: center; justify-content: center;
|
|
565
|
-
font-size: 10px; font-weight: 700; color: #fff;
|
|
566
|
-
font-family: monospace; letter-spacing: -0.5px; flex-shrink: 0;
|
|
567
|
-
}
|
|
568
|
-
.page-title { font-size: 18px; font-weight: 600; color: #e6edf3; }
|
|
569
|
-
.page-meta { font-size: 12px; color: #8b949e; margin-left: auto; }
|
|
570
|
-
.content { max-width: 900px; margin: 0 auto; padding: 32px 24px; display: flex; flex-direction: column; gap: 24px; }
|
|
571
|
-
.cell { border-radius: 8px; overflow: hidden; }
|
|
572
|
-
.md-cell { padding: 4px 0; }
|
|
573
|
-
.md-cell h1 { font-size: 26px; font-weight: 700; color: #e6edf3; margin: 0 0 12px; }
|
|
574
|
-
.md-cell h2 { font-size: 20px; font-weight: 600; color: #e6edf3; margin: 20px 0 10px; }
|
|
575
|
-
.md-cell h3 { font-size: 16px; font-weight: 600; color: #e6edf3; margin: 16px 0 8px; }
|
|
576
|
-
.md-cell p { color: #c9d1d9; margin-bottom: 8px; }
|
|
577
|
-
.md-cell ul { padding-left: 20px; color: #c9d1d9; margin-bottom: 8px; }
|
|
578
|
-
.md-cell code { background: #21262d; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 13px; }
|
|
579
|
-
.md-cell pre { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 14px; overflow-x: auto; margin-bottom: 8px; }
|
|
580
|
-
.md-cell pre code { background: none; padding: 0; }
|
|
581
|
-
.md-cell blockquote { border-left: 3px solid #388bfd; padding-left: 14px; color: #8b949e; }
|
|
582
|
-
.sql-cell { background: #161b22; border: 1px solid #30363d; }
|
|
583
|
-
.cell-header { display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-bottom: 1px solid #21262d; background: #1c2128; }
|
|
584
|
-
.cell-type { font-size: 10px; font-weight: 600; letter-spacing: 0.05em; color: #8b949e; background: #21262d; padding: 2px 6px; border-radius: 4px; font-family: monospace; }
|
|
585
|
-
.cell-name { font-size: 12px; color: #388bfd; font-family: monospace; }
|
|
586
|
-
.cell-code { background: #0d1117; padding: 14px; font-size: 12px; font-family: 'JetBrains Mono', monospace; color: #c9d1d9; overflow-x: auto; border-bottom: 1px solid #21262d; line-height: 1.55; white-space: pre; }
|
|
587
|
-
.cell-output { padding: 14px; }
|
|
588
|
-
.output-meta { font-size: 11px; color: #8b949e; margin-bottom: 10px; }
|
|
589
|
-
.table-wrap { overflow-x: auto; }
|
|
590
|
-
table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
|
591
|
-
th { background: #1c2128; color: #8b949e; font-weight: 600; text-align: left; padding: 7px 12px; border-bottom: 1px solid #30363d; white-space: nowrap; }
|
|
592
|
-
td { padding: 6px 12px; border-bottom: 1px solid #21262d; color: #e6edf3; }
|
|
593
|
-
td.num { text-align: right; font-family: monospace; }
|
|
594
|
-
tr:last-child td { border-bottom: none; }
|
|
595
|
-
.truncated { font-size: 11px; color: #8b949e; margin-top: 8px; }
|
|
596
|
-
.cell-error { padding: 12px 14px; background: #3d1a1a; border-top: 1px solid #f85149; color: #f85149; font-size: 13px; }
|
|
597
|
-
.exported-by { text-align: center; color: #484f58; font-size: 11px; padding: 40px 0 24px; }
|
|
598
|
-
</style>
|
|
599
|
-
</head>
|
|
600
|
-
<body>
|
|
601
|
-
<div class="page-header">
|
|
602
|
-
<div class="logo">DQL</div>
|
|
603
|
-
<span class="page-title">${He(e)}</span>
|
|
604
|
-
<span class="page-meta">Exported ${new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}</span>
|
|
605
|
-
</div>
|
|
606
|
-
<div class="content">
|
|
607
|
-
${n}
|
|
608
|
-
</div>
|
|
609
|
-
<p class="exported-by">Built with DQL Notebook</p>
|
|
610
|
-
</body>
|
|
611
|
-
</html>`}function ob(e,t){const n=rb(e,t),r=new Blob([n],{type:"text/html;charset=utf-8"}),o=URL.createObjectURL(r),i=document.createElement("a");i.href=o,i.download=`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-dashboard.html`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o)}function sb({t:e}){return s.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"linear-gradient(135deg, #5b8cff 0%, #7c5cff 100%)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:s.jsx("span",{style:{color:"#ffffff",fontSize:10,fontWeight:700,fontFamily:e.fontMono,letterSpacing:"-0.5px"},children:"DQL"})})}function ib(){const{state:e,dispatch:t}=fe(),n=ie[e.themeMode],{executeAll:r}=ca(),[o,i]=f.useState(!1),[a,l]=f.useState(""),[c,d]=f.useState(!1),[E,u]=f.useState(!1),[T,p]=f.useState(!1),[h,A]=f.useState(!1),[S,R]=f.useState(!1),m=f.useRef(null),[I,O]=f.useState(!1),[N,x]=f.useState(!1),g=f.useRef(null),C=f.useRef(null),y=e.mainView==="block_studio"?e.blockStudioDirty:e.notebookDirty,w=e.mainView==="notebook",v=e.mainView==="connection"?"Connections":e.mainView==="reference"?"Quick Reference":e.notebookTitle||"Untitled";f.useEffect(()=>{o&&C.current&&(C.current.focus(),C.current.select())},[o]),f.useEffect(()=>{if(!N)return;function _(F){g.current&&!g.current.contains(F.target)&&x(!1)}return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[N]);const B=()=>{l(e.notebookTitle),i(!0)},b=()=>{i(!1),a.trim()&&a!==e.notebookTitle&&(e.mainView==="block_studio"&&e.blockStudioMetadata?(t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,name:a.trim()}}),t({type:"SET_BLOCK_STUDIO_DRAFT",draft:VR(e.blockStudioDraft,a.trim())})):t({type:"SET_NOTEBOOK_DIRTY",dirty:!0}))},L=f.useCallback(async()=>{var _;if(e.activeFile){t({type:"SET_SAVING",saving:!0});try{if(e.mainView==="block_studio"){if(!e.blockStudioMetadata)return;const F=await z.saveBlockStudio({path:e.activeBlockPath,source:e.blockStudioDraft,metadata:{name:e.blockStudioMetadata.name,domain:e.blockStudioMetadata.domain,description:e.blockStudioMetadata.description,owner:e.blockStudioMetadata.owner,tags:e.blockStudioMetadata.tags}});t({type:"OPEN_BLOCK_STUDIO",file:{name:`${F.metadata.name}.dql`,path:F.path,type:"block",folder:"blocks"},payload:F}),e.files.some(k=>k.path===F.path)||t({type:"FILE_ADDED",file:{name:`${F.metadata.name}.dql`,path:F.path,type:"block",folder:"blocks"}})}else{const F=e.activeFile.type==="block"?((_=e.cells[0])==null?void 0:_.content)??"":w0(e.notebookTitle,e.cells,e.notebookMetadata);await z.saveNotebook(e.activeFile.path,F),t({type:"SET_NOTEBOOK_DIRTY",dirty:!1})}d(!0),setTimeout(()=>d(!1),2e3)}catch(F){console.error("Save failed:",F)}finally{t({type:"SET_SAVING",saving:!1})}}},[e.activeFile,e.activeBlockPath,e.blockStudioDraft,e.blockStudioMetadata,e.files,e.mainView,e.notebookTitle,e.notebookMetadata,e.cells,t]);f.useEffect(()=>{const _=F=>{(F.metaKey||F.ctrlKey)&&F.key==="s"&&(F.preventDefault(),L())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[L]),f.useEffect(()=>{if(!e.autoSave||!y||!e.activeFile)return;const _=setTimeout(()=>{L()},2e3);return()=>clearTimeout(_)},[e.autoSave,y,e.activeFile,e.cells,e.blockStudioDraft,L]);const D=[{mode:"obsidian",label:"Obsidian",glyph:"●",swatch:"#0d0e11"},{mode:"paper",label:"Paper",glyph:"☼",swatch:"#f7f4ed"},{mode:"white",label:"White",glyph:"○",swatch:"#ffffff"}],M=e.themeMode==="dark"||e.themeMode==="midnight"?"obsidian":e.themeMode==="light"?"paper":e.themeMode==="arctic"?"white":e.themeMode,U=D.find(_=>_.mode===M)??D[0];f.useEffect(()=>{if(!S)return;const _=k=>{m.current&&!m.current.contains(k.target)&&R(!1)},F=k=>{k.key==="Escape"&&R(!1)};return document.addEventListener("mousedown",_),document.addEventListener("keydown",F),()=>{document.removeEventListener("mousedown",_),document.removeEventListener("keydown",F)}},[S]);const P={height:28,padding:"0 10px",borderRadius:6,border:`1px solid ${n.btnBorder}`,cursor:"pointer",fontSize:12,fontWeight:500,fontFamily:n.font,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s, color 0.15s",whiteSpace:"nowrap"};return s.jsxs("div",{style:{height:48,flexShrink:0,background:n.headerBg,borderBottom:`1px solid ${n.headerBorder}`,display:"flex",alignItems:"center",padding:"0 12px",gap:8,userSelect:"none"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[s.jsx(sb,{t:n}),s.jsx("div",{style:{width:1,height:20,background:n.headerBorder,flexShrink:0}}),e.activeFile&&s.jsx("span",{style:{fontSize:10,fontWeight:600,color:e.activeFile.type==="block"?"#e3b341":n.accent,background:`${e.activeFile.type==="block"?"#e3b341":n.accent}18`,borderRadius:4,padding:"2px 6px",fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em",flexShrink:0},children:e.activeFile.type}),e.activeFile&&e.mainView!=="connection"&&e.mainView!=="reference"?o?s.jsx("input",{ref:C,value:a,onChange:_=>l(_.target.value),onBlur:b,onKeyDown:_=>{_.key==="Enter"&&b(),_.key==="Escape"&&i(!1)},style:{background:"transparent",border:`1px solid ${n.cellBorderActive}`,borderRadius:4,color:n.textPrimary,fontSize:13,fontWeight:500,fontFamily:n.font,padding:"2px 6px",outline:"none",minWidth:120,maxWidth:320}}):s.jsxs("span",{onClick:B,title:"Click to rename",style:{color:n.textPrimary,fontSize:13,fontWeight:500,fontFamily:n.font,cursor:"text",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",padding:"2px 4px",borderRadius:4,border:"1px solid transparent"},children:[v,y&&s.jsx("span",{style:{color:n.textMuted,marginLeft:4},children:"●"})]}):s.jsx("span",{style:{color:n.textSecondary,fontSize:13,fontFamily:n.font,padding:"2px 4px"},children:v})]}),s.jsx("div",{style:{flex:1}}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.appMode==="studio"&&s.jsx(s.Fragment,{children:s.jsxs("button",{onClick:w?r:void 0,disabled:!e.activeFile||!w,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...P,height:30,padding:"0 14px",borderRadius:999,background:n.accent,color:"#ffffff",border:`1px solid ${n.accent}`,opacity:!e.activeFile||!w?.4:E?.9:1,boxShadow:"0 1px 2px rgba(107,93,211,0.25)",gap:6},children:[s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:s.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})}),"Run all"]})}),s.jsxs("div",{ref:m,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>R(_=>!_),onMouseEnter:()=>A(!0),onMouseLeave:()=>A(!1),title:`Theme: ${U.label}`,"aria-haspopup":"true","aria-expanded":S,style:{...P,background:h||S?n.btnHover:n.btnBg,color:n.textSecondary,padding:"0 10px",fontSize:12,display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{style:{width:12,height:12,borderRadius:3,background:U.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),s.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10,letterSpacing:"0.04em"},children:U.label}),s.jsx("span",{style:{fontSize:8,color:n.textMuted},children:"▾"})]}),S&&s.jsx("div",{role:"menu",style:{position:"absolute",top:"100%",right:0,marginTop:4,minWidth:160,background:n.headerBg,border:`1px solid ${n.headerBorder}`,borderRadius:6,boxShadow:"0 8px 24px rgba(0,0,0,0.32)",padding:4,zIndex:1e3,display:"flex",flexDirection:"column",gap:1},children:D.map(_=>{const F=_.mode===M;return s.jsxs("button",{role:"menuitemradio","aria-checked":F,onClick:()=>{t({type:"SET_THEME",mode:_.mode}),R(!1)},style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",background:F?n.btnHover:"transparent",color:n.textPrimary,cursor:"pointer",borderRadius:4,fontSize:12,fontFamily:n.font,textAlign:"left"},onMouseEnter:k=>{F||(k.currentTarget.style.background=n.btnHover)},onMouseLeave:k=>{F||(k.currentTarget.style.background="transparent")},children:[s.jsx("span",{style:{width:14,height:14,borderRadius:3,background:_.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),s.jsx("span",{style:{flex:1},children:_.label}),F&&s.jsx("span",{style:{color:n.accent,fontSize:11},children:"✓"})]},_.mode)})})]}),e.appMode==="studio"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:L,disabled:!e.activeFile||e.savingFile,onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),title:"Save (Cmd+S)",style:{...P,background:T&&e.activeFile?n.btnHover:n.btnBg,color:c?n.success:n.textSecondary,opacity:e.activeFile?1:.4},children:e.savingFile?s.jsxs(s.Fragment,{children:[s.jsx(lb,{}),"Saving…"]}):c?s.jsx(s.Fragment,{children:"✓ Saved"}):s.jsx(s.Fragment,{children:"Save"})}),s.jsx("button",{onClick:()=>t({type:"SET_AUTO_SAVE",enabled:!e.autoSave}),title:e.autoSave?"Auto-save on":"Auto-save off",style:{...P,background:e.autoSave?`${n.accent}20`:n.btnBg,color:e.autoSave?n.accent:n.textMuted,padding:"0 6px",fontSize:10,fontWeight:600,letterSpacing:"0.03em",border:`1px solid ${e.autoSave?n.accent:n.btnBorder}`},children:"AUTO"}),s.jsxs("button",{onClick:()=>t({type:"TOGGLE_DASHBOARD_MODE"}),disabled:!e.activeFile,title:e.dashboardMode?"Switch to editor mode":"Switch to dashboard mode",style:{...P,background:e.dashboardMode?`${n.accent}20`:n.btnBg,color:e.dashboardMode?n.accent:n.textSecondary,border:`1px solid ${e.dashboardMode?n.accent:n.btnBorder}`,opacity:e.activeFile?1:.4,padding:"0 8px"},children:[s.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:e.dashboardMode?s.jsx("path",{d:"M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 8.75 4.25V1.5Z"}):s.jsx("path",{d:"M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v3.585a.746.746 0 0 1 0 .83v8.085A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25Zm1.75-.25a.25.25 0 0 0-.25.25V5h13V1.75a.25.25 0 0 0-.25-.25ZM1.5 6.5v7.75c0 .138.112.25.25.25H7v-8Zm7 8h5.75a.25.25 0 0 0 .25-.25V6.5h-6Z"})}),e.dashboardMode?"Editor":"Dashboard"]}),s.jsx("div",{style:{width:1,height:20,background:n.headerBorder}})]}),s.jsxs("div",{ref:g,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>{e.activeFile&&x(_=>!_)},disabled:!e.activeFile,onMouseEnter:()=>O(!0),onMouseLeave:()=>O(!1),title:"Share / export",style:{...P,height:30,padding:"0 14px",borderRadius:999,background:(I||N)&&e.activeFile?"#2a2a30":"#1a1a1a",color:"#ffffff",border:"1px solid #1a1a1a",opacity:e.activeFile?1:.4,gap:6},children:[s.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M5.5 10.75a.75.75 0 0 1 .75-.75h3.5a.75.75 0 0 1 0 1.5h-3.5a.75.75 0 0 1-.75-.75Zm0-3a.75.75 0 0 1 .75-.75h3.5a.75.75 0 0 1 0 1.5h-3.5a.75.75 0 0 1-.75-.75ZM3 3.75A1.75 1.75 0 0 1 4.75 2h6.586c.464 0 .909.184 1.237.513l1.914 1.914c.329.328.513.773.513 1.237v6.586A1.75 1.75 0 0 1 13.25 14h-8.5A1.75 1.75 0 0 1 3 12.25Z"})}),"Share",s.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"currentColor",style:{marginLeft:1,opacity:.7},children:s.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),N&&s.jsx("div",{style:{position:"absolute",top:32,right:0,zIndex:200,background:n.modalBg,border:`1px solid ${n.cellBorder}`,borderRadius:8,boxShadow:"0 8px 24px rgba(0,0,0,0.3)",padding:4,minWidth:160,display:"flex",flexDirection:"column",gap:2},children:s.jsx(ab,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{ob(e.notebookTitle||"dashboard",e.cells),x(!1)}})})]})]})]})}function ab({label:e,description:t,t:n,onClick:r}){const[o,i]=f.useState(!1);return s.jsxs("button",{onClick:r,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:o?n.btnHover:"transparent",border:"none",borderRadius:5,cursor:"pointer",padding:"6px 10px",textAlign:"left",display:"flex",flexDirection:"column",gap:1,transition:"background 0.12s"},children:[s.jsx("span",{style:{fontSize:12,fontWeight:500,color:n.textPrimary,fontFamily:n.font},children:e}),s.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:t})]})}function lb(){return s.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",style:{animation:"spin 0.8s linear infinite"},children:[s.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"}),s.jsx("circle",{cx:"6",cy:"6",r:"4.5",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"14 7"})]})}function cb(e){return e.toTimeString().slice(0,8)}function db(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function Eb(){const{state:e,dispatch:t}=fe(),n=ie[e.themeMode],[r,o]=f.useState(!1),i=e.queryLog.filter(l=>l.error),a=l=>t({type:"SET_DEV_PANEL_TAB",tab:l});return s.jsxs("div",{style:{height:e.devPanelOpen?180:0,flexShrink:0,background:n.sidebarBg,borderTop:`1px solid ${n.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden",transition:"height 0.2s ease",position:"relative"},children:[e.devPanelOpen&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{height:32,flexShrink:0,display:"flex",alignItems:"center",borderBottom:`1px solid ${n.headerBorder}`,padding:"0 8px",gap:2},children:[["logs","errors"].map(l=>s.jsx(ub,{label:l==="errors"?`Errors${i.length>0?` (${i.length})`:""}`:`Logs (${e.queryLog.length})`,active:e.devPanelTab===l,onClick:()=>a(l),t:n},l)),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:()=>t({type:"SET_CELLS",cells:e.cells}),title:"Clear logs",style:{background:"transparent",borderTop:"none",borderLeft:"none",borderRight:"none",borderBottom:"none",cursor:"pointer",color:n.textMuted,fontSize:11,fontFamily:n.font,padding:"2px 6px",borderRadius:4},children:"Clear"})]}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[e.devPanelTab==="logs"&&(e.queryLog.length===0?s.jsx(Iu,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(l=>s.jsx(mu,{entry:l,t:n},l.id))),e.devPanelTab==="errors"&&(i.length===0?s.jsx(Iu,{t:n,message:"No errors."}):[...i].reverse().map(l=>s.jsx(mu,{entry:l,t:n},l.id)))]})]}),s.jsxs("button",{onClick:()=>t({type:"TOGGLE_DEV_PANEL"}),onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),title:e.devPanelOpen?"Close panel":"Open dev panel",style:{position:"absolute",bottom:e.devPanelOpen?4:-28,right:8,height:22,padding:"0 8px",borderRadius:"4px 4px 0 0",borderTop:`1px solid ${n.headerBorder}`,borderLeft:`1px solid ${n.headerBorder}`,borderRight:`1px solid ${n.headerBorder}`,borderBottom:e.devPanelOpen?`1px solid ${n.sidebarBg}`:`1px solid ${n.headerBorder}`,background:r?n.btnHover:n.sidebarBg,color:n.textMuted,cursor:"pointer",fontSize:11,fontFamily:n.font,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s, bottom 0.2s ease",zIndex:10},children:[s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:s.jsx("path",{d:e.devPanelOpen?"M1 7l4-4 4 4":"M1 3l4 4 4-4",strokeWidth:"1.5",stroke:"currentColor",fill:"none"})}),"Dev"]})]})}function ub({label:e,active:t,onClick:n,t:r}){const[o,i]=f.useState(!1);return s.jsx("button",{onClick:n,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:"transparent",borderTop:"none",borderLeft:"none",borderRight:"none",borderBottom:t?`2px solid ${r.accent}`:"2px solid transparent",cursor:"pointer",color:t?r.textPrimary:o?r.textSecondary:r.textMuted,fontSize:12,fontFamily:r.font,fontWeight:t?500:400,padding:"4px 8px",height:32,transition:"color 0.15s"},children:e})}function Iu({t:e,message:t}){return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:e.textMuted,fontSize:12,fontFamily:e.font,fontStyle:"italic"},children:t})}function mu({entry:e,t}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"3px 12px",fontSize:11,fontFamily:t.fontMono,color:e.error?t.error:t.textSecondary,borderLeft:e.error?`2px solid ${t.error}`:"2px solid transparent"},children:[s.jsx("span",{style:{color:t.textMuted,flexShrink:0},children:cb(e.ts)}),s.jsx("span",{style:{flexShrink:0,color:t.textPrimary,maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.cellName}),e.error?s.jsx("span",{style:{color:t.error,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.error}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{style:{color:t.textMuted},children:[e.rows.toLocaleString()," rows"]}),s.jsx("span",{style:{color:t.textMuted},children:db(e.time)})]})]})}function Tb({onOpenFile:e}){const{state:t,dispatch:n}=fe(),r=ie[t.themeMode],o=t.files.slice(0,3);return s.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",background:r.appBg,padding:40,overflow:"auto"},children:s.jsxs("div",{style:{maxWidth:720,width:"100%",display:"flex",flexDirection:"column",alignItems:"center",gap:48},children:[s.jsxs("div",{style:{textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[s.jsx("div",{style:{width:72,height:72,borderRadius:16,background:"linear-gradient(135deg, #5b8cff 0%, #7c5cff 60%, #4a34a8 100%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 8px 32px rgba(91,140,255,0.28)"},children:s.jsx("span",{style:{color:"#fff",fontSize:26,fontWeight:800,fontFamily:r.fontMono,letterSpacing:"-1px"},children:"DQL"})}),s.jsxs("div",{children:[s.jsx("h1",{style:{fontSize:32,fontWeight:700,color:r.textPrimary,fontFamily:r.font,marginBottom:8,letterSpacing:"-0.5px"},children:"DQL Notebook"}),s.jsx("p",{style:{fontSize:15,color:r.textSecondary,fontFamily:r.font,letterSpacing:"0.02em"},children:"Analytics as Code"})]})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16,width:"100%"},children:[s.jsx(Ou,{title:"New Notebook",description:"Start a fresh analysis with an empty notebook.",icon:s.jsx(Sb,{}),accent:r.accent,onClick:()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}),t:r}),s.jsx(fb,{recentFiles:o,onOpenFile:e,t:r}),s.jsx(Ou,{title:"New Block",description:"Create a reusable SQL block file.",icon:s.jsx(hb,{}),accent:"#ffc857",onClick:()=>n({type:"OPEN_NEW_BLOCK_MODAL"}),t:r})]}),s.jsxs("div",{style:{width:"100%",borderRadius:10,border:`1px solid ${r.cellBorder}`,padding:"16px 20px",background:r.cellBg},children:[s.jsx("div",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.08em",textTransform:"uppercase",color:r.textMuted,fontFamily:r.font,marginBottom:12},children:"Quick Tips"}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:8},children:[["Shift + Enter","Run cell"],["⌘ + S","Save notebook"],["⌘ + B","Toggle sidebar"],["⌘ + D","Dashboard mode"],["⌘ + Shift + Enter","Run all cells"],["⌘ + J","Toggle dev panel"],["Click +","Add a new cell"],["Drag handle","Reorder cells"]].map(([i,a])=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("kbd",{style:{background:r.pillBg,border:`1px solid ${r.cellBorder}`,borderRadius:4,padding:"2px 6px",fontSize:11,fontFamily:r.fontMono,color:r.textSecondary,whiteSpace:"nowrap"},children:i}),s.jsx("span",{style:{fontSize:12,color:r.textMuted,fontFamily:r.font},children:a})]},i))})]})]})})}function Ou({title:e,description:t,icon:n,accent:r,onClick:o,t:i}){const[a,l]=f.useState(!1);return s.jsxs("button",{onClick:o,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{background:a?i.cellBg:"transparent",border:`1px solid ${a?r:i.cellBorder}`,borderRadius:10,padding:"20px 16px",cursor:"pointer",textAlign:"left",display:"flex",flexDirection:"column",gap:10,transition:"border-color 0.2s, background 0.2s, box-shadow 0.2s",boxShadow:a?`0 0 0 1px ${r}30, 0 4px 16px rgba(0,0,0,0.15)`:"none"},children:[s.jsx("div",{style:{width:36,height:36,borderRadius:8,background:`${r}18`,display:"flex",alignItems:"center",justifyContent:"center",color:r},children:n}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:13,fontWeight:600,color:i.textPrimary,fontFamily:i.font,marginBottom:4},children:e}),s.jsx("div",{style:{fontSize:12,color:i.textSecondary,fontFamily:i.font,lineHeight:1.5},children:t})]})]})}function fb({recentFiles:e,onOpenFile:t,t:n}){const[r,o]=f.useState(!1);return s.jsxs("div",{onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),style:{background:r?n.cellBg:"transparent",border:`1px solid ${r?n.textMuted:n.cellBorder}`,borderRadius:10,padding:"20px 16px",textAlign:"left",display:"flex",flexDirection:"column",gap:10,transition:"border-color 0.2s, background 0.2s"},children:[s.jsx("div",{style:{width:36,height:36,borderRadius:8,background:`${n.warning}18`,display:"flex",alignItems:"center",justifyContent:"center",color:n.warning},children:s.jsx(Rb,{})}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,fontFamily:n.font,marginBottom:8},children:"Open Recent"}),e.length===0?s.jsx("div",{style:{fontSize:12,color:n.textMuted,fontFamily:n.font,fontStyle:"italic"},children:"No recent files."}):s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:e.map(i=>s.jsx(pb,{file:i,onClick:()=>t(i),t:n},i.path))})]})]})}function pb({file:e,onClick:t,t:n}){const[r,o]=f.useState(!1);return s.jsx("button",{onClick:t,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),style:{background:"transparent",border:"none",cursor:"pointer",color:r?n.accent:n.textSecondary,fontSize:12,fontFamily:n.font,textAlign:"left",padding:"2px 0",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",transition:"color 0.15s"},children:e.name.replace(/\.(dqlnb|dql)$/,"")})}function Sb(){return s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 8.75 4.25V1.5ZM8.75 5.5h2.836L10.25 3.664V4.25c0 .138.112.25.25.25H8.75Zm.5 3.25a.75.75 0 0 1 .75.75v.75h.75a.75.75 0 0 1 0 1.5H10v.75a.75.75 0 0 1-1.5 0V11.5H7.75a.75.75 0 0 1 0-1.5H8.5V9.5a.75.75 0 0 1 .75-.75Z"})})}function Rb(){return s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm7-3.25v2.992l2.028.812a.75.75 0 0 1-.557 1.392l-2.5-1A.751.751 0 0 1 7 8.25v-3.5a.75.75 0 0 1 1.5 0Z"})})}function hb(){return s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M8.75 1.75a.75.75 0 0 0-1.5 0V6.5H2.75a.75.75 0 0 0 0 1.5H7.25v4.75a.75.75 0 0 0 1.5 0V8H13.25a.75.75 0 0 0 0-1.5H8.75V1.75Z"})})}const Nu=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class Ao{constructor(t,n,r=0,o=t.length,i,a){this.test=a,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=t.iterRange(r,o),this.bufferStart=r,this.normalize=i?l=>i(Nu(l)):Nu,this.query=this.normalize(n)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return Sm(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let t=this.peek();if(t<0)return this.done=!0,this;let n=Om(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=Rm(t);let o=this.normalize(n);if(o.length)for(let i=0,a=r;;i++){let l=o.charCodeAt(i),c=this.match(l,a,this.bufferPos+this.bufferStart);if(i==o.length-1){if(c)return this.value=c,this;break}a==r&&i<n.length&&n.charCodeAt(i)==l&&a++}}}match(t,n,r){let o=null;for(let i=0;i<this.matches.length;i+=2){let a=this.matches[i],l=!1;this.query.charCodeAt(a)==t&&(a==this.query.length-1?o={from:this.matches[i+1],to:r}:(this.matches[i]++,l=!0)),l||(this.matches.splice(i,2),i-=2)}return this.query.charCodeAt(0)==t&&(this.query.length==1?o={from:n,to:r}:this.matches.push(1,n)),o&&this.test&&!this.test(o.from,o.to,this.buffer,this.bufferStart)&&(o=null),o}}typeof Symbol<"u"&&(Ao.prototype[Symbol.iterator]=function(){return this});const XR={from:-1,to:-1,match:/.*/.exec("")},Ud="gm"+(/x/.unicode==null?"":"u");class zR{constructor(t,n,r,o=0,i=t.length){if(this.text=t,this.to=i,this.curLine="",this.done=!1,this.value=XR,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new KR(t,n,r,o,i);this.re=new RegExp(n,Ud+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.iter=t.iter();let a=t.lineAt(o);this.curLineStart=a.from,this.matchPos=Ai(t,o),this.getLine(this.curLineStart)}getLine(t){this.iter.next(t),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let t=this.matchPos-this.curLineStart;;){this.re.lastIndex=t;let n=this.matchPos<=this.to&&this.re.exec(this.curLine);if(n){let r=this.curLineStart+n.index,o=r+n[0].length;if(this.matchPos=Ai(this.text,o+(r==o?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<o||r>this.value.to)&&(!this.test||this.test(r,o,n)))return this.value={from:r,to:o,match:n},this;t=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),t=0;else return this.done=!0,this}}}const Tl=new WeakMap;class hr{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let o=Tl.get(t);if(!o||o.from>=r||o.to<=n){let l=new hr(n,t.sliceString(n,r));return Tl.set(t,l),l}if(o.from==n&&o.to==r)return o;let{text:i,from:a}=o;return a>n&&(i=t.sliceString(n,a)+i,a=n),o.to<r&&(i+=t.sliceString(o.to,r)),Tl.set(t,new hr(a,i)),new hr(n,i.slice(n-a,r-a))}}class KR{constructor(t,n,r,o,i){this.text=t,this.to=i,this.done=!1,this.value=XR,this.matchPos=Ai(t,o),this.re=new RegExp(n,Ud+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=hr.get(t,o,this.chunkEnd(o+5e3))}chunkEnd(t){return t>=this.to?this.to:this.text.lineAt(t).to}next(){for(;;){let t=this.re.lastIndex=this.matchPos-this.flat.from,n=this.re.exec(this.flat.text);if(n&&!n[0]&&n.index==t&&(this.re.lastIndex=t+1,n=this.re.exec(this.flat.text)),n){let r=this.flat.from+n.index,o=r+n[0].length;if((this.flat.to>=this.to||n.index+n[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,o,n)))return this.value={from:r,to:o,match:n},this.matchPos=Ai(this.text,o+(r==o?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=hr.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(zR.prototype[Symbol.iterator]=KR.prototype[Symbol.iterator]=function(){return this});function Ab(e){try{return new RegExp(e,Ud),!0}catch{return!1}}function Ai(e,t){if(t>=e.length)return t;let n=e.lineAt(t),r;for(;t<n.to&&(r=n.text.charCodeAt(t-n.from))>=56320&&r<57344;)t++;return t}const Ib=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:o}=Tm(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return o.then(i=>{let a=i&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(i.elements.line.value);if(!a){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,d,E,u]=a,T=E?+E.slice(1):0,p=d?+d:l.number;if(d&&u){let S=p/100;c&&(S=S*(c=="-"?-1:1)+l.number/t.doc.lines),p=Math.round(t.doc.lines*S)}else d&&c&&(p=p*(c=="-"?-1:1)+l.number);let h=t.doc.line(Math.max(1,Math.min(t.doc.lines,p))),A=Rt.cursor(h.from+Math.max(0,Math.min(T,h.length)));e.dispatch({effects:[r,je.scrollIntoView(A.from,{y:"center"})],selection:A})}),!0},mb=({state:e,dispatch:t})=>{let{selection:n}=e,r=Rt.create(n.ranges.map(o=>e.wordAt(o.head)||Rt.cursor(o.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function Ob(e,t){let{main:n,ranges:r}=e.selection,o=e.wordAt(n.head),i=o&&o.from==n.from&&o.to==n.to;for(let a=!1,l=new Ao(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(a)return null;l=new Ao(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),a=!0}else{if(a&&r.some(c=>c.from==l.value.from))continue;if(i){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const Nb=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(i=>i.from===i.to))return mb({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(i=>e.sliceDoc(i.from,i.to)!=r))return!1;let o=Ob(e,r);return o?(t(e.update({selection:e.selection.addRange(Rt.range(o.from,o.to),!1),effects:je.scrollIntoView(o.to)})),!0):!1},zn=hm.define({combine(e){return Am(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new Fb(t),scrollToMatch:t=>je.scrollIntoView(t)})}});function gb(e){return e?[zn.of(e),bc]:bc}class qR{constructor(t){this.search=t.search,this.caseSensitive=!!t.caseSensitive,this.literal=!!t.literal,this.regexp=!!t.regexp,this.replace=t.replace||"",this.valid=!!this.search&&(!this.regexp||Ab(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord,this.test=t.test}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
|
|
612
|
-
`:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new bb(this):new Cb(this)}getCursor(t,n=0,r){let o=t.doc?t:mp.create({doc:t});return r==null&&(r=o.doc.length),this.regexp?Tr(this,o,n,r):ur(this,o,n,r)}}class JR{constructor(t){this.spec=t}}function xb(e,t,n){return(r,o,i,a)=>{if(n&&!n(r,o,i,a))return!1;let l=r>=a&&o<=a+i.length?i.slice(r-a,o-a):t.doc.sliceString(r,o);return e(l,t,r,o)}}function ur(e,t,n,r){let o;return e.wholeWord&&(o=yb(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(o=xb(e.test,t,o)),new Ao(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:i=>i.toLowerCase(),o)}function yb(e,t){return(n,r,o,i)=>((i>n||i+o.length<r)&&(i=Math.max(0,n-2),o=e.sliceString(i,Math.min(e.length,r+2))),(t(Ii(o,n-i))!=ln.Word||t(mi(o,n-i))!=ln.Word)&&(t(mi(o,r-i))!=ln.Word||t(Ii(o,r-i))!=ln.Word))}class Cb extends JR{constructor(t){super(t)}nextMatch(t,n,r){let o=ur(this.spec,t,r,t.doc.length).nextOverlapping();if(o.done){let i=Math.min(t.doc.length,n+this.spec.unquoted.length);o=ur(this.spec,t,0,i).nextOverlapping()}return o.done||o.value.from==n&&o.value.to==r?null:o.value}prevMatchInRange(t,n,r){for(let o=r;;){let i=Math.max(n,o-1e4-this.spec.unquoted.length),a=ur(this.spec,t,i,o),l=null;for(;!a.nextOverlapping().done;)l=a.value;if(l)return l;if(i==n)return null;o-=1e4}}prevMatch(t,n,r){let o=this.prevMatchInRange(t,0,n);return o||(o=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),o&&(o.from!=n||o.to!=r)?o:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=ur(this.spec,t,0,t.doc.length),o=[];for(;!r.next().done;){if(o.length>=n)return null;o.push(r.value)}return o}highlight(t,n,r,o){let i=ur(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!i.next().done;)o(i.value.from,i.value.to)}}function Lb(e,t,n){return(r,o,i)=>(!n||n(r,o,i))&&e(i[0],t,r,o)}function Tr(e,t,n,r){let o;return e.wholeWord&&(o=_b(t.charCategorizer(t.selection.main.head))),e.test&&(o=Lb(e.test,t,o)),new zR(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:o},n,r)}function Ii(e,t){return e.slice(Op(e,t,!1),t)}function mi(e,t){return e.slice(t,Op(e,t))}function _b(e){return(t,n,r)=>!r[0].length||(e(Ii(r.input,r.index))!=ln.Word||e(mi(r.input,r.index))!=ln.Word)&&(e(mi(r.input,r.index+r[0].length))!=ln.Word||e(Ii(r.input,r.index+r[0].length))!=ln.Word)}class bb extends JR{nextMatch(t,n,r){let o=Tr(this.spec,t,r,t.doc.length).next();return o.done&&(o=Tr(this.spec,t,0,n).next()),o.done?null:o.value}prevMatchInRange(t,n,r){for(let o=1;;o++){let i=Math.max(n,r-o*1e4),a=Tr(this.spec,t,i,r),l=null;for(;!a.next().done;)l=a.value;if(l&&(i==n||l.from>i+10))return l;if(i==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let o=r.length;o>0;o--){let i=+r.slice(0,o);if(i>0&&i<t.match.length)return t.match[i]+r.slice(o)}return n})}matchAll(t,n){let r=Tr(this.spec,t,0,t.doc.length),o=[];for(;!r.next().done;){if(o.length>=n)return null;o.push(r.value)}return o}highlight(t,n,r,o){let i=Tr(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!i.next().done;)o(i.value.from,i.value.to)}}const Io=$i.define(),Bd=$i.define(),dn=Ip.define({create(e){return new fl(_c(e).create(),null)},update(e,t){for(let n of t.effects)n.is(Io)?e=new fl(n.value.create(),e.panel):n.is(Bd)&&(e=new fl(e.query,n.value?Fd:null));return e},provide:e=>fm.from(e,t=>t.panel)});class fl{constructor(t,n){this.query=t,this.panel=n}}const Db=Mn.mark({class:"cm-searchMatch"}),Mb=Mn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),vb=Im.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(dn))}update(e){let t=e.state.field(dn);(t!=e.startState.field(dn)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Mn.none;let{view:n}=this,r=new mm;for(let o=0,i=n.visibleRanges,a=i.length;o<a;o++){let{from:l,to:c}=i[o];for(;o<a-1&&c>i[o+1].from-500;)c=i[++o].to;e.highlight(n.state,l,c,(d,E)=>{let u=n.state.selection.ranges.some(T=>T.from==d&&T.to==E);r.add(d,E,u?Mb:Db)})}return r.finish()}},{decorations:e=>e.decorations});function Ho(e){return t=>{let n=t.state.field(dn,!1);return n&&n.query.spec.valid?e(t,n):eh(t)}}const Oi=Ho((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let o=Rt.single(r.from,r.to),i=e.state.facet(zn);return e.dispatch({selection:o,effects:[kd(e,r),i.scrollToMatch(o.main,e)],userEvent:"select.search"}),ZR(e),!0}),Ni=Ho((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,o=t.prevMatch(n,r,r);if(!o)return!1;let i=Rt.single(o.from,o.to),a=e.state.facet(zn);return e.dispatch({selection:i,effects:[kd(e,o),a.scrollToMatch(i.main,e)],userEvent:"select.search"}),ZR(e),!0}),Pb=Ho((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:Rt.create(n.map(r=>Rt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),wb=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:o}=n.main,i=[],a=0;for(let l=new Ao(e.doc,e.sliceDoc(r,o));!l.next().done;){if(i.length>1e3)return!1;l.value.from==r&&(a=i.length),i.push(Rt.range(l.value.from,l.value.to))}return t(e.update({selection:Rt.create(i,a),userEvent:"select.search.matches"})),!0},gu=Ho((e,{query:t})=>{let{state:n}=e,{from:r,to:o}=n.selection.main;if(n.readOnly)return!1;let i=t.nextMatch(n,r,r);if(!i)return!1;let a=i,l=[],c,d,E=[];a.from==r&&a.to==o&&(d=n.toText(t.getReplacement(a)),l.push({from:a.from,to:a.to,insert:d}),a=t.nextMatch(n,a.from,a.to),E.push(je.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+".")));let u=e.state.changes(l);return a&&(c=Rt.single(a.from,a.to).map(u),E.push(kd(e,a)),E.push(n.facet(zn).scrollToMatch(c.main,e))),e.dispatch({changes:u,selection:c,effects:E,userEvent:"input.replace"}),!0}),Ub=Ho((e,{query:t})=>{if(e.state.readOnly)return!1;let n=t.matchAll(e.state,1e9).map(o=>{let{from:i,to:a}=o;return{from:i,to:a,insert:t.getReplacement(o)}});if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:je.announce.of(r),userEvent:"input.replace.all"}),!0});function Fd(e){return e.state.facet(zn).createPanel(e)}function _c(e,t){var n,r,o,i,a;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let d=e.facet(zn);return new qR({search:((n=t==null?void 0:t.literal)!==null&&n!==void 0?n:d.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t==null?void 0:t.caseSensitive)!==null&&r!==void 0?r:d.caseSensitive,literal:(o=t==null?void 0:t.literal)!==null&&o!==void 0?o:d.literal,regexp:(i=t==null?void 0:t.regexp)!==null&&i!==void 0?i:d.regexp,wholeWord:(a=t==null?void 0:t.wholeWord)!==null&&a!==void 0?a:d.wholeWord})}function QR(e){let t=Ap(e,Fd);return t&&t.dom.querySelector("[main-field]")}function ZR(e){let t=QR(e);t&&t==e.root.activeElement&&t.select()}const eh=e=>{let t=e.state.field(dn,!1);if(t&&t.panel){let n=QR(e);if(n&&n!=e.root.activeElement){let r=_c(e.state,t.query.spec);r.valid&&e.dispatch({effects:Io.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Bd.of(!0),t?Io.of(_c(e.state,t.query.spec)):$i.appendConfig.of(bc)]});return!0},th=e=>{let t=e.state.field(dn,!1);if(!t||!t.panel)return!1;let n=Ap(e,Fd);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Bd.of(!1)}),!0},Bb=[{key:"Mod-f",run:eh,scope:"editor search-panel"},{key:"F3",run:Oi,shift:Ni,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:Oi,shift:Ni,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:th,scope:"editor search-panel"},{key:"Mod-Shift-l",run:wb},{key:"Mod-Alt-g",run:Ib},{key:"Mod-d",run:Nb,preventDefault:!0}];class Fb{constructor(t){this.view=t;let n=this.query=t.state.field(dn).query.spec;this.commit=this.commit.bind(this),this.searchField=et("input",{value:n.search,placeholder:$e(t,"Find"),"aria-label":$e(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=et("input",{value:n.replace,placeholder:$e(t,"Replace"),"aria-label":$e(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=et("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=et("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=et("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(o,i,a){return et("button",{class:"cm-button",name:o,onclick:i,type:"button"},a)}this.dom=et("div",{onkeydown:o=>this.keydown(o),class:"cm-search"},[this.searchField,r("next",()=>Oi(t),[$e(t,"next")]),r("prev",()=>Ni(t),[$e(t,"previous")]),r("select",()=>Pb(t),[$e(t,"all")]),et("label",null,[this.caseField,$e(t,"match case")]),et("label",null,[this.reField,$e(t,"regexp")]),et("label",null,[this.wordField,$e(t,"by word")]),...t.state.readOnly?[]:[et("br"),this.replaceField,r("replace",()=>gu(t),[$e(t,"replace")]),r("replaceAll",()=>Ub(t),[$e(t,"replace all")])],et("button",{name:"close",onclick:()=>th(t),"aria-label":$e(t,"close"),type:"button"},["×"])])}commit(){let t=new qR({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});t.eq(this.query)||(this.query=t,this.view.dispatch({effects:Io.of(t)}))}keydown(t){Nm(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?Ni:Oi)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),gu(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(Io)&&!r.value.eq(this.query)&&this.setQuery(r.value)}setQuery(t){this.query=t,this.searchField.value=t.search,this.replaceField.value=t.replace,this.caseField.checked=t.caseSensitive,this.reField.checked=t.regexp,this.wordField.checked=t.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(zn).top}}function $e(e,t){return e.state.phrase(t)}const Cs=30,Ls=/[\s\.,:;?!]/;function kd(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),o=e.state.doc.lineAt(n).to,i=Math.max(r.from,t-Cs),a=Math.min(o,n+Cs),l=e.state.sliceDoc(i,a);if(i!=r.from){for(let c=0;c<Cs;c++)if(!Ls.test(l[c+1])&&Ls.test(l[c])){l=l.slice(c);break}}if(a!=o){for(let c=l.length-1;c>l.length-Cs;c--)if(!Ls.test(l[c-1])&&Ls.test(l[c])){l=l.slice(0,c);break}}return je.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const kb=je.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),bc=[dn,pm.low(vb),kb],jb=3e4,gi="application/dql-semantic-ref";let _s=[],xu=0,mo=null;function Gb(e){z.trackUsage(e),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:e}}))}async function yu(){if(Date.now()<xu&&_s.length>0)return _s;const e=await fetch(`${window.location.origin}/api/semantic-completions`);if(!e.ok)throw new Error(`Failed to load semantic completions: HTTP ${e.status}`);const t=await e.json();return _s=Array.isArray(t.completions)?t.completions:[],xu=Date.now()+jb,_s}function nh(e,t,n){const r=n??e.state.selection.main.from;e.dispatch({changes:{from:r,to:n??e.state.selection.main.to,insert:t},selection:{anchor:r+t.length}}),e.focus()}function Hb(e){mo=e}function Yb(e){mo===e&&(mo=null)}function Wb(e){return mo?(nh(mo,e),!0):!1}function $b(e,t,n){const r=n?e.posAtCoords(n)??e.state.selection.main.from:e.state.selection.main.from;nh(e,t,r)}function Cu(e,t,n){return{label:e.name,detail:e.type==="metric"?"@metric":"@dim",type:e.type==="metric"?"function":"variable",info:`${e.label}${e.description?`
|
|
613
|
-
${e.description}`:""}${e.sql?`
|
|
614
|
-
${e.sql}`:""}`,apply(r){const i=r.state.sliceDoc(n,n+1)===")"?e.name:`${e.name})`;r.dispatch({changes:{from:t,to:n,insert:i},selection:{anchor:t+i.length}}),Gb(e.name)}}}function Vb(e){return{from:e,options:[{label:"@metric(",detail:"semantic metric",type:"function",apply(t,n,r,o){t.dispatch({changes:{from:r,to:o,insert:"@metric("},selection:{anchor:r+8}})}},{label:"@dim(",detail:"semantic dimension",type:"function",apply(t,n,r,o){t.dispatch({changes:{from:r,to:o,insert:"@dim("},selection:{anchor:r+5}})}}]}}const Xb=async e=>{const{state:t,pos:n}=e,r=t.sliceDoc(Math.max(0,n-120),n),o=/@metric\(([^)]*)$/i.exec(r);if(o){const l=o[1].trim().toLowerCase(),c=n-o[1].length,d=(await yu()).filter(E=>E.type==="metric").filter(E=>!l||E.name.toLowerCase().includes(l)||E.label.toLowerCase().includes(l)||(E.domain??"").toLowerCase().includes(l)||E.tags.some(u=>u.toLowerCase().includes(l))).slice(0,50);return{from:c,options:d.map(E=>Cu(E,c,n)),validFor:/^[\w-]*$/}}const i=/@dim\(([^)]*)$/i.exec(r);if(i){const l=i[1].trim().toLowerCase(),c=n-i[1].length,d=(await yu()).filter(E=>E.type==="dimension").filter(E=>!l||E.name.toLowerCase().includes(l)||E.label.toLowerCase().includes(l)||(E.domain??"").toLowerCase().includes(l)||E.tags.some(u=>u.toLowerCase().includes(l))).slice(0,50);return{from:c,options:d.map(E=>Cu(E,c,n)),validFor:/^[\w-]*$/}}const a=/@([md][a-z_]*)?$/i.exec(r);return a?Vb(n-a[0].length):(e.explicit,null)};function rh(e){if(!e)return null;try{const t=JSON.parse(e);return(t.type==="metric"||t.type==="dimension")&&t.name&&t.reference?{type:t.type,name:t.name,reference:t.reference}:null}catch{return null}}function zb(e){const t=e.match(/LINE\s+(\d+)/i);if(t){const o=parseInt(t[1],10),i=e.match(/\n(\s*)\^/),a=i?i[1].length+1:1;return{line:o,col:a}}const n=e.match(/at line\s+(\d+),?\s*column\s+(\d+)/i);if(n)return{line:parseInt(n[1],10),col:parseInt(n[2],10)};const r=e.match(/line\s+(\d+)/i);return r?{line:parseInt(r[1],10),col:1}:null}const Qs=$i.define(),Kb=Ip.define({create(){return Mn.none},update(e,t){for(const n of t.effects)if(n.is(Qs)){if(!n.value)return Mn.none;const{from:r,to:o,message:i}=n.value;return Mn.set([Mn.mark({class:"cm-sql-error",attributes:{title:i}}).range(r,o)])}return e},provide:e=>je.decorations.from(e)}),qb=gm.define([{tag:xe.keyword,color:"var(--sql-keyword)",fontWeight:"600"},{tag:[xe.controlKeyword,xe.moduleKeyword],color:"var(--sql-keyword)",fontWeight:"600"},{tag:[xe.string,xe.special(xe.string)],color:"var(--sql-string)"},{tag:xe.number,color:"var(--sql-number)"},{tag:xe.bool,color:"var(--sql-number)",fontWeight:"600"},{tag:xe.null,color:"var(--sql-number)",fontWeight:"600"},{tag:[xe.comment,xe.lineComment,xe.blockComment,xe.docComment],color:"var(--sql-comment)",fontStyle:"italic"},{tag:[xe.function(xe.variableName),xe.function(xe.propertyName)],color:"var(--sql-function)"},{tag:[xe.typeName,xe.className],color:"var(--sql-type)"},{tag:xe.operator,color:"var(--sql-punctuation)"},{tag:xe.punctuation,color:"var(--sql-punctuation)"},{tag:xe.bracket,color:"var(--sql-punctuation)"},{tag:[xe.variableName,xe.name,xe.propertyName,xe.attributeName],color:"var(--sql-ident)"},{tag:xe.invalid,color:"var(--color-status-error)"}]),Jb=je.baseTheme({".cm-sql-error":{textDecoration:"underline wavy var(--color-status-error)",textUnderlineOffset:"3px",background:"color-mix(in srgb, var(--color-status-error) 10%, transparent)"}});function oh(e){return je.theme({"&":{background:"var(--color-bg-sunken)",color:"var(--color-text-primary)"},".cm-content":{caretColor:"var(--color-text-primary)"},".cm-cursor":{borderLeftColor:"var(--color-text-primary)"},".cm-selectionBackground":{background:"color-mix(in srgb, var(--color-accent-blue) 30%, transparent)"},"&.cm-focused .cm-selectionBackground":{background:"color-mix(in srgb, var(--color-accent-blue) 30%, transparent)"},".cm-gutters":{background:"var(--color-bg-sunken)",color:"var(--color-text-tertiary)",border:"none",borderRight:"1px solid var(--color-border-subtle)"},".cm-activeLineGutter":{background:"var(--color-bg-hover)"},".cm-activeLine":{background:"var(--color-bg-hover)"},".cm-matchingBracket":{background:"color-mix(in srgb, var(--color-accent-blue) 18%, transparent)",outline:"1px solid var(--color-accent-blue)"},".cm-foldPlaceholder":{background:"var(--color-bg-tertiary)",border:"1px solid var(--color-border-subtle)",color:"var(--color-text-secondary)",borderRadius:3,padding:"0 4px"},".cm-tooltip":{background:"var(--color-bg-card)",border:"1px solid var(--color-border-primary)",color:"var(--color-text-primary)",borderRadius:6,boxShadow:"0 4px 12px color-mix(in srgb, var(--color-bg-primary) 40%, transparent)"},".cm-tooltip.cm-tooltip-autocomplete":{"& > ul > li":{padding:"3px 8px"},"& > ul > li[aria-selected]":{background:"color-mix(in srgb, var(--color-accent-blue) 20%, transparent)",color:"var(--color-accent-blue)"}},".cm-searchMatch":{background:"color-mix(in srgb, var(--color-status-warning) 25%, transparent)",outline:"1px solid var(--color-status-warning)"},".cm-searchMatch.cm-searchMatch-selected":{background:"color-mix(in srgb, var(--color-status-warning) 50%, transparent)"},".cm-panels":{background:"var(--color-bg-secondary)",borderTop:"1px solid var(--color-border-subtle)"},".cm-panel":{padding:"6px 8px"},".cm-panel input":{background:"var(--color-bg-sunken)",border:"1px solid var(--color-border-subtle)",color:"var(--color-text-primary)",borderRadius:4,padding:"2px 6px",fontSize:12},".cm-panel button":{background:"var(--color-bg-tertiary)",border:"1px solid var(--color-border-subtle)",color:"var(--color-text-primary)",borderRadius:4,padding:"2px 8px",cursor:"pointer",fontSize:12,marginLeft:4}},{dark:e})}const Qb=oh(!0),Zb=oh(!1);function e1(e){return e==="midnight"||e==="obsidian"||e==="dark"}function jd({value:e,onChange:t,onRun:n,themeMode:r,autoFocus:o,schema:i,errorMessage:a,editorRef:l,wrap:c=!0}){const d=ie[r],E=f.useRef(null),u=f.useRef(null),[T,p]=f.useState(!1),h=f.useRef(n),A=f.useRef(t),S=f.useRef(new xm);return h.current=n,A.current=t,f.useEffect(()=>{l&&(l.current={undo:()=>{u.current&&Cm(u.current)},redo:()=>{u.current&&ym(u.current)},resetTo:R=>{const m=u.current;m&&m.dispatch({changes:{from:0,to:m.state.doc.length,insert:R}})}})}),f.useEffect(()=>{if(!E.current)return;const R=Lm.of([{key:"Shift-Enter",run:()=>(h.current(),!0)},{key:"Ctrl-Enter",mac:"Cmd-Enter",run:()=>(h.current(),!0)},{key:"Ctrl-/",mac:"Cmd-/",run:_m},bm,...Dm,...Mm,...vm,...Bb,...Pm,...wm]),m=je.updateListener.of(y=>{y.docChanged&&A.current(y.state.doc.toString())}),I=je.domEventHandlers({focus:(y,w)=>{Hb(w)},blur:(y,w)=>{Yb(w)}}),O=je.theme({"&":{background:"var(--color-bg-surface)",color:"var(--color-text-primary)",fontFamily:"var(--font-mono)",fontSize:"13px",minHeight:"80px",maxHeight:"480px"},".cm-scroller":{overflow:"auto",fontFamily:"inherit"},".cm-content":{padding:"10px 0",minHeight:"80px",color:"var(--color-text-primary)"},".cm-focused":{outline:"none"},".cm-editor":{border:"none"},".cm-gutters":{minWidth:40},".cm-foldGutter":{cursor:"pointer"}}),N=i?hs({schema:i,upperCaseKeywords:!1}):hs({upperCaseKeywords:!1}),x=[R,m,I,O,S.current.of(N),Um({closeOnBlur:!1,override:[Xb]}),Bm(),Fm(),km(),jm(),Gm(),Hm(),Ym(),Wm(),...c?[je.lineWrapping]:[],gb({top:!0}),Kb,Jb,$m(qb),e1(r)?Qb:Zb],g=mp.create({doc:e,extensions:x}),C=new je({state:g,parent:E.current});return u.current=C,o&&C.focus(),()=>{C.destroy(),u.current=null}},[r]),f.useEffect(()=>{const R=u.current;if(!R)return;const m=i?hs({schema:i,upperCaseKeywords:!1}):hs({upperCaseKeywords:!1});R.dispatch({effects:S.current.reconfigure(m)})},[i]),f.useEffect(()=>{const R=u.current;if(!R)return;const m=R.state.doc.toString();m!==e&&R.dispatch({changes:{from:0,to:m.length,insert:e}})},[e]),f.useEffect(()=>{const R=u.current;if(!R)return;if(!a){R.dispatch({effects:Qs.of(null)});return}const m=zb(a),I=R.state.doc;if(m&&m.line>=1&&m.line<=I.lines){const O=I.line(m.line),N=O.from+Math.max(0,m.col-1),x=Math.max(N+1,O.to);R.dispatch({effects:Qs.of({from:Math.min(N,I.length),to:Math.min(x,I.length),message:a})})}else if(I.lines>=1){const O=I.line(1);R.dispatch({effects:Qs.of({from:O.from,to:Math.max(O.from+1,O.to),message:a})})}},[a]),s.jsx("div",{onDragOver:R=>{R.dataTransfer.types.includes(gi)&&(R.preventDefault(),p(!0))},onDragLeave:()=>p(!1),onDrop:R=>{const m=u.current;if(!m)return;const I=rh(R.dataTransfer.getData(gi));I&&(R.preventDefault(),p(!1),$b(m,I.reference,{x:R.clientX,y:R.clientY}),z.trackUsage(I.name),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:I.name}})))},style:{background:"var(--color-bg-surface)",minHeight:80,border:T?`1px solid ${d.accent}`:"1px solid transparent",borderRadius:6,transition:"border-color 0.15s"},children:s.jsx("div",{ref:E,style:{minHeight:80}})})}jd.displayName="SQLCellEditor";function t1(e,t){const n=e.split(`
|
|
615
|
-
`),r=[];let o=0;for(;o<n.length;){const i=n[o],a=i.match(/^(#{1,6})\s+(.+)$/);if(a){const l=a[1].length,c=a[2],E=[28,22,18,16,14,13][l-1];r.push(s.jsx("div",{style:{fontSize:E,fontWeight:l<=2?700:600,color:t.textPrimary,fontFamily:t.font,lineHeight:1.3,marginBottom:l===1?12:8,marginTop:o>0?l===1?16:10:0,borderBottom:l===1?`1px solid ${t.cellBorder}`:void 0,paddingBottom:l===1?8:void 0},children:Zr(c,t)},o)),o++;continue}if(/^[-*_]{3,}$/.test(i.trim())){r.push(s.jsx("hr",{style:{border:"none",borderTop:`1px solid ${t.cellBorder}`,margin:"12px 0"}},o)),o++;continue}if(i.startsWith("> ")){r.push(s.jsx("div",{style:{borderLeft:`3px solid ${t.textMuted}`,paddingLeft:12,marginLeft:4,color:t.textSecondary,fontStyle:"italic",fontFamily:t.fontSerif,fontSize:14},children:Zr(i.slice(2),t)},o)),o++;continue}if(i.startsWith("```")){const l=[];for(o++;o<n.length&&!n[o].startsWith("```");)l.push(n[o]),o++;r.push(s.jsx("pre",{style:{background:"var(--color-bg-surface)",border:"1px solid var(--color-border-subtle)",borderRadius:6,padding:"10px 12px",fontSize:12,fontFamily:"var(--font-mono)",color:"var(--color-text-primary)",overflow:"auto",margin:"8px 0",lineHeight:1.6},children:l.join(`
|
|
616
|
-
`)},o)),o++;continue}if(/^[-*+]\s/.test(i)){const l=o,c=[];for(;o<n.length&&/^[-*+]\s/.test(n[o]);)c.push(n[o].replace(/^[-*+]\s/,"")),o++;r.push(s.jsx("ul",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:c.map((d,E)=>s.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:Zr(d,t)},E))},`ul-${l}`));continue}if(/^\d+\.\s/.test(i)){const l=o,c=[];for(;o<n.length&&/^\d+\.\s/.test(n[o]);)c.push(n[o].replace(/^\d+\.\s/,"")),o++;r.push(s.jsx("ol",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:c.map((d,E)=>s.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:Zr(d,t)},E))},`ol-${l}`));continue}if(!i.trim()){r.push(s.jsx("div",{style:{height:8}},o)),o++;continue}r.push(s.jsx("p",{style:{fontSize:14,lineHeight:1.7,fontFamily:t.fontSerif,color:t.textSecondary,marginBottom:6},children:Zr(i,t)},o)),o++}return r}function Zr(e,t){const n=[];let r=e,o=0;for(;r.length>0;){const i=r.match(/\*{3}(.+?)\*{3}/),a=r.match(/\*{2}(.+?)\*{2}/),l=r.match(/\*(.+?)\*/),c=r.match(/`(.+?)`/),d=r.match(/\[(.+?)\]\((.+?)\)/),E=[i?{match:i,type:"boldItalic"}:null,a?{match:a,type:"bold"}:null,l?{match:l,type:"italic"}:null,c?{match:c,type:"code"}:null,d?{match:d,type:"link"}:null].filter(Boolean);if(E.length===0){n.push(s.jsx(_e.Fragment,{children:r},o++));break}const u=E.reduce((p,h)=>(p.match.index??0)<(h.match.index??0)?p:h),T=u.match.index??0;switch(T>0&&n.push(s.jsx(_e.Fragment,{children:r.slice(0,T)},o++)),u.type){case"boldItalic":n.push(s.jsx("strong",{style:{fontStyle:"italic"},children:u.match[1]},o++));break;case"bold":n.push(s.jsx("strong",{children:u.match[1]},o++));break;case"italic":n.push(s.jsx("em",{children:u.match[1]},o++));break;case"code":n.push(s.jsx("code",{style:{background:"var(--color-bg-surface)",border:"1px solid var(--color-border-subtle)",borderRadius:4,padding:"1px 5px",fontSize:"0.9em",fontFamily:"var(--font-mono)",color:"var(--color-accent-blue)"},children:u.match[1]},o++));break;case"link":n.push(s.jsx("a",{href:u.match[2],target:"_blank",rel:"noopener noreferrer",style:{color:t.accent,textDecoration:"underline"},children:u.match[1]},o++));break}r=r.slice(T+u.match[0].length)}return s.jsx(s.Fragment,{children:n})}function n1({value:e,onChange:t,onRun:n,themeMode:r}){const o=ie[r],[i,a]=f.useState(!1),l=f.useRef(null);f.useEffect(()=>{if(i&&l.current){l.current.focus();const u=l.current;u.style.height="auto",u.style.height=`${Math.max(u.scrollHeight,80)}px`}},[i]);const c=()=>{a(!1)},d=u=>{if(u.key==="Escape"&&a(!1),u.key==="Enter"&&u.shiftKey&&(u.preventDefault(),a(!1),n==null||n()),u.key==="Tab"){u.preventDefault();const T=u.currentTarget,p=T.selectionStart,h=T.selectionEnd,A=e.slice(0,p)+" "+e.slice(h);t(A),requestAnimationFrame(()=>{T.selectionStart=T.selectionEnd=p+2})}},E=u=>{t(u.target.value);const T=u.target;T.style.height="auto",T.style.height=`${Math.max(T.scrollHeight,80)}px`};return i?s.jsx("textarea",{ref:l,value:e,onChange:E,onBlur:c,onKeyDown:d,placeholder:"Write markdown here...",spellCheck:!1,style:{display:"block",width:"100%",minHeight:80,padding:"12px 16px",background:o.editorBg,color:o.textPrimary,border:"none",outline:"none",resize:"none",fontFamily:o.fontMono,fontSize:13,lineHeight:"20px",borderRadius:0,caretColor:o.accent}}):e.trim()?s.jsx("div",{onDoubleClick:()=>a(!0),title:"Double-click to edit",style:{padding:"12px 16px",cursor:"text",minHeight:48},children:t1(e,o)}):s.jsx("div",{onDoubleClick:()=>a(!0),style:{padding:"12px 16px",color:o.textMuted,fontFamily:o.font,fontSize:13,fontStyle:"italic",cursor:"text",minHeight:48,display:"flex",alignItems:"center"},children:"Double-click to add markdown..."})}function r1({cell:e,themeMode:t,onApplyParam:n}){const{dispatch:r}=fe(),o=ie[t],[i,a]=f.useState(!1),l=e.paramConfig??{paramType:"text",label:"Parameter",defaultValue:"",options:[]},c=e.paramValue??l.defaultValue,d=p=>{r({type:"UPDATE_CELL",id:e.id,updates:{paramConfig:{...l,...p}}})},E=p=>{r({type:"SET_PARAM_VALUE",id:e.id,value:p})},u=(l.options??[]).map(p=>p.trim()).filter(Boolean),T=e.name?`{{${e.name}}}`:null;return s.jsxs("div",{style:{background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderLeft:`3px solid ${o.warning}`,borderRadius:8,overflow:"hidden"},children:[i&&s.jsxs("div",{style:{background:o.tableHeaderBg,borderBottom:`1px solid ${o.cellBorder}`,padding:"12px 14px",display:"flex",flexDirection:"column",gap:10},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:2},children:[s.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",color:o.warning,fontFamily:o.fontMono,textTransform:"uppercase"},children:"Configure Parameter"}),s.jsx("button",{onClick:()=>a(!1),title:"Done",style:{background:o.warning,border:"none",borderRadius:5,cursor:"pointer",color:"#000",fontSize:11,fontWeight:700,fontFamily:o.font,padding:"3px 10px",display:"flex",alignItems:"center",gap:4},children:"✓ Done"})]}),s.jsxs("div",{style:{display:"flex",gap:10,flexWrap:"wrap"},children:[s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[s.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Variable name"}),s.jsx("input",{value:e.name??"",onChange:p=>r({type:"UPDATE_CELL",id:e.id,updates:{name:p.target.value||void 0}}),placeholder:"e.g. start_date",style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:12,fontFamily:o.fontMono,padding:"4px 7px",outline:"none"}})]}),s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[s.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Display label"}),s.jsx("input",{value:l.label,onChange:p=>d({label:p.target.value}),placeholder:"e.g. Start Date",style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:12,fontFamily:o.font,padding:"4px 7px",outline:"none"}})]}),s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 100px"},children:[s.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Type"}),s.jsxs("select",{value:l.paramType,onChange:p=>d({paramType:p.target.value}),style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:12,fontFamily:o.font,padding:"4px 7px",outline:"none"},children:[s.jsx("option",{value:"text",children:"Text"}),s.jsx("option",{value:"number",children:"Number"}),s.jsx("option",{value:"date",children:"Date"}),s.jsx("option",{value:"select",children:"Select"})]})]}),s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[s.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Default value"}),s.jsx("input",{type:l.paramType==="number"?"number":l.paramType==="date"?"date":"text",value:l.defaultValue,onChange:p=>d({defaultValue:p.target.value}),style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:12,fontFamily:o.font,padding:"4px 7px",outline:"none"}})]})]}),l.paramType==="select"&&s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3},children:[s.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Options (one per line)"}),s.jsx("textarea",{value:(l.options??[]).join(`
|
|
617
|
-
`),onChange:p=>d({options:p.target.value.split(`
|
|
618
|
-
`)}),rows:4,placeholder:`Option A
|
|
619
|
-
Option B
|
|
620
|
-
Option C`,style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:12,fontFamily:o.fontMono,padding:"5px 7px",outline:"none",resize:"vertical"}})]})]}),s.jsxs("div",{style:{padding:"12px 14px",display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[s.jsx("button",{onClick:()=>a(p=>!p),title:i?"Close config":"Configure parameter",style:{background:i?`${o.warning}18`:"transparent",border:`1px solid ${i?o.warning:o.cellBorder}`,borderRadius:5,cursor:"pointer",color:i?o.warning:o.textMuted,width:26,height:26,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,transition:"all 0.15s"},children:i?s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.749.749 0 1 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"})}):s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:s.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.385.506.792.704 1.218.315.675.111 1.422-.364 1.891l-.814.806c-.049.048-.098.147-.088.294.016.257.016.515 0 .772-.01.147.038.246.088.294l.814.806c.475.469.679 1.216.364 1.891a7.977 7.977 0 0 1-.704 1.217c-.428.61-1.176.807-1.82.63l-1.102-.302c-.067-.019-.177-.011-.3.071a5.909 5.909 0 0 1-.668.386c-.133.066-.194.158-.211.224l-.29 1.106c-.168.646-.715 1.196-1.458 1.26a8.006 8.006 0 0 1-1.402 0c-.743-.064-1.289-.614-1.458-1.26l-.289-1.106c-.018-.066-.079-.158-.212-.224a5.738 5.738 0 0 1-.668-.386c-.123-.082-.233-.09-.299-.071l-1.103.303c-.644.176-1.392-.021-1.82-.63a8.12 8.12 0 0 1-.704-1.218c-.315-.675-.111-1.422.363-1.891l.815-.806c.05-.048.098-.147.088-.294a6.214 6.214 0 0 1 0-.772c.01-.147-.038-.246-.088-.294l-.815-.806C.635 6.045.431 5.298.746 4.623a7.92 7.92 0 0 1 .704-1.217c.428-.61 1.176-.807 1.82-.63l1.102.302c.067.019.177.011.3-.071.214-.143.437-.272.668-.386.133-.066.194-.158.211-.224l.29-1.106C6.009.645 6.556.095 7.299.03 7.53.01 7.764 0 8 0Zm-.571 1.525c-.036.003-.108.036-.137.146l-.289 1.105c-.147.561-.549.967-.998 1.189-.173.086-.34.183-.5.29-.417.278-.97.423-1.529.27l-1.103-.303c-.109-.03-.175.016-.195.045-.22.312-.412.644-.573.99-.014.031-.021.11.059.19l.815.806c.411.406.562.957.53 1.456a4.709 4.709 0 0 0 0 .582c.032.499-.119 1.05-.53 1.456l-.815.806c-.081.08-.073.159-.059.19.162.346.353.677.573.989.02.03.085.076.195.046l1.102-.303c.56-.153 1.113-.008 1.53.27.161.107.328.204.501.29.447.222.85.629.997 1.189l.289 1.105c.029.109.101.143.137.146a6.6 6.6 0 0 0 1.142 0c.036-.003.108-.036.137-.146l.289-1.105c.147-.561.549-.967.998-1.189.173-.086.34-.183.5-.29.417-.278.97-.423 1.529-.27l1.103.303c.109.029.175-.016.195-.045.22-.313.411-.644.573-.99.014-.031.021-.11-.059-.19l-.815-.806c-.411-.406-.562-.957-.53-1.456a4.709 4.709 0 0 0 0-.582c-.032-.499.119-1.05.53-1.456l.815-.806c.081-.08.073-.159.059-.19a6.464 6.464 0 0 0-.573-.989c-.02-.03-.085-.076-.195-.046l-1.102.303c-.56.153-1.113.008-1.53-.27a4.44 4.44 0 0 0-.501-.29c-.447-.222-.85-.629-.997-1.189l-.289-1.105c-.029-.11-.101-.143-.137-.146a6.6 6.6 0 0 0-1.142 0ZM8 5.5a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5ZM8 7a1 1 0 1 0 0 2 1 1 0 0 0 0-2Z"})})}),s.jsx("span",{style:{fontSize:13,fontWeight:500,fontFamily:o.font,color:o.textSecondary,flexShrink:0},children:l.label}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[l.paramType==="select"?s.jsx("select",{value:c,onChange:p=>E(p.target.value),style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:5,color:o.textPrimary,fontSize:13,fontFamily:o.font,padding:"5px 10px",outline:"none",minWidth:160},children:u.length===0?s.jsx("option",{value:"",children:"— no options configured —"}):u.map(p=>s.jsx("option",{value:p,children:p},p))}):s.jsx("input",{type:l.paramType,value:c,onChange:p=>E(p.target.value),style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:5,color:o.textPrimary,fontSize:13,fontFamily:l.paramType==="number"?o.fontMono:o.font,padding:"5px 10px",outline:"none",minWidth:160}}),T&&s.jsx("span",{style:{fontSize:10,fontFamily:o.fontMono,color:o.warning,opacity:.8},children:T})]}),c&&s.jsx("span",{style:{fontSize:12,fontFamily:o.fontMono,color:o.textPrimary,background:`${o.warning}18`,border:`1px solid ${o.warning}40`,borderRadius:4,padding:"2px 8px",flexShrink:0},children:c}),e.name&&n&&s.jsx("button",{onClick:()=>n(e.name),title:`Re-run cells that use {{${e.name}}}`,style:{background:o.warning,border:"none",borderRadius:5,cursor:"pointer",color:"#000",fontSize:11,fontWeight:600,fontFamily:o.font,padding:"4px 12px",flexShrink:0,transition:"opacity 0.15s"},children:"Apply"})]})]})}function o1({cell:e,themeMode:t,title:n,subtitle:r,color:o,badge:i}){const a=ie[t];return s.jsx(mR,{typeLabel:n,typeColor:o,idleBorder:a.cellBorder,background:a.cellBg,headerBackground:`${a.tableHeaderBg}80`,title:e.name?s.jsx("span",{style:{fontSize:12,fontFamily:a.fontMono,color:a.textSecondary},children:e.name}):void 0,actions:i?s.jsx("span",{style:{fontSize:9,fontFamily:a.fontMono,fontWeight:600,letterSpacing:"0.1em",color:a.textMuted,textTransform:"uppercase",padding:"2px 6px",border:`1px solid ${a.cellBorder}`,borderRadius:3},children:i}):void 0,children:s.jsx("div",{style:{padding:"12px 14px",fontSize:12,color:a.textSecondary,lineHeight:1.5,fontFamily:a.font},children:r})})}function s1(e){return e.type==="param"?"param":e.type.toUpperCase()}function i1({cells:e,index:t,content:n,themeMode:r,onInsertHandle:o}){const i=ie[r],[a,l]=f.useState(!1),c=f.useRef(null),d=f.useMemo(()=>e.slice(0,t).filter(T=>T.name&&T.name.trim().length>0),[e,t]),E=f.useMemo(()=>B0(n),[n]);f.useEffect(()=>{if(!a)return;const T=p=>{var h;(h=c.current)!=null&&h.contains(p.target)||l(!1)};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[a]);const u=E.length===0?"df":E.length===1?`df: ${E[0]}`:`df: ${E[0]} +${E.length-1}`;return s.jsxs("div",{ref:c,style:{position:"relative",flexShrink:0},children:[s.jsxs("button",{onClick:()=>l(T=>!T),title:"Insert an upstream dataframe handle ({{name}})",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:10,fontFamily:i.fontMono,fontWeight:600,letterSpacing:"0.04em",color:E.length>0?i.accent:i.textMuted,background:E.length>0?`${i.accent}14`:"transparent",border:`1px solid ${E.length>0?`${i.accent}55`:i.btnBorder}`,borderRadius:4,padding:"1px 6px",cursor:"pointer",textTransform:"lowercase",transition:"border-color 0.15s, color 0.15s"},children:[u,s.jsx("span",{style:{fontSize:8,opacity:.7},children:"▾"})]}),a&&s.jsxs("div",{style:{position:"absolute",top:"calc(100% + 4px)",left:0,zIndex:20,minWidth:220,maxWidth:280,background:i.cellBg,border:`1px solid ${i.cellBorder}`,borderRadius:6,boxShadow:"0 6px 16px rgba(0,0,0,0.25)",padding:4,display:"flex",flexDirection:"column",gap:2},children:[s.jsx("div",{style:{fontSize:9,fontFamily:i.font,fontWeight:700,letterSpacing:"0.1em",color:i.textMuted,textTransform:"uppercase",padding:"4px 8px 2px"},children:"Upstream dataframes"}),d.length===0&&s.jsx("div",{style:{fontSize:11,fontFamily:i.font,color:i.textMuted,padding:"6px 8px 8px",lineHeight:1.4},children:"No named upstream cells yet. Name a cell (click its header) to expose it here."}),d.map(T=>{const p=T.name?E.includes(T.name):!1;return s.jsxs("button",{onClick:()=>{T.name&&o(T.name),l(!1)},style:{display:"flex",alignItems:"center",gap:8,padding:"5px 8px",background:p?`${i.accent}14`:"transparent",border:"none",borderRadius:4,cursor:"pointer",textAlign:"left",color:i.textPrimary,fontFamily:i.fontMono,fontSize:11},onMouseEnter:h=>{p||(h.currentTarget.style.background=i.tableRowHover)},onMouseLeave:h=>{p||(h.currentTarget.style.background="transparent")},children:[s.jsx("span",{style:{fontSize:9,fontFamily:i.fontMono,fontWeight:700,color:i.textMuted,minWidth:36},children:s1(T)}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T.name}),p&&s.jsx("span",{style:{fontSize:9,color:i.accent,fontWeight:700,letterSpacing:"0.08em"},children:"IN USE"})]},T.id)})]})]})}const a1=/date|time|_at$|_on$|timestamp/i;function l1(e){return typeof e=="number"||typeof e=="string"&&e!==""&&!isNaN(Number(e))}function Gd(e,t){if(a1.test(e))return"date";const n=t.slice(0,40).map(o=>o[e]).filter(o=>o!=null);return n.length===0?"string":n.every(o=>typeof o=="boolean")?"bool":n.every(o=>typeof o=="object")?"json":n.filter(l1).length/n.length>.8?"numeric":"string"}function sh(e){return e==="numeric"?"measure":e==="date"?"temporal":"dimension"}const c1=[25,50,100,500];function Dc(e){return typeof e=="number"?!0:typeof e=="string"?!isNaN(Number(e))&&e.trim()!=="":!1}function d1(e){switch(e){case"numeric":return{icon:"#",color:"#79c0ff"};case"date":return{icon:"D",color:"#e3b341"};case"bool":return{icon:"B",color:"#a371f7"};case"json":return{icon:"{}",color:"#ff7b72"};case"string":default:return{icon:"A",color:"#56d364"}}}function ih(e){return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function E1(e,t){return e==null?1:t==null?-1:Dc(e)&&Dc(t)?Number(e)-Number(t):String(e).localeCompare(String(t))}function u1(e,t){const n=a=>a.includes(",")||a.includes('"')||a.includes(`
|
|
621
|
-
`)?`"${a.replace(/"/g,'""')}"`:a,r=e.columns.map(n).join(","),o=e.rows.map(a=>e.columns.map(l=>n(ih(a[l]))).join(",")),i=[r,...o].join(`
|
|
622
|
-
`);ah(i,"export.csv","text/csv")}function T1(e,t){const n=JSON.stringify(e.rows,null,2);ah(n,"export.json","application/json")}function ah(e,t,n){const r=new Blob([e],{type:n}),o=URL.createObjectURL(r),i=document.createElement("a");i.href=o,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o)}function f1({dir:e,color:t}){return e?s.jsx("svg",{width:"8",height:"10",viewBox:"0 0 8 10",fill:t,style:{marginLeft:3,flexShrink:0},children:e==="asc"?s.jsx("path",{d:"M4 0L7 4H1L4 0Z"}):s.jsx("path",{d:"M4 10L1 6H7L4 10Z"})}):s.jsxs("svg",{width:"8",height:"10",viewBox:"0 0 8 10",fill:t,opacity:.3,style:{marginLeft:3,flexShrink:0},children:[s.jsx("path",{d:"M4 0L7 3.5H1L4 0Z"}),s.jsx("path",{d:"M4 10L1 6.5H7L4 10Z"})]})}function Kn({result:e,themeMode:t}){const n=ie[t],[r,o]=f.useState(null),[i,a]=f.useState(null),[l,c]=f.useState(null),[d,E]=f.useState(""),[u,T]=f.useState(50),[p,h]=f.useState(0),A=f.useCallback(C=>{i===C?l==="asc"?c("desc"):l==="desc"?(a(null),c(null)):c("asc"):(a(C),c("asc")),h(0)},[i,l]),S=f.useMemo(()=>{if(!d.trim())return e.rows;const C=d.toLowerCase();return e.rows.filter(y=>e.columns.some(w=>{const v=y[w];return v==null?!1:String(v).toLowerCase().includes(C)}))},[e.rows,e.columns,d]),R=f.useMemo(()=>{if(!i||!l)return S;const C=[...S];return C.sort((y,w)=>{const v=E1(y[i],w[i]);return l==="desc"?-v:v}),C},[S,i,l]),m=f.useMemo(()=>{const C=new Map;for(const y of e.columns)C.set(y,Gd(y,e.rows));return C},[e.columns,e.rows]),[I,O]=f.useState(!1),N=Math.max(1,Math.ceil(R.length/u)),x=Math.min(p,N-1),g=R.slice(x*u,(x+1)*u);return e.columns.length===0?s.jsx("div",{style:{padding:"12px 16px",color:n.textMuted,fontSize:12,fontFamily:n.font,fontStyle:"italic"},children:"Query executed successfully. No columns to display."}):s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 8px",borderBottom:`1px solid ${n.tableBorder}`,background:`${n.tableHeaderBg}60`,flexWrap:"wrap"},children:[s.jsxs("div",{style:{position:"relative",flex:"0 1 200px",minWidth:120},children:[s.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:n.textMuted,style:{position:"absolute",left:6,top:6},children:s.jsx("path",{d:"M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"})}),s.jsx("input",{value:d,onChange:C=>{E(C.target.value),h(0)},placeholder:"Filter rows...",style:{width:"100%",background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:4,color:n.textPrimary,fontSize:11,fontFamily:n.font,padding:"3px 8px 3px 22px",outline:"none"}}),d&&s.jsx("button",{onClick:()=>E(""),style:{position:"absolute",right:4,top:3,background:"none",border:"none",color:n.textMuted,cursor:"pointer",fontSize:12,padding:"0 2px"},children:"×"})]}),s.jsxs("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:[d?`${R.length} of ${e.rows.length}`:`${e.rows.length}`," rows"]}),s.jsx("div",{style:{flex:1}}),s.jsx(Lu,{label:"CSV",onClick:()=>u1(e),t:n}),s.jsx(Lu,{label:"JSON",onClick:()=>T1(e),t:n}),s.jsx("select",{value:u,onChange:C=>{T(Number(C.target.value)),h(0)},style:{background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:3,color:n.textSecondary,fontSize:10,fontFamily:n.font,padding:"2px 4px",outline:"none"},children:c1.map(C=>s.jsxs("option",{value:C,children:[C," / page"]},C))}),N>1&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[s.jsx(ir,{disabled:x===0,onClick:()=>h(0),t:n,children:"«"}),s.jsx(ir,{disabled:x===0,onClick:()=>h(x-1),t:n,children:"‹"}),s.jsxs("span",{style:{fontSize:10,color:n.textSecondary,fontFamily:n.font,padding:"0 4px"},children:[x+1,"/",N]}),s.jsx(ir,{disabled:x>=N-1,onClick:()=>h(x+1),t:n,children:"›"}),s.jsx(ir,{disabled:x>=N-1,onClick:()=>h(N-1),t:n,children:"»"})]})]}),s.jsx("div",{style:{maxHeight:440,overflow:"auto",position:"relative"},onScroll:C=>O(C.target.scrollTop>0),children:s.jsxs("table",{style:{width:"100%",borderCollapse:"separate",borderSpacing:0,tableLayout:"auto",fontSize:12.5,fontFamily:n.fontMono},children:[s.jsx("thead",{children:s.jsx("tr",{children:e.columns.map(C=>{const y=m.get(C)??"string",w=y==="numeric";return s.jsx("th",{onClick:()=>A(C),style:{background:n.tableHeaderBg,color:n.textSecondary,fontWeight:600,fontSize:11,textAlign:w?"right":"left",padding:"8px 14px",borderBottom:`1px solid ${n.tableBorder}`,minWidth:80,maxWidth:320,whiteSpace:"nowrap",position:"sticky",top:0,zIndex:1,fontFamily:n.font,letterSpacing:"0.03em",overflow:"hidden",textOverflow:"ellipsis",cursor:"pointer",userSelect:"none",boxShadow:I?"0 2px 4px -2px rgba(0,0,0,0.18)":"none",transition:"background 0.1s, box-shadow 0.18s"},children:s.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6,justifyContent:w?"flex-end":"flex-start"},children:[(()=>{const v=d1(y);return s.jsx("span",{title:y,style:{fontSize:9,fontFamily:n.fontMono,fontWeight:700,color:v.color,background:`${v.color}15`,border:`1px solid ${v.color}40`,borderRadius:3,padding:"0 4px",minWidth:14,textAlign:"center",lineHeight:"14px",flexShrink:0},children:v.icon})})(),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:C}),s.jsx(f1,{dir:i===C?l:null,color:i===C?n.accent:n.textMuted})]})},C)})})}),s.jsx("tbody",{children:g.map((C,y)=>{const w=r===y,B=y%2===1?n.tableHeaderBg:"transparent";return s.jsx("tr",{onMouseEnter:()=>o(y),onMouseLeave:()=>o(null),style:{transition:"background 0.1s"},children:e.columns.map(b=>{const L=C[b],D=L==null,M=Dc(L);return s.jsx("td",{style:{padding:"7px 14px",borderBottom:`1px solid ${n.tableBorder}`,background:w?n.tableRowHover:B,color:D?n.textMuted:n.textPrimary,fontStyle:D?"italic":"normal",fontVariantNumeric:M?"tabular-nums":"normal",textAlign:M?"right":"left",whiteSpace:"nowrap",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",transition:"background 0.1s"},children:D?"—":ih(L)},b)})},y)})})]})}),s.jsxs("div",{style:{padding:"5px 10px",color:n.textMuted,fontSize:10,fontFamily:n.font,borderTop:`1px solid ${n.tableBorder}`,background:`${n.tableHeaderBg}60`,display:"flex",alignItems:"center",gap:4},children:[N>1&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[s.jsx(ir,{disabled:x===0,onClick:()=>h(x-1),t:n,children:"‹"}),p1(N,x).map((C,y)=>C==="…"?s.jsx("span",{style:{color:n.textMuted,fontSize:10,padding:"0 2px"},children:"…"},`gap-${y}`):s.jsx("button",{onClick:()=>h(C-1),style:{background:C-1===x?`${n.accent}20`:"transparent",border:"none",color:C-1===x?n.accent:n.textSecondary,fontSize:10,fontFamily:n.font,fontWeight:C-1===x?700:400,padding:"1px 6px",borderRadius:3,cursor:"pointer",minWidth:20},children:C},C)),s.jsx(ir,{disabled:x>=N-1,onClick:()=>h(x+1),t:n,children:"›"})]}),s.jsx("div",{style:{flex:1}}),s.jsxs("span",{style:{fontSize:10,color:n.textSecondary,fontFamily:n.font,marginLeft:6,whiteSpace:"nowrap"},children:[R.length.toLocaleString()," ",R.length===1?"row":"rows",d&&e.rows.length!==R.length&&` of ${e.rows.length.toLocaleString()}`]})]})]})}function p1(e,t){if(e<=7)return Array.from({length:e},(o,i)=>i+1);const n=t+1,r=[1];n>3&&r.push("…");for(let o=Math.max(2,n-1);o<=Math.min(e-1,n+1);o++)r.push(o);return n<e-2&&r.push("…"),r.push(e),r}function Lu({label:e,onClick:t,t:n}){const[r,o]=f.useState(!1);return s.jsxs("button",{onClick:t,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),style:{background:r?n.btnHover:"transparent",border:`1px solid ${r?n.btnBorder:"transparent"}`,borderRadius:3,cursor:"pointer",color:r?n.textSecondary:n.textMuted,fontSize:10,fontFamily:n.font,fontWeight:600,padding:"2px 6px",transition:"all 0.15s",display:"flex",alignItems:"center",gap:3},children:[s.jsxs("svg",{width:"9",height:"9",viewBox:"0 0 16 16",fill:"currentColor",children:[s.jsx("path",{d:"M2.75 14A1.75 1.75 0 0 1 1 12.25v-2.5a.75.75 0 0 1 1.5 0v2.5c0 .138.112.25.25.25h10.5a.25.25 0 0 0 .25-.25v-2.5a.75.75 0 0 1 1.5 0v2.5A1.75 1.75 0 0 1 13.25 14Z"}),s.jsx("path",{d:"M7.25 7.689V2a.75.75 0 0 1 1.5 0v5.689l1.97-1.97a.749.749 0 1 1 1.06 1.06l-3.25 3.25a.749.749 0 0 1-1.06 0L4.22 6.779a.749.749 0 1 1 1.06-1.06l1.97 1.97Z"})]}),e]})}function ir({disabled:e,onClick:t,children:n,t:r}){return s.jsx("button",{disabled:e,onClick:t,style:{background:"transparent",border:"none",cursor:e?"default":"pointer",color:e?r.textMuted:r.textSecondary,fontSize:12,fontFamily:r.font,padding:"0 3px",opacity:e?.4:1,transition:"opacity 0.1s"},children:n})}const da=[{value:"bar",label:"Bar"},{value:"grouped-bar",label:"Grouped Bar"},{value:"stacked-bar",label:"Stacked Bar"},{value:"line",label:"Line"},{value:"area",label:"Area"},{value:"scatter",label:"Scatter"},{value:"pie",label:"Pie"},{value:"donut",label:"Donut"},{value:"heatmap",label:"Heatmap"},{value:"histogram",label:"Histogram"},{value:"funnel",label:"Funnel"},{value:"waterfall",label:"Waterfall"},{value:"gauge",label:"Gauge"},{value:"kpi",label:"KPI"}],S1=/date|time|at|day|month|year/i,lh=/^(label|name|category|status|type|group)$/i,ch=/^(value|count|total|revenue|amount|sum|avg|price|quantity|sales)$/i;function En(e){return typeof e=="number"?!0:typeof e=="string"?e.trim()!==""&&!isNaN(Number(e)):!1}function R1(e){return typeof e=="string"||typeof e=="number"}const h1=new Set(["bar","line","area","pie","donut","scatter","heatmap","funnel","waterfall","histogram","gauge","stacked-bar","grouped-bar","kpi","table"]);function Cr(e,t){if(t!=null&&t.chart){const n=t.chart.toLowerCase().replace(/_/g,"-");if(h1.has(n))return n}return A1(e)}function A1(e){const{columns:t,rows:n}=e;if(t.length<2||n.length===0)return"table";const r=t[0],o=t[1],i=n.slice(0,5),a=i.every(u=>En(u[o])),l=i.every(u=>R1(u[r]));if(S1.test(r)&&a&&l)return"line";const c=t.find(u=>lh.test(u)),d=t.find(u=>ch.test(u));return c&&d&&i.every(T=>En(T[d]))?"bar":i.every(u=>En(u[r]))&&a&&t.length>=2?"scatter":t.length===2&&l&&a?"bar":"table"}const dh={default:["#388bfd","#56d364","#e3b341","#f78166","#a371f7","#39c5cf","#ffa657","#ff7b72","#89d185","#d2a8ff","#58a6ff","#3fb950"],warm:["#f85149","#f78166","#ffa657","#e3b341","#d29922","#db6d28","#ff7b72","#ffa198","#ffdfb6","#e6c174","#c4a35a","#b08c3e"],cool:["#388bfd","#58a6ff","#79c0ff","#39c5cf","#56d364","#3fb950","#a371f7","#d2a8ff","#bc8cff","#6cb6ff","#2ea043","#1f6feb"],mono:["#c9d1d9","#b1bac4","#8b949e","#6e7681","#484f58","#30363d","#21262d","#161b22","#a0a8b2","#9e9e9e","#757575","#616161"],pastel:["#b8d8f8","#b4e6c8","#f4e6a0","#f8c4a4","#d2b8f0","#a8e0e0","#f8d8a0","#f4b8b4","#c0e8c0","#e0d0f8","#a8d8f8","#b0e8b0"]},ke=dh.default;function Be(e){return Math.abs(e)>=1e6?`${(e/1e6).toFixed(1)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString(void 0,{maximumFractionDigits:2})}function I1(e){const t=new Date(e);if(!isNaN(t.getTime())){if(/^\d{4}-\d{2}-\d{2}/.test(e))return t.toLocaleDateString("en-US",{month:"short",day:"numeric"});if(/^\d{4}-\d{2}$/.test(e))return t.toLocaleDateString("en-US",{year:"numeric",month:"short"})}return String(e).length>8?String(e).slice(0,8):String(e)}function Ea(e,t){const n=(t!=null&&t.x&&e.columns.includes(t.x)?t.x:void 0)??e.columns.find(o=>lh.test(o))??e.columns[0],r=(t!=null&&t.y&&e.columns.includes(t.y)?t.y:void 0)??e.columns.find(o=>ch.test(o))??e.columns[1];return{labelCol:n,valueCol:r}}const kn=20;function Hd({result:e,themeMode:t,chartConfig:n}){const r=ie[t],[o,i]=f.useState(null),{labelCol:a,valueCol:l}=Ea(e,n),c=(n==null?void 0:n.maxItems)??kn,d=e.rows.slice(0,c).map(R=>({label:String(R[a]??""),value:Number(R[l]??0)})),E=e.rows.length>c,u=Math.max(...d.map(R=>R.value),1),T=28,p=120,h=6,A=12,S=d.length*(T+h)+A*2;return s.jsxs("div",{style:{padding:"8px 0"},children:[s.jsx("svg",{width:"100%",height:S,viewBox:`0 0 600 ${S}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:d.map((R,m)=>{const I=A+m*(T+h),O=600-p-84,N=Math.max(R.value/u*O,2),x=o===m;return s.jsxs("g",{onMouseEnter:()=>i(m),onMouseLeave:()=>i(null),style:{cursor:"default"},children:[s.jsx("text",{x:p-8,y:I+T/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:R.label.length>16?R.label.slice(0,15)+"…":R.label}),s.jsx("rect",{x:p,y:I,width:N,height:T,rx:3,fill:x?r.accentHover:r.accent,style:{transition:"fill 0.15s"}}),s.jsx("text",{x:p+N+6,y:I+T/2+4,textAnchor:"start",fontSize:11,fontFamily:r.fontMono,fill:r.textMuted,children:Be(R.value)})]},m)})}),E&&s.jsxs("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,fontStyle:"italic",padding:"4px 12px"},children:["Showing ",kn," of ",e.rows.length," rows"]})]})}function m1({result:e,themeMode:t,chartConfig:n}){const r=ie[t],[o,i]=f.useState(null),a=n!=null&&n.x&&e.columns.includes(n.x)?n.x:e.columns[0],l=e.rows.slice(0,5),c=e.columns.filter(R=>R!==a&&l.some(m=>En(m[R])));if(c.length===0)return s.jsx(Hd,{result:e,themeMode:t,chartConfig:n});const d=e.rows.slice(0,kn).map(R=>String(R[a]??"")),E=Math.max(...e.rows.slice(0,kn).flatMap(R=>c.map(m=>Math.abs(Number(R[m]??0)))),1),u=24,T=u/c.length,p=120,h=12,A=8,S=d.length*(u+A)+h*2;return s.jsxs("div",{style:{padding:"8px 0"},children:[s.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:c.map((R,m)=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[s.jsx("div",{style:{width:10,height:10,borderRadius:2,background:ke[m%ke.length]}}),s.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:R})]},R))}),s.jsx("svg",{width:"100%",height:S,viewBox:`0 0 600 ${S}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:d.map((R,m)=>{const I=h+m*(u+A),O=e.rows[m];return s.jsxs("g",{children:[s.jsx("text",{x:p-8,y:I+u/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:R.length>16?R.slice(0,15)+"…":R}),c.map((N,x)=>{const g=Number(O[N]??0),C=600-p-60,y=Math.max(Math.abs(g)/E*C,1),w=I+x*T,v=`${m}-${x}`;return s.jsxs("g",{onMouseEnter:()=>i(v),onMouseLeave:()=>i(null),children:[s.jsx("rect",{x:p,y:w,width:y,height:T-1,rx:2,fill:ke[x%ke.length],opacity:o===v?1:.85,style:{transition:"opacity 0.15s"}}),o===v&&s.jsx("text",{x:p+y+4,y:w+T/2+3,fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Be(g)})]},x)})]},m)})})]})}function O1({result:e,themeMode:t,chartConfig:n}){const r=ie[t],[o,i]=f.useState(null),a=n!=null&&n.x&&e.columns.includes(n.x)?n.x:e.columns[0],l=e.rows.slice(0,5),c=e.columns.filter(R=>R!==a&&l.some(m=>En(m[R])));if(c.length===0)return s.jsx(Hd,{result:e,themeMode:t,chartConfig:n});const d=e.rows.slice(0,kn),E=d.map(R=>String(R[a]??"")),u=Math.max(...d.map(R=>c.reduce((m,I)=>m+Math.abs(Number(R[I]??0)),0)),1),T=28,p=120,h=12,A=6,S=E.length*(T+A)+h*2;return s.jsxs("div",{style:{padding:"8px 0"},children:[s.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:c.map((R,m)=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[s.jsx("div",{style:{width:10,height:10,borderRadius:2,background:ke[m%ke.length]}}),s.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:R})]},R))}),s.jsx("svg",{width:"100%",height:S,viewBox:`0 0 600 ${S}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:E.map((R,m)=>{const I=h+m*(T+A),O=d[m],N=600-p-60;let x=p;return s.jsxs("g",{children:[s.jsx("text",{x:p-8,y:I+T/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:R.length>16?R.slice(0,15)+"…":R}),c.map((g,C)=>{const y=Math.abs(Number(O[g]??0)),w=Math.max(y/u*N,0),v=x;x+=w;const B=`${m}-${C}`;return s.jsxs("g",{onMouseEnter:()=>i(B),onMouseLeave:()=>i(null),children:[s.jsx("rect",{x:v,y:I,width:w,height:T,rx:C===0?3:0,fill:ke[C%ke.length],opacity:o===B?1:.85,style:{transition:"opacity 0.15s"}}),o===B&&w>30&&s.jsx("text",{x:v+w/2,y:I+T/2+4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:"#fff",fontWeight:600,children:Be(y)})]},C)})]},m)})})]})}function _u({result:e,themeMode:t,showArea:n}){const r=ie[t],[o,i]=f.useState(null),a=e.columns[0],l=e.columns[1],c=e.rows.map(L=>({label:String(L[a]??""),value:Number(L[l]??0)}));if(c.length<2)return null;const d=560,E=200,u=52,T=16,p=16,h=36,A=d-u-T,S=E-p-h,R=Math.min(...c.map(L=>L.value)),I=Math.max(...c.map(L=>L.value))-R||1,O=A/(c.length-1),N=L=>u+L*O,x=L=>p+S-(L-R)/I*S,g=c.map((L,D)=>({x:N(D),y:x(L.value)})),C=g.reduce((L,D,M)=>{if(M===0)return`M ${D.x},${D.y}`;const U=g[M-1],P=U.x+(D.x-U.x)/2;return`${L} C ${P},${U.y} ${P},${D.y} ${D.x},${D.y}`},""),y=`${C} L ${g[g.length-1].x},${p+S} L ${u},${p+S} Z`,w=5,v=Array.from({length:w+1},(L,D)=>{const M=R+I*D/w;return{val:M,y:x(M)}}),B=Math.ceil(c.length/8),b=c.filter((L,D)=>D%B===0||D===c.length-1);return s.jsx("div",{style:{position:"relative",padding:"8px 0"},children:s.jsxs("svg",{width:"100%",height:E,viewBox:`0 0 ${d} ${E}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},onMouseLeave:()=>i(null),children:[v.map((L,D)=>s.jsxs("g",{children:[s.jsx("line",{x1:u,y1:L.y,x2:u+A,y2:L.y,stroke:r.tableBorder,strokeWidth:.5}),s.jsx("text",{x:u-6,y:L.y+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Be(L.val)})]},D)),s.jsx("path",{d:y,fill:r.accent,opacity:n?.3:.15}),s.jsx("path",{d:C,fill:"none",stroke:r.accent,strokeWidth:2,strokeLinejoin:"round"}),g.map((L,D)=>s.jsx("circle",{cx:L.x,cy:L.y,r:3,fill:r.accent,style:{cursor:"crosshair"},onMouseEnter:()=>i({x:L.x,y:L.y,label:c[D].label,value:c[D].value})},D)),b.map((L,D)=>{const M=c.indexOf(L);return s.jsx("text",{x:N(M),y:p+S+16,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:I1(L.label)},D)}),s.jsx("line",{x1:u,y1:p,x2:u,y2:p+S,stroke:r.tableBorder,strokeWidth:1}),s.jsx("line",{x1:u,y1:p+S,x2:u+A,y2:p+S,stroke:r.tableBorder,strokeWidth:1}),o&&s.jsxs("g",{children:[s.jsx("rect",{x:o.x+8,y:o.y-20,width:90,height:32,rx:4,fill:r.cellBg,stroke:r.cellBorder,strokeWidth:1}),s.jsx("text",{x:o.x+13,y:o.y-8,fontSize:10,fontFamily:r.font,fill:r.textSecondary,children:o.label.length>10?o.label.slice(0,10)+"…":o.label}),s.jsx("text",{x:o.x+13,y:o.y+6,fontSize:11,fontFamily:r.fontMono,fill:r.textPrimary,fontWeight:600,children:Be(o.value)})]})]})})}function N1({result:e,themeMode:t,chartConfig:n}){const r=ie[t],[o,i]=f.useState(null),a=n!=null&&n.x&&e.columns.includes(n.x)?n.x:e.columns[0],l=n!=null&&n.y&&e.columns.includes(n.y)?n.y:e.columns[1],c=n!=null&&n.color&&e.columns.includes(n.color)?n.color:void 0,d=e.rows.slice(0,200).map(v=>({x:Number(v[a]??0),y:Number(v[l]??0),color:c?String(v[c]??""):void 0})),E=560,u=300,T=52,p=16,h=16,A=36,S=E-T-p,R=u-h-A,m=Math.min(...d.map(v=>v.x)),I=Math.max(...d.map(v=>v.x)),O=Math.min(...d.map(v=>v.y)),N=Math.max(...d.map(v=>v.y)),x=I-m||1,g=N-O||1,C=v=>T+(v-m)/x*S,y=v=>h+R-(v-O)/g*R,w=c?[...new Set(d.map(v=>v.color))]:[];return s.jsxs("div",{style:{padding:"8px 0"},children:[c&&w.length>0&&s.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:w.slice(0,12).map((v,B)=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:ke[B%ke.length]}}),s.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:v})]},v))}),s.jsxs("svg",{width:"100%",height:u,viewBox:`0 0 ${E} ${u}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:6},(v,B)=>{const b=O+g*B/5,L=y(b);return s.jsxs("g",{children:[s.jsx("line",{x1:T,y1:L,x2:T+S,y2:L,stroke:r.tableBorder,strokeWidth:.5}),s.jsx("text",{x:T-6,y:L+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Be(b)})]},B)}),Array.from({length:6},(v,B)=>{const b=m+x*B/5,L=C(b);return s.jsx("text",{x:L,y:h+R+16,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Be(b)},B)}),s.jsx("line",{x1:T,y1:h,x2:T,y2:h+R,stroke:r.tableBorder,strokeWidth:1}),s.jsx("line",{x1:T,y1:h+R,x2:T+S,y2:h+R,stroke:r.tableBorder,strokeWidth:1}),s.jsx("text",{x:T+S/2,y:u-2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:a}),s.jsx("text",{x:10,y:h+R/2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,transform:`rotate(-90, 10, ${h+R/2})`,children:l}),d.map((v,B)=>{const b=c?w.indexOf(v.color):0;return s.jsx("circle",{cx:C(v.x),cy:y(v.y),r:o===B?5:3.5,fill:ke[b%ke.length],opacity:o===B?1:.7,style:{cursor:"crosshair",transition:"r 0.1s, opacity 0.1s"},onMouseEnter:()=>i(B),onMouseLeave:()=>i(null)},B)}),o!==null&&s.jsxs("g",{children:[s.jsx("rect",{x:C(d[o].x)+8,y:y(d[o].y)-24,width:100,height:28,rx:4,fill:r.cellBg,stroke:r.cellBorder,strokeWidth:1}),s.jsxs("text",{x:C(d[o].x)+13,y:y(d[o].y)-8,fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:["(",Be(d[o].x),", ",Be(d[o].y),")"]})]})]})]})}const g1=12;function bu({result:e,themeMode:t,chartConfig:n,isDonut:r}){const o=ie[t],[i,a]=f.useState(null),{labelCol:l,valueCol:c}=Ea(e,n),d=e.rows.slice(0,g1).map(m=>({label:String(m[l]??""),value:Math.abs(Number(m[c]??0))})),E=d.reduce((m,I)=>m+I.value,0)||1,u=90,T=90,p=70,h=r?40:0,A=[];let S=-Math.PI/2;d.forEach((m,I)=>{const O=m.value/E*2*Math.PI,N=S,x=S+O,g=u+p*Math.cos(N),C=T+p*Math.sin(N),y=u+p*Math.cos(x),w=T+p*Math.sin(x),v=O>Math.PI?1:0;let B;if(h>0){const b=u+h*Math.cos(N),L=T+h*Math.sin(N),D=u+h*Math.cos(x),M=T+h*Math.sin(x);B=`M ${g} ${C} A ${p} ${p} 0 ${v} 1 ${y} ${w} L ${D} ${M} A ${h} ${h} 0 ${v} 0 ${b} ${L} Z`}else B=`M ${u} ${T} L ${g} ${C} A ${p} ${p} 0 ${v} 1 ${y} ${w} Z`;A.push({path:B,color:ke[I%ke.length],label:m.label,value:m.value,pct:m.value/E*100}),S=x});const R=i!==null?A[i]:null;return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,padding:"8px 12px",flexWrap:"wrap"},children:[s.jsxs("svg",{width:180,height:180,style:{flexShrink:0},onMouseLeave:()=>a(null),children:[A.map((m,I)=>s.jsx("path",{d:m.path,fill:m.color,opacity:i===null||i===I?1:.55,style:{cursor:"pointer",transition:"opacity 0.15s"},onMouseEnter:()=>a(I)},I)),r&&s.jsxs(s.Fragment,{children:[s.jsx("text",{x:u,y:T-5,textAnchor:"middle",fontSize:11,fontFamily:o.fontMono,fill:o.textSecondary,children:Be(R?R.value:E)}),s.jsx("text",{x:u,y:T+9,textAnchor:"middle",fontSize:9,fontFamily:o.font,fill:o.textMuted,children:R?`${R.pct.toFixed(1)}%`:"total"})]})]}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,maxHeight:180,overflowY:"auto",flex:1},children:A.map((m,I)=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,cursor:"default",opacity:i===null||i===I?1:.5},onMouseEnter:()=>a(I),onMouseLeave:()=>a(null),children:[s.jsx("div",{style:{width:10,height:10,borderRadius:2,background:m.color,flexShrink:0}}),s.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.label}),s.jsxs("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textMuted,marginLeft:"auto",flexShrink:0},children:[m.pct.toFixed(1),"%"]})]},I))})]})}function x1({result:e,themeMode:t}){const n=ie[t],[r,o]=f.useState(null),i=e.columns[0],a=e.columns.slice(1),l=e.rows.slice(0,30),c=l.flatMap(S=>a.map(R=>Number(S[R]??0))),d=Math.min(...c),u=Math.max(...c)-d||1,T=Math.min(50,480/a.length),p=24,h=100;function A(S){const R=(S-d)/u,m=Math.round(56+R*192),I=Math.round(139+R*-58),O=Math.round(253+R*-180);return`rgb(${m},${I},${O})`}return s.jsx("div",{style:{padding:"8px 0",overflowX:"auto"},children:s.jsxs("svg",{width:h+a.length*T+20,height:l.length*p+p+16,style:{display:"block",overflow:"visible"},children:[a.map((S,R)=>s.jsx("text",{x:h+R*T+T/2,y:14,textAnchor:"middle",fontSize:9,fontFamily:n.font,fill:n.textMuted,transform:`rotate(-30, ${h+R*T+T/2}, 14)`,children:S.length>8?S.slice(0,7)+"…":S},R)),l.map((S,R)=>{const m=String(S[i]??""),I=p+R*p;return s.jsxs("g",{children:[s.jsx("text",{x:h-6,y:I+p/2+4,textAnchor:"end",fontSize:10,fontFamily:n.font,fill:n.textSecondary,children:m.length>14?m.slice(0,13)+"…":m}),a.map((O,N)=>{const x=Number(S[O]??0),g=(r==null?void 0:r.r)===R&&(r==null?void 0:r.c)===N;return s.jsxs("g",{onMouseEnter:()=>o({r:R,c:N}),onMouseLeave:()=>o(null),children:[s.jsx("rect",{x:h+N*T,y:I,width:T-1,height:p-1,rx:2,fill:A(x),opacity:g?1:.85,stroke:g?n.accent:"none",strokeWidth:g?1.5:0}),g&&s.jsx("text",{x:h+N*T+T/2,y:I+p/2+4,textAnchor:"middle",fontSize:10,fontFamily:n.fontMono,fill:"#fff",fontWeight:600,children:Be(x)})]},N)})]},R)})]})})}function y1({result:e,themeMode:t,chartConfig:n}){const r=ie[t],[o,i]=f.useState(null),a=(n!=null&&n.x&&e.columns.includes(n.x)?n.x:void 0)??e.columns.find(C=>e.rows.slice(0,5).some(y=>En(y[C])))??e.columns[0],l=e.rows.map(C=>Number(C[a]??0)).filter(C=>!isNaN(C));if(l.length===0)return null;const c=Math.min(20,Math.max(5,Math.ceil(Math.sqrt(l.length)))),d=Math.min(...l),T=(Math.max(...l)-d||1)/c,p=Array.from({length:c},(C,y)=>({low:d+y*T,high:d+(y+1)*T,count:0}));l.forEach(C=>{const y=Math.min(Math.floor((C-d)/T),c-1);p[y].count++});const h=Math.max(...p.map(C=>C.count),1),A=560,S=200,R=52,m=16,I=16,O=36,N=A-R-m,x=S-I-O,g=N/c;return s.jsx("div",{style:{padding:"8px 0"},children:s.jsxs("svg",{width:"100%",height:S,viewBox:`0 0 ${A} ${S}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:5},(C,y)=>{const w=h*(y+1)/5,v=I+x-w/h*x;return s.jsxs("g",{children:[s.jsx("line",{x1:R,y1:v,x2:R+N,y2:v,stroke:r.tableBorder,strokeWidth:.5}),s.jsx("text",{x:R-6,y:v+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Math.round(w)})]},y)}),p.map((C,y)=>{const w=C.count/h*x,v=R+y*g,B=I+x-w,b=o===y;return s.jsxs("g",{onMouseEnter:()=>i(y),onMouseLeave:()=>i(null),children:[s.jsx("rect",{x:v+1,y:B,width:g-2,height:w,rx:1,fill:b?r.accentHover:r.accent,opacity:b?1:.85,style:{transition:"fill 0.1s"}}),b&&s.jsx("text",{x:v+g/2,y:B-4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:C.count})]},y)}),p.filter((C,y)=>y%Math.ceil(c/6)===0).map((C,y)=>{const w=p.indexOf(C);return s.jsx("text",{x:R+w*g+g/2,y:I+x+16,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Be(C.low)},y)}),s.jsx("line",{x1:R,y1:I,x2:R,y2:I+x,stroke:r.tableBorder,strokeWidth:1}),s.jsx("line",{x1:R,y1:I+x,x2:R+N,y2:I+x,stroke:r.tableBorder,strokeWidth:1}),s.jsx("text",{x:R+N/2,y:S-2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:a})]})})}function C1({result:e,themeMode:t,chartConfig:n}){const r=ie[t],[o,i]=f.useState(null),{labelCol:a,valueCol:l}=Ea(e,n),c=e.rows.slice(0,10).map(S=>({label:String(S[a]??""),value:Math.abs(Number(S[l]??0))}));if(c.length===0)return null;const d=c[0].value||1,E=400,u=36,T=4,p=16,h=c.length*(u+T)+p*2,A=E/2;return s.jsx("div",{style:{padding:"8px 0",display:"flex",justifyContent:"center"},children:s.jsx("svg",{width:E,height:h,style:{display:"block"},children:c.map((S,R)=>{const m=p+R*(u+T),I=S.value/d,O=Math.max(I*(E-80),40),N=o===R,x=R<c.length-1?c[R+1].value/d:I*.8,g=Math.max(x*(E-80),40),C=A-O/2,y=A+O/2,w=A+g/2,v=A-g/2,B=`M ${C} ${m} L ${y} ${m} L ${w} ${m+u} L ${v} ${m+u} Z`;return s.jsxs("g",{onMouseEnter:()=>i(R),onMouseLeave:()=>i(null),style:{cursor:"default"},children:[s.jsx("path",{d:B,fill:ke[R%ke.length],opacity:N?1:.85,style:{transition:"opacity 0.15s"}}),s.jsx("text",{x:A,y:m+u/2+1,textAnchor:"middle",fontSize:11,fontFamily:r.font,fill:"#fff",fontWeight:500,children:S.label}),s.jsxs("text",{x:A,y:m+u/2+13,textAnchor:"middle",fontSize:9,fontFamily:r.fontMono,fill:"rgba(255,255,255,0.7)",children:[Be(S.value)," (",(I*100).toFixed(0),"%)"]})]},R)})})})}function L1({result:e,themeMode:t,chartConfig:n}){const r=ie[t],[o,i]=f.useState(null),{labelCol:a,valueCol:l}=Ea(e,n),c=e.rows.slice(0,15).map(y=>({label:String(y[a]??""),value:Number(y[l]??0)}));if(c.length===0)return null;let d=0;const E=c.map(y=>{const w=d;return d+=y.value,{...y,start:w,end:d}}),u=E.flatMap(y=>[y.start,y.end]),T=Math.min(0,...u),h=Math.max(0,...u)-T||1,A=560,S=240,R=52,m=16,I=16,O=44,N=A-R-m,x=S-I-O,g=N/E.length,C=y=>I+x-(y-T)/h*x;return s.jsx("div",{style:{padding:"8px 0"},children:s.jsxs("svg",{width:"100%",height:S,viewBox:`0 0 ${A} ${S}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:6},(y,w)=>{const v=T+h*w/5,B=C(v);return s.jsxs("g",{children:[s.jsx("line",{x1:R,y1:B,x2:R+N,y2:B,stroke:r.tableBorder,strokeWidth:.5}),s.jsx("text",{x:R-6,y:B+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Be(v)})]},w)}),s.jsx("line",{x1:R,y1:C(0),x2:R+N,y2:C(0),stroke:r.textMuted,strokeWidth:1,strokeDasharray:"3,3"}),E.map((y,w)=>{const v=R+w*g,B=C(Math.max(y.start,y.end)),L=C(Math.min(y.start,y.end))-B,D=y.value>=0,M=o===w;return s.jsxs("g",{onMouseEnter:()=>i(w),onMouseLeave:()=>i(null),children:[w<E.length-1&&s.jsx("line",{x1:v+g-2,y1:C(y.end),x2:v+g+2,y2:C(y.end),stroke:r.textMuted,strokeWidth:1,strokeDasharray:"2,2"}),s.jsx("rect",{x:v+4,y:B,width:g-8,height:Math.max(L,1),rx:2,fill:D?r.success:r.error,opacity:M?1:.8,style:{transition:"opacity 0.1s"}}),M&&s.jsxs("text",{x:v+g/2,y:B-4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:[y.value>=0?"+":"",Be(y.value)]})]},w)}),E.map((y,w)=>s.jsx("text",{x:R+w*g+g/2,y:S-6,textAnchor:"middle",fontSize:9,fontFamily:r.font,fill:r.textMuted,transform:`rotate(-20, ${R+w*g+g/2}, ${S-6})`,children:y.label.length>8?y.label.slice(0,7)+"…":y.label},w)),s.jsx("line",{x1:R,y1:I,x2:R,y2:I+x,stroke:r.tableBorder,strokeWidth:1}),s.jsx("line",{x1:R,y1:I+x,x2:R+N,y2:I+x,stroke:r.tableBorder,strokeWidth:1})]})})}function _1({result:e,themeMode:t,chartConfig:n}){const r=ie[t],o=e.rows[0];if(!o)return null;const i=(n!=null&&n.y&&e.columns.includes(n.y)?n.y:void 0)??e.columns.find(C=>En(o[C]))??e.columns[0],a=Number(o[i]??0),l=(n==null?void 0:n.title)??i,c=a>100?a*1.2:100,d=Math.min(Math.max(a/c,0),1),E=120,u=110,T=80,p=Math.PI,h=0,A=p-(p-h)*d,S=E+T*Math.cos(p),R=u+T*Math.sin(p),m=E+T*Math.cos(A),I=u+T*Math.sin(A),O=d>.5?1:0,N=E+T*Math.cos(h),x=u+T*Math.sin(h),g=d<.33?r.error:d<.66?r.warning:r.success;return s.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:"16px 24px"},children:s.jsxs("svg",{width:240,height:140,style:{display:"block",overflow:"visible"},children:[s.jsx("path",{d:`M ${S} ${R} A ${T} ${T} 0 1 1 ${N} ${x}`,fill:"none",stroke:r.tableBorder,strokeWidth:12,strokeLinecap:"round"}),d>0&&s.jsx("path",{d:`M ${S} ${R} A ${T} ${T} 0 ${O} 1 ${m} ${I}`,fill:"none",stroke:g,strokeWidth:12,strokeLinecap:"round"}),s.jsx("text",{x:E,y:u-4,textAnchor:"middle",fontSize:28,fontFamily:r.fontMono,fill:g,fontWeight:700,children:Be(a)}),s.jsx("text",{x:E,y:u+16,textAnchor:"middle",fontSize:11,fontFamily:r.font,fill:r.textMuted,children:l})]})})}function Eh({result:e,themeMode:t,chartConfig:n}){const r=ie[t],o=e.rows[0];if(!o)return null;const i=n!=null&&n.y&&e.columns.includes(n.y)?n.y:e.columns.find(E=>En(o[E]))??e.columns[0],a=o[i],l=Number(a),c=isNaN(l)?String(a):l.toLocaleString(void 0,{maximumFractionDigits:2}),d=(n==null?void 0:n.title)??(n!=null&&n.x&&o[n.x]?String(o[n.x]):i);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"32px 24px",gap:8},children:[s.jsx("span",{style:{fontSize:40,fontWeight:700,fontFamily:r.fontMono,color:r.accent,lineHeight:1.1},children:c}),s.jsx("span",{style:{fontSize:13,fontFamily:r.font,color:r.textMuted,textTransform:"uppercase",letterSpacing:"0.08em",fontWeight:500},children:d})]})}function b1({config:e,columns:t,onChange:n,onClose:r,t:o}){const i={background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:11,fontFamily:o.font,padding:"4px 8px",outline:"none",width:"100%",boxSizing:"border-box"};return s.jsxs("div",{style:{position:"absolute",top:4,right:4,zIndex:100,background:o.cellBg,border:`1px solid ${o.headerBorder}`,borderRadius:8,padding:12,width:240,boxShadow:"0 4px 16px rgba(0,0,0,0.3)",display:"grid",gap:8},onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{style:{fontSize:11,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:"Chart Settings"}),s.jsx("button",{onClick:r,style:{background:"none",border:"none",color:o.textMuted,cursor:"pointer",fontSize:14},children:"×"})]}),s.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Title",s.jsx("input",{value:e.title??"",onChange:a=>n({title:a.target.value||void 0}),placeholder:"Chart title",style:{...i,marginTop:2}})]}),s.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["X-axis label",s.jsx("input",{value:e.xLabel??"",onChange:a=>n({xLabel:a.target.value||void 0}),placeholder:"Auto",style:{...i,marginTop:2}})]}),s.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Y-axis label",s.jsx("input",{value:e.yLabel??"",onChange:a=>n({yLabel:a.target.value||void 0}),placeholder:"Auto",style:{...i,marginTop:2}})]}),s.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Legend",s.jsxs("select",{value:e.legendPosition??"top",onChange:a=>n({legendPosition:a.target.value}),style:{...i,marginTop:2},children:[s.jsx("option",{value:"top",children:"Top"}),s.jsx("option",{value:"bottom",children:"Bottom"}),s.jsx("option",{value:"left",children:"Left"}),s.jsx("option",{value:"right",children:"Right"}),s.jsx("option",{value:"none",children:"Hidden"})]})]}),s.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Color palette",s.jsx("select",{value:e.colorPalette??"default",onChange:a=>n({colorPalette:a.target.value}),style:{...i,marginTop:2},children:Object.keys(dh).map(a=>s.jsx("option",{value:a,children:a.charAt(0).toUpperCase()+a.slice(1)},a))})]}),s.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Max items",s.jsx("input",{type:"number",value:e.maxItems??kn,min:5,max:200,onChange:a=>n({maxItems:parseInt(a.target.value)||kn}),style:{...i,marginTop:2}})]})]})}function Yd({result:e,themeMode:t,chartConfig:n,onConfigChange:r}){const o=ie[t],i=Cr(e,n),[a,l]=f.useState(!1);return i==="kpi"?s.jsx(Eh,{result:e,themeMode:t,chartConfig:n}):s.jsxs("div",{style:{position:"relative"},children:[(n==null?void 0:n.title)&&s.jsx("div",{style:{padding:"8px 12px 0",fontSize:13,fontWeight:600,color:o.textPrimary,fontFamily:o.font,textAlign:"center"},children:n.title}),r&&s.jsx("button",{onClick:()=>l(!a),title:"Chart settings",style:{position:"absolute",top:4,right:4,zIndex:50,background:a?`${o.accent}18`:"transparent",border:`1px solid ${a?o.accent:"transparent"}`,borderRadius:4,color:a?o.accent:o.textMuted,cursor:"pointer",fontSize:14,padding:"2px 6px",lineHeight:1},children:"⚙"}),a&&r&&s.jsx(b1,{config:n??{},columns:e.columns,onChange:c=>r(c),onClose:()=>l(!1),t:o}),ua(i,e,t,n)]})}function ua(e,t,n,r){const o=r!=null&&r.x&&t.columns.includes(r.x)?r.x:void 0,i=r!=null&&r.y&&t.columns.includes(r.y)?r.y:void 0,a=o||i?D1(t,o,i):t;switch(e){case"line":return s.jsx(_u,{result:a,themeMode:n});case"area":return s.jsx(_u,{result:a,themeMode:n,showArea:!0});case"bar":return s.jsx(Hd,{result:a,themeMode:n,chartConfig:r});case"grouped-bar":return s.jsx(m1,{result:a,themeMode:n,chartConfig:r});case"stacked-bar":return s.jsx(O1,{result:a,themeMode:n,chartConfig:r});case"scatter":return s.jsx(N1,{result:t,themeMode:n,chartConfig:r});case"pie":return s.jsx(bu,{result:t,themeMode:n,chartConfig:r,isDonut:!1});case"donut":return s.jsx(bu,{result:t,themeMode:n,chartConfig:r,isDonut:!0});case"heatmap":return s.jsx(x1,{result:t,themeMode:n});case"histogram":return s.jsx(y1,{result:t,themeMode:n,chartConfig:r});case"funnel":return s.jsx(C1,{result:t,themeMode:n,chartConfig:r});case"waterfall":return s.jsx(L1,{result:t,themeMode:n,chartConfig:r});case"gauge":return s.jsx(_1,{result:t,themeMode:n,chartConfig:r});case"kpi":return s.jsx(Eh,{result:t,themeMode:n,chartConfig:r});default:return s.jsx(Kn,{result:t,themeMode:n})}}function D1(e,t,n){const r=e.columns,o=[];t&&r.includes(t)&&o.push(t),n&&r.includes(n)&&o.push(n);for(const i of r)o.includes(i)||o.push(i);return o.join(",")===r.join(",")?e:{...e,columns:o,rows:e.rows.map(i=>{const a={};for(const l of o)a[l]=i[l];return a})}}function Ta(e){var c,d;if(!e)return{metrics:[],dimensions:[],columns:[],fields:[],hasSemanticBinding:!1};const t=new Set(((c=e.semanticRefs)==null?void 0:c.metrics)??[]),n=new Set(((d=e.semanticRefs)==null?void 0:d.dimensions)??[]),r=t.size>0||n.size>0,o=[],i=[],a=[],l=[];for(const E of e.columns)t.has(E)?(o.push(E),l.push({name:E,kind:"metric"})):n.has(E)&&(i.push(E),l.push({name:E,kind:"dimension"}));for(const E of e.columns)t.has(E)||n.has(E)||(a.push(E),l.push({name:E,kind:"column",chartRole:sh(Gd(E,e.rows))}));return{metrics:o,dimensions:i,columns:a,fields:l,hasSemanticBinding:r}}function Oo(e){return e==="metric"?"#":e==="dimension"?"∴":"A"}function No(e,t){return e==="metric"?t:e==="dimension"?"#e3b341":"#56d364"}function Du(e){return e==="metric"?"metric":e==="dimension"?"dimension":"column"}function uh({theme:e,value:t,fields:n,allowKinds:r,placeholder:o="Select field",minWidth:i=180,onChange:a}){const[l,c]=f.useState(!1),[d,E]=f.useState(""),u=f.useRef(null),T=f.useRef(null);f.useEffect(()=>{if(!l)return;const S=R=>{var m;(m=u.current)!=null&&m.contains(R.target)||c(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[l]),f.useEffect(()=>{if(l){const S=setTimeout(()=>{var R;return(R=T.current)==null?void 0:R.focus()},20);return()=>clearTimeout(S)}E("")},[l]);const p=f.useMemo(()=>n.find(S=>S.name===t),[n,t]),h=f.useMemo(()=>{if(!d)return n;const S=d.toLowerCase();return n.filter(R=>R.name.toLowerCase().includes(S))},[n,d]),A=S=>r?r.includes(S):!0;return s.jsxs("div",{ref:u,style:{position:"relative",minWidth:i},children:[s.jsxs("button",{onClick:()=>c(S=>!S),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 8px",background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:3,cursor:"pointer",color:p?e.textPrimary:e.textMuted,fontFamily:e.fontMono,fontSize:11,textAlign:"left"},children:[p?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{color:No(p.kind,e.accent),fontWeight:700,width:12},children:Oo(p.kind)}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p.name})]}):s.jsx("span",{style:{flex:1},children:o}),s.jsx("span",{style:{color:e.textMuted,fontSize:9},children:"▾"})]}),l&&s.jsxs("div",{style:{position:"absolute",top:"calc(100% + 2px)",left:0,right:0,zIndex:20,background:e.cellBg,border:`1px solid ${e.cellBorder}`,borderRadius:6,boxShadow:"0 6px 16px rgba(0,0,0,0.28)",padding:4,maxHeight:260,overflow:"auto",minWidth:Math.max(i,200)},children:[s.jsx("input",{ref:T,value:d,onChange:S=>E(S.target.value),placeholder:"Search fields...",style:{width:"100%",padding:"4px 6px",marginBottom:4,background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:3,color:e.textPrimary,fontFamily:e.font,fontSize:11,outline:"none"}}),t&&s.jsx("button",{onClick:()=>{a(void 0),c(!1)},style:{width:"100%",textAlign:"left",padding:"3px 6px",background:"transparent",border:"none",borderRadius:3,color:e.textMuted,fontSize:10,fontFamily:e.font,cursor:"pointer",fontStyle:"italic"},children:"Clear selection"}),h.length===0&&s.jsx("div",{style:{padding:"6px 8px",fontSize:11,color:e.textMuted,fontFamily:e.font},children:"No matches"}),h.map(S=>{const R=A(S.kind);return s.jsxs("button",{onClick:()=>{R&&(a(S.name),c(!1))},disabled:!R,title:R?S.name:`${Du(S.kind)} — not selectable here`,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 6px",background:"transparent",border:"none",borderRadius:3,cursor:R?"pointer":"not-allowed",textAlign:"left",color:R?e.textPrimary:e.textMuted,fontFamily:e.fontMono,fontSize:11,opacity:R?1:.55},onMouseEnter:m=>{R&&(m.currentTarget.style.background=e.tableRowHover)},onMouseLeave:m=>{m.currentTarget.style.background="transparent"},children:[s.jsx("span",{style:{color:No(S.kind,e.accent),fontWeight:700,width:12,textAlign:"center"},children:Oo(S.kind)}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.name}),s.jsx("span",{style:{fontSize:9,color:e.textMuted,fontFamily:e.font,textTransform:"uppercase",letterSpacing:"0.06em"},children:Du(S.kind)})]},S.name)})]})]})}function fa({theme:e}){return s.jsxs("div",{style:{fontSize:10,fontFamily:e.font,color:e.textMuted,background:`${e.cellBorder}60`,borderRadius:3,padding:"3px 8px",letterSpacing:"0.02em"},children:["No semantic binding — metrics and dimensions unavailable. Use ",s.jsx("code",{children:"@metric(...)"})," or ",s.jsx("code",{children:"@dim(...)"})," upstream to populate typed pickers."]})}function Yo({theme:e,accentColor:t,cellLabel:n,cellName:r,description:o,upstreamOptions:i,onPick:a}){return s.jsxs("div",{style:{background:e.cellBg,border:`1px solid ${e.cellBorder}`,borderLeft:`3px solid ${t}`,borderRadius:6,padding:"18px 20px",fontFamily:e.font},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[s.jsx("span",{style:{fontSize:10,fontFamily:e.fontMono,fontWeight:700,letterSpacing:"0.08em",color:t,background:`${t}18`,padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:n}),r&&s.jsx("span",{style:{fontSize:12,fontFamily:e.fontMono,color:e.textSecondary},children:r})]}),s.jsx("div",{style:{fontSize:12,color:e.textSecondary,marginBottom:8,lineHeight:1.5},children:o}),i.length===0?s.jsxs("div",{style:{fontSize:11,color:e.textMuted,background:`${t}0A`,border:`1px dashed ${e.cellBorder}`,borderRadius:4,padding:"10px 12px",lineHeight:1.6},children:[s.jsx("div",{style:{fontWeight:600,color:e.textSecondary,marginBottom:4},children:"No dataframe available yet"}),s.jsxs("div",{children:["1. Add a ",s.jsx("span",{style:{fontFamily:e.fontMono,color:e.textSecondary},children:"SQL"})," or"," ",s.jsx("span",{style:{fontFamily:e.fontMono,color:e.textSecondary},children:"Block"})," cell above this one.",s.jsx("br",{}),"2. Run it ",s.jsx("span",{style:{fontFamily:e.fontMono},children:"(⌘↵)"})," and give the cell a name.",s.jsx("br",{}),"3. Come back here — named upstream cells show up as chips you can pick."]}),s.jsxs("div",{style:{marginTop:8,fontSize:10,color:e.textMuted,fontStyle:"italic"},children:["Tip: use ",s.jsx("span",{style:{fontFamily:e.fontMono},children:"@metric(...)"})," and"," ",s.jsx("span",{style:{fontFamily:e.fontMono},children:"@dim(...)"})," in the upstream SQL and metrics / dimensions appear with typed icons in the pickers here."]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:10,color:e.textMuted,marginBottom:6,letterSpacing:"0.06em",textTransform:"uppercase",fontWeight:700},children:"Pick an upstream dataframe"}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:i.map(l=>s.jsx("button",{onClick:()=>l.name&&a(l.name),style:{fontSize:11,fontFamily:e.fontMono,color:t,background:`${t}14`,border:`1px solid ${t}55`,borderRadius:4,padding:"3px 10px",cursor:"pointer"},children:l.name},l.id))})]})]})}function Mc(e){return e==="measure"?"#":e==="temporal"?"📅":"A"}function vc(e,t){return e==="measure"?t.accent:e==="temporal"?t.warning:t.success}const M1=[{key:"x",label:"X-axis"},{key:"y",label:"Y-axis"},{key:"color",label:"Color"},{key:"facet",label:"Faceting"}],v1={chart:"bar"},Wd="application/x-dql-chart-column";function Th(e,t){e.effectAllowed="move",e.setData(Wd,JSON.stringify(t)),e.setData("text/plain",t.column)}function P1(e){const t=e.getData(Wd);if(!t)return null;try{return JSON.parse(t)}catch{return null}}function w1({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const i=ie[r],a=e.chartConfig??v1,l=a.chart??"bar",c=f.useMemo(()=>{const S=e.upstream;if(S)return t.find(R=>R.name===S)},[e.upstream,t]),d=f.useMemo(()=>t.slice(0,n).filter(S=>S.name&&S.result),[t,n]),E=c==null?void 0:c.result,u=f.useMemo(()=>Ta(E),[E]),T=f.useMemo(()=>{if(!E)return new Map;const S=new Map,R=new Set(u.metrics),m=new Set(u.dimensions);for(const I of E.columns)R.has(I)?S.set(I,"measure"):m.has(I)?S.set(I,"dimension"):S.set(I,sh(Gd(I,E.rows)));return S},[E,u]),p=f.useMemo(()=>E?E.columns.filter(S=>T.get(S)==="measure"):[],[E,T]),h=f.useMemo(()=>E?E.columns.filter(S=>T.get(S)!=="measure"):[],[E,T]),A=S=>{o({chartConfig:{...a,...S}})};return!e.upstream||!E?s.jsx(Yo,{theme:i,accentColor:"#a371f7",cellLabel:"Chart",cellName:e.name,description:"Charts render from an upstream dataframe — the rows of a named SQL, DQL, or Block cell above. Drag measures to Y, dimensions to X.",upstreamOptions:d,onPick:S=>o({upstream:S})}):s.jsxs("div",{style:{display:"flex",flexDirection:"column",background:i.cellBg,borderTop:`1px solid ${i.cellBorder}`,borderRight:`1px solid ${i.cellBorder}`,borderBottom:`1px solid ${i.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,overflow:"hidden",fontFamily:i.font},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${i.cellBorder}`,background:`${i.tableHeaderBg}60`},children:[s.jsx("span",{style:{fontSize:10,fontFamily:i.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Chart"}),e.name&&s.jsx("span",{style:{fontSize:12,fontFamily:i.fontMono,color:i.textSecondary},children:e.name}),s.jsxs("span",{style:{fontSize:11,color:i.textMuted,fontFamily:i.fontMono},children:["· df: ",e.upstream]}),s.jsx("button",{onClick:()=>o({upstream:void 0}),title:"Change upstream dataframe",style:{fontSize:10,background:"transparent",border:`1px solid ${i.btnBorder}`,borderRadius:3,color:i.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:i.fontMono},children:"change"}),s.jsx("div",{style:{flex:1}}),s.jsx("select",{value:l,onChange:S=>A({chart:S.target.value}),style:{fontSize:11,fontFamily:i.font,background:i.editorBg,color:i.textSecondary,border:`1px solid ${i.cellBorder}`,borderRadius:3,padding:"2px 6px",outline:"none"},children:da.map(S=>s.jsx("option",{value:S.value,children:S.label},S.value))})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"200px 240px 1fr",minHeight:320},children:[s.jsxs("div",{style:{borderRight:`1px solid ${i.cellBorder}`,padding:10,display:"flex",flexDirection:"column",gap:12,overflow:"auto"},children:[!u.hasSemanticBinding&&s.jsx(fa,{theme:i}),s.jsx(Mu,{label:"Measures",columns:p,kinds:T,theme:i,onPick:S=>A({y:S}),pickHint:"Y-axis"}),s.jsx(Mu,{label:"Dimensions",columns:h,kinds:T,theme:i,onPick:S=>A({x:S}),pickHint:"X-axis"})]}),s.jsxs("div",{style:{borderRight:`1px solid ${i.cellBorder}`,padding:10,display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{display:"flex",gap:4,borderBottom:`1px solid ${i.cellBorder}`,paddingBottom:4},children:[s.jsx(vu,{label:"Data",active:!0,theme:i}),s.jsx(vu,{label:"Style",theme:i})]}),M1.map(S=>s.jsx(U1,{slotKey:S.key,label:S.label,value:a[S.key],columns:E.columns,kinds:T,theme:i,onAssign:(R,m)=>{const I={[S.key]:R};m&&m!==S.key&&(I[m]=void 0),A(I)},onClear:()=>A({[S.key]:void 0})},S.key))]}),s.jsx("div",{style:{padding:10,minWidth:0,overflow:"hidden"},children:ua(l,E,r,a)})]})]})}function Mu({label:e,columns:t,kinds:n,theme:r,onPick:o,pickHint:i}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("div",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:r.textMuted,textTransform:"uppercase",fontFamily:r.font,padding:"0 2px"},children:e}),t.length===0&&s.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,padding:"2px 2px"},children:"None"}),t.map(a=>{const l=n.get(a)??"dimension";return s.jsxs("button",{onClick:()=>o(a),draggable:!0,onDragStart:c=>Th(c.dataTransfer,{column:a}),title:`Drag to an axis slot, or click to set as ${i}`,style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",background:"transparent",border:"1px solid transparent",borderRadius:4,cursor:"grab",textAlign:"left",color:r.textPrimary,fontFamily:r.fontMono,fontSize:11,transition:"border-color 0.1s, background 0.1s"},onMouseEnter:c=>{c.currentTarget.style.borderColor=r.cellBorder,c.currentTarget.style.background=r.tableRowHover},onMouseLeave:c=>{c.currentTarget.style.borderColor="transparent",c.currentTarget.style.background="transparent"},children:[s.jsx("span",{style:{fontSize:9,fontFamily:r.fontMono,fontWeight:700,color:vc(l,r),width:14,textAlign:"center"},children:Mc(l)}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a})]},a)})]})}function vu({label:e,active:t,theme:n}){return s.jsx("span",{style:{fontSize:11,fontFamily:n.font,fontWeight:600,color:t?n.textPrimary:n.textMuted,padding:"3px 10px",borderRadius:3,background:t?n.tableHeaderBg:"transparent",cursor:t?"default":"not-allowed"},children:e})}function U1({slotKey:e,label:t,value:n,columns:r,kinds:o,theme:i,onAssign:a,onClear:l}){const[c,d]=f.useState(!1),[E,u]=f.useState(!1),T=f.useRef(null);f.useEffect(()=>{if(!c)return;const m=I=>{var O;(O=T.current)!=null&&O.contains(I.target)||d(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[c]);const p=m=>{m.dataTransfer.types.includes(Wd)&&(m.preventDefault(),m.dataTransfer.dropEffect="move",E||u(!0))},h=()=>u(!1),A=m=>{u(!1);const I=P1(m.dataTransfer);I&&(m.preventDefault(),a(I.column,I.fromSlot),d(!1))},S=E?i.accent:n?`${i.accent}77`:i.cellBorder,R=E?`${i.accent}22`:n?`${i.accent}10`:i.editorBg;return s.jsxs("div",{ref:T,style:{position:"relative"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:i.textMuted,textTransform:"uppercase",fontFamily:i.font,marginBottom:3},children:t}),s.jsx("button",{onClick:()=>d(m=>!m),onDragOver:p,onDragEnter:p,onDragLeave:h,onDrop:A,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"5px 8px",background:R,border:`1px dashed ${S}`,borderRadius:4,cursor:"pointer",color:n?i.textPrimary:i.textMuted,fontFamily:i.fontMono,fontSize:11,textAlign:"left",transition:"background 0.1s, border-color 0.1s"},children:n?s.jsxs(s.Fragment,{children:[s.jsxs("span",{draggable:!0,onDragStart:m=>{m.stopPropagation(),Th(m.dataTransfer,{column:n,fromSlot:e})},style:{display:"inline-flex",alignItems:"center",gap:6,flex:1,cursor:"grab",minWidth:0},children:[s.jsx("span",{style:{color:vc(o.get(n)??"dimension",i),fontWeight:700,width:14},children:Mc(o.get(n)??"dimension")}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]}),s.jsx("span",{onClick:m=>{m.stopPropagation(),l(),d(!1)},title:"Clear",style:{color:i.textMuted,fontSize:10,padding:"0 4px"},children:"✕"})]}):s.jsx("span",{children:E?"drop to set":"+ drop column"})}),c&&s.jsx("div",{style:{position:"absolute",top:"calc(100% + 2px)",left:0,right:0,zIndex:10,background:i.cellBg,border:`1px solid ${i.cellBorder}`,borderRadius:6,boxShadow:"0 6px 16px rgba(0,0,0,0.25)",padding:4,maxHeight:220,overflow:"auto"},children:r.map(m=>s.jsxs("button",{onClick:()=>{a(m),d(!1)},style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 6px",background:"transparent",border:"none",borderRadius:3,cursor:"pointer",textAlign:"left",color:i.textPrimary,fontFamily:i.fontMono,fontSize:11},onMouseEnter:I=>{I.currentTarget.style.background=i.tableRowHover},onMouseLeave:I=>{I.currentTarget.style.background="transparent"},children:[s.jsx("span",{style:{color:vc(o.get(m)??"dimension",i),fontWeight:700,width:14},children:Mc(o.get(m)??"dimension")}),s.jsx("span",{children:m})]},m))})]})}const Zs=[{value:"eq",label:"=",needsValue:!0},{value:"neq",label:"!=",needsValue:!0},{value:"gt",label:">",needsValue:!0},{value:"gte",label:">=",needsValue:!0},{value:"lt",label:"<",needsValue:!0},{value:"lte",label:"<=",needsValue:!0},{value:"contains",label:"contains",needsValue:!0},{value:"not_contains",label:"does not contain",needsValue:!0},{value:"starts_with",label:"starts with",needsValue:!0},{value:"ends_with",label:"ends with",needsValue:!0},{value:"in",label:"in (list)",needsValue:!0},{value:"not_in",label:"not in (list)",needsValue:!0},{value:"between",label:"between (a, b)",needsValue:!0},{value:"is_null",label:"is empty",needsValue:!1},{value:"is_not_null",label:"is not empty",needsValue:!1}];function Pc(e){return`${e}_${Math.random().toString(36).slice(2,10)}`}function B1(){return{mode:"keep",groups:[{id:Pc("g"),combinator:"and",rules:[]}]}}function F1(e){const t=Zs.find(n=>n.value===e.operation);return t?e.column?t.needsValue?`${e.column} ${t.label} ${e.value||"…"}`:`${e.column} ${t.label}`:"…":""}function k1({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const i=ie[r],a=f.useMemo(B1,[e.id]),l=e.filterConfig??a,c=f.useMemo(()=>{const N=e.upstream??l.upstream;if(N)return t.find(x=>x.name===N)},[e.upstream,l.upstream,t]),d=f.useMemo(()=>t.slice(0,n).filter(N=>N.name&&N.result),[t,n]),E=c==null?void 0:c.result,u=(E==null?void 0:E.columns)??[],T=f.useMemo(()=>Ta(E),[E]),p=N=>{o({filterConfig:N})},h=(N,x)=>{p({...l,groups:l.groups.map(g=>g.id===N?{...g,...x}:g)})},A=(N,x,g)=>{p({...l,groups:l.groups.map(C=>C.id===N?{...C,rules:C.rules.map(y=>y.id===x?{...y,...g}:y)}:C)})},S=N=>{p({...l,groups:l.groups.map(x=>x.id===N?{...x,rules:[...x.rules,{id:Pc("r"),column:u[0]??"",operation:"eq",value:""}]}:x)})},R=(N,x)=>{p({...l,groups:l.groups.map(g=>g.id===N?{...g,rules:g.rules.filter(C=>C.id!==x)}:g)})},m=()=>{p({...l,groups:[...l.groups,{id:Pc("g"),combinator:"and",rules:[]}]})},I=N=>{p({...l,groups:l.groups.filter(x=>x.id!==N)})};if(!c||!E)return s.jsx(Yo,{theme:i,accentColor:"#ff7b72",cellLabel:"Filter",cellName:e.name,description:"Filter cells keep or drop rows from an upstream dataframe using column-by-column rules — no SQL needed.",upstreamOptions:d,onPick:N=>o({upstream:N})});const O={background:i.editorBg,border:`1px solid ${i.cellBorder}`,borderRadius:3,color:i.textPrimary,fontSize:11,fontFamily:i.fontMono,padding:"3px 6px",outline:"none"};return s.jsxs("div",{style:{background:i.cellBg,border:`1px solid ${i.cellBorder}`,borderLeft:"3px solid #ff7b72",borderRadius:6,fontFamily:i.font,overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${i.cellBorder}`,background:`${i.tableHeaderBg}60`},children:[s.jsx("span",{style:{fontSize:10,fontFamily:i.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#ff7b72",background:"#ff7b7218",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Filter"}),e.name&&s.jsx("span",{style:{fontSize:12,fontFamily:i.fontMono,color:i.textSecondary},children:e.name}),s.jsxs("span",{style:{fontSize:11,color:i.textMuted,fontFamily:i.fontMono},children:["· df: ",c.name]}),s.jsx("button",{onClick:()=>o({upstream:void 0}),style:{fontSize:10,background:"transparent",border:`1px solid ${i.btnBorder}`,borderRadius:3,color:i.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:i.fontMono},children:"change"}),s.jsx("div",{style:{flex:1}}),s.jsx("div",{style:{display:"inline-flex",border:`1px solid ${i.cellBorder}`,borderRadius:3,overflow:"hidden"},children:["keep","drop"].map(N=>s.jsx("button",{onClick:()=>p({...l,mode:N}),style:{fontSize:10,fontFamily:i.font,fontWeight:600,letterSpacing:"0.04em",padding:"3px 10px",background:l.mode===N?`${i.accent}20`:"transparent",color:l.mode===N?i.accent:i.textMuted,border:"none",cursor:"pointer",textTransform:"uppercase"},children:N==="keep"?"Keep rows":"Drop rows"},N))})]}),s.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:10},children:[!T.hasSemanticBinding&&s.jsx(fa,{theme:i}),l.groups.map((N,x)=>s.jsxs("div",{style:{border:`1px solid ${i.cellBorder}`,borderRadius:6,padding:10,background:`${i.tableHeaderBg}30`,display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsxs("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:i.textMuted,textTransform:"uppercase",fontFamily:i.font},children:["Group ",x+1]}),s.jsx("div",{style:{display:"inline-flex",border:`1px solid ${i.cellBorder}`,borderRadius:3,overflow:"hidden"},children:["and","or"].map(g=>s.jsx("button",{onClick:()=>h(N.id,{combinator:g}),style:{fontSize:10,fontFamily:i.fontMono,padding:"2px 8px",background:N.combinator===g?`${i.accent}20`:"transparent",color:N.combinator===g?i.accent:i.textMuted,border:"none",cursor:"pointer",textTransform:"uppercase",fontWeight:700},children:g},g))}),s.jsx("div",{style:{flex:1}}),l.groups.length>1&&s.jsx("button",{onClick:()=>I(N.id),style:{fontSize:10,background:"transparent",border:`1px solid ${i.btnBorder}`,borderRadius:3,color:i.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:i.font},children:"Remove group"})]}),N.rules.length===0&&s.jsx("div",{style:{fontSize:11,color:i.textMuted,fontFamily:i.font,padding:"4px 2px"},children:"No rules yet — add one below."}),N.rules.map(g=>{const C=Zs.find(y=>y.value===g.operation)??Zs[0];return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx(uh,{theme:i,value:g.column||void 0,fields:T.fields,placeholder:"Select field",minWidth:180,onChange:y=>A(N.id,g.id,{column:y??""})}),s.jsx("select",{value:g.operation,onChange:y=>A(N.id,g.id,{operation:y.target.value}),style:{...O,minWidth:120},children:Zs.map(y=>s.jsx("option",{value:y.value,children:y.label},y.value))}),C.needsValue&&s.jsx("input",{value:g.value,onChange:y=>A(N.id,g.id,{value:y.target.value}),placeholder:"Value",style:{...O,flex:1,minWidth:100}}),s.jsx("button",{onClick:()=>R(N.id,g.id),title:"Remove rule",style:{background:"transparent",border:`1px solid ${i.btnBorder}`,borderRadius:3,color:i.textMuted,fontSize:10,padding:"2px 6px",cursor:"pointer"},children:"✕"})]},g.id)}),s.jsx("div",{children:s.jsx("button",{onClick:()=>S(N.id),style:{fontSize:10,fontFamily:i.font,color:i.accent,background:"transparent",border:`1px dashed ${i.accent}55`,borderRadius:3,padding:"3px 10px",cursor:"pointer",letterSpacing:"0.04em"},children:"+ Add filter"})})]},N.id)),s.jsx("div",{children:s.jsx("button",{onClick:m,style:{fontSize:10,fontFamily:i.font,color:i.textMuted,background:"transparent",border:`1px dashed ${i.btnBorder}`,borderRadius:3,padding:"3px 10px",cursor:"pointer",letterSpacing:"0.04em"},children:"+ Add filter group"})})]}),s.jsxs("div",{style:{padding:"6px 12px",borderTop:`1px solid ${i.cellBorder}`,background:`${i.tableHeaderBg}40`,fontSize:10,fontFamily:i.fontMono,color:i.textMuted,letterSpacing:"0.04em",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},children:[l.mode==="keep"?"KEEP WHERE ":"DROP WHERE ",l.groups.map(N=>N.rules.map(F1).join(` ${N.combinator.toUpperCase()} `)).filter(Boolean).map(N=>`(${N})`).join(" AND ")||"—"]})]})}function Pu(e){return typeof e=="number"?e:typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e))?Number(e):null}function wc(e,t){if(t==="count")return e.length;if(t==="count_distinct")return new Set(e.map(r=>String(r))).size;if(t==="last"){const r=e[e.length-1];return Pu(r)}const n=e.map(Pu).filter(r=>r!==null);if(n.length===0)return null;switch(t){case"sum":return n.reduce((r,o)=>r+o,0);case"avg":return n.reduce((r,o)=>r+o,0)/n.length;case"min":return n.reduce((r,o)=>o<r?o:r,n[0]);case"max":return n.reduce((r,o)=>o>r?o:r,n[0])}}const j1=[{value:"sum",label:"Sum"},{value:"avg",label:"Average"},{value:"count",label:"Count"},{value:"min",label:"Min"},{value:"max",label:"Max"},{value:"last",label:"Last"}],G1=[{value:"number",label:"Number"},{value:"currency",label:"Currency"},{value:"percent",label:"Percent"},{value:"duration",label:"Duration"}],H1={aggregation:"count",format:"number"};function Y1(e,t,n){return n==="count"?wc(e.rows,"count"):!t||!e.columns.includes(t)?null:wc(e.rows.map(r=>r[t]),n)}function W1(e,t){if(e===null)return"—";switch(t){case"currency":return e.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2});case"percent":return`${(e*100).toFixed(1)}%`;case"duration":return e<60?`${e.toFixed(1)}s`:e<3600?`${(e/60).toFixed(1)}m`:`${(e/3600).toFixed(1)}h`;case"number":default:return Math.abs(e)>=1e3?e.toLocaleString(void 0,{maximumFractionDigits:2}):e.toFixed(Number.isInteger(e)?0:2)}}function $1({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const i=ie[r],a=e.singleValueConfig??H1,l=a.aggregation??"count",c=a.format??"number",d=f.useMemo(()=>{const R=e.upstream??a.upstream;if(R)return t.find(m=>m.name===R)},[e.upstream,a.upstream,t]),E=f.useMemo(()=>t.slice(0,n).filter(R=>R.name&&R.result),[t,n]),u=d==null?void 0:d.result,T=f.useMemo(()=>Ta(u),[u]),p=f.useMemo(()=>u?Y1(u,a.metric,l):null,[u,a.metric,l]),h=R=>{o({singleValueConfig:{...a,...R}})};if(!d||!u)return s.jsx(Yo,{theme:i,accentColor:"#a371f7",cellLabel:"Single value",cellName:e.name,description:"Single-value cards render one KPI from an upstream dataframe — sum, avg, count, min, max, or last — with a format of your choice.",upstreamOptions:E,onPick:R=>o({upstream:R})});const A=W1(p,c),S={background:i.editorBg,border:`1px solid ${i.cellBorder}`,borderRadius:3,color:i.textPrimary,fontSize:11,fontFamily:i.fontMono,padding:"3px 6px",outline:"none"};return s.jsxs("div",{style:{background:i.cellBg,border:`1px solid ${i.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,fontFamily:i.font,overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${i.cellBorder}`,background:`${i.tableHeaderBg}60`},children:[s.jsx("span",{style:{fontSize:10,fontFamily:i.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Single value"}),e.name&&s.jsx("span",{style:{fontSize:12,fontFamily:i.fontMono,color:i.textSecondary},children:e.name}),s.jsxs("span",{style:{fontSize:11,color:i.textMuted,fontFamily:i.fontMono},children:["· df: ",d.name]}),s.jsx("button",{onClick:()=>o({upstream:void 0}),style:{fontSize:10,background:"transparent",border:`1px solid ${i.btnBorder}`,borderRadius:3,color:i.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:i.fontMono},children:"change"})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"280px 1fr"},children:[s.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:8,borderRight:`1px solid ${i.cellBorder}`},children:[s.jsx(bs,{label:"Aggregation",theme:i,children:s.jsx("select",{value:l,onChange:R=>h({aggregation:R.target.value}),style:{...S,width:"100%"},children:j1.map(R=>s.jsx("option",{value:R.value,children:R.label},R.value))})}),l!=="count"&&s.jsxs(bs,{label:"Metric field",theme:i,children:[s.jsx(uh,{theme:i,value:a.metric,fields:T.fields,placeholder:"Select metric or column",minWidth:240,onChange:R=>h({metric:R})}),!T.hasSemanticBinding&&s.jsx(fa,{theme:i})]}),s.jsx(bs,{label:"Format",theme:i,children:s.jsx("select",{value:c,onChange:R=>h({format:R.target.value}),style:{...S,width:"100%"},children:G1.map(R=>s.jsx("option",{value:R.value,children:R.label},R.value))})}),s.jsx(bs,{label:"Label",theme:i,children:s.jsx("input",{value:a.label??"",onChange:R=>h({label:R.target.value||void 0}),placeholder:"e.g. Total revenue",style:{...S,width:"100%"}})})]}),s.jsxs("div",{style:{padding:"24px 20px",display:"flex",flexDirection:"column",justifyContent:"center",gap:6},children:[s.jsx("div",{style:{fontSize:11,fontFamily:i.font,color:i.textMuted,letterSpacing:"0.06em",textTransform:"uppercase",fontWeight:600},children:a.label??`${l.toUpperCase()}${a.metric?` · ${a.metric}`:""}`}),s.jsx("div",{style:{fontSize:42,fontWeight:700,fontFamily:i.font,color:i.textPrimary,lineHeight:1.1,letterSpacing:"-0.02em"},children:A}),s.jsxs("div",{style:{fontSize:10,color:i.textMuted,fontFamily:i.fontMono},children:["from ",u.rows.length.toLocaleString()," rows"]})]})]})]})}function bs({label:e,theme:t,children:n}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[s.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:t.textMuted,textTransform:"uppercase",fontFamily:t.font},children:e}),n]})}const V1=["sum","avg","count","min","max","count_distinct"],X1={rows:[],columns:[],values:[]};function wu(e,t){return t.map(n=>String(e[n]??"")).join("|")}function pl(e,t){return e.metrics.includes(t)?"metric":e.dimensions.includes(t)?"dimension":"column"}function Uu(e,t){const n=e.fields.filter(o=>o.kind===t),r=e.fields.filter(o=>o.kind!==t);return[...n,...r].map(o=>({name:o.name,kind:o.kind}))}function z1({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const i=ie[r],a=e.pivotConfig??X1,l={upstream:a.upstream,rows:a.rows??[],columns:a.columns??[],values:a.values??[]},c=f.useMemo(()=>{const S=e.upstream??l.upstream;if(S)return t.find(R=>R.name===S)},[e.upstream,l.upstream,t]),d=f.useMemo(()=>t.slice(0,n).filter(S=>S.name&&S.result),[t,n]),E=c==null?void 0:c.result;E==null||E.columns;const u=f.useMemo(()=>Ta(E),[E]),T=f.useMemo(()=>Uu(u,"dimension"),[u]),p=f.useMemo(()=>Uu(u,"metric"),[u]),h=S=>o({pivotConfig:S}),A=f.useMemo(()=>{if(!E||l.rows.length===0&&l.columns.length===0||l.values.length===0)return null;const S=new Set,R=new Map;for(const N of E.rows){const x=wu(N,l.rows),g=wu(N,l.columns);S.add(g);let C=R.get(x);if(!C){const w={};for(const v of l.rows)w[v]=N[v];C={row:w,groups:new Map},R.set(x,C)}const y=C.groups.get(g)??[];y.push(N),C.groups.set(g,y)}const m=[...S].sort(),I=m.map(N=>N===""?"value":N),O=[];for(const[,N]of R){const x=N,g=m.map(C=>{const y=x.groups.get(C)??[],w={};for(const v of l.values){const B=y.map(b=>b[v.column]);w[`${v.aggregation}(${v.column})`]=wc(B,v.aggregation)}return w});O.push({rowDims:x.row,values:g})}return{columnKeys:m,columnHeaders:I,body:O}},[l,E]);return!c||!E?s.jsx(Yo,{theme:i,accentColor:"#a371f7",cellLabel:"Pivot",cellName:e.name,description:"Pivots reshape an upstream dataframe into a rows × columns grid. Pick dimensions for rows/columns and a metric for values.",upstreamOptions:d,onPick:S=>o({upstream:S})}):s.jsxs("div",{style:{background:i.cellBg,border:`1px solid ${i.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,fontFamily:i.font,overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${i.cellBorder}`,background:`${i.tableHeaderBg}60`},children:[s.jsx("span",{style:{fontSize:10,fontFamily:i.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Pivot"}),e.name&&s.jsx("span",{style:{fontSize:12,fontFamily:i.fontMono,color:i.textSecondary},children:e.name}),s.jsxs("span",{style:{fontSize:11,color:i.textMuted,fontFamily:i.fontMono},children:["· df: ",c.name]}),s.jsx("button",{onClick:()=>o({upstream:void 0}),style:{fontSize:10,background:"transparent",border:`1px solid ${i.btnBorder}`,borderRadius:3,color:i.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:i.fontMono},children:"change"})]}),!u.hasSemanticBinding&&s.jsx("div",{style:{padding:"8px 12px 0"},children:s.jsx(fa,{theme:i})}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",padding:12,gap:10,borderBottom:`1px solid ${i.cellBorder}`},children:[s.jsx(Bu,{label:"Rows",selected:l.rows,availableFields:T.filter(S=>!l.rows.includes(S.name)),kindFor:S=>pl(u,S),theme:i,onAdd:S=>h({...l,rows:[...l.rows,S]}),onRemove:S=>h({...l,rows:l.rows.filter(R=>R!==S)})}),s.jsx(Bu,{label:"Columns",selected:l.columns,availableFields:T.filter(S=>!l.columns.includes(S.name)),kindFor:S=>pl(u,S),theme:i,onAdd:S=>h({...l,columns:[...l.columns,S]}),onRemove:S=>h({...l,columns:l.columns.filter(R=>R!==S)})}),s.jsx(K1,{values:l.values,availableFields:p,kindFor:S=>pl(u,S),theme:i,onAdd:S=>h({...l,values:[...l.values,{column:S,aggregation:"sum"}]}),onUpdate:(S,R)=>h({...l,values:l.values.map((m,I)=>I===S?{...m,...R}:m)}),onRemove:S=>h({...l,values:l.values.filter((R,m)=>m!==S)})})]}),s.jsx("div",{style:{padding:12,overflowX:"auto"},children:!A||A.body.length===0?s.jsx("div",{style:{fontSize:11,color:i.textMuted,fontFamily:i.font},children:"Pick at least one row/column dimension and one value to see a preview."}):s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontFamily:i.fontMono,fontSize:11},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[l.rows.map(S=>s.jsx("th",{style:{textAlign:"left",padding:"4px 8px",borderBottom:`1px solid ${i.cellBorder}`,color:i.textSecondary,fontWeight:600},children:S},S)),A.columnHeaders.map((S,R)=>s.jsx("th",{style:{textAlign:"right",padding:"4px 8px",borderBottom:`1px solid ${i.cellBorder}`,color:i.textSecondary,fontWeight:600},children:S},R))]})}),s.jsx("tbody",{children:A.body.slice(0,50).map((S,R)=>s.jsxs("tr",{children:[l.rows.map(m=>s.jsx("td",{style:{padding:"3px 8px",color:i.textPrimary,borderBottom:`1px solid ${i.cellBorder}30`},children:String(S.rowDims[m]??"")},m)),S.values.map((m,I)=>s.jsx("td",{style:{padding:"3px 8px",color:i.textPrimary,textAlign:"right",borderBottom:`1px solid ${i.cellBorder}30`},children:Object.values(m).map((O,N)=>s.jsx("div",{children:O===null?"—":typeof O=="number"?O.toLocaleString(void 0,{maximumFractionDigits:2}):String(O)},N))},I))]},R))})]})})]})}function Bu({label:e,selected:t,availableFields:n,kindFor:r,theme:o,onAdd:i,onRemove:a}){return s.jsx(fh,{label:e,theme:o,availableFields:n,onAdd:i,children:t.length===0?s.jsx("span",{style:{fontSize:11,color:o.textMuted,fontFamily:o.font},children:"+ add field"}):t.map(l=>{const c=r(l);return s.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 6px",background:`${o.accent}14`,border:`1px solid ${o.accent}55`,borderRadius:3,fontSize:11,fontFamily:o.fontMono,color:o.textPrimary,margin:2},children:[s.jsx("span",{style:{color:No(c,o.accent),fontWeight:700},children:Oo(c)}),l,s.jsx("span",{onClick:()=>a(l),style:{cursor:"pointer",color:o.textMuted,fontSize:10},title:"Remove",children:"✕"})]},l)})})}function K1({values:e,availableFields:t,kindFor:n,theme:r,onAdd:o,onUpdate:i,onRemove:a}){return s.jsx(fh,{label:"Values",theme:r,availableFields:t,onAdd:o,children:e.length===0?s.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:"+ add value"}):e.map((l,c)=>{const d=n(l.column);return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,margin:2},children:[s.jsx("select",{value:l.aggregation,onChange:E=>i(c,{aggregation:E.target.value}),style:{background:r.editorBg,border:`1px solid ${r.cellBorder}`,borderRadius:3,color:r.textSecondary,fontSize:10,fontFamily:r.fontMono,padding:"1px 4px"},children:V1.map(E=>s.jsx("option",{value:E,children:E},E))}),s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 6px",background:`${r.accent}14`,border:`1px solid ${r.accent}55`,borderRadius:3,fontSize:11,fontFamily:r.fontMono,color:r.textPrimary},children:[s.jsx("span",{style:{color:No(d,r.accent),fontWeight:700},children:Oo(d)}),l.column,s.jsx("span",{onClick:()=>a(c),style:{cursor:"pointer",color:r.textMuted,fontSize:10},children:"✕"})]})]},c)})})}function fh({label:e,theme:t,availableFields:n,onAdd:r,children:o}){const[i,a]=f.useState(!1),l=f.useRef(null);return f.useEffect(()=>{if(!i)return;const c=d=>{var E;(E=l.current)!=null&&E.contains(d.target)||a(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[i]),s.jsxs("div",{ref:l,style:{position:"relative",display:"flex",flexDirection:"column",gap:4},children:[s.jsx("div",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:t.textMuted,textTransform:"uppercase",fontFamily:t.font},children:e}),s.jsx("div",{onClick:()=>a(c=>!c),style:{minHeight:42,border:`1px dashed ${t.cellBorder}`,borderRadius:4,padding:4,cursor:"pointer",display:"flex",flexWrap:"wrap",alignItems:"center"},children:o}),i&&n.length>0&&s.jsx("div",{style:{position:"absolute",top:"calc(100% + 2px)",left:0,right:0,zIndex:10,background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:6,boxShadow:"0 6px 16px rgba(0,0,0,0.25)",padding:4,maxHeight:200,overflow:"auto"},children:n.map(c=>s.jsxs("button",{onClick:()=>{r(c.name),a(!1)},style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 8px",background:"transparent",border:"none",borderRadius:3,cursor:"pointer",textAlign:"left",color:t.textPrimary,fontFamily:t.fontMono,fontSize:11},onMouseEnter:d=>{d.currentTarget.style.background=t.tableRowHover},onMouseLeave:d=>{d.currentTarget.style.background="transparent"},children:[s.jsx("span",{style:{color:No(c.kind,t.accent),fontWeight:700,width:12},children:Oo(c.kind)}),s.jsx("span",{children:c.name})]},c.name))})]})}const Ds="#79c0ff";function q1({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const i=ie[r],a=e.tableConfig??{},l=f.useMemo(()=>{const T=e.upstream??a.upstream;if(T)return t.find(p=>p.name===T)},[e.upstream,a.upstream,t]),c=f.useMemo(()=>t.slice(0,n).filter(T=>T.name&&T.result),[t,n]),d=l==null?void 0:l.result,E=a.visibleColumns,u=f.useMemo(()=>{if(!d)return;if(!E||E.length===0)return d;const T=new Set(d.columns),p=E.filter(h=>T.has(h));return p.length===0?d:{...d,columns:p}},[d,E]);return!l||!u?s.jsx(Yo,{theme:i,accentColor:Ds,cellLabel:"Table",cellName:e.name,description:"Renders an upstream dataframe — the rows of a named SQL, DQL, or Block cell above — as a sortable, exportable table. Use visibleColumns in tableConfig to pin a subset.",upstreamOptions:c,onPick:T=>o({upstream:T})}):s.jsxs("div",{style:{display:"flex",flexDirection:"column",background:i.cellBg,border:`1px solid ${i.cellBorder}`,borderLeft:`3px solid ${Ds}`,borderRadius:6,overflow:"hidden",fontFamily:i.font},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${i.cellBorder}`,background:`${i.tableHeaderBg}60`},children:[s.jsx("span",{style:{fontSize:10,fontFamily:i.fontMono,fontWeight:700,letterSpacing:"0.08em",color:Ds,background:`${Ds}18`,padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Table"}),e.name&&s.jsx("span",{style:{fontSize:12,fontFamily:i.fontMono,color:i.textSecondary},children:e.name}),s.jsxs("span",{style:{fontSize:11,color:i.textMuted,fontFamily:i.fontMono},children:["· df: ",e.upstream??a.upstream]}),s.jsx("button",{onClick:()=>o({upstream:void 0}),title:"Change upstream dataframe",style:{fontSize:10,background:"transparent",border:`1px solid ${i.btnBorder}`,borderRadius:3,color:i.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:i.fontMono},children:"change"}),s.jsx("div",{style:{flex:1}}),s.jsxs("span",{style:{fontSize:11,color:i.textMuted,fontFamily:i.fontMono},children:[u.rows.length.toLocaleString()," rows · ",u.columns.length," cols"]})]}),s.jsx(Kn,{result:u,themeMode:r})]})}async function ph(e,t){const n=await fetch("/api/llm/run",{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify({provider:e.provider,messages:e.messages,upstream:e.upstream}),signal:e.signal});if(!n.ok){const a=await n.text().catch(()=>n.statusText);throw new Error(a||`HTTP ${n.status}`)}if(!n.body)throw new Error("Response has no body");const r=n.body.getReader(),o=new TextDecoder;let i="";try{for(;;){const{value:a,done:l}=await r.read();if(l)break;i+=o.decode(a,{stream:!0});let c;for(;(c=i.indexOf(`
|
|
623
|
-
|
|
624
|
-
`))!==-1;){const d=i.slice(0,c);i=i.slice(c+2);const E=d.split(`
|
|
625
|
-
`).find(u=>u.startsWith("data: "));if(E)try{t(JSON.parse(E.slice(6)))}catch{}}}}finally{r.releaseLock()}}function Ms(){return s.jsx("span",{style:{color:"#ff7b72",marginLeft:2},children:"*"})}function Sl(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function J1(e){const t=new Set,n=/@(metric|dim)\(([^)]+)\)/gi;let r;for(;r=n.exec(e);)t.add(r[2].trim());return Array.from(t)}function Sh({cell:e,onClose:t,onSaved:n,initialContent:r,initialName:o,initialDescription:i,initialTags:a}){const{state:l,dispatch:c}=fe(),d=ie[l.themeMode],E=f.useRef(null),[u,T]=f.useState(o||e.name||"new_block"),[p,h]=f.useState(""),[A,S]=f.useState(""),[R,m]=f.useState(i??l.notebookMetadata.description??""),[I,O]=f.useState((a??l.notebookMetadata.categories??[]).join(", ")),[N,x]=f.useState(r??e.content),[g,C]=f.useState(""),[y,w]=f.useState(""),[v,B]=f.useState([]),[b,L]=f.useState(!1),[D,M]=f.useState(null),U=f.useMemo(()=>J1(N),[N]),P=f.useMemo(()=>I.split(",").map($=>$.trim()).filter(Boolean),[I]),_=[{id:"has-name",label:"Block has name",severity:"error",passed:!!u.trim()},{id:"has-description",label:"Block has description",severity:"error",passed:!!R.trim()},{id:"has-owner",label:"Block has owner",severity:"error",passed:!!A.trim()},{id:"has-domain",label:"Block has domain",severity:"error",passed:!!p.trim()},{id:"has-tags",label:"Has at least one tag",severity:"warning",passed:P.length>0},{id:"has-llm-context",label:"Has LLM context (for agents)",severity:"warning",passed:!!g.trim()}],F=_.some($=>$.severity==="error"&&!$.passed);f.useEffect(()=>{var $;($=E.current)==null||$.focus()},[]),f.useEffect(()=>{const $=Z=>{Z.key==="Escape"&&t()};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[t]);const k=l.semanticLayer.domains,H=`${p.trim()?`blocks/${Sl(p)}/`:"blocks/"}${Sl(u)||"new-block"}.dql`,Q=async()=>{var $;if(F){M("Fix the required governance fields before saving.");return}if(!N.trim()){M("Block content is required.");return}L(!0),M(null);try{const Z=y.split(`
|
|
626
|
-
`).map(re=>re.trim()).filter(Boolean),Y=v.map(re=>({question:re.question.trim(),sql:re.sql.trim()||void 0})).filter(re=>re.question),G=await z.saveAsBlock({cellId:e.id,notebookPath:(($=l.activeFile)==null?void 0:$.path)??null,name:u.trim(),domain:p.trim()||void 0,owner:A.trim()||void 0,content:N,description:R.trim()||void 0,tags:P,metricRefs:U,llmContext:g.trim()||void 0,examples:Y.length>0?Y:void 0,invariants:Z.length>0?Z:void 0}),J={name:`${Sl(u)||"new-block"}.dql`,path:G.path,type:"block",folder:"blocks"};l.files.some(re=>re.path===G.path)||c({type:"FILE_ADDED",file:J});const te=await z.openBlockStudio(G.path);c({type:"OPEN_BLOCK_STUDIO",file:J,payload:te}),n==null||n({...G,name:u.trim()}),t()}catch(Z){M(Z instanceof Error?Z.message:String(Z))}finally{L(!1)}},q={width:"100%",background:d.inputBg,border:`1px solid ${D?d.error:d.inputBorder}`,borderRadius:6,color:d.textPrimary,fontSize:13,fontFamily:d.font,padding:"8px 12px",outline:"none",boxSizing:"border-box"};return s.jsx("div",{onClick:$=>{$.target===$.currentTarget&&t()},style:{position:"fixed",inset:0,background:d.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1100,backdropFilter:"blur(4px)"},children:s.jsxs("div",{style:{width:760,maxWidth:"calc(100vw - 48px)",maxHeight:"calc(100vh - 48px)",overflow:"auto",background:d.modalBg,border:`1px solid ${d.cellBorder}`,borderRadius:12,boxShadow:"0 20px 60px rgba(0,0,0,0.5)"},children:[s.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s.jsx("h2",{style:{margin:0,fontSize:16,fontWeight:600,color:d.textPrimary,fontFamily:d.font},children:"Save as Block"}),s.jsx("button",{onClick:t,style:{background:"transparent",border:"none",color:d.textMuted,cursor:"pointer",fontSize:18},children:"×"})]}),s.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},children:[s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsxs("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:["Block Name ",s.jsx(Ms,{})]}),s.jsx("input",{ref:E,value:u,onChange:$=>T($.target.value),style:q})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsxs("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:["Domain ",s.jsx(Ms,{})]}),s.jsx("input",{value:p,onChange:$=>h($.target.value),list:"semantic-domain-options",style:q,placeholder:"finance"}),s.jsx("datalist",{id:"semantic-domain-options",children:k.map($=>s.jsx("option",{value:$},$))})]})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsxs("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:["Owner ",s.jsx(Ms,{})]}),s.jsx("input",{value:A,onChange:$=>S($.target.value),style:q,placeholder:"data-platform@company.com"})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsx("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:"Tags"}),s.jsx("input",{value:I,onChange:$=>O($.target.value),style:q,placeholder:"revenue, dashboard"})]})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsxs("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:["Description ",s.jsx(Ms,{})]}),s.jsx("input",{value:R,onChange:$=>m($.target.value),style:q})]}),s.jsxs("details",{style:{border:`1px solid ${d.cellBorder}`,borderRadius:6,padding:"8px 12px"},children:[s.jsx("summary",{style:{fontSize:12,fontWeight:600,color:d.textSecondary,fontFamily:d.font,cursor:"pointer"},children:"Agent-facing metadata (optional — helps AI tools ground answers on this block)"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,paddingTop:10},children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsx("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:"How should an AI describe this block?"}),s.jsx("textarea",{value:g,onChange:$=>C($.target.value),rows:3,placeholder:'One paragraph. E.g. "Monthly revenue recognized from closed-won deals, grouped by billing month. Excludes refunds."',style:{...q,fontFamily:d.font,lineHeight:1.5,resize:"vertical"}})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsx("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:"Invariants (one per line)"}),s.jsx("textarea",{value:y,onChange:$=>w($.target.value),rows:2,placeholder:`Revenue is never negative
|
|
627
|
-
Each row is a unique month`,style:{...q,fontFamily:d.fontMono,lineHeight:1.5,resize:"vertical"}})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsx("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:"Example questions (grounding for chat cells)"}),v.map(($,Z)=>s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:6},children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("input",{value:$.question,onChange:Y=>{const G=[...v];G[Z]={...G[Z],question:Y.target.value},B(G)},placeholder:"What was revenue last month?",style:q}),s.jsx("input",{value:$.sql,onChange:Y=>{const G=[...v];G[Z]={...G[Z],sql:Y.target.value},B(G)},placeholder:"Optional SQL snippet",style:{...q,fontFamily:d.fontMono,fontSize:12}})]}),s.jsx("button",{type:"button",onClick:()=>B(v.filter((Y,G)=>G!==Z)),style:{background:"transparent",border:`1px solid ${d.cellBorder}`,borderRadius:6,color:d.textMuted,cursor:"pointer",fontSize:12,padding:"0 10px"},children:"×"})]},Z)),s.jsx("button",{type:"button",onClick:()=>B([...v,{question:"",sql:""}]),style:{alignSelf:"flex-start",background:d.btnBg,border:`1px solid ${d.btnBorder}`,borderRadius:6,color:d.textSecondary,cursor:"pointer",fontSize:12,fontFamily:d.font,padding:"4px 10px"},children:"+ Add example"})]})]})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,padding:"10px 12px",background:d.pillBg,borderRadius:6,border:`1px solid ${d.cellBorder}`},children:[s.jsx("div",{style:{fontSize:11,fontWeight:700,color:d.textSecondary,fontFamily:d.font,letterSpacing:"0.06em",textTransform:"uppercase"},children:"Governance checks"}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:_.map($=>{const Z=$.passed?"#3fb950":$.severity==="error"?"#ff7b72":"#e3b341",Y=$.passed?"✓":$.severity==="error"?"✕":"!";return s.jsxs("span",{title:$.passed?`${$.label} — passed`:`${$.label} — ${$.severity}`,style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,fontFamily:d.font,color:Z,background:`${Z}18`,border:`1px solid ${Z}55`,borderRadius:999,padding:"2px 10px"},children:[s.jsx("span",{style:{fontWeight:700},children:Y}),$.label]},$.id)})})]}),s.jsx("div",{style:{fontSize:12,color:d.textMuted,fontFamily:d.fontMono,padding:"8px 12px",background:d.pillBg,borderRadius:6},children:H}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsx("label",{style:{fontSize:12,color:d.textSecondary,fontFamily:d.font},children:"Content Preview"}),s.jsx("textarea",{value:N,onChange:$=>x($.target.value),style:{...q,minHeight:220,resize:"vertical",fontFamily:d.fontMono,lineHeight:1.5}})]}),U.length>0&&s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,padding:"10px 12px",background:d.pillBg,borderRadius:6},children:[s.jsx("span",{style:{fontSize:11,color:d.textMuted,fontFamily:d.font},children:"Detected semantic refs:"}),U.map($=>s.jsx("span",{style:{fontSize:11,color:d.accent,fontFamily:d.fontMono,background:`${d.accent}18`,borderRadius:999,padding:"2px 8px"},children:$},$))]}),D&&s.jsx("div",{style:{fontSize:12,color:d.error,fontFamily:d.font},children:D})]}),s.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${d.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[s.jsx("button",{onClick:t,style:{background:d.btnBg,border:`1px solid ${d.btnBorder}`,borderRadius:6,color:d.textSecondary,cursor:"pointer",fontSize:13,fontFamily:d.font,padding:"7px 16px"},children:"Cancel"}),s.jsx("button",{onClick:Q,disabled:b||F,title:F?"Fix governance errors to enable Save":void 0,style:{background:d.accent,border:`1px solid ${d.accent}`,borderRadius:6,color:"#fff",cursor:b||F?"not-allowed":"pointer",fontSize:13,fontFamily:d.font,padding:"7px 20px",opacity:b||F?.5:1},children:b?"Saving...":"Save Block"})]})]})})}function $d(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.kind!=="tool_result"||n.id!=="governed_answer")continue;const r=n.output;if(r&&typeof r=="object"&&"kind"in r)return r}return null}function Q1(e){const t=e.result;if(!t||!Array.isArray(t.rows))return null;const r=(Array.isArray(t.columns)?t.columns:[]).map(i=>typeof i=="string"?i:i&&typeof i=="object"&&typeof i.name=="string"?String(i.name):String(i)),o=t.rows.filter(i=>!!(i&&typeof i=="object"&&!Array.isArray(i))).map(i=>i);return{columns:r,rows:o,rowCount:typeof t.rowCount=="number"?t.rowCount:o.length,executionTime:t.executionTime}}function Z1(e,t){const n=e&&typeof e=="object"?e:{},r=typeof n.chart=="string"?n.chart:typeof t.suggestedViz=="string"?t.suggestedViz:void 0;return{...r?{chart:r}:{},...typeof n.x=="string"?{x:n.x}:{},...typeof n.y=="string"?{y:n.y}:{},...typeof n.color=="string"?{color:n.color}:{},...typeof n.title=="string"?{title:n.title}:{}}}function Vd({answer:e,themeMode:t,showSql:n=!0,compact:r=!1,addToAppTarget:o}){var L,D,M,U,P,_,F,k,H;const i=ie[t],a=Q1(e),l=Z1((L=e.result)==null?void 0:L.chartConfig,e),c=!!(a&&Cr(a,l)!=="table"),d=n?e.sql??((D=e.result)==null?void 0:D.sql)??e.proposedSql:void 0,E=((M=e.result)==null?void 0:M.blockPath)??((U=e.block)==null?void 0:U.sourcePath),u=!!(d||n&&E),T=!!e.evidence,[p,h]=f.useState("answer"),[A,S]=f.useState(!1),R=e.certification==="certified"?"Certified":e.kind==="no_answer"?"No answer":"AI generated",m=e.certification==="certified"?"#3fb950":e.kind==="no_answer"?"#ff7b72":"#f0883e",I=(e.answer??e.text??"").replace(/\n\n_Question:_[\s\S]*$/m,"").trim(),O=((P=e.result)==null?void 0:P.blockName)??((_=e.block)==null?void 0:_.name)??((k=(F=e.citations)==null?void 0:F.find(Q=>Q.kind==="block"))==null?void 0:k.name),[N,x]=f.useState(!1),[g,C]=f.useState(null),y=!!(o&&(a||d||I||O)),w=async(Q="auto")=>{if(!o)return;const q=Q==="both"?["chart","data"]:Q==="data"?["data"]:Q==="chart"?["chart"]:a?[c?"chart":"data"]:[];x(!0),S(!1),C(null);try{if(e.certification==="certified"&&O){const $=await z.getDashboard(o.appId,o.dashboardId);if(!$)throw new Error("Dashboard could not be loaded.");const Z=[...$.dashboard.layout.items],Y=q.length>0?q:["chart"];for(const te of Y){const re=Y.length>1?`${O}_${te}`:O,oe={...$.dashboard,layout:{...$.dashboard.layout,items:Z}},V=cD(oe,re);Z.push({i:V,...lD(oe),block:{blockId:O},viz:{type:te==="data"?"table":dD(l==null?void 0:l.chart)},title:Y.length>1?`${O} ${te==="data"?"data":"chart"}`:O})}const G={...$.dashboard.layout,items:Z},J=await z.patchDashboardLayout(o.appId,o.dashboardId,G);if(!J.ok)throw new Error(J.error);C(Y.length>1?"Added certified chart and data tiles.":"Added certified block tile.")}else{const $=!!(d&&window.confirm("Keep this AI result refreshed daily?")),Z=O??(I.slice(0,60)||"AI result"),Y=q.length>0?q:["data"];for(const G of Y){const J=G==="data"?{...l??{},chart:"table",title:`${Z} data`}:l,te=await z.createAiPin(o.appId,{dashboardId:o.dashboardId,title:Y.length>1?`${Z} ${G==="data"?"data":"chart"}`:Z,answer:I||e.answer||e.text||"AI generated answer",sql:d,sourceTier:e.sourceTier,certification:e.certification==="certified"?"certified":"ai_generated",refreshCadence:$?"daily":"none",chartConfig:J,result:a??void 0,citations:e.citations});if(!te.ok)throw new Error(te.error)}C(Y.length>1?"Pinned chart and data tiles for review.":"Pinned AI result for review.")}window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:o}))}catch($){C($ instanceof Error?$.message:String($))}finally{x(!1)}},B=[{id:"answer",label:"Answer",visible:!0},{id:"visual",label:r?"Chart":"Visualization",visible:c},{id:"data",label:"Data",visible:!!a},{id:"lineage",label:"Lineage",visible:T},{id:"context",label:r?"Context":"Business Context",visible:T},{id:"sql",label:"SQL / Block",visible:n&&u},{id:"review",label:"Review",visible:T||!!((H=e.citations)!=null&&H.length)}].filter(Q=>Q.visible),b=B.some(Q=>Q.id===p)?p:"answer";return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:r?8:10,whiteSpace:"normal"},children:[s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[s.jsx("span",{style:{fontSize:10,fontFamily:i.fontMono,fontWeight:700,letterSpacing:"0.08em",color:m,textTransform:"uppercase",padding:"2px 6px",borderRadius:3,background:`${m}18`,border:`1px solid ${m}40`},children:R}),O&&s.jsxs("span",{style:{fontSize:12,fontFamily:i.fontMono,color:i.textSecondary},children:["block: ",O]}),a&&s.jsxs("span",{style:{fontSize:12,color:i.textMuted},children:[(a.rowCount??a.rows.length).toLocaleString()," rows",a.executionTime!==void 0&&s.jsxs(s.Fragment,{children:[" - ",Math.round(a.executionTime),"ms"]})]}),y&&s.jsx(iD,{t:i,adding:N,hasResult:!!a,hasChart:c,fallbackLabel:e.certification==="certified"&&O?"Add block":"Add summary",open:A,onToggle:()=>S(Q=>!Q),onAdd:Q=>void w(Q)})]}),g&&s.jsx("div",{style:{fontSize:11,color:g.toLowerCase().includes("added")||g.toLowerCase().includes("pinned")?"#3fb950":"#ff7b72"},children:g}),s.jsxs("div",{style:{border:`1px solid ${i.cellBorder}`,borderRadius:6,overflow:"hidden",background:i.cellBg},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:`1px solid ${i.cellBorder}`,background:`${i.tableHeaderBg}70`,flexWrap:"wrap"},children:[B.map(Q=>s.jsx(sD,{active:b===Q.id,label:Q.label,onClick:()=>h(Q.id),t:i},Q.id)),!n&&E&&s.jsx("span",{style:{marginLeft:"auto",minWidth:0,fontSize:11,fontFamily:i.fontMono,color:i.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:E})]}),b==="answer"&&s.jsx(eD,{summary:I,evidence:e.evidence,result:a,sourceTier:e.sourceTier,compact:r,t:i}),b==="visual"&&a&&c&&s.jsx("div",{style:{padding:r?"8px 10px":"10px 12px",minHeight:r?180:220},children:s.jsx(Yd,{result:a,themeMode:t,chartConfig:l})}),b==="data"&&a&&s.jsx("div",{style:{maxHeight:r?320:420,overflow:"auto"},children:s.jsx(Kn,{result:a,themeMode:t})}),b==="lineage"&&s.jsx(tD,{evidence:e.evidence,t:i}),b==="context"&&s.jsx(nD,{evidence:e.evidence,t:i}),b==="sql"&&n&&u&&s.jsx(oD,{sql:d,blockPath:E,t:i}),b==="review"&&s.jsx(rD,{answer:e,t:i})]})]})}function eD({summary:e,evidence:t,result:n,sourceTier:r,compact:o,t:i}){var a,l;return s.jsxs("div",{style:{padding:o?14:12,display:"flex",flexDirection:"column",gap:o?10:12},children:[e?s.jsx("div",{style:{fontSize:o?13.5:13,lineHeight:1.55,color:i.textPrimary,whiteSpace:"pre-wrap"},children:e}):s.jsx("div",{style:{fontSize:12,color:i.textMuted},children:"No summary text was returned."}),s.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[r&&s.jsx(cn,{label:jn(r),t:i}),n&&s.jsx(cn,{label:`${(n.rowCount??n.rows.length).toLocaleString()} rows`,t:i}),((a=t==null?void 0:t.validation)==null?void 0:a.status)&&s.jsx(cn,{label:`validation: ${t.validation.status}`,t:i}),((l=t==null?void 0:t.execution)==null?void 0:l.status)&&s.jsx(cn,{label:`execution: ${t.execution.status}`,t:i})]}),!o&&(t==null?void 0:t.route)&&t.route.length>0&&s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsx(go,{t:i,children:"Route"}),t.route.map((c,d)=>s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"120px 1fr",gap:10,fontSize:12,alignItems:"baseline"},children:[s.jsx("span",{style:{fontFamily:i.fontMono,color:aD(c.status),minWidth:0},children:c.tool??"step"}),s.jsxs("span",{style:{color:i.textSecondary},children:[c.label??c.status,c.detail&&s.jsxs("span",{style:{color:i.textMuted},children:[" (",c.detail,")"]})]})]},`${c.tool}-${d}`))]}),(t==null?void 0:t.selectedAssets)&&t.selectedAssets.length>0&&s.jsx(Uc,{title:"Selected Assets",assets:t.selectedAssets,t:i})]})}function tD({evidence:e,t}){const n=(e==null?void 0:e.lineage)??[];return n.length===0?s.jsx(Rh,{t,children:"No lineage evidence was returned for this answer."}):s.jsx("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:10},children:n.map((r,o)=>s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"20px 1fr",gap:8},children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center"},children:[s.jsx("div",{style:{width:8,height:8,borderRadius:8,marginTop:5,background:r.role==="question"?t.accent:t.textMuted}}),o<n.length-1&&s.jsx("div",{style:{width:1,flex:1,minHeight:18,background:t.cellBorder}})]}),s.jsxs("div",{style:{minWidth:0},children:[s.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"},children:[s.jsx("span",{style:{fontSize:12,fontWeight:700,color:t.textPrimary},children:r.name??r.nodeId}),r.role&&s.jsx(cn,{label:jn(r.role),t}),r.kind&&s.jsx(cn,{label:jn(r.kind),t})]}),r.description&&s.jsx("div",{style:{fontSize:12,color:t.textSecondary,marginTop:3},children:r.description}),(r.sourcePath||r.provenance)&&s.jsxs("div",{style:{fontSize:11,color:t.textMuted,fontFamily:t.fontMono,marginTop:3,overflow:"hidden",textOverflow:"ellipsis"},children:[r.provenance??r.sourcePath,r.sourcePath&&r.provenance?` - ${r.sourcePath}`:""]})]})]},`${r.nodeId??r.name}-${o}`))})}function nD({evidence:e,t}){var o;const n=(e==null?void 0:e.businessContext)??[],r=e==null?void 0:e.outcome;return!r&&n.length===0?s.jsx(Rh,{t,children:"No business context was returned for this answer."}):s.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:12},children:[r&&s.jsxs("div",{style:{display:"grid",gap:6},children:[s.jsx(go,{t,children:"Outcome"}),r.name&&s.jsx(tt,{label:"Outcome",value:r.name,t}),r.owner&&s.jsx(tt,{label:"Owner",value:r.owner,t}),r.decisionUse&&s.jsx(tt,{label:"Decision Use",value:r.decisionUse,t}),r.reviewCadence&&s.jsx(tt,{label:"Review Cadence",value:r.reviewCadence,t}),(o=r.caveats)==null?void 0:o.map((i,a)=>s.jsx(tt,{label:"Caveat",value:i,t},`caveat-${a}`))]}),n.length>0&&s.jsxs("div",{style:{display:"grid",gap:6},children:[s.jsx(go,{t,children:"Context"}),n.map((i,a)=>s.jsx(tt,{label:i.label??"Context",value:i.value??"",source:i.source,t},`${i.label}-${a}`))]}),(e==null?void 0:e.semanticObjects)&&e.semanticObjects.length>0&&s.jsx(Uc,{title:"Semantic Objects",assets:e.semanticObjects,t}),(e==null?void 0:e.sourceTables)&&e.sourceTables.length>0&&s.jsx(Uc,{title:"Source Tables",assets:e.sourceTables,t})]})}function rD({answer:e,t}){var o,i;const n=e.evidence,r=(n==null?void 0:n.citations)??e.citations??[];return s.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:12},children:[s.jsxs("div",{style:{display:"grid",gap:6},children:[s.jsx(tt,{label:"Certification",value:jn(e.certification??e.kind),t}),e.reviewStatus&&s.jsx(tt,{label:"Review Status",value:jn(e.reviewStatus),t}),typeof e.confidence=="number"&&s.jsx(tt,{label:"Confidence",value:`${Math.round(e.confidence*100)}%`,t}),((o=n==null?void 0:n.validation)==null?void 0:o.message)&&s.jsx(tt,{label:`Validation ${n.validation.status??""}`.trim(),value:n.validation.message,t}),((i=n==null?void 0:n.execution)==null?void 0:i.message)&&s.jsx(tt,{label:`Execution ${n.execution.status??""}`.trim(),value:n.execution.message,t}),e.kind!=="certified"&&s.jsx(tt,{label:"Promotion Path",value:"Create draft block, edit SQL, attach tests, then certify after analyst approval.",t})]}),r.length>0&&s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsx(go,{t,children:"Citations"}),r.slice(0,8).map((a,l)=>s.jsxs("div",{style:{fontSize:12,color:t.textSecondary,fontFamily:t.fontMono},children:[a.kind??"source",": ",a.name??"unknown",a.provenance&&s.jsxs("span",{style:{color:t.textMuted},children:[" (",a.provenance,")"]})]},`${a.kind}-${a.name}-${l}`))]})]})}function Uc({title:e,assets:t,t:n}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsx(go,{t:n,children:e}),t.map((r,o)=>s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,paddingBottom:4},children:[s.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"},children:[s.jsx("span",{style:{fontSize:12,fontWeight:700,color:n.textPrimary},children:r.name??r.nodeId}),r.kind&&s.jsx(cn,{label:jn(r.kind),t:n}),r.certification&&s.jsx(cn,{label:jn(r.certification),t:n})]}),r.description&&s.jsx("div",{style:{fontSize:12,color:n.textSecondary},children:r.description}),(r.sourcePath||r.owner||r.domain)&&s.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.fontMono},children:[r.domain,r.owner,r.sourcePath].filter(Boolean).join(" - ")})]},`${r.nodeId??r.name}-${o}`))]})}function oD({sql:e,blockPath:t,t:n}){return s.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:8},children:[t&&s.jsxs("div",{style:{fontSize:12,color:n.textSecondary},children:["Source block: ",s.jsx("span",{style:{fontFamily:n.fontMono,color:n.textPrimary},children:t})]}),e?s.jsx("pre",{style:{margin:0,padding:10,overflow:"auto",maxHeight:260,borderRadius:4,background:n.editorBg,color:n.textPrimary,border:`1px solid ${n.cellBorder}`,fontSize:12,fontFamily:n.fontMono,whiteSpace:"pre"},children:e}):s.jsx("div",{style:{fontSize:12,color:n.textMuted},children:"No SQL text was returned for this answer."})]})}function tt({label:e,value:t,source:n,t:r}){return t?s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"130px 1fr",gap:10,fontSize:12,alignItems:"baseline"},children:[s.jsx("span",{style:{color:r.textMuted},children:e}),s.jsxs("span",{style:{color:r.textSecondary},children:[t,n&&s.jsxs("span",{style:{color:r.textMuted},children:[" (",n,")"]})]})]}):null}function go({children:e,t}){return s.jsx("div",{style:{fontSize:11,fontWeight:700,fontFamily:t.fontMono,color:t.textMuted,textTransform:"uppercase",letterSpacing:"0.08em"},children:e})}function Rh({children:e,t}){return s.jsx("div",{style:{padding:12,fontSize:12,color:t.textMuted},children:e})}function cn({label:e,t}){return s.jsx("span",{style:{fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,padding:"2px 6px",borderRadius:4,background:t.editorBg,border:`1px solid ${t.cellBorder}`},children:e})}function sD({active:e,label:t,onClick:n,t:r}){return s.jsx("button",{onClick:n,style:{padding:"3px 8px",fontSize:11,borderRadius:4,border:`1px solid ${e?r.accent:r.btnBorder}`,background:e?`${r.accent}18`:"transparent",color:e?r.accent:r.textSecondary,cursor:"pointer"},children:t})}function iD({t:e,adding:t,hasResult:n,hasChart:r,fallbackLabel:o,open:i,onToggle:a,onAdd:l}){if(!n)return s.jsx("button",{type:"button",onClick:()=>l("auto"),disabled:t,style:{...Fu(e,t),marginLeft:"auto"},children:t?"Adding...":o});const c=r?[{mode:"both",label:"Chart + data",description:"Add chart and table tiles"},{mode:"chart",label:"Chart only",description:"Add the visualization tile"},{mode:"data",label:"Data table",description:"Add the rows as a table tile"}]:[{mode:"data",label:"Data table",description:"Add the rows as a table tile"}];return s.jsxs("div",{style:{marginLeft:"auto",position:"relative"},children:[s.jsxs("button",{type:"button",onClick:a,disabled:t,style:Fu(e,t),children:[t?"Adding...":"Add to App",!t&&s.jsx("span",{style:{marginLeft:6,fontSize:10},children:"v"})]}),i&&!t&&s.jsx("div",{style:{position:"absolute",right:0,top:"calc(100% + 6px)",zIndex:30,width:190,border:`1px solid ${e.cellBorder}`,borderRadius:8,background:e.cellBg,boxShadow:"0 14px 34px rgba(0, 0, 0, 0.18)",padding:6},children:c.map(d=>s.jsxs("button",{type:"button",onClick:()=>l(d.mode),style:{width:"100%",border:0,borderRadius:6,background:"transparent",color:e.textPrimary,textAlign:"left",padding:"8px 9px",cursor:"pointer"},children:[s.jsx("div",{style:{fontSize:12,fontWeight:700},children:d.label}),s.jsx("div",{style:{fontSize:11,color:e.textMuted,marginTop:2},children:d.description})]},d.mode))})]})}function Fu(e,t){return{border:`1px solid ${e.btnBorder}`,borderRadius:5,background:t?e.editorBg:`${e.accent}18`,color:t?e.textMuted:e.accent,padding:"4px 8px",fontSize:11,cursor:t?"default":"pointer"}}function jn(e){return e.replace(/_/g," ")}function aD(e){return e==="selected"||e==="passed"||e==="executed"?"#3fb950":e==="failed"?"#ff7b72":e==="warning"||e==="checked"?"#f0883e":"#8b949e"}function lD(e){return{x:0,y:e.layout.items.reduce((n,r)=>Math.max(n,r.y+r.h),0),w:6,h:3}}function cD(e,t){const n=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tile",r=new Set(e.layout.items.map(o=>o.i));if(!r.has(n))return n;for(let o=2;o<1e3;o++){const i=`${n}-${o}`;if(!r.has(i))return i}return`${n}-${Date.now()}`}function dD(e){const t=String(e??"table").toLowerCase().replace(/-/g,"_");return t==="single_value"||t==="kpi"||t==="line"||t==="bar"||t==="area"||t==="pie"||t==="pivot"||t==="map"||t==="funnel"?t:"table"}function ku(){return`m_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function ED(e,t,n){if(n){const r=e.find(o=>o.name===n);if(r!=null&&r.content)return r.content}for(let r=t-1;r>=0;r--){const o=e[r];if((o.type==="sql"||o.type==="dql")&&o.content)return o.content}}function uD({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const{dispatch:i}=fe(),a=ie[r],l={history:[],...e.chatConfig},[c,d]=f.useState(""),[E,u]=f.useState(!1),[T,p]=f.useState(""),[h,A]=f.useState([]),[S,R]=f.useState(null),[m,I]=f.useState(!1),O=f.useRef(null),N=w=>{o({chatConfig:{...l,...w}})},x=async()=>{const w=c.trim();if(!w||E)return;const v={id:ku(),role:"user",content:w},B={id:ku(),role:"assistant",content:"",events:[]},b=[...l.history,v,B];N({history:b}),d(""),p(""),A([]),R(null),u(!0);const L=new AbortController;O.current=L;let D="";const M=[];let U;try{await ph({messages:[...l.history,v].map(P=>({role:P.role,content:P.content})),upstream:{cellId:e.id,sql:ED(t,n,l.upstream)},signal:L.signal},P=>{M.push(P),A([...M]),P.kind==="text"?(D+=P.text,p(D)):P.kind==="error"?R(P.message):P.kind==="proposal"&&(U={...P.proposal,certified:P.governance.certified,errors:P.governance.errors,warnings:P.governance.warnings})})}catch(P){R(P instanceof Error?P.message:String(P))}finally{const P=b.map(_=>_.id===B.id?{..._,content:D,events:M.map(F=>({kind:F.kind,payload:F}))}:_);o({chatConfig:{...l,history:P,lastProposal:U??l.lastProposal}}),u(!1),p(""),A([]),O.current=null}},g=()=>{var w;(w=O.current)==null||w.abort()},C=()=>{N({history:[],lastProposal:void 0})},y=l.lastProposal;return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:"14px 16px",background:a.cellBg,fontFamily:a.font},children:[s.jsx(TD,{cell:e,onClear:l.history.length>0?C:void 0,t:a}),l.history.length===0&&!E&&s.jsx("div",{style:{fontSize:12,color:a.textSecondary,lineHeight:1.5},children:"Ask for a metric, a comparison, or a dashboard. The agent searches blocks, checks the semantic layer, and proposes a governed block when you're ready."}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[l.history.map(w=>s.jsx(fD,{msg:w,t:a,themeMode:r},w.id)),E&&s.jsx(pD,{streamingText:T,events:h,t:a,themeMode:r})]}),S&&s.jsx("div",{style:{fontSize:12,color:"#ff7b72",padding:"6px 10px",background:"#ff7b7218",borderRadius:4},children:S}),y&&s.jsx(RD,{proposal:y,t:a,onOpen:()=>I(!0),onDismiss:()=>N({lastProposal:void 0})}),s.jsx(SD,{value:c,onChange:d,onSend:x,onStop:g,running:E,t:a}),m&&y&&s.jsx(Sh,{cell:e,initialContent:y.sql,initialName:y.name,initialDescription:y.description,initialTags:y.tags,onClose:()=>I(!1),onSaved:({path:w,name:v})=>{I(!1),N({lastProposal:void 0}),i({type:"FILE_ADDED",file:{name:v,path:w,type:"block",folder:"blocks"}})}})]})}function TD({cell:e,onClear:t,t:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("span",{style:{fontSize:10,fontFamily:n.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#f0883e",textTransform:"uppercase",padding:"2px 6px",borderRadius:3,background:"#f0883e18"},children:"Chat"}),e.name&&s.jsx("span",{style:{fontSize:12,fontFamily:n.fontMono,color:n.textSecondary},children:e.name}),s.jsx("span",{title:"Configure the active AI provider in Settings",style:{marginLeft:"auto",fontSize:11,fontFamily:n.fontMono,color:n.textMuted},children:"Provider from Settings"}),t&&s.jsx("button",{onClick:t,style:{fontSize:11,padding:"3px 8px",background:"transparent",color:n.textSecondary,border:`1px solid ${n.cellBorder}`,borderRadius:4,cursor:"pointer"},children:"Clear"})]})}function fD({msg:e,t,themeMode:n}){const r=e.role==="user",o=(e.events??[]).map(a=>a.payload),i=r?null:$d(o);return s.jsxs("div",{style:{padding:"8px 12px",borderRadius:6,background:r?`${t.accent}14`:t.cellBg,border:`1px solid ${r?`${t.accent}40`:t.cellBorder}`,fontSize:13,lineHeight:1.5,color:t.textPrimary,whiteSpace:"pre-wrap"},children:[s.jsx("div",{style:{fontSize:10,fontFamily:t.fontMono,color:t.textMuted,marginBottom:4,textTransform:"uppercase",letterSpacing:"0.08em"},children:r?"You":"Assistant"}),i?s.jsx(Vd,{answer:i,themeMode:n}):e.content||(o.length>0?s.jsx("em",{style:{color:t.textSecondary},children:"(tool calls only)"}):null),o.filter(a=>a.kind==="tool_call").map(a=>s.jsx(hh,{turn:a,t},`tc-${a.id}`))]})}function pD({streamingText:e,events:t,t:n,themeMode:r}){const o=$d(t);return s.jsxs("div",{style:{padding:"8px 12px",borderRadius:6,background:n.cellBg,border:`1px solid ${n.cellBorder}`,fontSize:13,lineHeight:1.5,color:n.textPrimary,whiteSpace:"pre-wrap"},children:[s.jsxs("div",{style:{fontSize:10,fontFamily:n.fontMono,color:n.textMuted,marginBottom:4,textTransform:"uppercase",letterSpacing:"0.08em"},children:["Assistant ",s.jsx("span",{style:{color:n.accent},children:"●"})]}),o?s.jsx(Vd,{answer:o,themeMode:r}):e||s.jsx("em",{style:{color:n.textSecondary},children:"Thinking…"}),t.filter(i=>i.kind==="tool_call").map(i=>s.jsx(hh,{turn:i,t:n},`live-${i.id}`))]})}function hh({turn:e,t}){return e.kind!=="tool_call"?null:s.jsxs("div",{style:{marginTop:6,fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,padding:"4px 8px",background:t.cellBorder,borderRadius:4,display:"inline-block"},children:["🔧 ",e.name,"(",JSON.stringify(e.input).slice(0,80),JSON.stringify(e.input).length>80?"…":"",")"]})}function SD({value:e,onChange:t,onSend:n,onStop:r,running:o,t:i}){return s.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-end"},children:[s.jsx("textarea",{value:e,onChange:a=>t(a.target.value),onKeyDown:a=>{a.key==="Enter"&&(a.metaKey||a.ctrlKey)&&(a.preventDefault(),n())},placeholder:"Ask for a metric or dashboard — ⌘↵ to send",rows:2,style:{flex:1,resize:"vertical",minHeight:44,padding:"8px 10px",fontSize:13,fontFamily:i.font,background:i.cellBg,color:i.textPrimary,border:`1px solid ${i.cellBorder}`,borderRadius:6}}),o?s.jsx("button",{onClick:r,style:{padding:"8px 14px",fontSize:12,background:"#ff7b7218",color:"#ff7b72",border:"1px solid #ff7b72",borderRadius:6,cursor:"pointer"},children:"Stop"}):s.jsx("button",{onClick:n,disabled:!e.trim(),style:{padding:"8px 14px",fontSize:12,background:e.trim()?`${i.accent}28`:"transparent",color:e.trim()?i.accent:i.textMuted,border:`1px solid ${e.trim()?i.accent:i.cellBorder}`,borderRadius:6,cursor:e.trim()?"pointer":"not-allowed"},children:"Send"})]})}function RD({proposal:e,t,onOpen:n,onDismiss:r}){const o=[{id:"has-name",label:"Name",passed:!!e.name,severity:"error"},{id:"has-description",label:"Description",passed:!!e.description,severity:"error"},{id:"has-owner",label:"Owner",passed:!!e.owner,severity:"error"},{id:"has-domain",label:"Domain",passed:!!e.domain,severity:"error"},{id:"has-sql",label:"SQL",passed:!!e.sql,severity:"error"}];return s.jsxs("div",{style:{border:`1px solid ${e.certified?"#3fb950":t.cellBorder}`,borderLeft:`3px solid ${e.certified?"#3fb950":"#f0883e"}`,borderRadius:6,padding:"10px 12px",background:e.certified?"#3fb95010":"#f0883e10",display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("span",{style:{fontSize:10,fontFamily:t.fontMono,fontWeight:700,letterSpacing:"0.08em",color:e.certified?"#3fb950":"#f0883e",textTransform:"uppercase"},children:"Block Proposal"}),s.jsx("span",{style:{fontSize:13,fontFamily:t.fontMono,color:t.textPrimary},children:e.name}),e.domain&&s.jsxs("span",{style:{fontSize:11,color:t.textSecondary},children:["· ",e.domain]}),s.jsx("button",{onClick:r,style:{marginLeft:"auto",fontSize:11,padding:"2px 6px",background:"transparent",color:t.textMuted,border:"none",cursor:"pointer"},children:"✕"})]}),s.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:o.map(i=>s.jsxs("span",{style:{fontSize:10,fontFamily:t.fontMono,padding:"2px 6px",borderRadius:3,background:i.passed?"#3fb95020":"#ff7b7220",color:i.passed?"#3fb950":"#ff7b72",border:`1px solid ${i.passed?"#3fb95040":"#ff7b7240"}`},children:[i.passed?"✓":"✕"," ",i.label]},i.id))}),e.description&&s.jsx("div",{style:{fontSize:12,color:t.textSecondary},children:e.description}),s.jsx("div",{children:s.jsx("button",{onClick:n,style:{padding:"6px 12px",fontSize:12,background:`${t.accent}28`,color:t.accent,border:`1px solid ${t.accent}`,borderRadius:4,cursor:"pointer"},children:"Review & Save as Block"})})]})}const hD=[{id:"select-all",label:"Select all rows",description:"Read all rows from a CSV file with a row limit",category:"SQL",code:"SELECT * FROM read_csv_auto('data/filename.csv') LIMIT 100"},{id:"group-by",label:"Group and aggregate",description:"Group rows and compute count + sum",category:"SQL",code:`SELECT
|
|
628
|
-
category,
|
|
629
|
-
COUNT(*) AS count,
|
|
630
|
-
SUM(amount) AS total
|
|
631
|
-
FROM read_csv_auto('data/filename.csv')
|
|
632
|
-
GROUP BY category
|
|
633
|
-
ORDER BY total DESC`},{id:"filter-date",label:"Filter by date range",description:"Filter rows between two dates",category:"SQL",code:`SELECT *
|
|
634
|
-
FROM read_csv_auto('data/filename.csv')
|
|
635
|
-
WHERE date_column >= '2024-01-01'
|
|
636
|
-
AND date_column < '2025-01-01'`},{id:"window-rank",label:"Window function: rank",description:"Rank rows within groups using ROW_NUMBER()",category:"SQL",code:`SELECT
|
|
637
|
-
*,
|
|
638
|
-
ROW_NUMBER() OVER (PARTITION BY category ORDER BY amount DESC) AS rank
|
|
639
|
-
FROM read_csv_auto('data/filename.csv')`},{id:"cte",label:"CTE (WITH clause)",description:"Define a named subquery with WITH",category:"SQL",code:`WITH base AS (
|
|
640
|
-
SELECT *
|
|
641
|
-
FROM read_csv_auto('data/filename.csv')
|
|
642
|
-
WHERE amount > 0
|
|
643
|
-
)
|
|
644
|
-
SELECT
|
|
645
|
-
category,
|
|
646
|
-
SUM(amount) AS total
|
|
647
|
-
FROM base
|
|
648
|
-
GROUP BY category`},{id:"join",label:"Join two tables",description:"Join two CSV files on a shared key",category:"SQL",code:`SELECT a.*, b.name
|
|
649
|
-
FROM read_csv_auto('data/table_a.csv') AS a
|
|
650
|
-
JOIN read_csv_auto('data/table_b.csv') AS b
|
|
651
|
-
ON a.id = b.id`},{id:"pivot",label:"Pivot / unpivot",description:"Pivot a column into multiple columns",category:"SQL",code:`SELECT *
|
|
652
|
-
FROM (
|
|
653
|
-
SELECT category, quarter, amount
|
|
654
|
-
FROM read_csv_auto('data/filename.csv')
|
|
655
|
-
) PIVOT (SUM(amount) FOR quarter IN ('Q1', 'Q2', 'Q3', 'Q4'))`},{id:"dql-block",label:"DQL block (basic)",description:"Minimal DQL block with a table visualization",category:"DQL",code:`block "My Block" {
|
|
656
|
-
domain = "analytics"
|
|
657
|
-
type = "custom"
|
|
658
|
-
description = "Describe what this block does"
|
|
659
|
-
owner = "data-team"
|
|
660
|
-
tags = ["analytics"]
|
|
661
|
-
|
|
662
|
-
query = """
|
|
663
|
-
SELECT *
|
|
664
|
-
FROM read_csv_auto('data/filename.csv')
|
|
665
|
-
LIMIT 100
|
|
666
|
-
"""
|
|
667
|
-
|
|
668
|
-
visualization {
|
|
669
|
-
chart = "table"
|
|
670
|
-
}
|
|
671
|
-
}`},{id:"dql-block-bar",label:"DQL block with bar chart",description:"DQL block with params, bar chart, and a test assertion",category:"DQL",code:`block "Revenue by Segment" {
|
|
672
|
-
domain = "revenue"
|
|
673
|
-
type = "custom"
|
|
674
|
-
description = "Revenue grouped by segment"
|
|
675
|
-
owner = "data-team"
|
|
676
|
-
tags = ["revenue"]
|
|
677
|
-
|
|
678
|
-
params {
|
|
679
|
-
period = "current_quarter"
|
|
680
|
-
}
|
|
681
|
-
|
|
682
|
-
query = """
|
|
683
|
-
SELECT
|
|
684
|
-
segment_tier AS segment,
|
|
685
|
-
SUM(amount) AS revenue
|
|
686
|
-
FROM read_csv_auto('data/revenue.csv')
|
|
687
|
-
WHERE fiscal_period = \${period}
|
|
688
|
-
GROUP BY segment_tier
|
|
689
|
-
ORDER BY revenue DESC
|
|
690
|
-
"""
|
|
691
|
-
|
|
692
|
-
visualization {
|
|
693
|
-
chart = "bar"
|
|
694
|
-
x = segment
|
|
695
|
-
y = revenue
|
|
696
|
-
}
|
|
697
|
-
|
|
698
|
-
tests {
|
|
699
|
-
assert row_count > 0
|
|
700
|
-
}
|
|
701
|
-
}`},{id:"dql-semantic-metric",label:"Semantic metric reference",description:"Reference a metric and dimension from the semantic layer in a SQL cell",category:"DQL",code:`SELECT @dim(segment), @metric(total_revenue)
|
|
702
|
-
FROM fct_revenue
|
|
703
|
-
GROUP BY @dim(segment)
|
|
704
|
-
ORDER BY @metric(total_revenue) DESC`},{id:"dql-semantic-block",label:"Semantic block (inline)",description:"DQL block that references a named metric from the semantic layer — no SQL duplication",category:"DQL",code:`block "ARR by Plan Tier" {
|
|
705
|
-
domain = "revenue"
|
|
706
|
-
type = "semantic"
|
|
707
|
-
owner = "data-team"
|
|
708
|
-
description = "Annual Recurring Revenue by subscription plan tier"
|
|
709
|
-
tags = ["arr", "revenue", "saas"]
|
|
710
|
-
|
|
711
|
-
metric = "arr"
|
|
712
|
-
dimensions = ["plan_tier"]
|
|
713
|
-
|
|
714
|
-
visualization {
|
|
715
|
-
chart = "bar"
|
|
716
|
-
x = plan_tier
|
|
717
|
-
y = arr
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
tests {
|
|
721
|
-
assert row_count > 0
|
|
722
|
-
}
|
|
723
|
-
}`},{id:"revenue-by-segment",label:"Revenue by segment",description:"Aggregate revenue totals, deal count, and average deal size per segment",category:"Analysis",code:`SELECT
|
|
724
|
-
segment_tier,
|
|
725
|
-
SUM(amount) AS total_revenue,
|
|
726
|
-
COUNT(*) AS deals,
|
|
727
|
-
ROUND(AVG(amount), 0) AS avg_deal
|
|
728
|
-
FROM read_csv_auto('data/revenue.csv')
|
|
729
|
-
GROUP BY segment_tier
|
|
730
|
-
ORDER BY total_revenue DESC`},{id:"quarterly-trend",label:"Quarterly trend",description:"Revenue totals grouped by fiscal year and quarter",category:"Analysis",code:`SELECT
|
|
731
|
-
fiscal_year || ' ' || fiscal_quarter AS period,
|
|
732
|
-
SUM(amount) AS revenue
|
|
733
|
-
FROM read_csv_auto('data/revenue.csv')
|
|
734
|
-
GROUP BY fiscal_year, fiscal_quarter
|
|
735
|
-
ORDER BY fiscal_year, fiscal_quarter`}];function AD({onInsert:e,themeMode:t,cellType:n}){const r=ie[t],[o,i]=f.useState(!1),[a,l]=f.useState(null),c=f.useRef(null),d=hD.filter(T=>n==="dql"?T.category==="DQL":T.category==="SQL"||T.category==="Analysis"),E=Array.from(new Set(d.map(T=>T.category)));f.useEffect(()=>{if(!o)return;function T(p){c.current&&!c.current.contains(p.target)&&i(!1)}return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[o]);function u(T){e(T),i(!1)}return s.jsxs("div",{ref:c,style:{position:"relative",display:"inline-block"},children:[s.jsxs("button",{title:"Insert template snippet",onClick:()=>i(T=>!T),style:{height:22,padding:"0 8px",fontSize:10,fontFamily:r.font,fontWeight:600,letterSpacing:"0.04em",color:o?r.accent:r.textMuted,background:o?`${r.accent}15`:"transparent",border:`1px solid ${o?r.accent+"50":r.btnBorder}`,borderRadius:4,cursor:"pointer",display:"flex",alignItems:"center",gap:4,transition:"all 0.15s",whiteSpace:"nowrap"},children:[s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"})}),"Templates"]}),o&&s.jsx("div",{style:{position:"absolute",top:"calc(100% + 4px)",left:0,zIndex:300,width:300,maxHeight:360,overflowY:"auto",background:r.modalBg,border:`1px solid ${r.cellBorder}`,borderRadius:8,boxShadow:"0 8px 24px rgba(0,0,0,0.3)",padding:"6px 0"},children:E.map(T=>s.jsxs("div",{children:[s.jsx("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:700,fontFamily:r.font,letterSpacing:"0.08em",textTransform:"uppercase",color:r.textMuted},children:T}),d.filter(p=>p.category===T).map(p=>s.jsxs("button",{onMouseEnter:()=>l(p.id),onMouseLeave:()=>l(null),onClick:()=>u(p.code),style:{width:"100%",padding:"7px 12px",textAlign:"left",background:a===p.id?r.sidebarItemHover:"transparent",border:"none",cursor:"pointer",display:"flex",flexDirection:"column",gap:2,transition:"background 0.1s"},children:[s.jsx("span",{style:{fontSize:12,fontWeight:600,fontFamily:r.font,color:r.textPrimary,lineHeight:1.4},children:p.label}),s.jsx("span",{style:{fontSize:11,fontFamily:r.font,color:r.textMuted,lineHeight:1.4},children:p.description})]},p.id))]},T))})]})}function ID(e,t){var o,i,a,l;const n=e.upstream??((o=e.singleValueConfig)==null?void 0:o.upstream)??((i=e.filterConfig)==null?void 0:i.upstream)??((a=e.pivotConfig)==null?void 0:a.upstream)??((l=e.tableConfig)==null?void 0:l.upstream);if(!n)return null;const r=t.find(c=>c.name===n&&(c.type==="sql"||c.type==="dql"));return!r||!r.content.trim()?null:{name:r.name,sql:r.content.trim()}}function mD(e){if(!e||!e.chart)return"";const t=[`chart = "${e.chart}"`];return e.x&&t.push(`x = ${e.x}`),e.y&&t.push(`y = ${e.y}`),e.color&&t.push(`color = ${e.color}`),e.facet&&t.push(`facet = ${e.facet}`),`
|
|
736
|
-
visualization {
|
|
737
|
-
${t.join(`
|
|
738
|
-
`)}
|
|
739
|
-
}`}function OD(e){if(!e)return"";const t=['chart = "kpi"'];return e.metric&&t.push(`y = ${e.metric}`),e.format&&t.push(`format = "${e.format}"`),e.label&&t.push(`label = "${e.label.replace(/"/g,'\\"')}"`),`
|
|
740
|
-
visualization {
|
|
741
|
-
${t.join(`
|
|
742
|
-
`)}
|
|
743
|
-
}`}function ND(e,t){return` query = """
|
|
744
|
-
${e.replace(/^/gm," ")}
|
|
745
|
-
"""${t}`}function gD(e,t){var a,l,c,d;if(e.type==="sql"||e.type==="dql")return{content:e.content,suggestedName:e.name,derivedFromUpstream:!1,blocker:e.content.trim()?void 0:"Cell is empty — add a SQL query first."};if(e.type==="markdown"||e.type==="param"||e.type==="map"||e.type==="writeback"||e.type==="python")return{content:"",derivedFromUpstream:!1,blocker:`${e.type} cells cannot be promoted to blocks yet.`};const n=ID(e,t);if(!n)return{content:"",derivedFromUpstream:!0,blocker:"No upstream SQL cell is wired — pick an upstream dataframe before saving as a block."};let r="",o,i;switch(e.type){case"chart":r=mD(e.chartConfig),o=e.name??(n.name?`${n.name}_chart`:"chart_block"),i=((a=e.chartConfig)==null?void 0:a.title)??((l=e.chartConfig)!=null&&l.chart?`${e.chartConfig.chart} of ${n.name??"upstream"}`:void 0);break;case"single_value":r=OD(e.singleValueConfig),o=e.name??((c=e.singleValueConfig)!=null&&c.label?e.singleValueConfig.label:`${n.name??"metric"}_kpi`),i=(d=e.singleValueConfig)==null?void 0:d.label;break;case"filter":case"pivot":case"table":o=e.name??(n.name?`${n.name}_${e.type}`:`${e.type}_block`);break}return{content:ND(n.sql,r),suggestedName:o,suggestedDescription:i,derivedFromUpstream:!0}}function xD(e){let t=e;try{const d=JSON.parse(e);d&&typeof d.error=="string"&&(t=d.error)}catch{}t=t.replace(/^DuckDB query failed:\s*/i,"").trim();let n="Error";/Parser Error/i.test(t)?n="Syntax Error":/Binder Error/i.test(t)?n="Reference Error":/Conversion Error/i.test(t)?n="Type Error":/Invalid Input Error/i.test(t)?n="Input Error":/IO Error/i.test(t)?n="File Error":/Constraint Error/i.test(t)&&(n="Constraint Error");let r;const o=t.match(/LINE\s+(\d+):/i)??t.match(/\bline\s+(\d+)\b/i);o&&(r=parseInt(o[1],10));let i;const a=t.match(/at or near "([^"]+)"/i);a?i=a[1]:/at end of input/i.test(t)&&(i="end of input");let l;n==="Syntax Error"?i==='"""'||t.includes('"""')?l="Triple-quoted strings are DQL block syntax. Use a DQL cell for block syntax, or plain SQL in a SQL cell.":i==="end of input"||/at end of input/i.test(t)?l="Query is incomplete — check for unclosed parentheses, missing keywords, or a dangling comma.":(i===")"||i==="(")&&(l="Mismatched parentheses — check that every opening ( has a closing )."):n==="Reference Error"?/column.*not found|Referenced column/i.test(t)?l="Column not found — check the column name in the Schema panel (left sidebar).":/table.*not found|Table.*does not exist/i.test(t)&&(l="Table not found — make sure the file path is correct and the file exists in your data/ folder."):n==="Input Error"?/No files found/i.test(t)&&(l="File not found — use read_csv_auto('./data/filename.csv'). Open the Schema panel (left sidebar) to see all files available in your data/ folder."):n==="File Error"?l="File could not be read — use read_csv_auto('./data/filename.csv'). Open the Schema panel to browse available data files.":n==="Type Error"&&(l="Type mismatch — you may be comparing or casting incompatible types (e.g. text vs number).");const c=t.replace(/^(Parser Error|Binder Error|Conversion Error|Invalid Input Error|IO Error|Constraint Error):\s*/i,"").trim();return{type:n,message:c,line:r,near:i,hint:l}}function yD(e,t){const n=e.length,r=t.length,o=Array.from({length:n+1},(i,a)=>Array.from({length:r+1},(l,c)=>a===0?c:c===0?a:0));for(let i=1;i<=n;i++)for(let a=1;a<=r;a++)o[i][a]=e[i-1]===t[a-1]?o[i-1][a-1]:1+Math.min(o[i-1][a],o[i][a-1],o[i-1][a-1]);return o[n][r]}function ju(e,t){const n=e.toLowerCase();let r=null,o=4;for(const i of t){const a=yD(n,i.toLowerCase());a<o&&(o=a,r=i)}return r}function CD({message:e,themeMode:t,onFix:n,schemaTables:r}){const o=ie[t],i=xD(e);let a=null;if(r&&r.length>0&&i.type==="Reference Error"){const c=/column.*not found|Referenced column/i.test(i.message),d=/table.*not found|Table.*does not exist/i.test(i.message);if(c&&i.near){const E=r.flatMap(T=>T.columns.map(p=>p.name)),u=ju(i.near,E);u&&(a=`Did you mean column "${u}"?`)}else if(d&&i.near){const E=ju(i.near,r.map(u=>u.name));E&&(a=`Did you mean table "${E}"?`)}}const l=n&&(i.type==="Syntax Error"||i.near===")"||i.near==="("||i.near==="end of input");return s.jsxs("div",{style:{padding:"12px 14px",background:`${o.error}10`,borderLeft:`3px solid ${o.error}`,display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[s.jsx("div",{style:{flexShrink:0,color:o.error,display:"flex",alignItems:"center"},children:s.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M4.47.22A.749.749 0 0 1 5 0h6c.199 0 .389.079.53.22l4.25 4.25c.141.14.22.331.22.53v6a.749.749 0 0 1-.22.53l-4.25 4.25A.749.749 0 0 1 11 16H5a.749.749 0 0 1-.53-.22L.22 11.53A.749.749 0 0 1 0 11V5c0-.199.079-.389.22-.53Zm.84 1.28L1.5 5.31v5.38l3.81 3.81h5.38l3.81-3.81V5.31L10.69 1.5ZM8 4a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 4Zm0 8a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z"})})}),s.jsx("span",{style:{fontSize:10,fontWeight:700,fontFamily:o.fontMono,letterSpacing:"0.06em",textTransform:"uppercase",color:o.error,background:`${o.error}18`,border:`1px solid ${o.error}40`,borderRadius:4,padding:"1px 7px",flexShrink:0},children:i.type}),i.line!==void 0&&s.jsxs("span",{style:{fontSize:10,fontWeight:600,fontFamily:o.fontMono,color:o.textSecondary,background:`${o.textMuted}18`,border:`1px solid ${o.textMuted}30`,borderRadius:4,padding:"1px 7px",flexShrink:0},children:["Line ",i.line]}),i.near&&s.jsxs("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textSecondary,flexShrink:0},children:["near ",s.jsxs("span",{style:{color:o.error},children:["“",i.near,"”"]})]})]}),s.jsx("pre",{style:{margin:0,fontFamily:o.fontMono,fontSize:12,color:o.error,lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:i.message}),a&&s.jsxs("div",{style:{fontSize:12,fontFamily:o.font,color:o.textSecondary,display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{style:{color:o.accent},children:"→"}),a]}),i.hint&&s.jsxs("div",{style:{marginTop:2,padding:"8px 12px",background:`${o.warning}12`,border:`1px solid ${o.warning}40`,borderRadius:6,display:"flex",alignItems:"flex-start",gap:8},children:[s.jsx("span",{style:{flexShrink:0,fontSize:13,lineHeight:1.5},children:"💡"}),s.jsx("span",{style:{fontSize:12,fontFamily:o.font,color:o.warning,lineHeight:1.6},children:i.hint})]}),l&&s.jsxs("button",{onClick:n,style:{alignSelf:"flex-start",marginTop:2,padding:"5px 12px",background:`${o.accent}15`,border:`1px solid ${o.accent}50`,borderRadius:6,color:o.accent,fontSize:12,fontFamily:o.font,fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center",gap:6,transition:"all 0.15s"},onMouseEnter:c=>{c.currentTarget.style.background=`${o.accent}25`},onMouseLeave:c=>{c.currentTarget.style.background=`${o.accent}15`},children:[s.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:s.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"})}),"Format & Run"]})]})}function Bc({path:e,onNodeClick:t,focalNodeId:n,t:r}){return e.nodes.length===0?null:s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,alignItems:"center"},children:e.nodes.map((o,i)=>s.jsxs(_e.Fragment,{children:[s.jsx(LD,{node:o,isFocal:o.id===n,onClick:t?()=>t(o.id):void 0,t:r}),i<e.nodes.length-1&&s.jsx("span",{style:{color:r.textMuted,fontSize:10,lineHeight:1},children:"→"})]},o.id))})}function Gu({title:e,paths:t,onNodeClick:n,focalNodeId:r,maxVisible:o=4,t:i}){const[a,l]=_e.useState(!1),c=a?t:t.slice(0,o),d=t.length>o;return t.length===0?null:s.jsxs("div",{style:{border:`1px solid ${i.cellBorder}`,borderRadius:10,overflow:"hidden",background:i.inputBg},children:[s.jsxs("div",{style:{padding:"8px 12px",borderBottom:`1px solid ${i.cellBorder}`,fontSize:11,fontWeight:700,color:i.textMuted,fontFamily:i.font,textTransform:"uppercase",letterSpacing:"0.04em",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{children:e}),s.jsxs("span",{style:{fontWeight:400,fontSize:10},children:[t.length," path",t.length!==1?"s":""]})]}),s.jsxs("div",{style:{display:"grid",gap:8,padding:10},children:[c.map((E,u)=>s.jsx(Bc,{path:E,onNodeClick:n,focalNodeId:r,t:i},`path-${u}`)),d&&!a&&s.jsxs("button",{onClick:()=>l(!0),style:{background:"none",border:"none",color:i.accent,cursor:"pointer",fontSize:11,fontFamily:i.font,padding:"2px 0",textAlign:"left"},children:["Show ",t.length-o," more path",t.length-o!==1?"s":"","..."]})]})]})}function LD({node:e,isFocal:t,onClick:n,t:r}){const o=we[e.type]??"#8b949e",i=aa[e.type]??e.type.slice(0,3).toUpperCase();return s.jsxs("button",{onClick:n,disabled:!n,style:{display:"inline-flex",alignItems:"center",gap:4,background:t?`${o}18`:r.pillBg??`${r.cellBg}`,border:`1px solid ${t?o:r.cellBorder}`,borderRadius:999,color:r.textPrimary,cursor:n?"pointer":"default",fontSize:10,fontFamily:r.font,padding:"3px 8px",transition:"border-color 0.15s",whiteSpace:"nowrap",maxWidth:180},title:`${e.type}: ${e.name}${e.domain?` (${e.domain})`:""}`,children:[s.jsx("span",{style:{fontSize:8,fontWeight:700,color:"#0d1117",background:o,borderRadius:3,padding:"1px 3px",flexShrink:0},children:i}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]})}function _D({layerSummary:e,t}){const n=["source","transform","answer","consumption"];if(Object.values(e).reduce((a,l)=>a+l,0)===0)return null;const o={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},i={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"};return s.jsx("div",{style:{display:"flex",gap:10,fontSize:10,color:t.textMuted,fontFamily:t.font},children:n.map(a=>{const l=e[a]??0;return l===0?null:s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:2,background:o[a],display:"inline-block"}}),i[a],": ",l]},a)})})}function De(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=De(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var bD={value:()=>{}};function pa(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new ei(n)}function ei(e){this._=e}function DD(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",o=n.indexOf(".");if(o>=0&&(r=n.slice(o+1),n=n.slice(0,o)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}ei.prototype=pa.prototype={constructor:ei,on:function(e,t){var n=this._,r=DD(e+"",n),o,i=-1,a=r.length;if(arguments.length<2){for(;++i<a;)if((o=(e=r[i]).type)&&(o=MD(n[o],e.name)))return o;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++i<a;)if(o=(e=r[i]).type)n[o]=Hu(n[o],e.name,t);else if(t==null)for(o in n)n[o]=Hu(n[o],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new ei(e)},call:function(e,t){if((o=arguments.length-2)>0)for(var n=new Array(o),r=0,o,i;r<o;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(i=this._[e],r=0,o=i.length;r<o;++r)i[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],o=0,i=r.length;o<i;++o)r[o].value.apply(t,n)}};function MD(e,t){for(var n=0,r=e.length,o;n<r;++n)if((o=e[n]).name===t)return o.value}function Hu(e,t,n){for(var r=0,o=e.length;r<o;++r)if(e[r].name===t){e[r]=bD,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Fc="http://www.w3.org/1999/xhtml";const Yu={svg:"http://www.w3.org/2000/svg",xhtml:Fc,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Sa(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),Yu.hasOwnProperty(t)?{space:Yu[t],local:e}:e}function vD(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Fc&&t.documentElement.namespaceURI===Fc?t.createElement(e):t.createElementNS(n,e)}}function PD(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function Ah(e){var t=Sa(e);return(t.local?PD:vD)(t)}function wD(){}function Xd(e){return e==null?wD:function(){return this.querySelector(e)}}function UD(e){typeof e!="function"&&(e=Xd(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var i=t[o],a=i.length,l=r[o]=new Array(a),c,d,E=0;E<a;++E)(c=i[E])&&(d=e.call(c,c.__data__,E,i))&&("__data__"in c&&(d.__data__=c.__data__),l[E]=d);return new Qe(r,this._parents)}function BD(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function FD(){return[]}function Ih(e){return e==null?FD:function(){return this.querySelectorAll(e)}}function kD(e){return function(){return BD(e.apply(this,arguments))}}function jD(e){typeof e=="function"?e=kD(e):e=Ih(e);for(var t=this._groups,n=t.length,r=[],o=[],i=0;i<n;++i)for(var a=t[i],l=a.length,c,d=0;d<l;++d)(c=a[d])&&(r.push(e.call(c,c.__data__,d,a)),o.push(c));return new Qe(r,o)}function mh(e){return function(){return this.matches(e)}}function Oh(e){return function(t){return t.matches(e)}}var GD=Array.prototype.find;function HD(e){return function(){return GD.call(this.children,e)}}function YD(){return this.firstElementChild}function WD(e){return this.select(e==null?YD:HD(typeof e=="function"?e:Oh(e)))}var $D=Array.prototype.filter;function VD(){return Array.from(this.children)}function XD(e){return function(){return $D.call(this.children,e)}}function zD(e){return this.selectAll(e==null?VD:XD(typeof e=="function"?e:Oh(e)))}function KD(e){typeof e!="function"&&(e=mh(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var i=t[o],a=i.length,l=r[o]=[],c,d=0;d<a;++d)(c=i[d])&&e.call(c,c.__data__,d,i)&&l.push(c);return new Qe(r,this._parents)}function Nh(e){return new Array(e.length)}function qD(){return new Qe(this._enter||this._groups.map(Nh),this._parents)}function xi(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}xi.prototype={constructor:xi,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function JD(e){return function(){return e}}function QD(e,t,n,r,o,i){for(var a=0,l,c=t.length,d=i.length;a<d;++a)(l=t[a])?(l.__data__=i[a],r[a]=l):n[a]=new xi(e,i[a]);for(;a<c;++a)(l=t[a])&&(o[a]=l)}function ZD(e,t,n,r,o,i,a){var l,c,d=new Map,E=t.length,u=i.length,T=new Array(E),p;for(l=0;l<E;++l)(c=t[l])&&(T[l]=p=a.call(c,c.__data__,l,t)+"",d.has(p)?o[l]=c:d.set(p,c));for(l=0;l<u;++l)p=a.call(e,i[l],l,i)+"",(c=d.get(p))?(r[l]=c,c.__data__=i[l],d.delete(p)):n[l]=new xi(e,i[l]);for(l=0;l<E;++l)(c=t[l])&&d.get(T[l])===c&&(o[l]=c)}function eM(e){return e.__data__}function tM(e,t){if(!arguments.length)return Array.from(this,eM);var n=t?ZD:QD,r=this._parents,o=this._groups;typeof e!="function"&&(e=JD(e));for(var i=o.length,a=new Array(i),l=new Array(i),c=new Array(i),d=0;d<i;++d){var E=r[d],u=o[d],T=u.length,p=nM(e.call(E,E&&E.__data__,d,r)),h=p.length,A=l[d]=new Array(h),S=a[d]=new Array(h),R=c[d]=new Array(T);n(E,u,A,S,R,p,t);for(var m=0,I=0,O,N;m<h;++m)if(O=A[m]){for(m>=I&&(I=m+1);!(N=S[I])&&++I<h;);O._next=N||null}}return a=new Qe(a,r),a._enter=l,a._exit=c,a}function nM(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function rM(){return new Qe(this._exit||this._groups.map(Nh),this._parents)}function oM(e,t,n){var r=this.enter(),o=this,i=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(o=t(o),o&&(o=o.selection())),n==null?i.remove():n(i),r&&o?r.merge(o).order():o}function sM(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,o=n.length,i=r.length,a=Math.min(o,i),l=new Array(o),c=0;c<a;++c)for(var d=n[c],E=r[c],u=d.length,T=l[c]=new Array(u),p,h=0;h<u;++h)(p=d[h]||E[h])&&(T[h]=p);for(;c<o;++c)l[c]=n[c];return new Qe(l,this._parents)}function iM(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],o=r.length-1,i=r[o],a;--o>=0;)(a=r[o])&&(i&&a.compareDocumentPosition(i)^4&&i.parentNode.insertBefore(a,i),i=a);return this}function aM(e){e||(e=lM);function t(u,T){return u&&T?e(u.__data__,T.__data__):!u-!T}for(var n=this._groups,r=n.length,o=new Array(r),i=0;i<r;++i){for(var a=n[i],l=a.length,c=o[i]=new Array(l),d,E=0;E<l;++E)(d=a[E])&&(c[E]=d);c.sort(t)}return new Qe(o,this._parents).order()}function lM(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function cM(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function dM(){return Array.from(this)}function EM(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,i=r.length;o<i;++o){var a=r[o];if(a)return a}return null}function uM(){let e=0;for(const t of this)++e;return e}function TM(){return!this.node()}function fM(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var o=t[n],i=0,a=o.length,l;i<a;++i)(l=o[i])&&e.call(l,l.__data__,i,o);return this}function pM(e){return function(){this.removeAttribute(e)}}function SM(e){return function(){this.removeAttributeNS(e.space,e.local)}}function RM(e,t){return function(){this.setAttribute(e,t)}}function hM(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function AM(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function IM(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function mM(e,t){var n=Sa(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?SM:pM:typeof t=="function"?n.local?IM:AM:n.local?hM:RM)(n,t))}function gh(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function OM(e){return function(){this.style.removeProperty(e)}}function NM(e,t,n){return function(){this.style.setProperty(e,t,n)}}function gM(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function xM(e,t,n){return arguments.length>1?this.each((t==null?OM:typeof t=="function"?gM:NM)(e,t,n??"")):Lr(this.node(),e)}function Lr(e,t){return e.style.getPropertyValue(t)||gh(e).getComputedStyle(e,null).getPropertyValue(t)}function yM(e){return function(){delete this[e]}}function CM(e,t){return function(){this[e]=t}}function LM(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function _M(e,t){return arguments.length>1?this.each((t==null?yM:typeof t=="function"?LM:CM)(e,t)):this.node()[e]}function xh(e){return e.trim().split(/^|\s+/)}function zd(e){return e.classList||new yh(e)}function yh(e){this._node=e,this._names=xh(e.getAttribute("class")||"")}yh.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function Ch(e,t){for(var n=zd(e),r=-1,o=t.length;++r<o;)n.add(t[r])}function Lh(e,t){for(var n=zd(e),r=-1,o=t.length;++r<o;)n.remove(t[r])}function bM(e){return function(){Ch(this,e)}}function DM(e){return function(){Lh(this,e)}}function MM(e,t){return function(){(t.apply(this,arguments)?Ch:Lh)(this,e)}}function vM(e,t){var n=xh(e+"");if(arguments.length<2){for(var r=zd(this.node()),o=-1,i=n.length;++o<i;)if(!r.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?MM:t?bM:DM)(n,t))}function PM(){this.textContent=""}function wM(e){return function(){this.textContent=e}}function UM(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function BM(e){return arguments.length?this.each(e==null?PM:(typeof e=="function"?UM:wM)(e)):this.node().textContent}function FM(){this.innerHTML=""}function kM(e){return function(){this.innerHTML=e}}function jM(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function GM(e){return arguments.length?this.each(e==null?FM:(typeof e=="function"?jM:kM)(e)):this.node().innerHTML}function HM(){this.nextSibling&&this.parentNode.appendChild(this)}function YM(){return this.each(HM)}function WM(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function $M(){return this.each(WM)}function VM(e){var t=typeof e=="function"?e:Ah(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function XM(){return null}function zM(e,t){var n=typeof e=="function"?e:Ah(e),r=t==null?XM:typeof t=="function"?t:Xd(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function KM(){var e=this.parentNode;e&&e.removeChild(this)}function qM(){return this.each(KM)}function JM(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function QM(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function ZM(e){return this.select(e?QM:JM)}function ev(e){return arguments.length?this.property("__data__",e):this.node().__data__}function tv(e){return function(t){e.call(this,t,this.__data__)}}function nv(e){return e.trim().split(/^|\s+/).map(function(t){var n="",r=t.indexOf(".");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function rv(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,o=t.length,i;n<o;++n)i=t[n],(!e.type||i.type===e.type)&&i.name===e.name?this.removeEventListener(i.type,i.listener,i.options):t[++r]=i;++r?t.length=r:delete this.__on}}}function ov(e,t,n){return function(){var r=this.__on,o,i=tv(t);if(r){for(var a=0,l=r.length;a<l;++a)if((o=r[a]).type===e.type&&o.name===e.name){this.removeEventListener(o.type,o.listener,o.options),this.addEventListener(o.type,o.listener=i,o.options=n),o.value=t;return}}this.addEventListener(e.type,i,n),o={type:e.type,name:e.name,value:t,listener:i,options:n},r?r.push(o):this.__on=[o]}}function sv(e,t,n){var r=nv(e+""),o,i=r.length,a;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,d=l.length,E;c<d;++c)for(o=0,E=l[c];o<i;++o)if((a=r[o]).type===E.type&&a.name===E.name)return E.value}return}for(l=t?ov:rv,o=0;o<i;++o)this.each(l(r[o],t,n));return this}function _h(e,t,n){var r=gh(e),o=r.CustomEvent;typeof o=="function"?o=new o(t,n):(o=r.document.createEvent("Event"),n?(o.initEvent(t,n.bubbles,n.cancelable),o.detail=n.detail):o.initEvent(t,!1,!1)),e.dispatchEvent(o)}function iv(e,t){return function(){return _h(this,e,t)}}function av(e,t){return function(){return _h(this,e,t.apply(this,arguments))}}function lv(e,t){return this.each((typeof t=="function"?av:iv)(e,t))}function*cv(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,i=r.length,a;o<i;++o)(a=r[o])&&(yield a)}var bh=[null];function Qe(e,t){this._groups=e,this._parents=t}function Wo(){return new Qe([[document.documentElement]],bh)}function dv(){return this}Qe.prototype=Wo.prototype={constructor:Qe,select:UD,selectAll:jD,selectChild:WD,selectChildren:zD,filter:KD,data:tM,enter:qD,exit:rM,join:oM,merge:sM,selection:dv,order:iM,sort:aM,call:cM,nodes:dM,node:EM,size:uM,empty:TM,each:fM,attr:mM,style:xM,property:_M,classed:vM,text:BM,html:GM,raise:YM,lower:$M,append:VM,insert:zM,remove:qM,clone:ZM,datum:ev,on:sv,dispatch:lv,[Symbol.iterator]:cv};function qe(e){return typeof e=="string"?new Qe([[document.querySelector(e)]],[document.documentElement]):new Qe([[e]],bh)}function Ev(e){let t;for(;t=e.sourceEvent;)e=t;return e}function dt(e,t){if(e=Ev(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var o=t.getBoundingClientRect();return[e.clientX-o.left-t.clientLeft,e.clientY-o.top-t.clientTop]}}return[e.pageX,e.pageY]}const uv={passive:!1},xo={capture:!0,passive:!1};function Rl(e){e.stopImmediatePropagation()}function Ar(e){e.preventDefault(),e.stopImmediatePropagation()}function Dh(e){var t=e.document.documentElement,n=qe(e).on("dragstart.drag",Ar,xo);"onselectstart"in t?n.on("selectstart.drag",Ar,xo):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function Mh(e,t){var n=e.document.documentElement,r=qe(e).on("dragstart.drag",null);t&&(r.on("click.drag",Ar,xo),setTimeout(function(){r.on("click.drag",null)},0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const vs=e=>()=>e;function kc(e,{sourceEvent:t,subject:n,target:r,identifier:o,active:i,x:a,y:l,dx:c,dy:d,dispatch:E}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:o,enumerable:!0,configurable:!0},active:{value:i,enumerable:!0,configurable:!0},x:{value:a,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:d,enumerable:!0,configurable:!0},_:{value:E}})}kc.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function Tv(e){return!e.ctrlKey&&!e.button}function fv(){return this.parentNode}function pv(e,t){return t??{x:e.x,y:e.y}}function Sv(){return navigator.maxTouchPoints||"ontouchstart"in this}function vh(){var e=Tv,t=fv,n=pv,r=Sv,o={},i=pa("start","drag","end"),a=0,l,c,d,E,u=0;function T(O){O.on("mousedown.drag",p).filter(r).on("touchstart.drag",S).on("touchmove.drag",R,uv).on("touchend.drag touchcancel.drag",m).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(O,N){if(!(E||!e.call(this,O,N))){var x=I(this,t.call(this,O,N),O,N,"mouse");x&&(qe(O.view).on("mousemove.drag",h,xo).on("mouseup.drag",A,xo),Dh(O.view),Rl(O),d=!1,l=O.clientX,c=O.clientY,x("start",O))}}function h(O){if(Ar(O),!d){var N=O.clientX-l,x=O.clientY-c;d=N*N+x*x>u}o.mouse("drag",O)}function A(O){qe(O.view).on("mousemove.drag mouseup.drag",null),Mh(O.view,d),Ar(O),o.mouse("end",O)}function S(O,N){if(e.call(this,O,N)){var x=O.changedTouches,g=t.call(this,O,N),C=x.length,y,w;for(y=0;y<C;++y)(w=I(this,g,O,N,x[y].identifier,x[y]))&&(Rl(O),w("start",O,x[y]))}}function R(O){var N=O.changedTouches,x=N.length,g,C;for(g=0;g<x;++g)(C=o[N[g].identifier])&&(Ar(O),C("drag",O,N[g]))}function m(O){var N=O.changedTouches,x=N.length,g,C;for(E&&clearTimeout(E),E=setTimeout(function(){E=null},500),g=0;g<x;++g)(C=o[N[g].identifier])&&(Rl(O),C("end",O,N[g]))}function I(O,N,x,g,C,y){var w=i.copy(),v=dt(y||x,N),B,b,L;if((L=n.call(O,new kc("beforestart",{sourceEvent:x,target:T,identifier:C,active:a,x:v[0],y:v[1],dx:0,dy:0,dispatch:w}),g))!=null)return B=L.x-v[0]||0,b=L.y-v[1]||0,function D(M,U,P){var _=v,F;switch(M){case"start":o[C]=D,F=a++;break;case"end":delete o[C],--a;case"drag":v=dt(P||U,N),F=a;break}w.call(M,O,new kc(M,{sourceEvent:U,subject:L,target:T,identifier:C,active:F,x:v[0]+B,y:v[1]+b,dx:v[0]-_[0],dy:v[1]-_[1],dispatch:w}),g)}}return T.filter=function(O){return arguments.length?(e=typeof O=="function"?O:vs(!!O),T):e},T.container=function(O){return arguments.length?(t=typeof O=="function"?O:vs(O),T):t},T.subject=function(O){return arguments.length?(n=typeof O=="function"?O:vs(O),T):n},T.touchable=function(O){return arguments.length?(r=typeof O=="function"?O:vs(!!O),T):r},T.on=function(){var O=i.on.apply(i,arguments);return O===i?T:O},T.clickDistance=function(O){return arguments.length?(u=(O=+O)*O,T):Math.sqrt(u)},T}function Kd(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function Ph(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function $o(){}var yo=.7,yi=1/yo,Ir="\\s*([+-]?\\d+)\\s*",Co="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",_t="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Rv=/^#([0-9a-f]{3,8})$/,hv=new RegExp(`^rgb\\(${Ir},${Ir},${Ir}\\)$`),Av=new RegExp(`^rgb\\(${_t},${_t},${_t}\\)$`),Iv=new RegExp(`^rgba\\(${Ir},${Ir},${Ir},${Co}\\)$`),mv=new RegExp(`^rgba\\(${_t},${_t},${_t},${Co}\\)$`),Ov=new RegExp(`^hsl\\(${Co},${_t},${_t}\\)$`),Nv=new RegExp(`^hsla\\(${Co},${_t},${_t},${Co}\\)$`),Wu={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};Kd($o,Gn,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:$u,formatHex:$u,formatHex8:gv,formatHsl:xv,formatRgb:Vu,toString:Vu});function $u(){return this.rgb().formatHex()}function gv(){return this.rgb().formatHex8()}function xv(){return wh(this).formatHsl()}function Vu(){return this.rgb().formatRgb()}function Gn(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=Rv.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Xu(t):n===3?new Ye(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Ps(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Ps(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=hv.exec(e))?new Ye(t[1],t[2],t[3],1):(t=Av.exec(e))?new Ye(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Iv.exec(e))?Ps(t[1],t[2],t[3],t[4]):(t=mv.exec(e))?Ps(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Ov.exec(e))?qu(t[1],t[2]/100,t[3]/100,1):(t=Nv.exec(e))?qu(t[1],t[2]/100,t[3]/100,t[4]):Wu.hasOwnProperty(e)?Xu(Wu[e]):e==="transparent"?new Ye(NaN,NaN,NaN,0):null}function Xu(e){return new Ye(e>>16&255,e>>8&255,e&255,1)}function Ps(e,t,n,r){return r<=0&&(e=t=n=NaN),new Ye(e,t,n,r)}function yv(e){return e instanceof $o||(e=Gn(e)),e?(e=e.rgb(),new Ye(e.r,e.g,e.b,e.opacity)):new Ye}function jc(e,t,n,r){return arguments.length===1?yv(e):new Ye(e,t,n,r??1)}function Ye(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Kd(Ye,jc,Ph($o,{brighter(e){return e=e==null?yi:Math.pow(yi,e),new Ye(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?yo:Math.pow(yo,e),new Ye(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Ye(wn(this.r),wn(this.g),wn(this.b),Ci(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:zu,formatHex:zu,formatHex8:Cv,formatRgb:Ku,toString:Ku}));function zu(){return`#${vn(this.r)}${vn(this.g)}${vn(this.b)}`}function Cv(){return`#${vn(this.r)}${vn(this.g)}${vn(this.b)}${vn((isNaN(this.opacity)?1:this.opacity)*255)}`}function Ku(){const e=Ci(this.opacity);return`${e===1?"rgb(":"rgba("}${wn(this.r)}, ${wn(this.g)}, ${wn(this.b)}${e===1?")":`, ${e})`}`}function Ci(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function wn(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function vn(e){return e=wn(e),(e<16?"0":"")+e.toString(16)}function qu(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Et(e,t,n,r)}function wh(e){if(e instanceof Et)return new Et(e.h,e.s,e.l,e.opacity);if(e instanceof $o||(e=Gn(e)),!e)return new Et;if(e instanceof Et)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,o=Math.min(t,n,r),i=Math.max(t,n,r),a=NaN,l=i-o,c=(i+o)/2;return l?(t===i?a=(n-r)/l+(n<r)*6:n===i?a=(r-t)/l+2:a=(t-n)/l+4,l/=c<.5?i+o:2-i-o,a*=60):l=c>0&&c<1?0:a,new Et(a,l,c,e.opacity)}function Lv(e,t,n,r){return arguments.length===1?wh(e):new Et(e,t,n,r??1)}function Et(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Kd(Et,Lv,Ph($o,{brighter(e){return e=e==null?yi:Math.pow(yi,e),new Et(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?yo:Math.pow(yo,e),new Et(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,o=2*n-r;return new Ye(hl(e>=240?e-240:e+120,o,r),hl(e,o,r),hl(e<120?e+240:e-120,o,r),this.opacity)},clamp(){return new Et(Ju(this.h),ws(this.s),ws(this.l),Ci(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=Ci(this.opacity);return`${e===1?"hsl(":"hsla("}${Ju(this.h)}, ${ws(this.s)*100}%, ${ws(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Ju(e){return e=(e||0)%360,e<0?e+360:e}function ws(e){return Math.max(0,Math.min(1,e||0))}function hl(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const qd=e=>()=>e;function _v(e,t){return function(n){return e+n*t}}function bv(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function Dv(e){return(e=+e)==1?Uh:function(t,n){return n-t?bv(t,n,e):qd(isNaN(t)?n:t)}}function Uh(e,t){var n=t-e;return n?_v(e,n):qd(isNaN(e)?t:e)}const Li=(function e(t){var n=Dv(t);function r(o,i){var a=n((o=jc(o)).r,(i=jc(i)).r),l=n(o.g,i.g),c=n(o.b,i.b),d=Uh(o.opacity,i.opacity);return function(E){return o.r=a(E),o.g=l(E),o.b=c(E),o.opacity=d(E),o+""}}return r.gamma=e,r})(1);function Mv(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),o;return function(i){for(o=0;o<n;++o)r[o]=e[o]*(1-i)+t[o]*i;return r}}function vv(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Pv(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,o=new Array(r),i=new Array(n),a;for(a=0;a<r;++a)o[a]=Eo(e[a],t[a]);for(;a<n;++a)i[a]=t[a];return function(l){for(a=0;a<r;++a)i[a]=o[a](l);return i}}function wv(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function Nt(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function Uv(e,t){var n={},r={},o;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(o in t)o in e?n[o]=Eo(e[o],t[o]):r[o]=t[o];return function(i){for(o in n)r[o]=n[o](i);return r}}var Gc=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Al=new RegExp(Gc.source,"g");function Bv(e){return function(){return e}}function Fv(e){return function(t){return e(t)+""}}function Bh(e,t){var n=Gc.lastIndex=Al.lastIndex=0,r,o,i,a=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Gc.exec(e))&&(o=Al.exec(t));)(i=o.index)>n&&(i=t.slice(n,i),l[a]?l[a]+=i:l[++a]=i),(r=r[0])===(o=o[0])?l[a]?l[a]+=o:l[++a]=o:(l[++a]=null,c.push({i:a,x:Nt(r,o)})),n=Al.lastIndex;return n<t.length&&(i=t.slice(n),l[a]?l[a]+=i:l[++a]=i),l.length<2?c[0]?Fv(c[0].x):Bv(t):(t=c.length,function(d){for(var E=0,u;E<t;++E)l[(u=c[E]).i]=u.x(d);return l.join("")})}function Eo(e,t){var n=typeof t,r;return t==null||n==="boolean"?qd(t):(n==="number"?Nt:n==="string"?(r=Gn(t))?(t=r,Li):Bh:t instanceof Gn?Li:t instanceof Date?wv:vv(t)?Mv:Array.isArray(t)?Pv:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?Uv:Nt)(e,t)}var Qu=180/Math.PI,Hc={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Fh(e,t,n,r,o,i){var a,l,c;return(a=Math.sqrt(e*e+t*t))&&(e/=a,t/=a),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,a=-a),{translateX:o,translateY:i,rotate:Math.atan2(t,e)*Qu,skewX:Math.atan(c)*Qu,scaleX:a,scaleY:l}}var Us;function kv(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Hc:Fh(t.a,t.b,t.c,t.d,t.e,t.f)}function jv(e){return e==null||(Us||(Us=document.createElementNS("http://www.w3.org/2000/svg","g")),Us.setAttribute("transform",e),!(e=Us.transform.baseVal.consolidate()))?Hc:(e=e.matrix,Fh(e.a,e.b,e.c,e.d,e.e,e.f))}function kh(e,t,n,r){function o(d){return d.length?d.pop()+" ":""}function i(d,E,u,T,p,h){if(d!==u||E!==T){var A=p.push("translate(",null,t,null,n);h.push({i:A-4,x:Nt(d,u)},{i:A-2,x:Nt(E,T)})}else(u||T)&&p.push("translate("+u+t+T+n)}function a(d,E,u,T){d!==E?(d-E>180?E+=360:E-d>180&&(d+=360),T.push({i:u.push(o(u)+"rotate(",null,r)-2,x:Nt(d,E)})):E&&u.push(o(u)+"rotate("+E+r)}function l(d,E,u,T){d!==E?T.push({i:u.push(o(u)+"skewX(",null,r)-2,x:Nt(d,E)}):E&&u.push(o(u)+"skewX("+E+r)}function c(d,E,u,T,p,h){if(d!==u||E!==T){var A=p.push(o(p)+"scale(",null,",",null,")");h.push({i:A-4,x:Nt(d,u)},{i:A-2,x:Nt(E,T)})}else(u!==1||T!==1)&&p.push(o(p)+"scale("+u+","+T+")")}return function(d,E){var u=[],T=[];return d=e(d),E=e(E),i(d.translateX,d.translateY,E.translateX,E.translateY,u,T),a(d.rotate,E.rotate,u,T),l(d.skewX,E.skewX,u,T),c(d.scaleX,d.scaleY,E.scaleX,E.scaleY,u,T),d=E=null,function(p){for(var h=-1,A=T.length,S;++h<A;)u[(S=T[h]).i]=S.x(p);return u.join("")}}}var Gv=kh(kv,"px, ","px)","deg)"),Hv=kh(jv,", ",")",")"),Yv=1e-12;function Zu(e){return((e=Math.exp(e))+1/e)/2}function Wv(e){return((e=Math.exp(e))-1/e)/2}function $v(e){return((e=Math.exp(2*e))-1)/(e+1)}const ti=(function e(t,n,r){function o(i,a){var l=i[0],c=i[1],d=i[2],E=a[0],u=a[1],T=a[2],p=E-l,h=u-c,A=p*p+h*h,S,R;if(A<Yv)R=Math.log(T/d)/t,S=function(g){return[l+g*p,c+g*h,d*Math.exp(t*g*R)]};else{var m=Math.sqrt(A),I=(T*T-d*d+r*A)/(2*d*n*m),O=(T*T-d*d-r*A)/(2*T*n*m),N=Math.log(Math.sqrt(I*I+1)-I),x=Math.log(Math.sqrt(O*O+1)-O);R=(x-N)/t,S=function(g){var C=g*R,y=Zu(N),w=d/(n*m)*(y*$v(t*C+N)-Wv(N));return[l+w*p,c+w*h,d*y/Zu(t*C+N)]}}return S.duration=R*1e3*t/Math.SQRT2,S}return o.rho=function(i){var a=Math.max(.001,+i),l=a*a,c=l*l;return e(a,l,c)},o})(Math.SQRT2,2,4);var _r=0,so=0,eo=0,jh=1e3,_i,io,bi=0,Hn=0,Ra=0,Lo=typeof performance=="object"&&performance.now?performance:Date,Gh=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function Jd(){return Hn||(Gh(Vv),Hn=Lo.now()+Ra)}function Vv(){Hn=0}function Di(){this._call=this._time=this._next=null}Di.prototype=Hh.prototype={constructor:Di,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?Jd():+n)+(t==null?0:+t),!this._next&&io!==this&&(io?io._next=this:_i=this,io=this),this._call=e,this._time=n,Yc()},stop:function(){this._call&&(this._call=null,this._time=1/0,Yc())}};function Hh(e,t,n){var r=new Di;return r.restart(e,t,n),r}function Xv(){Jd(),++_r;for(var e=_i,t;e;)(t=Hn-e._time)>=0&&e._call.call(void 0,t),e=e._next;--_r}function eT(){Hn=(bi=Lo.now())+Ra,_r=so=0;try{Xv()}finally{_r=0,Kv(),Hn=0}}function zv(){var e=Lo.now(),t=e-bi;t>jh&&(Ra-=t,bi=e)}function Kv(){for(var e,t=_i,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:_i=n);io=e,Yc(r)}function Yc(e){if(!_r){so&&(so=clearTimeout(so));var t=e-Hn;t>24?(e<1/0&&(so=setTimeout(eT,e-Lo.now()-Ra)),eo&&(eo=clearInterval(eo))):(eo||(bi=Lo.now(),eo=setInterval(zv,jh)),_r=1,Gh(eT))}}function tT(e,t,n){var r=new Di;return t=t==null?0:+t,r.restart(o=>{r.stop(),e(o+t)},t,n),r}var qv=pa("start","end","cancel","interrupt"),Jv=[],Yh=0,nT=1,Wc=2,ni=3,rT=4,$c=5,ri=6;function ha(e,t,n,r,o,i){var a=e.__transition;if(!a)e.__transition={};else if(n in a)return;Qv(e,n,{name:t,index:r,group:o,on:qv,tween:Jv,time:i.time,delay:i.delay,duration:i.duration,ease:i.ease,timer:null,state:Yh})}function Qd(e,t){var n=mt(e,t);if(n.state>Yh)throw new Error("too late; already scheduled");return n}function Mt(e,t){var n=mt(e,t);if(n.state>ni)throw new Error("too late; already running");return n}function mt(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function Qv(e,t,n){var r=e.__transition,o;r[t]=n,n.timer=Hh(i,0,n.time);function i(d){n.state=nT,n.timer.restart(a,n.delay,n.time),n.delay<=d&&a(d-n.delay)}function a(d){var E,u,T,p;if(n.state!==nT)return c();for(E in r)if(p=r[E],p.name===n.name){if(p.state===ni)return tT(a);p.state===rT?(p.state=ri,p.timer.stop(),p.on.call("interrupt",e,e.__data__,p.index,p.group),delete r[E]):+E<t&&(p.state=ri,p.timer.stop(),p.on.call("cancel",e,e.__data__,p.index,p.group),delete r[E])}if(tT(function(){n.state===ni&&(n.state=rT,n.timer.restart(l,n.delay,n.time),l(d))}),n.state=Wc,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Wc){for(n.state=ni,o=new Array(T=n.tween.length),E=0,u=-1;E<T;++E)(p=n.tween[E].value.call(e,e.__data__,n.index,n.group))&&(o[++u]=p);o.length=u+1}}function l(d){for(var E=d<n.duration?n.ease.call(null,d/n.duration):(n.timer.restart(c),n.state=$c,1),u=-1,T=o.length;++u<T;)o[u].call(e,E);n.state===$c&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=ri,n.timer.stop(),delete r[t];for(var d in r)return;delete e.__transition}}function oi(e,t){var n=e.__transition,r,o,i=!0,a;if(n){t=t==null?null:t+"";for(a in n){if((r=n[a]).name!==t){i=!1;continue}o=r.state>Wc&&r.state<$c,r.state=ri,r.timer.stop(),r.on.call(o?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[a]}i&&delete e.__transition}}function Zv(e){return this.each(function(){oi(this,e)})}function eP(e,t){var n,r;return function(){var o=Mt(this,e),i=o.tween;if(i!==n){r=n=i;for(var a=0,l=r.length;a<l;++a)if(r[a].name===t){r=r.slice(),r.splice(a,1);break}}o.tween=r}}function tP(e,t,n){var r,o;if(typeof n!="function")throw new Error;return function(){var i=Mt(this,e),a=i.tween;if(a!==r){o=(r=a).slice();for(var l={name:t,value:n},c=0,d=o.length;c<d;++c)if(o[c].name===t){o[c]=l;break}c===d&&o.push(l)}i.tween=o}}function nP(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=mt(this.node(),n).tween,o=0,i=r.length,a;o<i;++o)if((a=r[o]).name===e)return a.value;return null}return this.each((t==null?eP:tP)(n,e,t))}function Zd(e,t,n){var r=e._id;return e.each(function(){var o=Mt(this,r);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return mt(o,r).value[t]}}function Wh(e,t){var n;return(typeof t=="number"?Nt:t instanceof Gn?Li:(n=Gn(t))?(t=n,Li):Bh)(e,t)}function rP(e){return function(){this.removeAttribute(e)}}function oP(e){return function(){this.removeAttributeNS(e.space,e.local)}}function sP(e,t,n){var r,o=n+"",i;return function(){var a=this.getAttribute(e);return a===o?null:a===r?i:i=t(r=a,n)}}function iP(e,t,n){var r,o=n+"",i;return function(){var a=this.getAttributeNS(e.space,e.local);return a===o?null:a===r?i:i=t(r=a,n)}}function aP(e,t,n){var r,o,i;return function(){var a,l=n(this),c;return l==null?void this.removeAttribute(e):(a=this.getAttribute(e),c=l+"",a===c?null:a===r&&c===o?i:(o=c,i=t(r=a,l)))}}function lP(e,t,n){var r,o,i;return function(){var a,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(a=this.getAttributeNS(e.space,e.local),c=l+"",a===c?null:a===r&&c===o?i:(o=c,i=t(r=a,l)))}}function cP(e,t){var n=Sa(e),r=n==="transform"?Hv:Wh;return this.attrTween(e,typeof t=="function"?(n.local?lP:aP)(n,r,Zd(this,"attr."+e,t)):t==null?(n.local?oP:rP)(n):(n.local?iP:sP)(n,r,t))}function dP(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function EP(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function uP(e,t){var n,r;function o(){var i=t.apply(this,arguments);return i!==r&&(n=(r=i)&&EP(e,i)),n}return o._value=t,o}function TP(e,t){var n,r;function o(){var i=t.apply(this,arguments);return i!==r&&(n=(r=i)&&dP(e,i)),n}return o._value=t,o}function fP(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=Sa(e);return this.tween(n,(r.local?uP:TP)(r,t))}function pP(e,t){return function(){Qd(this,e).delay=+t.apply(this,arguments)}}function SP(e,t){return t=+t,function(){Qd(this,e).delay=t}}function RP(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?pP:SP)(t,e)):mt(this.node(),t).delay}function hP(e,t){return function(){Mt(this,e).duration=+t.apply(this,arguments)}}function AP(e,t){return t=+t,function(){Mt(this,e).duration=t}}function IP(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?hP:AP)(t,e)):mt(this.node(),t).duration}function mP(e,t){if(typeof t!="function")throw new Error;return function(){Mt(this,e).ease=t}}function OP(e){var t=this._id;return arguments.length?this.each(mP(t,e)):mt(this.node(),t).ease}function NP(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Mt(this,e).ease=n}}function gP(e){if(typeof e!="function")throw new Error;return this.each(NP(this._id,e))}function xP(e){typeof e!="function"&&(e=mh(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var i=t[o],a=i.length,l=r[o]=[],c,d=0;d<a;++d)(c=i[d])&&e.call(c,c.__data__,d,i)&&l.push(c);return new Yt(r,this._parents,this._name,this._id)}function yP(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,o=n.length,i=Math.min(r,o),a=new Array(r),l=0;l<i;++l)for(var c=t[l],d=n[l],E=c.length,u=a[l]=new Array(E),T,p=0;p<E;++p)(T=c[p]||d[p])&&(u[p]=T);for(;l<r;++l)a[l]=t[l];return new Yt(a,this._parents,this._name,this._id)}function CP(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function LP(e,t,n){var r,o,i=CP(t)?Qd:Mt;return function(){var a=i(this,e),l=a.on;l!==r&&(o=(r=l).copy()).on(t,n),a.on=o}}function _P(e,t){var n=this._id;return arguments.length<2?mt(this.node(),n).on.on(e):this.each(LP(n,e,t))}function bP(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function DP(){return this.on("end.remove",bP(this._id))}function MP(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Xd(e));for(var r=this._groups,o=r.length,i=new Array(o),a=0;a<o;++a)for(var l=r[a],c=l.length,d=i[a]=new Array(c),E,u,T=0;T<c;++T)(E=l[T])&&(u=e.call(E,E.__data__,T,l))&&("__data__"in E&&(u.__data__=E.__data__),d[T]=u,ha(d[T],t,n,T,d,mt(E,n)));return new Yt(i,this._parents,t,n)}function vP(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Ih(e));for(var r=this._groups,o=r.length,i=[],a=[],l=0;l<o;++l)for(var c=r[l],d=c.length,E,u=0;u<d;++u)if(E=c[u]){for(var T=e.call(E,E.__data__,u,c),p,h=mt(E,n),A=0,S=T.length;A<S;++A)(p=T[A])&&ha(p,t,n,A,T,h);i.push(T),a.push(E)}return new Yt(i,a,t,n)}var PP=Wo.prototype.constructor;function wP(){return new PP(this._groups,this._parents)}function UP(e,t){var n,r,o;return function(){var i=Lr(this,e),a=(this.style.removeProperty(e),Lr(this,e));return i===a?null:i===n&&a===r?o:o=t(n=i,r=a)}}function $h(e){return function(){this.style.removeProperty(e)}}function BP(e,t,n){var r,o=n+"",i;return function(){var a=Lr(this,e);return a===o?null:a===r?i:i=t(r=a,n)}}function FP(e,t,n){var r,o,i;return function(){var a=Lr(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),Lr(this,e))),a===c?null:a===r&&c===o?i:(o=c,i=t(r=a,l))}}function kP(e,t){var n,r,o,i="style."+t,a="end."+i,l;return function(){var c=Mt(this,e),d=c.on,E=c.value[i]==null?l||(l=$h(t)):void 0;(d!==n||o!==E)&&(r=(n=d).copy()).on(a,o=E),c.on=r}}function jP(e,t,n){var r=(e+="")=="transform"?Gv:Wh;return t==null?this.styleTween(e,UP(e,r)).on("end.style."+e,$h(e)):typeof t=="function"?this.styleTween(e,FP(e,r,Zd(this,"style."+e,t))).each(kP(this._id,e)):this.styleTween(e,BP(e,r,t),n).on("end.style."+e,null)}function GP(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function HP(e,t,n){var r,o;function i(){var a=t.apply(this,arguments);return a!==o&&(r=(o=a)&&GP(e,a,n)),r}return i._value=t,i}function YP(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(t==null)return this.tween(r,null);if(typeof t!="function")throw new Error;return this.tween(r,HP(e,t,n??""))}function WP(e){return function(){this.textContent=e}}function $P(e){return function(){var t=e(this);this.textContent=t??""}}function VP(e){return this.tween("text",typeof e=="function"?$P(Zd(this,"text",e)):WP(e==null?"":e+""))}function XP(e){return function(t){this.textContent=e.call(this,t)}}function zP(e){var t,n;function r(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&XP(o)),t}return r._value=e,r}function KP(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(e==null)return this.tween(t,null);if(typeof e!="function")throw new Error;return this.tween(t,zP(e))}function qP(){for(var e=this._name,t=this._id,n=Vh(),r=this._groups,o=r.length,i=0;i<o;++i)for(var a=r[i],l=a.length,c,d=0;d<l;++d)if(c=a[d]){var E=mt(c,t);ha(c,e,n,d,a,{time:E.time+E.delay+E.duration,delay:0,duration:E.duration,ease:E.ease})}return new Yt(r,this._parents,e,n)}function JP(){var e,t,n=this,r=n._id,o=n.size();return new Promise(function(i,a){var l={value:a},c={value:function(){--o===0&&i()}};n.each(function(){var d=Mt(this,r),E=d.on;E!==e&&(t=(e=E).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),d.on=t}),o===0&&i()})}var QP=0;function Yt(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Vh(){return++QP}var Ut=Wo.prototype;Yt.prototype={constructor:Yt,select:MP,selectAll:vP,selectChild:Ut.selectChild,selectChildren:Ut.selectChildren,filter:xP,merge:yP,selection:wP,transition:qP,call:Ut.call,nodes:Ut.nodes,node:Ut.node,size:Ut.size,empty:Ut.empty,each:Ut.each,on:_P,attr:cP,attrTween:fP,style:jP,styleTween:YP,text:VP,textTween:KP,remove:DP,tween:nP,delay:RP,duration:IP,ease:OP,easeVarying:gP,end:JP,[Symbol.iterator]:Ut[Symbol.iterator]};function ZP(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var ew={time:null,delay:0,duration:250,ease:ZP};function tw(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}function nw(e){var t,n;e instanceof Yt?(t=e._id,e=e._name):(t=Vh(),(n=ew).time=Jd(),e=e==null?null:e+"");for(var r=this._groups,o=r.length,i=0;i<o;++i)for(var a=r[i],l=a.length,c,d=0;d<l;++d)(c=a[d])&&ha(c,e,t,d,a,n||tw(c,t));return new Yt(r,this._parents,e,t)}Wo.prototype.interrupt=Zv;Wo.prototype.transition=nw;const Bs=e=>()=>e;function rw(e,{sourceEvent:t,target:n,transform:r,dispatch:o}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:o}})}function Ft(e,t,n){this.k=e,this.x=t,this.y=n}Ft.prototype={constructor:Ft,scale:function(e){return e===1?this:new Ft(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Ft(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var Aa=new Ft(1,0,0);Xh.prototype=Ft.prototype;function Xh(e){for(;!e.__zoom;)if(!(e=e.parentNode))return Aa;return e.__zoom}function Il(e){e.stopImmediatePropagation()}function to(e){e.preventDefault(),e.stopImmediatePropagation()}function ow(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function sw(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute("viewBox")?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function oT(){return this.__zoom||Aa}function iw(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function aw(){return navigator.maxTouchPoints||"ontouchstart"in this}function lw(e,t,n){var r=e.invertX(t[0][0])-n[0][0],o=e.invertX(t[1][0])-n[1][0],i=e.invertY(t[0][1])-n[0][1],a=e.invertY(t[1][1])-n[1][1];return e.translate(o>r?(r+o)/2:Math.min(0,r)||Math.max(0,o),a>i?(i+a)/2:Math.min(0,i)||Math.max(0,a))}function zh(){var e=ow,t=sw,n=lw,r=iw,o=aw,i=[0,1/0],a=[[-1/0,-1/0],[1/0,1/0]],l=250,c=ti,d=pa("start","zoom","end"),E,u,T,p=500,h=150,A=0,S=10;function R(L){L.property("__zoom",oT).on("wheel.zoom",C,{passive:!1}).on("mousedown.zoom",y).on("dblclick.zoom",w).filter(o).on("touchstart.zoom",v).on("touchmove.zoom",B).on("touchend.zoom touchcancel.zoom",b).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}R.transform=function(L,D,M,U){var P=L.selection?L.selection():L;P.property("__zoom",oT),L!==P?N(L,D,M,U):P.interrupt().each(function(){x(this,arguments).event(U).start().zoom(null,typeof D=="function"?D.apply(this,arguments):D).end()})},R.scaleBy=function(L,D,M,U){R.scaleTo(L,function(){var P=this.__zoom.k,_=typeof D=="function"?D.apply(this,arguments):D;return P*_},M,U)},R.scaleTo=function(L,D,M,U){R.transform(L,function(){var P=t.apply(this,arguments),_=this.__zoom,F=M==null?O(P):typeof M=="function"?M.apply(this,arguments):M,k=_.invert(F),H=typeof D=="function"?D.apply(this,arguments):D;return n(I(m(_,H),F,k),P,a)},M,U)},R.translateBy=function(L,D,M,U){R.transform(L,function(){return n(this.__zoom.translate(typeof D=="function"?D.apply(this,arguments):D,typeof M=="function"?M.apply(this,arguments):M),t.apply(this,arguments),a)},null,U)},R.translateTo=function(L,D,M,U,P){R.transform(L,function(){var _=t.apply(this,arguments),F=this.__zoom,k=U==null?O(_):typeof U=="function"?U.apply(this,arguments):U;return n(Aa.translate(k[0],k[1]).scale(F.k).translate(typeof D=="function"?-D.apply(this,arguments):-D,typeof M=="function"?-M.apply(this,arguments):-M),_,a)},U,P)};function m(L,D){return D=Math.max(i[0],Math.min(i[1],D)),D===L.k?L:new Ft(D,L.x,L.y)}function I(L,D,M){var U=D[0]-M[0]*L.k,P=D[1]-M[1]*L.k;return U===L.x&&P===L.y?L:new Ft(L.k,U,P)}function O(L){return[(+L[0][0]+ +L[1][0])/2,(+L[0][1]+ +L[1][1])/2]}function N(L,D,M,U){L.on("start.zoom",function(){x(this,arguments).event(U).start()}).on("interrupt.zoom end.zoom",function(){x(this,arguments).event(U).end()}).tween("zoom",function(){var P=this,_=arguments,F=x(P,_).event(U),k=t.apply(P,_),H=M==null?O(k):typeof M=="function"?M.apply(P,_):M,Q=Math.max(k[1][0]-k[0][0],k[1][1]-k[0][1]),q=P.__zoom,$=typeof D=="function"?D.apply(P,_):D,Z=c(q.invert(H).concat(Q/q.k),$.invert(H).concat(Q/$.k));return function(Y){if(Y===1)Y=$;else{var G=Z(Y),J=Q/G[2];Y=new Ft(J,H[0]-G[0]*J,H[1]-G[1]*J)}F.zoom(null,Y)}})}function x(L,D,M){return!M&&L.__zooming||new g(L,D)}function g(L,D){this.that=L,this.args=D,this.active=0,this.sourceEvent=null,this.extent=t.apply(L,D),this.taps=0}g.prototype={event:function(L){return L&&(this.sourceEvent=L),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(L,D){return this.mouse&&L!=="mouse"&&(this.mouse[1]=D.invert(this.mouse[0])),this.touch0&&L!=="touch"&&(this.touch0[1]=D.invert(this.touch0[0])),this.touch1&&L!=="touch"&&(this.touch1[1]=D.invert(this.touch1[0])),this.that.__zoom=D,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(L){var D=qe(this.that).datum();d.call(L,this.that,new rw(L,{sourceEvent:this.sourceEvent,target:R,transform:this.that.__zoom,dispatch:d}),D)}};function C(L,...D){if(!e.apply(this,arguments))return;var M=x(this,D).event(L),U=this.__zoom,P=Math.max(i[0],Math.min(i[1],U.k*Math.pow(2,r.apply(this,arguments)))),_=dt(L);if(M.wheel)(M.mouse[0][0]!==_[0]||M.mouse[0][1]!==_[1])&&(M.mouse[1]=U.invert(M.mouse[0]=_)),clearTimeout(M.wheel);else{if(U.k===P)return;M.mouse=[_,U.invert(_)],oi(this),M.start()}to(L),M.wheel=setTimeout(F,h),M.zoom("mouse",n(I(m(U,P),M.mouse[0],M.mouse[1]),M.extent,a));function F(){M.wheel=null,M.end()}}function y(L,...D){if(T||!e.apply(this,arguments))return;var M=L.currentTarget,U=x(this,D,!0).event(L),P=qe(L.view).on("mousemove.zoom",H,!0).on("mouseup.zoom",Q,!0),_=dt(L,M),F=L.clientX,k=L.clientY;Dh(L.view),Il(L),U.mouse=[_,this.__zoom.invert(_)],oi(this),U.start();function H(q){if(to(q),!U.moved){var $=q.clientX-F,Z=q.clientY-k;U.moved=$*$+Z*Z>A}U.event(q).zoom("mouse",n(I(U.that.__zoom,U.mouse[0]=dt(q,M),U.mouse[1]),U.extent,a))}function Q(q){P.on("mousemove.zoom mouseup.zoom",null),Mh(q.view,U.moved),to(q),U.event(q).end()}}function w(L,...D){if(e.apply(this,arguments)){var M=this.__zoom,U=dt(L.changedTouches?L.changedTouches[0]:L,this),P=M.invert(U),_=M.k*(L.shiftKey?.5:2),F=n(I(m(M,_),U,P),t.apply(this,D),a);to(L),l>0?qe(this).transition().duration(l).call(N,F,U,L):qe(this).call(R.transform,F,U,L)}}function v(L,...D){if(e.apply(this,arguments)){var M=L.touches,U=M.length,P=x(this,D,L.changedTouches.length===U).event(L),_,F,k,H;for(Il(L),F=0;F<U;++F)k=M[F],H=dt(k,this),H=[H,this.__zoom.invert(H),k.identifier],P.touch0?!P.touch1&&P.touch0[2]!==H[2]&&(P.touch1=H,P.taps=0):(P.touch0=H,_=!0,P.taps=1+!!E);E&&(E=clearTimeout(E)),_&&(P.taps<2&&(u=H[0],E=setTimeout(function(){E=null},p)),oi(this),P.start())}}function B(L,...D){if(this.__zooming){var M=x(this,D).event(L),U=L.changedTouches,P=U.length,_,F,k,H;for(to(L),_=0;_<P;++_)F=U[_],k=dt(F,this),M.touch0&&M.touch0[2]===F.identifier?M.touch0[0]=k:M.touch1&&M.touch1[2]===F.identifier&&(M.touch1[0]=k);if(F=M.that.__zoom,M.touch1){var Q=M.touch0[0],q=M.touch0[1],$=M.touch1[0],Z=M.touch1[1],Y=(Y=$[0]-Q[0])*Y+(Y=$[1]-Q[1])*Y,G=(G=Z[0]-q[0])*G+(G=Z[1]-q[1])*G;F=m(F,Math.sqrt(Y/G)),k=[(Q[0]+$[0])/2,(Q[1]+$[1])/2],H=[(q[0]+Z[0])/2,(q[1]+Z[1])/2]}else if(M.touch0)k=M.touch0[0],H=M.touch0[1];else return;M.zoom("touch",n(I(F,k,H),M.extent,a))}}function b(L,...D){if(this.__zooming){var M=x(this,D).event(L),U=L.changedTouches,P=U.length,_,F;for(Il(L),T&&clearTimeout(T),T=setTimeout(function(){T=null},p),_=0;_<P;++_)F=U[_],M.touch0&&M.touch0[2]===F.identifier?delete M.touch0:M.touch1&&M.touch1[2]===F.identifier&&delete M.touch1;if(M.touch1&&!M.touch0&&(M.touch0=M.touch1,delete M.touch1),M.touch0)M.touch0[1]=this.__zoom.invert(M.touch0[0]);else if(M.end(),M.taps===2&&(F=dt(F,this),Math.hypot(u[0]-F[0],u[1]-F[1])<S)){var k=qe(this).on("dblclick.zoom");k&&k.apply(this,arguments)}}}return R.wheelDelta=function(L){return arguments.length?(r=typeof L=="function"?L:Bs(+L),R):r},R.filter=function(L){return arguments.length?(e=typeof L=="function"?L:Bs(!!L),R):e},R.touchable=function(L){return arguments.length?(o=typeof L=="function"?L:Bs(!!L),R):o},R.extent=function(L){return arguments.length?(t=typeof L=="function"?L:Bs([[+L[0][0],+L[0][1]],[+L[1][0],+L[1][1]]]),R):t},R.scaleExtent=function(L){return arguments.length?(i[0]=+L[0],i[1]=+L[1],R):[i[0],i[1]]},R.translateExtent=function(L){return arguments.length?(a[0][0]=+L[0][0],a[1][0]=+L[1][0],a[0][1]=+L[0][1],a[1][1]=+L[1][1],R):[[a[0][0],a[0][1]],[a[1][0],a[1][1]]]},R.constrain=function(L){return arguments.length?(n=L,R):n},R.duration=function(L){return arguments.length?(l=+L,R):l},R.interpolate=function(L){return arguments.length?(c=L,R):c},R.on=function(){var L=d.on.apply(d,arguments);return L===d?R:L},R.clickDistance=function(L){return arguments.length?(A=(L=+L)*L,R):Math.sqrt(A)},R.tapDistance=function(L){return arguments.length?(S=+L,R):S},R}const bt={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},_o=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Kh=["Enter"," ","Escape"],qh={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var br;(function(e){e.Strict="strict",e.Loose="loose"})(br||(br={}));var Un;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Un||(Un={}));var bo;(function(e){e.Partial="partial",e.Full="full"})(bo||(bo={}));const Jh={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var an;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(an||(an={}));var Dr;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(Dr||(Dr={}));var ae;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(ae||(ae={}));const sT={[ae.Left]:ae.Right,[ae.Right]:ae.Left,[ae.Top]:ae.Bottom,[ae.Bottom]:ae.Top};function Qh(e){return e===null?null:e?"valid":"invalid"}const Zh=e=>"id"in e&&"source"in e&&"target"in e,cw=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),eE=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),Vo=(e,t=[0,0])=>{const{width:n,height:r}=$t(e),o=e.origin??t,i=n*o[0],a=r*o[1];return{x:e.position.x-i,y:e.position.y-a}},dw=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,o)=>{const i=typeof o=="string";let a=!t.nodeLookup&&!i?o:void 0;t.nodeLookup&&(a=i?t.nodeLookup.get(o):eE(o)?o:t.nodeLookup.get(o.id));const l=a?Mi(a,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return Ia(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return ma(n)},Xo=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(o=>{(t.filter===void 0||t.filter(o))&&(n=Ia(n,Mi(o)),r=!0)}),r?ma(n):{x:0,y:0,width:0,height:0}},tE=(e,t,[n,r,o]=[0,0,1],i=!1,a=!1)=>{const l={...Ko(t,[n,r,o]),width:t.width/o,height:t.height/o},c=[];for(const d of e.values()){const{measured:E,selectable:u=!0,hidden:T=!1}=d;if(a&&!u||T)continue;const p=E.width??d.width??d.initialWidth??null,h=E.height??d.height??d.initialHeight??null,A=Do(l,vr(d)),S=(p??0)*(h??0),R=i&&A>0;(!d.internals.handleBounds||R||A>=S||d.dragging)&&c.push(d)}return c},Ew=(e,t)=>{const n=new Set;return e.forEach(r=>{n.add(r.id)}),t.filter(r=>n.has(r.source)||n.has(r.target))};function uw(e,t){const n=new Map,r=t!=null&&t.nodes?new Set(t.nodes.map(o=>o.id)):null;return e.forEach(o=>{o.measured.width&&o.measured.height&&((t==null?void 0:t.includeHiddenNodes)||!o.hidden)&&(!r||r.has(o.id))&&n.set(o.id,o)}),n}async function Tw({nodes:e,width:t,height:n,panZoom:r,minZoom:o,maxZoom:i},a){if(e.size===0)return Promise.resolve(!0);const l=uw(e,a),c=Xo(l),d=nE(c,t,n,(a==null?void 0:a.minZoom)??o,(a==null?void 0:a.maxZoom)??i,(a==null?void 0:a.padding)??.1);return await r.setViewport(d,{duration:a==null?void 0:a.duration,ease:a==null?void 0:a.ease,interpolate:a==null?void 0:a.interpolate}),Promise.resolve(!0)}function eA({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:o,onError:i}){const a=n.get(e),l=a.parentId?n.get(a.parentId):void 0,{x:c,y:d}=l?l.internals.positionAbsolute:{x:0,y:0},E=a.origin??r;let u=a.extent||o;if(a.extent==="parent"&&!a.expandParent)if(!l)i==null||i("005",bt.error005());else{const p=l.measured.width,h=l.measured.height;p&&h&&(u=[[c,d],[c+p,d+h]])}else l&&Pr(a.extent)&&(u=[[a.extent[0][0]+c,a.extent[0][1]+d],[a.extent[1][0]+c,a.extent[1][1]+d]]);const T=Pr(u)?Yn(t,u,a.measured):t;return(a.measured.width===void 0||a.measured.height===void 0)&&(i==null||i("015",bt.error015())),{position:{x:T.x-c+(a.measured.width??0)*E[0],y:T.y-d+(a.measured.height??0)*E[1]},positionAbsolute:T}}async function fw({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:o}){const i=new Set(e.map(T=>T.id)),a=[];for(const T of n){if(T.deletable===!1)continue;const p=i.has(T.id),h=!p&&T.parentId&&a.find(A=>A.id===T.parentId);(p||h)&&a.push(T)}const l=new Set(t.map(T=>T.id)),c=r.filter(T=>T.deletable!==!1),E=Ew(a,c);for(const T of c)l.has(T.id)&&!E.find(h=>h.id===T.id)&&E.push(T);if(!o)return{edges:E,nodes:a};const u=await o({nodes:a,edges:E});return typeof u=="boolean"?u?{edges:E,nodes:a}:{edges:[],nodes:[]}:u}const Mr=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Yn=(e={x:0,y:0},t,n)=>({x:Mr(e.x,t[0][0],t[1][0]-((n==null?void 0:n.width)??0)),y:Mr(e.y,t[0][1],t[1][1]-((n==null?void 0:n.height)??0))});function tA(e,t,n){const{width:r,height:o}=$t(n),{x:i,y:a}=n.internals.positionAbsolute;return Yn(e,[[i,a],[i+r,a+o]],t)}const iT=(e,t,n)=>e<t?Mr(Math.abs(e-t),1,t)/t:e>n?-Mr(Math.abs(e-n),1,t)/t:0,nA=(e,t,n=15,r=40)=>{const o=iT(e.x,r,t.width-r)*n,i=iT(e.y,r,t.height-r)*n;return[o,i]},Ia=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Vc=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),ma=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),vr=(e,t=[0,0])=>{var o,i;const{x:n,y:r}=eE(e)?e.internals.positionAbsolute:Vo(e,t);return{x:n,y:r,width:((o=e.measured)==null?void 0:o.width)??e.width??e.initialWidth??0,height:((i=e.measured)==null?void 0:i.height)??e.height??e.initialHeight??0}},Mi=(e,t=[0,0])=>{var o,i;const{x:n,y:r}=eE(e)?e.internals.positionAbsolute:Vo(e,t);return{x:n,y:r,x2:n+(((o=e.measured)==null?void 0:o.width)??e.width??e.initialWidth??0),y2:r+(((i=e.measured)==null?void 0:i.height)??e.height??e.initialHeight??0)}},rA=(e,t)=>ma(Ia(Vc(e),Vc(t))),Do=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},aT=e=>Tt(e.width)&&Tt(e.height)&&Tt(e.x)&&Tt(e.y),Tt=e=>!isNaN(e)&&isFinite(e),pw=(e,t)=>{},zo=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),Ko=({x:e,y:t},[n,r,o],i=!1,a=[1,1])=>{const l={x:(e-n)/o,y:(t-r)/o};return i?zo(l,a):l},vi=({x:e,y:t},[n,r,o])=>({x:e*o+n,y:t*o+r});function ar(e,t){if(typeof e=="number")return Math.floor((t-t/(1+e))*.5);if(typeof e=="string"&&e.endsWith("px")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(n)}if(typeof e=="string"&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function Sw(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=ar(e,n),o=ar(e,t);return{top:r,right:o,bottom:r,left:o,x:o*2,y:r*2}}if(typeof e=="object"){const r=ar(e.top??e.y??0,n),o=ar(e.bottom??e.y??0,n),i=ar(e.left??e.x??0,t),a=ar(e.right??e.x??0,t);return{top:r,right:a,bottom:o,left:i,x:i+a,y:r+o}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function Rw(e,t,n,r,o,i){const{x:a,y:l}=vi(e,[t,n,r]),{x:c,y:d}=vi({x:e.x+e.width,y:e.y+e.height},[t,n,r]),E=o-c,u=i-d;return{left:Math.floor(a),top:Math.floor(l),right:Math.floor(E),bottom:Math.floor(u)}}const nE=(e,t,n,r,o,i)=>{const a=Sw(i,t,n),l=(t-a.x)/e.width,c=(n-a.y)/e.height,d=Math.min(l,c),E=Mr(d,r,o),u=e.x+e.width/2,T=e.y+e.height/2,p=t/2-u*E,h=n/2-T*E,A=Rw(e,p,h,E,t,n),S={left:Math.min(A.left-a.left,0),top:Math.min(A.top-a.top,0),right:Math.min(A.right-a.right,0),bottom:Math.min(A.bottom-a.bottom,0)};return{x:p-S.left+S.right,y:h-S.top+S.bottom,zoom:E}},Mo=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0};function Pr(e){return e!=null&&e!=="parent"}function $t(e){var t,n;return{width:((t=e.measured)==null?void 0:t.width)??e.width??e.initialWidth??0,height:((n=e.measured)==null?void 0:n.height)??e.height??e.initialHeight??0}}function oA(e){var t,n;return(((t=e.measured)==null?void 0:t.width)??e.width??e.initialWidth)!==void 0&&(((n=e.measured)==null?void 0:n.height)??e.height??e.initialHeight)!==void 0}function sA(e,t={width:0,height:0},n,r,o){const i={...e},a=r.get(n);if(a){const l=a.origin||o;i.x+=a.internals.positionAbsolute.x-(t.width??0)*l[0],i.y+=a.internals.positionAbsolute.y-(t.height??0)*l[1]}return i}function lT(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function hw(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function Aw(e){return{...qh,...e||{}}}function uo(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:o}){const{x:i,y:a}=ft(e),l=Ko({x:i-((o==null?void 0:o.left)??0),y:a-((o==null?void 0:o.top)??0)},r),{x:c,y:d}=n?zo(l,t):l;return{xSnapped:c,ySnapped:d,...l}}const rE=e=>({width:e.offsetWidth,height:e.offsetHeight}),iA=e=>{var t;return((t=e==null?void 0:e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},Iw=["INPUT","SELECT","TEXTAREA"];function aA(e){var r,o;const t=((o=(r=e.composedPath)==null?void 0:r.call(e))==null?void 0:o[0])||e.target;return(t==null?void 0:t.nodeType)!==1?!1:Iw.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const lA=e=>"clientX"in e,ft=(e,t)=>{var i,a;const n=lA(e),r=n?e.clientX:(i=e.touches)==null?void 0:i[0].clientX,o=n?e.clientY:(a=e.touches)==null?void 0:a[0].clientY;return{x:r-((t==null?void 0:t.left)??0),y:o-((t==null?void 0:t.top)??0)}},cT=(e,t,n,r,o)=>{const i=t.querySelectorAll(`.${e}`);return!i||!i.length?null:Array.from(i).map(a=>{const l=a.getBoundingClientRect();return{id:a.getAttribute("data-handleid"),type:e,nodeId:o,position:a.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...rE(a)}})};function cA({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:o,sourceControlY:i,targetControlX:a,targetControlY:l}){const c=e*.125+o*.375+a*.375+n*.125,d=t*.125+i*.375+l*.375+r*.125,E=Math.abs(c-e),u=Math.abs(d-t);return[c,d,E,u]}function Fs(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function dT({pos:e,x1:t,y1:n,x2:r,y2:o,c:i}){switch(e){case ae.Left:return[t-Fs(t-r,i),n];case ae.Right:return[t+Fs(r-t,i),n];case ae.Top:return[t,n-Fs(n-o,i)];case ae.Bottom:return[t,n+Fs(o-n,i)]}}function dA({sourceX:e,sourceY:t,sourcePosition:n=ae.Bottom,targetX:r,targetY:o,targetPosition:i=ae.Top,curvature:a=.25}){const[l,c]=dT({pos:n,x1:e,y1:t,x2:r,y2:o,c:a}),[d,E]=dT({pos:i,x1:r,y1:o,x2:e,y2:t,c:a}),[u,T,p,h]=cA({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:l,sourceControlY:c,targetControlX:d,targetControlY:E});return[`M${e},${t} C${l},${c} ${d},${E} ${r},${o}`,u,T,p,h]}function EA({sourceX:e,sourceY:t,targetX:n,targetY:r}){const o=Math.abs(n-e)/2,i=n<e?n+o:n-o,a=Math.abs(r-t)/2,l=r<t?r+a:r-a;return[i,l,o,a]}function mw({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:o=!1,zIndexMode:i="basic"}){if(i==="manual")return r;const a=o&&n?r+1e3:r,l=Math.max(e.parentId||o&&e.selected?e.internals.z:0,t.parentId||o&&t.selected?t.internals.z:0);return a+l}function Ow({sourceNode:e,targetNode:t,width:n,height:r,transform:o}){const i=Ia(Mi(e),Mi(t));i.x===i.x2&&(i.x2+=1),i.y===i.y2&&(i.y2+=1);const a={x:-o[0]/o[2],y:-o[1]/o[2],width:n/o[2],height:r/o[2]};return Do(a,ma(i))>0}const Nw=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,gw=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),xw=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||Nw;let o;return Zh(e)?o={...e}:o={...e,id:r(e)},gw(o,t)?t:(o.sourceHandle===null&&delete o.sourceHandle,o.targetHandle===null&&delete o.targetHandle,t.concat(o))};function uA({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[o,i,a,l]=EA({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,o,i,a,l]}const ET={[ae.Left]:{x:-1,y:0},[ae.Right]:{x:1,y:0},[ae.Top]:{x:0,y:-1},[ae.Bottom]:{x:0,y:1}},yw=({source:e,sourcePosition:t=ae.Bottom,target:n})=>t===ae.Left||t===ae.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},uT=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function Cw({source:e,sourcePosition:t=ae.Bottom,target:n,targetPosition:r=ae.Top,center:o,offset:i,stepPosition:a}){const l=ET[t],c=ET[r],d={x:e.x+l.x*i,y:e.y+l.y*i},E={x:n.x+c.x*i,y:n.y+c.y*i},u=yw({source:d,sourcePosition:t,target:E}),T=u.x!==0?"x":"y",p=u[T];let h=[],A,S;const R={x:0,y:0},m={x:0,y:0},[,,I,O]=EA({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[T]*c[T]===-1){T==="x"?(A=o.x??d.x+(E.x-d.x)*a,S=o.y??(d.y+E.y)/2):(A=o.x??(d.x+E.x)/2,S=o.y??d.y+(E.y-d.y)*a);const x=[{x:A,y:d.y},{x:A,y:E.y}],g=[{x:d.x,y:S},{x:E.x,y:S}];l[T]===p?h=T==="x"?x:g:h=T==="x"?g:x}else{const x=[{x:d.x,y:E.y}],g=[{x:E.x,y:d.y}];if(T==="x"?h=l.x===p?g:x:h=l.y===p?x:g,t===r){const B=Math.abs(e[T]-n[T]);if(B<=i){const b=Math.min(i-1,i-B);l[T]===p?R[T]=(d[T]>e[T]?-1:1)*b:m[T]=(E[T]>n[T]?-1:1)*b}}if(t!==r){const B=T==="x"?"y":"x",b=l[T]===c[B],L=d[B]>E[B],D=d[B]<E[B];(l[T]===1&&(!b&&L||b&&D)||l[T]!==1&&(!b&&D||b&&L))&&(h=T==="x"?x:g)}const C={x:d.x+R.x,y:d.y+R.y},y={x:E.x+m.x,y:E.y+m.y},w=Math.max(Math.abs(C.x-h[0].x),Math.abs(y.x-h[0].x)),v=Math.max(Math.abs(C.y-h[0].y),Math.abs(y.y-h[0].y));w>=v?(A=(C.x+y.x)/2,S=h[0].y):(A=h[0].x,S=(C.y+y.y)/2)}return[[e,{x:d.x+R.x,y:d.y+R.y},...h,{x:E.x+m.x,y:E.y+m.y},n],A,S,I,O]}function Lw(e,t,n,r){const o=Math.min(uT(e,t)/2,uT(t,n)/2,r),{x:i,y:a}=t;if(e.x===i&&i===n.x||e.y===a&&a===n.y)return`L${i} ${a}`;if(e.y===a){const d=e.x<n.x?-1:1,E=e.y<n.y?1:-1;return`L ${i+o*d},${a}Q ${i},${a} ${i},${a+o*E}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${i},${a+o*c}Q ${i},${a} ${i+o*l},${a}`}function Xc({sourceX:e,sourceY:t,sourcePosition:n=ae.Bottom,targetX:r,targetY:o,targetPosition:i=ae.Top,borderRadius:a=5,centerX:l,centerY:c,offset:d=20,stepPosition:E=.5}){const[u,T,p,h,A]=Cw({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:o},targetPosition:i,center:{x:l,y:c},offset:d,stepPosition:E});return[u.reduce((R,m,I)=>{let O="";return I>0&&I<u.length-1?O=Lw(u[I-1],m,u[I+1],a):O=`${I===0?"M":"L"}${m.x} ${m.y}`,R+=O,R},""),T,p,h,A]}function TT(e){var t;return e&&!!(e.internals.handleBounds||(t=e.handles)!=null&&t.length)&&!!(e.measured.width||e.width||e.initialWidth)}function _w(e){var u;const{sourceNode:t,targetNode:n}=e;if(!TT(t)||!TT(n))return null;const r=t.internals.handleBounds||fT(t.handles),o=n.internals.handleBounds||fT(n.handles),i=pT((r==null?void 0:r.source)??[],e.sourceHandle),a=pT(e.connectionMode===br.Strict?(o==null?void 0:o.target)??[]:((o==null?void 0:o.target)??[]).concat((o==null?void 0:o.source)??[]),e.targetHandle);if(!i||!a)return(u=e.onError)==null||u.call(e,"008",bt.error008(i?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=(i==null?void 0:i.position)||ae.Bottom,c=(a==null?void 0:a.position)||ae.Top,d=Wn(t,i,l),E=Wn(n,a,c);return{sourceX:d.x,sourceY:d.y,targetX:E.x,targetY:E.y,sourcePosition:l,targetPosition:c}}function fT(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,r.type==="source"?t.push(r):r.type==="target"&&n.push(r);return{source:t,target:n}}function Wn(e,t,n=ae.Left,r=!1){const o=((t==null?void 0:t.x)??0)+e.internals.positionAbsolute.x,i=((t==null?void 0:t.y)??0)+e.internals.positionAbsolute.y,{width:a,height:l}=t??$t(e);if(r)return{x:o+a/2,y:i+l/2};switch((t==null?void 0:t.position)??n){case ae.Top:return{x:o+a/2,y:i};case ae.Right:return{x:o+a,y:i+l/2};case ae.Bottom:return{x:o+a/2,y:i+l};case ae.Left:return{x:o,y:i+l/2}}}function pT(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function zc(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function bw(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:o}){const i=new Set;return e.reduce((a,l)=>([l.markerStart||r,l.markerEnd||o].forEach(c=>{if(c&&typeof c=="object"){const d=zc(c,t);i.has(d)||(a.push({id:d,color:c.color||n,...c}),i.add(d))}}),a),[]).sort((a,l)=>a.id.localeCompare(l.id))}const TA=1e3,Dw=10,oE={nodeOrigin:[0,0],nodeExtent:_o,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},Mw={...oE,checkEquality:!0};function sE(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function vw(e,t,n){const r=sE(oE,n);for(const o of e.values())if(o.parentId)aE(o,e,t,r);else{const i=Vo(o,r.nodeOrigin),a=Pr(o.extent)?o.extent:r.nodeExtent,l=Yn(i,a,$t(o));o.internals.positionAbsolute=l}}function Pw(e,t){if(!e.handles)return e.measured?t==null?void 0:t.internals.handleBounds:void 0;const n=[],r=[];for(const o of e.handles){const i={id:o.id,width:o.width??1,height:o.height??1,nodeId:e.id,x:o.x,y:o.y,position:o.position,type:o.type};o.type==="source"?n.push(i):o.type==="target"&&r.push(i)}return{source:n,target:r}}function iE(e){return e==="manual"}function Kc(e,t,n,r={}){var d,E;const o=sE(Mw,r),i={i:0},a=new Map(t),l=o!=null&&o.elevateNodesOnSelect&&!iE(o.zIndexMode)?TA:0;let c=e.length>0;t.clear(),n.clear();for(const u of e){let T=a.get(u.id);if(o.checkEquality&&u===(T==null?void 0:T.internals.userNode))t.set(u.id,T);else{const p=Vo(u,o.nodeOrigin),h=Pr(u.extent)?u.extent:o.nodeExtent,A=Yn(p,h,$t(u));T={...o.defaults,...u,measured:{width:(d=u.measured)==null?void 0:d.width,height:(E=u.measured)==null?void 0:E.height},internals:{positionAbsolute:A,handleBounds:Pw(u,T),z:fA(u,l,o.zIndexMode),userNode:u}},t.set(u.id,T)}(T.measured===void 0||T.measured.width===void 0||T.measured.height===void 0)&&!T.hidden&&(c=!1),u.parentId&&aE(T,t,n,r,i)}return c}function ww(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function aE(e,t,n,r,o){const{elevateNodesOnSelect:i,nodeOrigin:a,nodeExtent:l,zIndexMode:c}=sE(oE,r),d=e.parentId,E=t.get(d);if(!E){console.warn(`Parent node ${d} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}ww(e,n),o&&!E.parentId&&E.internals.rootParentIndex===void 0&&c==="auto"&&(E.internals.rootParentIndex=++o.i,E.internals.z=E.internals.z+o.i*Dw),o&&E.internals.rootParentIndex!==void 0&&(o.i=E.internals.rootParentIndex);const u=i&&!iE(c)?TA:0,{x:T,y:p,z:h}=Uw(e,E,a,l,u,c),{positionAbsolute:A}=e.internals,S=T!==A.x||p!==A.y;(S||h!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:S?{x:T,y:p}:A,z:h}})}function fA(e,t,n){const r=Tt(e.zIndex)?e.zIndex:0;return iE(n)?r:r+(e.selected?t:0)}function Uw(e,t,n,r,o,i){const{x:a,y:l}=t.internals.positionAbsolute,c=$t(e),d=Vo(e,n),E=Pr(e.extent)?Yn(d,e.extent,c):d;let u=Yn({x:a+E.x,y:l+E.y},r,c);e.extent==="parent"&&(u=tA(u,c,t));const T=fA(e,o,i),p=t.internals.z??0;return{x:u.x,y:u.y,z:p>=T?p+1:T}}function lE(e,t,n,r=[0,0]){var a;const o=[],i=new Map;for(const l of e){const c=t.get(l.parentId);if(!c)continue;const d=((a=i.get(l.parentId))==null?void 0:a.expandedRect)??vr(c),E=rA(d,l.rect);i.set(l.parentId,{expandedRect:E,parent:c})}return i.size>0&&i.forEach(({expandedRect:l,parent:c},d)=>{var I;const E=c.internals.positionAbsolute,u=$t(c),T=c.origin??r,p=l.x<E.x?Math.round(Math.abs(E.x-l.x)):0,h=l.y<E.y?Math.round(Math.abs(E.y-l.y)):0,A=Math.max(u.width,Math.round(l.width)),S=Math.max(u.height,Math.round(l.height)),R=(A-u.width)*T[0],m=(S-u.height)*T[1];(p>0||h>0||R||m)&&(o.push({id:d,type:"position",position:{x:c.position.x-p+R,y:c.position.y-h+m}}),(I=n.get(d))==null||I.forEach(O=>{e.some(N=>N.id===O.id)||o.push({id:O.id,type:"position",position:{x:O.position.x+p,y:O.position.y+h}})})),(u.width<l.width||u.height<l.height||p||h)&&o.push({id:d,type:"dimensions",setAttributes:!0,dimensions:{width:A+(p?T[0]*p-R:0),height:S+(h?T[1]*h-m:0)}})}),o}function Bw(e,t,n,r,o,i,a){const l=r==null?void 0:r.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const d=[],E=window.getComputedStyle(l),{m22:u}=new window.DOMMatrixReadOnly(E.transform),T=[];for(const p of e.values()){const h=t.get(p.id);if(!h)continue;if(h.hidden){t.set(h.id,{...h,internals:{...h.internals,handleBounds:void 0}}),c=!0;continue}const A=rE(p.nodeElement),S=h.measured.width!==A.width||h.measured.height!==A.height;if(!!(A.width&&A.height&&(S||!h.internals.handleBounds||p.force))){const m=p.nodeElement.getBoundingClientRect(),I=Pr(h.extent)?h.extent:i;let{positionAbsolute:O}=h.internals;h.parentId&&h.extent==="parent"?O=tA(O,A,t.get(h.parentId)):I&&(O=Yn(O,I,A));const N={...h,measured:A,internals:{...h.internals,positionAbsolute:O,handleBounds:{source:cT("source",p.nodeElement,m,u,h.id),target:cT("target",p.nodeElement,m,u,h.id)}}};t.set(h.id,N),h.parentId&&aE(N,t,n,{nodeOrigin:o,zIndexMode:a}),c=!0,S&&(d.push({id:h.id,type:"dimensions",dimensions:A}),h.expandParent&&h.parentId&&T.push({id:h.id,parentId:h.parentId,rect:vr(N,o)}))}}if(T.length>0){const p=lE(T,t,n,o);d.push(...p)}return{changes:d,updatedInternals:c}}async function Fw({delta:e,panZoom:t,transform:n,translateExtent:r,width:o,height:i}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const a=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[o,i]],r),l=!!a&&(a.x!==n[0]||a.y!==n[1]||a.k!==n[2]);return Promise.resolve(l)}function ST(e,t,n,r,o,i){let a=o;const l=r.get(a)||new Map;r.set(a,l.set(n,t)),a=`${o}-${e}`;const c=r.get(a)||new Map;if(r.set(a,c.set(n,t)),i){a=`${o}-${e}-${i}`;const d=r.get(a)||new Map;r.set(a,d.set(n,t))}}function pA(e,t,n){e.clear(),t.clear();for(const r of n){const{source:o,target:i,sourceHandle:a=null,targetHandle:l=null}=r,c={edgeId:r.id,source:o,target:i,sourceHandle:a,targetHandle:l},d=`${o}-${a}--${i}-${l}`,E=`${i}-${l}--${o}-${a}`;ST("source",c,E,e,o,a),ST("target",c,d,e,i,l),t.set(r.id,r)}}function SA(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:SA(n,t):!1}function RT(e,t,n){var o;let r=e;do{if((o=r==null?void 0:r.matches)!=null&&o.call(r,t))return!0;if(r===n)return!1;r=r==null?void 0:r.parentElement}while(r);return!1}function kw(e,t,n,r){const o=new Map;for(const[i,a]of e)if((a.selected||a.id===r)&&(!a.parentId||!SA(a,e))&&(a.draggable||t&&typeof a.draggable>"u")){const l=e.get(i);l&&o.set(i,{id:i,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return o}function ml({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){var a,l,c;const o=[];for(const[d,E]of t){const u=(a=n.get(d))==null?void 0:a.internals.userNode;u&&o.push({...u,position:E.position,dragging:r})}if(!e)return[o[0],o];const i=(l=n.get(e))==null?void 0:l.internals.userNode;return[i?{...i,position:((c=t.get(e))==null?void 0:c.position)||i.position,dragging:r}:o[0],o]}function jw({dragItems:e,snapGrid:t,x:n,y:r}){const o=e.values().next().value;if(!o)return null;const i={x:n-o.distance.x,y:r-o.distance.y},a=zo(i,t);return{x:a.x-i.x,y:a.y-i.y}}function Gw({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:o}){let i={x:null,y:null},a=0,l=new Map,c=!1,d={x:0,y:0},E=null,u=!1,T=null,p=!1,h=!1,A=null;function S({noDragClassName:m,handleSelector:I,domNode:O,isSelectable:N,nodeId:x,nodeClickDistance:g=0}){T=qe(O);function C({x:B,y:b}){const{nodeLookup:L,nodeExtent:D,snapGrid:M,snapToGrid:U,nodeOrigin:P,onNodeDrag:_,onSelectionDrag:F,onError:k,updateNodePositions:H}=t();i={x:B,y:b};let Q=!1;const q=l.size>1,$=q&&D?Vc(Xo(l)):null,Z=q&&U?jw({dragItems:l,snapGrid:M,x:B,y:b}):null;for(const[Y,G]of l){if(!L.has(Y))continue;let J={x:B-G.distance.x,y:b-G.distance.y};U&&(J=Z?{x:Math.round(J.x+Z.x),y:Math.round(J.y+Z.y)}:zo(J,M));let te=null;if(q&&D&&!G.extent&&$){const{positionAbsolute:V}=G.internals,le=V.x-$.x+D[0][0],Te=V.x+G.measured.width-$.x2+D[1][0],de=V.y-$.y+D[0][1],ne=V.y+G.measured.height-$.y2+D[1][1];te=[[le,de],[Te,ne]]}const{position:re,positionAbsolute:oe}=eA({nodeId:Y,nextPosition:J,nodeLookup:L,nodeExtent:te||D,nodeOrigin:P,onError:k});Q=Q||G.position.x!==re.x||G.position.y!==re.y,G.position=re,G.internals.positionAbsolute=oe}if(h=h||Q,!!Q&&(H(l,!0),A&&(r||_||!x&&F))){const[Y,G]=ml({nodeId:x,dragItems:l,nodeLookup:L});r==null||r(A,l,Y,G),_==null||_(A,Y,G),x||F==null||F(A,G)}}async function y(){if(!E)return;const{transform:B,panBy:b,autoPanSpeed:L,autoPanOnNodeDrag:D}=t();if(!D){c=!1,cancelAnimationFrame(a);return}const[M,U]=nA(d,E,L);(M!==0||U!==0)&&(i.x=(i.x??0)-M/B[2],i.y=(i.y??0)-U/B[2],await b({x:M,y:U})&&C(i)),a=requestAnimationFrame(y)}function w(B){var q;const{nodeLookup:b,multiSelectionActive:L,nodesDraggable:D,transform:M,snapGrid:U,snapToGrid:P,selectNodesOnDrag:_,onNodeDragStart:F,onSelectionDragStart:k,unselectNodesAndEdges:H}=t();u=!0,(!_||!N)&&!L&&x&&((q=b.get(x))!=null&&q.selected||H()),N&&_&&x&&(e==null||e(x));const Q=uo(B.sourceEvent,{transform:M,snapGrid:U,snapToGrid:P,containerBounds:E});if(i=Q,l=kw(b,D,Q,x),l.size>0&&(n||F||!x&&k)){const[$,Z]=ml({nodeId:x,dragItems:l,nodeLookup:b});n==null||n(B.sourceEvent,l,$,Z),F==null||F(B.sourceEvent,$,Z),x||k==null||k(B.sourceEvent,Z)}}const v=vh().clickDistance(g).on("start",B=>{const{domNode:b,nodeDragThreshold:L,transform:D,snapGrid:M,snapToGrid:U}=t();E=(b==null?void 0:b.getBoundingClientRect())||null,p=!1,h=!1,A=B.sourceEvent,L===0&&w(B),i=uo(B.sourceEvent,{transform:D,snapGrid:M,snapToGrid:U,containerBounds:E}),d=ft(B.sourceEvent,E)}).on("drag",B=>{const{autoPanOnNodeDrag:b,transform:L,snapGrid:D,snapToGrid:M,nodeDragThreshold:U,nodeLookup:P}=t(),_=uo(B.sourceEvent,{transform:L,snapGrid:D,snapToGrid:M,containerBounds:E});if(A=B.sourceEvent,(B.sourceEvent.type==="touchmove"&&B.sourceEvent.touches.length>1||x&&!P.has(x))&&(p=!0),!p){if(!c&&b&&u&&(c=!0,y()),!u){const F=ft(B.sourceEvent,E),k=F.x-d.x,H=F.y-d.y;Math.sqrt(k*k+H*H)>U&&w(B)}(i.x!==_.xSnapped||i.y!==_.ySnapped)&&l&&u&&(d=ft(B.sourceEvent,E),C(_))}}).on("end",B=>{if(!(!u||p)&&(c=!1,u=!1,cancelAnimationFrame(a),l.size>0)){const{nodeLookup:b,updateNodePositions:L,onNodeDragStop:D,onSelectionDragStop:M}=t();if(h&&(L(l,!1),h=!1),o||D||!x&&M){const[U,P]=ml({nodeId:x,dragItems:l,nodeLookup:b,dragging:!1});o==null||o(B.sourceEvent,l,U,P),D==null||D(B.sourceEvent,U,P),x||M==null||M(B.sourceEvent,P)}}}).filter(B=>{const b=B.target;return!B.button&&(!m||!RT(b,`.${m}`,O))&&(!I||RT(b,I,O))});T.call(v)}function R(){T==null||T.on(".drag",null)}return{update:S,destroy:R}}function Hw(e,t,n){const r=[],o={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const i of t.values())Do(o,vr(i))>0&&r.push(i);return r}const Yw=250;function Ww(e,t,n,r){var l,c;let o=[],i=1/0;const a=Hw(e,n,t+Yw);for(const d of a){const E=[...((l=d.internals.handleBounds)==null?void 0:l.source)??[],...((c=d.internals.handleBounds)==null?void 0:c.target)??[]];for(const u of E){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:T,y:p}=Wn(d,u,u.position,!0),h=Math.sqrt(Math.pow(T-e.x,2)+Math.pow(p-e.y,2));h>t||(h<i?(o=[{...u,x:T,y:p}],i=h):h===i&&o.push({...u,x:T,y:p}))}}if(!o.length)return null;if(o.length>1){const d=r.type==="source"?"target":"source";return o.find(E=>E.type===d)??o[0]}return o[0]}function RA(e,t,n,r,o,i=!1){var d,E,u;const a=r.get(e);if(!a)return null;const l=o==="strict"?(d=a.internals.handleBounds)==null?void 0:d[t]:[...((E=a.internals.handleBounds)==null?void 0:E.source)??[],...((u=a.internals.handleBounds)==null?void 0:u.target)??[]],c=(n?l==null?void 0:l.find(T=>T.id===n):l==null?void 0:l[0])??null;return c&&i?{...c,...Wn(a,c,c.position,!0)}:c}function hA(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function $w(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const AA=()=>!0;function Vw(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:o,edgeUpdaterType:i,isTarget:a,domNode:l,nodeLookup:c,lib:d,autoPanOnConnect:E,flowId:u,panBy:T,cancelConnection:p,onConnectStart:h,onConnect:A,onConnectEnd:S,isValidConnection:R=AA,onReconnectEnd:m,updateConnection:I,getTransform:O,getFromHandle:N,autoPanSpeed:x,dragThreshold:g=1,handleDomNode:C}){const y=iA(e.target);let w=0,v;const{x:B,y:b}=ft(e),L=hA(i,C),D=l==null?void 0:l.getBoundingClientRect();let M=!1;if(!D||!L)return;const U=RA(o,L,r,c,t);if(!U)return;let P=ft(e,D),_=!1,F=null,k=!1,H=null;function Q(){if(!E||!D)return;const[re,oe]=nA(P,D,x);T({x:re,y:oe}),w=requestAnimationFrame(Q)}const q={...U,nodeId:o,type:L,position:U.position},$=c.get(o);let Y={inProgress:!0,isValid:null,from:Wn($,q,ae.Left,!0),fromHandle:q,fromPosition:q.position,fromNode:$,to:P,toHandle:null,toPosition:sT[q.position],toNode:null,pointer:P};function G(){M=!0,I(Y),h==null||h(e,{nodeId:o,handleId:r,handleType:L})}g===0&&G();function J(re){if(!M){const{x:ne,y:Re}=ft(re),Oe=ne-B,Fe=Re-b;if(!(Oe*Oe+Fe*Fe>g*g))return;G()}if(!N()||!q){te(re);return}const oe=O();P=ft(re,D),v=Ww(Ko(P,oe,!1,[1,1]),n,c,q),_||(Q(),_=!0);const V=IA(re,{handle:v,connectionMode:t,fromNodeId:o,fromHandleId:r,fromType:a?"target":"source",isValidConnection:R,doc:y,lib:d,flowId:u,nodeLookup:c});H=V.handleDomNode,F=V.connection,k=$w(!!v,V.isValid);const le=c.get(o),Te=le?Wn(le,q,ae.Left,!0):Y.from,de={...Y,from:Te,isValid:k,to:V.toHandle&&k?vi({x:V.toHandle.x,y:V.toHandle.y},oe):P,toHandle:V.toHandle,toPosition:k&&V.toHandle?V.toHandle.position:sT[q.position],toNode:V.toHandle?c.get(V.toHandle.nodeId):null,pointer:P};I(de),Y=de}function te(re){if(!("touches"in re&&re.touches.length>0)){if(M){(v||H)&&F&&k&&(A==null||A(F));const{inProgress:oe,...V}=Y,le={...V,toPosition:Y.toHandle?Y.toPosition:null};S==null||S(re,le),i&&(m==null||m(re,le))}p(),cancelAnimationFrame(w),_=!1,k=!1,F=null,H=null,y.removeEventListener("mousemove",J),y.removeEventListener("mouseup",te),y.removeEventListener("touchmove",J),y.removeEventListener("touchend",te)}}y.addEventListener("mousemove",J),y.addEventListener("mouseup",te),y.addEventListener("touchmove",J),y.addEventListener("touchend",te)}function IA(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:o,fromType:i,doc:a,lib:l,flowId:c,isValidConnection:d=AA,nodeLookup:E}){const u=i==="target",T=t?a.querySelector(`.${l}-flow__handle[data-id="${c}-${t==null?void 0:t.nodeId}-${t==null?void 0:t.id}-${t==null?void 0:t.type}"]`):null,{x:p,y:h}=ft(e),A=a.elementFromPoint(p,h),S=A!=null&&A.classList.contains(`${l}-flow__handle`)?A:T,R={handleDomNode:S,isValid:!1,connection:null,toHandle:null};if(S){const m=hA(void 0,S),I=S.getAttribute("data-nodeid"),O=S.getAttribute("data-handleid"),N=S.classList.contains("connectable"),x=S.classList.contains("connectableend");if(!I||!m)return R;const g={source:u?I:r,sourceHandle:u?O:o,target:u?r:I,targetHandle:u?o:O};R.connection=g;const y=N&&x&&(n===br.Strict?u&&m==="source"||!u&&m==="target":I!==r||O!==o);R.isValid=y&&d(g),R.toHandle=RA(I,m,O,E,n,!0)}return R}const qc={onPointerDown:Vw,isValid:IA};function Xw({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const o=qe(e);function i({translateExtent:l,width:c,height:d,zoomStep:E=1,pannable:u=!0,zoomable:T=!0,inversePan:p=!1}){const h=I=>{if(I.sourceEvent.type!=="wheel"||!t)return;const O=n(),N=I.sourceEvent.ctrlKey&&Mo()?10:1,x=-I.sourceEvent.deltaY*(I.sourceEvent.deltaMode===1?.05:I.sourceEvent.deltaMode?1:.002)*E,g=O[2]*Math.pow(2,x*N);t.scaleTo(g)};let A=[0,0];const S=I=>{(I.sourceEvent.type==="mousedown"||I.sourceEvent.type==="touchstart")&&(A=[I.sourceEvent.clientX??I.sourceEvent.touches[0].clientX,I.sourceEvent.clientY??I.sourceEvent.touches[0].clientY])},R=I=>{const O=n();if(I.sourceEvent.type!=="mousemove"&&I.sourceEvent.type!=="touchmove"||!t)return;const N=[I.sourceEvent.clientX??I.sourceEvent.touches[0].clientX,I.sourceEvent.clientY??I.sourceEvent.touches[0].clientY],x=[N[0]-A[0],N[1]-A[1]];A=N;const g=r()*Math.max(O[2],Math.log(O[2]))*(p?-1:1),C={x:O[0]-x[0]*g,y:O[1]-x[1]*g},y=[[0,0],[c,d]];t.setViewportConstrained({x:C.x,y:C.y,zoom:O[2]},y,l)},m=zh().on("start",S).on("zoom",u?R:null).on("zoom.wheel",T?h:null);o.call(m,{})}function a(){o.on("zoom",null)}return{update:i,destroy:a,pointer:dt}}const Oa=e=>({x:e.x,y:e.y,zoom:e.k}),Ol=({x:e,y:t,zoom:n})=>Aa.translate(e,t).scale(n),fr=(e,t)=>e.target.closest(`.${t}`),mA=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),zw=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Nl=(e,t=0,n=zw,r=()=>{})=>{const o=typeof t=="number"&&t>0;return o||r(),o?e.transition().duration(t).ease(n).on("end",r):e},OA=e=>{const t=e.ctrlKey&&Mo()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function Kw({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:o,panOnScrollSpeed:i,zoomOnPinch:a,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:d}){return E=>{if(fr(E,t))return E.ctrlKey&&E.preventDefault(),!1;E.preventDefault(),E.stopImmediatePropagation();const u=n.property("__zoom").k||1;if(E.ctrlKey&&a){const S=dt(E),R=OA(E),m=u*Math.pow(2,R);r.scaleTo(n,m,S,E);return}const T=E.deltaMode===1?20:1;let p=o===Un.Vertical?0:E.deltaX*T,h=o===Un.Horizontal?0:E.deltaY*T;!Mo()&&E.shiftKey&&o!==Un.Vertical&&(p=E.deltaY*T,h=0),r.translateBy(n,-(p/u)*i,-(h/u)*i,{internal:!0});const A=Oa(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c==null||c(E,A),e.panScrollTimeout=setTimeout(()=>{d==null||d(E,A),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l==null||l(E,A))}}function qw({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,o){const i=r.type==="wheel",a=!t&&i&&!r.ctrlKey,l=fr(r,e);if(r.ctrlKey&&i&&l&&r.preventDefault(),a||l)return null;r.preventDefault(),n.call(this,r,o)}}function Jw({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{var i,a,l;if((i=r.sourceEvent)!=null&&i.internal)return;const o=Oa(r.transform);e.mouseButton=((a=r.sourceEvent)==null?void 0:a.button)||0,e.isZoomingOrPanning=!0,e.prevViewport=o,((l=r.sourceEvent)==null?void 0:l.type)==="mousedown"&&t(!0),n&&(n==null||n(r.sourceEvent,o))}}function Qw({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:o}){return i=>{var a,l;e.usedRightMouseButton=!!(n&&mA(t,e.mouseButton??0)),(a=i.sourceEvent)!=null&&a.sync||r([i.transform.x,i.transform.y,i.transform.k]),o&&!((l=i.sourceEvent)!=null&&l.internal)&&(o==null||o(i.sourceEvent,Oa(i.transform)))}}function Zw({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:o,onPaneContextMenu:i}){return a=>{var l;if(!((l=a.sourceEvent)!=null&&l.internal)&&(e.isZoomingOrPanning=!1,i&&mA(t,e.mouseButton??0)&&!e.usedRightMouseButton&&a.sourceEvent&&i(a.sourceEvent),e.usedRightMouseButton=!1,r(!1),o)){const c=Oa(a.transform);e.prevViewport=c,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{o==null||o(a.sourceEvent,c)},n?150:0)}}}function eU({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:o,zoomOnDoubleClick:i,userSelectionActive:a,noWheelClassName:l,noPanClassName:c,lib:d,connectionInProgress:E}){return u=>{var S;const T=e||t,p=n&&u.ctrlKey,h=u.type==="wheel";if(u.button===1&&u.type==="mousedown"&&(fr(u,`${d}-flow__node`)||fr(u,`${d}-flow__edge`)))return!0;if(!r&&!T&&!o&&!i&&!n||a||E&&!h||fr(u,l)&&h||fr(u,c)&&(!h||o&&h&&!e)||!n&&u.ctrlKey&&h)return!1;if(!n&&u.type==="touchstart"&&((S=u.touches)==null?void 0:S.length)>1)return u.preventDefault(),!1;if(!T&&!o&&!p&&h||!r&&(u.type==="mousedown"||u.type==="touchstart")||Array.isArray(r)&&!r.includes(u.button)&&u.type==="mousedown")return!1;const A=Array.isArray(r)&&r.includes(u.button)||!u.button||u.button<=1;return(!u.ctrlKey||h)&&A}}function tU({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:o,onPanZoom:i,onPanZoomStart:a,onPanZoomEnd:l,onDraggingChange:c}){const d={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},E=e.getBoundingClientRect(),u=zh().scaleExtent([t,n]).translateExtent(r),T=qe(e).call(u);m({x:o.x,y:o.y,zoom:Mr(o.zoom,t,n)},[[0,0],[E.width,E.height]],r);const p=T.on("wheel.zoom"),h=T.on("dblclick.zoom");u.wheelDelta(OA);function A(v,B){return T?new Promise(b=>{u==null||u.interpolate((B==null?void 0:B.interpolate)==="linear"?Eo:ti).transform(Nl(T,B==null?void 0:B.duration,B==null?void 0:B.ease,()=>b(!0)),v)}):Promise.resolve(!1)}function S({noWheelClassName:v,noPanClassName:B,onPaneContextMenu:b,userSelectionActive:L,panOnScroll:D,panOnDrag:M,panOnScrollMode:U,panOnScrollSpeed:P,preventScrolling:_,zoomOnPinch:F,zoomOnScroll:k,zoomOnDoubleClick:H,zoomActivationKeyPressed:Q,lib:q,onTransformChange:$,connectionInProgress:Z,paneClickDistance:Y,selectionOnDrag:G}){L&&!d.isZoomingOrPanning&&R();const J=D&&!Q&&!L;u.clickDistance(G?1/0:!Tt(Y)||Y<0?0:Y);const te=J?Kw({zoomPanValues:d,noWheelClassName:v,d3Selection:T,d3Zoom:u,panOnScrollMode:U,panOnScrollSpeed:P,zoomOnPinch:F,onPanZoomStart:a,onPanZoom:i,onPanZoomEnd:l}):qw({noWheelClassName:v,preventScrolling:_,d3ZoomHandler:p});if(T.on("wheel.zoom",te,{passive:!1}),!L){const oe=Jw({zoomPanValues:d,onDraggingChange:c,onPanZoomStart:a});u.on("start",oe);const V=Qw({zoomPanValues:d,panOnDrag:M,onPaneContextMenu:!!b,onPanZoom:i,onTransformChange:$});u.on("zoom",V);const le=Zw({zoomPanValues:d,panOnDrag:M,panOnScroll:D,onPaneContextMenu:b,onPanZoomEnd:l,onDraggingChange:c});u.on("end",le)}const re=eU({zoomActivationKeyPressed:Q,panOnDrag:M,zoomOnScroll:k,panOnScroll:D,zoomOnDoubleClick:H,zoomOnPinch:F,userSelectionActive:L,noPanClassName:B,noWheelClassName:v,lib:q,connectionInProgress:Z});u.filter(re),H?T.on("dblclick.zoom",h):T.on("dblclick.zoom",null)}function R(){u.on("zoom",null)}async function m(v,B,b){const L=Ol(v),D=u==null?void 0:u.constrain()(L,B,b);return D&&await A(D),new Promise(M=>M(D))}async function I(v,B){const b=Ol(v);return await A(b,B),new Promise(L=>L(b))}function O(v){if(T){const B=Ol(v),b=T.property("__zoom");(b.k!==v.zoom||b.x!==v.x||b.y!==v.y)&&(u==null||u.transform(T,B,null,{sync:!0}))}}function N(){const v=T?Xh(T.node()):{x:0,y:0,k:1};return{x:v.x,y:v.y,zoom:v.k}}function x(v,B){return T?new Promise(b=>{u==null||u.interpolate((B==null?void 0:B.interpolate)==="linear"?Eo:ti).scaleTo(Nl(T,B==null?void 0:B.duration,B==null?void 0:B.ease,()=>b(!0)),v)}):Promise.resolve(!1)}function g(v,B){return T?new Promise(b=>{u==null||u.interpolate((B==null?void 0:B.interpolate)==="linear"?Eo:ti).scaleBy(Nl(T,B==null?void 0:B.duration,B==null?void 0:B.ease,()=>b(!0)),v)}):Promise.resolve(!1)}function C(v){u==null||u.scaleExtent(v)}function y(v){u==null||u.translateExtent(v)}function w(v){const B=!Tt(v)||v<0?0:v;u==null||u.clickDistance(B)}return{update:S,destroy:R,setViewport:I,setViewportConstrained:m,getViewport:N,scaleTo:x,scaleBy:g,setScaleExtent:C,setTranslateExtent:y,syncViewport:O,setClickDistance:w}}var wr;(function(e){e.Line="line",e.Handle="handle"})(wr||(wr={}));function nU({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:o,affectsY:i}){const a=e-t,l=n-r,c=[a>0?1:a<0?-1:0,l>0?1:l<0?-1:0];return a&&o&&(c[0]=c[0]*-1),l&&i&&(c[1]=c[1]*-1),c}function hT(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),o=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:o}}function en(e,t){return Math.max(0,t-e)}function tn(e,t){return Math.max(0,e-t)}function ks(e,t,n){return Math.max(0,t-e,e-n)}function AT(e,t){return e?!t:t}function rU(e,t,n,r,o,i,a,l){let{affectsX:c,affectsY:d}=t;const{isHorizontal:E,isVertical:u}=t,T=E&&u,{xSnapped:p,ySnapped:h}=n,{minWidth:A,maxWidth:S,minHeight:R,maxHeight:m}=r,{x:I,y:O,width:N,height:x,aspectRatio:g}=e;let C=Math.floor(E?p-e.pointerX:0),y=Math.floor(u?h-e.pointerY:0);const w=N+(c?-C:C),v=x+(d?-y:y),B=-i[0]*N,b=-i[1]*x;let L=ks(w,A,S),D=ks(v,R,m);if(a){let P=0,_=0;c&&C<0?P=en(I+C+B,a[0][0]):!c&&C>0&&(P=tn(I+w+B,a[1][0])),d&&y<0?_=en(O+y+b,a[0][1]):!d&&y>0&&(_=tn(O+v+b,a[1][1])),L=Math.max(L,P),D=Math.max(D,_)}if(l){let P=0,_=0;c&&C>0?P=tn(I+C,l[0][0]):!c&&C<0&&(P=en(I+w,l[1][0])),d&&y>0?_=tn(O+y,l[0][1]):!d&&y<0&&(_=en(O+v,l[1][1])),L=Math.max(L,P),D=Math.max(D,_)}if(o){if(E){const P=ks(w/g,R,m)*g;if(L=Math.max(L,P),a){let _=0;!c&&!d||c&&!d&&T?_=tn(O+b+w/g,a[1][1])*g:_=en(O+b+(c?C:-C)/g,a[0][1])*g,L=Math.max(L,_)}if(l){let _=0;!c&&!d||c&&!d&&T?_=en(O+w/g,l[1][1])*g:_=tn(O+(c?C:-C)/g,l[0][1])*g,L=Math.max(L,_)}}if(u){const P=ks(v*g,A,S)/g;if(D=Math.max(D,P),a){let _=0;!c&&!d||d&&!c&&T?_=tn(I+v*g+B,a[1][0])/g:_=en(I+(d?y:-y)*g+B,a[0][0])/g,D=Math.max(D,_)}if(l){let _=0;!c&&!d||d&&!c&&T?_=en(I+v*g,l[1][0])/g:_=tn(I+(d?y:-y)*g,l[0][0])/g,D=Math.max(D,_)}}}y=y+(y<0?D:-D),C=C+(C<0?L:-L),o&&(T?w>v*g?y=(AT(c,d)?-C:C)/g:C=(AT(c,d)?-y:y)*g:E?(y=C/g,d=c):(C=y*g,c=d));const M=c?I+C:I,U=d?O+y:O;return{width:N+(c?-C:C),height:x+(d?-y:y),x:i[0]*C*(c?-1:1)+M,y:i[1]*y*(d?-1:1)+U}}const NA={width:0,height:0,x:0,y:0},oU={...NA,pointerX:0,pointerY:0,aspectRatio:1};function sU(e){return[[0,0],[e.measured.width,e.measured.height]]}function iU(e,t,n){const r=t.position.x+e.position.x,o=t.position.y+e.position.y,i=e.measured.width??0,a=e.measured.height??0,l=n[0]*i,c=n[1]*a;return[[r-l,o-c],[r+i-l,o+a-c]]}function aU({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:o}){const i=qe(e);let a={controlDirection:hT("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:d,boundaries:E,keepAspectRatio:u,resizeDirection:T,onResizeStart:p,onResize:h,onResizeEnd:A,shouldResize:S}){let R={...NA},m={...oU};a={boundaries:E,resizeDirection:T,keepAspectRatio:u,controlDirection:hT(d)};let I,O=null,N=[],x,g,C,y=!1;const w=vh().on("start",v=>{const{nodeLookup:B,transform:b,snapGrid:L,snapToGrid:D,nodeOrigin:M,paneDomNode:U}=n();if(I=B.get(t),!I)return;O=(U==null?void 0:U.getBoundingClientRect())??null;const{xSnapped:P,ySnapped:_}=uo(v.sourceEvent,{transform:b,snapGrid:L,snapToGrid:D,containerBounds:O});R={width:I.measured.width??0,height:I.measured.height??0,x:I.position.x??0,y:I.position.y??0},m={...R,pointerX:P,pointerY:_,aspectRatio:R.width/R.height},x=void 0,I.parentId&&(I.extent==="parent"||I.expandParent)&&(x=B.get(I.parentId),g=x&&I.extent==="parent"?sU(x):void 0),N=[],C=void 0;for(const[F,k]of B)if(k.parentId===t&&(N.push({id:F,position:{...k.position},extent:k.extent}),k.extent==="parent"||k.expandParent)){const H=iU(k,I,k.origin??M);C?C=[[Math.min(H[0][0],C[0][0]),Math.min(H[0][1],C[0][1])],[Math.max(H[1][0],C[1][0]),Math.max(H[1][1],C[1][1])]]:C=H}p==null||p(v,{...R})}).on("drag",v=>{const{transform:B,snapGrid:b,snapToGrid:L,nodeOrigin:D}=n(),M=uo(v.sourceEvent,{transform:B,snapGrid:b,snapToGrid:L,containerBounds:O}),U=[];if(!I)return;const{x:P,y:_,width:F,height:k}=R,H={},Q=I.origin??D,{width:q,height:$,x:Z,y:Y}=rU(m,a.controlDirection,M,a.boundaries,a.keepAspectRatio,Q,g,C),G=q!==F,J=$!==k,te=Z!==P&&G,re=Y!==_&&J;if(!te&&!re&&!G&&!J)return;if((te||re||Q[0]===1||Q[1]===1)&&(H.x=te?Z:R.x,H.y=re?Y:R.y,R.x=H.x,R.y=H.y,N.length>0)){const Te=Z-P,de=Y-_;for(const ne of N)ne.position={x:ne.position.x-Te+Q[0]*(q-F),y:ne.position.y-de+Q[1]*($-k)},U.push(ne)}if((G||J)&&(H.width=G&&(!a.resizeDirection||a.resizeDirection==="horizontal")?q:R.width,H.height=J&&(!a.resizeDirection||a.resizeDirection==="vertical")?$:R.height,R.width=H.width,R.height=H.height),x&&I.expandParent){const Te=Q[0]*(H.width??0);H.x&&H.x<Te&&(R.x=Te,m.x=m.x-(H.x-Te));const de=Q[1]*(H.height??0);H.y&&H.y<de&&(R.y=de,m.y=m.y-(H.y-de))}const oe=nU({width:R.width,prevWidth:F,height:R.height,prevHeight:k,affectsX:a.controlDirection.affectsX,affectsY:a.controlDirection.affectsY}),V={...R,direction:oe};(S==null?void 0:S(v,V))!==!1&&(y=!0,h==null||h(v,V),r(H,U))}).on("end",v=>{y&&(A==null||A(v,{...R}),o==null||o({...R}),y=!1)});i.call(w)}function c(){i.on(".drag",null)}return{update:l,destroy:c}}var gl={exports:{}},xl={},yl={exports:{}},Cl={};/**
|
|
746
|
-
* @license React
|
|
747
|
-
* use-sync-external-store-shim.production.js
|
|
748
|
-
*
|
|
749
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
750
|
-
*
|
|
751
|
-
* This source code is licensed under the MIT license found in the
|
|
752
|
-
* LICENSE file in the root directory of this source tree.
|
|
753
|
-
*/var IT;function lU(){if(IT)return Cl;IT=1;var e=Yi();function t(u,T){return u===T&&(u!==0||1/u===1/T)||u!==u&&T!==T}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,i=e.useLayoutEffect,a=e.useDebugValue;function l(u,T){var p=T(),h=r({inst:{value:p,getSnapshot:T}}),A=h[0].inst,S=h[1];return i(function(){A.value=p,A.getSnapshot=T,c(A)&&S({inst:A})},[u,p,T]),o(function(){return c(A)&&S({inst:A}),u(function(){c(A)&&S({inst:A})})},[u]),a(p),p}function c(u){var T=u.getSnapshot;u=u.value;try{var p=T();return!n(u,p)}catch{return!0}}function d(u,T){return T()}var E=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:l;return Cl.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:E,Cl}var mT;function cU(){return mT||(mT=1,yl.exports=lU()),yl.exports}/**
|
|
754
|
-
* @license React
|
|
755
|
-
* use-sync-external-store-shim/with-selector.production.js
|
|
756
|
-
*
|
|
757
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
758
|
-
*
|
|
759
|
-
* This source code is licensed under the MIT license found in the
|
|
760
|
-
* LICENSE file in the root directory of this source tree.
|
|
761
|
-
*/var OT;function dU(){if(OT)return xl;OT=1;var e=Yi(),t=cU();function n(d,E){return d===E&&(d!==0||1/d===1/E)||d!==d&&E!==E}var r=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,i=e.useRef,a=e.useEffect,l=e.useMemo,c=e.useDebugValue;return xl.useSyncExternalStoreWithSelector=function(d,E,u,T,p){var h=i(null);if(h.current===null){var A={hasValue:!1,value:null};h.current=A}else A=h.current;h=l(function(){function R(x){if(!m){if(m=!0,I=x,x=T(x),p!==void 0&&A.hasValue){var g=A.value;if(p(g,x))return O=g}return O=x}if(g=O,r(I,x))return g;var C=T(x);return p!==void 0&&p(g,C)?(I=x,g):(I=x,O=C)}var m=!1,I,O,N=u===void 0?null:u;return[function(){return R(E())},N===null?void 0:function(){return R(N())}]},[E,u,T,p]);var S=o(d,h[0],h[1]);return a(function(){A.hasValue=!0,A.value=S},[S]),c(S),S},xl}var NT;function EU(){return NT||(NT=1,gl.exports=dU()),gl.exports}var uU=EU();const TU=Wi(uU),fU={},gT=e=>{let t;const n=new Set,r=(E,u)=>{const T=typeof E=="function"?E(t):E;if(!Object.is(T,t)){const p=t;t=u??(typeof T!="object"||T===null)?T:Object.assign({},t,T),n.forEach(h=>h(t,p))}},o=()=>t,c={setState:r,getState:o,getInitialState:()=>d,subscribe:E=>(n.add(E),()=>n.delete(E)),destroy:()=>{(fU?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},d=t=e(r,o,c);return c},pU=e=>e?gT(e):gT,{useDebugValue:SU}=_e,{useSyncExternalStoreWithSelector:RU}=TU,hU=e=>e;function gA(e,t=hU,n){const r=RU(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return SU(r),r}const xT=(e,t)=>{const n=pU(e),r=(o,i=t)=>gA(n,o,i);return Object.assign(r,n),r},AU=(e,t)=>e?xT(e,t):xT;function ye(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}const Na=f.createContext(null),IU=Na.Provider,xA=bt.error001();function Ae(e,t){const n=f.useContext(Na);if(n===null)throw new Error(xA);return gA(n,e,t)}function Le(){const e=f.useContext(Na);if(e===null)throw new Error(xA);return f.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const yT={display:"none"},mU={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},yA="react-flow__node-desc",CA="react-flow__edge-desc",OU="react-flow__aria-live",NU=e=>e.ariaLiveMessage,gU=e=>e.ariaLabelConfig;function xU({rfId:e}){const t=Ae(NU);return s.jsx("div",{id:`${OU}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:mU,children:t})}function yU({rfId:e,disableKeyboardA11y:t}){const n=Ae(gU);return s.jsxs(s.Fragment,{children:[s.jsx("div",{id:`${yA}-${e}`,style:yT,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),s.jsx("div",{id:`${CA}-${e}`,style:yT,children:n["edge.a11yDescription.default"]}),!t&&s.jsx(xU,{rfId:e})]})}const Ur=f.forwardRef(({position:e="top-left",children:t,className:n,style:r,...o},i)=>{const a=`${e}`.split("-");return s.jsx("div",{className:De(["react-flow__panel",n,...a]),style:r,ref:i,...o,children:t})});Ur.displayName="Panel";function CU({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:s.jsx(Ur,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:s.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const LU=e=>{const t=[],n=[];for(const[,r]of e.nodeLookup)r.selected&&t.push(r.internals.userNode);for(const[,r]of e.edgeLookup)r.selected&&n.push(r);return{selectedNodes:t,selectedEdges:n}},js=e=>e.id;function _U(e,t){return ye(e.selectedNodes.map(js),t.selectedNodes.map(js))&&ye(e.selectedEdges.map(js),t.selectedEdges.map(js))}function bU({onSelectionChange:e}){const t=Le(),{selectedNodes:n,selectedEdges:r}=Ae(LU,_U);return f.useEffect(()=>{const o={nodes:n,edges:r};e==null||e(o),t.getState().onSelectionChangeHandlers.forEach(i=>i(o))},[n,r,e]),null}const DU=e=>!!e.onSelectionChangeHandlers;function MU({onSelectionChange:e}){const t=Ae(DU);return e||t?s.jsx(bU,{onSelectionChange:e}):null}const LA=[0,0],vU={x:0,y:0,zoom:1},PU=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode"],CT=[...PU,"rfId"],wU=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),LT={translateExtent:_o,nodeOrigin:LA,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function UU(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:o,setTranslateExtent:i,setNodeExtent:a,reset:l,setDefaultNodesAndEdges:c}=Ae(wU,ye),d=Le();f.useEffect(()=>(c(e.defaultNodes,e.defaultEdges),()=>{E.current=LT,l()}),[]);const E=f.useRef(LT);return f.useEffect(()=>{for(const u of CT){const T=e[u],p=E.current[u];T!==p&&(typeof e[u]>"u"||(u==="nodes"?t(T):u==="edges"?n(T):u==="minZoom"?r(T):u==="maxZoom"?o(T):u==="translateExtent"?i(T):u==="nodeExtent"?a(T):u==="ariaLabelConfig"?d.setState({ariaLabelConfig:Aw(T)}):u==="fitView"?d.setState({fitViewQueued:T}):u==="fitViewOptions"?d.setState({fitViewOptions:T}):d.setState({[u]:T})))}E.current=e},CT.map(u=>e[u])),null}function _T(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function BU(e){var r;const[t,n]=f.useState(e==="system"?null:e);return f.useEffect(()=>{if(e!=="system"){n(e);return}const o=_T(),i=()=>n(o!=null&&o.matches?"dark":"light");return i(),o==null||o.addEventListener("change",i),()=>{o==null||o.removeEventListener("change",i)}},[e]),t!==null?t:(r=_T())!=null&&r.matches?"dark":"light"}const bT=typeof document<"u"?document:null;function vo(e=null,t={target:bT,actInsideInputWithModifier:!0}){const[n,r]=f.useState(!1),o=f.useRef(!1),i=f.useRef(new Set([])),[a,l]=f.useMemo(()=>{if(e!==null){const d=(Array.isArray(e)?e:[e]).filter(u=>typeof u=="string").map(u=>u.replace("+",`
|
|
762
|
-
`).replace(`
|
|
763
|
-
|
|
764
|
-
`,`
|
|
765
|
-
+`).split(`
|
|
766
|
-
`)),E=d.reduce((u,T)=>u.concat(...T),[]);return[d,E]}return[[],[]]},[e]);return f.useEffect(()=>{const c=(t==null?void 0:t.target)??bT,d=(t==null?void 0:t.actInsideInputWithModifier)??!0;if(e!==null){const E=p=>{var S,R;if(o.current=p.ctrlKey||p.metaKey||p.shiftKey||p.altKey,(!o.current||o.current&&!d)&&aA(p))return!1;const A=MT(p.code,l);if(i.current.add(p[A]),DT(a,i.current,!1)){const m=((R=(S=p.composedPath)==null?void 0:S.call(p))==null?void 0:R[0])||p.target,I=(m==null?void 0:m.nodeName)==="BUTTON"||(m==null?void 0:m.nodeName)==="A";t.preventDefault!==!1&&(o.current||!I)&&p.preventDefault(),r(!0)}},u=p=>{const h=MT(p.code,l);DT(a,i.current,!0)?(r(!1),i.current.clear()):i.current.delete(p[h]),p.key==="Meta"&&i.current.clear(),o.current=!1},T=()=>{i.current.clear(),r(!1)};return c==null||c.addEventListener("keydown",E),c==null||c.addEventListener("keyup",u),window.addEventListener("blur",T),window.addEventListener("contextmenu",T),()=>{c==null||c.removeEventListener("keydown",E),c==null||c.removeEventListener("keyup",u),window.removeEventListener("blur",T),window.removeEventListener("contextmenu",T)}}},[e,r]),n}function DT(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(o=>t.has(o)))}function MT(e,t){return t.includes(e)?"code":"key"}const FU=()=>{const e=Le();return f.useMemo(()=>({zoomIn:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1.2,{duration:t==null?void 0:t.duration}):Promise.resolve(!1)},zoomOut:t=>{const{panZoom:n}=e.getState();return n?n.scaleBy(1/1.2,{duration:t==null?void 0:t.duration}):Promise.resolve(!1)},zoomTo:(t,n)=>{const{panZoom:r}=e.getState();return r?r.scaleTo(t,{duration:n==null?void 0:n.duration}):Promise.resolve(!1)},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{const{transform:[r,o,i],panZoom:a}=e.getState();return a?(await a.setViewport({x:t.x??r,y:t.y??o,zoom:t.zoom??i},n),Promise.resolve(!0)):Promise.resolve(!1)},getViewport:()=>{const[t,n,r]=e.getState().transform;return{x:t,y:n,zoom:r}},setCenter:async(t,n,r)=>e.getState().setCenter(t,n,r),fitBounds:async(t,n)=>{const{width:r,height:o,minZoom:i,maxZoom:a,panZoom:l}=e.getState(),c=nE(t,r,o,i,a,(n==null?void 0:n.padding)??.1);return l?(await l.setViewport(c,{duration:n==null?void 0:n.duration,ease:n==null?void 0:n.ease,interpolate:n==null?void 0:n.interpolate}),Promise.resolve(!0)):Promise.resolve(!1)},screenToFlowPosition:(t,n={})=>{const{transform:r,snapGrid:o,snapToGrid:i,domNode:a}=e.getState();if(!a)return t;const{x:l,y:c}=a.getBoundingClientRect(),d={x:t.x-l,y:t.y-c},E=n.snapGrid??o,u=n.snapToGrid??i;return Ko(d,r,u,E)},flowToScreenPosition:t=>{const{transform:n,domNode:r}=e.getState();if(!r)return t;const{x:o,y:i}=r.getBoundingClientRect(),a=vi(t,n);return{x:a.x+o,y:a.y+i}}}),[])};function _A(e,t){const n=[],r=new Map,o=[];for(const i of e)if(i.type==="add"){o.push(i);continue}else if(i.type==="remove"||i.type==="replace")r.set(i.id,[i]);else{const a=r.get(i.id);a?a.push(i):r.set(i.id,[i])}for(const i of t){const a=r.get(i.id);if(!a){n.push(i);continue}if(a[0].type==="remove")continue;if(a[0].type==="replace"){n.push({...a[0].item});continue}const l={...i};for(const c of a)kU(c,l);n.push(l)}return o.length&&o.forEach(i=>{i.index!==void 0?n.splice(i.index,0,{...i.item}):n.push({...i.item})}),n}function kU(e,t){switch(e.type){case"select":{t.selected=e.selected;break}case"position":{typeof e.position<"u"&&(t.position=e.position),typeof e.dragging<"u"&&(t.dragging=e.dragging);break}case"dimensions":{typeof e.dimensions<"u"&&(t.measured={...e.dimensions},e.setAttributes&&((e.setAttributes===!0||e.setAttributes==="width")&&(t.width=e.dimensions.width),(e.setAttributes===!0||e.setAttributes==="height")&&(t.height=e.dimensions.height))),typeof e.resizing=="boolean"&&(t.resizing=e.resizing);break}}}function bA(e,t){return _A(e,t)}function DA(e,t){return _A(e,t)}function Dn(e,t){return{id:e,type:"select",selected:t}}function pr(e,t=new Set,n=!1){const r=[];for(const[o,i]of e){const a=t.has(o);!(i.selected===void 0&&!a)&&i.selected!==a&&(n&&(i.selected=a),r.push(Dn(i.id,a)))}return r}function vT({items:e=[],lookup:t}){var o;const n=[],r=new Map(e.map(i=>[i.id,i]));for(const[i,a]of e.entries()){const l=t.get(a.id),c=((o=l==null?void 0:l.internals)==null?void 0:o.userNode)??l;c!==void 0&&c!==a&&n.push({id:a.id,item:a,type:"replace"}),c===void 0&&n.push({item:a,type:"add",index:i})}for(const[i]of t)r.get(i)===void 0&&n.push({id:i,type:"remove"});return n}function PT(e){return{id:e.id,type:"remove"}}const wT=e=>cw(e),jU=e=>Zh(e);function MA(e){return f.forwardRef(e)}const GU=typeof window<"u"?f.useLayoutEffect:f.useEffect;function UT(e){const[t,n]=f.useState(BigInt(0)),[r]=f.useState(()=>HU(()=>n(o=>o+BigInt(1))));return GU(()=>{const o=r.get();o.length&&(e(o),r.reset())},[t]),r}function HU(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}const vA=f.createContext(null);function YU({children:e}){const t=Le(),n=f.useCallback(l=>{const{nodes:c=[],setNodes:d,hasDefaultNodes:E,onNodesChange:u,nodeLookup:T,fitViewQueued:p,onNodesChangeMiddlewareMap:h}=t.getState();let A=c;for(const R of l)A=typeof R=="function"?R(A):R;let S=vT({items:A,lookup:T});for(const R of h.values())S=R(S);E&&d(A),S.length>0?u==null||u(S):p&&window.requestAnimationFrame(()=>{const{fitViewQueued:R,nodes:m,setNodes:I}=t.getState();R&&I(m)})},[]),r=UT(n),o=f.useCallback(l=>{const{edges:c=[],setEdges:d,hasDefaultEdges:E,onEdgesChange:u,edgeLookup:T}=t.getState();let p=c;for(const h of l)p=typeof h=="function"?h(p):h;E?d(p):u&&u(vT({items:p,lookup:T}))},[]),i=UT(o),a=f.useMemo(()=>({nodeQueue:r,edgeQueue:i}),[]);return s.jsx(vA.Provider,{value:a,children:e})}function WU(){const e=f.useContext(vA);if(!e)throw new Error("useBatchContext must be used within a BatchProvider");return e}const $U=e=>!!e.panZoom;function ga(){const e=FU(),t=Le(),n=WU(),r=Ae($U),o=f.useMemo(()=>{const i=u=>t.getState().nodeLookup.get(u),a=u=>{n.nodeQueue.push(u)},l=u=>{n.edgeQueue.push(u)},c=u=>{var R,m;const{nodeLookup:T,nodeOrigin:p}=t.getState(),h=wT(u)?u:T.get(u.id),A=h.parentId?sA(h.position,h.measured,h.parentId,T,p):h.position,S={...h,position:A,width:((R=h.measured)==null?void 0:R.width)??h.width,height:((m=h.measured)==null?void 0:m.height)??h.height};return vr(S)},d=(u,T,p={replace:!1})=>{a(h=>h.map(A=>{if(A.id===u){const S=typeof T=="function"?T(A):T;return p.replace&&wT(S)?S:{...A,...S}}return A}))},E=(u,T,p={replace:!1})=>{l(h=>h.map(A=>{if(A.id===u){const S=typeof T=="function"?T(A):T;return p.replace&&jU(S)?S:{...A,...S}}return A}))};return{getNodes:()=>t.getState().nodes.map(u=>({...u})),getNode:u=>{var T;return(T=i(u))==null?void 0:T.internals.userNode},getInternalNode:i,getEdges:()=>{const{edges:u=[]}=t.getState();return u.map(T=>({...T}))},getEdge:u=>t.getState().edgeLookup.get(u),setNodes:a,setEdges:l,addNodes:u=>{const T=Array.isArray(u)?u:[u];n.nodeQueue.push(p=>[...p,...T])},addEdges:u=>{const T=Array.isArray(u)?u:[u];n.edgeQueue.push(p=>[...p,...T])},toObject:()=>{const{nodes:u=[],edges:T=[],transform:p}=t.getState(),[h,A,S]=p;return{nodes:u.map(R=>({...R})),edges:T.map(R=>({...R})),viewport:{x:h,y:A,zoom:S}}},deleteElements:async({nodes:u=[],edges:T=[]})=>{const{nodes:p,edges:h,onNodesDelete:A,onEdgesDelete:S,triggerNodeChanges:R,triggerEdgeChanges:m,onDelete:I,onBeforeDelete:O}=t.getState(),{nodes:N,edges:x}=await fw({nodesToRemove:u,edgesToRemove:T,nodes:p,edges:h,onBeforeDelete:O}),g=x.length>0,C=N.length>0;if(g){const y=x.map(PT);S==null||S(x),m(y)}if(C){const y=N.map(PT);A==null||A(N),R(y)}return(C||g)&&(I==null||I({nodes:N,edges:x})),{deletedNodes:N,deletedEdges:x}},getIntersectingNodes:(u,T=!0,p)=>{const h=aT(u),A=h?u:c(u),S=p!==void 0;return A?(p||t.getState().nodes).filter(R=>{const m=t.getState().nodeLookup.get(R.id);if(m&&!h&&(R.id===u.id||!m.internals.positionAbsolute))return!1;const I=vr(S?R:m),O=Do(I,A);return T&&O>0||O>=I.width*I.height||O>=A.width*A.height}):[]},isNodeIntersecting:(u,T,p=!0)=>{const A=aT(u)?u:c(u);if(!A)return!1;const S=Do(A,T);return p&&S>0||S>=T.width*T.height||S>=A.width*A.height},updateNode:d,updateNodeData:(u,T,p={replace:!1})=>{d(u,h=>{const A=typeof T=="function"?T(h):T;return p.replace?{...h,data:A}:{...h,data:{...h.data,...A}}},p)},updateEdge:E,updateEdgeData:(u,T,p={replace:!1})=>{E(u,h=>{const A=typeof T=="function"?T(h):T;return p.replace?{...h,data:A}:{...h,data:{...h.data,...A}}},p)},getNodesBounds:u=>{const{nodeLookup:T,nodeOrigin:p}=t.getState();return dw(u,{nodeLookup:T,nodeOrigin:p})},getHandleConnections:({type:u,id:T,nodeId:p})=>{var h;return Array.from(((h=t.getState().connectionLookup.get(`${p}-${u}${T?`-${T}`:""}`))==null?void 0:h.values())??[])},getNodeConnections:({type:u,handleId:T,nodeId:p})=>{var h;return Array.from(((h=t.getState().connectionLookup.get(`${p}${u?T?`-${u}-${T}`:`-${u}`:""}`))==null?void 0:h.values())??[])},fitView:async u=>{const T=t.getState().fitViewResolver??hw();return t.setState({fitViewQueued:!0,fitViewOptions:u,fitViewResolver:T}),n.nodeQueue.push(p=>[...p]),T.promise}}},[]);return f.useMemo(()=>({...o,...e,viewportInitialized:r}),[r])}const BT=e=>e.selected,VU=typeof window<"u"?window:void 0;function XU({deleteKeyCode:e,multiSelectionKeyCode:t}){const n=Le(),{deleteElements:r}=ga(),o=vo(e,{actInsideInputWithModifier:!1}),i=vo(t,{target:VU});f.useEffect(()=>{if(o){const{edges:a,nodes:l}=n.getState();r({nodes:l.filter(BT),edges:a.filter(BT)}),n.setState({nodesSelectionActive:!1})}},[o]),f.useEffect(()=>{n.setState({multiSelectionActive:i})},[i])}function zU(e){const t=Le();f.useEffect(()=>{const n=()=>{var o,i,a,l;if(!e.current||!(((i=(o=e.current).checkVisibility)==null?void 0:i.call(o))??!0))return!1;const r=rE(e.current);(r.height===0||r.width===0)&&((l=(a=t.getState()).onError)==null||l.call(a,"004",bt.error004())),t.setState({width:r.width||500,height:r.height||500})};if(e.current){n(),window.addEventListener("resize",n);const r=new ResizeObserver(()=>n());return r.observe(e.current),()=>{window.removeEventListener("resize",n),r&&e.current&&r.unobserve(e.current)}}},[])}const xa={position:"absolute",width:"100%",height:"100%",top:0,left:0},KU=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function qU({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panOnScrollSpeed:o=.5,panOnScrollMode:i=Un.Free,zoomOnDoubleClick:a=!0,panOnDrag:l=!0,defaultViewport:c,translateExtent:d,minZoom:E,maxZoom:u,zoomActivationKeyCode:T,preventScrolling:p=!0,children:h,noWheelClassName:A,noPanClassName:S,onViewportChange:R,isControlledViewport:m,paneClickDistance:I,selectionOnDrag:O}){const N=Le(),x=f.useRef(null),{userSelectionActive:g,lib:C,connectionInProgress:y}=Ae(KU,ye),w=vo(T),v=f.useRef();zU(x);const B=f.useCallback(b=>{R==null||R({x:b[0],y:b[1],zoom:b[2]}),m||N.setState({transform:b})},[R,m]);return f.useEffect(()=>{if(x.current){v.current=tU({domNode:x.current,minZoom:E,maxZoom:u,translateExtent:d,viewport:c,onDraggingChange:M=>N.setState(U=>U.paneDragging===M?U:{paneDragging:M}),onPanZoomStart:(M,U)=>{const{onViewportChangeStart:P,onMoveStart:_}=N.getState();_==null||_(M,U),P==null||P(U)},onPanZoom:(M,U)=>{const{onViewportChange:P,onMove:_}=N.getState();_==null||_(M,U),P==null||P(U)},onPanZoomEnd:(M,U)=>{const{onViewportChangeEnd:P,onMoveEnd:_}=N.getState();_==null||_(M,U),P==null||P(U)}});const{x:b,y:L,zoom:D}=v.current.getViewport();return N.setState({panZoom:v.current,transform:[b,L,D],domNode:x.current.closest(".react-flow")}),()=>{var M;(M=v.current)==null||M.destroy()}}},[]),f.useEffect(()=>{var b;(b=v.current)==null||b.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panOnScrollSpeed:o,panOnScrollMode:i,zoomOnDoubleClick:a,panOnDrag:l,zoomActivationKeyPressed:w,preventScrolling:p,noPanClassName:S,userSelectionActive:g,noWheelClassName:A,lib:C,onTransformChange:B,connectionInProgress:y,selectionOnDrag:O,paneClickDistance:I})},[e,t,n,r,o,i,a,l,w,p,S,g,A,C,B,y,O,I]),s.jsx("div",{className:"react-flow__renderer",ref:x,style:xa,children:h})}const JU=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function QU(){const{userSelectionActive:e,userSelectionRect:t}=Ae(JU,ye);return e&&t?s.jsx("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}const Ll=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},ZU=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function eB({isSelecting:e,selectionKeyPressed:t,selectionMode:n=bo.Full,panOnDrag:r,paneClickDistance:o,selectionOnDrag:i,onSelectionStart:a,onSelectionEnd:l,onPaneClick:c,onPaneContextMenu:d,onPaneScroll:E,onPaneMouseEnter:u,onPaneMouseMove:T,onPaneMouseLeave:p,children:h}){const A=Le(),{userSelectionActive:S,elementsSelectable:R,dragging:m,connectionInProgress:I}=Ae(ZU,ye),O=R&&(e||S),N=f.useRef(null),x=f.useRef(),g=f.useRef(new Set),C=f.useRef(new Set),y=f.useRef(!1),w=P=>{if(y.current||I){y.current=!1;return}c==null||c(P),A.getState().resetSelectedElements(),A.setState({nodesSelectionActive:!1})},v=P=>{if(Array.isArray(r)&&(r!=null&&r.includes(2))){P.preventDefault();return}d==null||d(P)},B=E?P=>E(P):void 0,b=P=>{y.current&&(P.stopPropagation(),y.current=!1)},L=P=>{var $,Z;const{domNode:_}=A.getState();if(x.current=_==null?void 0:_.getBoundingClientRect(),!x.current)return;const F=P.target===N.current;if(!F&&!!P.target.closest(".nokey")||!e||!(i&&F||t)||P.button!==0||!P.isPrimary)return;(Z=($=P.target)==null?void 0:$.setPointerCapture)==null||Z.call($,P.pointerId),y.current=!1;const{x:Q,y:q}=ft(P.nativeEvent,x.current);A.setState({userSelectionRect:{width:0,height:0,startX:Q,startY:q,x:Q,y:q}}),F||(P.stopPropagation(),P.preventDefault())},D=P=>{const{userSelectionRect:_,transform:F,nodeLookup:k,edgeLookup:H,connectionLookup:Q,triggerNodeChanges:q,triggerEdgeChanges:$,defaultEdgeOptions:Z,resetSelectedElements:Y}=A.getState();if(!x.current||!_)return;const{x:G,y:J}=ft(P.nativeEvent,x.current),{startX:te,startY:re}=_;if(!y.current){const de=t?0:o;if(Math.hypot(G-te,J-re)<=de)return;Y(),a==null||a(P)}y.current=!0;const oe={startX:te,startY:re,x:G<te?G:te,y:J<re?J:re,width:Math.abs(G-te),height:Math.abs(J-re)},V=g.current,le=C.current;g.current=new Set(tE(k,oe,F,n===bo.Partial,!0).map(de=>de.id)),C.current=new Set;const Te=(Z==null?void 0:Z.selectable)??!0;for(const de of g.current){const ne=Q.get(de);if(ne)for(const{edgeId:Re}of ne.values()){const Oe=H.get(Re);Oe&&(Oe.selectable??Te)&&C.current.add(Re)}}if(!lT(V,g.current)){const de=pr(k,g.current,!0);q(de)}if(!lT(le,C.current)){const de=pr(H,C.current);$(de)}A.setState({userSelectionRect:oe,userSelectionActive:!0,nodesSelectionActive:!1})},M=P=>{var _,F;P.button===0&&((F=(_=P.target)==null?void 0:_.releasePointerCapture)==null||F.call(_,P.pointerId),!S&&P.target===N.current&&A.getState().userSelectionRect&&(w==null||w(P)),A.setState({userSelectionActive:!1,userSelectionRect:null}),y.current&&(l==null||l(P),A.setState({nodesSelectionActive:g.current.size>0})))},U=r===!0||Array.isArray(r)&&r.includes(0);return s.jsxs("div",{className:De(["react-flow__pane",{draggable:U,dragging:m,selection:e}]),onClick:O?void 0:Ll(w,N),onContextMenu:Ll(v,N),onWheel:Ll(B,N),onPointerEnter:O?void 0:u,onPointerMove:O?D:T,onPointerUp:O?M:void 0,onPointerDownCapture:O?L:void 0,onClickCapture:O?b:void 0,onPointerLeave:p,ref:N,style:xa,children:[h,s.jsx(QU,{})]})}function Jc({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:o,unselectNodesAndEdges:i,multiSelectionActive:a,nodeLookup:l,onError:c}=t.getState(),d=l.get(e);if(!d){c==null||c("012",bt.error012(e));return}t.setState({nodesSelectionActive:!1}),d.selected?(n||d.selected&&a)&&(i({nodes:[d],edges:[]}),requestAnimationFrame(()=>{var E;return(E=r==null?void 0:r.current)==null?void 0:E.blur()})):o([e])}function PA({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:o,isSelectable:i,nodeClickDistance:a}){const l=Le(),[c,d]=f.useState(!1),E=f.useRef();return f.useEffect(()=>{E.current=Gw({getStoreItems:()=>l.getState(),onNodeMouseDown:u=>{Jc({id:u,store:l,nodeRef:e})},onDragStart:()=>{d(!0)},onDragStop:()=>{d(!1)}})},[]),f.useEffect(()=>{if(!(t||!e.current||!E.current))return E.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:i,nodeId:o,nodeClickDistance:a}),()=>{var u;(u=E.current)==null||u.destroy()}},[n,r,t,i,e,o,a]),c}const tB=e=>t=>t.selected&&(t.draggable||e&&typeof t.draggable>"u");function wA(){const e=Le();return f.useCallback(n=>{const{nodeExtent:r,snapToGrid:o,snapGrid:i,nodesDraggable:a,onError:l,updateNodePositions:c,nodeLookup:d,nodeOrigin:E}=e.getState(),u=new Map,T=tB(a),p=o?i[0]:5,h=o?i[1]:5,A=n.direction.x*p*n.factor,S=n.direction.y*h*n.factor;for(const[,R]of d){if(!T(R))continue;let m={x:R.internals.positionAbsolute.x+A,y:R.internals.positionAbsolute.y+S};o&&(m=zo(m,i));const{position:I,positionAbsolute:O}=eA({nodeId:R.id,nextPosition:m,nodeLookup:d,nodeExtent:r,nodeOrigin:E,onError:l});R.position=I,R.internals.positionAbsolute=O,u.set(R.id,R)}c(u)},[])}const cE=f.createContext(null),nB=cE.Provider;cE.Consumer;const UA=()=>f.useContext(cE),rB=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),oB=(e,t,n)=>r=>{const{connectionClickStartHandle:o,connectionMode:i,connection:a}=r,{fromHandle:l,toHandle:c,isValid:d}=a,E=(c==null?void 0:c.nodeId)===e&&(c==null?void 0:c.id)===t&&(c==null?void 0:c.type)===n;return{connectingFrom:(l==null?void 0:l.nodeId)===e&&(l==null?void 0:l.id)===t&&(l==null?void 0:l.type)===n,connectingTo:E,clickConnecting:(o==null?void 0:o.nodeId)===e&&(o==null?void 0:o.id)===t&&(o==null?void 0:o.type)===n,isPossibleEndHandle:i===br.Strict?(l==null?void 0:l.type)!==n:e!==(l==null?void 0:l.nodeId)||t!==(l==null?void 0:l.id),connectionInProcess:!!l,clickConnectionInProcess:!!o,valid:E&&d}};function sB({type:e="source",position:t=ae.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:o=!0,isConnectableEnd:i=!0,id:a,onConnect:l,children:c,className:d,onMouseDown:E,onTouchStart:u,...T},p){var D,M;const h=a||null,A=e==="target",S=Le(),R=UA(),{connectOnClick:m,noPanClassName:I,rfId:O}=Ae(rB,ye),{connectingFrom:N,connectingTo:x,clickConnecting:g,isPossibleEndHandle:C,connectionInProcess:y,clickConnectionInProcess:w,valid:v}=Ae(oB(R,h,e),ye);R||(M=(D=S.getState()).onError)==null||M.call(D,"010",bt.error010());const B=U=>{const{defaultEdgeOptions:P,onConnect:_,hasDefaultEdges:F}=S.getState(),k={...P,...U};if(F){const{edges:H,setEdges:Q}=S.getState();Q(xw(k,H))}_==null||_(k),l==null||l(k)},b=U=>{if(!R)return;const P=lA(U.nativeEvent);if(o&&(P&&U.button===0||!P)){const _=S.getState();qc.onPointerDown(U.nativeEvent,{handleDomNode:U.currentTarget,autoPanOnConnect:_.autoPanOnConnect,connectionMode:_.connectionMode,connectionRadius:_.connectionRadius,domNode:_.domNode,nodeLookup:_.nodeLookup,lib:_.lib,isTarget:A,handleId:h,nodeId:R,flowId:_.rfId,panBy:_.panBy,cancelConnection:_.cancelConnection,onConnectStart:_.onConnectStart,onConnectEnd:(...F)=>{var k,H;return(H=(k=S.getState()).onConnectEnd)==null?void 0:H.call(k,...F)},updateConnection:_.updateConnection,onConnect:B,isValidConnection:n||((...F)=>{var k,H;return((H=(k=S.getState()).isValidConnection)==null?void 0:H.call(k,...F))??!0}),getTransform:()=>S.getState().transform,getFromHandle:()=>S.getState().connection.fromHandle,autoPanSpeed:_.autoPanSpeed,dragThreshold:_.connectionDragThreshold})}P?E==null||E(U):u==null||u(U)},L=U=>{const{onClickConnectStart:P,onClickConnectEnd:_,connectionClickStartHandle:F,connectionMode:k,isValidConnection:H,lib:Q,rfId:q,nodeLookup:$,connection:Z}=S.getState();if(!R||!F&&!o)return;if(!F){P==null||P(U.nativeEvent,{nodeId:R,handleId:h,handleType:e}),S.setState({connectionClickStartHandle:{nodeId:R,type:e,id:h}});return}const Y=iA(U.target),G=n||H,{connection:J,isValid:te}=qc.isValid(U.nativeEvent,{handle:{nodeId:R,id:h,type:e},connectionMode:k,fromNodeId:F.nodeId,fromHandleId:F.id||null,fromType:F.type,isValidConnection:G,flowId:q,doc:Y,lib:Q,nodeLookup:$});te&&J&&B(J);const re=structuredClone(Z);delete re.inProgress,re.toPosition=re.toHandle?re.toHandle.position:null,_==null||_(U,re),S.setState({connectionClickStartHandle:null})};return s.jsx("div",{"data-handleid":h,"data-nodeid":R,"data-handlepos":t,"data-id":`${O}-${R}-${h}-${e}`,className:De(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",I,d,{source:!A,target:A,connectable:r,connectablestart:o,connectableend:i,clickconnecting:g,connectingfrom:N,connectingto:x,valid:v,connectionindicator:r&&(!y||C)&&(y||w?i:o)}]),onMouseDown:b,onTouchStart:b,onClick:m?L:void 0,ref:p,...T,children:c})}const Rn=f.memo(MA(sB));function iB({data:e,isConnectable:t,sourcePosition:n=ae.Bottom}){return s.jsxs(s.Fragment,{children:[e==null?void 0:e.label,s.jsx(Rn,{type:"source",position:n,isConnectable:t})]})}function aB({data:e,isConnectable:t,targetPosition:n=ae.Top,sourcePosition:r=ae.Bottom}){return s.jsxs(s.Fragment,{children:[s.jsx(Rn,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,s.jsx(Rn,{type:"source",position:r,isConnectable:t})]})}function lB(){return null}function cB({data:e,isConnectable:t,targetPosition:n=ae.Top}){return s.jsxs(s.Fragment,{children:[s.jsx(Rn,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label]})}const Pi={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},FT={input:iB,default:aB,output:cB,group:lB};function dB(e){var t,n,r,o;return e.internals.handleBounds===void 0?{width:e.width??e.initialWidth??((t=e.style)==null?void 0:t.width),height:e.height??e.initialHeight??((n=e.style)==null?void 0:n.height)}:{width:e.width??((r=e.style)==null?void 0:r.width),height:e.height??((o=e.style)==null?void 0:o.height)}}const EB=e=>{const{width:t,height:n,x:r,y:o}=Xo(e.nodeLookup,{filter:i=>!!i.selected});return{width:Tt(t)?t:null,height:Tt(n)?n:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${r}px,${o}px)`}};function uB({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=Le(),{width:o,height:i,transformString:a,userSelectionActive:l}=Ae(EB,ye),c=wA(),d=f.useRef(null);f.useEffect(()=>{var p;n||(p=d.current)==null||p.focus({preventScroll:!0})},[n]);const E=!l&&o!==null&&i!==null;if(PA({nodeRef:d,disabled:!E}),!E)return null;const u=e?p=>{const h=r.getState().nodes.filter(A=>A.selected);e(p,h)}:void 0,T=p=>{Object.prototype.hasOwnProperty.call(Pi,p.key)&&(p.preventDefault(),c({direction:Pi[p.key],factor:p.shiftKey?4:1}))};return s.jsx("div",{className:De(["react-flow__nodesselection","react-flow__container",t]),style:{transform:a},children:s.jsx("div",{ref:d,className:"react-flow__nodesselection-rect",onContextMenu:u,tabIndex:n?void 0:-1,onKeyDown:n?void 0:T,style:{width:o,height:i}})})}const kT=typeof window<"u"?window:void 0,TB=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function BA({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:i,onPaneScroll:a,paneClickDistance:l,deleteKeyCode:c,selectionKeyCode:d,selectionOnDrag:E,selectionMode:u,onSelectionStart:T,onSelectionEnd:p,multiSelectionKeyCode:h,panActivationKeyCode:A,zoomActivationKeyCode:S,elementsSelectable:R,zoomOnScroll:m,zoomOnPinch:I,panOnScroll:O,panOnScrollSpeed:N,panOnScrollMode:x,zoomOnDoubleClick:g,panOnDrag:C,defaultViewport:y,translateExtent:w,minZoom:v,maxZoom:B,preventScrolling:b,onSelectionContextMenu:L,noWheelClassName:D,noPanClassName:M,disableKeyboardA11y:U,onViewportChange:P,isControlledViewport:_}){const{nodesSelectionActive:F,userSelectionActive:k}=Ae(TB,ye),H=vo(d,{target:kT}),Q=vo(A,{target:kT}),q=Q||C,$=Q||O,Z=E&&q!==!0,Y=H||k||Z;return XU({deleteKeyCode:c,multiSelectionKeyCode:h}),s.jsx(qU,{onPaneContextMenu:i,elementsSelectable:R,zoomOnScroll:m,zoomOnPinch:I,panOnScroll:$,panOnScrollSpeed:N,panOnScrollMode:x,zoomOnDoubleClick:g,panOnDrag:!H&&q,defaultViewport:y,translateExtent:w,minZoom:v,maxZoom:B,zoomActivationKeyCode:S,preventScrolling:b,noWheelClassName:D,noPanClassName:M,onViewportChange:P,isControlledViewport:_,paneClickDistance:l,selectionOnDrag:Z,children:s.jsxs(eB,{onSelectionStart:T,onSelectionEnd:p,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:i,onPaneScroll:a,panOnDrag:q,isSelecting:!!Y,selectionMode:u,selectionKeyPressed:H,paneClickDistance:l,selectionOnDrag:Z,children:[e,F&&s.jsx(uB,{onSelectionContextMenu:L,noPanClassName:M,disableKeyboardA11y:U})]})})}BA.displayName="FlowRenderer";const fB=f.memo(BA),pB=e=>t=>e?tE(t.nodeLookup,{x:0,y:0,width:t.width,height:t.height},t.transform,!0).map(n=>n.id):Array.from(t.nodeLookup.keys());function SB(e){return Ae(f.useCallback(pB(e),[e]),ye)}const RB=e=>e.updateNodeInternals;function hB(){const e=Ae(RB),[t]=f.useState(()=>typeof ResizeObserver>"u"?null:new ResizeObserver(n=>{const r=new Map;n.forEach(o=>{const i=o.target.getAttribute("data-id");r.set(i,{id:i,nodeElement:o.target,force:!0})}),e(r)}));return f.useEffect(()=>()=>{t==null||t.disconnect()},[t]),t}function AB({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){const o=Le(),i=f.useRef(null),a=f.useRef(null),l=f.useRef(e.sourcePosition),c=f.useRef(e.targetPosition),d=f.useRef(t),E=n&&!!e.internals.handleBounds;return f.useEffect(()=>{i.current&&!e.hidden&&(!E||a.current!==i.current)&&(a.current&&(r==null||r.unobserve(a.current)),r==null||r.observe(i.current),a.current=i.current)},[E,e.hidden]),f.useEffect(()=>()=>{a.current&&(r==null||r.unobserve(a.current),a.current=null)},[]),f.useEffect(()=>{if(i.current){const u=d.current!==t,T=l.current!==e.sourcePosition,p=c.current!==e.targetPosition;(u||T||p)&&(d.current=t,l.current=e.sourcePosition,c.current=e.targetPosition,o.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:i.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),i}function IB({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:o,onContextMenu:i,onDoubleClick:a,nodesDraggable:l,elementsSelectable:c,nodesConnectable:d,nodesFocusable:E,resizeObserver:u,noDragClassName:T,noPanClassName:p,disableKeyboardA11y:h,rfId:A,nodeTypes:S,nodeClickDistance:R,onError:m}){const{node:I,internals:O,isParent:N}=Ae(G=>{const J=G.nodeLookup.get(e),te=G.parentLookup.has(e);return{node:J,internals:J.internals,isParent:te}},ye);let x=I.type||"default",g=(S==null?void 0:S[x])||FT[x];g===void 0&&(m==null||m("003",bt.error003(x)),x="default",g=(S==null?void 0:S.default)||FT.default);const C=!!(I.draggable||l&&typeof I.draggable>"u"),y=!!(I.selectable||c&&typeof I.selectable>"u"),w=!!(I.connectable||d&&typeof I.connectable>"u"),v=!!(I.focusable||E&&typeof I.focusable>"u"),B=Le(),b=oA(I),L=AB({node:I,nodeType:x,hasDimensions:b,resizeObserver:u}),D=PA({nodeRef:L,disabled:I.hidden||!C,noDragClassName:T,handleSelector:I.dragHandle,nodeId:e,isSelectable:y,nodeClickDistance:R}),M=wA();if(I.hidden)return null;const U=$t(I),P=dB(I),_=y||C||t||n||r||o,F=n?G=>n(G,{...O.userNode}):void 0,k=r?G=>r(G,{...O.userNode}):void 0,H=o?G=>o(G,{...O.userNode}):void 0,Q=i?G=>i(G,{...O.userNode}):void 0,q=a?G=>a(G,{...O.userNode}):void 0,$=G=>{const{selectNodesOnDrag:J,nodeDragThreshold:te}=B.getState();y&&(!J||!C||te>0)&&Jc({id:e,store:B,nodeRef:L}),t&&t(G,{...O.userNode})},Z=G=>{if(!(aA(G.nativeEvent)||h)){if(Kh.includes(G.key)&&y){const J=G.key==="Escape";Jc({id:e,store:B,unselect:J,nodeRef:L})}else if(C&&I.selected&&Object.prototype.hasOwnProperty.call(Pi,G.key)){G.preventDefault();const{ariaLabelConfig:J}=B.getState();B.setState({ariaLiveMessage:J["node.a11yDescription.ariaLiveMessage"]({direction:G.key.replace("Arrow","").toLowerCase(),x:~~O.positionAbsolute.x,y:~~O.positionAbsolute.y})}),M({direction:Pi[G.key],factor:G.shiftKey?4:1})}}},Y=()=>{var le;if(h||!((le=L.current)!=null&&le.matches(":focus-visible")))return;const{transform:G,width:J,height:te,autoPanOnNodeFocus:re,setCenter:oe}=B.getState();if(!re)return;tE(new Map([[e,I]]),{x:0,y:0,width:J,height:te},G,!0).length>0||oe(I.position.x+U.width/2,I.position.y+U.height/2,{zoom:G[2]})};return s.jsx("div",{className:De(["react-flow__node",`react-flow__node-${x}`,{[p]:C},I.className,{selected:I.selected,selectable:y,parent:N,draggable:C,dragging:D}]),ref:L,style:{zIndex:O.z,transform:`translate(${O.positionAbsolute.x}px,${O.positionAbsolute.y}px)`,pointerEvents:_?"all":"none",visibility:b?"visible":"hidden",...I.style,...P},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:F,onMouseMove:k,onMouseLeave:H,onContextMenu:Q,onClick:$,onDoubleClick:q,onKeyDown:v?Z:void 0,tabIndex:v?0:void 0,onFocus:v?Y:void 0,role:I.ariaRole??(v?"group":void 0),"aria-roledescription":"node","aria-describedby":h?void 0:`${yA}-${A}`,"aria-label":I.ariaLabel,...I.domAttributes,children:s.jsx(nB,{value:e,children:s.jsx(g,{id:e,data:I.data,type:x,positionAbsoluteX:O.positionAbsolute.x,positionAbsoluteY:O.positionAbsolute.y,selected:I.selected??!1,selectable:y,draggable:C,deletable:I.deletable??!0,isConnectable:w,sourcePosition:I.sourcePosition,targetPosition:I.targetPosition,dragging:D,dragHandle:I.dragHandle,zIndex:O.z,parentId:I.parentId,...U})})})}var mB=f.memo(IB);const OB=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function FA(e){const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,onError:i}=Ae(OB,ye),a=SB(e.onlyRenderVisibleElements),l=hB();return s.jsx("div",{className:"react-flow__nodes",style:xa,children:a.map(c=>s.jsx(mB,{id:c,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:l,nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,nodeClickDistance:e.nodeClickDistance,onError:i},c))})}FA.displayName="NodeRenderer";const NB=f.memo(FA);function gB(e){return Ae(f.useCallback(n=>{if(!e)return n.edges.map(o=>o.id);const r=[];if(n.width&&n.height)for(const o of n.edges){const i=n.nodeLookup.get(o.source),a=n.nodeLookup.get(o.target);i&&a&&Ow({sourceNode:i,targetNode:a,width:n.width,height:n.height,transform:n.transform})&&r.push(o.id)}return r},[e]),ye)}const xB=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e}};return s.jsx("polyline",{className:"arrow",style:n,strokeLinecap:"round",fill:"none",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4"})},yB=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e,fill:e}};return s.jsx("polyline",{className:"arrowclosed",style:n,strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},jT={[Dr.Arrow]:xB,[Dr.ArrowClosed]:yB};function CB(e){const t=Le();return f.useMemo(()=>{var o,i;return Object.prototype.hasOwnProperty.call(jT,e)?jT[e]:((i=(o=t.getState()).onError)==null||i.call(o,"009",bt.error009(e)),null)},[e])}const LB=({id:e,type:t,color:n,width:r=12.5,height:o=12.5,markerUnits:i="strokeWidth",strokeWidth:a,orient:l="auto-start-reverse"})=>{const c=CB(t);return c?s.jsx("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${o}`,viewBox:"-10 -10 20 20",markerUnits:i,orient:l,refX:"0",refY:"0",children:s.jsx(c,{color:n,strokeWidth:a})}):null},kA=({defaultColor:e,rfId:t})=>{const n=Ae(i=>i.edges),r=Ae(i=>i.defaultEdgeOptions),o=f.useMemo(()=>bw(n,{id:t,defaultColor:e,defaultMarkerStart:r==null?void 0:r.markerStart,defaultMarkerEnd:r==null?void 0:r.markerEnd}),[n,r,t,e]);return o.length?s.jsx("svg",{className:"react-flow__marker","aria-hidden":"true",children:s.jsx("defs",{children:o.map(i=>s.jsx(LB,{id:i.id,type:i.type,color:i.color,width:i.width,height:i.height,markerUnits:i.markerUnits,strokeWidth:i.strokeWidth,orient:i.orient},i.id))})}):null};kA.displayName="MarkerDefinitions";var _B=f.memo(kA);function jA({x:e,y:t,label:n,labelStyle:r,labelShowBg:o=!0,labelBgStyle:i,labelBgPadding:a=[2,4],labelBgBorderRadius:l=2,children:c,className:d,...E}){const[u,T]=f.useState({x:1,y:0,width:0,height:0}),p=De(["react-flow__edge-textwrapper",d]),h=f.useRef(null);return f.useEffect(()=>{if(h.current){const A=h.current.getBBox();T({x:A.x,y:A.y,width:A.width,height:A.height})}},[n]),n?s.jsxs("g",{transform:`translate(${e-u.width/2} ${t-u.height/2})`,className:p,visibility:u.width?"visible":"hidden",...E,children:[o&&s.jsx("rect",{width:u.width+2*a[0],x:-a[0],y:-a[1],height:u.height+2*a[1],className:"react-flow__edge-textbg",style:i,rx:l,ry:l}),s.jsx("text",{className:"react-flow__edge-text",y:u.height/2,dy:"0.3em",ref:h,style:r,children:n}),c]}):null}jA.displayName="EdgeText";const bB=f.memo(jA);function ya({path:e,labelX:t,labelY:n,label:r,labelStyle:o,labelShowBg:i,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c,interactionWidth:d=20,...E}){return s.jsxs(s.Fragment,{children:[s.jsx("path",{...E,d:e,fill:"none",className:De(["react-flow__edge-path",E.className])}),d?s.jsx("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:d,className:"react-flow__edge-interaction"}):null,r&&Tt(t)&&Tt(n)?s.jsx(bB,{x:t,y:n,label:r,labelStyle:o,labelShowBg:i,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:c}):null]})}function GT({pos:e,x1:t,y1:n,x2:r,y2:o}){return e===ae.Left||e===ae.Right?[.5*(t+r),n]:[t,.5*(n+o)]}function GA({sourceX:e,sourceY:t,sourcePosition:n=ae.Bottom,targetX:r,targetY:o,targetPosition:i=ae.Top}){const[a,l]=GT({pos:n,x1:e,y1:t,x2:r,y2:o}),[c,d]=GT({pos:i,x1:r,y1:o,x2:e,y2:t}),[E,u,T,p]=cA({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:a,sourceControlY:l,targetControlX:c,targetControlY:d});return[`M${e},${t} C${a},${l} ${c},${d} ${r},${o}`,E,u,T,p]}function HA(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:i,sourcePosition:a,targetPosition:l,label:c,labelStyle:d,labelShowBg:E,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:p,style:h,markerEnd:A,markerStart:S,interactionWidth:R})=>{const[m,I,O]=GA({sourceX:n,sourceY:r,sourcePosition:a,targetX:o,targetY:i,targetPosition:l}),N=e.isInternal?void 0:t;return s.jsx(ya,{id:N,path:m,labelX:I,labelY:O,label:c,labelStyle:d,labelShowBg:E,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:p,style:h,markerEnd:A,markerStart:S,interactionWidth:R})})}const DB=HA({isInternal:!1}),YA=HA({isInternal:!0});DB.displayName="SimpleBezierEdge";YA.displayName="SimpleBezierEdgeInternal";function WA(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:i,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:d,labelBgPadding:E,labelBgBorderRadius:u,style:T,sourcePosition:p=ae.Bottom,targetPosition:h=ae.Top,markerEnd:A,markerStart:S,pathOptions:R,interactionWidth:m})=>{const[I,O,N]=Xc({sourceX:n,sourceY:r,sourcePosition:p,targetX:o,targetY:i,targetPosition:h,borderRadius:R==null?void 0:R.borderRadius,offset:R==null?void 0:R.offset,stepPosition:R==null?void 0:R.stepPosition}),x=e.isInternal?void 0:t;return s.jsx(ya,{id:x,path:I,labelX:O,labelY:N,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:d,labelBgPadding:E,labelBgBorderRadius:u,style:T,markerEnd:A,markerStart:S,interactionWidth:m})})}const $A=WA({isInternal:!1}),VA=WA({isInternal:!0});$A.displayName="SmoothStepEdge";VA.displayName="SmoothStepEdgeInternal";function XA(e){return f.memo(({id:t,...n})=>{var o;const r=e.isInternal?void 0:t;return s.jsx($A,{...n,id:r,pathOptions:f.useMemo(()=>{var i;return{borderRadius:0,offset:(i=n.pathOptions)==null?void 0:i.offset}},[(o=n.pathOptions)==null?void 0:o.offset])})})}const MB=XA({isInternal:!1}),zA=XA({isInternal:!0});MB.displayName="StepEdge";zA.displayName="StepEdgeInternal";function KA(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:i,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:d,labelBgPadding:E,labelBgBorderRadius:u,style:T,markerEnd:p,markerStart:h,interactionWidth:A})=>{const[S,R,m]=uA({sourceX:n,sourceY:r,targetX:o,targetY:i}),I=e.isInternal?void 0:t;return s.jsx(ya,{id:I,path:S,labelX:R,labelY:m,label:a,labelStyle:l,labelShowBg:c,labelBgStyle:d,labelBgPadding:E,labelBgBorderRadius:u,style:T,markerEnd:p,markerStart:h,interactionWidth:A})})}const vB=KA({isInternal:!1}),qA=KA({isInternal:!0});vB.displayName="StraightEdge";qA.displayName="StraightEdgeInternal";function JA(e){return f.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:i,sourcePosition:a=ae.Bottom,targetPosition:l=ae.Top,label:c,labelStyle:d,labelShowBg:E,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:p,style:h,markerEnd:A,markerStart:S,pathOptions:R,interactionWidth:m})=>{const[I,O,N]=dA({sourceX:n,sourceY:r,sourcePosition:a,targetX:o,targetY:i,targetPosition:l,curvature:R==null?void 0:R.curvature}),x=e.isInternal?void 0:t;return s.jsx(ya,{id:x,path:I,labelX:O,labelY:N,label:c,labelStyle:d,labelShowBg:E,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:p,style:h,markerEnd:A,markerStart:S,interactionWidth:m})})}const PB=JA({isInternal:!1}),QA=JA({isInternal:!0});PB.displayName="BezierEdge";QA.displayName="BezierEdgeInternal";const HT={default:QA,straight:qA,step:zA,smoothstep:VA,simplebezier:YA},YT={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},wB=(e,t,n)=>n===ae.Left?e-t:n===ae.Right?e+t:e,UB=(e,t,n)=>n===ae.Top?e-t:n===ae.Bottom?e+t:e,WT="react-flow__edgeupdater";function $T({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:o,onMouseEnter:i,onMouseOut:a,type:l}){return s.jsx("circle",{onMouseDown:o,onMouseEnter:i,onMouseOut:a,className:De([WT,`${WT}-${l}`]),cx:wB(t,r,e),cy:UB(n,r,e),r,stroke:"transparent",fill:"transparent"})}function BB({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:o,targetX:i,targetY:a,sourcePosition:l,targetPosition:c,onReconnect:d,onReconnectStart:E,onReconnectEnd:u,setReconnecting:T,setUpdateHover:p}){const h=Le(),A=(O,N)=>{if(O.button!==0)return;const{autoPanOnConnect:x,domNode:g,connectionMode:C,connectionRadius:y,lib:w,onConnectStart:v,cancelConnection:B,nodeLookup:b,rfId:L,panBy:D,updateConnection:M}=h.getState(),U=N.type==="target",P=(k,H)=>{T(!1),u==null||u(k,n,N.type,H)},_=k=>d==null?void 0:d(n,k),F=(k,H)=>{T(!0),E==null||E(O,n,N.type),v==null||v(k,H)};qc.onPointerDown(O.nativeEvent,{autoPanOnConnect:x,connectionMode:C,connectionRadius:y,domNode:g,handleId:N.id,nodeId:N.nodeId,nodeLookup:b,isTarget:U,edgeUpdaterType:N.type,lib:w,flowId:L,cancelConnection:B,panBy:D,isValidConnection:(...k)=>{var H,Q;return((Q=(H=h.getState()).isValidConnection)==null?void 0:Q.call(H,...k))??!0},onConnect:_,onConnectStart:F,onConnectEnd:(...k)=>{var H,Q;return(Q=(H=h.getState()).onConnectEnd)==null?void 0:Q.call(H,...k)},onReconnectEnd:P,updateConnection:M,getTransform:()=>h.getState().transform,getFromHandle:()=>h.getState().connection.fromHandle,dragThreshold:h.getState().connectionDragThreshold,handleDomNode:O.currentTarget})},S=O=>A(O,{nodeId:n.target,id:n.targetHandle??null,type:"target"}),R=O=>A(O,{nodeId:n.source,id:n.sourceHandle??null,type:"source"}),m=()=>p(!0),I=()=>p(!1);return s.jsxs(s.Fragment,{children:[(e===!0||e==="source")&&s.jsx($T,{position:l,centerX:r,centerY:o,radius:t,onMouseDown:S,onMouseEnter:m,onMouseOut:I,type:"source"}),(e===!0||e==="target")&&s.jsx($T,{position:c,centerX:i,centerY:a,radius:t,onMouseDown:R,onMouseEnter:m,onMouseOut:I,type:"target"})]})}function FB({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:o,onDoubleClick:i,onContextMenu:a,onMouseEnter:l,onMouseMove:c,onMouseLeave:d,reconnectRadius:E,onReconnect:u,onReconnectStart:T,onReconnectEnd:p,rfId:h,edgeTypes:A,noPanClassName:S,onError:R,disableKeyboardA11y:m}){let I=Ae(oe=>oe.edgeLookup.get(e));const O=Ae(oe=>oe.defaultEdgeOptions);I=O?{...O,...I}:I;let N=I.type||"default",x=(A==null?void 0:A[N])||HT[N];x===void 0&&(R==null||R("011",bt.error011(N)),N="default",x=(A==null?void 0:A.default)||HT.default);const g=!!(I.focusable||t&&typeof I.focusable>"u"),C=typeof u<"u"&&(I.reconnectable||n&&typeof I.reconnectable>"u"),y=!!(I.selectable||r&&typeof I.selectable>"u"),w=f.useRef(null),[v,B]=f.useState(!1),[b,L]=f.useState(!1),D=Le(),{zIndex:M,sourceX:U,sourceY:P,targetX:_,targetY:F,sourcePosition:k,targetPosition:H}=Ae(f.useCallback(oe=>{const V=oe.nodeLookup.get(I.source),le=oe.nodeLookup.get(I.target);if(!V||!le)return{zIndex:I.zIndex,...YT};const Te=_w({id:e,sourceNode:V,targetNode:le,sourceHandle:I.sourceHandle||null,targetHandle:I.targetHandle||null,connectionMode:oe.connectionMode,onError:R});return{zIndex:mw({selected:I.selected,zIndex:I.zIndex,sourceNode:V,targetNode:le,elevateOnSelect:oe.elevateEdgesOnSelect,zIndexMode:oe.zIndexMode}),...Te||YT}},[I.source,I.target,I.sourceHandle,I.targetHandle,I.selected,I.zIndex]),ye),Q=f.useMemo(()=>I.markerStart?`url('#${zc(I.markerStart,h)}')`:void 0,[I.markerStart,h]),q=f.useMemo(()=>I.markerEnd?`url('#${zc(I.markerEnd,h)}')`:void 0,[I.markerEnd,h]);if(I.hidden||U===null||P===null||_===null||F===null)return null;const $=oe=>{var de;const{addSelectedEdges:V,unselectNodesAndEdges:le,multiSelectionActive:Te}=D.getState();y&&(D.setState({nodesSelectionActive:!1}),I.selected&&Te?(le({nodes:[],edges:[I]}),(de=w.current)==null||de.blur()):V([e])),o&&o(oe,I)},Z=i?oe=>{i(oe,{...I})}:void 0,Y=a?oe=>{a(oe,{...I})}:void 0,G=l?oe=>{l(oe,{...I})}:void 0,J=c?oe=>{c(oe,{...I})}:void 0,te=d?oe=>{d(oe,{...I})}:void 0,re=oe=>{var V;if(!m&&Kh.includes(oe.key)&&y){const{unselectNodesAndEdges:le,addSelectedEdges:Te}=D.getState();oe.key==="Escape"?((V=w.current)==null||V.blur(),le({edges:[I]})):Te([e])}};return s.jsx("svg",{style:{zIndex:M},children:s.jsxs("g",{className:De(["react-flow__edge",`react-flow__edge-${N}`,I.className,S,{selected:I.selected,animated:I.animated,inactive:!y&&!o,updating:v,selectable:y}]),onClick:$,onDoubleClick:Z,onContextMenu:Y,onMouseEnter:G,onMouseMove:J,onMouseLeave:te,onKeyDown:g?re:void 0,tabIndex:g?0:void 0,role:I.ariaRole??(g?"group":"img"),"aria-roledescription":"edge","data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":I.ariaLabel===null?void 0:I.ariaLabel||`Edge from ${I.source} to ${I.target}`,"aria-describedby":g?`${CA}-${h}`:void 0,ref:w,...I.domAttributes,children:[!b&&s.jsx(x,{id:e,source:I.source,target:I.target,type:I.type,selected:I.selected,animated:I.animated,selectable:y,deletable:I.deletable??!0,label:I.label,labelStyle:I.labelStyle,labelShowBg:I.labelShowBg,labelBgStyle:I.labelBgStyle,labelBgPadding:I.labelBgPadding,labelBgBorderRadius:I.labelBgBorderRadius,sourceX:U,sourceY:P,targetX:_,targetY:F,sourcePosition:k,targetPosition:H,data:I.data,style:I.style,sourceHandleId:I.sourceHandle,targetHandleId:I.targetHandle,markerStart:Q,markerEnd:q,pathOptions:"pathOptions"in I?I.pathOptions:void 0,interactionWidth:I.interactionWidth}),C&&s.jsx(BB,{edge:I,isReconnectable:C,reconnectRadius:E,onReconnect:u,onReconnectStart:T,onReconnectEnd:p,sourceX:U,sourceY:P,targetX:_,targetY:F,sourcePosition:k,targetPosition:H,setUpdateHover:B,setReconnecting:L})]})})}var kB=f.memo(FB);const jB=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function ZA({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:o,onReconnect:i,onEdgeContextMenu:a,onEdgeMouseEnter:l,onEdgeMouseMove:c,onEdgeMouseLeave:d,onEdgeClick:E,reconnectRadius:u,onEdgeDoubleClick:T,onReconnectStart:p,onReconnectEnd:h,disableKeyboardA11y:A}){const{edgesFocusable:S,edgesReconnectable:R,elementsSelectable:m,onError:I}=Ae(jB,ye),O=gB(t);return s.jsxs("div",{className:"react-flow__edges",children:[s.jsx(_B,{defaultColor:e,rfId:n}),O.map(N=>s.jsx(kB,{id:N,edgesFocusable:S,edgesReconnectable:R,elementsSelectable:m,noPanClassName:o,onReconnect:i,onContextMenu:a,onMouseEnter:l,onMouseMove:c,onMouseLeave:d,onClick:E,reconnectRadius:u,onDoubleClick:T,onReconnectStart:p,onReconnectEnd:h,rfId:n,onError:I,edgeTypes:r,disableKeyboardA11y:A},N))]})}ZA.displayName="EdgeRenderer";const GB=f.memo(ZA),HB=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function YB({children:e}){const t=Ae(HB);return s.jsx("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:t},children:e})}function WB(e){const t=ga(),n=f.useRef(!1);f.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const $B=e=>{var t;return(t=e.panZoom)==null?void 0:t.syncViewport};function VB(e){const t=Ae($B),n=Le();return f.useEffect(()=>{e&&(t==null||t(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function XB(e){return e.connection.inProgress?{...e.connection,to:Ko(e.connection.to,e.transform)}:{...e.connection}}function zB(e){return XB}function KB(e){const t=zB();return Ae(t,ye)}const qB=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function JB({containerStyle:e,style:t,type:n,component:r}){const{nodesConnectable:o,width:i,height:a,isValid:l,inProgress:c}=Ae(qB,ye);return!(i&&o&&c)?null:s.jsx("svg",{style:e,width:i,height:a,className:"react-flow__connectionline react-flow__container",children:s.jsx("g",{className:De(["react-flow__connection",Qh(l)]),children:s.jsx(eI,{style:t,type:n,CustomComponent:r,isValid:l})})})}const eI=({style:e,type:t=an.Bezier,CustomComponent:n,isValid:r})=>{const{inProgress:o,from:i,fromNode:a,fromHandle:l,fromPosition:c,to:d,toNode:E,toHandle:u,toPosition:T,pointer:p}=KB();if(!o)return;if(n)return s.jsx(n,{connectionLineType:t,connectionLineStyle:e,fromNode:a,fromHandle:l,fromX:i.x,fromY:i.y,toX:d.x,toY:d.y,fromPosition:c,toPosition:T,connectionStatus:Qh(r),toNode:E,toHandle:u,pointer:p});let h="";const A={sourceX:i.x,sourceY:i.y,sourcePosition:c,targetX:d.x,targetY:d.y,targetPosition:T};switch(t){case an.Bezier:[h]=dA(A);break;case an.SimpleBezier:[h]=GA(A);break;case an.Step:[h]=Xc({...A,borderRadius:0});break;case an.SmoothStep:[h]=Xc(A);break;default:[h]=uA(A)}return s.jsx("path",{d:h,fill:"none",className:"react-flow__connection-path",style:e})};eI.displayName="ConnectionLine";const QB={};function VT(e=QB){f.useRef(e),Le(),f.useEffect(()=>{},[e])}function ZB(){Le(),f.useRef(!1),f.useEffect(()=>{},[])}function tI({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:o,onNodeDoubleClick:i,onEdgeDoubleClick:a,onNodeMouseEnter:l,onNodeMouseMove:c,onNodeMouseLeave:d,onNodeContextMenu:E,onSelectionContextMenu:u,onSelectionStart:T,onSelectionEnd:p,connectionLineType:h,connectionLineStyle:A,connectionLineComponent:S,connectionLineContainerStyle:R,selectionKeyCode:m,selectionOnDrag:I,selectionMode:O,multiSelectionKeyCode:N,panActivationKeyCode:x,zoomActivationKeyCode:g,deleteKeyCode:C,onlyRenderVisibleElements:y,elementsSelectable:w,defaultViewport:v,translateExtent:B,minZoom:b,maxZoom:L,preventScrolling:D,defaultMarkerColor:M,zoomOnScroll:U,zoomOnPinch:P,panOnScroll:_,panOnScrollSpeed:F,panOnScrollMode:k,zoomOnDoubleClick:H,panOnDrag:Q,onPaneClick:q,onPaneMouseEnter:$,onPaneMouseMove:Z,onPaneMouseLeave:Y,onPaneScroll:G,onPaneContextMenu:J,paneClickDistance:te,nodeClickDistance:re,onEdgeContextMenu:oe,onEdgeMouseEnter:V,onEdgeMouseMove:le,onEdgeMouseLeave:Te,reconnectRadius:de,onReconnect:ne,onReconnectStart:Re,onReconnectEnd:Oe,noDragClassName:Fe,noWheelClassName:Nn,noPanClassName:Vt,disableKeyboardA11y:Qn,nodeExtent:Jo,rfId:Xt,viewport:vt,onViewportChange:zt}){return VT(e),VT(t),ZB(),WB(n),VB(vt),s.jsx(fB,{onPaneClick:q,onPaneMouseEnter:$,onPaneMouseMove:Z,onPaneMouseLeave:Y,onPaneContextMenu:J,onPaneScroll:G,paneClickDistance:te,deleteKeyCode:C,selectionKeyCode:m,selectionOnDrag:I,selectionMode:O,onSelectionStart:T,onSelectionEnd:p,multiSelectionKeyCode:N,panActivationKeyCode:x,zoomActivationKeyCode:g,elementsSelectable:w,zoomOnScroll:U,zoomOnPinch:P,zoomOnDoubleClick:H,panOnScroll:_,panOnScrollSpeed:F,panOnScrollMode:k,panOnDrag:Q,defaultViewport:v,translateExtent:B,minZoom:b,maxZoom:L,onSelectionContextMenu:u,preventScrolling:D,noDragClassName:Fe,noWheelClassName:Nn,noPanClassName:Vt,disableKeyboardA11y:Qn,onViewportChange:zt,isControlledViewport:!!vt,children:s.jsxs(YB,{children:[s.jsx(GB,{edgeTypes:t,onEdgeClick:o,onEdgeDoubleClick:a,onReconnect:ne,onReconnectStart:Re,onReconnectEnd:Oe,onlyRenderVisibleElements:y,onEdgeContextMenu:oe,onEdgeMouseEnter:V,onEdgeMouseMove:le,onEdgeMouseLeave:Te,reconnectRadius:de,defaultMarkerColor:M,noPanClassName:Vt,disableKeyboardA11y:Qn,rfId:Xt}),s.jsx(JB,{style:A,type:h,component:S,containerStyle:R}),s.jsx("div",{className:"react-flow__edgelabel-renderer"}),s.jsx(NB,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:i,onNodeMouseEnter:l,onNodeMouseMove:c,onNodeMouseLeave:d,onNodeContextMenu:E,nodeClickDistance:re,onlyRenderVisibleElements:y,noPanClassName:Vt,noDragClassName:Fe,disableKeyboardA11y:Qn,nodeExtent:Jo,rfId:Xt}),s.jsx("div",{className:"react-flow__viewport-portal"})]})})}tI.displayName="GraphView";const eF=f.memo(tI),XT=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:i,fitView:a,fitViewOptions:l,minZoom:c=.5,maxZoom:d=2,nodeOrigin:E,nodeExtent:u,zIndexMode:T="basic"}={})=>{const p=new Map,h=new Map,A=new Map,S=new Map,R=r??t??[],m=n??e??[],I=E??[0,0],O=u??_o;pA(A,S,R);const N=Kc(m,p,h,{nodeOrigin:I,nodeExtent:O,zIndexMode:T});let x=[0,0,1];if(a&&o&&i){const g=Xo(p,{filter:v=>!!((v.width||v.initialWidth)&&(v.height||v.initialHeight))}),{x:C,y,zoom:w}=nE(g,o,i,c,d,(l==null?void 0:l.padding)??.1);x=[C,y,w]}return{rfId:"1",width:o??0,height:i??0,transform:x,nodes:m,nodesInitialized:N,nodeLookup:p,parentLookup:h,edges:R,edgeLookup:S,connectionLookup:A,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:c,maxZoom:d,translateExtent:_o,nodeExtent:O,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:br.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:I,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!0,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:a??!1,fitViewOptions:l,fitViewResolver:null,connection:{...Jh},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:pw,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:qh,zIndexMode:T,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},tF=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:i,fitView:a,fitViewOptions:l,minZoom:c,maxZoom:d,nodeOrigin:E,nodeExtent:u,zIndexMode:T})=>AU((p,h)=>{async function A(){const{nodeLookup:S,panZoom:R,fitViewOptions:m,fitViewResolver:I,width:O,height:N,minZoom:x,maxZoom:g}=h();R&&(await Tw({nodes:S,width:O,height:N,panZoom:R,minZoom:x,maxZoom:g},m),I==null||I.resolve(!0),p({fitViewResolver:null}))}return{...XT({nodes:e,edges:t,width:o,height:i,fitView:a,fitViewOptions:l,minZoom:c,maxZoom:d,nodeOrigin:E,nodeExtent:u,defaultNodes:n,defaultEdges:r,zIndexMode:T}),setNodes:S=>{const{nodeLookup:R,parentLookup:m,nodeOrigin:I,elevateNodesOnSelect:O,fitViewQueued:N,zIndexMode:x}=h(),g=Kc(S,R,m,{nodeOrigin:I,nodeExtent:u,elevateNodesOnSelect:O,checkEquality:!0,zIndexMode:x});N&&g?(A(),p({nodes:S,nodesInitialized:g,fitViewQueued:!1,fitViewOptions:void 0})):p({nodes:S,nodesInitialized:g})},setEdges:S=>{const{connectionLookup:R,edgeLookup:m}=h();pA(R,m,S),p({edges:S})},setDefaultNodesAndEdges:(S,R)=>{if(S){const{setNodes:m}=h();m(S),p({hasDefaultNodes:!0})}if(R){const{setEdges:m}=h();m(R),p({hasDefaultEdges:!0})}},updateNodeInternals:S=>{const{triggerNodeChanges:R,nodeLookup:m,parentLookup:I,domNode:O,nodeOrigin:N,nodeExtent:x,debug:g,fitViewQueued:C,zIndexMode:y}=h(),{changes:w,updatedInternals:v}=Bw(S,m,I,O,N,x,y);v&&(vw(m,I,{nodeOrigin:N,nodeExtent:x,zIndexMode:y}),C?(A(),p({fitViewQueued:!1,fitViewOptions:void 0})):p({}),(w==null?void 0:w.length)>0&&(g&&console.log("React Flow: trigger node changes",w),R==null||R(w)))},updateNodePositions:(S,R=!1)=>{const m=[];let I=[];const{nodeLookup:O,triggerNodeChanges:N,connection:x,updateConnection:g,onNodesChangeMiddlewareMap:C}=h();for(const[y,w]of S){const v=O.get(y),B=!!(v!=null&&v.expandParent&&(v!=null&&v.parentId)&&(w!=null&&w.position)),b={id:y,type:"position",position:B?{x:Math.max(0,w.position.x),y:Math.max(0,w.position.y)}:w.position,dragging:R};if(v&&x.inProgress&&x.fromNode.id===v.id){const L=Wn(v,x.fromHandle,ae.Left,!0);g({...x,from:L})}B&&v.parentId&&m.push({id:y,parentId:v.parentId,rect:{...w.internals.positionAbsolute,width:w.measured.width??0,height:w.measured.height??0}}),I.push(b)}if(m.length>0){const{parentLookup:y,nodeOrigin:w}=h(),v=lE(m,O,y,w);I.push(...v)}for(const y of C.values())I=y(I);N(I)},triggerNodeChanges:S=>{const{onNodesChange:R,setNodes:m,nodes:I,hasDefaultNodes:O,debug:N}=h();if(S!=null&&S.length){if(O){const x=bA(S,I);m(x)}N&&console.log("React Flow: trigger node changes",S),R==null||R(S)}},triggerEdgeChanges:S=>{const{onEdgesChange:R,setEdges:m,edges:I,hasDefaultEdges:O,debug:N}=h();if(S!=null&&S.length){if(O){const x=DA(S,I);m(x)}N&&console.log("React Flow: trigger edge changes",S),R==null||R(S)}},addSelectedNodes:S=>{const{multiSelectionActive:R,edgeLookup:m,nodeLookup:I,triggerNodeChanges:O,triggerEdgeChanges:N}=h();if(R){const x=S.map(g=>Dn(g,!0));O(x);return}O(pr(I,new Set([...S]),!0)),N(pr(m))},addSelectedEdges:S=>{const{multiSelectionActive:R,edgeLookup:m,nodeLookup:I,triggerNodeChanges:O,triggerEdgeChanges:N}=h();if(R){const x=S.map(g=>Dn(g,!0));N(x);return}N(pr(m,new Set([...S]))),O(pr(I,new Set,!0))},unselectNodesAndEdges:({nodes:S,edges:R}={})=>{const{edges:m,nodes:I,nodeLookup:O,triggerNodeChanges:N,triggerEdgeChanges:x}=h(),g=S||I,C=R||m,y=[];for(const v of g){if(!v.selected)continue;const B=O.get(v.id);B&&(B.selected=!1),y.push(Dn(v.id,!1))}const w=[];for(const v of C)v.selected&&w.push(Dn(v.id,!1));N(y),x(w)},setMinZoom:S=>{const{panZoom:R,maxZoom:m}=h();R==null||R.setScaleExtent([S,m]),p({minZoom:S})},setMaxZoom:S=>{const{panZoom:R,minZoom:m}=h();R==null||R.setScaleExtent([m,S]),p({maxZoom:S})},setTranslateExtent:S=>{var R;(R=h().panZoom)==null||R.setTranslateExtent(S),p({translateExtent:S})},resetSelectedElements:()=>{const{edges:S,nodes:R,triggerNodeChanges:m,triggerEdgeChanges:I,elementsSelectable:O}=h();if(!O)return;const N=R.reduce((g,C)=>C.selected?[...g,Dn(C.id,!1)]:g,[]),x=S.reduce((g,C)=>C.selected?[...g,Dn(C.id,!1)]:g,[]);m(N),I(x)},setNodeExtent:S=>{const{nodes:R,nodeLookup:m,parentLookup:I,nodeOrigin:O,elevateNodesOnSelect:N,nodeExtent:x,zIndexMode:g}=h();S[0][0]===x[0][0]&&S[0][1]===x[0][1]&&S[1][0]===x[1][0]&&S[1][1]===x[1][1]||(Kc(R,m,I,{nodeOrigin:O,nodeExtent:S,elevateNodesOnSelect:N,checkEquality:!1,zIndexMode:g}),p({nodeExtent:S}))},panBy:S=>{const{transform:R,width:m,height:I,panZoom:O,translateExtent:N}=h();return Fw({delta:S,panZoom:O,transform:R,translateExtent:N,width:m,height:I})},setCenter:async(S,R,m)=>{const{width:I,height:O,maxZoom:N,panZoom:x}=h();if(!x)return Promise.resolve(!1);const g=typeof(m==null?void 0:m.zoom)<"u"?m.zoom:N;return await x.setViewport({x:I/2-S*g,y:O/2-R*g,zoom:g},{duration:m==null?void 0:m.duration,ease:m==null?void 0:m.ease,interpolate:m==null?void 0:m.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{p({connection:{...Jh}})},updateConnection:S=>{p({connection:S})},reset:()=>p({...XT()})}},Object.is);function nI({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:o,initialHeight:i,initialMinZoom:a,initialMaxZoom:l,initialFitViewOptions:c,fitView:d,nodeOrigin:E,nodeExtent:u,zIndexMode:T,children:p}){const[h]=f.useState(()=>tF({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:i,fitView:d,minZoom:a,maxZoom:l,fitViewOptions:c,nodeOrigin:E,nodeExtent:u,zIndexMode:T}));return s.jsx(IU,{value:h,children:s.jsx(YU,{children:p})})}function nF({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:o,width:i,height:a,fitView:l,fitViewOptions:c,minZoom:d,maxZoom:E,nodeOrigin:u,nodeExtent:T,zIndexMode:p}){return f.useContext(Na)?s.jsx(s.Fragment,{children:e}):s.jsx(nI,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:o,initialWidth:i,initialHeight:a,fitView:l,initialFitViewOptions:c,initialMinZoom:d,initialMaxZoom:E,nodeOrigin:u,nodeExtent:T,zIndexMode:p,children:e})}const rF={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};function oF({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:o,nodeTypes:i,edgeTypes:a,onNodeClick:l,onEdgeClick:c,onInit:d,onMove:E,onMoveStart:u,onMoveEnd:T,onConnect:p,onConnectStart:h,onConnectEnd:A,onClickConnectStart:S,onClickConnectEnd:R,onNodeMouseEnter:m,onNodeMouseMove:I,onNodeMouseLeave:O,onNodeContextMenu:N,onNodeDoubleClick:x,onNodeDragStart:g,onNodeDrag:C,onNodeDragStop:y,onNodesDelete:w,onEdgesDelete:v,onDelete:B,onSelectionChange:b,onSelectionDragStart:L,onSelectionDrag:D,onSelectionDragStop:M,onSelectionContextMenu:U,onSelectionStart:P,onSelectionEnd:_,onBeforeDelete:F,connectionMode:k,connectionLineType:H=an.Bezier,connectionLineStyle:Q,connectionLineComponent:q,connectionLineContainerStyle:$,deleteKeyCode:Z="Backspace",selectionKeyCode:Y="Shift",selectionOnDrag:G=!1,selectionMode:J=bo.Full,panActivationKeyCode:te="Space",multiSelectionKeyCode:re=Mo()?"Meta":"Control",zoomActivationKeyCode:oe=Mo()?"Meta":"Control",snapToGrid:V,snapGrid:le,onlyRenderVisibleElements:Te=!1,selectNodesOnDrag:de,nodesDraggable:ne,autoPanOnNodeFocus:Re,nodesConnectable:Oe,nodesFocusable:Fe,nodeOrigin:Nn=LA,edgesFocusable:Vt,edgesReconnectable:Qn,elementsSelectable:Jo=!0,defaultViewport:Xt=vU,minZoom:vt=.5,maxZoom:zt=2,translateExtent:Qo=_o,preventScrolling:Zo=!0,nodeExtent:$r,defaultMarkerColor:es="#b1b1b7",zoomOnScroll:ba=!0,zoomOnPinch:Kt=!0,panOnScroll:ts=!1,panOnScrollSpeed:qt=.5,panOnScrollMode:ns=Un.Free,zoomOnDoubleClick:Da=!0,panOnDrag:Zn=!0,onPaneClick:Pt,onPaneMouseEnter:rs,onPaneMouseMove:er,onPaneMouseLeave:Vr,onPaneScroll:at,onPaneContextMenu:Ma,paneClickDistance:va=1,nodeClickDistance:Pa=0,children:tr,onReconnect:gn,onReconnectStart:wa,onReconnectEnd:Ua,onEdgeContextMenu:Jt,onEdgeDoubleClick:Ba,onEdgeMouseEnter:os,onEdgeMouseMove:Ze,onEdgeMouseLeave:Qt,reconnectRadius:lt=10,onNodesChange:ss,onEdgesChange:Fa,noDragClassName:ka="nodrag",noWheelClassName:ja="nowheel",noPanClassName:Xr="nopan",fitView:is,fitViewOptions:as,connectOnClick:ls,attributionPosition:Ga,proOptions:Ha,defaultEdgeOptions:Ya,elevateNodesOnSelect:Wa=!0,elevateEdgesOnSelect:cs=!1,disableKeyboardA11y:zr=!1,autoPanOnConnect:ds,autoPanOnNodeDrag:Es,autoPanSpeed:us,connectionRadius:Ts,isValidConnection:fs,onError:ps,style:Ss,id:Kr,nodeDragThreshold:W,connectionDragThreshold:ce,viewport:ge,onViewportChange:Ne,width:xn,height:qr,colorMode:Jr="light",debug:am,onScroll:Rs,ariaLabelConfig:lm,zIndexMode:hE="basic",...cm},dm){const $a=Kr||"1",Em=BU(Jr),um=f.useCallback(AE=>{AE.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),Rs==null||Rs(AE)},[Rs]);return s.jsx("div",{"data-testid":"rf__wrapper",...cm,onScroll:um,style:{...Ss,...rF},ref:dm,className:De(["react-flow",o,Em]),id:Kr,role:"application",children:s.jsxs(nF,{nodes:e,edges:t,width:xn,height:qr,fitView:is,fitViewOptions:as,minZoom:vt,maxZoom:zt,nodeOrigin:Nn,nodeExtent:$r,zIndexMode:hE,children:[s.jsx(eF,{onInit:d,onNodeClick:l,onEdgeClick:c,onNodeMouseEnter:m,onNodeMouseMove:I,onNodeMouseLeave:O,onNodeContextMenu:N,onNodeDoubleClick:x,nodeTypes:i,edgeTypes:a,connectionLineType:H,connectionLineStyle:Q,connectionLineComponent:q,connectionLineContainerStyle:$,selectionKeyCode:Y,selectionOnDrag:G,selectionMode:J,deleteKeyCode:Z,multiSelectionKeyCode:re,panActivationKeyCode:te,zoomActivationKeyCode:oe,onlyRenderVisibleElements:Te,defaultViewport:Xt,translateExtent:Qo,minZoom:vt,maxZoom:zt,preventScrolling:Zo,zoomOnScroll:ba,zoomOnPinch:Kt,zoomOnDoubleClick:Da,panOnScroll:ts,panOnScrollSpeed:qt,panOnScrollMode:ns,panOnDrag:Zn,onPaneClick:Pt,onPaneMouseEnter:rs,onPaneMouseMove:er,onPaneMouseLeave:Vr,onPaneScroll:at,onPaneContextMenu:Ma,paneClickDistance:va,nodeClickDistance:Pa,onSelectionContextMenu:U,onSelectionStart:P,onSelectionEnd:_,onReconnect:gn,onReconnectStart:wa,onReconnectEnd:Ua,onEdgeContextMenu:Jt,onEdgeDoubleClick:Ba,onEdgeMouseEnter:os,onEdgeMouseMove:Ze,onEdgeMouseLeave:Qt,reconnectRadius:lt,defaultMarkerColor:es,noDragClassName:ka,noWheelClassName:ja,noPanClassName:Xr,rfId:$a,disableKeyboardA11y:zr,nodeExtent:$r,viewport:ge,onViewportChange:Ne}),s.jsx(UU,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:p,onConnectStart:h,onConnectEnd:A,onClickConnectStart:S,onClickConnectEnd:R,nodesDraggable:ne,autoPanOnNodeFocus:Re,nodesConnectable:Oe,nodesFocusable:Fe,edgesFocusable:Vt,edgesReconnectable:Qn,elementsSelectable:Jo,elevateNodesOnSelect:Wa,elevateEdgesOnSelect:cs,minZoom:vt,maxZoom:zt,nodeExtent:$r,onNodesChange:ss,onEdgesChange:Fa,snapToGrid:V,snapGrid:le,connectionMode:k,translateExtent:Qo,connectOnClick:ls,defaultEdgeOptions:Ya,fitView:is,fitViewOptions:as,onNodesDelete:w,onEdgesDelete:v,onDelete:B,onNodeDragStart:g,onNodeDrag:C,onNodeDragStop:y,onSelectionDrag:D,onSelectionDragStart:L,onSelectionDragStop:M,onMove:E,onMoveStart:u,onMoveEnd:T,noPanClassName:Xr,nodeOrigin:Nn,rfId:$a,autoPanOnConnect:ds,autoPanOnNodeDrag:Es,autoPanSpeed:us,onError:ps,connectionRadius:Ts,isValidConnection:fs,selectNodesOnDrag:de,nodeDragThreshold:W,connectionDragThreshold:ce,onBeforeDelete:F,debug:am,ariaLabelConfig:lm,zIndexMode:hE}),s.jsx(MU,{onSelectionChange:b}),tr,s.jsx(CU,{proOptions:Ha,position:Ga}),s.jsx(yU,{rfId:$a,disableKeyboardA11y:zr})]})})}var rI=MA(oF);function oI(e){const[t,n]=f.useState(e),r=f.useCallback(o=>n(i=>bA(o,i)),[]);return[t,n,r]}function sI(e){const[t,n]=f.useState(e),r=f.useCallback(o=>n(i=>DA(o,i)),[]);return[t,n,r]}function sF({dimensions:e,lineWidth:t,variant:n,className:r}){return s.jsx("path",{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:De(["react-flow__background-pattern",n,r])})}function iF({radius:e,className:t}){return s.jsx("circle",{cx:e,cy:e,r:e,className:De(["react-flow__background-pattern","dots",t])})}var un;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(un||(un={}));const aF={[un.Dots]:1,[un.Lines]:1,[un.Cross]:6},lF=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function iI({id:e,variant:t=un.Dots,gap:n=20,size:r,lineWidth:o=1,offset:i=0,color:a,bgColor:l,style:c,className:d,patternClassName:E}){const u=f.useRef(null),{transform:T,patternId:p}=Ae(lF,ye),h=r||aF[t],A=t===un.Dots,S=t===un.Cross,R=Array.isArray(n)?n:[n,n],m=[R[0]*T[2]||1,R[1]*T[2]||1],I=h*T[2],O=Array.isArray(i)?i:[i,i],N=S?[I,I]:m,x=[O[0]*T[2]||1+N[0]/2,O[1]*T[2]||1+N[1]/2],g=`${p}${e||""}`;return s.jsxs("svg",{className:De(["react-flow__background",d]),style:{...c,...xa,"--xy-background-color-props":l,"--xy-background-pattern-color-props":a},ref:u,"data-testid":"rf__background",children:[s.jsx("pattern",{id:g,x:T[0]%m[0],y:T[1]%m[1],width:m[0],height:m[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${x[0]},-${x[1]})`,children:A?s.jsx(iF,{radius:I/2,className:E}):s.jsx(sF,{dimensions:N,lineWidth:o,variant:t,className:E})}),s.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${g})`})]})}iI.displayName="Background";const aI=f.memo(iI);function cF(){return s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:s.jsx("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function dF(){return s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:s.jsx("path",{d:"M0 0h32v4.2H0z"})})}function EF(){return s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:s.jsx("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"})})}function uF(){return s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:s.jsx("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"})})}function TF(){return s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:s.jsx("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"})})}function Gs({children:e,className:t,...n}){return s.jsx("button",{type:"button",className:De(["react-flow__controls-button",t]),...n,children:e})}const fF=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function lI({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:o,onZoomIn:i,onZoomOut:a,onFitView:l,onInteractiveChange:c,className:d,children:E,position:u="bottom-left",orientation:T="vertical","aria-label":p}){const h=Le(),{isInteractive:A,minZoomReached:S,maxZoomReached:R,ariaLabelConfig:m}=Ae(fF,ye),{zoomIn:I,zoomOut:O,fitView:N}=ga(),x=()=>{I(),i==null||i()},g=()=>{O(),a==null||a()},C=()=>{N(o),l==null||l()},y=()=>{h.setState({nodesDraggable:!A,nodesConnectable:!A,elementsSelectable:!A}),c==null||c(!A)},w=T==="horizontal"?"horizontal":"vertical";return s.jsxs(Ur,{className:De(["react-flow__controls",w,d]),position:u,style:e,"data-testid":"rf__controls","aria-label":p??m["controls.ariaLabel"],children:[t&&s.jsxs(s.Fragment,{children:[s.jsx(Gs,{onClick:x,className:"react-flow__controls-zoomin",title:m["controls.zoomIn.ariaLabel"],"aria-label":m["controls.zoomIn.ariaLabel"],disabled:R,children:s.jsx(cF,{})}),s.jsx(Gs,{onClick:g,className:"react-flow__controls-zoomout",title:m["controls.zoomOut.ariaLabel"],"aria-label":m["controls.zoomOut.ariaLabel"],disabled:S,children:s.jsx(dF,{})})]}),n&&s.jsx(Gs,{className:"react-flow__controls-fitview",onClick:C,title:m["controls.fitView.ariaLabel"],"aria-label":m["controls.fitView.ariaLabel"],children:s.jsx(EF,{})}),r&&s.jsx(Gs,{className:"react-flow__controls-interactive",onClick:y,title:m["controls.interactive.ariaLabel"],"aria-label":m["controls.interactive.ariaLabel"],children:A?s.jsx(TF,{}):s.jsx(uF,{})}),E]})}lI.displayName="Controls";const pF=f.memo(lI);function SF({id:e,x:t,y:n,width:r,height:o,style:i,color:a,strokeColor:l,strokeWidth:c,className:d,borderRadius:E,shapeRendering:u,selected:T,onClick:p}){const{background:h,backgroundColor:A}=i||{},S=a||h||A;return s.jsx("rect",{className:De(["react-flow__minimap-node",{selected:T},d]),x:t,y:n,rx:E,ry:E,width:r,height:o,style:{fill:S,stroke:l,strokeWidth:c},shapeRendering:u,onClick:p?R=>p(R,e):void 0})}const RF=f.memo(SF),hF=e=>e.nodes.map(t=>t.id),_l=e=>e instanceof Function?e:()=>e;function AF({nodeStrokeColor:e,nodeColor:t,nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:o,nodeComponent:i=RF,onClick:a}){const l=Ae(hF,ye),c=_l(t),d=_l(e),E=_l(n),u=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return s.jsx(s.Fragment,{children:l.map(T=>s.jsx(mF,{id:T,nodeColorFunc:c,nodeStrokeColorFunc:d,nodeClassNameFunc:E,nodeBorderRadius:r,nodeStrokeWidth:o,NodeComponent:i,onClick:a,shapeRendering:u},T))})}function IF({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:o,nodeStrokeWidth:i,shapeRendering:a,NodeComponent:l,onClick:c}){const{node:d,x:E,y:u,width:T,height:p}=Ae(h=>{const A=h.nodeLookup.get(e);if(!A)return{node:void 0,x:0,y:0,width:0,height:0};const S=A.internals.userNode,{x:R,y:m}=A.internals.positionAbsolute,{width:I,height:O}=$t(S);return{node:S,x:R,y:m,width:I,height:O}},ye);return!d||d.hidden||!oA(d)?null:s.jsx(l,{x:E,y:u,width:T,height:p,style:d.style,selected:!!d.selected,className:r(d),color:t(d),borderRadius:o,strokeColor:n(d),strokeWidth:i,shapeRendering:a,onClick:c,id:d.id})}const mF=f.memo(IF);var OF=f.memo(AF);const NF=200,gF=150,xF=e=>!e.hidden,yF=e=>{const t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};return{viewBB:t,boundingRect:e.nodeLookup.size>0?rA(Xo(e.nodeLookup,{filter:xF}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},CF="react-flow__minimap-desc";function cI({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:o="",nodeBorderRadius:i=5,nodeStrokeWidth:a,nodeComponent:l,bgColor:c,maskColor:d,maskStrokeColor:E,maskStrokeWidth:u,position:T="bottom-right",onClick:p,onNodeClick:h,pannable:A=!1,zoomable:S=!1,ariaLabel:R,inversePan:m,zoomStep:I=1,offsetScale:O=5}){const N=Le(),x=f.useRef(null),{boundingRect:g,viewBB:C,rfId:y,panZoom:w,translateExtent:v,flowWidth:B,flowHeight:b,ariaLabelConfig:L}=Ae(yF,ye),D=(e==null?void 0:e.width)??NF,M=(e==null?void 0:e.height)??gF,U=g.width/D,P=g.height/M,_=Math.max(U,P),F=_*D,k=_*M,H=O*_,Q=g.x-(F-g.width)/2-H,q=g.y-(k-g.height)/2-H,$=F+H*2,Z=k+H*2,Y=`${CF}-${y}`,G=f.useRef(0),J=f.useRef();G.current=_,f.useEffect(()=>{if(x.current&&w)return J.current=Xw({domNode:x.current,panZoom:w,getTransform:()=>N.getState().transform,getViewScale:()=>G.current}),()=>{var V;(V=J.current)==null||V.destroy()}},[w]),f.useEffect(()=>{var V;(V=J.current)==null||V.update({translateExtent:v,width:B,height:b,inversePan:m,pannable:A,zoomStep:I,zoomable:S})},[A,S,m,I,v,B,b]);const te=p?V=>{var de;const[le,Te]=((de=J.current)==null?void 0:de.pointer(V))||[0,0];p(V,{x:le,y:Te})}:void 0,re=h?f.useCallback((V,le)=>{const Te=N.getState().nodeLookup.get(le).internals.userNode;h(V,Te)},[]):void 0,oe=R??L["minimap.ariaLabel"];return s.jsx(Ur,{position:T,style:{...e,"--xy-minimap-background-color-props":typeof c=="string"?c:void 0,"--xy-minimap-mask-background-color-props":typeof d=="string"?d:void 0,"--xy-minimap-mask-stroke-color-props":typeof E=="string"?E:void 0,"--xy-minimap-mask-stroke-width-props":typeof u=="number"?u*_:void 0,"--xy-minimap-node-background-color-props":typeof r=="string"?r:void 0,"--xy-minimap-node-stroke-color-props":typeof n=="string"?n:void 0,"--xy-minimap-node-stroke-width-props":typeof a=="number"?a:void 0},className:De(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:s.jsxs("svg",{width:D,height:M,viewBox:`${Q} ${q} ${$} ${Z}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":Y,ref:x,onClick:te,children:[oe&&s.jsx("title",{id:Y,children:oe}),s.jsx(OF,{onClick:re,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:i,nodeClassName:o,nodeStrokeWidth:a,nodeComponent:l}),s.jsx("path",{className:"react-flow__minimap-mask",d:`M${Q-H},${q-H}h${$+H*2}v${Z+H*2}h${-$-H*2}z
|
|
767
|
-
M${C.x},${C.y}h${C.width}v${C.height}h${-C.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}cI.displayName="MiniMap";const LF=f.memo(cI),_F=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,bF={[wr.Line]:"right",[wr.Handle]:"bottom-right"};function DF({nodeId:e,position:t,variant:n=wr.Handle,className:r,style:o=void 0,children:i,color:a,minWidth:l=10,minHeight:c=10,maxWidth:d=Number.MAX_VALUE,maxHeight:E=Number.MAX_VALUE,keepAspectRatio:u=!1,resizeDirection:T,autoScale:p=!0,shouldResize:h,onResizeStart:A,onResize:S,onResizeEnd:R}){const m=UA(),I=typeof e=="string"?e:m,O=Le(),N=f.useRef(null),x=n===wr.Handle,g=Ae(f.useCallback(_F(x&&p),[x,p]),ye),C=f.useRef(null),y=t??bF[n];f.useEffect(()=>{if(!(!N.current||!I))return C.current||(C.current=aU({domNode:N.current,nodeId:I,getStoreItems:()=>{const{nodeLookup:v,transform:B,snapGrid:b,snapToGrid:L,nodeOrigin:D,domNode:M}=O.getState();return{nodeLookup:v,transform:B,snapGrid:b,snapToGrid:L,nodeOrigin:D,paneDomNode:M}},onChange:(v,B)=>{const{triggerNodeChanges:b,nodeLookup:L,parentLookup:D,nodeOrigin:M}=O.getState(),U=[],P={x:v.x,y:v.y},_=L.get(I);if(_&&_.expandParent&&_.parentId){const F=_.origin??M,k=v.width??_.measured.width??0,H=v.height??_.measured.height??0,Q={id:_.id,parentId:_.parentId,rect:{width:k,height:H,...sA({x:v.x??_.position.x,y:v.y??_.position.y},{width:k,height:H},_.parentId,L,F)}},q=lE([Q],L,D,M);U.push(...q),P.x=v.x?Math.max(F[0]*k,v.x):void 0,P.y=v.y?Math.max(F[1]*H,v.y):void 0}if(P.x!==void 0&&P.y!==void 0){const F={id:I,type:"position",position:{...P}};U.push(F)}if(v.width!==void 0&&v.height!==void 0){const k={id:I,type:"dimensions",resizing:!0,setAttributes:T?T==="horizontal"?"width":"height":!0,dimensions:{width:v.width,height:v.height}};U.push(k)}for(const F of B){const k={...F,type:"position"};U.push(k)}b(U)},onEnd:({width:v,height:B})=>{const b={id:I,type:"dimensions",resizing:!1,dimensions:{width:v,height:B}};O.getState().triggerNodeChanges([b])}})),C.current.update({controlPosition:y,boundaries:{minWidth:l,minHeight:c,maxWidth:d,maxHeight:E},keepAspectRatio:u,resizeDirection:T,onResizeStart:A,onResize:S,onResizeEnd:R,shouldResize:h}),()=>{var v;(v=C.current)==null||v.destroy()}},[y,l,c,d,E,u,A,S,R,h]);const w=y.split("-");return s.jsx("div",{className:De(["react-flow__resize-control","nodrag",...w,n,r]),ref:N,style:{...o,scale:g,...a&&{[x?"backgroundColor":"borderColor"]:a}},children:i})}f.memo(DF);var dI=Object.defineProperty,MF=(e,t,n)=>t in e?dI(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,vF=(e,t)=>{for(var n in t)dI(e,n,{get:t[n],enumerable:!0})},PF=(e,t,n)=>MF(e,t+"",n),EI={};vF(EI,{Graph:()=>it,alg:()=>dE,json:()=>TI,version:()=>BF});var wF=Object.defineProperty,uI=(e,t)=>{for(var n in t)wF(e,n,{get:t[n],enumerable:!0})},it=class{constructor(e){this._isDirected=!0,this._isMultigraph=!1,this._isCompound=!1,this._nodes={},this._in={},this._preds={},this._out={},this._sucs={},this._edgeObjs={},this._edgeLabels={},this._nodeCount=0,this._edgeCount=0,this._defaultNodeLabelFn=()=>{},this._defaultEdgeLabelFn=()=>{},e&&(this._isDirected="directed"in e?e.directed:!0,this._isMultigraph="multigraph"in e?e.multigraph:!1,this._isCompound="compound"in e?e.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children["\0"]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(e){return this._label=e,this}graph(){return this._label}setDefaultNodeLabel(e){return typeof e!="function"?this._defaultNodeLabelFn=()=>e:this._defaultNodeLabelFn=e,this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){return this.nodes().filter(e=>Object.keys(this._in[e]).length===0)}sinks(){return this.nodes().filter(e=>Object.keys(this._out[e]).length===0)}setNodes(e,t){return e.forEach(n=>{t!==void 0?this.setNode(n,t):this.setNode(n)}),this}setNode(e,t){return e in this._nodes?(arguments.length>1&&(this._nodes[e]=t),this):(this._nodes[e]=arguments.length>1?t:this._defaultNodeLabelFn(e),this._isCompound&&(this._parent[e]="\0",this._children[e]={},this._children["\0"][e]=!0),this._in[e]={},this._preds[e]={},this._out[e]={},this._sucs[e]={},++this._nodeCount,this)}node(e){return this._nodes[e]}hasNode(e){return e in this._nodes}removeNode(e){if(e in this._nodes){let t=n=>this.removeEdge(this._edgeObjs[n]);delete this._nodes[e],this._isCompound&&(this._removeFromParentsChildList(e),delete this._parent[e],this.children(e).forEach(n=>{this.setParent(n)}),delete this._children[e]),Object.keys(this._in[e]).forEach(t),delete this._in[e],delete this._preds[e],Object.keys(this._out[e]).forEach(t),delete this._out[e],delete this._sucs[e],--this._nodeCount}return this}setParent(e,t){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(t===void 0)t="\0";else{t+="";for(let n=t;n!==void 0;n=this.parent(n))if(n===e)throw new Error("Setting "+t+" as parent of "+e+" would create a cycle");this.setNode(t)}return this.setNode(e),this._removeFromParentsChildList(e),this._parent[e]=t,this._children[t][e]=!0,this}parent(e){if(this._isCompound){let t=this._parent[e];if(t!=="\0")return t}}children(e="\0"){if(this._isCompound){let t=this._children[e];if(t)return Object.keys(t)}else{if(e==="\0")return this.nodes();if(this.hasNode(e))return[]}return[]}predecessors(e){let t=this._preds[e];if(t)return Object.keys(t)}successors(e){let t=this._sucs[e];if(t)return Object.keys(t)}neighbors(e){let t=this.predecessors(e);if(t){let n=new Set(t);for(let r of this.successors(e))n.add(r);return Array.from(n.values())}}isLeaf(e){let t;return this.isDirected()?t=this.successors(e):t=this.neighbors(e),t.length===0}filterNodes(e){let t=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});t.setGraph(this.graph()),Object.entries(this._nodes).forEach(([o,i])=>{e(o)&&t.setNode(o,i)}),Object.values(this._edgeObjs).forEach(o=>{t.hasNode(o.v)&&t.hasNode(o.w)&&t.setEdge(o,this.edge(o))});let n={},r=o=>{let i=this.parent(o);return!i||t.hasNode(i)?(n[o]=i??void 0,i??void 0):i in n?n[i]:r(i)};return this._isCompound&&t.nodes().forEach(o=>t.setParent(o,r(o))),t}setDefaultEdgeLabel(e){return typeof e!="function"?this._defaultEdgeLabelFn=()=>e:this._defaultEdgeLabelFn=e,this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(e,t){return e.reduce((n,r)=>(t!==void 0?this.setEdge(n,r,t):this.setEdge(n,r),r)),this}setEdge(e,t,n,r){let o,i,a,l,c=!1;typeof e=="object"&&e!==null&&"v"in e?(o=e.v,i=e.w,a=e.name,arguments.length===2&&(l=t,c=!0)):(o=e,i=t,a=r,arguments.length>2&&(l=n,c=!0)),o=""+o,i=""+i,a!==void 0&&(a=""+a);let d=ao(this._isDirected,o,i,a);if(d in this._edgeLabels)return c&&(this._edgeLabels[d]=l),this;if(a!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(o),this.setNode(i),this._edgeLabels[d]=c?l:this._defaultEdgeLabelFn(o,i,a);let E=UF(this._isDirected,o,i,a);return o=E.v,i=E.w,Object.freeze(E),this._edgeObjs[d]=E,zT(this._preds[i],o),zT(this._sucs[o],i),this._in[i][d]=E,this._out[o][d]=E,this._edgeCount++,this}edge(e,t,n){let r=arguments.length===1?bl(this._isDirected,e):ao(this._isDirected,e,t,n);return this._edgeLabels[r]}edgeAsObj(e,t,n){let r=arguments.length===1?this.edge(e):this.edge(e,t,n);return typeof r!="object"?{label:r}:r}hasEdge(e,t,n){return(arguments.length===1?bl(this._isDirected,e):ao(this._isDirected,e,t,n))in this._edgeLabels}removeEdge(e,t,n){let r=arguments.length===1?bl(this._isDirected,e):ao(this._isDirected,e,t,n),o=this._edgeObjs[r];if(o){let i=o.v,a=o.w;delete this._edgeLabels[r],delete this._edgeObjs[r],KT(this._preds[a],i),KT(this._sucs[i],a),delete this._in[a][r],delete this._out[i][r],this._edgeCount--}return this}inEdges(e,t){return this.isDirected()?this.filterEdges(this._in[e],e,t):this.nodeEdges(e,t)}outEdges(e,t){return this.isDirected()?this.filterEdges(this._out[e],e,t):this.nodeEdges(e,t)}nodeEdges(e,t){if(e in this._nodes)return this.filterEdges({...this._in[e],...this._out[e]},e,t)}_removeFromParentsChildList(e){delete this._children[this._parent[e]][e]}filterEdges(e,t,n){if(!e)return;let r=Object.values(e);return n?r.filter(o=>o.v===t&&o.w===n||o.v===n&&o.w===t):r}};function zT(e,t){e[t]?e[t]++:e[t]=1}function KT(e,t){e[t]!==void 0&&!--e[t]&&delete e[t]}function ao(e,t,n,r){let o=""+t,i=""+n;if(!e&&o>i){let a=o;o=i,i=a}return o+""+i+""+(r===void 0?"\0":r)}function UF(e,t,n,r){let o=""+t,i=""+n;if(!e&&o>i){let l=o;o=i,i=l}let a={v:o,w:i};return r&&(a.name=r),a}function bl(e,t){return ao(e,t.v,t.w,t.name)}var BF="4.0.1",TI={};uI(TI,{read:()=>GF,write:()=>FF});function FF(e){let t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:kF(e),edges:jF(e)},n=e.graph();return n!==void 0&&(t.value=structuredClone(n)),t}function kF(e){return e.nodes().map(t=>{let n=e.node(t),r=e.parent(t),o={v:t};return n!==void 0&&(o.value=n),r!==void 0&&(o.parent=r),o})}function jF(e){return e.edges().map(t=>{let n=e.edge(t),r={v:t.v,w:t.w};return t.name!==void 0&&(r.name=t.name),n!==void 0&&(r.value=n),r})}function GF(e){let t=new it(e.options);return e.value!==void 0&&t.setGraph(e.value),e.nodes.forEach(n=>{t.setNode(n.v,n.value),n.parent&&t.setParent(n.v,n.parent)}),e.edges.forEach(n=>{t.setEdge({v:n.v,w:n.w,name:n.name},n.value)}),t}var dE={};uI(dE,{CycleException:()=>Ui,bellmanFord:()=>fI,components:()=>WF,dijkstra:()=>wi,dijkstraAll:()=>XF,findCycles:()=>zF,floydWarshall:()=>qF,isAcyclic:()=>QF,postorder:()=>e2,preorder:()=>t2,prim:()=>n2,shortestPaths:()=>r2,tarjan:()=>SI,topsort:()=>RI});var HF=()=>1;function fI(e,t,n,r){return YF(e,String(t),n||HF,r||function(o){return e.outEdges(o)})}function YF(e,t,n,r){let o={},i,a=0,l=e.nodes(),c=function(u){let T=n(u);o[u.v].distance+T<o[u.w].distance&&(o[u.w]={distance:o[u.v].distance+T,predecessor:u.v},i=!0)},d=function(){l.forEach(function(u){r(u).forEach(function(T){let p=T.v===u?T.v:T.w,h=p===T.v?T.w:T.v;c({v:p,w:h})})})};l.forEach(function(u){let T=u===t?0:Number.POSITIVE_INFINITY;o[u]={distance:T,predecessor:""}});let E=l.length;for(let u=1;u<E&&(i=!1,a++,d(),!!i);u++);if(a===E-1&&(i=!1,d(),i))throw new Error("The graph contains a negative weight cycle");return o}function WF(e){let t={},n=[],r;function o(i){i in t||(t[i]=!0,r.push(i),e.successors(i).forEach(o),e.predecessors(i).forEach(o))}return e.nodes().forEach(function(i){r=[],o(i),r.length&&n.push(r)}),n}var pI=class{constructor(){this._arr=[],this._keyIndices={}}size(){return this._arr.length}keys(){return this._arr.map(e=>e.key)}has(e){return e in this._keyIndices}priority(e){let t=this._keyIndices[e];if(t!==void 0)return this._arr[t].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(e,t){let n=this._keyIndices,r=String(e);if(!(r in n)){let o=this._arr,i=o.length;return n[r]=i,o.push({key:r,priority:t}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);let e=this._arr.pop();return delete this._keyIndices[e.key],this._heapify(0),e.key}decrease(e,t){let n=this._keyIndices[e];if(n===void 0)throw new Error(`Key not found: ${e}`);let r=this._arr[n].priority;if(t>r)throw new Error(`New priority is greater than current priority. Key: ${e} Old: ${r} New: ${t}`);this._arr[n].priority=t,this._decrease(n)}_heapify(e){let t=this._arr,n=2*e,r=n+1,o=e;n<t.length&&(o=t[n].priority<t[o].priority?n:o,r<t.length&&(o=t[r].priority<t[o].priority?r:o),o!==e&&(this._swap(e,o),this._heapify(o)))}_decrease(e){let t=this._arr,n=t[e].priority,r;for(;e!==0&&(r=e>>1,!(t[r].priority<n));)this._swap(e,r),e=r}_swap(e,t){let n=this._arr,r=this._keyIndices,o=n[e],i=n[t];n[e]=i,n[t]=o,r[i.key]=e,r[o.key]=t}},$F=()=>1;function wi(e,t,n,r){let o=function(i){return e.outEdges(i)};return VF(e,String(t),n||$F,r||o)}function VF(e,t,n,r){let o={},i=new pI,a,l,c=function(d){let E=d.v!==a?d.v:d.w,u=o[E],T=n(d),p=l.distance+T;if(T<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+d+" Weight: "+T);p<u.distance&&(u.distance=p,u.predecessor=a,i.decrease(E,p))};for(e.nodes().forEach(function(d){let E=d===t?0:Number.POSITIVE_INFINITY;o[d]={distance:E,predecessor:""},i.add(d,E)});i.size()>0&&(a=i.removeMin(),l=o[a],l.distance!==Number.POSITIVE_INFINITY);)r(a).forEach(c);return o}function XF(e,t,n){return e.nodes().reduce(function(r,o){return r[o]=wi(e,o,t,n),r},{})}function SI(e){let t=0,n=[],r={},o=[];function i(a){let l=r[a]={onStack:!0,lowlink:t,index:t++};if(n.push(a),e.successors(a).forEach(function(c){c in r?r[c].onStack&&(l.lowlink=Math.min(l.lowlink,r[c].index)):(i(c),l.lowlink=Math.min(l.lowlink,r[c].lowlink))}),l.lowlink===l.index){let c=[],d;do d=n.pop(),r[d].onStack=!1,c.push(d);while(a!==d);o.push(c)}}return e.nodes().forEach(function(a){a in r||i(a)}),o}function zF(e){return SI(e).filter(function(t){return t.length>1||t.length===1&&e.hasEdge(t[0],t[0])})}var KF=()=>1;function qF(e,t,n){return JF(e,t||KF,n||function(r){return e.outEdges(r)})}function JF(e,t,n){let r={},o=e.nodes();return o.forEach(function(i){r[i]={},r[i][i]={distance:0,predecessor:""},o.forEach(function(a){i!==a&&(r[i][a]={distance:Number.POSITIVE_INFINITY,predecessor:""})}),n(i).forEach(function(a){let l=a.v===i?a.w:a.v,c=t(a);r[i][l]={distance:c,predecessor:i}})}),o.forEach(function(i){let a=r[i];o.forEach(function(l){let c=r[l];o.forEach(function(d){let E=c[i],u=a[d],T=c[d],p=E.distance+u.distance;p<T.distance&&(T.distance=p,T.predecessor=u.predecessor)})})}),r}var Ui=class extends Error{constructor(...e){super(...e)}};function RI(e){let t={},n={},r=[];function o(i){if(i in n)throw new Ui;i in t||(n[i]=!0,t[i]=!0,e.predecessors(i).forEach(o),delete n[i],r.push(i))}if(e.sinks().forEach(o),Object.keys(t).length!==e.nodeCount())throw new Ui;return r}function QF(e){try{RI(e)}catch(t){if(t instanceof Ui)return!1;throw t}return!0}function ZF(e,t,n,r,o){Array.isArray(t)||(t=[t]);let i=(l=>{var c;return(c=e.isDirected()?e.successors(l):e.neighbors(l))!=null?c:[]}),a={};return t.forEach(function(l){if(!e.hasNode(l))throw new Error("Graph does not have node: "+l);o=hI(e,l,n==="post",a,i,r,o)}),o}function hI(e,t,n,r,o,i,a){return t in r||(r[t]=!0,n||(a=i(a,t)),o(t).forEach(function(l){a=hI(e,l,n,r,o,i,a)}),n&&(a=i(a,t))),a}function AI(e,t,n){return ZF(e,t,n,function(r,o){return r.push(o),r},[])}function e2(e,t){return AI(e,t,"post")}function t2(e,t){return AI(e,t,"pre")}function n2(e,t){let n=new it,r={},o=new pI,i;function a(c){let d=c.v===i?c.w:c.v,E=o.priority(d);if(E!==void 0){let u=t(c);u<E&&(r[d]=i,o.decrease(d,u))}}if(e.nodeCount()===0)return n;e.nodes().forEach(function(c){o.add(c,Number.POSITIVE_INFINITY),n.setNode(c)}),o.decrease(e.nodes()[0],0);let l=!1;for(;o.size()>0;){if(i=o.removeMin(),i in r)n.setEdge(i,r[i]);else{if(l)throw new Error("Input graph is not connected: "+e);l=!0}e.nodeEdges(i).forEach(a)}return n}function r2(e,t,n,r){return o2(e,t,n,r??(o=>{let i=e.outEdges(o);return i??[]}))}function o2(e,t,n,r){if(n===void 0)return wi(e,t,n,r);let o=!1,i=e.nodes();for(let a=0;a<i.length;a++){let l=r(i[a]);for(let c=0;c<l.length;c++){let d=l[c],E=d.v===i[a]?d.v:d.w,u=E===d.v?d.w:d.v;n({v:E,w:u})<0&&(o=!0)}if(o)return fI(e,t,n,r)}return wi(e,t,n,r)}function Yr(e,t,n,r){let o=r;for(;e.hasNode(o);)o=EE(r);return n.dummy=t,e.setNode(o,n),o}function s2(e){let t=new it().setGraph(e.graph());return e.nodes().forEach(n=>t.setNode(n,e.node(n))),e.edges().forEach(n=>{let r=t.edge(n.v,n.w)||{weight:0,minlen:1},o=e.edge(n);t.setEdge(n.v,n.w,{weight:r.weight+o.weight,minlen:Math.max(r.minlen,o.minlen)})}),t}function II(e){let t=new it({multigraph:e.isMultigraph()}).setGraph(e.graph());return e.nodes().forEach(n=>{e.children(n).length||t.setNode(n,e.node(n))}),e.edges().forEach(n=>{t.setEdge(n,e.edge(n))}),t}function qT(e,t){let n=e.x,r=e.y,o=t.x-n,i=t.y-r,a=e.width/2,l=e.height/2;if(!o&&!i)throw new Error("Not possible to find intersection inside of the rectangle");let c,d;return Math.abs(i)*a>Math.abs(o)*l?(i<0&&(l=-l),c=l*o/i,d=l):(o<0&&(a=-a),c=a,d=a*i/o),{x:n+c,y:r+d}}function qo(e){let t=Po(OI(e)+1).map(()=>[]);return e.nodes().forEach(n=>{let r=e.node(n),o=r.rank;o!==void 0&&(t[o]||(t[o]=[]),t[o][r.order]=n)}),t}function i2(e){let t=e.nodes().map(r=>{let o=e.node(r).rank;return o===void 0?Number.MAX_VALUE:o}),n=Ct(Math.min,t);e.nodes().forEach(r=>{let o=e.node(r);Object.hasOwn(o,"rank")&&(o.rank-=n)})}function a2(e){let t=e.nodes().map(a=>e.node(a).rank).filter(a=>a!==void 0),n=Ct(Math.min,t),r=[];e.nodes().forEach(a=>{let l=e.node(a).rank-n;r[l]||(r[l]=[]),r[l].push(a)});let o=0,i=e.graph().nodeRankFactor;Array.from(r).forEach((a,l)=>{a===void 0&&l%i!==0?--o:a!==void 0&&o&&a.forEach(c=>e.node(c).rank+=o)})}function JT(e,t,n,r){let o={width:0,height:0};return arguments.length>=4&&(o.rank=n,o.order=r),Yr(e,"border",o,t)}function l2(e,t=mI){let n=[];for(let r=0;r<e.length;r+=t){let o=e.slice(r,r+t);n.push(o)}return n}var mI=65535;function Ct(e,t){if(t.length>mI){let n=l2(t);return e(...n.map(r=>e(...r)))}else return e(...t)}function OI(e){let t=e.nodes().map(n=>{let r=e.node(n).rank;return r===void 0?Number.MIN_VALUE:r});return Ct(Math.max,t)}function c2(e,t){let n={lhs:[],rhs:[]};return e.forEach(r=>{t(r)?n.lhs.push(r):n.rhs.push(r)}),n}function NI(e,t){let n=Date.now();try{return t()}finally{console.log(e+" time: "+(Date.now()-n)+"ms")}}function gI(e,t){return t()}var d2=0;function EE(e){let t=++d2;return e+(""+t)}function Po(e,t,n=1){t==null&&(t=e,e=0);let r=i=>i<t;n<0&&(r=i=>t<i);let o=[];for(let i=e;r(i);i+=n)o.push(i);return o}function Bi(e,t){let n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return n}function Ca(e,t){let n;return typeof t=="string"?n=r=>r[t]:n=t,Object.entries(e).reduce((r,[o,i])=>(r[o]=n(i,o),r),{})}function E2(e,t){return e.reduce((n,r,o)=>(n[r]=t[o],n),{})}var La="\0",u2="3.0.0",T2=class{constructor(){PF(this,"_sentinel");let e={};e._next=e._prev=e,this._sentinel=e}dequeue(){let e=this._sentinel,t=e._prev;if(t!==e)return QT(t),t}enqueue(e){let t=this._sentinel;e._prev&&e._next&&QT(e),e._next=t._next,t._next._prev=e,t._next=e,e._prev=t}toString(){let e=[],t=this._sentinel,n=t._prev;for(;n!==t;)e.push(JSON.stringify(n,f2)),n=n._prev;return"["+e.join(", ")+"]"}};function QT(e){e._prev._next=e._next,e._next._prev=e._prev,delete e._next,delete e._prev}function f2(e,t){if(e!=="_next"&&e!=="_prev")return t}var p2=T2,S2=()=>1;function R2(e,t){if(e.nodeCount()<=1)return[];let n=A2(e,t||S2);return h2(n.graph,n.buckets,n.zeroIdx).flatMap(r=>e.outEdges(r.v,r.w)||[])}function h2(e,t,n){var r;let o=[],i=t[t.length-1],a=t[0],l;for(;e.nodeCount();){for(;l=a.dequeue();)Dl(e,t,n,l);for(;l=i.dequeue();)Dl(e,t,n,l);if(e.nodeCount()){for(let c=t.length-2;c>0;--c)if(l=(r=t[c])==null?void 0:r.dequeue(),l){o=o.concat(Dl(e,t,n,l,!0)||[]);break}}}return o}function Dl(e,t,n,r,o){let i=[],a=o?i:void 0;return(e.inEdges(r.v)||[]).forEach(l=>{let c=e.edge(l),d=e.node(l.v);o&&i.push({v:l.v,w:l.w}),d.out-=c,Qc(t,n,d)}),(e.outEdges(r.v)||[]).forEach(l=>{let c=e.edge(l),d=l.w,E=e.node(d);E.in-=c,Qc(t,n,E)}),e.removeNode(r.v),a}function A2(e,t){let n=new it,r=0,o=0;e.nodes().forEach(l=>{n.setNode(l,{v:l,in:0,out:0})}),e.edges().forEach(l=>{let c=n.edge(l.v,l.w)||0,d=t(l),E=c+d;n.setEdge(l.v,l.w,E);let u=n.node(l.v),T=n.node(l.w);o=Math.max(o,u.out+=d),r=Math.max(r,T.in+=d)});let i=I2(o+r+3).map(()=>new p2),a=r+1;return n.nodes().forEach(l=>{Qc(i,a,n.node(l))}),{graph:n,buckets:i,zeroIdx:a}}function Qc(e,t,n){var r,o,i;n.out?n.in?(i=e[n.out-n.in+t])==null||i.enqueue(n):(o=e[e.length-1])==null||o.enqueue(n):(r=e[0])==null||r.enqueue(n)}function I2(e){let t=[];for(let n=0;n<e;n++)t.push(n);return t}function m2(e){(e.graph().acyclicer==="greedy"?R2(e,t(e)):O2(e)).forEach(n=>{let r=e.edge(n);e.removeEdge(n),r.forwardName=n.name,r.reversed=!0,e.setEdge(n.w,n.v,r,EE("rev"))});function t(n){return r=>n.edge(r).weight}}function O2(e){let t=[],n={},r={};function o(i){Object.hasOwn(r,i)||(r[i]=!0,n[i]=!0,e.outEdges(i).forEach(a=>{Object.hasOwn(n,a.w)?t.push(a):o(a.w)}),delete n[i])}return e.nodes().forEach(o),t}function N2(e){e.edges().forEach(t=>{let n=e.edge(t);if(n.reversed){e.removeEdge(t);let r=n.forwardName;delete n.reversed,delete n.forwardName,e.setEdge(t.w,t.v,n,r)}})}function g2(e){e.graph().dummyChains=[],e.edges().forEach(t=>x2(e,t))}function x2(e,t){let n=t.v,r=e.node(n).rank,o=t.w,i=e.node(o).rank,a=t.name,l=e.edge(t),c=l.labelRank;if(i===r+1)return;e.removeEdge(t);let d,E,u;for(u=0,++r;r<i;++u,++r)l.points=[],E={width:0,height:0,edgeLabel:l,edgeObj:t,rank:r},d=Yr(e,"edge",E,"_d"),r===c&&(E.width=l.width,E.height=l.height,E.dummy="edge-label",E.labelpos=l.labelpos),e.setEdge(n,d,{weight:l.weight},a),u===0&&e.graph().dummyChains.push(d),n=d;e.setEdge(n,o,{weight:l.weight},a)}function y2(e){e.graph().dummyChains.forEach(t=>{let n=e.node(t),r=n.edgeLabel,o;for(e.setEdge(n.edgeObj,r);n.dummy;)o=e.successors(t)[0],e.removeNode(t),r.points.push({x:n.x,y:n.y}),n.dummy==="edge-label"&&(r.x=n.x,r.y=n.y,r.width=n.width,r.height=n.height),t=o,n=e.node(t)})}function uE(e){let t={};function n(r){let o=e.node(r);if(Object.hasOwn(t,r))return o.rank;t[r]=!0;let i=e.outEdges(r),a=i?i.map(c=>c==null?Number.POSITIVE_INFINITY:n(c.w)-e.edge(c).minlen):[],l=Ct(Math.min,a);return l===Number.POSITIVE_INFINITY&&(l=0),o.rank=l}e.sources().forEach(n)}function Br(e,t){return e.node(t.w).rank-e.node(t.v).rank-e.edge(t).minlen}var xI=C2;function C2(e){let t=new it({directed:!1}),n=e.nodes();if(n.length===0)throw new Error("Graph must have at least one node");let r=n[0],o=e.nodeCount();t.setNode(r,{});let i,a;for(;L2(t,e)<o&&(i=_2(t,e),!!i);)a=t.hasNode(i.v)?Br(e,i):-Br(e,i),b2(t,e,a);return t}function L2(e,t){function n(r){let o=t.nodeEdges(r);o&&o.forEach(i=>{let a=i.v,l=r===a?i.w:a;!e.hasNode(l)&&!Br(t,i)&&(e.setNode(l,{}),e.setEdge(r,l,{}),n(l))})}return e.nodes().forEach(n),e.nodeCount()}function _2(e,t){return t.edges().reduce((n,r)=>{let o=Number.POSITIVE_INFINITY;return e.hasNode(r.v)!==e.hasNode(r.w)&&(o=Br(t,r)),o<n[0]?[o,r]:n},[Number.POSITIVE_INFINITY,null])[1]}function b2(e,t,n){e.nodes().forEach(r=>t.node(r).rank+=n)}var{preorder:D2,postorder:M2}=dE,v2=qn;qn.initLowLimValues=fE;qn.initCutValues=TE;qn.calcCutValue=yI;qn.leaveEdge=LI;qn.enterEdge=_I;qn.exchangeEdges=bI;function qn(e){e=s2(e),uE(e);let t=xI(e);fE(t),TE(t,e);let n,r;for(;n=LI(t);)r=_I(t,e,n),bI(t,e,n,r)}function TE(e,t){let n=M2(e,e.nodes());n=n.slice(0,n.length-1),n.forEach(r=>P2(e,t,r))}function P2(e,t,n){let r=e.node(n).parent,o=e.edge(n,r);o.cutvalue=yI(e,t,n)}function yI(e,t,n){let r=e.node(n).parent,o=!0,i=t.edge(n,r),a=0;i||(o=!1,i=t.edge(r,n)),a=i.weight;let l=t.nodeEdges(n);return l&&l.forEach(c=>{let d=c.v===n,E=d?c.w:c.v;if(E!==r){let u=d===o,T=t.edge(c).weight;if(a+=u?T:-T,U2(e,n,E)){let p=e.edge(n,E).cutvalue;a+=u?-p:p}}}),a}function fE(e,t){arguments.length<2&&(t=e.nodes()[0]),CI(e,{},1,t)}function CI(e,t,n,r,o){let i=n,a=e.node(r);t[r]=!0;let l=e.neighbors(r);return l&&l.forEach(c=>{Object.hasOwn(t,c)||(n=CI(e,t,n,c,r))}),a.low=i,a.lim=n++,o?a.parent=o:delete a.parent,n}function LI(e){return e.edges().find(t=>e.edge(t).cutvalue<0)}function _I(e,t,n){let r=n.v,o=n.w;t.hasEdge(r,o)||(r=n.w,o=n.v);let i=e.node(r),a=e.node(o),l=i,c=!1;return i.lim>a.lim&&(l=a,c=!0),t.edges().filter(d=>c===ZT(e,e.node(d.v),l)&&c!==ZT(e,e.node(d.w),l)).reduce((d,E)=>Br(t,E)<Br(t,d)?E:d)}function bI(e,t,n,r){let o=n.v,i=n.w;e.removeEdge(o,i),e.setEdge(r.v,r.w,{}),fE(e),TE(e,t),w2(e,t)}function w2(e,t){let n=e.nodes().find(o=>!e.node(o).parent);if(!n)return;let r=D2(e,[n]);r=r.slice(1),r.forEach(o=>{let i=e.node(o).parent,a=t.edge(o,i),l=!1;a||(a=t.edge(i,o),l=!0),t.node(o).rank=t.node(i).rank+(l?a.minlen:-a.minlen)})}function U2(e,t,n){return e.hasEdge(t,n)}function ZT(e,t,n){return n.low<=t.lim&&t.lim<=n.lim}var B2=F2;function F2(e){let t=e.graph().ranker;if(typeof t=="function")return t(e);switch(t){case"network-simplex":ef(e);break;case"tight-tree":j2(e);break;case"longest-path":k2(e);break;case"none":break;default:ef(e)}}var k2=uE;function j2(e){uE(e),xI(e)}function ef(e){v2(e)}var G2=H2;function H2(e){let t=W2(e);e.graph().dummyChains.forEach(n=>{let r=e.node(n),o=r.edgeObj,i=Y2(e,t,o.v,o.w),a=i.path,l=i.lca,c=0,d=a[c],E=!0;for(;n!==o.w;){if(r=e.node(n),E){for(;(d=a[c])!==l&&e.node(d).maxRank<r.rank;)c++;d===l&&(E=!1)}if(!E){for(;c<a.length-1&&e.node(a[c+1]).minRank<=r.rank;)c++;d=a[c]}d!==void 0&&e.setParent(n,d),n=e.successors(n)[0]}})}function Y2(e,t,n,r){let o=[],i=[],a=Math.min(t[n].low,t[r].low),l=Math.max(t[n].lim,t[r].lim),c;c=n;do c=e.parent(c),o.push(c);while(c&&(t[c].low>a||l>t[c].lim));let d=c,E=r;for(;(E=e.parent(E))!==d;)i.push(E);return{path:o.concat(i.reverse()),lca:d}}function W2(e){let t={},n=0;function r(o){let i=n;e.children(o).forEach(r),t[o]={low:i,lim:n++}}return e.children(La).forEach(r),t}function $2(e){let t=Yr(e,"root",{},"_root"),n=V2(e),r=Object.values(n),o=Ct(Math.max,r)-1,i=2*o+1;e.graph().nestingRoot=t,e.edges().forEach(l=>e.edge(l).minlen*=i);let a=X2(e)+1;e.children(La).forEach(l=>DI(e,t,i,a,o,n,l)),e.graph().nodeRankFactor=i}function DI(e,t,n,r,o,i,a){var l;let c=e.children(a);if(!c.length){a!==t&&e.setEdge(t,a,{weight:0,minlen:n});return}let d=JT(e,"_bt"),E=JT(e,"_bb"),u=e.node(a);e.setParent(d,a),u.borderTop=d,e.setParent(E,a),u.borderBottom=E,c.forEach(T=>{var p;DI(e,t,n,r,o,i,T);let h=e.node(T),A=h.borderTop?h.borderTop:T,S=h.borderBottom?h.borderBottom:T,R=h.borderTop?r:2*r,m=A!==S?1:o-((p=i[a])!=null?p:0)+1;e.setEdge(d,A,{weight:R,minlen:m,nestingEdge:!0}),e.setEdge(S,E,{weight:R,minlen:m,nestingEdge:!0})}),e.parent(a)||e.setEdge(t,d,{weight:0,minlen:o+((l=i[a])!=null?l:0)})}function V2(e){let t={};function n(r,o){let i=e.children(r);i&&i.length&&i.forEach(a=>n(a,o+1)),t[r]=o}return e.children(La).forEach(r=>n(r,1)),t}function X2(e){return e.edges().reduce((t,n)=>t+e.edge(n).weight,0)}function z2(e){let t=e.graph();e.removeNode(t.nestingRoot),delete t.nestingRoot,e.edges().forEach(n=>{e.edge(n).nestingEdge&&e.removeEdge(n)})}var K2=q2;function q2(e){function t(n){let r=e.children(n),o=e.node(n);if(r.length&&r.forEach(t),Object.hasOwn(o,"minRank")){o.borderLeft=[],o.borderRight=[];for(let i=o.minRank,a=o.maxRank+1;i<a;++i)tf(e,"borderLeft","_bl",n,o,i),tf(e,"borderRight","_br",n,o,i)}}e.children(La).forEach(t)}function tf(e,t,n,r,o,i){let a={width:0,height:0,rank:i,borderType:t},l=o[t][i-1],c=Yr(e,"border",a,n);o[t][i]=c,e.setParent(c,r),l&&e.setEdge(l,c,{weight:1})}function J2(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="lr"||n==="rl")&&MI(e)}function Q2(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="bt"||n==="rl")&&Z2(e),(n==="lr"||n==="rl")&&(ek(e),MI(e))}function MI(e){e.nodes().forEach(t=>nf(e.node(t))),e.edges().forEach(t=>nf(e.edge(t)))}function nf(e){let t=e.width;e.width=e.height,e.height=t}function Z2(e){e.nodes().forEach(t=>Ml(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(Ml),Object.hasOwn(r,"y")&&Ml(r)})}function Ml(e){e.y=-e.y}function ek(e){e.nodes().forEach(t=>vl(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(vl),Object.hasOwn(r,"x")&&vl(r)})}function vl(e){let t=e.x;e.x=e.y,e.y=t}function tk(e){let t={},n=e.nodes().filter(l=>!e.children(l).length),r=n.map(l=>e.node(l).rank),o=Ct(Math.max,r),i=Po(o+1).map(()=>[]);function a(l){if(t[l])return;t[l]=!0;let c=e.node(l);i[c.rank].push(l);let d=e.successors(l);d&&d.forEach(a)}return n.sort((l,c)=>e.node(l).rank-e.node(c).rank).forEach(a),i}function nk(e,t){let n=0;for(let r=1;r<t.length;++r)n+=rk(e,t[r-1],t[r]);return n}function rk(e,t,n){let r=E2(n,n.map((d,E)=>E)),o=t.flatMap(d=>{let E=e.outEdges(d);return E?E.map(u=>({pos:r[u.w],weight:e.edge(u).weight})).sort((u,T)=>u.pos-T.pos):[]}),i=1;for(;i<n.length;)i<<=1;let a=2*i-1;i-=1;let l=new Array(a).fill(0),c=0;return o.forEach(d=>{let E=d.pos+i;l[E]+=d.weight;let u=0;for(;E>0;)E%2&&(u+=l[E+1]),E=E-1>>1,l[E]+=d.weight;c+=d.weight*u}),c}function ok(e,t=[]){return t.map(n=>{let r=e.inEdges(n);if(!r||!r.length)return{v:n};{let o=r.reduce((i,a)=>{let l=e.edge(a),c=e.node(a.v);return{sum:i.sum+l.weight*c.order,weight:i.weight+l.weight}},{sum:0,weight:0});return{v:n,barycenter:o.sum/o.weight,weight:o.weight}}})}function sk(e,t){let n={};e.forEach((o,i)=>{let a={indegree:0,in:[],out:[],vs:[o.v],i};o.barycenter!==void 0&&(a.barycenter=o.barycenter,a.weight=o.weight),n[o.v]=a}),t.edges().forEach(o=>{let i=n[o.v],a=n[o.w];i!==void 0&&a!==void 0&&(a.indegree++,i.out.push(a))});let r=Object.values(n).filter(o=>!o.indegree);return ik(r)}function ik(e){let t=[];function n(o){return i=>{i.merged||(i.barycenter===void 0||o.barycenter===void 0||i.barycenter>=o.barycenter)&&ak(o,i)}}function r(o){return i=>{i.in.push(o),--i.indegree===0&&e.push(i)}}for(;e.length;){let o=e.pop();t.push(o),o.in.reverse().forEach(n(o)),o.out.forEach(r(o))}return t.filter(o=>!o.merged).map(o=>Bi(o,["vs","i","barycenter","weight"]))}function ak(e,t){let n=0,r=0;e.weight&&(n+=e.barycenter*e.weight,r+=e.weight),t.weight&&(n+=t.barycenter*t.weight,r+=t.weight),e.vs=t.vs.concat(e.vs),e.barycenter=n/r,e.weight=r,e.i=Math.min(t.i,e.i),t.merged=!0}function lk(e,t){let n=c2(e,E=>Object.hasOwn(E,"barycenter")),r=n.lhs,o=n.rhs.sort((E,u)=>u.i-E.i),i=[],a=0,l=0,c=0;r.sort(ck(!!t)),c=rf(i,o,c),r.forEach(E=>{c+=E.vs.length,i.push(E.vs),a+=E.barycenter*E.weight,l+=E.weight,c=rf(i,o,c)});let d={vs:i.flat(1)};return l&&(d.barycenter=a/l,d.weight=l),d}function rf(e,t,n){let r;for(;t.length&&(r=t[t.length-1]).i<=n;)t.pop(),e.push(r.vs),n++;return n}function ck(e){return(t,n)=>t.barycenter<n.barycenter?-1:t.barycenter>n.barycenter?1:e?n.i-t.i:t.i-n.i}function vI(e,t,n,r){let o=e.children(t),i=e.node(t),a=i?i.borderLeft:void 0,l=i?i.borderRight:void 0,c={};a&&(o=o.filter(T=>T!==a&&T!==l));let d=ok(e,o);d.forEach(T=>{if(e.children(T.v).length){let p=vI(e,T.v,n,r);c[T.v]=p,Object.hasOwn(p,"barycenter")&&Ek(T,p)}});let E=sk(d,n);dk(E,c);let u=lk(E,r);if(a&&l){u.vs=[a,u.vs,l].flat(1);let T=e.predecessors(a);if(T&&T.length){let p=e.node(T[0]),h=e.predecessors(l),A=e.node(h[0]);Object.hasOwn(u,"barycenter")||(u.barycenter=0,u.weight=0),u.barycenter=(u.barycenter*u.weight+p.order+A.order)/(u.weight+2),u.weight+=2}}return u}function dk(e,t){e.forEach(n=>{n.vs=n.vs.flatMap(r=>t[r]?t[r].vs:r)})}function Ek(e,t){e.barycenter!==void 0?(e.barycenter=(e.barycenter*e.weight+t.barycenter*t.weight)/(e.weight+t.weight),e.weight+=t.weight):(e.barycenter=t.barycenter,e.weight=t.weight)}function uk(e,t,n,r){r||(r=e.nodes());let o=Tk(e),i=new it({compound:!0}).setGraph({root:o}).setDefaultNodeLabel(a=>e.node(a));return r.forEach(a=>{let l=e.node(a),c=e.parent(a);if(l.rank===t||l.minRank<=t&&t<=l.maxRank){i.setNode(a),i.setParent(a,c||o);let d=e[n](a);d&&d.forEach(E=>{let u=E.v===a?E.w:E.v,T=i.edge(u,a),p=T!==void 0?T.weight:0;i.setEdge(u,a,{weight:e.edge(E).weight+p})}),Object.hasOwn(l,"minRank")&&i.setNode(a,{borderLeft:l.borderLeft[t],borderRight:l.borderRight[t]})}}),i}function Tk(e){let t;for(;e.hasNode(t=EE("_root")););return t}function fk(e,t,n){let r={},o;n.forEach(i=>{let a=e.parent(i),l,c;for(;a;){if(l=e.parent(a),l?(c=r[l],r[l]=a):(c=o,o=a),c&&c!==a){t.setEdge(c,a);return}a=l}})}function PI(e,t={}){if(typeof t.customOrder=="function"){t.customOrder(e,PI);return}let n=OI(e),r=of(e,Po(1,n+1),"inEdges"),o=of(e,Po(n-1,-1,-1),"outEdges"),i=tk(e);if(sf(e,i),t.disableOptimalOrderHeuristic)return;let a=Number.POSITIVE_INFINITY,l,c=t.constraints||[];for(let d=0,E=0;E<4;++d,++E){pk(d%2?r:o,d%4>=2,c),i=qo(e);let u=nk(e,i);u<a?(E=0,l=Object.assign({},i),a=u):u===a&&(l=structuredClone(i))}sf(e,l)}function of(e,t,n){let r=new Map,o=(i,a)=>{r.has(i)||r.set(i,[]),r.get(i).push(a)};for(let i of e.nodes()){let a=e.node(i);if(typeof a.rank=="number"&&o(a.rank,i),typeof a.minRank=="number"&&typeof a.maxRank=="number")for(let l=a.minRank;l<=a.maxRank;l++)l!==a.rank&&o(l,i)}return t.map(function(i){return uk(e,i,n,r.get(i)||[])})}function pk(e,t,n){let r=new it;e.forEach(function(o){n.forEach(l=>r.setEdge(l.left,l.right));let i=o.graph().root,a=vI(o,i,r,t);a.vs.forEach((l,c)=>o.node(l).order=c),fk(o,r,a.vs)})}function sf(e,t){Object.values(t).forEach(n=>n.forEach((r,o)=>e.node(r).order=o))}function Sk(e,t){let n={};function r(o,i){let a=0,l=0,c=o.length,d=i[i.length-1];return i.forEach((E,u)=>{let T=hk(e,E),p=T?e.node(T).order:c;(T||E===d)&&(i.slice(l,u+1).forEach(h=>{let A=e.predecessors(h);A&&A.forEach(S=>{let R=e.node(S),m=R.order;(m<a||p<m)&&!(R.dummy&&e.node(h).dummy)&&wI(n,S,h)})}),l=u+1,a=p)}),i}return t.length&&t.reduce(r),n}function Rk(e,t){let n={};function r(i,a,l,c,d){Po(a,l).forEach(E=>{let u=i[E];if(u!==void 0&&e.node(u).dummy){let T=e.predecessors(u);T&&T.forEach(p=>{if(p===void 0)return;let h=e.node(p);h.dummy&&(h.order<c||h.order>d)&&wI(n,p,u)})}})}function o(i,a){let l=-1,c=-1,d=0;return a.forEach((E,u)=>{if(e.node(E).dummy==="border"){let T=e.predecessors(E);if(T&&T.length){let p=T[0];if(p===void 0)return;c=e.node(p).order,r(a,d,u,l,c),d=u,l=c}}r(a,d,a.length,c,i.length)}),a}return t.length&&t.reduce(o),n}function hk(e,t){if(e.node(t).dummy){let n=e.predecessors(t);if(n)return n.find(r=>e.node(r).dummy)}}function wI(e,t,n){if(t>n){let o=t;t=n,n=o}let r=e[t];r||(e[t]=r={}),r[n]=!0}function Ak(e,t,n){if(t>n){let o=t;t=n,n=o}let r=e[t];return r!==void 0&&Object.hasOwn(r,n)}function Ik(e,t,n,r){let o={},i={},a={};return t.forEach(l=>{l.forEach((c,d)=>{o[c]=c,i[c]=c,a[c]=d})}),t.forEach(l=>{let c=-1;l.forEach(d=>{let E=r(d);if(E&&E.length){let u=E.sort((p,h)=>{let A=a[p],S=a[h];return(A!==void 0?A:0)-(S!==void 0?S:0)}),T=(u.length-1)/2;for(let p=Math.floor(T),h=Math.ceil(T);p<=h;++p){let A=u[p];if(A===void 0)continue;let S=a[A];if(S!==void 0&&i[d]===d&&c<S&&!Ak(n,d,A)){let R=o[A];R!==void 0&&(i[A]=d,i[d]=o[d]=R,c=S)}}}})}),{root:o,align:i}}function mk(e,t,n,r,o=!1){let i={},a=Ok(e,t,n,o),l=o?"borderLeft":"borderRight";function c(p,h){let A=a.nodes().slice(),S={},R=A.pop();for(;R;){if(S[R])p(R);else{S[R]=!0,A.push(R);for(let m of h(R))A.push(m)}R=A.pop()}}function d(p){let h=a.inEdges(p);h?i[p]=h.reduce((A,S)=>{var R;let m=(R=i[S.v])!=null?R:0,I=a.edge(S);return Math.max(A,m+(I!==void 0?I:0))},0):i[p]=0}function E(p){let h=a.outEdges(p),A=Number.POSITIVE_INFINITY;h&&(A=h.reduce((R,m)=>{let I=i[m.w],O=a.edge(m);return Math.min(R,(I!==void 0?I:0)-(O!==void 0?O:0))},Number.POSITIVE_INFINITY));let S=e.node(p);A!==Number.POSITIVE_INFINITY&&S.borderType!==l&&(i[p]=Math.max(i[p]!==void 0?i[p]:0,A))}function u(p){return a.predecessors(p)||[]}function T(p){return a.successors(p)||[]}return c(d,u),c(E,T),Object.keys(r).forEach(p=>{var h;let A=n[p];A!==void 0&&(i[p]=(h=i[A])!=null?h:0)}),i}function Ok(e,t,n,r){let o=new it,i=e.graph(),a=Ck(i.nodesep,i.edgesep,r);return t.forEach(l=>{let c;l.forEach(d=>{let E=n[d];if(E!==void 0){if(o.setNode(E),c!==void 0){let u=n[c];if(u!==void 0){let T=o.edge(u,E);o.setEdge(u,E,Math.max(a(e,d,c),T||0))}}c=d}})}),o}function Nk(e,t){return Object.values(t).reduce((n,r)=>{let o=Number.NEGATIVE_INFINITY,i=Number.POSITIVE_INFINITY;Object.entries(r).forEach(([l,c])=>{let d=Lk(e,l)/2;o=Math.max(c+d,o),i=Math.min(c-d,i)});let a=o-i;return a<n[0]&&(n=[a,r]),n},[Number.POSITIVE_INFINITY,null])[1]}function gk(e,t){let n=Object.values(t),r=Ct(Math.min,n),o=Ct(Math.max,n);["u","d"].forEach(i=>{["l","r"].forEach(a=>{let l=i+a,c=e[l];if(!c||c===t)return;let d=Object.values(c),E=r-Ct(Math.min,d);a!=="l"&&(E=o-Ct(Math.max,d)),E&&(e[l]=Ca(c,u=>u+E))})})}function xk(e,t=void 0){let n=e.ul;return n?Ca(n,(r,o)=>{var i,a;if(t){let c=t.toLowerCase(),d=e[c];if(d&&d[o]!==void 0)return d[o]}let l=Object.values(e).map(c=>{let d=c[o];return d!==void 0?d:0}).sort((c,d)=>c-d);return(((i=l[1])!=null?i:0)+((a=l[2])!=null?a:0))/2}):{}}function yk(e){let t=qo(e),n=Object.assign(Sk(e,t),Rk(e,t)),r={},o;["u","d"].forEach(a=>{o=a==="u"?t:Object.values(t).reverse(),["l","r"].forEach(l=>{l==="r"&&(o=o.map(E=>Object.values(E).reverse()));let c=Ik(e,o,n,E=>(a==="u"?e.predecessors(E):e.successors(E))||[]),d=mk(e,o,c.root,c.align,l==="r");l==="r"&&(d=Ca(d,E=>-E)),r[a+l]=d})});let i=Nk(e,r);return gk(r,i),xk(r,e.graph().align)}function Ck(e,t,n){return(r,o,i)=>{let a=r.node(o),l=r.node(i),c=0,d;if(c+=a.width/2,Object.hasOwn(a,"labelpos"))switch(a.labelpos.toLowerCase()){case"l":d=-a.width/2;break;case"r":d=a.width/2;break}if(d&&(c+=n?d:-d),d=void 0,c+=(a.dummy?t:e)/2,c+=(l.dummy?t:e)/2,c+=l.width/2,Object.hasOwn(l,"labelpos"))switch(l.labelpos.toLowerCase()){case"l":d=l.width/2;break;case"r":d=-l.width/2;break}return d&&(c+=n?d:-d),c}}function Lk(e,t){return e.node(t).width}function _k(e){e=II(e),bk(e),Object.entries(yk(e)).forEach(([t,n])=>e.node(t).x=n)}function bk(e){let t=qo(e),n=e.graph(),r=n.ranksep,o=n.rankalign,i=0;t.forEach(a=>{let l=a.reduce((c,d)=>{var E;let u=(E=e.node(d).height)!=null?E:0;return c>u?c:u},0);a.forEach(c=>{let d=e.node(c);o==="top"?d.y=i+d.height/2:o==="bottom"?d.y=i+l-d.height/2:d.y=i+l/2}),i+=l+r})}function Dk(e,t={}){let n=t.debugTiming?NI:gI;return n("layout",()=>{let r=n(" buildLayoutGraph",()=>Gk(e));return n(" runLayout",()=>Mk(r,n,t)),n(" updateInputGraph",()=>vk(e,r)),r})}function Mk(e,t,n){t(" makeSpaceForEdgeLabels",()=>Hk(e)),t(" removeSelfEdges",()=>Jk(e)),t(" acyclic",()=>m2(e)),t(" nestingGraph.run",()=>$2(e)),t(" rank",()=>B2(II(e))),t(" injectEdgeLabelProxies",()=>Yk(e)),t(" removeEmptyRanks",()=>a2(e)),t(" nestingGraph.cleanup",()=>z2(e)),t(" normalizeRanks",()=>i2(e)),t(" assignRankMinMax",()=>Wk(e)),t(" removeEdgeLabelProxies",()=>$k(e)),t(" normalize.run",()=>g2(e)),t(" parentDummyChains",()=>G2(e)),t(" addBorderSegments",()=>K2(e)),t(" order",()=>PI(e,n)),t(" insertSelfEdges",()=>Qk(e)),t(" adjustCoordinateSystem",()=>J2(e)),t(" position",()=>_k(e)),t(" positionSelfEdges",()=>Zk(e)),t(" removeBorderNodes",()=>qk(e)),t(" normalize.undo",()=>y2(e)),t(" fixupEdgeLabelCoords",()=>zk(e)),t(" undoCoordinateSystem",()=>Q2(e)),t(" translateGraph",()=>Vk(e)),t(" assignNodeIntersects",()=>Xk(e)),t(" reversePoints",()=>Kk(e)),t(" acyclic.undo",()=>N2(e))}function vk(e,t){e.nodes().forEach(n=>{let r=e.node(n),o=t.node(n);r&&(r.x=o.x,r.y=o.y,r.order=o.order,r.rank=o.rank,t.children(n).length&&(r.width=o.width,r.height=o.height))}),e.edges().forEach(n=>{let r=e.edge(n),o=t.edge(n);r.points=o.points,Object.hasOwn(o,"x")&&(r.x=o.x,r.y=o.y)}),e.graph().width=t.graph().width,e.graph().height=t.graph().height}var Pk=["nodesep","edgesep","ranksep","marginx","marginy"],wk={ranksep:50,edgesep:20,nodesep:50,rankdir:"TB",rankalign:"center"},Uk=["acyclicer","ranker","rankdir","align","rankalign"],Bk=["width","height","rank"],af={width:0,height:0},Fk=["minlen","weight","width","height","labeloffset"],kk={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},jk=["labelpos"];function Gk(e){let t=new it({multigraph:!0,compound:!0}),n=wl(e.graph());return t.setGraph(Object.assign({},wk,Pl(n,Pk),Bi(n,Uk))),e.nodes().forEach(r=>{let o=wl(e.node(r)),i=Pl(o,Bk);Object.keys(af).forEach(l=>{i[l]===void 0&&(i[l]=af[l])}),t.setNode(r,i);let a=e.parent(r);a!==void 0&&t.setParent(r,a)}),e.edges().forEach(r=>{let o=wl(e.edge(r));t.setEdge(r,Object.assign({},kk,Pl(o,Fk),Bi(o,jk)))}),t}function Hk(e){let t=e.graph();t.ranksep/=2,e.edges().forEach(n=>{let r=e.edge(n);r.minlen*=2,r.labelpos.toLowerCase()!=="c"&&(t.rankdir==="TB"||t.rankdir==="BT"?r.width+=r.labeloffset:r.height+=r.labeloffset)})}function Yk(e){e.edges().forEach(t=>{let n=e.edge(t);if(n.width&&n.height){let r=e.node(t.v),o={rank:(e.node(t.w).rank-r.rank)/2+r.rank,e:t};Yr(e,"edge-proxy",o,"_ep")}})}function Wk(e){let t=0;e.nodes().forEach(n=>{let r=e.node(n);r.borderTop&&(r.minRank=e.node(r.borderTop).rank,r.maxRank=e.node(r.borderBottom).rank,t=Math.max(t,r.maxRank))}),e.graph().maxRank=t}function $k(e){e.nodes().forEach(t=>{let n=e.node(t);if(n.dummy==="edge-proxy"){let r=n;e.edge(r.e).labelRank=n.rank,e.removeNode(t)}})}function Vk(e){let t=Number.POSITIVE_INFINITY,n=0,r=Number.POSITIVE_INFINITY,o=0,i=e.graph(),a=i.marginx||0,l=i.marginy||0;function c(d){let E=d.x,u=d.y,T=d.width,p=d.height;t=Math.min(t,E-T/2),n=Math.max(n,E+T/2),r=Math.min(r,u-p/2),o=Math.max(o,u+p/2)}e.nodes().forEach(d=>c(e.node(d))),e.edges().forEach(d=>{let E=e.edge(d);Object.hasOwn(E,"x")&&c(E)}),t-=a,r-=l,e.nodes().forEach(d=>{let E=e.node(d);E.x-=t,E.y-=r}),e.edges().forEach(d=>{let E=e.edge(d);E.points.forEach(u=>{u.x-=t,u.y-=r}),Object.hasOwn(E,"x")&&(E.x-=t),Object.hasOwn(E,"y")&&(E.y-=r)}),i.width=n-t+a,i.height=o-r+l}function Xk(e){e.edges().forEach(t=>{let n=e.edge(t),r=e.node(t.v),o=e.node(t.w),i,a;n.points?(i=n.points[0],a=n.points[n.points.length-1]):(n.points=[],i=o,a=r),n.points.unshift(qT(r,i)),n.points.push(qT(o,a))})}function zk(e){e.edges().forEach(t=>{let n=e.edge(t);if(Object.hasOwn(n,"x"))switch((n.labelpos==="l"||n.labelpos==="r")&&(n.width-=n.labeloffset),n.labelpos){case"l":n.x-=n.width/2+n.labeloffset;break;case"r":n.x+=n.width/2+n.labeloffset;break}})}function Kk(e){e.edges().forEach(t=>{let n=e.edge(t);n.reversed&&n.points.reverse()})}function qk(e){e.nodes().forEach(t=>{if(e.children(t).length){let n=e.node(t),r=e.node(n.borderTop),o=e.node(n.borderBottom),i=e.node(n.borderLeft[n.borderLeft.length-1]),a=e.node(n.borderRight[n.borderRight.length-1]);n.width=Math.abs(a.x-i.x),n.height=Math.abs(o.y-r.y),n.x=i.x+n.width/2,n.y=r.y+n.height/2}}),e.nodes().forEach(t=>{e.node(t).dummy==="border"&&e.removeNode(t)})}function Jk(e){e.edges().forEach(t=>{if(t.v===t.w){let n=e.node(t.v);n.selfEdges||(n.selfEdges=[]),n.selfEdges.push({e:t,label:e.edge(t)}),e.removeEdge(t)}})}function Qk(e){qo(e).forEach(t=>{let n=0;t.forEach((r,o)=>{let i=e.node(r);i.order=o+n,(i.selfEdges||[]).forEach(a=>{Yr(e,"selfedge",{width:a.label.width,height:a.label.height,rank:i.rank,order:o+ ++n,e:a.e,label:a.label},"_se")}),delete i.selfEdges})})}function Zk(e){e.nodes().forEach(t=>{let n=e.node(t);if(n.dummy==="selfedge"){let r=n,o=e.node(r.e.v),i=o.x+o.width/2,a=o.y,l=n.x-i,c=o.height/2;e.setEdge(r.e,r.label),e.removeNode(t),r.label.points=[{x:i+2*l/3,y:a-c},{x:i+5*l/6,y:a-c},{x:i+l,y:a},{x:i+5*l/6,y:a+c},{x:i+2*l/3,y:a+c}],r.label.x=n.x,r.label.y=n.y}})}function Pl(e,t){return Ca(Bi(e,t),Number)}function wl(e){let t={};return e&&Object.entries(e).forEach(([n,r])=>{typeof n=="string"&&(n=n.toLowerCase()),t[n]=r}),t}function ej(e){let t=qo(e),n=new it({compound:!0,multigraph:!0}).setGraph({});return e.nodes().forEach(r=>{n.setNode(r,{label:r}),n.setParent(r,"layer"+e.node(r).rank)}),e.edges().forEach(r=>n.setEdge(r.v,r.w,{},r.name)),t.forEach((r,o)=>{let i="layer"+o;n.setNode(i,{rank:"same"}),r.reduce((a,l)=>(n.setEdge(a,l,{style:"invis"}),l))}),n}var tj={graphlib:EI,version:u2,layout:Dk,debug:ej,util:{time:NI,notime:gI}},Fi=tj;/*! For license information please see dagre.esm.js.LEGAL.txt */function nj(e,t,n={}){var o;if(e.length===0)return e;const r=new Fi.graphlib.Graph().setDefaultEdgeLabel(()=>({}));r.setGraph({rankdir:"LR",ranksep:60,nodesep:30,marginx:20,marginy:20});for(const i of e){const a={width:170,height:52};if(n.mode==="layered"&&((o=i.data)!=null&&o.layer)){const l=hi.indexOf(i.data.layer);l>=0&&(a.rank=l)}r.setNode(i.id,a)}for(const i of t)r.setEdge(i.source,i.target);return Fi.layout(r),e.map(i=>{const a=r.node(i.id);return{...i,position:{x:a.x-85,y:a.y-26}}})}function rj({data:e,selected:t}){const n=e.nodeType,r=e.isFocal,o=we[n]??"var(--color-text-tertiary)",i=aa[n]??n.toUpperCase();return s.jsxs("div",{style:{minWidth:140,maxWidth:190,background:"var(--color-bg-card)",border:`2px solid ${r||t?"var(--color-accent-blue)":o}`,borderRadius:8,padding:"6px 8px",boxShadow:r?"0 0 0 2px color-mix(in srgb, var(--color-accent-blue) 25%, transparent)":"none"},children:[s.jsx(Rn,{type:"target",position:ae.Left,style:{width:6,height:6,background:o,border:"none"}}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginBottom:2},children:[s.jsx("span",{style:{fontSize:8,fontWeight:700,letterSpacing:"0.04em",color:"var(--color-bg-card)",background:o,borderRadius:3,padding:"1px 4px"},children:i}),e.domain&&s.jsx("span",{style:{color:"var(--color-text-tertiary)",fontSize:9},children:e.domain})]}),s.jsx("div",{style:{color:"var(--color-text-primary)",fontSize:10,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.label,children:e.label}),s.jsx(Rn,{type:"source",position:ae.Right,style:{width:6,height:6,background:o,border:"none"}})]})}const oj={miniDagNode:rj};function sj({nodes:e,edges:t,focalNodeId:n,height:r=250,onNodeClick:o,interactive:i=!0,layoutMode:a="flow"}){const[l,c,d]=oI([]),[E,u,T]=sI([]),{fitView:p}=ga(),h=f.useRef(null);return f.useEffect(()=>{const A=e.map(R=>({id:R.id,type:"miniDagNode",position:{x:0,y:0},data:{label:R.name,nodeType:R.type,domain:R.domain,layer:vd(R),isFocal:R.id===n}})),S=t.map((R,m)=>({id:`mini-edge-${m}-${R.source}-${R.target}`,source:R.source,target:R.target,style:{stroke:co[R.type]??"#8b949e",strokeWidth:1.4},markerEnd:{type:Dr.ArrowClosed,color:co[R.type]??"#8b949e",width:10,height:10}}));c(nj(A,S,{mode:a})),u(S),requestAnimationFrame(()=>{p({padding:.15,duration:200})})},[e,t,n,a,c,u,p]),f.useEffect(()=>{if(!h.current)return;const A=h.current,S=new ResizeObserver(()=>{p({padding:.15,duration:0})});return S.observe(A),()=>S.disconnect()},[p]),e.length===0?s.jsx("div",{style:{height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--color-text-tertiary)",fontSize:11},children:"No lineage nodes to display"}):s.jsx("div",{ref:h,style:{height:r,width:"100%",borderRadius:8,overflow:"hidden",border:"1px solid var(--color-border-subtle)"},children:s.jsx(rI,{nodes:l,edges:E,onNodesChange:i?d:void 0,onEdgesChange:i?T:void 0,onNodeClick:o?(A,S)=>o(S.id):void 0,nodeTypes:oj,fitView:!0,fitViewOptions:{padding:.15},minZoom:.25,proOptions:{hideAttribution:!0},nodesDraggable:i,nodesConnectable:!1,zoomOnScroll:i,panOnDrag:i,style:{background:"var(--color-bg-sunken)"},children:s.jsx(aI,{color:"var(--color-border-subtle)",gap:20,size:1})})})}function pE(e){return s.jsx(nI,{children:s.jsx(sj,{...e})})}function ij(e){const t=e.match(/^\s*block\s+"([^"]+)"/i);return t?t[1]:null}function aj(e){const t=[],n=/\b(?:FROM|JOIN)\s+([a-zA-Z_][\w.]*)/gi;for(const o of e.matchAll(n)){const i=o[1].toLowerCase();["select","where","group","order","having","limit","union","lateral"].includes(i)||t.push(i)}const r=/\bref\s*\(\s*"([^"]+)"\s*\)/gi;for(const o of e.matchAll(r))t.push(o[1]);return[...new Set(t)]}function lj(e){const t=[],n=[];for(const r of e.matchAll(/@metric\s*\(\s*([^)]+)\s*\)/gi))t.push(r[1].replace(/['"]/g,"").trim());for(const r of e.matchAll(/@dim\s*\(\s*([^)]+)\s*\)/gi))n.push(r[1].replace(/['"]/g,"").trim());return{metrics:t,dimensions:n}}function cj({cellContent:e,cellType:t,cellName:n,themeMode:r,t:o,onFocusNode:i}){const[a,l]=f.useState(!1),[c,d]=f.useState(380),E=f.useRef(c);E.current=c;const[u,T]=f.useState(!1),[p,h]=f.useState(!1),[A,S]=f.useState([]),[R,m]=f.useState([]),[I,O]=f.useState(),[N,x]=f.useState([]),[g,C]=f.useState({metrics:[],dimensions:[]}),[y,w]=f.useState(null),[v,B]=f.useState(null),L=(t==="dql"?ij(e):null)||n,D=f.useCallback(async()=>{if(!(!L&&t!=="sql")){h(!0),B(null);try{const U=aj(e);if(x(U),C(lj(e)),L){const P=`block:${L}`;O(P);const[_,F]=await Promise.all([z.queryLineage({focus:P,upstreamDepth:2,downstreamDepth:2}),z.fetchLineagePaths(P)]);_!=null&&_.graph&&(S(_.graph.nodes??[]),m(_.graph.edges??[])),F&&w(F)}else{O(void 0);const _=((await z.fetchLineage()).nodes??[]).filter(F=>U.some(k=>F.name===k||F.id===`table:${k}`));S(_),m([])}}catch{B("Failed to load lineage")}finally{h(!1)}}},[L,e,t]);f.useEffect(()=>{a&&D()},[a,D]);const M=N.length>0||g.metrics.length>0||g.dimensions.length>0;return e.trim()?s.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[s.jsxs("button",{onClick:()=>l(U=>!U),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 12px",background:a?`${o.tableHeaderBg}60`:"transparent",border:"none",cursor:"pointer",color:o.textMuted,fontSize:10,fontFamily:o.font,transition:"background 0.15s"},children:[s.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",style:{flexShrink:0},children:[s.jsx("circle",{cx:"4",cy:"4",r:"2"}),s.jsx("circle",{cx:"12",cy:"8",r:"2"}),s.jsx("circle",{cx:"4",cy:"12",r:"2"}),s.jsx("line",{x1:"6",y1:"4",x2:"10",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"10",y2:"8"})]}),s.jsx("span",{children:"Lineage"}),s.jsx("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:a?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.15s"},children:s.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})}),a&&L&&i&&s.jsx("span",{onClick:U=>{U.stopPropagation(),i(`block:${L}`)},style:{marginLeft:"auto",fontSize:9,color:o.accent,cursor:"pointer",textDecoration:"underline"},children:"View in DAG"})]}),a&&s.jsx("div",{style:{fontSize:11},children:p?s.jsx("div",{style:{color:o.textMuted,padding:"8px 12px"},children:"Loading lineage..."}):v?s.jsx("div",{style:{color:o.error,padding:"8px 12px"},children:v}):s.jsxs(s.Fragment,{children:[A.length>0&&I&&s.jsxs("div",{style:{borderBottom:`1px solid ${o.cellBorder}`,position:"relative"},children:[s.jsx(pE,{nodes:A,edges:R,focalNodeId:I,height:c,onNodeClick:i,interactive:!0,layoutMode:"flow"}),s.jsx("div",{onMouseDown:U=>{U.preventDefault();const P=U.clientY,_=E.current;T(!0);const F=H=>{const Q=Math.min(800,Math.max(160,_+(H.clientY-P)));E.current=Q,d(Q)},k=()=>{T(!1),window.removeEventListener("mousemove",F),window.removeEventListener("mouseup",k)};window.addEventListener("mousemove",F),window.addEventListener("mouseup",k)},title:"Drag to resize lineage view",style:{position:"absolute",left:0,right:0,bottom:-3,height:6,cursor:"row-resize",background:u?o.accent:"transparent",transition:u?"none":"background 0.15s",zIndex:5},onMouseEnter:U=>{u||(U.currentTarget.style.background=`${o.accent}40`)},onMouseLeave:U=>{u||(U.currentTarget.style.background="transparent")}})]}),s.jsxs("div",{style:{padding:"6px 12px 8px"},children:[y&&(y.upstreamPaths.length>0||y.downstreamPaths.length>0)&&s.jsxs("div",{style:{marginBottom:8},children:[s.jsx("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:4},children:"Complete Paths"}),s.jsxs("div",{style:{display:"grid",gap:6},children:[y.upstreamPaths.slice(0,3).map((U,P)=>s.jsx(Bc,{path:U,onNodeClick:i,focalNodeId:I,t:o},`up-${P}`)),y.downstreamPaths.slice(0,2).map((U,P)=>s.jsx(Bc,{path:U,onNodeClick:i,focalNodeId:I,t:o},`down-${P}`))]})]}),N.length>0&&s.jsxs("div",{style:{marginBottom:6},children:[s.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Reads From (",N.length,")"]}),N.map(U=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[s.jsx("span",{style:{color:we.source_table,fontSize:9,fontWeight:700,width:26},children:"TBL"}),s.jsx("span",{children:U})]},U))]}),g.metrics.length>0&&s.jsxs("div",{style:{marginBottom:6},children:[s.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Metrics (",g.metrics.length,")"]}),g.metrics.map(U=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[s.jsx("span",{style:{color:we.metric,fontSize:9,fontWeight:700,width:26},children:"MET"}),s.jsx("span",{children:U})]},U))]}),g.dimensions.length>0&&s.jsxs("div",{style:{marginBottom:6},children:[s.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Dimensions (",g.dimensions.length,")"]}),g.dimensions.map(U=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[s.jsx("span",{style:{color:we.dimension,fontSize:9,fontWeight:700,width:26},children:"DIM"}),s.jsx("span",{children:U})]},U))]}),!M&&A.length===0&&!y&&s.jsx("div",{style:{color:o.textMuted,padding:"2px 0"},children:"No lineage dependencies detected for this cell."})]})]})})]}):null}const j=e=>e.flatMap(dj),dj=e=>si(uj(e)).map(Ej),Ej=e=>e.replace(/ +/g," ").trim(),uj=e=>({type:"mandatory_block",items:SE(e,0)[0]}),SE=(e,t,n)=>{const r=[];for(;e[t];){const[o,i]=Tj(e,t);if(r.push(o),t=i,e[t]==="|")t++;else if(e[t]==="}"||e[t]==="]"){if(n!==e[t])throw new Error(`Unbalanced parenthesis in: ${e}`);return t++,[r,t]}else if(t===e.length){if(n)throw new Error(`Unbalanced parenthesis in: ${e}`);return[r,t]}else throw new Error(`Unexpected "${e[t]}"`)}return[r,t]},Tj=(e,t)=>{const n=[];for(;;){const[r,o]=fj(e,t);if(r)n.push(r),t=o;else break}return n.length===1?[n[0],t]:[{type:"concatenation",items:n},t]},fj=(e,t)=>{if(e[t]==="{")return pj(e,t+1);if(e[t]==="[")return Sj(e,t+1);{let n="";for(;e[t]&&/[A-Za-z0-9_ ]/.test(e[t]);)n+=e[t],t++;return[n,t]}},pj=(e,t)=>{const[n,r]=SE(e,t,"}");return[{type:"mandatory_block",items:n},r]},Sj=(e,t)=>{const[n,r]=SE(e,t,"]");return[{type:"optional_block",items:n},r]},si=e=>{if(typeof e=="string")return[e];if(e.type==="concatenation")return e.items.map(si).reduce(Rj,[""]);if(e.type==="mandatory_block")return e.items.flatMap(si);if(e.type==="optional_block")return["",...e.items.flatMap(si)];throw new Error(`Unknown node type: ${e}`)},Rj=(e,t)=>{const n=[];for(const r of e)for(const o of t)n.push(r+o);return n};var K;(function(e){e.QUOTED_IDENTIFIER="QUOTED_IDENTIFIER",e.IDENTIFIER="IDENTIFIER",e.STRING="STRING",e.VARIABLE="VARIABLE",e.RESERVED_DATA_TYPE="RESERVED_DATA_TYPE",e.RESERVED_PARAMETERIZED_DATA_TYPE="RESERVED_PARAMETERIZED_DATA_TYPE",e.RESERVED_KEYWORD="RESERVED_KEYWORD",e.RESERVED_FUNCTION_NAME="RESERVED_FUNCTION_NAME",e.RESERVED_KEYWORD_PHRASE="RESERVED_KEYWORD_PHRASE",e.RESERVED_DATA_TYPE_PHRASE="RESERVED_DATA_TYPE_PHRASE",e.RESERVED_SET_OPERATION="RESERVED_SET_OPERATION",e.RESERVED_CLAUSE="RESERVED_CLAUSE",e.RESERVED_SELECT="RESERVED_SELECT",e.RESERVED_JOIN="RESERVED_JOIN",e.ARRAY_IDENTIFIER="ARRAY_IDENTIFIER",e.ARRAY_KEYWORD="ARRAY_KEYWORD",e.CASE="CASE",e.END="END",e.WHEN="WHEN",e.ELSE="ELSE",e.THEN="THEN",e.LIMIT="LIMIT",e.BETWEEN="BETWEEN",e.AND="AND",e.OR="OR",e.XOR="XOR",e.OPERATOR="OPERATOR",e.COMMA="COMMA",e.ASTERISK="ASTERISK",e.PROPERTY_ACCESS_OPERATOR="PROPERTY_ACCESS_OPERATOR",e.OPEN_PAREN="OPEN_PAREN",e.CLOSE_PAREN="CLOSE_PAREN",e.LINE_COMMENT="LINE_COMMENT",e.BLOCK_COMMENT="BLOCK_COMMENT",e.DISABLE_COMMENT="DISABLE_COMMENT",e.NUMBER="NUMBER",e.NAMED_PARAMETER="NAMED_PARAMETER",e.QUOTED_PARAMETER="QUOTED_PARAMETER",e.NUMBERED_PARAMETER="NUMBERED_PARAMETER",e.POSITIONAL_PARAMETER="POSITIONAL_PARAMETER",e.CUSTOM_PARAMETER="CUSTOM_PARAMETER",e.DELIMITER="DELIMITER",e.EOF="EOF"})(K=K||(K={}));const UI=e=>({type:K.EOF,raw:"«EOF»",text:"«EOF»",start:e}),hn=UI(1/0),lr=e=>t=>t.type===e.type&&t.text===e.text,An={ARRAY:lr({text:"ARRAY",type:K.RESERVED_DATA_TYPE}),BY:lr({text:"BY",type:K.RESERVED_KEYWORD}),SET:lr({text:"SET",type:K.RESERVED_CLAUSE}),STRUCT:lr({text:"STRUCT",type:K.RESERVED_DATA_TYPE}),WINDOW:lr({text:"WINDOW",type:K.RESERVED_CLAUSE}),VALUES:lr({text:"VALUES",type:K.RESERVED_CLAUSE})},BI=e=>e===K.RESERVED_DATA_TYPE||e===K.RESERVED_KEYWORD||e===K.RESERVED_FUNCTION_NAME||e===K.RESERVED_KEYWORD_PHRASE||e===K.RESERVED_DATA_TYPE_PHRASE||e===K.RESERVED_CLAUSE||e===K.RESERVED_SELECT||e===K.RESERVED_SET_OPERATION||e===K.RESERVED_JOIN||e===K.ARRAY_KEYWORD||e===K.CASE||e===K.END||e===K.WHEN||e===K.ELSE||e===K.THEN||e===K.LIMIT||e===K.BETWEEN||e===K.AND||e===K.OR||e===K.XOR,hj=e=>e===K.AND||e===K.OR||e===K.XOR,Aj=["KEYS.NEW_KEYSET","KEYS.ADD_KEY_FROM_RAW_BYTES","AEAD.DECRYPT_BYTES","AEAD.DECRYPT_STRING","AEAD.ENCRYPT","KEYS.KEYSET_CHAIN","KEYS.KEYSET_FROM_JSON","KEYS.KEYSET_TO_JSON","KEYS.ROTATE_KEYSET","KEYS.KEYSET_LENGTH","ANY_VALUE","ARRAY_AGG","AVG","CORR","COUNT","COUNTIF","COVAR_POP","COVAR_SAMP","MAX","MIN","ST_CLUSTERDBSCAN","STDDEV_POP","STDDEV_SAMP","STRING_AGG","SUM","VAR_POP","VAR_SAMP","ANY_VALUE","ARRAY_AGG","ARRAY_CONCAT_AGG","AVG","BIT_AND","BIT_OR","BIT_XOR","COUNT","COUNTIF","LOGICAL_AND","LOGICAL_OR","MAX","MIN","STRING_AGG","SUM","APPROX_COUNT_DISTINCT","APPROX_QUANTILES","APPROX_TOP_COUNT","APPROX_TOP_SUM","ARRAY_CONCAT","ARRAY_LENGTH","ARRAY_TO_STRING","GENERATE_ARRAY","GENERATE_DATE_ARRAY","GENERATE_TIMESTAMP_ARRAY","ARRAY_REVERSE","OFFSET","SAFE_OFFSET","ORDINAL","SAFE_ORDINAL","BIT_COUNT","PARSE_BIGNUMERIC","PARSE_NUMERIC","SAFE_CAST","CURRENT_DATE","EXTRACT","DATE","DATE_ADD","DATE_SUB","DATE_DIFF","DATE_TRUNC","DATE_FROM_UNIX_DATE","FORMAT_DATE","LAST_DAY","PARSE_DATE","UNIX_DATE","CURRENT_DATETIME","DATETIME","EXTRACT","DATETIME_ADD","DATETIME_SUB","DATETIME_DIFF","DATETIME_TRUNC","FORMAT_DATETIME","LAST_DAY","PARSE_DATETIME","ERROR","EXTERNAL_QUERY","S2_CELLIDFROMPOINT","S2_COVERINGCELLIDS","ST_ANGLE","ST_AREA","ST_ASBINARY","ST_ASGEOJSON","ST_ASTEXT","ST_AZIMUTH","ST_BOUNDARY","ST_BOUNDINGBOX","ST_BUFFER","ST_BUFFERWITHTOLERANCE","ST_CENTROID","ST_CENTROID_AGG","ST_CLOSESTPOINT","ST_CLUSTERDBSCAN","ST_CONTAINS","ST_CONVEXHULL","ST_COVEREDBY","ST_COVERS","ST_DIFFERENCE","ST_DIMENSION","ST_DISJOINT","ST_DISTANCE","ST_DUMP","ST_DWITHIN","ST_ENDPOINT","ST_EQUALS","ST_EXTENT","ST_EXTERIORRING","ST_GEOGFROM","ST_GEOGFROMGEOJSON","ST_GEOGFROMTEXT","ST_GEOGFROMWKB","ST_GEOGPOINT","ST_GEOGPOINTFROMGEOHASH","ST_GEOHASH","ST_GEOMETRYTYPE","ST_INTERIORRINGS","ST_INTERSECTION","ST_INTERSECTS","ST_INTERSECTSBOX","ST_ISCOLLECTION","ST_ISEMPTY","ST_LENGTH","ST_MAKELINE","ST_MAKEPOLYGON","ST_MAKEPOLYGONORIENTED","ST_MAXDISTANCE","ST_NPOINTS","ST_NUMGEOMETRIES","ST_NUMPOINTS","ST_PERIMETER","ST_POINTN","ST_SIMPLIFY","ST_SNAPTOGRID","ST_STARTPOINT","ST_TOUCHES","ST_UNION","ST_UNION_AGG","ST_WITHIN","ST_X","ST_Y","FARM_FINGERPRINT","MD5","SHA1","SHA256","SHA512","HLL_COUNT.INIT","HLL_COUNT.MERGE","HLL_COUNT.MERGE_PARTIAL","HLL_COUNT.EXTRACT","MAKE_INTERVAL","EXTRACT","JUSTIFY_DAYS","JUSTIFY_HOURS","JUSTIFY_INTERVAL","JSON_EXTRACT","JSON_QUERY","JSON_EXTRACT_SCALAR","JSON_VALUE","JSON_EXTRACT_ARRAY","JSON_QUERY_ARRAY","JSON_EXTRACT_STRING_ARRAY","JSON_VALUE_ARRAY","TO_JSON_STRING","ABS","SIGN","IS_INF","IS_NAN","IEEE_DIVIDE","RAND","SQRT","POW","POWER","EXP","LN","LOG","LOG10","GREATEST","LEAST","DIV","SAFE_DIVIDE","SAFE_MULTIPLY","SAFE_NEGATE","SAFE_ADD","SAFE_SUBTRACT","MOD","ROUND","TRUNC","CEIL","CEILING","FLOOR","COS","COSH","ACOS","ACOSH","SIN","SINH","ASIN","ASINH","TAN","TANH","ATAN","ATANH","ATAN2","RANGE_BUCKET","FIRST_VALUE","LAST_VALUE","NTH_VALUE","LEAD","LAG","PERCENTILE_CONT","PERCENTILE_DISC","NET.IP_FROM_STRING","NET.SAFE_IP_FROM_STRING","NET.IP_TO_STRING","NET.IP_NET_MASK","NET.IP_TRUNC","NET.IPV4_FROM_INT64","NET.IPV4_TO_INT64","NET.HOST","NET.PUBLIC_SUFFIX","NET.REG_DOMAIN","RANK","DENSE_RANK","PERCENT_RANK","CUME_DIST","NTILE","ROW_NUMBER","SESSION_USER","CORR","COVAR_POP","COVAR_SAMP","STDDEV_POP","STDDEV_SAMP","STDDEV","VAR_POP","VAR_SAMP","VARIANCE","ASCII","BYTE_LENGTH","CHAR_LENGTH","CHARACTER_LENGTH","CHR","CODE_POINTS_TO_BYTES","CODE_POINTS_TO_STRING","CONCAT","CONTAINS_SUBSTR","ENDS_WITH","FORMAT","FROM_BASE32","FROM_BASE64","FROM_HEX","INITCAP","INSTR","LEFT","LENGTH","LPAD","LOWER","LTRIM","NORMALIZE","NORMALIZE_AND_CASEFOLD","OCTET_LENGTH","REGEXP_CONTAINS","REGEXP_EXTRACT","REGEXP_EXTRACT_ALL","REGEXP_INSTR","REGEXP_REPLACE","REGEXP_SUBSTR","REPLACE","REPEAT","REVERSE","RIGHT","RPAD","RTRIM","SAFE_CONVERT_BYTES_TO_STRING","SOUNDEX","SPLIT","STARTS_WITH","STRPOS","SUBSTR","SUBSTRING","TO_BASE32","TO_BASE64","TO_CODE_POINTS","TO_HEX","TRANSLATE","TRIM","UNICODE","UPPER","CURRENT_TIME","TIME","EXTRACT","TIME_ADD","TIME_SUB","TIME_DIFF","TIME_TRUNC","FORMAT_TIME","PARSE_TIME","CURRENT_TIMESTAMP","EXTRACT","STRING","TIMESTAMP","TIMESTAMP_ADD","TIMESTAMP_SUB","TIMESTAMP_DIFF","TIMESTAMP_TRUNC","FORMAT_TIMESTAMP","PARSE_TIMESTAMP","TIMESTAMP_SECONDS","TIMESTAMP_MILLIS","TIMESTAMP_MICROS","UNIX_SECONDS","UNIX_MILLIS","UNIX_MICROS","GENERATE_UUID","COALESCE","IF","IFNULL","NULLIF","AVG","BIT_AND","BIT_OR","BIT_XOR","CORR","COUNT","COVAR_POP","COVAR_SAMP","EXACT_COUNT_DISTINCT","FIRST","GROUP_CONCAT","GROUP_CONCAT_UNQUOTED","LAST","MAX","MIN","NEST","NTH","QUANTILES","STDDEV","STDDEV_POP","STDDEV_SAMP","SUM","TOP","UNIQUE","VARIANCE","VAR_POP","VAR_SAMP","BIT_COUNT","BOOLEAN","BYTES","CAST","FLOAT","HEX_STRING","INTEGER","STRING","COALESCE","GREATEST","IFNULL","IS_INF","IS_NAN","IS_EXPLICITLY_DEFINED","LEAST","NVL","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","DATE","DATE_ADD","DATEDIFF","DAY","DAYOFWEEK","DAYOFYEAR","FORMAT_UTC_USEC","HOUR","MINUTE","MONTH","MSEC_TO_TIMESTAMP","NOW","PARSE_UTC_USEC","QUARTER","SEC_TO_TIMESTAMP","SECOND","STRFTIME_UTC_USEC","TIME","TIMESTAMP","TIMESTAMP_TO_MSEC","TIMESTAMP_TO_SEC","TIMESTAMP_TO_USEC","USEC_TO_TIMESTAMP","UTC_USEC_TO_DAY","UTC_USEC_TO_HOUR","UTC_USEC_TO_MONTH","UTC_USEC_TO_WEEK","UTC_USEC_TO_YEAR","WEEK","YEAR","FORMAT_IP","PARSE_IP","FORMAT_PACKED_IP","PARSE_PACKED_IP","JSON_EXTRACT","JSON_EXTRACT_SCALAR","ABS","ACOS","ACOSH","ASIN","ASINH","ATAN","ATANH","ATAN2","CEIL","COS","COSH","DEGREES","EXP","FLOOR","LN","LOG","LOG2","LOG10","PI","POW","RADIANS","RAND","ROUND","SIN","SINH","SQRT","TAN","TANH","REGEXP_MATCH","REGEXP_EXTRACT","REGEXP_REPLACE","CONCAT","INSTR","LEFT","LENGTH","LOWER","LPAD","LTRIM","REPLACE","RIGHT","RPAD","RTRIM","SPLIT","SUBSTR","UPPER","TABLE_DATE_RANGE","TABLE_DATE_RANGE_STRICT","TABLE_QUERY","HOST","DOMAIN","TLD","AVG","COUNT","MAX","MIN","STDDEV","SUM","CUME_DIST","DENSE_RANK","FIRST_VALUE","LAG","LAST_VALUE","LEAD","NTH_VALUE","NTILE","PERCENT_RANK","PERCENTILE_CONT","PERCENTILE_DISC","RANK","RATIO_TO_REPORT","ROW_NUMBER","CURRENT_USER","EVERY","FROM_BASE64","HASH","FARM_FINGERPRINT","IF","POSITION","SHA1","SOME","TO_BASE64","BQ.JOBS.CANCEL","BQ.REFRESH_MATERIALIZED_VIEW","OPTIONS","PIVOT","UNPIVOT"],Ij=["ALL","AND","ANY","AS","ASC","ASSERT_ROWS_MODIFIED","AT","BETWEEN","BY","CASE","CAST","COLLATE","CONTAINS","CREATE","CROSS","CUBE","CURRENT","DEFAULT","DEFINE","DESC","DISTINCT","ELSE","END","ENUM","ESCAPE","EXCEPT","EXCLUDE","EXISTS","EXTRACT","FALSE","FETCH","FOLLOWING","FOR","FROM","FULL","GROUP","GROUPING","GROUPS","HASH","HAVING","IF","IGNORE","IN","INNER","INTERSECT","INTO","IS","JOIN","LATERAL","LEFT","LIMIT","LOOKUP","MERGE","NATURAL","NEW","NO","NOT","NULL","NULLS","OF","ON","OR","ORDER","OUTER","OVER","PARTITION","PRECEDING","PROTO","RANGE","RECURSIVE","RESPECT","RIGHT","ROLLUP","ROWS","SELECT","SET","SOME","TABLE","TABLESAMPLE","THEN","TO","TREAT","TRUE","UNBOUNDED","UNION","UNNEST","USING","WHEN","WHERE","WINDOW","WITH","WITHIN","SAFE","LIKE","COPY","CLONE","IN","OUT","INOUT","RETURNS","LANGUAGE","CASCADE","RESTRICT","DETERMINISTIC"],mj=["ARRAY","BOOL","BYTES","DATE","DATETIME","GEOGRAPHY","INTERVAL","INT64","INT","SMALLINT","INTEGER","BIGINT","TINYINT","BYTEINT","NUMERIC","DECIMAL","BIGNUMERIC","BIGDECIMAL","FLOAT64","STRING","STRUCT","TIME","TIMEZONE"],Oj=j(["SELECT [ALL | DISTINCT] [AS STRUCT | AS VALUE]"]),Nj=j(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","QUALIFY","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","OMIT RECORD IF","INSERT [INTO]","VALUES","SET","MERGE [INTO]","WHEN [NOT] MATCHED [BY SOURCE | BY TARGET] [THEN]","UPDATE SET","CLUSTER BY","FOR SYSTEM_TIME AS OF","WITH CONNECTION","WITH PARTITION COLUMNS","REMOTE WITH CONNECTION"]),lf=j(["CREATE [OR REPLACE] [TEMP|TEMPORARY|SNAPSHOT|EXTERNAL] TABLE [IF NOT EXISTS]"]),Ul=j(["CREATE [OR REPLACE] [MATERIALIZED] VIEW [IF NOT EXISTS]","UPDATE","DELETE [FROM]","DROP [SNAPSHOT | EXTERNAL] TABLE [IF EXISTS]","ALTER TABLE [IF EXISTS]","ADD COLUMN [IF NOT EXISTS]","DROP COLUMN [IF EXISTS]","RENAME TO","ALTER COLUMN [IF EXISTS]","SET DEFAULT COLLATE","SET OPTIONS","DROP NOT NULL","SET DATA TYPE","ALTER SCHEMA [IF EXISTS]","ALTER [MATERIALIZED] VIEW [IF EXISTS]","ALTER BI_CAPACITY","TRUNCATE TABLE","CREATE SCHEMA [IF NOT EXISTS]","DEFAULT COLLATE","CREATE [OR REPLACE] [TEMP|TEMPORARY|TABLE] FUNCTION [IF NOT EXISTS]","CREATE [OR REPLACE] PROCEDURE [IF NOT EXISTS]","CREATE [OR REPLACE] ROW ACCESS POLICY [IF NOT EXISTS]","GRANT TO","FILTER USING","CREATE CAPACITY","AS JSON","CREATE RESERVATION","CREATE ASSIGNMENT","CREATE SEARCH INDEX [IF NOT EXISTS]","DROP SCHEMA [IF EXISTS]","DROP [MATERIALIZED] VIEW [IF EXISTS]","DROP [TABLE] FUNCTION [IF EXISTS]","DROP PROCEDURE [IF EXISTS]","DROP ROW ACCESS POLICY","DROP ALL ROW ACCESS POLICIES","DROP CAPACITY [IF EXISTS]","DROP RESERVATION [IF EXISTS]","DROP ASSIGNMENT [IF EXISTS]","DROP SEARCH INDEX [IF EXISTS]","DROP [IF EXISTS]","GRANT","REVOKE","DECLARE","EXECUTE IMMEDIATE","LOOP","END LOOP","REPEAT","END REPEAT","WHILE","END WHILE","BREAK","LEAVE","CONTINUE","ITERATE","FOR","END FOR","BEGIN","BEGIN TRANSACTION","COMMIT TRANSACTION","ROLLBACK TRANSACTION","RAISE","RETURN","CALL","ASSERT","EXPORT DATA"]),gj=j(["UNION {ALL | DISTINCT}","EXCEPT DISTINCT","INTERSECT DISTINCT"]),xj=j(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),yj=j(["TABLESAMPLE SYSTEM","ANY TYPE","ALL COLUMNS","NOT DETERMINISTIC","{ROWS | RANGE} BETWEEN","IS [NOT] DISTINCT FROM"]),Cj=j([]),Lj={name:"bigquery",tokenizerOptions:{reservedSelect:Oj,reservedClauses:[...Nj,...Ul,...lf],reservedSetOperations:gj,reservedJoins:xj,reservedKeywordPhrases:yj,reservedDataTypePhrases:Cj,reservedKeywords:Ij,reservedDataTypes:mj,reservedFunctionNames:Aj,extraParens:["[]"],stringTypes:[{quote:'""".."""',prefixes:["R","B","RB","BR"]},{quote:"'''..'''",prefixes:["R","B","RB","BR"]},'""-bs',"''-bs",{quote:'""-raw',prefixes:["R","B","RB","BR"],requirePrefix:!0},{quote:"''-raw",prefixes:["R","B","RB","BR"],requirePrefix:!0}],identTypes:["``"],identChars:{dashes:!0},paramTypes:{positional:!0,named:["@"],quoted:["@"]},variableTypes:[{regex:String.raw`@@\w+`}],lineCommentTypes:["--","#"],operators:["&","|","^","~",">>","<<","||","=>"],postProcess:_j},formatOptions:{onelineClauses:[...lf,...Ul],tabularOnelineClauses:Ul}};function _j(e){return bj(Dj(e))}function bj(e){let t=hn;return e.map(n=>n.text==="OFFSET"&&t.text==="["?(t=n,Object.assign(Object.assign({},n),{type:K.RESERVED_FUNCTION_NAME})):(t=n,n))}function Dj(e){var t;const n=[];for(let r=0;r<e.length;r++){const o=e[r];if((An.ARRAY(o)||An.STRUCT(o))&&((t=e[r+1])===null||t===void 0?void 0:t.text)==="<"){const i=Mj(e,r+1),a=e.slice(r,i+1);n.push({type:K.IDENTIFIER,raw:a.map(cf("raw")).join(""),text:a.map(cf("text")).join(""),start:o.start}),r=i}else n.push(o)}return n}const cf=e=>t=>t.type===K.IDENTIFIER||t.type===K.COMMA?t[e]+" ":t[e];function Mj(e,t){let n=0;for(let r=t;r<e.length;r++){const o=e[r];if(o.text==="<"?n++:o.text===">"?n--:o.text===">>"&&(n-=2),n===0)return r}return e.length-1}const vj=["BIT_AND","BIT_OR","BIT_XOR","BLAKE3","CAST","CHARACTER_LENGTH","CHAR_LENGTH","COVAR_POP","COVAR_SAMP","CRC32","CRC32IEEE","CRC64","DATE","DATE_DIFF","DATE_FORMAT","DATE_TRUNC","DAY","DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","FORMAT_BYTES","FQDN","FROM_BASE64","FROM_DAYS","FROM_UNIXTIME","HOUR","INET6_ATON","INET6_NTOA","INET_ATON","INET_NTOA","IPv4CIDRToRange","IPv4NumToString","IPv4NumToStringClassC","IPv4StringToNum","IPv4StringToNumOrDefault","IPv4StringToNumOrNull","IPv4ToIPv6","IPv6CIDRToRange","IPv6NumToString","IPv6StringToNum","IPv6StringToNumOrDefault","IPv6StringToNumOrNull","JSONAllPaths","JSONAllPathsWithTypes","JSONArrayLength","JSONDynamicPaths","JSONDynamicPathsWithTypes","JSONExtract","JSONExtractArrayRaw","JSONExtractArrayRawCaseInsensitive","JSONExtractBool","JSONExtractBoolCaseInsensitive","JSONExtractCaseInsensitive","JSONExtractFloat","JSONExtractFloatCaseInsensitive","JSONExtractInt","JSONExtractIntCaseInsensitive","JSONExtractKeys","JSONExtractKeysAndValues","JSONExtractKeysAndValuesCaseInsensitive","JSONExtractKeysAndValuesRaw","JSONExtractKeysAndValuesRawCaseInsensitive","JSONExtractKeysCaseInsensitive","JSONExtractRaw","JSONExtractRawCaseInsensitive","JSONExtractString","JSONExtractStringCaseInsensitive","JSONExtractUInt","JSONExtractUIntCaseInsensitive","JSONHas","JSONKey","JSONLength","JSONMergePatch","JSONSharedDataPaths","JSONSharedDataPathsWithTypes","JSONType","JSON_ARRAY_LENGTH","JSON_EXISTS","JSON_QUERY","JSON_VALUE","L1Distance","L1Norm","L1Normalize","L2Distance","L2Norm","L2Normalize","L2SquaredDistance","L2SquaredNorm","LAST_DAY","LinfDistance","LinfNorm","LinfNormalize","LpDistance","LpNorm","LpNormalize","MACNumToString","MACStringToNum","MACStringToOUI","MAP_FROM_ARRAYS","MD4","MD5","MILLISECOND","MINUTE","MONTH","OCTET_LENGTH","QUARTER","REGEXP_EXTRACT","REGEXP_MATCHES","REGEXP_REPLACE","RIPEMD160","SCHEMA","SECOND","SHA1","SHA224","SHA256","SHA384","SHA512","SHA512_256","STD","STDDEV_POP","STDDEV_SAMP","ST_LineFromWKB","ST_MLineFromWKB","ST_MPolyFromWKB","ST_PointFromWKB","ST_PolyFromWKB","SUBSTRING_INDEX","SVG","TIMESTAMP_DIFF","TO_BASE64","TO_DAYS","TO_UNIXTIME","ULIDStringToDateTime","URLHash","URLHierarchy","URLPathHierarchy","UTCTimestamp","UTC_timestamp","UUIDNumToString","UUIDStringToNum","UUIDToNum","UUIDv7ToDateTime","VAR_POP","VAR_SAMP","YEAR","YYYYMMDDToDate","YYYYMMDDToDate32","YYYYMMDDhhmmssToDateTime","YYYYMMDDhhmmssToDateTime64","_CAST","__actionName","__bitBoolMaskAnd","__bitBoolMaskOr","__bitSwapLastTwo","__bitWrapperFunc","__getScalar","__patchPartitionID","__scalarSubqueryResult","abs","accurateCast","accurateCastOrDefault","accurateCastOrNull","acos","acosh","addDate","addDays","addHours","addInterval","addMicroseconds","addMilliseconds","addMinutes","addMonths","addNanoseconds","addQuarters","addSeconds","addTupleOfIntervals","addWeeks","addYears","addressToLine","addressToLineWithInlines","addressToSymbol","aes_decrypt_mysql","aes_encrypt_mysql","age","aggThrow","alphaTokens","analysisOfVariance","anova","any","anyHeavy","anyLast","anyLastRespectNulls","anyLast_respect_nulls","anyRespectNulls","anyValueRespectNulls","any_respect_nulls","any_value","any_value_respect_nulls","appendTrailingCharIfAbsent","approx_top_count","approx_top_k","approx_top_sum","argMax","argMin","array","arrayAUC","arrayAUCPR","arrayAll","arrayAvg","arrayCompact","arrayConcat","arrayCount","arrayCumSum","arrayCumSumNonNegative","arrayDifference","arrayDistinct","arrayDotProduct","arrayElement","arrayElementOrNull","arrayEnumerate","arrayEnumerateDense","arrayEnumerateDenseRanked","arrayEnumerateUniq","arrayEnumerateUniqRanked","arrayExists","arrayFill","arrayFilter","arrayFirst","arrayFirstIndex","arrayFirstOrNull","arrayFlatten","arrayFold","arrayIntersect","arrayJaccardIndex","arrayJoin","arrayLast","arrayLastIndex","arrayLastOrNull","arrayLevenshteinDistance","arrayLevenshteinDistanceWeighted","arrayMap","arrayMax","arrayMin","arrayNormalizedGini","arrayPRAUC","arrayPartialReverseSort","arrayPartialShuffle","arrayPartialSort","arrayPopBack","arrayPopFront","arrayProduct","arrayPushBack","arrayPushFront","arrayROCAUC","arrayRandomSample","arrayReduce","arrayReduceInRanges","arrayResize","arrayReverse","arrayReverseFill","arrayReverseSort","arrayReverseSplit","arrayRotateLeft","arrayRotateRight","arrayShiftLeft","arrayShiftRight","arrayShingles","arrayShuffle","arraySimilarity","arraySlice","arraySort","arraySplit","arrayStringConcat","arraySum","arraySymmetricDifference","arrayUnion","arrayUniq","arrayWithConstant","arrayZip","arrayZipUnaligned","array_agg","array_concat_agg","ascii","asin","asinh","assumeNotNull","atan","atan2","atanh","authenticatedUser","avg","avgWeighted","bar","base32Decode","base32Encode","base58Decode","base58Encode","base64Decode","base64Encode","base64URLDecode","base64URLEncode","basename","bech32Decode","bech32Encode","bin","bitAnd","bitCount","bitHammingDistance","bitNot","bitOr","bitPositionsToArray","bitRotateLeft","bitRotateRight","bitShiftLeft","bitShiftRight","bitSlice","bitTest","bitTestAll","bitTestAny","bitXor","bitmapAnd","bitmapAndCardinality","bitmapAndnot","bitmapAndnotCardinality","bitmapBuild","bitmapCardinality","bitmapContains","bitmapHasAll","bitmapHasAny","bitmapMax","bitmapMin","bitmapOr","bitmapOrCardinality","bitmapSubsetInRange","bitmapSubsetLimit","bitmapToArray","bitmapTransform","bitmapXor","bitmapXorCardinality","bitmaskToArray","bitmaskToList","blockNumber","blockSerializedSize","blockSize","boundingRatio","buildId","byteHammingDistance","byteSize","byteSlice","byteSwap","caseWithExpr","caseWithExpression","caseWithoutExpr","caseWithoutExpression","catboostEvaluate","categoricalInformationValue","cbrt","ceil","ceiling","changeDay","changeHour","changeMinute","changeMonth","changeSecond","changeYear","char","cityHash64","clamp","coalesce","colorOKLCHToSRGB","colorSRGBToOKLCH","compareSubstrings","concat","concatAssumeInjective","concatWithSeparator","concatWithSeparatorAssumeInjective","concat_ws","connectionId","connection_id","contingency","convertCharset","corr","corrMatrix","corrStable","cos","cosh","cosineDistance","count","countDigits","countEqual","countMatches","countMatchesCaseInsensitive","countSubstrings","countSubstringsCaseInsensitive","countSubstringsCaseInsensitiveUTF8","covarPop","covarPopMatrix","covarPopStable","covarSamp","covarSampMatrix","covarSampStable","cramersV","cramersVBiasCorrected","curdate","currentDatabase","currentProfiles","currentQueryID","currentRoles","currentSchemas","currentUser","current_database","current_date","current_query_id","current_schemas","current_timestamp","current_user","cutFragment","cutIPv6","cutQueryString","cutQueryStringAndFragment","cutToFirstSignificantSubdomain","cutToFirstSignificantSubdomainCustom","cutToFirstSignificantSubdomainCustomRFC","cutToFirstSignificantSubdomainCustomWithWWW","cutToFirstSignificantSubdomainCustomWithWWWRFC","cutToFirstSignificantSubdomainRFC","cutToFirstSignificantSubdomainWithWWW","cutToFirstSignificantSubdomainWithWWWRFC","cutURLParameter","cutWWW","damerauLevenshteinDistance","dateDiff","dateName","dateTime64ToSnowflake","dateTime64ToSnowflakeID","dateTimeToSnowflake","dateTimeToSnowflakeID","dateTimeToUUIDv7","dateTrunc","date_bin","date_diff","decodeHTMLComponent","decodeURLComponent","decodeURLFormComponent","decodeXMLComponent","decrypt","defaultProfiles","defaultRoles","defaultValueOfArgumentType","defaultValueOfTypeName","degrees","deltaSum","deltaSumTimestamp","demangle","denseRank","dense_rank","detectCharset","detectLanguage","detectLanguageMixed","detectLanguageUnknown","detectProgrammingLanguage","detectTonality","dictGet","dictGetAll","dictGetChildren","dictGetDate","dictGetDateOrDefault","dictGetDateTime","dictGetDateTimeOrDefault","dictGetDescendants","dictGetFloat32","dictGetFloat32OrDefault","dictGetFloat64","dictGetFloat64OrDefault","dictGetHierarchy","dictGetIPv4","dictGetIPv4OrDefault","dictGetIPv6","dictGetIPv6OrDefault","dictGetInt16","dictGetInt16OrDefault","dictGetInt32","dictGetInt32OrDefault","dictGetInt64","dictGetInt64OrDefault","dictGetInt8","dictGetInt8OrDefault","dictGetOrDefault","dictGetOrNull","dictGetString","dictGetStringOrDefault","dictGetUInt16","dictGetUInt16OrDefault","dictGetUInt32","dictGetUInt32OrDefault","dictGetUInt64","dictGetUInt64OrDefault","dictGetUInt8","dictGetUInt8OrDefault","dictGetUUID","dictGetUUIDOrDefault","dictHas","dictIsIn","displayName","distanceL1","distanceL2","distanceL2Squared","distanceLinf","distanceLp","distinctDynamicTypes","distinctJSONPaths","distinctJSONPathsAndTypes","divide","divideDecimal","divideOrNull","domain","domainRFC","domainWithoutWWW","domainWithoutWWWRFC","dotProduct","dumpColumnStructure","dynamicElement","dynamicType","e","editDistance","editDistanceUTF8","empty","emptyArrayDate","emptyArrayDateTime","emptyArrayFloat32","emptyArrayFloat64","emptyArrayInt16","emptyArrayInt32","emptyArrayInt64","emptyArrayInt8","emptyArrayString","emptyArrayToSingle","emptyArrayUInt16","emptyArrayUInt32","emptyArrayUInt64","emptyArrayUInt8","enabledProfiles","enabledRoles","encodeURLComponent","encodeURLFormComponent","encodeXMLComponent","encrypt","endsWith","endsWithUTF8","entropy","equals","erf","erfc","errorCodeToName","estimateCompressionRatio","evalMLMethod","exp","exp10","exp2","exponentialMovingAverage","exponentialTimeDecayedAvg","exponentialTimeDecayedCount","exponentialTimeDecayedMax","exponentialTimeDecayedSum","extract","extractAll","extractAllGroups","extractAllGroupsHorizontal","extractAllGroupsVertical","extractGroups","extractKeyValuePairs","extractKeyValuePairsWithEscaping","extractTextFromHTML","extractURLParameter","extractURLParameterNames","extractURLParameters","factorial","farmFingerprint64","farmHash64","file","filesystemAvailable","filesystemCapacity","filesystemUnreserved","finalizeAggregation","financialInternalRateOfReturn","financialInternalRateOfReturnExtended","financialNetPresentValue","financialNetPresentValueExtended","firstLine","firstSignificantSubdomain","firstSignificantSubdomainCustom","firstSignificantSubdomainCustomRFC","firstSignificantSubdomainRFC","firstValueRespectNulls","first_value","first_value_respect_nulls","flameGraph","flatten","flattenTuple","floor","formatDateTime","formatDateTimeInJodaSyntax","formatQuery","formatQueryOrNull","formatQuerySingleLine","formatQuerySingleLineOrNull","formatReadableDecimalSize","formatReadableQuantity","formatReadableSize","formatReadableTimeDelta","formatRow","formatRowNoNewline","fragment","fromDaysSinceYearZero","fromDaysSinceYearZero32","fromModifiedJulianDay","fromModifiedJulianDayOrNull","fromUTCTimestamp","fromUnixTimestamp","fromUnixTimestamp64Micro","fromUnixTimestamp64Milli","fromUnixTimestamp64Nano","fromUnixTimestamp64Second","fromUnixTimestampInJodaSyntax","from_utc_timestamp","fullHostName","fuzzBits","gccMurmurHash","gcd","generateRandomStructure","generateSerialID","generateSnowflakeID","generateULID","generateUUIDv4","generateUUIDv7","geoDistance","geoToH3","geoToS2","geohashDecode","geohashEncode","geohashesInBox","getClientHTTPHeader","getMacro","getMaxTableNameLengthForDatabase","getMergeTreeSetting","getOSKernelVersion","getServerPort","getServerSetting","getSetting","getSettingOrDefault","getSizeOfEnumType","getSubcolumn","getTypeSerializationStreams","globalIn","globalInIgnoreSet","globalNotIn","globalNotInIgnoreSet","globalNotNullIn","globalNotNullInIgnoreSet","globalNullIn","globalNullInIgnoreSet","globalVariable","greatCircleAngle","greatCircleDistance","greater","greaterOrEquals","greatest","groupArray","groupArrayInsertAt","groupArrayIntersect","groupArrayLast","groupArrayMovingAvg","groupArrayMovingSum","groupArraySample","groupArraySorted","groupBitAnd","groupBitOr","groupBitXor","groupBitmap","groupBitmapAnd","groupBitmapOr","groupBitmapXor","groupConcat","groupNumericIndexedVector","groupUniqArray","group_concat","h3CellAreaM2","h3CellAreaRads2","h3Distance","h3EdgeAngle","h3EdgeLengthKm","h3EdgeLengthM","h3ExactEdgeLengthKm","h3ExactEdgeLengthM","h3ExactEdgeLengthRads","h3GetBaseCell","h3GetDestinationIndexFromUnidirectionalEdge","h3GetFaces","h3GetIndexesFromUnidirectionalEdge","h3GetOriginIndexFromUnidirectionalEdge","h3GetPentagonIndexes","h3GetRes0Indexes","h3GetResolution","h3GetUnidirectionalEdge","h3GetUnidirectionalEdgeBoundary","h3GetUnidirectionalEdgesFromHexagon","h3HexAreaKm2","h3HexAreaM2","h3HexRing","h3IndexesAreNeighbors","h3IsPentagon","h3IsResClassIII","h3IsValid","h3Line","h3NumHexagons","h3PointDistKm","h3PointDistM","h3PointDistRads","h3ToCenterChild","h3ToChildren","h3ToGeo","h3ToGeoBoundary","h3ToParent","h3ToString","h3UnidirectionalEdgeIsValid","h3kRing","halfMD5","has","hasAll","hasAny","hasColumnInTable","hasSubsequence","hasSubsequenceCaseInsensitive","hasSubsequenceCaseInsensitiveUTF8","hasSubsequenceUTF8","hasSubstr","hasThreadFuzzer","hasToken","hasTokenCaseInsensitive","hasTokenCaseInsensitiveOrNull","hasTokenOrNull","hex","hilbertDecode","hilbertEncode","histogram","hiveHash","hop","hopEnd","hopStart","hostName","hostname","hypot","icebergBucket","icebergHash","icebergTruncate","identity","idnaDecode","idnaEncode","if","ifNotFinite","ifNull","ignore","inIgnoreSet","indexHint","indexOf","indexOfAssumeSorted","initcap","initcapUTF8","initialQueryID","initialQueryStartTime","initial_query_id","initial_query_start_time","initializeAggregation","instr","intDiv","intDivOrNull","intDivOrZero","intExp10","intExp2","intHash32","intHash64","intervalLengthSum","isConstant","isDecimalOverflow","isDynamicElementInSharedData","isFinite","isIPAddressInRange","isIPv4String","isIPv6String","isInfinite","isMergeTreePartCoveredBy","isNaN","isNotDistinctFrom","isNotNull","isNull","isNullable","isValidJSON","isValidUTF8","isZeroOrNull","jaroSimilarity","jaroWinklerSimilarity","javaHash","javaHashUTF16LE","joinGet","joinGetOrNull","jsonMergePatch","jumpConsistentHash","kafkaMurmurHash","keccak256","kolmogorovSmirnovTest","kostikConsistentHash","kql_array_sort_asc","kql_array_sort_desc","kurtPop","kurtSamp","lag","lagInFrame","largestTriangleThreeBuckets","lastValueRespectNulls","last_value","last_value_respect_nulls","lcase","lcm","lead","leadInFrame","least","left","leftPad","leftPadUTF8","leftUTF8","lemmatize","length","lengthUTF8","less","lessOrEquals","levenshteinDistance","levenshteinDistanceUTF8","lgamma","ln","locate","log","log10","log1p","log2","logTrace","lowCardinalityIndices","lowCardinalityKeys","lower","lowerUTF8","lpad","ltrim","lttb","makeDate","makeDate32","makeDateTime","makeDateTime64","mannWhitneyUTest","map","mapAdd","mapAll","mapApply","mapConcat","mapContains","mapContainsKey","mapContainsKeyLike","mapContainsValue","mapContainsValueLike","mapExists","mapExtractKeyLike","mapExtractValueLike","mapFilter","mapFromArrays","mapFromString","mapKeys","mapPartialReverseSort","mapPartialSort","mapPopulateSeries","mapReverseSort","mapSort","mapSubtract","mapUpdate","mapValues","match","materialize","max","max2","maxIntersections","maxIntersectionsPosition","maxMappedArrays","meanZTest","median","medianBFloat16","medianBFloat16Weighted","medianDD","medianDeterministic","medianExact","medianExactHigh","medianExactLow","medianExactWeighted","medianExactWeightedInterpolated","medianGK","medianInterpolatedWeighted","medianTDigest","medianTDigestWeighted","medianTiming","medianTimingWeighted","mergeTreePartInfo","metroHash64","mid","min","min2","minMappedArrays","minSampleSizeContinous","minSampleSizeContinuous","minSampleSizeConversion","minus","mismatches","mod","modOrNull","modulo","moduloLegacy","moduloOrNull","moduloOrZero","monthName","mortonDecode","mortonEncode","multiFuzzyMatchAllIndices","multiFuzzyMatchAny","multiFuzzyMatchAnyIndex","multiIf","multiMatchAllIndices","multiMatchAny","multiMatchAnyIndex","multiSearchAllPositions","multiSearchAllPositionsCaseInsensitive","multiSearchAllPositionsCaseInsensitiveUTF8","multiSearchAllPositionsUTF8","multiSearchAny","multiSearchAnyCaseInsensitive","multiSearchAnyCaseInsensitiveUTF8","multiSearchAnyUTF8","multiSearchFirstIndex","multiSearchFirstIndexCaseInsensitive","multiSearchFirstIndexCaseInsensitiveUTF8","multiSearchFirstIndexUTF8","multiSearchFirstPosition","multiSearchFirstPositionCaseInsensitive","multiSearchFirstPositionCaseInsensitiveUTF8","multiSearchFirstPositionUTF8","multiply","multiplyDecimal","murmurHash2_32","murmurHash2_64","murmurHash3_128","murmurHash3_32","murmurHash3_64","negate","neighbor","nested","netloc","ngramDistance","ngramDistanceCaseInsensitive","ngramDistanceCaseInsensitiveUTF8","ngramDistanceUTF8","ngramMinHash","ngramMinHashArg","ngramMinHashArgCaseInsensitive","ngramMinHashArgCaseInsensitiveUTF8","ngramMinHashArgUTF8","ngramMinHashCaseInsensitive","ngramMinHashCaseInsensitiveUTF8","ngramMinHashUTF8","ngramSearch","ngramSearchCaseInsensitive","ngramSearchCaseInsensitiveUTF8","ngramSearchUTF8","ngramSimHash","ngramSimHashCaseInsensitive","ngramSimHashCaseInsensitiveUTF8","ngramSimHashUTF8","ngrams","nonNegativeDerivative","normL1","normL2","normL2Squared","normLinf","normLp","normalizeL1","normalizeL2","normalizeLinf","normalizeLp","normalizeQuery","normalizeQueryKeepNames","normalizeUTF8NFC","normalizeUTF8NFD","normalizeUTF8NFKC","normalizeUTF8NFKD","normalizedQueryHash","normalizedQueryHashKeepNames","notEmpty","notEquals","notILike","notIn","notInIgnoreSet","notLike","notNullIn","notNullInIgnoreSet","nothing","nothingNull","nothingUInt64","now","now64","nowInBlock","nowInBlock64","nth_value","ntile","nullIf","nullIn","nullInIgnoreSet","numbers","numericIndexedVectorAllValueSum","numericIndexedVectorBuild","numericIndexedVectorCardinality","numericIndexedVectorGetValue","numericIndexedVectorPointwiseAdd","numericIndexedVectorPointwiseDivide","numericIndexedVectorPointwiseEqual","numericIndexedVectorPointwiseGreater","numericIndexedVectorPointwiseGreaterEqual","numericIndexedVectorPointwiseLess","numericIndexedVectorPointwiseLessEqual","numericIndexedVectorPointwiseMultiply","numericIndexedVectorPointwiseNotEqual","numericIndexedVectorPointwiseSubtract","numericIndexedVectorShortDebugString","numericIndexedVectorToMap","overlay","overlayUTF8","parseDateTime","parseDateTime32BestEffort","parseDateTime32BestEffortOrNull","parseDateTime32BestEffortOrZero","parseDateTime64","parseDateTime64BestEffort","parseDateTime64BestEffortOrNull","parseDateTime64BestEffortOrZero","parseDateTime64BestEffortUS","parseDateTime64BestEffortUSOrNull","parseDateTime64BestEffortUSOrZero","parseDateTime64InJodaSyntax","parseDateTime64InJodaSyntaxOrNull","parseDateTime64InJodaSyntaxOrZero","parseDateTime64OrNull","parseDateTime64OrZero","parseDateTimeBestEffort","parseDateTimeBestEffortOrNull","parseDateTimeBestEffortOrZero","parseDateTimeBestEffortUS","parseDateTimeBestEffortUSOrNull","parseDateTimeBestEffortUSOrZero","parseDateTimeInJodaSyntax","parseDateTimeInJodaSyntaxOrNull","parseDateTimeInJodaSyntaxOrZero","parseDateTimeOrNull","parseDateTimeOrZero","parseReadableSize","parseReadableSizeOrNull","parseReadableSizeOrZero","parseTimeDelta","partitionID","partitionId","path","pathFull","percentRank","percent_rank","pi","plus","pmod","pmodOrNull","pointInEllipses","pointInPolygon","polygonAreaCartesian","polygonAreaSpherical","polygonConvexHullCartesian","polygonPerimeterCartesian","polygonPerimeterSpherical","polygonsDistanceCartesian","polygonsDistanceSpherical","polygonsEqualsCartesian","polygonsIntersectCartesian","polygonsIntersectSpherical","polygonsIntersectionCartesian","polygonsIntersectionSpherical","polygonsSymDifferenceCartesian","polygonsSymDifferenceSpherical","polygonsUnionCartesian","polygonsUnionSpherical","polygonsWithinCartesian","polygonsWithinSpherical","port","portRFC","position","positionCaseInsensitive","positionCaseInsensitiveUTF8","positionUTF8","positiveModulo","positiveModuloOrNull","positive_modulo","positive_modulo_or_null","pow","power","printf","proportionsZTest","protocol","punycodeDecode","punycodeEncode","quantile","quantileBFloat16","quantileBFloat16Weighted","quantileDD","quantileDeterministic","quantileExact","quantileExactExclusive","quantileExactHigh","quantileExactInclusive","quantileExactLow","quantileExactWeighted","quantileExactWeightedInterpolated","quantileGK","quantileInterpolatedWeighted","quantileTDigest","quantileTDigestWeighted","quantileTiming","quantileTimingWeighted","quantiles","quantilesBFloat16","quantilesBFloat16Weighted","quantilesDD","quantilesDeterministic","quantilesExact","quantilesExactExclusive","quantilesExactHigh","quantilesExactInclusive","quantilesExactLow","quantilesExactWeighted","quantilesExactWeightedInterpolated","quantilesGK","quantilesInterpolatedWeighted","quantilesTDigest","quantilesTDigestWeighted","quantilesTiming","quantilesTimingWeighted","queryID","queryString","queryStringAndFragment","query_id","radians","rand","rand32","rand64","randBernoulli","randBinomial","randCanonical","randChiSquared","randConstant","randExponential","randFisherF","randLogNormal","randNegativeBinomial","randNormal","randPoisson","randStudentT","randUniform","randomFixedString","randomPrintableASCII","randomString","randomStringUTF8","rank","rankCorr","readWKBLineString","readWKBMultiLineString","readWKBMultiPolygon","readWKBPoint","readWKBPolygon","readWKTLineString","readWKTMultiLineString","readWKTMultiPolygon","readWKTPoint","readWKTPolygon","readWKTRing","regexpExtract","regexpQuoteMeta","regionHierarchy","regionIn","regionToArea","regionToCity","regionToContinent","regionToCountry","regionToDistrict","regionToName","regionToPopulation","regionToTopContinent","reinterpret","reinterpretAsDate","reinterpretAsDateTime","reinterpretAsFixedString","reinterpretAsFloat32","reinterpretAsFloat64","reinterpretAsInt128","reinterpretAsInt16","reinterpretAsInt256","reinterpretAsInt32","reinterpretAsInt64","reinterpretAsInt8","reinterpretAsString","reinterpretAsUInt128","reinterpretAsUInt16","reinterpretAsUInt256","reinterpretAsUInt32","reinterpretAsUInt64","reinterpretAsUInt8","reinterpretAsUUID","repeat","replace","replaceAll","replaceOne","replaceRegexpAll","replaceRegexpOne","replicate","retention","reverse","reverseUTF8","revision","right","rightPad","rightPadUTF8","rightUTF8","round","roundAge","roundBankers","roundDown","roundDuration","roundToExp2","rowNumberInAllBlocks","rowNumberInBlock","row_number","rpad","rtrim","runningAccumulate","runningConcurrency","runningDifference","runningDifferenceStartingWithFirstValue","s2CapContains","s2CapUnion","s2CellsIntersect","s2GetNeighbors","s2RectAdd","s2RectContains","s2RectIntersection","s2RectUnion","s2ToGeo","scalarProduct","searchAll","searchAny","sequenceCount","sequenceMatch","sequenceMatchEvents","sequenceNextNode","seriesDecomposeSTL","seriesOutliersDetectTukey","seriesPeriodDetectFFT","serverTimeZone","serverTimezone","serverUUID","shardCount","shardNum","showCertificate","sigmoid","sign","simpleJSONExtractBool","simpleJSONExtractFloat","simpleJSONExtractInt","simpleJSONExtractRaw","simpleJSONExtractString","simpleJSONExtractUInt","simpleJSONHas","simpleLinearRegression","sin","singleValueOrNull","sinh","sipHash128","sipHash128Keyed","sipHash128Reference","sipHash128ReferenceKeyed","sipHash64","sipHash64Keyed","skewPop","skewSamp","sleep","sleepEachRow","snowflakeIDToDateTime","snowflakeIDToDateTime64","snowflakeToDateTime","snowflakeToDateTime64","soundex","space","sparkBar","sparkbar","sparseGrams","sparseGramsHashes","sparseGramsHashesUTF8","sparseGramsUTF8","splitByAlpha","splitByChar","splitByNonAlpha","splitByRegexp","splitByString","splitByWhitespace","sqid","sqidDecode","sqidEncode","sqrt","startsWith","startsWithUTF8","stddevPop","stddevPopStable","stddevSamp","stddevSampStable","stem","stochasticLinearRegression","stochasticLogisticRegression","str_to_date","str_to_map","stringBytesEntropy","stringBytesUniq","stringJaccardIndex","stringJaccardIndexUTF8","stringToH3","structureToCapnProtoSchema","structureToProtobufSchema","studentTTest","subBitmap","subDate","substr","substring","substringIndex","substringIndexUTF8","substringUTF8","subtractDays","subtractHours","subtractInterval","subtractMicroseconds","subtractMilliseconds","subtractMinutes","subtractMonths","subtractNanoseconds","subtractQuarters","subtractSeconds","subtractTupleOfIntervals","subtractWeeks","subtractYears","sum","sumCount","sumKahan","sumMapFiltered","sumMapFilteredWithOverflow","sumMapWithOverflow","sumMappedArrays","sumWithOverflow","svg","synonyms","tan","tanh","tcpPort","tgamma","theilsU","throwIf","tid","timeDiff","timeSeriesDeltaToGrid","timeSeriesDerivToGrid","timeSeriesFromGrid","timeSeriesGroupArray","timeSeriesIdToTags","timeSeriesIdToTagsGroup","timeSeriesIdeltaToGrid","timeSeriesInstantDeltaToGrid","timeSeriesInstantRateToGrid","timeSeriesIrateToGrid","timeSeriesLastToGrid","timeSeriesLastTwoSamples","timeSeriesPredictLinearToGrid","timeSeriesRange","timeSeriesRateToGrid","timeSeriesResampleToGridWithStaleness","timeSeriesStoreTags","timeSeriesTagsGroupToTags","timeSlot","timeSlots","timeZone","timeZoneOf","timeZoneOffset","time_bucket","timestamp","timestampDiff","timestamp_diff","timezone","timezoneOf","timezoneOffset","toBFloat16","toBFloat16OrNull","toBFloat16OrZero","toBool","toColumnTypeName","toDate","toDate32","toDate32OrDefault","toDate32OrNull","toDate32OrZero","toDateOrDefault","toDateOrNull","toDateOrZero","toDateTime","toDateTime32","toDateTime64","toDateTime64OrDefault","toDateTime64OrNull","toDateTime64OrZero","toDateTimeOrDefault","toDateTimeOrNull","toDateTimeOrZero","toDayOfMonth","toDayOfWeek","toDayOfYear","toDaysSinceYearZero","toDecimal128","toDecimal128OrDefault","toDecimal128OrNull","toDecimal128OrZero","toDecimal256","toDecimal256OrDefault","toDecimal256OrNull","toDecimal256OrZero","toDecimal32","toDecimal32OrDefault","toDecimal32OrNull","toDecimal32OrZero","toDecimal64","toDecimal64OrDefault","toDecimal64OrNull","toDecimal64OrZero","toDecimalString","toFixedString","toFloat32","toFloat32OrDefault","toFloat32OrNull","toFloat32OrZero","toFloat64","toFloat64OrDefault","toFloat64OrNull","toFloat64OrZero","toHour","toIPv4","toIPv4OrDefault","toIPv4OrNull","toIPv4OrZero","toIPv6","toIPv6OrDefault","toIPv6OrNull","toIPv6OrZero","toISOWeek","toISOYear","toInt128","toInt128OrDefault","toInt128OrNull","toInt128OrZero","toInt16","toInt16OrDefault","toInt16OrNull","toInt16OrZero","toInt256","toInt256OrDefault","toInt256OrNull","toInt256OrZero","toInt32","toInt32OrDefault","toInt32OrNull","toInt32OrZero","toInt64","toInt64OrDefault","toInt64OrNull","toInt64OrZero","toInt8","toInt8OrDefault","toInt8OrNull","toInt8OrZero","toInterval","toIntervalDay","toIntervalHour","toIntervalMicrosecond","toIntervalMillisecond","toIntervalMinute","toIntervalMonth","toIntervalNanosecond","toIntervalQuarter","toIntervalSecond","toIntervalWeek","toIntervalYear","toJSONString","toLastDayOfMonth","toLastDayOfWeek","toLowCardinality","toMillisecond","toMinute","toModifiedJulianDay","toModifiedJulianDayOrNull","toMonday","toMonth","toMonthNumSinceEpoch","toNullable","toQuarter","toRelativeDayNum","toRelativeHourNum","toRelativeMinuteNum","toRelativeMonthNum","toRelativeQuarterNum","toRelativeSecondNum","toRelativeWeekNum","toRelativeYearNum","toSecond","toStartOfDay","toStartOfFifteenMinutes","toStartOfFiveMinute","toStartOfFiveMinutes","toStartOfHour","toStartOfISOYear","toStartOfInterval","toStartOfMicrosecond","toStartOfMillisecond","toStartOfMinute","toStartOfMonth","toStartOfNanosecond","toStartOfQuarter","toStartOfSecond","toStartOfTenMinutes","toStartOfWeek","toStartOfYear","toString","toStringCutToZero","toTime","toTime64","toTime64OrNull","toTime64OrZero","toTimeOrNull","toTimeOrZero","toTimeWithFixedDate","toTimeZone","toTimezone","toTypeName","toUInt128","toUInt128OrDefault","toUInt128OrNull","toUInt128OrZero","toUInt16","toUInt16OrDefault","toUInt16OrNull","toUInt16OrZero","toUInt256","toUInt256OrDefault","toUInt256OrNull","toUInt256OrZero","toUInt32","toUInt32OrDefault","toUInt32OrNull","toUInt32OrZero","toUInt64","toUInt64OrDefault","toUInt64OrNull","toUInt64OrZero","toUInt8","toUInt8OrDefault","toUInt8OrNull","toUInt8OrZero","toUTCTimestamp","toUUID","toUUIDOrDefault","toUUIDOrNull","toUUIDOrZero","toUnixTimestamp","toUnixTimestamp64Micro","toUnixTimestamp64Milli","toUnixTimestamp64Nano","toUnixTimestamp64Second","toValidUTF8","toWeek","toYYYYMM","toYYYYMMDD","toYYYYMMDDhhmmss","toYear","toYearNumSinceEpoch","toYearWeek","to_utc_timestamp","today","tokens","topK","topKWeighted","topLevelDomain","topLevelDomainRFC","transactionID","transactionLatestSnapshot","transactionOldestSnapshot","transform","translate","translateUTF8","trim","trimBoth","trimLeft","trimRight","trunc","tryBase32Decode","tryBase58Decode","tryBase64Decode","tryBase64URLDecode","tryDecrypt","tryIdnaEncode","tryPunycodeDecode","tumble","tumbleEnd","tumbleStart","tuple","tupleConcat","tupleDivide","tupleDivideByNumber","tupleElement","tupleHammingDistance","tupleIntDiv","tupleIntDivByNumber","tupleIntDivOrZero","tupleIntDivOrZeroByNumber","tupleMinus","tupleModulo","tupleModuloByNumber","tupleMultiply","tupleMultiplyByNumber","tupleNames","tupleNegate","tuplePlus","tupleToNameValuePairs","ucase","unbin","unhex","uniq","uniqCombined","uniqCombined64","uniqExact","uniqHLL12","uniqTheta","uniqThetaIntersect","uniqThetaNot","uniqThetaUnion","uniqUpTo","upper","upperUTF8","uptime","user","validateNestedArraySizes","varPop","varPopStable","varSamp","varSampStable","variantElement","variantType","vectorDifference","vectorSum","version","visibleWidth","visitParamExtractBool","visitParamExtractFloat","visitParamExtractInt","visitParamExtractRaw","visitParamExtractString","visitParamExtractUInt","visitParamHas","week","welchTTest","widthBucket","width_bucket","windowFunnel","windowID","wkb","wkt","wordShingleMinHash","wordShingleMinHashArg","wordShingleMinHashArgCaseInsensitive","wordShingleMinHashArgCaseInsensitiveUTF8","wordShingleMinHashArgUTF8","wordShingleMinHashCaseInsensitive","wordShingleMinHashCaseInsensitiveUTF8","wordShingleMinHashUTF8","wordShingleSimHash","wordShingleSimHashCaseInsensitive","wordShingleSimHashCaseInsensitiveUTF8","wordShingleSimHashUTF8","wyHash64","xor","xxHash32","xxHash64","xxh3","yandexConsistentHash","yearweek","yesterday","zookeeperSessionUptime","MergeTree","ReplacingMergeTree","SummingMergeTree","AggregatingMergeTree","CollapsingMergeTree","VersionedCollapsingMergeTree","GraphiteMergeTree","CoalescingMergeTree","Atomic","Shared","Lazy","Replicated","PostgreSQL","MySQL","SQLite","MaterializedPostgreSQL","DataLakeCatalog"],Pj=["ACCESS","ACTION","ADD","ADMIN","AFTER","ALGORITHM","ALIAS","ALL","ALLOWED_LATENESS","ALTER","AND","ANTI","APPEND","APPLY","AS","ASC","ASCENDING","ASOF","ASSUME","AST","ASYNC","ATTACH","AUTO_INCREMENT","AZURE","BACKUP","BAGEXPANSION","BASE_BACKUP","BCRYPT_HASH","BCRYPT_PASSWORD","BEGIN","BETWEEN","BIDIRECTIONAL","BOTH","BY","CACHE","CACHES","CASCADE","CASE","CHANGE","CHANGEABLE_IN_READONLY","CHANGED","CHARACTER","CHECK","CLEANUP","CLEAR","CLUSTER","CLUSTERS","CLUSTER_HOST_IDS","CN","CODEC","COLLATE","COLLECTION","COLUMN","COLUMNS","COMMENT","COMMIT","COMPRESSION","CONST","CONSTRAINT","CREATE","CROSS","CUBE","CURRENT","D","DATA","DATABASE","DATABASES","DAYS","DD","DDL","DEDUPLICATE","DEFAULT","DEFINER","DELAY","DELETE","DELETED","DEPENDS","DESC","DESCENDING","DESCRIBE","DETACH","DETACHED","DICTIONARIES","DICTIONARY","DISK","DISTINCT","DIV","DOUBLE_SHA1_HASH","DOUBLE_SHA1_PASSWORD","DROP","ELSE","ENABLED","END","ENFORCED","ENGINE","ENGINES","EPHEMERAL","ESTIMATE","EVENT","EVENTS","EVERY","EXCEPT","EXCHANGE","EXISTS","EXPLAIN","EXPRESSION","EXTENDED","EXTERNAL","FAKE","FALSE","FETCH","FIELDS","FILESYSTEM","FILL","FILTER","FINAL","FIRST","FOLLOWING","FOR","FOREIGN","FORMAT","FREEZE","FROM","FULL","FULLTEXT","FUNCTION","FUNCTIONS","GLOBAL","GRANT","GRANTEES","GRANTS","GRANULARITY","GROUP","GROUPING","GROUPS","H","HASH","HAVING","HDFS","HH","HIERARCHICAL","HOST","HOURS","HTTP","IDENTIFIED","ILIKE","IN","INDEX","INDEXES","INDICES","INFILE","INHERIT","INJECTIVE","INNER","INSERT","INTERPOLATE","INTERSECT","INTERVAL","INTO","INVISIBLE","INVOKER","IP","IS","IS_OBJECT_ID","JOIN","JWT","KERBEROS","KEY","KEYED","KEYS","KILL","KIND","LARGE","LAST","LAYOUT","LDAP","LEADING","LEVEL","LIFETIME","LIGHTWEIGHT","LIKE","LIMIT","LIMITS","LINEAR","LIST","LIVE","LOCAL","M","MASK","MATERIALIZED","MCS","MEMORY","MERGES","METRICS","MI","MICROSECOND","MICROSECONDS","MILLISECONDS","MINUTES","MM","MODIFY","MONTHS","MOVE","MS","MUTATION","N","NAME","NAMED","NANOSECOND","NANOSECONDS","NEXT","NO","NONE","NOT","NO_PASSWORD","NS","NULL","NULLS","OBJECT","OFFSET","ON","ONLY","OPTIMIZE","OPTION","OR","ORDER","OUTER","OUTFILE","OVER","OVERRIDABLE","OVERRIDE","PART","PARTIAL","PARTITION","PARTITIONS","PART_MOVE_TO_SHARD","PASTE","PERIODIC","PERMANENTLY","PERMISSIVE","PERSISTENT","PIPELINE","PLAINTEXT_PASSWORD","PLAN","POLICY","POPULATE","PRECEDING","PRECISION","PREWHERE","PRIMARY","PRIVILEGES","PROCESSLIST","PROFILE","PROJECTION","PROTOBUF","PULL","Q","QQ","QUALIFY","QUARTERS","QUERY","QUOTA","RANDOMIZE","RANDOMIZED","RANGE","READONLY","REALM","RECOMPRESS","RECURSIVE","REFERENCES","REFRESH","REGEXP","REMOVE","RENAME","RESET","RESPECT","RESTORE","RESTRICT","RESTRICTIVE","RESUME","REVOKE","ROLE","ROLES","ROLLBACK","ROLLUP","ROW","ROWS","S","S3","SALT","SAMPLE","SAN","SCHEME","SECONDS","SECURITY","SELECT","SEMI","SEQUENTIAL","SERVER","SET","SETS","SETTING","SETTINGS","SHA256_HASH","SHA256_PASSWORD","SHARD","SHOW","SIGNED","SIMPLE","SNAPSHOT","SOURCE","SPATIAL","SQL","SQL_TSI_DAY","SQL_TSI_HOUR","SQL_TSI_MICROSECOND","SQL_TSI_MILLISECOND","SQL_TSI_MINUTE","SQL_TSI_MONTH","SQL_TSI_NANOSECOND","SQL_TSI_QUARTER","SQL_TSI_SECOND","SQL_TSI_WEEK","SQL_TSI_YEAR","SS","SSH_KEY","SSL_CERTIFICATE","STALENESS","START","STATISTICS","STDOUT","STEP","STORAGE","STRICT","STRICTLY_ASCENDING","SUBPARTITION","SUBPARTITIONS","SUSPEND","SYNC","SYNTAX","SYSTEM","TABLE","TABLES","TAGS","TEMPORARY","TEST","THAN","THEN","TIES","TIME","TO","TOP","TOTALS","TRACKING","TRAILING","TRANSACTION","TREE","TRIGGER","TRUE","TRUNCATE","TTL","TYPE","TYPEOF","UNBOUNDED","UNDROP","UNFREEZE","UNION","UNIQUE","UNSET","UNSIGNED","UNTIL","UPDATE","URL","USE","USING","UUID","VALID","VALUES","VARYING","VIEW","VISIBLE","VOLUME","WATCH","WATERMARK","WEEKS","WHEN","WHERE","WINDOW","WITH","WITH_ITEMINDEX","WK","WRITABLE","WW","YEARS","YY","YYYY","ZKPATH"],wj=["AGGREGATEFUNCTION","ARRAY","BFLOAT16","BIGINT","BIGINT SIGNED","BIGINT UNSIGNED","BINARY","BINARY LARGE OBJECT","BINARY VARYING","BIT","BLOB","BYTE","BYTEA","BOOL","CHAR","CHAR LARGE OBJECT","CHAR VARYING","CHARACTER","CHARACTER LARGE OBJECT","CHARACTER VARYING","CLOB","DEC","DOUBLE","DOUBLE PRECISION","DATE","DATE32","DATETIME","DATETIME32","DATETIME64","DECIMAL","DECIMAL128","DECIMAL256","DECIMAL32","DECIMAL64","DYNAMIC","ENUM","ENUM","ENUM16","ENUM8","FIXED","FLOAT","FIXEDSTRING","FLOAT32","FLOAT64","GEOMETRY","INET4","INET6","INT","INT SIGNED","INT UNSIGNED","INT1","INT1 SIGNED","INT1 UNSIGNED","INTEGER","INTEGER SIGNED","INTEGER UNSIGNED","IPV4","IPV6","INT128","INT16","INT256","INT32","INT64","INT8","INTERVALDAY","INTERVALHOUR","INTERVALMICROSECOND","INTERVALMILLISECOND","INTERVALMINUTE","INTERVALMONTH","INTERVALNANOSECOND","INTERVALQUARTER","INTERVALSECOND","INTERVALWEEK","INTERVALYEAR","JSON","LONGBLOB","LONGTEXT","LINESTRING","LOWCARDINALITY","MEDIUMBLOB","MEDIUMINT","MEDIUMINT SIGNED","MEDIUMINT UNSIGNED","MEDIUMTEXT","MAP","MULTILINESTRING","MULTIPOLYGON","NATIONAL CHAR","NATIONAL CHAR VARYING","NATIONAL CHARACTER","NATIONAL CHARACTER LARGE OBJECT","NATIONAL CHARACTER VARYING","NCHAR","NCHAR LARGE OBJECT","NCHAR VARYING","NUMERIC","NVARCHAR","NESTED","NOTHING","NULLABLE","OBJECT","POINT","POLYGON","REAL","RING","SET","SIGNED","SINGLE","SMALLINT","SMALLINT SIGNED","SMALLINT UNSIGNED","SIMPLEAGGREGATEFUNCTION","STRING","TEXT","TIMESTAMP","TINYBLOB","TINYINT","TINYINT SIGNED","TINYINT UNSIGNED","TINYTEXT","TIME","TIME64","TUPLE","UINT128","UINT16","UINT256","UINT32","UINT64","UINT8","UNSIGNED","UUID","VARBINARY","VARCHAR","VARCHAR2","VARIANT","YEAR","BOOL","BOOLEAN"],Uj=j(["SELECT [DISTINCT]","MODIFY QUERY SELECT [DISTINCT]"]),Bj=j(["SET","WITH","FROM","SAMPLE","PREWHERE","WHERE","GROUP BY","HAVING","QUALIFY","ORDER BY","LIMIT","SETTINGS","INTO OUTFILE","FORMAT","WINDOW","PARTITION BY","INSERT INTO","VALUES","DEPENDS ON","MOVE {USER | ROLE | QUOTA | SETTINGS PROFILE | ROW POLICY}","GRANT","REVOKE","CHECK GRANT","SET [DEFAULT] ROLE [NONE | ALL | ALL EXCEPT]","DEDUPLICATE BY","MODIFY STATISTICS","TYPE","ALTER USER [IF EXISTS]","ALTER [ROW] POLICY [IF EXISTS]","DROP {USER | ROLE | QUOTA | PROFILE | SETTINGS PROFILE | ROW POLICY | POLICY} [IF EXISTS]"]),df=j(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),Bl=j(["ALL EXCEPT","ON CLUSTER","UPDATE","SYSTEM RELOAD {DICTIONARIES | DICTIONARY | FUNCTIONS | FUNCTION | ASYNCHRONOUS METRICS}","SYSTEM DROP {DNS CACHE | MARK CACHE | ICEBERG METADATA CACHE | TEXT INDEX DICTIONARY CACHE | TEXT INDEX HEADER CACHE | TEXT INDEX POSTINGS CACHE | REPLICA | DATABASE REPLICA | UNCOMPRESSED CACHE | COMPILED EXPRESSION CACHE | QUERY CONDITION CACHE | QUERY CACHE | FORMAT SCHEMA CACHE | FILESYSTEM CACHE}","SYSTEM FLUSH LOGS","SYSTEM RELOAD {CONFIG | USERS}","SYSTEM SHUTDOWN","SYSTEM KILL","SYSTEM FLUSH DISTRIBUTED","SYSTEM START DISTRIBUTED SENDS","SYSTEM {STOP | START} {LISTEN | MERGES | TTL MERGES | MOVES | FETCHES | REPLICATED SENDS | REPLICATION QUEUES | PULLING REPLICATION LOG}","SYSTEM {SYNC | RESTART | RESTORE} REPLICA","SYSTEM {SYNC | RESTORE} DATABASE REPLICA","SYSTEM RESTART REPLICAS","SYSTEM UNFREEZE","SYSTEM WAIT LOADING PARTS","SYSTEM {LOAD | UNLOAD} PRIMARY KEY","SYSTEM {STOP | START} [REPLICATED] VIEW","SYSTEM {STOP | START} VIEWS","SYSTEM {REFRESH | CANCEL | WAIT} VIEW","WITH NAME","SHOW [CREATE] {TABLE | TEMPORARY TABLE | DICTIONARY | VIEW | DATABASE}","SHOW DATABASES [[NOT] {LIKE | ILIKE}]","SHOW [FULL] [TEMPORARY] TABLES [FROM | IN]","SHOW [EXTENDED] [FULL] COLUMNS {FROM | IN}","ATTACH {TABLE | DICTIONARY | DATABASE} [IF NOT EXISTS]","DETACH {TABLE | DICTIONARY | DATABASE} [IF EXISTS]","PERMANENTLY","SYNC","DROP {DICTIONARY | DATABASE | PROFILE | VIEW | FUNCTION | NAMED COLLECTION} [IF EXISTS]","DROP [TEMPORARY] TABLE [IF EXISTS] [IF EMPTY]","RENAME TO","EXISTS [TEMPORARY] {TABLE | DICTIONARY | DATABASE}","KILL QUERY","OPTIMIZE TABLE","RENAME {TABLE | DICTIONARY | DATABASE}","EXCHANGE {TABLES | DICTIONARIES}","TRUNCATE TABLE [IF EXISTS]","EXECUTE AS","USE","TO","UNDROP TABLE","CREATE {DATABASE | NAMED COLLECTION} [IF NOT EXISTS]","CREATE [OR REPLACE] {VIEW | DICTIONARY} [IF NOT EXISTS]","CREATE MATERIALIZED VIEW [IF NOT EXISTS]","CREATE FUNCTION","CREATE {USER | ROLE | QUOTA | SETTINGS PROFILE} [IF NOT EXISTS | OR REPLACE]","CREATE [ROW] POLICY [IF NOT EXISTS | OR REPLACE]","REPLACE [TEMPORARY] TABLE [IF NOT EXISTS]","ALTER {ROLE | QUOTA | SETTINGS PROFILE} [IF EXISTS]","ALTER [TEMPORARY] TABLE","ALTER NAMED COLLECTION [IF EXISTS]","GRANTEES","NOT IDENTIFIED","RESET AUTHENTICATION METHODS TO NEW","{IDENTIFIED | ADD IDENTIFIED} [WITH | BY]","[ADD | DROP] HOST {LOCAL | NAME | REGEXP | IP | LIKE}","VALID UNTIL","DROP [ALL] {PROFILES | SETTINGS}","{ADD | MODIFY} SETTINGS","ADD PROFILES","APPLY DELETED MASK","IN PARTITION","{ADD | DROP | RENAME | CLEAR | COMMENT | MODIFY | ALTER | MATERIALIZE} COLUMN","{DETACH | DROP | ATTACH | FETCH | MOVE} {PART | PARTITION}","DROP DETACHED {PART | PARTITION}","{FORGET | REPLACE} PARTITION","CLEAR COLUMN","{FREEZE | UNFREEZE} [PARTITION]","CLEAR INDEX","TO {DISK | VOLUME}","[DELETE | REWRITE PARTS] IN PARTITION","{MODIFY | RESET} SETTING","DELETE WHERE","MODIFY ORDER BY","{MODIFY | REMOVE} SAMPLE BY","{ADD | MATERIALIZE | CLEAR} INDEX [IF NOT EXISTS]","DROP INDEX [IF EXISTS]","GRANULARITY","AFTER","FIRST","ADD CONSTRAINT [IF NOT EXISTS]","DROP CONSTRAINT [IF EXISTS]","MODIFY TTL","REMOVE TTL","ADD STATISTICS [IF NOT EXISTS]","{DROP | CLEAR} STATISTICS [IF EXISTS]","MATERIALIZE STATISTICS [ALL | IF EXISTS]","KEYED BY","NOT KEYED","FOR [RANDOMIZED] INTERVAL","AS {PERMISSIVE | RESTRICTIVE}","FOR SELECT","ADD PROJECTION [IF NOT EXISTS]","{DROP | MATERIALIZE | CLEAR} PROJECTION [IF EXISTS]","REFRESH {EVERY | AFTER}","RANDOMIZE FOR","APPEND","APPEND TO","DELETE FROM","EXPLAIN [AST | SYNTAX | QUERY TREE | PLAN | PIPELINE | ESTIMATE | TABLE OVERRIDE]","GRANT ON CLUSTER","GRANT CURRENT GRANTS","WITH GRANT OPTION","REVOKE ON CLUSTER","ADMIN OPTION FOR","CHECK TABLE","PARTITION ID","{DESC | DESCRIBE} TABLE"]),Fj=j(["UNION [ALL | DISTINCT]","PARALLEL WITH"]),kj=j(["[GLOBAL] [INNER|LEFT|RIGHT|FULL|CROSS] [OUTER|SEMI|ANTI|ANY|ALL|ASOF] JOIN","[LEFT] ARRAY JOIN"]),jj=j(["{ROWS | RANGE} BETWEEN","ALTER MATERIALIZE STATISTICS"]),Gj={name:"clickhouse",tokenizerOptions:{reservedSelect:Uj,reservedClauses:[...Bj,...df,...Bl],reservedSetOperations:Fj,reservedJoins:kj,reservedKeywordPhrases:jj,reservedKeywords:Pj,reservedDataTypes:wj,reservedFunctionNames:vj,extraParens:["[]","{}"],lineCommentTypes:["#","--"],nestedBlockComments:!1,underscoresInNumbers:!0,stringTypes:["$$","''-qq-bs"],identTypes:['""-qq-bs',"``"],paramTypes:{custom:[{regex:String.raw`\{[^:']+:[^}]+\}`,key:e=>{const t=/\{([^:]+):/.exec(e);return t?t[1].trim():e}}]},operators:["%","||","?",":","==","<=>","->"],postProcess:Hj},formatOptions:{onelineClauses:[...df,...Bl],tabularOnelineClauses:Bl}};function Hj(e){return e.map((t,n)=>{const r=e[n+1]||hn,o=e[n-1]||hn;return t.type===K.RESERVED_SELECT&&(r.type===K.COMMA||o.type===K.RESERVED_CLAUSE||o.type===K.COMMA)?Object.assign(Object.assign({},t),{type:K.RESERVED_KEYWORD}):An.SET(t)&&r.type===K.OPEN_PAREN?Object.assign(Object.assign({},t),{type:K.RESERVED_FUNCTION_NAME}):t})}const Yj=["ARRAY_AGG","AVG","CORRELATION","COUNT","COUNT_BIG","COVARIANCE","COVARIANCE_SAMP","CUME_DIST","GROUPING","LISTAGG","MAX","MEDIAN","MIN","PERCENTILE_CONT","PERCENTILE_DISC","PERCENT_RANK","REGR_AVGX","REGR_AVGY","REGR_COUNT","REGR_INTERCEPT","REGR_ICPT","REGR_R2","REGR_SLOPE","REGR_SXX","REGR_SXY","REGR_SYY","STDDEV","STDDEV_SAMP","SUM","VARIANCE","VARIANCE_SAMP","XMLAGG","XMLGROUP","ABS","ABSVAL","ACOS","ADD_DAYS","ADD_HOURS","ADD_MINUTES","ADD_MONTHS","ADD_SECONDS","ADD_YEARS","AGE","ARRAY_DELETE","ARRAY_FIRST","ARRAY_LAST","ARRAY_NEXT","ARRAY_PRIOR","ASCII","ASCII_STR","ASIN","ATAN","ATAN2","ATANH","BITAND","BITANDNOT","BITOR","BITXOR","BITNOT","BPCHAR","BSON_TO_JSON","BTRIM","CARDINALITY","CEILING","CEIL","CHARACTER_LENGTH","CHR","COALESCE","COLLATION_KEY","COLLATION_KEY_BIT","COMPARE_DECFLOAT","CONCAT","COS","COSH","COT","CURSOR_ROWCOUNT","DATAPARTITIONNUM","DATE_PART","DATE_TRUNC","DAY","DAYNAME","DAYOFMONTH","DAYOFWEEK","DAYOFWEEK_ISO","DAYOFYEAR","DAYS","DAYS_BETWEEN","DAYS_TO_END_OF_MONTH","DBPARTITIONNUM","DECFLOAT","DECFLOAT_FORMAT","DECODE","DECRYPT_BIN","DECRYPT_CHAR","DEGREES","DEREF","DIFFERENCE","DIGITS","DOUBLE_PRECISION","EMPTY_BLOB","EMPTY_CLOB","EMPTY_DBCLOB","EMPTY_NCLOB","ENCRYPT","EVENT_MON_STATE","EXP","EXTRACT","FIRST_DAY","FLOOR","FROM_UTC_TIMESTAMP","GENERATE_UNIQUE","GETHINT","GREATEST","HASH","HASH4","HASH8","HASHEDVALUE","HEX","HEXTORAW","HOUR","HOURS_BETWEEN","IDENTITY_VAL_LOCAL","IFNULL","INITCAP","INSERT","INSTR","INSTR2","INSTR4","INSTRB","INTNAND","INTNOR","INTNXOR","INTNNOT","ISNULL","JSON_ARRAY","JSON_OBJECT","JSON_QUERY","JSON_TO_BSON","JSON_VALUE","JULIAN_DAY","LAST_DAY","LCASE","LEAST","LEFT","LENGTH","LENGTH2","LENGTH4","LENGTHB","LN","LOCATE","LOCATE_IN_STRING","LOG10","LONG_VARCHAR","LONG_VARGRAPHIC","LOWER","LPAD","LTRIM","MAX","MAX_CARDINALITY","MICROSECOND","MIDNIGHT_SECONDS","MIN","MINUTE","MINUTES_BETWEEN","MOD","MONTH","MONTHNAME","MONTHS_BETWEEN","MULTIPLY_ALT","NEXT_DAY","NEXT_MONTH","NEXT_QUARTER","NEXT_WEEK","NEXT_YEAR","NORMALIZE_DECFLOAT","NOW","NULLIF","NVL","NVL2","OCTET_LENGTH","OVERLAY","PARAMETER","POSITION","POSSTR","POW","POWER","QUANTIZE","QUARTER","QUOTE_IDENT","QUOTE_LITERAL","RADIANS","RAISE_ERROR","RAND","RANDOM","RAWTOHEX","REC2XML","REGEXP_COUNT","REGEXP_EXTRACT","REGEXP_INSTR","REGEXP_LIKE","REGEXP_MATCH_COUNT","REGEXP_REPLACE","REGEXP_SUBSTR","REPEAT","REPLACE","RID","RID_BIT","RIGHT","ROUND","ROUND_TIMESTAMP","RPAD","RTRIM","SECLABEL","SECLABEL_BY_NAME","SECLABEL_TO_CHAR","SECOND","SECONDS_BETWEEN","SIGN","SIN","SINH","SOUNDEX","SPACE","SQRT","STRIP","STRLEFT","STRPOS","STRRIGHT","SUBSTR","SUBSTR2","SUBSTR4","SUBSTRB","SUBSTRING","TABLE_NAME","TABLE_SCHEMA","TAN","TANH","THIS_MONTH","THIS_QUARTER","THIS_WEEK","THIS_YEAR","TIMESTAMP_FORMAT","TIMESTAMP_ISO","TIMESTAMPDIFF","TIMEZONE","TO_CHAR","TO_CLOB","TO_DATE","TO_HEX","TO_MULTI_BYTE","TO_NCHAR","TO_NCLOB","TO_NUMBER","TO_SINGLE_BYTE","TO_TIMESTAMP","TO_UTC_TIMESTAMP","TOTALORDER","TRANSLATE","TRIM","TRIM_ARRAY","TRUNC_TIMESTAMP","TRUNCATE","TRUNC","TYPE_ID","TYPE_NAME","TYPE_SCHEMA","UCASE","UNICODE_STR","UPPER","VALUE","VARCHAR_BIT_FORMAT","VARCHAR_FORMAT","VARCHAR_FORMAT_BIT","VERIFY_GROUP_FOR_USER","VERIFY_ROLE_FOR_USER","VERIFY_TRUSTED_CONTEXT_ROLE_FOR_USER","WEEK","WEEK_ISO","WEEKS_BETWEEN","WIDTH_BUCKET","XMLATTRIBUTES","XMLCOMMENT","XMLCONCAT","XMLDOCUMENT","XMLELEMENT","XMLFOREST","XMLNAMESPACES","XMLPARSE","XMLPI","XMLQUERY","XMLROW","XMLSERIALIZE","XMLTEXT","XMLVALIDATE","XMLXSROBJECTID","XSLTRANSFORM","YEAR","YEARS_BETWEEN","YMD_BETWEEN","BASE_TABLE","JSON_TABLE","UNNEST","XMLTABLE","RANK","DENSE_RANK","NTILE","LAG","LEAD","ROW_NUMBER","FIRST_VALUE","LAST_VALUE","NTH_VALUE","RATIO_TO_REPORT","CAST"],Wj=["ACTIVATE","ADD","AFTER","ALIAS","ALL","ALLOCATE","ALLOW","ALTER","AND","ANY","AS","ASENSITIVE","ASSOCIATE","ASUTIME","AT","ATTRIBUTES","AUDIT","AUTHORIZATION","AUX","AUXILIARY","BEFORE","BEGIN","BETWEEN","BINARY","BUFFERPOOL","BY","CACHE","CALL","CALLED","CAPTURE","CARDINALITY","CASCADED","CASE","CAST","CHECK","CLONE","CLOSE","CLUSTER","COLLECTION","COLLID","COLUMN","COMMENT","COMMIT","CONCAT","CONDITION","CONNECT","CONNECTION","CONSTRAINT","CONTAINS","CONTINUE","COUNT","COUNT_BIG","CREATE","CROSS","CURRENT","CURRENT_DATE","CURRENT_LC_CTYPE","CURRENT_PATH","CURRENT_SCHEMA","CURRENT_SERVER","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_TIMEZONE","CURRENT_USER","CURSOR","CYCLE","DATA","DATABASE","DATAPARTITIONNAME","DATAPARTITIONNUM","DAY","DAYS","DB2GENERAL","DB2GENRL","DB2SQL","DBINFO","DBPARTITIONNAME","DBPARTITIONNUM","DEALLOCATE","DECLARE","DEFAULT","DEFAULTS","DEFINITION","DELETE","DENSERANK","DENSE_RANK","DESCRIBE","DESCRIPTOR","DETERMINISTIC","DIAGNOSTICS","DISABLE","DISALLOW","DISCONNECT","DISTINCT","DO","DOCUMENT","DROP","DSSIZE","DYNAMIC","EACH","EDITPROC","ELSE","ELSEIF","ENABLE","ENCODING","ENCRYPTION","END","END-EXEC","ENDING","ERASE","ESCAPE","EVERY","EXCEPT","EXCEPTION","EXCLUDING","EXCLUSIVE","EXECUTE","EXISTS","EXIT","EXPLAIN","EXTENDED","EXTERNAL","EXTRACT","FENCED","FETCH","FIELDPROC","FILE","FINAL","FIRST1","FOR","FOREIGN","FREE","FROM","FULL","FUNCTION","GENERAL","GENERATED","GET","GLOBAL","GO","GOTO","GRANT","GRAPHIC","GROUP","HANDLER","HASH","HASHED_VALUE","HAVING","HINT","HOLD","HOUR","HOURS","IDENTITY","IF","IMMEDIATE","IMPORT","IN","INCLUDING","INCLUSIVE","INCREMENT","INDEX","INDICATOR","INDICATORS","INF","INFINITY","INHERIT","INNER","INOUT","INSENSITIVE","INSERT","INTEGRITY","INTERSECT","INTO","IS","ISNULL","ISOBID","ISOLATION","ITERATE","JAR","JAVA","JOIN","KEEP","KEY","LABEL","LANGUAGE","LAST3","LATERAL","LC_CTYPE","LEAVE","LEFT","LIKE","LIMIT","LINKTYPE","LOCAL","LOCALDATE","LOCALE","LOCALTIME","LOCALTIMESTAMP","LOCATOR","LOCATORS","LOCK","LOCKMAX","LOCKSIZE","LOOP","MAINTAINED","MATERIALIZED","MAXVALUE","MICROSECOND","MICROSECONDS","MINUTE","MINUTES","MINVALUE","MODE","MODIFIES","MONTH","MONTHS","NAN","NEW","NEW_TABLE","NEXTVAL","NO","NOCACHE","NOCYCLE","NODENAME","NODENUMBER","NOMAXVALUE","NOMINVALUE","NONE","NOORDER","NORMALIZED","NOT2","NOTNULL","NULL","NULLS","NUMPARTS","OBID","OF","OFF","OFFSET","OLD","OLD_TABLE","ON","OPEN","OPTIMIZATION","OPTIMIZE","OPTION","OR","ORDER","OUT","OUTER","OVER","OVERRIDING","PACKAGE","PADDED","PAGESIZE","PARAMETER","PART","PARTITION","PARTITIONED","PARTITIONING","PARTITIONS","PASSWORD","PATH","PERCENT","PIECESIZE","PLAN","POSITION","PRECISION","PREPARE","PREVVAL","PRIMARY","PRIQTY","PRIVILEGES","PROCEDURE","PROGRAM","PSID","PUBLIC","QUERY","QUERYNO","RANGE","RANK","READ","READS","RECOVERY","REFERENCES","REFERENCING","REFRESH","RELEASE","RENAME","REPEAT","RESET","RESIGNAL","RESTART","RESTRICT","RESULT","RESULT_SET_LOCATOR","RETURN","RETURNS","REVOKE","RIGHT","ROLE","ROLLBACK","ROUND_CEILING","ROUND_DOWN","ROUND_FLOOR","ROUND_HALF_DOWN","ROUND_HALF_EVEN","ROUND_HALF_UP","ROUND_UP","ROUTINE","ROW","ROWNUMBER","ROWS","ROWSET","ROW_NUMBER","RRN","RUN","SAVEPOINT","SCHEMA","SCRATCHPAD","SCROLL","SEARCH","SECOND","SECONDS","SECQTY","SECURITY","SELECT","SENSITIVE","SEQUENCE","SESSION","SESSION_USER","SET","SIGNAL","SIMPLE","SNAN","SOME","SOURCE","SPECIFIC","SQL","SQLID","STACKED","STANDARD","START","STARTING","STATEMENT","STATIC","STATMENT","STAY","STOGROUP","STORES","STYLE","SUBSTRING","SUMMARY","SYNONYM","SYSFUN","SYSIBM","SYSPROC","SYSTEM","SYSTEM_USER","TABLE","TABLESPACE","THEN","TO","TRANSACTION","TRIGGER","TRIM","TRUNCATE","TYPE","UNDO","UNION","UNIQUE","UNTIL","UPDATE","USAGE","USER","USING","VALIDPROC","VALUE","VALUES","VARIABLE","VARIANT","VCAT","VERSION","VIEW","VOLATILE","VOLUMES","WHEN","WHENEVER","WHERE","WHILE","WITH","WITHOUT","WLM","WRITE","XMLELEMENT","XMLEXISTS","XMLNAMESPACES","YEAR","YEARS"],$j=["ARRAY","BIGINT","BINARY","BLOB","BOOLEAN","CCSID","CHAR","CHARACTER","CLOB","DATE","DATETIME","DBCLOB","DEC","DECIMAL","DOUBLE","DOUBLE PRECISION","FLOAT","FLOAT4","FLOAT8","GRAPHIC","INT","INT2","INT4","INT8","INTEGER","INTERVAL","LONG VARCHAR","LONG VARGRAPHIC","NCHAR","NCHR","NCLOB","NVARCHAR","NUMERIC","SMALLINT","REAL","TIME","TIMESTAMP","VARBINARY","VARCHAR","VARGRAPHIC"],Vj=j(["SELECT [ALL | DISTINCT]"]),Xj=j(["WITH","FROM","WHERE","GROUP BY","HAVING","PARTITION BY","ORDER BY [INPUT SEQUENCE]","LIMIT","OFFSET","FETCH NEXT","FOR UPDATE [OF]","FOR {READ | FETCH} ONLY","FOR {RR | CS | UR | RS} [USE AND KEEP {SHARE | UPDATE | EXCLUSIVE} LOCKS]","WAIT FOR OUTCOME","SKIP LOCKED DATA","INTO","INSERT INTO","VALUES","SET","MERGE INTO","WHEN [NOT] MATCHED [THEN]","UPDATE SET","INSERT"]),Ef=j(["CREATE [GLOBAL TEMPORARY | EXTERNAL] TABLE [IF NOT EXISTS]"]),Fl=j(["CREATE [OR REPLACE] VIEW","UPDATE","WHERE CURRENT OF","WITH {RR | RS | CS | UR}","DELETE FROM","DROP TABLE [IF EXISTS]","ALTER TABLE","ADD [COLUMN]","DROP [COLUMN]","RENAME COLUMN","ALTER [COLUMN]","SET DATA TYPE","SET NOT NULL","DROP {DEFAULT | GENERATED | NOT NULL}","TRUNCATE [TABLE]","ALLOCATE","ALTER AUDIT POLICY","ALTER BUFFERPOOL","ALTER DATABASE PARTITION GROUP","ALTER DATABASE","ALTER EVENT MONITOR","ALTER FUNCTION","ALTER HISTOGRAM TEMPLATE","ALTER INDEX","ALTER MASK","ALTER METHOD","ALTER MODULE","ALTER NICKNAME","ALTER PACKAGE","ALTER PERMISSION","ALTER PROCEDURE","ALTER SCHEMA","ALTER SECURITY LABEL COMPONENT","ALTER SECURITY POLICY","ALTER SEQUENCE","ALTER SERVER","ALTER SERVICE CLASS","ALTER STOGROUP","ALTER TABLESPACE","ALTER THRESHOLD","ALTER TRIGGER","ALTER TRUSTED CONTEXT","ALTER TYPE","ALTER USAGE LIST","ALTER USER MAPPING","ALTER VIEW","ALTER WORK ACTION SET","ALTER WORK CLASS SET","ALTER WORKLOAD","ALTER WRAPPER","ALTER XSROBJECT","ALTER STOGROUP","ALTER TABLESPACE","ALTER TRIGGER","ALTER TRUSTED CONTEXT","ALTER VIEW","ASSOCIATE [RESULT SET] {LOCATOR | LOCATORS}","AUDIT","BEGIN DECLARE SECTION","CALL","CLOSE","COMMENT ON","COMMIT [WORK]","CONNECT","CREATE [OR REPLACE] [PUBLIC] ALIAS","CREATE AUDIT POLICY","CREATE BUFFERPOOL","CREATE DATABASE PARTITION GROUP","CREATE EVENT MONITOR","CREATE [OR REPLACE] FUNCTION","CREATE FUNCTION MAPPING","CREATE HISTOGRAM TEMPLATE","CREATE [UNIQUE] INDEX","CREATE INDEX EXTENSION","CREATE [OR REPLACE] MASK","CREATE [SPECIFIC] METHOD","CREATE [OR REPLACE] MODULE","CREATE [OR REPLACE] NICKNAME","CREATE [OR REPLACE] PERMISSION","CREATE [OR REPLACE] PROCEDURE","CREATE ROLE","CREATE SCHEMA","CREATE SECURITY LABEL [COMPONENT]","CREATE SECURITY POLICY","CREATE [OR REPLACE] SEQUENCE","CREATE SERVICE CLASS","CREATE SERVER","CREATE STOGROUP","CREATE SYNONYM","CREATE [LARGE | REGULAR | {SYSTEM | USER} TEMPORARY] TABLESPACE","CREATE THRESHOLD","CREATE {TRANSFORM | TRANSFORMS} FOR","CREATE [OR REPLACE] TRIGGER","CREATE TRUSTED CONTEXT","CREATE [OR REPLACE] TYPE","CREATE TYPE MAPPING","CREATE USAGE LIST","CREATE USER MAPPING FOR","CREATE [OR REPLACE] VARIABLE","CREATE WORK ACTION SET","CREATE WORK CLASS SET","CREATE WORKLOAD","CREATE WRAPPER","DECLARE","DECLARE GLOBAL TEMPORARY TABLE","DESCRIBE [INPUT | OUTPUT]","DISCONNECT","DROP [PUBLIC] ALIAS","DROP AUDIT POLICY","DROP BUFFERPOOL","DROP DATABASE PARTITION GROUP","DROP EVENT MONITOR","DROP [SPECIFIC] FUNCTION","DROP FUNCTION MAPPING","DROP HISTOGRAM TEMPLATE","DROP INDEX [EXTENSION]","DROP MASK","DROP [SPECIFIC] METHOD","DROP MODULE","DROP NICKNAME","DROP PACKAGE","DROP PERMISSION","DROP [SPECIFIC] PROCEDURE","DROP ROLE","DROP SCHEMA","DROP SECURITY LABEL [COMPONENT]","DROP SECURITY POLICY","DROP SEQUENCE","DROP SERVER","DROP SERVICE CLASS","DROP STOGROUP","DROP TABLE HIERARCHY","DROP {TABLESPACE | TABLESPACES}","DROP {TRANSFORM | TRANSFORMS}","DROP THRESHOLD","DROP TRIGGER","DROP TRUSTED CONTEXT","DROP TYPE [MAPPING]","DROP USAGE LIST","DROP USER MAPPING FOR","DROP VARIABLE","DROP VIEW [HIERARCHY]","DROP WORK {ACTION | CLASS} SET","DROP WORKLOAD","DROP WRAPPER","DROP XSROBJECT","END DECLARE SECTION","EXECUTE [IMMEDIATE]","EXPLAIN {PLAN [SECTION] | ALL}","FETCH [FROM]","FLUSH {BUFFERPOOL | BUFFERPOOLS} ALL","FLUSH EVENT MONITOR","FLUSH FEDERATED CACHE","FLUSH OPTIMIZATION PROFILE CACHE","FLUSH PACKAGE CACHE [DYNAMIC]","FLUSH AUTHENTICATION CACHE [FOR ALL]","FREE LOCATOR","GET DIAGNOSTICS","GOTO","GRANT","INCLUDE","ITERATE","LEAVE","LOCK TABLE","LOOP","OPEN","PIPE","PREPARE","REFRESH TABLE","RELEASE","RELEASE [TO] SAVEPOINT","RENAME [TABLE | INDEX | STOGROUP | TABLESPACE]","REPEAT","RESIGNAL","RETURN","REVOKE","ROLLBACK [WORK] [TO SAVEPOINT]","SAVEPOINT","SET COMPILATION ENVIRONMENT","SET CONNECTION","SET CURRENT","SET ENCRYPTION PASSWORD","SET EVENT MONITOR STATE","SET INTEGRITY","SET PASSTHRU","SET PATH","SET ROLE","SET SCHEMA","SET SERVER OPTION","SET {SESSION AUTHORIZATION | SESSION_USER}","SET USAGE LIST","SIGNAL","TRANSFER OWNERSHIP OF","WHENEVER {NOT FOUND | SQLERROR | SQLWARNING}","WHILE"]),zj=j(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),Kj=j(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),qj=j(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),Jj=j([]),Qj={name:"db2",tokenizerOptions:{reservedSelect:Vj,reservedClauses:[...Xj,...Ef,...Fl],reservedSetOperations:zj,reservedJoins:Kj,reservedKeywordPhrases:qj,reservedDataTypePhrases:Jj,reservedKeywords:Wj,reservedDataTypes:$j,reservedFunctionNames:Yj,extraParens:["[]"],stringTypes:[{quote:"''-qq",prefixes:["G","N","U&"]},{quote:"''-raw",prefixes:["X","BX","GX","UX"],requirePrefix:!0}],identTypes:['""-qq'],identChars:{first:"@#$",rest:"@#$"},paramTypes:{positional:!0,named:[":"]},paramChars:{first:"@#$",rest:"@#$"},operators:["**","%","|","&","^","~","¬=","¬>","¬<","!>","!<","^=","^>","^<","||","->","=>"]},formatOptions:{onelineClauses:[...Ef,...Fl],tabularOnelineClauses:Fl}},Zj=["ARRAY_AGG","AVG","CORR","CORRELATION","COUNT","COUNT_BIG","COVAR_POP","COVARIANCE","COVAR","COVAR_SAMP","COVARIANCE_SAMP","EVERY","GROUPING","JSON_ARRAYAGG","JSON_OBJECTAGG","LISTAGG","MAX","MEDIAN","MIN","PERCENTILE_CONT","PERCENTILE_DISC","REGR_AVGX","REGR_AVGY","REGR_COUNT","REGR_INTERCEPT","REGR_R2","REGR_SLOPE","REGR_SXX","REGR_SXY","REGR_SYY","SOME","STDDEV_POP","STDDEV","STDDEV_SAMP","SUM","VAR_POP","VARIANCE","VAR","VAR_SAMP","VARIANCE_SAMP","XMLAGG","XMLGROUP","ABS","ABSVAL","ACOS","ADD_DAYS","ADD_HOURS","ADD_MINUTES","ADD_MONTHS","ADD_SECONDS","ADD_YEARS","ANTILOG","ARRAY_MAX_CARDINALITY","ARRAY_TRIM","ASCII","ASIN","ATAN","ATAN2","ATANH","BASE64_DECODE","BASE64_ENCODE","BIT_LENGTH","BITAND","BITANDNOT","BITNOT","BITOR","BITXOR","BSON_TO_JSON","CARDINALITY","CEIL","CEILING","CHAR_LENGTH","CHARACTER_LENGTH","CHR","COALESCE","COMPARE_DECFLOAT","CONCAT","CONTAINS","COS","COSH","COT","CURDATE","CURTIME","DATABASE","DATAPARTITIONNAME","DATAPARTITIONNUM","DAY","DAYNAME","DAYOFMONTH","DAYOFWEEK_ISO","DAYOFWEEK","DAYOFYEAR","DAYS","DBPARTITIONNAME","DBPARTITIONNUM","DECFLOAT_FORMAT","DECFLOAT_SORTKEY","DECRYPT_BINARY","DECRYPT_BIT","DECRYPT_CHAR","DECRYPT_DB","DEGREES","DIFFERENCE","DIGITS","DLCOMMENT","DLLINKTYPE","DLURLCOMPLETE","DLURLPATH","DLURLPATHONLY","DLURLSCHEME","DLURLSERVER","DLVALUE","DOUBLE_PRECISION","DOUBLE","ENCRPYT","ENCRYPT_AES","ENCRYPT_AES256","ENCRYPT_RC2","ENCRYPT_TDES","EXP","EXTRACT","FIRST_DAY","FLOOR","GENERATE_UNIQUE","GET_BLOB_FROM_FILE","GET_CLOB_FROM_FILE","GET_DBCLOB_FROM_FILE","GET_XML_FILE","GETHINT","GREATEST","HASH_MD5","HASH_ROW","HASH_SHA1","HASH_SHA256","HASH_SHA512","HASH_VALUES","HASHED_VALUE","HEX","HEXTORAW","HOUR","HTML_ENTITY_DECODE","HTML_ENTITY_ENCODE","HTTP_DELETE_BLOB","HTTP_DELETE","HTTP_GET_BLOB","HTTP_GET","HTTP_PATCH_BLOB","HTTP_PATCH","HTTP_POST_BLOB","HTTP_POST","HTTP_PUT_BLOB","HTTP_PUT","IDENTITY_VAL_LOCAL","IFNULL","INSERT","INSTR","INTERPRET","ISFALSE","ISNOTFALSE","ISNOTTRUE","ISTRUE","JSON_ARRAY","JSON_OBJECT","JSON_QUERY","JSON_TO_BSON","JSON_UPDATE","JSON_VALUE","JULIAN_DAY","LAND","LAST_DAY","LCASE","LEAST","LEFT","LENGTH","LN","LNOT","LOCATE_IN_STRING","LOCATE","LOG10","LOR","LOWER","LPAD","LTRIM","MAX_CARDINALITY","MAX","MICROSECOND","MIDNIGHT_SECONDS","MIN","MINUTE","MOD","MONTH","MONTHNAME","MONTHS_BETWEEN","MQREAD","MQREADCLOB","MQRECEIVE","MQRECEIVECLOB","MQSEND","MULTIPLY_ALT","NEXT_DAY","NORMALIZE_DECFLOAT","NOW","NULLIF","NVL","OCTET_LENGTH","OVERLAY","PI","POSITION","POSSTR","POW","POWER","QUANTIZE","QUARTER","RADIANS","RAISE_ERROR","RANDOM","RAND","REGEXP_COUNT","REGEXP_INSTR","REGEXP_REPLACE","REGEXP_SUBSTR","REPEAT","REPLACE","RID","RIGHT","ROUND_TIMESTAMP","ROUND","RPAD","RRN","RTRIM","SCORE","SECOND","SIGN","SIN","SINH","SOUNDEX","SPACE","SQRT","STRIP","STRLEFT","STRPOS","STRRIGHT","SUBSTR","SUBSTRING","TABLE_NAME","TABLE_SCHEMA","TAN","TANH","TIMESTAMP_FORMAT","TIMESTAMP_ISO","TIMESTAMPDIFF_BIG","TIMESTAMPDIFF","TO_CHAR","TO_CLOB","TO_DATE","TO_NUMBER","TO_TIMESTAMP","TOTALORDER","TRANSLATE","TRIM_ARRAY","TRIM","TRUNC_TIMESTAMP","TRUNC","TRUNCATE","UCASE","UPPER","URL_DECODE","URL_ENCODE","VALUE","VARBINARY_FORMAT","VARCHAR_BIT_FORMAT","VARCHAR_FORMAT_BINARY","VARCHAR_FORMAT","VERIFY_GROUP_FOR_USER","WEEK_ISO","WEEK","WRAP","XMLATTRIBUTES","XMLCOMMENT","XMLCONCAT","XMLDOCUMENT","XMLELEMENT","XMLFOREST","XMLNAMESPACES","XMLPARSE","XMLPI","XMLROW","XMLSERIALIZE","XMLTEXT","XMLVALIDATE","XOR","XSLTRANSFORM","YEAR","ZONED","BASE_TABLE","HTTP_DELETE_BLOB_VERBOSE","HTTP_DELETE_VERBOSE","HTTP_GET_BLOB_VERBOSE","HTTP_GET_VERBOSE","HTTP_PATCH_BLOB_VERBOSE","HTTP_PATCH_VERBOSE","HTTP_POST_BLOB_VERBOSE","HTTP_POST_VERBOSE","HTTP_PUT_BLOB_VERBOSE","HTTP_PUT_VERBOSE","JSON_TABLE","MQREADALL","MQREADALLCLOB","MQRECEIVEALL","MQRECEIVEALLCLOB","XMLTABLE","UNPACK","CUME_DIST","DENSE_RANK","FIRST_VALUE","LAG","LAST_VALUE","LEAD","NTH_VALUE","NTILE","PERCENT_RANK","RANK","RATIO_TO_REPORT","ROW_NUMBER","CAST"],eG=["ABSENT","ACCORDING","ACCTNG","ACTION","ACTIVATE","ADD","ALIAS","ALL","ALLOCATE","ALLOW","ALTER","AND","ANY","APPEND","APPLNAME","ARRAY","ARRAY_AGG","ARRAY_TRIM","AS","ASC","ASENSITIVE","ASSOCIATE","ATOMIC","ATTACH","ATTRIBUTES","AUTHORIZATION","AUTONOMOUS","BEFORE","BEGIN","BETWEEN","BIND","BSON","BUFFERPOOL","BY","CACHE","CALL","CALLED","CARDINALITY","CASE","CAST","CHECK","CL","CLOSE","CLUSTER","COLLECT","COLLECTION","COLUMN","COMMENT","COMMIT","COMPACT","COMPARISONS","COMPRESS","CONCAT","CONCURRENT","CONDITION","CONNECT","CONNECT_BY_ROOT","CONNECTION","CONSTANT","CONSTRAINT","CONTAINS","CONTENT","CONTINUE","COPY","COUNT","COUNT_BIG","CREATE","CREATEIN","CROSS","CUBE","CUME_DIST","CURRENT","CURRENT_DATE","CURRENT_PATH","CURRENT_SCHEMA","CURRENT_SERVER","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_TIMEZONE","CURRENT_USER","CURSOR","CYCLE","DATABASE","DATAPARTITIONNAME","DATAPARTITIONNUM","DAY","DAYS","DB2GENERAL","DB2GENRL","DB2SQL","DBINFO","DBPARTITIONNAME","DBPARTITIONNUM","DEACTIVATE","DEALLOCATE","DECLARE","DEFAULT","DEFAULTS","DEFER","DEFINE","DEFINITION","DELETE","DELETING","DENSE_RANK","DENSERANK","DESC","DESCRIBE","DESCRIPTOR","DETACH","DETERMINISTIC","DIAGNOSTICS","DISABLE","DISALLOW","DISCONNECT","DISTINCT","DO","DOCUMENT","DROP","DYNAMIC","EACH","ELSE","ELSEIF","EMPTY","ENABLE","ENCODING","ENCRYPTION","END","END-EXEC","ENDING","ENFORCED","ERROR","ESCAPE","EVERY","EXCEPT","EXCEPTION","EXCLUDING","EXCLUSIVE","EXECUTE","EXISTS","EXIT","EXTEND","EXTERNAL","EXTRACT","FALSE","FENCED","FETCH","FIELDPROC","FILE","FINAL","FIRST_VALUE","FOR","FOREIGN","FORMAT","FREE","FREEPAGE","FROM","FULL","FUNCTION","GBPCACHE","GENERAL","GENERATED","GET","GLOBAL","GO","GOTO","GRANT","GROUP","HANDLER","HASH","HASH_ROW","HASHED_VALUE","HAVING","HINT","HOLD","HOUR","HOURS","IDENTITY","IF","IGNORE","IMMEDIATE","IMPLICITLY","IN","INCLUDE","INCLUDING","INCLUSIVE","INCREMENT","INDEX","INDEXBP","INDICATOR","INF","INFINITY","INHERIT","INLINE","INNER","INOUT","INSENSITIVE","INSERT","INSERTING","INTEGRITY","INTERPRET","INTERSECT","INTO","IS","ISNULL","ISOLATION","ITERATE","JAVA","JOIN","JSON","JSON_ARRAY","JSON_ARRAYAGG","JSON_EXISTS","JSON_OBJECT","JSON_OBJECTAGG","JSON_QUERY","JSON_TABLE","JSON_VALUE","KEEP","KEY","KEYS","LABEL","LAG","LANGUAGE","LAST_VALUE","LATERAL","LEAD","LEAVE","LEFT","LEVEL2","LIKE","LIMIT","LINKTYPE","LISTAGG","LOCAL","LOCALDATE","LOCALTIME","LOCALTIMESTAMP","LOCATION","LOCATOR","LOCK","LOCKSIZE","LOG","LOGGED","LOOP","MAINTAINED","MASK","MATCHED","MATERIALIZED","MAXVALUE","MERGE","MICROSECOND","MICROSECONDS","MINPCTUSED","MINUTE","MINUTES","MINVALUE","MIRROR","MIXED","MODE","MODIFIES","MONTH","MONTHS","NAMESPACE","NAN","NATIONAL","NCHAR","NCLOB","NESTED","NEW","NEW_TABLE","NEXTVAL","NO","NOCACHE","NOCYCLE","NODENAME","NODENUMBER","NOMAXVALUE","NOMINVALUE","NONE","NOORDER","NORMALIZED","NOT","NOTNULL","NTH_VALUE","NTILE","NULL","NULLS","NVARCHAR","OBID","OBJECT","OF","OFF","OFFSET","OLD","OLD_TABLE","OMIT","ON","ONLY","OPEN","OPTIMIZE","OPTION","OR","ORDER","ORDINALITY","ORGANIZE","OUT","OUTER","OVER","OVERLAY","OVERRIDING","PACKAGE","PADDED","PAGE","PAGESIZE","PARAMETER","PART","PARTITION","PARTITIONED","PARTITIONING","PARTITIONS","PASSING","PASSWORD","PATH","PCTFREE","PERCENT_RANK","PERCENTILE_CONT","PERCENTILE_DISC","PERIOD","PERMISSION","PIECESIZE","PIPE","PLAN","POSITION","PREPARE","PREVVAL","PRIMARY","PRIOR","PRIQTY","PRIVILEGES","PROCEDURE","PROGRAM","PROGRAMID","QUERY","RANGE","RANK","RATIO_TO_REPORT","RCDFMT","READ","READS","RECOVERY","REFERENCES","REFERENCING","REFRESH","REGEXP_LIKE","RELEASE","RENAME","REPEAT","RESET","RESIGNAL","RESTART","RESULT","RESULT_SET_LOCATOR","RETURN","RETURNING","RETURNS","REVOKE","RID","RIGHT","ROLLBACK","ROLLUP","ROUTINE","ROW","ROW_NUMBER","ROWNUMBER","ROWS","RRN","RUN","SAVEPOINT","SBCS","SCALAR","SCHEMA","SCRATCHPAD","SCROLL","SEARCH","SECOND","SECONDS","SECQTY","SECURED","SELECT","SENSITIVE","SEQUENCE","SESSION","SESSION_USER","SET","SIGNAL","SIMPLE","SKIP","SNAN","SOME","SOURCE","SPECIFIC","SQL","SQLID","SQLIND_DEFAULT","SQLIND_UNASSIGNED","STACKED","START","STARTING","STATEMENT","STATIC","STOGROUP","SUBSTRING","SUMMARY","SYNONYM","SYSTEM_TIME","SYSTEM_USER","TABLE","TABLESPACE","TABLESPACES","TAG","THEN","THREADSAFE","TO","TRANSACTION","TRANSFER","TRIGGER","TRIM","TRIM_ARRAY","TRUE","TRUNCATE","TRY_CAST","TYPE","UNDO","UNION","UNIQUE","UNIT","UNKNOWN","UNNEST","UNTIL","UPDATE","UPDATING","URI","USAGE","USE","USER","USERID","USING","VALUE","VALUES","VARIABLE","VARIANT","VCAT","VERSION","VERSIONING","VIEW","VOLATILE","WAIT","WHEN","WHENEVER","WHERE","WHILE","WITH","WITHIN","WITHOUT","WRAPPED","WRAPPER","WRITE","WRKSTNNAME","XMLAGG","XMLATTRIBUTES","XMLCAST","XMLCOMMENT","XMLCONCAT","XMLDOCUMENT","XMLELEMENT","XMLFOREST","XMLGROUP","XMLNAMESPACES","XMLPARSE","XMLPI","XMLROW","XMLSERIALIZE","XMLTABLE","XMLTEXT","XMLVALIDATE","XSLTRANSFORM","XSROBJECT","YEAR","YEARS","YES","ZONE"],tG=["ARRAY","BIGINT","BINARY","BIT","BLOB","BOOLEAN","CCSID","CHAR","CHARACTER","CLOB","DATA","DATALINK","DATE","DBCLOB","DECFLOAT","DECIMAL","DEC","DOUBLE","DOUBLE PRECISION","FLOAT","GRAPHIC","INT","INTEGER","LONG","NUMERIC","REAL","ROWID","SMALLINT","TIME","TIMESTAMP","VARBINARY","VARCHAR","VARGRAPHIC","XML"],nG=j(["SELECT [ALL | DISTINCT]"]),rG=j(["WITH [RECURSIVE]","INTO","FROM","WHERE","GROUP BY","HAVING","PARTITION BY","ORDER [SIBLINGS] BY [INPUT SEQUENCE]","LIMIT","OFFSET","FETCH {FIRST | NEXT}","FOR UPDATE [OF]","FOR READ ONLY","OPTIMIZE FOR","INSERT INTO","VALUES","SET","MERGE INTO","WHEN [NOT] MATCHED [THEN]","UPDATE SET","DELETE","INSERT","FOR SYSTEM NAME"]),uf=j(["CREATE [OR REPLACE] TABLE"]),kl=j(["CREATE [OR REPLACE] [RECURSIVE] VIEW","UPDATE","WHERE CURRENT OF","WITH {NC | RR | RS | CS | UR}","DELETE FROM","DROP TABLE","ALTER TABLE","ADD [COLUMN]","ALTER [COLUMN]","DROP [COLUMN]","SET DATA TYPE","SET {GENERATED ALWAYS | GENERATED BY DEFAULT}","SET NOT NULL","SET {NOT HIDDEN | IMPLICITLY HIDDEN}","SET FIELDPROC","DROP {DEFAULT | NOT NULL | GENERATED | IDENTITY | ROW CHANGE TIMESTAMP | FIELDPROC}","TRUNCATE [TABLE]","SET [CURRENT] SCHEMA","SET CURRENT_SCHEMA","ALLOCATE CURSOR","ALLOCATE [SQL] DESCRIPTOR [LOCAL | GLOBAL] SQL","ALTER [SPECIFIC] {FUNCTION | PROCEDURE}","ALTER {MASK | PERMISSION | SEQUENCE | TRIGGER}","ASSOCIATE [RESULT SET] {LOCATOR | LOCATORS}","BEGIN DECLARE SECTION","CALL","CLOSE","COMMENT ON {ALIAS | COLUMN | CONSTRAINT | INDEX | MASK | PACKAGE | PARAMETER | PERMISSION | SEQUENCE | TABLE | TRIGGER | VARIABLE | XSROBJECT}","COMMENT ON [SPECIFIC] {FUNCTION | PROCEDURE | ROUTINE}","COMMENT ON PARAMETER SPECIFIC {FUNCTION | PROCEDURE | ROUTINE}","COMMENT ON [TABLE FUNCTION] RETURN COLUMN","COMMENT ON [TABLE FUNCTION] RETURN COLUMN SPECIFIC [PROCEDURE | ROUTINE]","COMMIT [WORK] [HOLD]","CONNECT [TO | RESET] USER","CREATE [OR REPLACE] {ALIAS | FUNCTION | MASK | PERMISSION | PROCEDURE | SEQUENCE | TRIGGER | VARIABLE}","CREATE [ENCODED VECTOR] INDEX","CREATE UNIQUE [WHERE NOT NULL] INDEX","CREATE SCHEMA","CREATE TYPE","DEALLOCATE [SQL] DESCRIPTOR [LOCAL | GLOBAL]","DECLARE CURSOR","DECLARE GLOBAL TEMPORARY TABLE","DECLARE","DESCRIBE CURSOR","DESCRIBE INPUT","DESCRIBE [OUTPUT]","DESCRIBE {PROCEDURE | ROUTINE}","DESCRIBE TABLE","DISCONNECT ALL [SQL]","DISCONNECT [CURRENT]","DROP {ALIAS | INDEX | MASK | PACKAGE | PERMISSION | SCHEMA | SEQUENCE | TABLE | TYPE | VARIABLE | XSROBJECT} [IF EXISTS]","DROP [SPECIFIC] {FUNCTION | PROCEDURE | ROUTINE} [IF EXISTS]","END DECLARE SECTION","EXECUTE [IMMEDIATE]","FREE LOCATOR","GET [SQL] DESCRIPTOR [LOCAL | GLOBAL]","GET [CURRENT | STACKED] DIAGNOSTICS","GRANT {ALL [PRIVILEGES] | ALTER | EXECUTE} ON {FUNCTION | PROCEDURE | ROUTINE | PACKAGE | SCHEMA | SEQUENCE | TABLE | TYPE | VARIABLE | XSROBJECT}","HOLD LOCATOR","INCLUDE","LABEL ON {ALIAS | COLUMN | CONSTRAINT | INDEX | MASK | PACKAGE | PERMISSION | SEQUENCE | TABLE | TRIGGER | VARIABLE | XSROBJECT}","LABEL ON [SPECIFIC] {FUNCTION | PROCEDURE | ROUTINE}","LOCK TABLE","OPEN","PREPARE","REFRESH TABLE","RELEASE","RELEASE [TO] SAVEPOINT","RENAME [TABLE | INDEX] TO","REVOKE {ALL [PRIVILEGES] | ALTER | EXECUTE} ON {FUNCTION | PROCEDURE | ROUTINE | PACKAGE | SCHEMA | SEQUENCE | TABLE | TYPE | VARIABLE | XSROBJECT}","ROLLBACK [WORK] [HOLD | TO SAVEPOINT]","SAVEPOINT","SET CONNECTION","SET CURRENT {DEBUG MODE | DECFLOAT ROUNDING MODE | DEGREE | IMPLICIT XMLPARSE OPTION | TEMPORAL SYSTEM_TIME}","SET [SQL] DESCRIPTOR [LOCAL | GLOBAL]","SET ENCRYPTION PASSWORD","SET OPTION","SET {[CURRENT [FUNCTION]] PATH | CURRENT_PATH}","SET RESULT SETS [WITH RETURN [TO CALLER | TO CLIENT]]","SET SESSION AUTHORIZATION","SET SESSION_USER","SET TRANSACTION","SIGNAL SQLSTATE [VALUE]","TAG","TRANSFER OWNERSHIP OF","WHENEVER {NOT FOUND | SQLERROR | SQLWARNING}"]),oG=j(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),sG=j(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","[LEFT | RIGHT] EXCEPTION JOIN","{INNER | CROSS} JOIN"]),iG=j(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),aG=j([]),lG={name:"db2i",tokenizerOptions:{reservedSelect:nG,reservedClauses:[...rG,...uf,...kl],reservedSetOperations:oG,reservedJoins:sG,reservedKeywordPhrases:iG,reservedDataTypePhrases:aG,reservedKeywords:eG,reservedDataTypes:tG,reservedFunctionNames:Zj,nestedBlockComments:!0,extraParens:["[]"],stringTypes:[{quote:"''-qq",prefixes:["G","N"]},{quote:"''-raw",prefixes:["X","BX","GX","UX"],requirePrefix:!0}],identTypes:['""-qq'],identChars:{first:"@#$",rest:"@#$"},paramTypes:{positional:!0,named:[":"]},paramChars:{first:"@#$",rest:"@#$"},operators:["**","¬=","¬>","¬<","!>","!<","||","=>"]},formatOptions:{onelineClauses:[...uf,...kl],tabularOnelineClauses:kl}},cG=["ABS","ACOS","ADD","ADD_PARQUET_KEY","AGE","AGGREGATE","ALIAS","ALL_PROFILING_OUTPUT","ANY_VALUE","APPLY","APPROX_COUNT_DISTINCT","APPROX_QUANTILE","ARBITRARY","ARGMAX","ARGMIN","ARG_MAX","ARG_MAX_NULL","ARG_MIN","ARG_MIN_NULL","ARRAY_AGG","ARRAY_AGGR","ARRAY_AGGREGATE","ARRAY_APPEND","ARRAY_APPLY","ARRAY_CAT","ARRAY_CONCAT","ARRAY_CONTAINS","ARRAY_COSINE_SIMILARITY","ARRAY_CROSS_PRODUCT","ARRAY_DISTANCE","ARRAY_DISTINCT","ARRAY_DOT_PRODUCT","ARRAY_EXTRACT","ARRAY_FILTER","ARRAY_GRADE_UP","ARRAY_HAS","ARRAY_HAS_ALL","ARRAY_HAS_ANY","ARRAY_INDEXOF","ARRAY_INNER_PRODUCT","ARRAY_INTERSECT","ARRAY_LENGTH","ARRAY_POP_BACK","ARRAY_POP_FRONT","ARRAY_POSITION","ARRAY_PREPEND","ARRAY_PUSH_BACK","ARRAY_PUSH_FRONT","ARRAY_REDUCE","ARRAY_RESIZE","ARRAY_REVERSE","ARRAY_REVERSE_SORT","ARRAY_SELECT","ARRAY_SLICE","ARRAY_SORT","ARRAY_TO_JSON","ARRAY_TO_STRING","ARRAY_TRANSFORM","ARRAY_UNIQUE","ARRAY_VALUE","ARRAY_WHERE","ARRAY_ZIP","ARROW_SCAN","ARROW_SCAN_DUMB","ASCII","ASIN","ATAN","ATAN2","AVG","BASE64","BIN","BITSTRING","BITSTRING_AGG","BIT_AND","BIT_COUNT","BIT_LENGTH","BIT_OR","BIT_POSITION","BIT_XOR","BOOL_AND","BOOL_OR","CARDINALITY","CBRT","CEIL","CEILING","CENTURY","CHECKPOINT","CHR","COLLATIONS","COL_DESCRIPTION","COMBINE","CONCAT","CONCAT_WS","CONSTANT_OR_NULL","CONTAINS","COPY_DATABASE","CORR","COS","COT","COUNT","COUNT_IF","COUNT_STAR","COVAR_POP","COVAR_SAMP","CREATE_SORT_KEY","CURRENT_CATALOG","CURRENT_DATABASE","CURRENT_DATE","CURRENT_LOCALTIME","CURRENT_LOCALTIMESTAMP","CURRENT_QUERY","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_SCHEMAS","CURRENT_SETTING","CURRENT_USER","CURRVAL","DAMERAU_LEVENSHTEIN","DATABASE_LIST","DATABASE_SIZE","DATEDIFF","DATEPART","DATESUB","DATETRUNC","DATE_ADD","DATE_DIFF","DATE_PART","DATE_SUB","DATE_TRUNC","DAY","DAYNAME","DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","DECADE","DECODE","DEGREES","DISABLE_CHECKPOINT_ON_SHUTDOWN","DISABLE_OBJECT_CACHE","DISABLE_OPTIMIZER","DISABLE_PRINT_PROGRESS_BAR","DISABLE_PROFILE","DISABLE_PROFILING","DISABLE_PROGRESS_BAR","DISABLE_VERIFICATION","DISABLE_VERIFY_EXTERNAL","DISABLE_VERIFY_FETCH_ROW","DISABLE_VERIFY_PARALLELISM","DISABLE_VERIFY_SERIALIZER","DIVIDE","DUCKDB_COLUMNS","DUCKDB_CONSTRAINTS","DUCKDB_DATABASES","DUCKDB_DEPENDENCIES","DUCKDB_EXTENSIONS","DUCKDB_FUNCTIONS","DUCKDB_INDEXES","DUCKDB_KEYWORDS","DUCKDB_MEMORY","DUCKDB_OPTIMIZERS","DUCKDB_SCHEMAS","DUCKDB_SECRETS","DUCKDB_SEQUENCES","DUCKDB_SETTINGS","DUCKDB_TABLES","DUCKDB_TEMPORARY_FILES","DUCKDB_TYPES","DUCKDB_VIEWS","EDIT","EDITDIST3","ELEMENT_AT","ENABLE_CHECKPOINT_ON_SHUTDOWN","ENABLE_OBJECT_CACHE","ENABLE_OPTIMIZER","ENABLE_PRINT_PROGRESS_BAR","ENABLE_PROFILE","ENABLE_PROFILING","ENABLE_PROGRESS_BAR","ENABLE_VERIFICATION","ENCODE","ENDS_WITH","ENTROPY","ENUM_CODE","ENUM_FIRST","ENUM_LAST","ENUM_RANGE","ENUM_RANGE_BOUNDARY","EPOCH","EPOCH_MS","EPOCH_NS","EPOCH_US","ERA","ERROR","EVEN","EXP","FACTORIAL","FAVG","FDIV","FILTER","FINALIZE","FIRST","FLATTEN","FLOOR","FMOD","FORCE_CHECKPOINT","FORMAT","FORMATREADABLEDECIMALSIZE","FORMATREADABLESIZE","FORMAT_BYTES","FORMAT_PG_TYPE","FORMAT_TYPE","FROM_BASE64","FROM_BINARY","FROM_HEX","FROM_JSON","FROM_JSON_STRICT","FSUM","FUNCTIONS","GAMMA","GCD","GENERATE_SERIES","GENERATE_SUBSCRIPTS","GEN_RANDOM_UUID","GEOMEAN","GEOMETRIC_MEAN","GETENV","GET_BIT","GET_BLOCK_SIZE","GET_CURRENT_TIME","GET_CURRENT_TIMESTAMP","GLOB","GRADE_UP","GREATEST","GREATEST_COMMON_DIVISOR","GROUP_CONCAT","HAMMING","HASH","HAS_ANY_COLUMN_PRIVILEGE","HAS_COLUMN_PRIVILEGE","HAS_DATABASE_PRIVILEGE","HAS_FOREIGN_DATA_WRAPPER_PRIVILEGE","HAS_FUNCTION_PRIVILEGE","HAS_LANGUAGE_PRIVILEGE","HAS_SCHEMA_PRIVILEGE","HAS_SEQUENCE_PRIVILEGE","HAS_SERVER_PRIVILEGE","HAS_TABLESPACE_PRIVILEGE","HAS_TABLE_PRIVILEGE","HEX","HISTOGRAM","HOUR","ICU_CALENDAR_NAMES","ICU_SORT_KEY","ILIKE_ESCAPE","IMPORT_DATABASE","INDEX_SCAN","INET_CLIENT_ADDR","INET_CLIENT_PORT","INET_SERVER_ADDR","INET_SERVER_PORT","INSTR","IN_SEARCH_PATH","ISFINITE","ISINF","ISNAN","ISODOW","ISOYEAR","JACCARD","JARO_SIMILARITY","JARO_WINKLER_SIMILARITY","JSON_ARRAY","JSON_ARRAY_LENGTH","JSON_CONTAINS","JSON_DESERIALIZE_SQL","JSON_EXECUTE_SERIALIZED_SQL","JSON_EXTRACT","JSON_EXTRACT_PATH","JSON_EXTRACT_PATH_TEXT","JSON_EXTRACT_STRING","JSON_GROUP_ARRAY","JSON_GROUP_OBJECT","JSON_GROUP_STRUCTURE","JSON_KEYS","JSON_MERGE_PATCH","JSON_OBJECT","JSON_QUOTE","JSON_SERIALIZE_PLAN","JSON_SERIALIZE_SQL","JSON_STRUCTURE","JSON_TRANSFORM","JSON_TRANSFORM_STRICT","JSON_TYPE","JSON_VALID","JULIAN","KAHAN_SUM","KURTOSIS","KURTOSIS_POP","LAST","LAST_DAY","LCASE","LCM","LEAST","LEAST_COMMON_MULTIPLE","LEFT","LEFT_GRAPHEME","LEN","LENGTH","LENGTH_GRAPHEME","LEVENSHTEIN","LGAMMA","LIKE_ESCAPE","LIST","LISTAGG","LIST_AGGR","LIST_AGGREGATE","LIST_ANY_VALUE","LIST_APPEND","LIST_APPLY","LIST_APPROX_COUNT_DISTINCT","LIST_AVG","LIST_BIT_AND","LIST_BIT_OR","LIST_BIT_XOR","LIST_BOOL_AND","LIST_BOOL_OR","LIST_CAT","LIST_CONCAT","LIST_CONTAINS","LIST_COSINE_SIMILARITY","LIST_COUNT","LIST_DISTANCE","LIST_DISTINCT","LIST_DOT_PRODUCT","LIST_ELEMENT","LIST_ENTROPY","LIST_EXTRACT","LIST_FILTER","LIST_FIRST","LIST_GRADE_UP","LIST_HAS","LIST_HAS_ALL","LIST_HAS_ANY","LIST_HISTOGRAM","LIST_INDEXOF","LIST_INNER_PRODUCT","LIST_INTERSECT","LIST_KURTOSIS","LIST_KURTOSIS_POP","LIST_LAST","LIST_MAD","LIST_MAX","LIST_MEDIAN","LIST_MIN","LIST_MODE","LIST_PACK","LIST_POSITION","LIST_PREPEND","LIST_PRODUCT","LIST_REDUCE","LIST_RESIZE","LIST_REVERSE","LIST_REVERSE_SORT","LIST_SELECT","LIST_SEM","LIST_SKEWNESS","LIST_SLICE","LIST_SORT","LIST_STDDEV_POP","LIST_STDDEV_SAMP","LIST_STRING_AGG","LIST_SUM","LIST_TRANSFORM","LIST_UNIQUE","LIST_VALUE","LIST_VAR_POP","LIST_VAR_SAMP","LIST_WHERE","LIST_ZIP","LN","LOG","LOG10","LOG2","LOWER","LPAD","LSMODE","LTRIM","MAD","MAKE_DATE","MAKE_TIME","MAKE_TIMESTAMP","MAKE_TIMESTAMPTZ","MAP","MAP_CONCAT","MAP_ENTRIES","MAP_EXTRACT","MAP_FROM_ENTRIES","MAP_KEYS","MAP_VALUES","MAX","MAX_BY","MD5","MD5_NUMBER","MD5_NUMBER_LOWER","MD5_NUMBER_UPPER","MEAN","MEDIAN","METADATA_INFO","MICROSECOND","MILLENNIUM","MILLISECOND","MIN","MINUTE","MIN_BY","MISMATCHES","MOD","MODE","MONTH","MONTHNAME","MULTIPLY","NEXTAFTER","NEXTVAL","NFC_NORMALIZE","NOT_ILIKE_ESCAPE","NOT_LIKE_ESCAPE","NOW","NULLIF","OBJ_DESCRIPTION","OCTET_LENGTH","ORD","PARQUET_FILE_METADATA","PARQUET_KV_METADATA","PARQUET_METADATA","PARQUET_SCAN","PARQUET_SCHEMA","PARSE_DIRNAME","PARSE_DIRPATH","PARSE_FILENAME","PARSE_PATH","PG_COLLATION_IS_VISIBLE","PG_CONF_LOAD_TIME","PG_CONVERSION_IS_VISIBLE","PG_FUNCTION_IS_VISIBLE","PG_GET_CONSTRAINTDEF","PG_GET_EXPR","PG_GET_VIEWDEF","PG_HAS_ROLE","PG_IS_OTHER_TEMP_SCHEMA","PG_MY_TEMP_SCHEMA","PG_OPCLASS_IS_VISIBLE","PG_OPERATOR_IS_VISIBLE","PG_OPFAMILY_IS_VISIBLE","PG_POSTMASTER_START_TIME","PG_SIZE_PRETTY","PG_TABLE_IS_VISIBLE","PG_TIMEZONE_NAMES","PG_TS_CONFIG_IS_VISIBLE","PG_TS_DICT_IS_VISIBLE","PG_TS_PARSER_IS_VISIBLE","PG_TS_TEMPLATE_IS_VISIBLE","PG_TYPEOF","PG_TYPE_IS_VISIBLE","PI","PLATFORM","POSITION","POW","POWER","PRAGMA_COLLATIONS","PRAGMA_DATABASE_SIZE","PRAGMA_METADATA_INFO","PRAGMA_PLATFORM","PRAGMA_SHOW","PRAGMA_STORAGE_INFO","PRAGMA_TABLE_INFO","PRAGMA_USER_AGENT","PRAGMA_VERSION","PREFIX","PRINTF","PRODUCT","QUANTILE","QUANTILE_CONT","QUANTILE_DISC","QUARTER","RADIANS","RANDOM","RANGE","READFILE","READ_BLOB","READ_CSV","READ_CSV_AUTO","READ_JSON","READ_JSON_AUTO","READ_JSON_OBJECTS","READ_JSON_OBJECTS_AUTO","READ_NDJSON","READ_NDJSON_AUTO","READ_NDJSON_OBJECTS","READ_PARQUET","READ_TEXT","REDUCE","REGEXP_ESCAPE","REGEXP_EXTRACT","REGEXP_EXTRACT_ALL","REGEXP_FULL_MATCH","REGEXP_MATCHES","REGEXP_REPLACE","REGEXP_SPLIT_TO_ARRAY","REGEXP_SPLIT_TO_TABLE","REGR_AVGX","REGR_AVGY","REGR_COUNT","REGR_INTERCEPT","REGR_R2","REGR_SLOPE","REGR_SXX","REGR_SXY","REGR_SYY","REPEAT","REPEAT_ROW","REPLACE","RESERVOIR_QUANTILE","REVERSE","RIGHT","RIGHT_GRAPHEME","ROUND","ROUNDBANKERS","ROUND_EVEN","ROW","ROW_TO_JSON","RPAD","RTRIM","SECOND","SEM","SEQ_SCAN","SESSION_USER","SETSEED","SET_BIT","SHA256","SHA3","SHELL_ADD_SCHEMA","SHELL_ESCAPE_CRNL","SHELL_IDQUOTE","SHELL_MODULE_SCHEMA","SHELL_PUTSNL","SHOBJ_DESCRIPTION","SHOW","SHOW_DATABASES","SHOW_TABLES","SHOW_TABLES_EXPANDED","SIGN","SIGNBIT","SIN","SKEWNESS","SNIFF_CSV","SPLIT","SPLIT_PART","SQL_AUTO_COMPLETE","SQRT","STARTS_WITH","STATS","STDDEV","STDDEV_POP","STDDEV_SAMP","STORAGE_INFO","STRFTIME","STRING_AGG","STRING_SPLIT","STRING_SPLIT_REGEX","STRING_TO_ARRAY","STRIP_ACCENTS","STRLEN","STRPOS","STRPTIME","STRUCT_EXTRACT","STRUCT_INSERT","STRUCT_PACK","STR_SPLIT","STR_SPLIT_REGEX","SUBSTR","SUBSTRING","SUBSTRING_GRAPHEME","SUBTRACT","SUFFIX","SUM","SUMKAHAN","SUMMARY","SUM_NO_OVERFLOW","TABLE_INFO","TAN","TEST_ALL_TYPES","TEST_VECTOR_TYPES","TIMEZONE","TIMEZONE_HOUR","TIMEZONE_MINUTE","TIME_BUCKET","TODAY","TO_BASE","TO_BASE64","TO_BINARY","TO_CENTURIES","TO_DAYS","TO_DECADES","TO_HEX","TO_HOURS","TO_JSON","TO_MICROSECONDS","TO_MILLENNIA","TO_MILLISECONDS","TO_MINUTES","TO_MONTHS","TO_SECONDS","TO_TIMESTAMP","TO_WEEKS","TO_YEARS","TRANSACTION_TIMESTAMP","TRANSLATE","TRIM","TRUNC","TRY_STRPTIME","TXID_CURRENT","TYPEOF","UCASE","UNBIN","UNHEX","UNICODE","UNION_EXTRACT","UNION_TAG","UNION_VALUE","UNNEST","UNPIVOT_LIST","UPPER","USER","USER_AGENT","UUID","VARIANCE","VAR_POP","VAR_SAMP","VECTOR_TYPE","VERIFY_EXTERNAL","VERIFY_FETCH_ROW","VERIFY_PARALLELISM","VERIFY_SERIALIZER","VERSION","WEEK","WEEKDAY","WEEKOFYEAR","WHICH_SECRET","WRITEFILE","XOR","YEAR","YEARWEEK","CAST","COALESCE","RANK","ROW_NUMBER"],dG=["ALL","ANALYSE","ANALYZE","AND","ANY","AS","ASC","ATTACH","ASYMMETRIC","BOTH","CASE","CAST","CHECK","COLLATE","COLUMN","CONSTRAINT","CREATE","DEFAULT","DEFERRABLE","DESC","DESCRIBE","DETACH","DISTINCT","DO","ELSE","END","EXCEPT","FALSE","FETCH","FOR","FOREIGN","FROM","GRANT","GROUP","HAVING","IN","INITIALLY","INTERSECT","INTO","IS","LATERAL","LEADING","LIMIT","NOT","NULL","OFFSET","ON","ONLY","OR","ORDER","PIVOT","PIVOT_LONGER","PIVOT_WIDER","PLACING","PRIMARY","REFERENCES","RETURNING","SELECT","SHOW","SOME","SUMMARIZE","SYMMETRIC","TABLE","THEN","TO","TRAILING","TRUE","UNION","UNIQUE","UNPIVOT","USING","VARIADIC","WHEN","WHERE","WINDOW","WITH"],EG=["ARRAY","BIGINT","BINARY","BIT","BITSTRING","BLOB","BOOL","BOOLEAN","BPCHAR","BYTEA","CHAR","DATE","DATETIME","DEC","DECIMAL","DOUBLE","ENUM","FLOAT","FLOAT4","FLOAT8","GUID","HUGEINT","INET","INT","INT1","INT128","INT16","INT2","INT32","INT4","INT64","INT8","INTEGER","INTEGRAL","INTERVAL","JSON","LIST","LOGICAL","LONG","MAP","NUMERIC","NVARCHAR","OID","REAL","ROW","SHORT","SIGNED","SMALLINT","STRING","STRUCT","TEXT","TIME","TIMESTAMP_MS","TIMESTAMP_NS","TIMESTAMP_S","TIMESTAMP_US","TIMESTAMP","TIMESTAMPTZ","TIMETZ","TINYINT","UBIGINT","UHUGEINT","UINT128","UINT16","UINT32","UINT64","UINT8","UINTEGER","UNION","USMALLINT","UTINYINT","UUID","VARBINARY","VARCHAR"],uG=j(["SELECT [ALL | DISTINCT]"]),TG=j(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY [ALL]","HAVING","WINDOW","PARTITION BY","ORDER BY [ALL]","LIMIT","OFFSET","USING SAMPLE","QUALIFY","INSERT [OR REPLACE] INTO","VALUES","DEFAULT VALUES","SET","RETURNING"]),Tf=j(["CREATE [OR REPLACE] [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),jl=j(["UPDATE","ON CONFLICT","DELETE FROM","DROP TABLE [IF EXISTS]","TRUNCATE","ALTER TABLE","ADD [COLUMN] [IF NOT EXISTS]","ADD PRIMARY KEY","DROP [COLUMN] [IF EXISTS]","ALTER [COLUMN]","RENAME [COLUMN]","RENAME TO","SET [DATA] TYPE","{SET | DROP} DEFAULT","{SET | DROP} NOT NULL","CREATE [OR REPLACE] [TEMPORARY | TEMP] {MACRO | FUNCTION}","DROP MACRO [TABLE] [IF EXISTS]","DROP FUNCTION [IF EXISTS]","CREATE [UNIQUE] INDEX [IF NOT EXISTS]","DROP INDEX [IF EXISTS]","CREATE [OR REPLACE] SCHEMA [IF NOT EXISTS]","DROP SCHEMA [IF EXISTS]","CREATE [OR REPLACE] [PERSISTENT | TEMPORARY] SECRET [IF NOT EXISTS]","DROP [PERSISTENT | TEMPORARY] SECRET [IF EXISTS]","CREATE [OR REPLACE] [TEMPORARY | TEMP] SEQUENCE","DROP SEQUENCE [IF EXISTS]","CREATE [OR REPLACE] [TEMPORARY | TEMP] VIEW [IF NOT EXISTS]","DROP VIEW [IF EXISTS]","ALTER VIEW","CREATE TYPE","DROP TYPE [IF EXISTS]","ANALYZE","ATTACH [DATABASE] [IF NOT EXISTS]","DETACH [DATABASE] [IF EXISTS]","CALL","[FORCE] CHECKPOINT","COMMENT ON [TABLE | COLUMN | VIEW | INDEX | SEQUENCE | TYPE | MACRO | MACRO TABLE]","COPY [FROM DATABASE]","DESCRIBE","EXPORT DATABASE","IMPORT DATABASE","INSTALL","LOAD","PIVOT","PIVOT_WIDER","UNPIVOT","EXPLAIN [ANALYZE]","SET {LOCAL | SESSION | GLOBAL}","RESET [LOCAL | SESSION | GLOBAL]","{SET | RESET} VARIABLE","SUMMARIZE","BEGIN TRANSACTION","ROLLBACK","COMMIT","ABORT","USE","VACUUM [ANALYZE]","PREPARE","EXECUTE","DEALLOCATE [PREPARE]"]),fG=j(["UNION [ALL | BY NAME]","EXCEPT [ALL]","INTERSECT [ALL]"]),pG=j(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","{NATURAL | ASOF} [INNER] JOIN","{NATURAL | ASOF} {LEFT | RIGHT | FULL} [OUTER] JOIN","POSITIONAL JOIN","ANTI JOIN","SEMI JOIN"]),SG=j(["{ROWS | RANGE | GROUPS} BETWEEN","SIMILAR TO","IS [NOT] DISTINCT FROM"]),RG=j(["TIMESTAMP WITH TIME ZONE"]),hG={name:"duckdb",tokenizerOptions:{reservedSelect:uG,reservedClauses:[...TG,...Tf,...jl],reservedSetOperations:fG,reservedJoins:pG,reservedKeywordPhrases:SG,reservedDataTypePhrases:RG,supportsXor:!0,reservedKeywords:dG,reservedDataTypes:EG,reservedFunctionNames:cG,nestedBlockComments:!0,extraParens:["[]","{}"],underscoresInNumbers:!0,stringTypes:["$$","''-qq",{quote:"''-qq-bs",prefixes:["E"],requirePrefix:!0},{quote:"''-raw",prefixes:["B","X"],requirePrefix:!0}],identTypes:['""-qq'],identChars:{rest:"$"},paramTypes:{positional:!0,numbered:["$"],quoted:["$"]},operators:["//","%","**","^","!","&","|","~","<<",">>","::","==","->","->>",":",":=","=>","~~","!~~","~~*","!~~*","~~~","~","!~","~*","!~*","^@","||",">>=","<<="]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...Tf,...jl],tabularOnelineClauses:jl}},AG=["ABS","ACOS","ASIN","ATAN","BIN","BROUND","CBRT","CEIL","CEILING","CONV","COS","DEGREES","EXP","FACTORIAL","FLOOR","GREATEST","HEX","LEAST","LN","LOG","LOG10","LOG2","NEGATIVE","PI","PMOD","POSITIVE","POW","POWER","RADIANS","RAND","ROUND","SHIFTLEFT","SHIFTRIGHT","SHIFTRIGHTUNSIGNED","SIGN","SIN","SQRT","TAN","UNHEX","WIDTH_BUCKET","ARRAY_CONTAINS","MAP_KEYS","MAP_VALUES","SIZE","SORT_ARRAY","BINARY","CAST","ADD_MONTHS","DATE","DATE_ADD","DATE_FORMAT","DATE_SUB","DATEDIFF","DAY","DAYNAME","DAYOFMONTH","DAYOFYEAR","EXTRACT","FROM_UNIXTIME","FROM_UTC_TIMESTAMP","HOUR","LAST_DAY","MINUTE","MONTH","MONTHS_BETWEEN","NEXT_DAY","QUARTER","SECOND","TIMESTAMP","TO_DATE","TO_UTC_TIMESTAMP","TRUNC","UNIX_TIMESTAMP","WEEKOFYEAR","YEAR","ASSERT_TRUE","COALESCE","IF","ISNOTNULL","ISNULL","NULLIF","NVL","ASCII","BASE64","CHARACTER_LENGTH","CHR","CONCAT","CONCAT_WS","CONTEXT_NGRAMS","DECODE","ELT","ENCODE","FIELD","FIND_IN_SET","FORMAT_NUMBER","GET_JSON_OBJECT","IN_FILE","INITCAP","INSTR","LCASE","LENGTH","LEVENSHTEIN","LOCATE","LOWER","LPAD","LTRIM","NGRAMS","OCTET_LENGTH","PARSE_URL","PRINTF","QUOTE","REGEXP_EXTRACT","REGEXP_REPLACE","REPEAT","REVERSE","RPAD","RTRIM","SENTENCES","SOUNDEX","SPACE","SPLIT","STR_TO_MAP","SUBSTR","SUBSTRING","TRANSLATE","TRIM","UCASE","UNBASE64","UPPER","MASK","MASK_FIRST_N","MASK_HASH","MASK_LAST_N","MASK_SHOW_FIRST_N","MASK_SHOW_LAST_N","AES_DECRYPT","AES_ENCRYPT","CRC32","CURRENT_DATABASE","CURRENT_USER","HASH","JAVA_METHOD","LOGGED_IN_USER","MD5","REFLECT","SHA","SHA1","SHA2","SURROGATE_KEY","VERSION","AVG","COLLECT_LIST","COLLECT_SET","CORR","COUNT","COVAR_POP","COVAR_SAMP","HISTOGRAM_NUMERIC","MAX","MIN","NTILE","PERCENTILE","PERCENTILE_APPROX","REGR_AVGX","REGR_AVGY","REGR_COUNT","REGR_INTERCEPT","REGR_R2","REGR_SLOPE","REGR_SXX","REGR_SXY","REGR_SYY","STDDEV_POP","STDDEV_SAMP","SUM","VAR_POP","VAR_SAMP","VARIANCE","EXPLODE","INLINE","JSON_TUPLE","PARSE_URL_TUPLE","POSEXPLODE","STACK","LEAD","LAG","FIRST_VALUE","LAST_VALUE","RANK","ROW_NUMBER","DENSE_RANK","CUME_DIST","PERCENT_RANK","NTILE"],IG=["ADD","ADMIN","AFTER","ANALYZE","ARCHIVE","ASC","BEFORE","BUCKET","BUCKETS","CASCADE","CHANGE","CLUSTER","CLUSTERED","CLUSTERSTATUS","COLLECTION","COLUMNS","COMMENT","COMPACT","COMPACTIONS","COMPUTE","CONCATENATE","CONTINUE","DATA","DATABASES","DATETIME","DAY","DBPROPERTIES","DEFERRED","DEFINED","DELIMITED","DEPENDENCY","DESC","DIRECTORIES","DIRECTORY","DISABLE","DISTRIBUTE","ELEM_TYPE","ENABLE","ESCAPED","EXCLUSIVE","EXPLAIN","EXPORT","FIELDS","FILE","FILEFORMAT","FIRST","FORMAT","FORMATTED","FUNCTIONS","HOLD_DDLTIME","HOUR","IDXPROPERTIES","IGNORE","INDEX","INDEXES","INPATH","INPUTDRIVER","INPUTFORMAT","ITEMS","JAR","KEYS","KEY_TYPE","LIMIT","LINES","LOAD","LOCATION","LOCK","LOCKS","LOGICAL","LONG","MAPJOIN","MATERIALIZED","METADATA","MINUS","MINUTE","MONTH","MSCK","NOSCAN","NO_DROP","OFFLINE","OPTION","OUTPUTDRIVER","OUTPUTFORMAT","OVERWRITE","OWNER","PARTITIONED","PARTITIONS","PLUS","PRETTY","PRINCIPALS","PROTECTION","PURGE","READ","READONLY","REBUILD","RECORDREADER","RECORDWRITER","RELOAD","RENAME","REPAIR","REPLACE","REPLICATION","RESTRICT","REWRITE","ROLE","ROLES","SCHEMA","SCHEMAS","SECOND","SEMI","SERDE","SERDEPROPERTIES","SERVER","SETS","SHARED","SHOW","SHOW_DATABASE","SKEWED","SORT","SORTED","SSL","STATISTICS","STORED","STREAMTABLE","STRING","TABLES","TBLPROPERTIES","TEMPORARY","TERMINATED","TINYINT","TOUCH","TRANSACTIONS","UNARCHIVE","UNDO","UNIONTYPE","UNLOCK","UNSET","UNSIGNED","URI","USE","UTC","UTCTIMESTAMP","VALUE_TYPE","VIEW","WHILE","YEAR","AUTOCOMMIT","ISOLATION","LEVEL","OFFSET","SNAPSHOT","TRANSACTION","WORK","WRITE","ABORT","KEY","LAST","NORELY","NOVALIDATE","NULLS","RELY","VALIDATE","DETAIL","DOW","EXPRESSION","OPERATOR","QUARTER","SUMMARY","VECTORIZATION","WEEK","YEARS","MONTHS","WEEKS","DAYS","HOURS","MINUTES","SECONDS","TIMESTAMPTZ","ZONE","ALL","ALTER","AND","AS","AUTHORIZATION","BETWEEN","BOTH","BY","CASE","CAST","COLUMN","CONF","CREATE","CROSS","CUBE","CURRENT","CURRENT_DATE","CURRENT_TIMESTAMP","CURSOR","DATABASE","DELETE","DESCRIBE","DISTINCT","DROP","ELSE","END","EXCHANGE","EXISTS","EXTENDED","EXTERNAL","FALSE","FETCH","FOLLOWING","FOR","FROM","FULL","FUNCTION","GRANT","GROUP","GROUPING","HAVING","IF","IMPORT","IN","INNER","INSERT","INTERSECT","INTO","IS","JOIN","LATERAL","LEFT","LESS","LIKE","LOCAL","MACRO","MORE","NONE","NOT","NULL","OF","ON","OR","ORDER","OUT","OUTER","OVER","PARTIALSCAN","PARTITION","PERCENT","PRECEDING","PRESERVE","PROCEDURE","RANGE","READS","REDUCE","REVOKE","RIGHT","ROLLUP","ROW","ROWS","SELECT","SET","TABLE","TABLESAMPLE","THEN","TO","TRANSFORM","TRIGGER","TRUE","TRUNCATE","UNBOUNDED","UNION","UNIQUEJOIN","UPDATE","USER","USING","UTC_TMESTAMP","VALUES","WHEN","WHERE","WINDOW","WITH","COMMIT","ONLY","REGEXP","RLIKE","ROLLBACK","START","CACHE","CONSTRAINT","FOREIGN","PRIMARY","REFERENCES","DAYOFWEEK","EXTRACT","FLOOR","VIEWS","TIME","SYNC","TEXTFILE","SEQUENCEFILE","ORC","CSV","TSV","PARQUET","AVRO","RCFILE","JSONFILE","INPUTFORMAT","OUTPUTFORMAT"],mG=["ARRAY","BIGINT","BINARY","BOOLEAN","CHAR","DATE","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","INTERVAL","MAP","NUMERIC","PRECISION","SMALLINT","STRUCT","TIMESTAMP","VARCHAR"],OG=j(["SELECT [ALL | DISTINCT]"]),NG=j(["WITH","FROM","WHERE","GROUP BY","HAVING","WINDOW","PARTITION BY","ORDER BY","SORT BY","CLUSTER BY","DISTRIBUTE BY","LIMIT","INSERT INTO [TABLE]","VALUES","SET","MERGE INTO","WHEN [NOT] MATCHED [THEN]","UPDATE SET","INSERT [VALUES]","INSERT OVERWRITE [LOCAL] DIRECTORY","LOAD DATA [LOCAL] INPATH","[OVERWRITE] INTO TABLE"]),ff=j(["CREATE [TEMPORARY] [EXTERNAL] TABLE [IF NOT EXISTS]"]),Gl=j(["CREATE [MATERIALIZED] VIEW [IF NOT EXISTS]","UPDATE","DELETE FROM","DROP TABLE [IF EXISTS]","ALTER TABLE","RENAME TO","TRUNCATE [TABLE]","ALTER","CREATE","USE","DESCRIBE","DROP","FETCH","SHOW","STORED AS","STORED BY","ROW FORMAT"]),gG=j(["UNION [ALL | DISTINCT]"]),xG=j(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","LEFT SEMI JOIN"]),yG=j(["{ROWS | RANGE} BETWEEN"]),CG=j([]),LG={name:"hive",tokenizerOptions:{reservedSelect:OG,reservedClauses:[...NG,...ff,...Gl],reservedSetOperations:gG,reservedJoins:xG,reservedKeywordPhrases:yG,reservedDataTypePhrases:CG,reservedKeywords:IG,reservedDataTypes:mG,reservedFunctionNames:AG,extraParens:["[]"],stringTypes:['""-bs',"''-bs"],identTypes:["``"],variableTypes:[{quote:"{}",prefixes:["$"],requirePrefix:!0}],operators:["%","~","^","|","&","<=>","==","!","||"]},formatOptions:{onelineClauses:[...ff,...Gl],tabularOnelineClauses:Gl}};function _a(e){return e.map((t,n)=>{const r=e[n+1]||hn;if(An.SET(t)&&r.text==="(")return Object.assign(Object.assign({},t),{type:K.RESERVED_FUNCTION_NAME});const o=e[n-1]||hn;return An.VALUES(t)&&o.text==="="?Object.assign(Object.assign({},t),{type:K.RESERVED_FUNCTION_NAME}):t})}const _G=["ACCESSIBLE","ADD","ALL","ALTER","ANALYZE","AND","AS","ASC","ASENSITIVE","BEFORE","BETWEEN","BOTH","BY","CALL","CASCADE","CASE","CHANGE","CHECK","COLLATE","COLUMN","CONDITION","CONSTRAINT","CONTINUE","CONVERT","CREATE","CROSS","CURRENT_DATE","CURRENT_ROLE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURSOR","DATABASE","DATABASES","DAY_HOUR","DAY_MICROSECOND","DAY_MINUTE","DAY_SECOND","DECLARE","DEFAULT","DELAYED","DELETE","DELETE_DOMAIN_ID","DESC","DESCRIBE","DETERMINISTIC","DISTINCT","DISTINCTROW","DIV","DO_DOMAIN_IDS","DROP","DUAL","EACH","ELSE","ELSEIF","ENCLOSED","ESCAPED","EXCEPT","EXISTS","EXIT","EXPLAIN","FALSE","FETCH","FOR","FORCE","FOREIGN","FROM","FULLTEXT","GENERAL","GRANT","GROUP","HAVING","HIGH_PRIORITY","HOUR_MICROSECOND","HOUR_MINUTE","HOUR_SECOND","IF","IGNORE","IGNORE_DOMAIN_IDS","IGNORE_SERVER_IDS","IN","INDEX","INFILE","INNER","INOUT","INSENSITIVE","INSERT","INTERSECT","INTERVAL","INTO","IS","ITERATE","JOIN","KEY","KEYS","KILL","LEADING","LEAVE","LEFT","LIKE","LIMIT","LINEAR","LINES","LOAD","LOCALTIME","LOCALTIMESTAMP","LOCK","LOOP","LOW_PRIORITY","MASTER_HEARTBEAT_PERIOD","MASTER_SSL_VERIFY_SERVER_CERT","MATCH","MAXVALUE","MINUTE_MICROSECOND","MINUTE_SECOND","MOD","MODIFIES","NATURAL","NOT","NO_WRITE_TO_BINLOG","NULL","OFFSET","ON","OPTIMIZE","OPTION","OPTIONALLY","OR","ORDER","OUT","OUTER","OUTFILE","OVER","PAGE_CHECKSUM","PARSE_VCOL_EXPR","PARTITION","POSITION","PRIMARY","PROCEDURE","PURGE","RANGE","READ","READS","READ_WRITE","RECURSIVE","REF_SYSTEM_ID","REFERENCES","REGEXP","RELEASE","RENAME","REPEAT","REPLACE","REQUIRE","RESIGNAL","RESTRICT","RETURN","RETURNING","REVOKE","RIGHT","RLIKE","ROW_NUMBER","ROWS","SCHEMA","SCHEMAS","SECOND_MICROSECOND","SELECT","SENSITIVE","SEPARATOR","SET","SHOW","SIGNAL","SLOW","SPATIAL","SPECIFIC","SQL","SQLEXCEPTION","SQLSTATE","SQLWARNING","SQL_BIG_RESULT","SQL_CALC_FOUND_ROWS","SQL_SMALL_RESULT","SSL","STARTING","STATS_AUTO_RECALC","STATS_PERSISTENT","STATS_SAMPLE_PAGES","STRAIGHT_JOIN","TABLE","TERMINATED","THEN","TO","TRAILING","TRIGGER","TRUE","UNDO","UNION","UNIQUE","UNLOCK","UNSIGNED","UPDATE","USAGE","USE","USING","UTC_DATE","UTC_TIME","UTC_TIMESTAMP","VALUES","WHEN","WHERE","WHILE","WINDOW","WITH","WRITE","XOR","YEAR_MONTH","ZEROFILL"],bG=["BIGINT","BINARY","BIT","BLOB","CHAR BYTE","CHAR","CHARACTER","DATETIME","DEC","DECIMAL","DOUBLE PRECISION","DOUBLE","ENUM","FIXED","FLOAT","FLOAT4","FLOAT8","INT","INT1","INT2","INT3","INT4","INT8","INTEGER","LONG","LONGBLOB","LONGTEXT","MEDIUMBLOB","MEDIUMINT","MEDIUMTEXT","MIDDLEINT","NATIONAL CHAR","NATIONAL VARCHAR","NUMERIC","PRECISION","REAL","SMALLINT","TEXT","TIMESTAMP","TINYBLOB","TINYINT","TINYTEXT","VARBINARY","VARCHAR","VARCHARACTER","VARYING","YEAR"],DG=["ADDDATE","ADD_MONTHS","BIT_AND","BIT_OR","BIT_XOR","CAST","COUNT","CUME_DIST","CURDATE","CURTIME","DATE_ADD","DATE_SUB","DATE_FORMAT","DECODE","DENSE_RANK","EXTRACT","FIRST_VALUE","GROUP_CONCAT","JSON_ARRAYAGG","JSON_OBJECTAGG","LAG","LEAD","MAX","MEDIAN","MID","MIN","NOW","NTH_VALUE","NTILE","POSITION","PERCENT_RANK","PERCENTILE_CONT","PERCENTILE_DISC","RANK","ROW_NUMBER","SESSION_USER","STD","STDDEV","STDDEV_POP","STDDEV_SAMP","SUBDATE","SUBSTR","SUBSTRING","SUM","SYSTEM_USER","TRIM","TRIM_ORACLE","VARIANCE","VAR_POP","VAR_SAMP","ABS","ACOS","ADDTIME","AES_DECRYPT","AES_ENCRYPT","ASIN","ATAN","ATAN2","BENCHMARK","BIN","BINLOG_GTID_POS","BIT_COUNT","BIT_LENGTH","CEIL","CEILING","CHARACTER_LENGTH","CHAR_LENGTH","CHR","COERCIBILITY","COLUMN_CHECK","COLUMN_EXISTS","COLUMN_LIST","COLUMN_JSON","COMPRESS","CONCAT","CONCAT_OPERATOR_ORACLE","CONCAT_WS","CONNECTION_ID","CONV","CONVERT_TZ","COS","COT","CRC32","DATEDIFF","DAYNAME","DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","DEGREES","DECODE_HISTOGRAM","DECODE_ORACLE","DES_DECRYPT","DES_ENCRYPT","ELT","ENCODE","ENCRYPT","EXP","EXPORT_SET","EXTRACTVALUE","FIELD","FIND_IN_SET","FLOOR","FORMAT","FOUND_ROWS","FROM_BASE64","FROM_DAYS","FROM_UNIXTIME","GET_LOCK","GREATEST","HEX","IFNULL","INSTR","ISNULL","IS_FREE_LOCK","IS_USED_LOCK","JSON_ARRAY","JSON_ARRAY_APPEND","JSON_ARRAY_INSERT","JSON_COMPACT","JSON_CONTAINS","JSON_CONTAINS_PATH","JSON_DEPTH","JSON_DETAILED","JSON_EXISTS","JSON_EXTRACT","JSON_INSERT","JSON_KEYS","JSON_LENGTH","JSON_LOOSE","JSON_MERGE","JSON_MERGE_PATCH","JSON_MERGE_PRESERVE","JSON_QUERY","JSON_QUOTE","JSON_OBJECT","JSON_REMOVE","JSON_REPLACE","JSON_SET","JSON_SEARCH","JSON_TYPE","JSON_UNQUOTE","JSON_VALID","JSON_VALUE","LAST_DAY","LAST_INSERT_ID","LCASE","LEAST","LENGTH","LENGTHB","LN","LOAD_FILE","LOCATE","LOG","LOG10","LOG2","LOWER","LPAD","LPAD_ORACLE","LTRIM","LTRIM_ORACLE","MAKEDATE","MAKETIME","MAKE_SET","MASTER_GTID_WAIT","MASTER_POS_WAIT","MD5","MONTHNAME","NAME_CONST","NVL","NVL2","OCT","OCTET_LENGTH","ORD","PERIOD_ADD","PERIOD_DIFF","PI","POW","POWER","QUOTE","REGEXP_INSTR","REGEXP_REPLACE","REGEXP_SUBSTR","RADIANS","RAND","RELEASE_ALL_LOCKS","RELEASE_LOCK","REPLACE_ORACLE","REVERSE","ROUND","RPAD","RPAD_ORACLE","RTRIM","RTRIM_ORACLE","SEC_TO_TIME","SHA","SHA1","SHA2","SIGN","SIN","SLEEP","SOUNDEX","SPACE","SQRT","STRCMP","STR_TO_DATE","SUBSTR_ORACLE","SUBSTRING_INDEX","SUBTIME","SYS_GUID","TAN","TIMEDIFF","TIME_FORMAT","TIME_TO_SEC","TO_BASE64","TO_CHAR","TO_DAYS","TO_SECONDS","UCASE","UNCOMPRESS","UNCOMPRESSED_LENGTH","UNHEX","UNIX_TIMESTAMP","UPDATEXML","UPPER","UUID","UUID_SHORT","VERSION","WEEKDAY","WEEKOFYEAR","WSREP_LAST_WRITTEN_GTID","WSREP_LAST_SEEN_GTID","WSREP_SYNC_WAIT_UPTO_GTID","YEARWEEK","COALESCE","NULLIF"],MG=j(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),vG=j(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","PARTITION BY","ORDER BY","LIMIT","OFFSET","FETCH {FIRST | NEXT}","INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO]","REPLACE [LOW_PRIORITY | DELAYED] [INTO]","VALUES","ON DUPLICATE KEY UPDATE","SET","RETURNING"]),pf=j(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),Hl=j(["CREATE [OR REPLACE] [SQL SECURITY DEFINER | SQL SECURITY INVOKER] VIEW [IF NOT EXISTS]","UPDATE [LOW_PRIORITY] [IGNORE]","DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM","DROP [TEMPORARY] TABLE [IF EXISTS]","ALTER [ONLINE] [IGNORE] TABLE [IF EXISTS]","ADD [COLUMN] [IF NOT EXISTS]","{CHANGE | MODIFY} [COLUMN] [IF EXISTS]","DROP [COLUMN] [IF EXISTS]","RENAME [TO]","RENAME COLUMN","ALTER [COLUMN]","{SET | DROP} DEFAULT","SET {VISIBLE | INVISIBLE}","TRUNCATE [TABLE]","ALTER DATABASE","ALTER DATABASE COMMENT","ALTER EVENT","ALTER FUNCTION","ALTER PROCEDURE","ALTER SCHEMA","ALTER SCHEMA COMMENT","ALTER SEQUENCE","ALTER SERVER","ALTER USER","ALTER VIEW","ANALYZE","ANALYZE TABLE","BACKUP LOCK","BACKUP STAGE","BACKUP UNLOCK","BEGIN","BINLOG","CACHE INDEX","CALL","CHANGE MASTER TO","CHECK TABLE","CHECK VIEW","CHECKSUM TABLE","COMMIT","CREATE AGGREGATE FUNCTION","CREATE DATABASE","CREATE EVENT","CREATE FUNCTION","CREATE INDEX","CREATE PROCEDURE","CREATE ROLE","CREATE SEQUENCE","CREATE SERVER","CREATE SPATIAL INDEX","CREATE TRIGGER","CREATE UNIQUE INDEX","CREATE USER","DEALLOCATE PREPARE","DESCRIBE","DROP DATABASE","DROP EVENT","DROP FUNCTION","DROP INDEX","DROP PREPARE","DROP PROCEDURE","DROP ROLE","DROP SEQUENCE","DROP SERVER","DROP TRIGGER","DROP USER","DROP VIEW","EXECUTE","EXPLAIN","FLUSH","GET DIAGNOSTICS","GET DIAGNOSTICS CONDITION","GRANT","HANDLER","HELP","INSTALL PLUGIN","INSTALL SONAME","KILL","LOAD DATA INFILE","LOAD INDEX INTO CACHE","LOAD XML INFILE","LOCK TABLE","OPTIMIZE TABLE","PREPARE","PURGE BINARY LOGS","PURGE MASTER LOGS","RELEASE SAVEPOINT","RENAME TABLE","RENAME USER","REPAIR TABLE","REPAIR VIEW","RESET MASTER","RESET QUERY CACHE","RESET REPLICA","RESET SLAVE","RESIGNAL","REVOKE","ROLLBACK","SAVEPOINT","SET CHARACTER SET","SET DEFAULT ROLE","SET GLOBAL TRANSACTION","SET NAMES","SET PASSWORD","SET ROLE","SET STATEMENT","SET TRANSACTION","SHOW","SHOW ALL REPLICAS STATUS","SHOW ALL SLAVES STATUS","SHOW AUTHORS","SHOW BINARY LOGS","SHOW BINLOG EVENTS","SHOW BINLOG STATUS","SHOW CHARACTER SET","SHOW CLIENT_STATISTICS","SHOW COLLATION","SHOW COLUMNS","SHOW CONTRIBUTORS","SHOW CREATE DATABASE","SHOW CREATE EVENT","SHOW CREATE FUNCTION","SHOW CREATE PACKAGE","SHOW CREATE PACKAGE BODY","SHOW CREATE PROCEDURE","SHOW CREATE SEQUENCE","SHOW CREATE TABLE","SHOW CREATE TRIGGER","SHOW CREATE USER","SHOW CREATE VIEW","SHOW DATABASES","SHOW ENGINE","SHOW ENGINE INNODB STATUS","SHOW ENGINES","SHOW ERRORS","SHOW EVENTS","SHOW EXPLAIN","SHOW FUNCTION CODE","SHOW FUNCTION STATUS","SHOW GRANTS","SHOW INDEX","SHOW INDEXES","SHOW INDEX_STATISTICS","SHOW KEYS","SHOW LOCALES","SHOW MASTER LOGS","SHOW MASTER STATUS","SHOW OPEN TABLES","SHOW PACKAGE BODY CODE","SHOW PACKAGE BODY STATUS","SHOW PACKAGE STATUS","SHOW PLUGINS","SHOW PLUGINS SONAME","SHOW PRIVILEGES","SHOW PROCEDURE CODE","SHOW PROCEDURE STATUS","SHOW PROCESSLIST","SHOW PROFILE","SHOW PROFILES","SHOW QUERY_RESPONSE_TIME","SHOW RELAYLOG EVENTS","SHOW REPLICA","SHOW REPLICA HOSTS","SHOW REPLICA STATUS","SHOW SCHEMAS","SHOW SLAVE","SHOW SLAVE HOSTS","SHOW SLAVE STATUS","SHOW STATUS","SHOW STORAGE ENGINES","SHOW TABLE STATUS","SHOW TABLES","SHOW TRIGGERS","SHOW USER_STATISTICS","SHOW VARIABLES","SHOW WARNINGS","SHOW WSREP_MEMBERSHIP","SHOW WSREP_STATUS","SHUTDOWN","SIGNAL","START ALL REPLICAS","START ALL SLAVES","START REPLICA","START SLAVE","START TRANSACTION","STOP ALL REPLICAS","STOP ALL SLAVES","STOP REPLICA","STOP SLAVE","UNINSTALL PLUGIN","UNINSTALL SONAME","UNLOCK TABLE","USE","XA BEGIN","XA COMMIT","XA END","XA PREPARE","XA RECOVER","XA ROLLBACK","XA START"]),PG=j(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]","MINUS [ALL | DISTINCT]"]),wG=j(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),UG=j(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),BG=j([]),FG={name:"mariadb",tokenizerOptions:{reservedSelect:MG,reservedClauses:[...vG,...pf,...Hl],reservedSetOperations:PG,reservedJoins:wG,reservedKeywordPhrases:UG,reservedDataTypePhrases:BG,supportsXor:!0,reservedKeywords:_G,reservedDataTypes:bG,reservedFunctionNames:DG,stringTypes:['""-qq-bs',"''-qq-bs",{quote:"''-raw",prefixes:["B","X"],requirePrefix:!0}],identTypes:["``"],identChars:{first:"$",rest:"$",allowFirstCharNumber:!0},variableTypes:[{regex:"@@?[A-Za-z0-9_.$]+"},{quote:'""-qq-bs',prefixes:["@"],requirePrefix:!0},{quote:"''-qq-bs",prefixes:["@"],requirePrefix:!0},{quote:"``",prefixes:["@"],requirePrefix:!0}],paramTypes:{positional:!0},lineCommentTypes:["--","#"],operators:["%",":=","&","|","^","~","<<",">>","<=>","&&","||","!","*.*"],postProcess:_a},formatOptions:{onelineClauses:[...pf,...Hl],tabularOnelineClauses:Hl}},kG=["ACCESSIBLE","ADD","ALL","ALTER","ANALYZE","AND","AS","ASC","ASENSITIVE","BEFORE","BETWEEN","BOTH","BY","CALL","CASCADE","CASE","CHANGE","CHECK","COLLATE","COLUMN","CONDITION","CONSTRAINT","CONTINUE","CONVERT","CREATE","CROSS","CUBE","CUME_DIST","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURSOR","DATABASE","DATABASES","DAY_HOUR","DAY_MICROSECOND","DAY_MINUTE","DAY_SECOND","DECLARE","DEFAULT","DELAYED","DELETE","DENSE_RANK","DESC","DESCRIBE","DETERMINISTIC","DISTINCT","DISTINCTROW","DIV","DROP","DUAL","EACH","ELSE","ELSEIF","EMPTY","ENCLOSED","ESCAPED","EXCEPT","EXISTS","EXIT","EXPLAIN","FALSE","FETCH","FIRST_VALUE","FOR","FORCE","FOREIGN","FROM","FULLTEXT","FUNCTION","GENERATED","GET","GRANT","GROUP","GROUPING","GROUPS","HAVING","HIGH_PRIORITY","HOUR_MICROSECOND","HOUR_MINUTE","HOUR_SECOND","IF","IGNORE","IN","INDEX","INFILE","INNER","INOUT","INSENSITIVE","INSERT","IN","INTERSECT","INTERVAL","INTO","IO_AFTER_GTIDS","IO_BEFORE_GTIDS","IS","ITERATE","JOIN","JSON_TABLE","KEY","KEYS","KILL","LAG","LAST_VALUE","LATERAL","LEAD","LEADING","LEAVE","LEFT","LIKE","LIMIT","LINEAR","LINES","LOAD","LOCALTIME","LOCALTIMESTAMP","LOCK","LONG","LOOP","LOW_PRIORITY","MASTER_BIND","MASTER_SSL_VERIFY_SERVER_CERT","MATCH","MAXVALUE","MINUTE_MICROSECOND","MINUTE_SECOND","MOD","MODIFIES","NATURAL","NOT","NO_WRITE_TO_BINLOG","NTH_VALUE","NTILE","NULL","OF","ON","OPTIMIZE","OPTIMIZER_COSTS","OPTION","OPTIONALLY","OR","ORDER","OUT","OUTER","OUTFILE","OVER","PARTITION","PERCENT_RANK","PRIMARY","PROCEDURE","PURGE","RANGE","RANK","READ","READS","READ_WRITE","RECURSIVE","REFERENCES","REGEXP","RELEASE","RENAME","REPEAT","REPLACE","REQUIRE","RESIGNAL","RESTRICT","RETURN","REVOKE","RIGHT","RLIKE","ROW","ROWS","ROW_NUMBER","SCHEMA","SCHEMAS","SECOND_MICROSECOND","SELECT","SENSITIVE","SEPARATOR","SET","SHOW","SIGNAL","SPATIAL","SPECIFIC","SQL","SQLEXCEPTION","SQLSTATE","SQLWARNING","SQL_BIG_RESULT","SQL_CALC_FOUND_ROWS","SQL_SMALL_RESULT","SSL","STARTING","STORED","STRAIGHT_JOIN","SYSTEM","TABLE","TERMINATED","THEN","TO","TRAILING","TRIGGER","TRUE","UNDO","UNION","UNIQUE","UNLOCK","UNSIGNED","UPDATE","USAGE","USE","USING","UTC_DATE","UTC_TIME","UTC_TIMESTAMP","VALUES","VIRTUAL","WHEN","WHERE","WHILE","WINDOW","WITH","WRITE","XOR","YEAR_MONTH","ZEROFILL"],jG=["BIGINT","BINARY","BIT","BLOB","BOOL","BOOLEAN","CHAR","CHARACTER","DATE","DATETIME","DEC","DECIMAL","DOUBLE PRECISION","DOUBLE","ENUM","FIXED","FLOAT","FLOAT4","FLOAT8","INT","INT1","INT2","INT3","INT4","INT8","INTEGER","LONGBLOB","LONGTEXT","MEDIUMBLOB","MEDIUMINT","MEDIUMTEXT","MIDDLEINT","NATIONAL CHAR","NATIONAL VARCHAR","NUMERIC","PRECISION","REAL","SMALLINT","TEXT","TIME","TIMESTAMP","TINYBLOB","TINYINT","TINYTEXT","VARBINARY","VARCHAR","VARCHARACTER","VARYING","YEAR"],GG=["ABS","ACOS","ADDDATE","ADDTIME","AES_DECRYPT","AES_ENCRYPT","ANY_VALUE","ASCII","ASIN","ATAN","ATAN2","AVG","BENCHMARK","BIN","BIN_TO_UUID","BINARY","BIT_AND","BIT_COUNT","BIT_LENGTH","BIT_OR","BIT_XOR","CAN_ACCESS_COLUMN","CAN_ACCESS_DATABASE","CAN_ACCESS_TABLE","CAN_ACCESS_USER","CAN_ACCESS_VIEW","CAST","CEIL","CEILING","CHAR","CHAR_LENGTH","CHARACTER_LENGTH","CHARSET","COALESCE","COERCIBILITY","COLLATION","COMPRESS","CONCAT","CONCAT_WS","CONNECTION_ID","CONV","CONVERT","CONVERT_TZ","COS","COT","COUNT","CRC32","CUME_DIST","CURDATE","CURRENT_DATE","CURRENT_ROLE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURTIME","DATABASE","DATE","DATE_ADD","DATE_FORMAT","DATE_SUB","DATEDIFF","DAY","DAYNAME","DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","DEFAULT","DEGREES","DENSE_RANK","DIV","ELT","EXP","EXPORT_SET","EXTRACT","EXTRACTVALUE","FIELD","FIND_IN_SET","FIRST_VALUE","FLOOR","FORMAT","FORMAT_BYTES","FORMAT_PICO_TIME","FOUND_ROWS","FROM_BASE64","FROM_DAYS","FROM_UNIXTIME","GEOMCOLLECTION","GEOMETRYCOLLECTION","GET_DD_COLUMN_PRIVILEGES","GET_DD_CREATE_OPTIONS","GET_DD_INDEX_SUB_PART_LENGTH","GET_FORMAT","GET_LOCK","GREATEST","GROUP_CONCAT","GROUPING","GTID_SUBSET","GTID_SUBTRACT","HEX","HOUR","ICU_VERSION","IF","IFNULL","INET_ATON","INET_NTOA","INET6_ATON","INET6_NTOA","INSERT","INSTR","INTERNAL_AUTO_INCREMENT","INTERNAL_AVG_ROW_LENGTH","INTERNAL_CHECK_TIME","INTERNAL_CHECKSUM","INTERNAL_DATA_FREE","INTERNAL_DATA_LENGTH","INTERNAL_DD_CHAR_LENGTH","INTERNAL_GET_COMMENT_OR_ERROR","INTERNAL_GET_ENABLED_ROLE_JSON","INTERNAL_GET_HOSTNAME","INTERNAL_GET_USERNAME","INTERNAL_GET_VIEW_WARNING_OR_ERROR","INTERNAL_INDEX_COLUMN_CARDINALITY","INTERNAL_INDEX_LENGTH","INTERNAL_IS_ENABLED_ROLE","INTERNAL_IS_MANDATORY_ROLE","INTERNAL_KEYS_DISABLED","INTERNAL_MAX_DATA_LENGTH","INTERNAL_TABLE_ROWS","INTERNAL_UPDATE_TIME","INTERVAL","IS","IS_FREE_LOCK","IS_IPV4","IS_IPV4_COMPAT","IS_IPV4_MAPPED","IS_IPV6","IS NOT","IS NOT NULL","IS NULL","IS_USED_LOCK","IS_UUID","ISNULL","JSON_ARRAY","JSON_ARRAY_APPEND","JSON_ARRAY_INSERT","JSON_ARRAYAGG","JSON_CONTAINS","JSON_CONTAINS_PATH","JSON_DEPTH","JSON_EXTRACT","JSON_INSERT","JSON_KEYS","JSON_LENGTH","JSON_MERGE","JSON_MERGE_PATCH","JSON_MERGE_PRESERVE","JSON_OBJECT","JSON_OBJECTAGG","JSON_OVERLAPS","JSON_PRETTY","JSON_QUOTE","JSON_REMOVE","JSON_REPLACE","JSON_SCHEMA_VALID","JSON_SCHEMA_VALIDATION_REPORT","JSON_SEARCH","JSON_SET","JSON_STORAGE_FREE","JSON_STORAGE_SIZE","JSON_TABLE","JSON_TYPE","JSON_UNQUOTE","JSON_VALID","JSON_VALUE","LAG","LAST_DAY","LAST_INSERT_ID","LAST_VALUE","LCASE","LEAD","LEAST","LEFT","LENGTH","LIKE","LINESTRING","LN","LOAD_FILE","LOCALTIME","LOCALTIMESTAMP","LOCATE","LOG","LOG10","LOG2","LOWER","LPAD","LTRIM","MAKE_SET","MAKEDATE","MAKETIME","MASTER_POS_WAIT","MATCH","MAX","MBRCONTAINS","MBRCOVEREDBY","MBRCOVERS","MBRDISJOINT","MBREQUALS","MBRINTERSECTS","MBROVERLAPS","MBRTOUCHES","MBRWITHIN","MD5","MICROSECOND","MID","MIN","MINUTE","MOD","MONTH","MONTHNAME","MULTILINESTRING","MULTIPOINT","MULTIPOLYGON","NAME_CONST","NOW","NTH_VALUE","NTILE","NULLIF","OCT","OCTET_LENGTH","ORD","PERCENT_RANK","PERIOD_ADD","PERIOD_DIFF","PI","POINT","POLYGON","POSITION","POW","POWER","PS_CURRENT_THREAD_ID","PS_THREAD_ID","QUARTER","QUOTE","RADIANS","RAND","RANDOM_BYTES","RANK","REGEXP","REGEXP_INSTR","REGEXP_LIKE","REGEXP_REPLACE","REGEXP_SUBSTR","RELEASE_ALL_LOCKS","RELEASE_LOCK","REPEAT","REPLACE","REVERSE","RIGHT","RLIKE","ROLES_GRAPHML","ROUND","ROW_COUNT","ROW_NUMBER","RPAD","RTRIM","SCHEMA","SEC_TO_TIME","SECOND","SESSION_USER","SHA1","SHA2","SIGN","SIN","SLEEP","SOUNDEX","SOUNDS LIKE","SOURCE_POS_WAIT","SPACE","SQRT","ST_AREA","ST_ASBINARY","ST_ASGEOJSON","ST_ASTEXT","ST_BUFFER","ST_BUFFER_STRATEGY","ST_CENTROID","ST_COLLECT","ST_CONTAINS","ST_CONVEXHULL","ST_CROSSES","ST_DIFFERENCE","ST_DIMENSION","ST_DISJOINT","ST_DISTANCE","ST_DISTANCE_SPHERE","ST_ENDPOINT","ST_ENVELOPE","ST_EQUALS","ST_EXTERIORRING","ST_FRECHETDISTANCE","ST_GEOHASH","ST_GEOMCOLLFROMTEXT","ST_GEOMCOLLFROMWKB","ST_GEOMETRYN","ST_GEOMETRYTYPE","ST_GEOMFROMGEOJSON","ST_GEOMFROMTEXT","ST_GEOMFROMWKB","ST_HAUSDORFFDISTANCE","ST_INTERIORRINGN","ST_INTERSECTION","ST_INTERSECTS","ST_ISCLOSED","ST_ISEMPTY","ST_ISSIMPLE","ST_ISVALID","ST_LATFROMGEOHASH","ST_LATITUDE","ST_LENGTH","ST_LINEFROMTEXT","ST_LINEFROMWKB","ST_LINEINTERPOLATEPOINT","ST_LINEINTERPOLATEPOINTS","ST_LONGFROMGEOHASH","ST_LONGITUDE","ST_MAKEENVELOPE","ST_MLINEFROMTEXT","ST_MLINEFROMWKB","ST_MPOINTFROMTEXT","ST_MPOINTFROMWKB","ST_MPOLYFROMTEXT","ST_MPOLYFROMWKB","ST_NUMGEOMETRIES","ST_NUMINTERIORRING","ST_NUMPOINTS","ST_OVERLAPS","ST_POINTATDISTANCE","ST_POINTFROMGEOHASH","ST_POINTFROMTEXT","ST_POINTFROMWKB","ST_POINTN","ST_POLYFROMTEXT","ST_POLYFROMWKB","ST_SIMPLIFY","ST_SRID","ST_STARTPOINT","ST_SWAPXY","ST_SYMDIFFERENCE","ST_TOUCHES","ST_TRANSFORM","ST_UNION","ST_VALIDATE","ST_WITHIN","ST_X","ST_Y","STATEMENT_DIGEST","STATEMENT_DIGEST_TEXT","STD","STDDEV","STDDEV_POP","STDDEV_SAMP","STR_TO_DATE","STRCMP","SUBDATE","SUBSTR","SUBSTRING","SUBSTRING_INDEX","SUBTIME","SUM","SYSDATE","SYSTEM_USER","TAN","TIME","TIME_FORMAT","TIME_TO_SEC","TIMEDIFF","TIMESTAMP","TIMESTAMPADD","TIMESTAMPDIFF","TO_BASE64","TO_DAYS","TO_SECONDS","TRIM","TRUNCATE","UCASE","UNCOMPRESS","UNCOMPRESSED_LENGTH","UNHEX","UNIX_TIMESTAMP","UPDATEXML","UPPER","UTC_DATE","UTC_TIME","UTC_TIMESTAMP","UUID","UUID_SHORT","UUID_TO_BIN","VALIDATE_PASSWORD_STRENGTH","VALUES","VAR_POP","VAR_SAMP","VARIANCE","VERSION","WAIT_FOR_EXECUTED_GTID_SET","WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS","WEEK","WEEKDAY","WEEKOFYEAR","WEIGHT_STRING","YEAR","YEARWEEK"],HG=j(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),YG=j(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO]","REPLACE [LOW_PRIORITY | DELAYED] [INTO]","VALUES","ON DUPLICATE KEY UPDATE","SET"]),Sf=j(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),Yl=j(["CREATE [OR REPLACE] [SQL SECURITY DEFINER | SQL SECURITY INVOKER] VIEW [IF NOT EXISTS]","UPDATE [LOW_PRIORITY] [IGNORE]","DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM","DROP [TEMPORARY] TABLE [IF EXISTS]","ALTER TABLE","ADD [COLUMN]","{CHANGE | MODIFY} [COLUMN]","DROP [COLUMN]","RENAME [TO | AS]","RENAME COLUMN","ALTER [COLUMN]","{SET | DROP} DEFAULT","TRUNCATE [TABLE]","ALTER DATABASE","ALTER EVENT","ALTER FUNCTION","ALTER INSTANCE","ALTER LOGFILE GROUP","ALTER PROCEDURE","ALTER RESOURCE GROUP","ALTER SERVER","ALTER TABLESPACE","ALTER USER","ALTER VIEW","ANALYZE TABLE","BINLOG","CACHE INDEX","CALL","CHANGE MASTER TO","CHANGE REPLICATION FILTER","CHANGE REPLICATION SOURCE TO","CHECK TABLE","CHECKSUM TABLE","CLONE","COMMIT","CREATE DATABASE","CREATE EVENT","CREATE FUNCTION","CREATE FUNCTION","CREATE INDEX","CREATE LOGFILE GROUP","CREATE PROCEDURE","CREATE RESOURCE GROUP","CREATE ROLE","CREATE SERVER","CREATE SPATIAL REFERENCE SYSTEM","CREATE TABLESPACE","CREATE TRIGGER","CREATE USER","DEALLOCATE PREPARE","DESCRIBE","DROP DATABASE","DROP EVENT","DROP FUNCTION","DROP FUNCTION","DROP INDEX","DROP LOGFILE GROUP","DROP PROCEDURE","DROP RESOURCE GROUP","DROP ROLE","DROP SERVER","DROP SPATIAL REFERENCE SYSTEM","DROP TABLESPACE","DROP TRIGGER","DROP USER","DROP VIEW","EXECUTE","EXPLAIN","FLUSH","GRANT","HANDLER","HELP","IMPORT TABLE","INSTALL COMPONENT","INSTALL PLUGIN","KILL","LOAD DATA","LOAD INDEX INTO CACHE","LOAD XML","LOCK INSTANCE FOR BACKUP","LOCK TABLES","MASTER_POS_WAIT","OPTIMIZE TABLE","PREPARE","PURGE BINARY LOGS","RELEASE SAVEPOINT","RENAME TABLE","RENAME USER","REPAIR TABLE","RESET","RESET MASTER","RESET PERSIST","RESET REPLICA","RESET SLAVE","RESTART","REVOKE","ROLLBACK","ROLLBACK TO SAVEPOINT","SAVEPOINT","SET CHARACTER SET","SET DEFAULT ROLE","SET NAMES","SET PASSWORD","SET RESOURCE GROUP","SET ROLE","SET TRANSACTION","SHOW","SHOW BINARY LOGS","SHOW BINLOG EVENTS","SHOW CHARACTER SET","SHOW COLLATION","SHOW COLUMNS","SHOW CREATE DATABASE","SHOW CREATE EVENT","SHOW CREATE FUNCTION","SHOW CREATE PROCEDURE","SHOW CREATE TABLE","SHOW CREATE TRIGGER","SHOW CREATE USER","SHOW CREATE VIEW","SHOW DATABASES","SHOW ENGINE","SHOW ENGINES","SHOW ERRORS","SHOW EVENTS","SHOW FUNCTION CODE","SHOW FUNCTION STATUS","SHOW GRANTS","SHOW INDEX","SHOW MASTER STATUS","SHOW OPEN TABLES","SHOW PLUGINS","SHOW PRIVILEGES","SHOW PROCEDURE CODE","SHOW PROCEDURE STATUS","SHOW PROCESSLIST","SHOW PROFILE","SHOW PROFILES","SHOW RELAYLOG EVENTS","SHOW REPLICA STATUS","SHOW REPLICAS","SHOW SLAVE","SHOW SLAVE HOSTS","SHOW STATUS","SHOW TABLE STATUS","SHOW TABLES","SHOW TRIGGERS","SHOW VARIABLES","SHOW WARNINGS","SHUTDOWN","SOURCE_POS_WAIT","START GROUP_REPLICATION","START REPLICA","START SLAVE","START TRANSACTION","STOP GROUP_REPLICATION","STOP REPLICA","STOP SLAVE","TABLE","UNINSTALL COMPONENT","UNINSTALL PLUGIN","UNLOCK INSTANCE","UNLOCK TABLES","USE","XA","ITERATE","LEAVE","LOOP","REPEAT","RETURN","WHILE"]),WG=j(["UNION [ALL | DISTINCT]"]),$G=j(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),VG=j(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),XG=j([]),zG={name:"mysql",tokenizerOptions:{reservedSelect:HG,reservedClauses:[...YG,...Sf,...Yl],reservedSetOperations:WG,reservedJoins:$G,reservedKeywordPhrases:VG,reservedDataTypePhrases:XG,supportsXor:!0,reservedKeywords:kG,reservedDataTypes:jG,reservedFunctionNames:GG,stringTypes:['""-qq-bs',{quote:"''-qq-bs",prefixes:["N"]},{quote:"''-raw",prefixes:["B","X"],requirePrefix:!0}],identTypes:["``"],identChars:{first:"$",rest:"$",allowFirstCharNumber:!0},variableTypes:[{regex:"@@?[A-Za-z0-9_.$]+"},{quote:'""-qq-bs',prefixes:["@"],requirePrefix:!0},{quote:"''-qq-bs",prefixes:["@"],requirePrefix:!0},{quote:"``",prefixes:["@"],requirePrefix:!0}],paramTypes:{positional:!0},lineCommentTypes:["--","#"],operators:["%",":=","&","|","^","~","<<",">>","<=>","->","->>","&&","||","!","*.*"],postProcess:_a},formatOptions:{onelineClauses:[...Sf,...Yl],tabularOnelineClauses:Yl}},KG=["ADD","ALL","ALTER","ANALYZE","AND","ARRAY","AS","ASC","BETWEEN","BOTH","BY","CALL","CASCADE","CASE","CHANGE","CHECK","COLLATE","COLUMN","CONSTRAINT","CONTINUE","CONVERT","CREATE","CROSS","CURRENT_DATE","CURRENT_ROLE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURSOR","DATABASE","DATABASES","DAY_HOUR","DAY_MICROSECOND","DAY_MINUTE","DAY_SECOND","DEFAULT","DELAYED","DELETE","DESC","DESCRIBE","DISTINCT","DISTINCTROW","DIV","DOUBLE","DROP","DUAL","ELSE","ELSEIF","ENCLOSED","ESCAPED","EXCEPT","EXISTS","EXIT","EXPLAIN","FALSE","FETCH","FOR","FORCE","FOREIGN","FROM","FULLTEXT","GENERATED","GRANT","GROUP","GROUPS","HAVING","HIGH_PRIORITY","HOUR_MICROSECOND","HOUR_MINUTE","HOUR_SECOND","IF","IGNORE","ILIKE","IN","INDEX","INFILE","INNER","INOUT","INSERT","INTERSECT","INTERVAL","INTO","IS","ITERATE","JOIN","KEY","KEYS","KILL","LEADING","LEAVE","LEFT","LIKE","LIMIT","LINEAR","LINES","LOAD","LOCALTIME","LOCALTIMESTAMP","LOCK","LONG","LOW_PRIORITY","MATCH","MAXVALUE","MINUTE_MICROSECOND","MINUTE_SECOND","MOD","NATURAL","NOT","NO_WRITE_TO_BINLOG","NULL","OF","ON","OPTIMIZE","OPTION","OPTIONALLY","OR","ORDER","OUT","OUTER","OUTFILE","OVER","PARTITION","PRIMARY","PROCEDURE","RANGE","READ","RECURSIVE","REFERENCES","REGEXP","RELEASE","RENAME","REPEAT","REPLACE","REQUIRE","RESTRICT","REVOKE","RIGHT","RLIKE","ROW","ROWS","SECOND_MICROSECOND","SELECT","SET","SHOW","SPATIAL","SQL","SQLEXCEPTION","SQLSTATE","SQLWARNING","SQL_BIG_RESULT","SQL_CALC_FOUND_ROWS","SQL_SMALL_RESULT","SSL","STARTING","STATS_EXTENDED","STORED","STRAIGHT_JOIN","TABLE","TABLESAMPLE","TERMINATED","THEN","TO","TRAILING","TRIGGER","TRUE","TiDB_CURRENT_TSO","UNION","UNIQUE","UNLOCK","UNSIGNED","UNTIL","UPDATE","USAGE","USE","USING","UTC_DATE","UTC_TIME","UTC_TIMESTAMP","VALUES","VIRTUAL","WHEN","WHERE","WHILE","WINDOW","WITH","WRITE","XOR","YEAR_MONTH","ZEROFILL"],qG=["BIGINT","BINARY","BIT","BLOB","BOOL","BOOLEAN","CHAR","CHARACTER","DATE","DATETIME","DEC","DECIMAL","DOUBLE PRECISION","DOUBLE","ENUM","FIXED","INT","INT1","INT2","INT3","INT4","INT8","INTEGER","LONGBLOB","LONGTEXT","MEDIUMBLOB","MEDIUMINT","MIDDLEINT","NATIONAL CHAR","NATIONAL VARCHAR","NUMERIC","PRECISION","SMALLINT","TEXT","TIME","TIMESTAMP","TINYBLOB","TINYINT","TINYTEXT","VARBINARY","VARCHAR","VARCHARACTER","VARYING","YEAR"],JG=["ABS","ACOS","ADDDATE","ADDTIME","AES_DECRYPT","AES_ENCRYPT","ANY_VALUE","ASCII","ASIN","ATAN","ATAN2","AVG","BENCHMARK","BIN","BIN_TO_UUID","BIT_AND","BIT_COUNT","BIT_LENGTH","BIT_OR","BIT_XOR","BITAND","BITNEG","BITOR","BITXOR","CASE","CAST","CEIL","CEILING","CHAR_FUNC","CHAR_LENGTH","CHARACTER_LENGTH","CHARSET","COALESCE","COERCIBILITY","COLLATION","COMPRESS","CONCAT","CONCAT_WS","CONNECTION_ID","CONV","CONVERT","CONVERT_TZ","COS","COT","COUNT","CRC32","CUME_DIST","CURDATE","CURRENT_DATE","CURRENT_RESOURCE_GROUP","CURRENT_ROLE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURTIME","DATABASE","DATE","DATE_ADD","DATE_FORMAT","DATE_SUB","DATEDIFF","DAY","DAYNAME","DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","DECODE","DEFAULT_FUNC","DEGREES","DENSE_RANK","DES_DECRYPT","DES_ENCRYPT","DIV","ELT","ENCODE","ENCRYPT","EQ","EXP","EXPORT_SET","EXTRACT","FIELD","FIND_IN_SET","FIRST_VALUE","FLOOR","FORMAT","FORMAT_BYTES","FORMAT_NANO_TIME","FOUND_ROWS","FROM_BASE64","FROM_DAYS","FROM_UNIXTIME","GE","GET_FORMAT","GET_LOCK","GETPARAM","GREATEST","GROUP_CONCAT","GROUPING","GT","HEX","HOUR","IF","IFNULL","ILIKE","INET6_ATON","INET6_NTOA","INET_ATON","INET_NTOA","INSERT_FUNC","INSTR","INTDIV","INTERVAL","IS_FREE_LOCK","IS_IPV4","IS_IPV4_COMPAT","IS_IPV4_MAPPED","IS_IPV6","IS_USED_LOCK","IS_UUID","ISFALSE","ISNULL","ISTRUE","JSON_ARRAY","JSON_ARRAYAGG","JSON_ARRAY_APPEND","JSON_ARRAY_INSERT","JSON_CONTAINS","JSON_CONTAINS_PATH","JSON_DEPTH","JSON_EXTRACT","JSON_INSERT","JSON_KEYS","JSON_LENGTH","JSON_MEMBEROF","JSON_MERGE","JSON_MERGE_PATCH","JSON_MERGE_PRESERVE","JSON_OBJECT","JSON_OBJECTAGG","JSON_OVERLAPS","JSON_PRETTY","JSON_QUOTE","JSON_REMOVE","JSON_REPLACE","JSON_SEARCH","JSON_SET","JSON_STORAGE_FREE","JSON_STORAGE_SIZE","JSON_TYPE","JSON_UNQUOTE","JSON_VALID","LAG","LAST_DAY","LAST_INSERT_ID","LAST_VALUE","LASTVAL","LCASE","LE","LEAD","LEAST","LEFT","LEFTSHIFT","LENGTH","LIKE","LN","LOAD_FILE","LOCALTIME","LOCALTIMESTAMP","LOCATE","LOG","LOG10","LOG2","LOWER","LPAD","LT","LTRIM","MAKE_SET","MAKEDATE","MAKETIME","MASTER_POS_WAIT","MAX","MD5","MICROSECOND","MID","MIN","MINUS","MINUTE","MOD","MONTH","MONTHNAME","MUL","NAME_CONST","NE","NEXTVAL","NOT","NOW","NTH_VALUE","NTILE","NULLEQ","OCT","OCTET_LENGTH","OLD_PASSWORD","ORD","PASSWORD_FUNC","PERCENT_RANK","PERIOD_ADD","PERIOD_DIFF","PI","PLUS","POSITION","POW","POWER","QUARTER","QUOTE","RADIANS","RAND","RANDOM_BYTES","RANK","REGEXP","REGEXP_INSTR","REGEXP_LIKE","REGEXP_REPLACE","REGEXP_SUBSTR","RELEASE_ALL_LOCKS","RELEASE_LOCK","REPEAT","REPLACE","REVERSE","RIGHT","RIGHTSHIFT","ROUND","ROW_COUNT","ROW_NUMBER","RPAD","RTRIM","SCHEMA","SEC_TO_TIME","SECOND","SESSION_USER","SETVAL","SETVAR","SHA","SHA1","SHA2","SIGN","SIN","SLEEP","SM3","SPACE","SQRT","STD","STDDEV","STDDEV_POP","STDDEV_SAMP","STR_TO_DATE","STRCMP","SUBDATE","SUBSTR","SUBSTRING","SUBSTRING_INDEX","SUBTIME","SUM","SYSDATE","SYSTEM_USER","TAN","TIDB_BOUNDED_STALENESS","TIDB_CURRENT_TSO","TIDB_DECODE_BINARY_PLAN","TIDB_DECODE_KEY","TIDB_DECODE_PLAN","TIDB_DECODE_SQL_DIGESTS","TIDB_ENCODE_SQL_DIGEST","TIDB_IS_DDL_OWNER","TIDB_PARSE_TSO","TIDB_PARSE_TSO_LOGICAL","TIDB_ROW_CHECKSUM","TIDB_SHARD","TIDB_VERSION","TIME","TIME_FORMAT","TIME_TO_SEC","TIMEDIFF","TIMESTAMP","TIMESTAMPADD","TIMESTAMPDIFF","TO_BASE64","TO_DAYS","TO_SECONDS","TRANSLATE","TRIM","TRUNCATE","UCASE","UNARYMINUS","UNCOMPRESS","UNCOMPRESSED_LENGTH","UNHEX","UNIX_TIMESTAMP","UPPER","UTC_DATE","UTC_TIME","UTC_TIMESTAMP","UUID","UUID_SHORT","UUID_TO_BIN","VALIDATE_PASSWORD_STRENGTH","VAR_POP","VAR_SAMP","VARIANCE","VERSION","VITESS_HASH","WEEK","WEEKDAY","WEEKOFYEAR","WEIGHT_STRING","YEAR","YEARWEEK"],QG=j(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),ZG=j(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE] [INTO]","REPLACE [LOW_PRIORITY | DELAYED] [INTO]","VALUES","ON DUPLICATE KEY UPDATE","SET"]),Rf=j(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),Wl=j(["CREATE [OR REPLACE] [SQL SECURITY DEFINER | SQL SECURITY INVOKER] VIEW [IF NOT EXISTS]","UPDATE [LOW_PRIORITY] [IGNORE]","DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM","DROP [TEMPORARY] TABLE [IF EXISTS]","ALTER TABLE","ADD [COLUMN]","{CHANGE | MODIFY} [COLUMN]","DROP [COLUMN]","RENAME [TO | AS]","RENAME COLUMN","ALTER [COLUMN]","{SET | DROP} DEFAULT","TRUNCATE [TABLE]","ALTER DATABASE","ALTER INSTANCE","ALTER RESOURCE GROUP","ALTER SEQUENCE","ALTER USER","ALTER VIEW","ANALYZE TABLE","CHECK TABLE","CHECKSUM TABLE","COMMIT","CREATE DATABASE","CREATE INDEX","CREATE RESOURCE GROUP","CREATE ROLE","CREATE SEQUENCE","CREATE USER","DEALLOCATE PREPARE","DESCRIBE","DROP DATABASE","DROP INDEX","DROP RESOURCE GROUP","DROP ROLE","DROP TABLESPACE","DROP USER","DROP VIEW","EXPLAIN","FLUSH","GRANT","IMPORT TABLE","INSTALL COMPONENT","INSTALL PLUGIN","KILL","LOAD DATA","LOCK INSTANCE FOR BACKUP","LOCK TABLES","OPTIMIZE TABLE","PREPARE","RELEASE SAVEPOINT","RENAME TABLE","RENAME USER","REPAIR TABLE","RESET","REVOKE","ROLLBACK","ROLLBACK TO SAVEPOINT","SAVEPOINT","SET CHARACTER SET","SET DEFAULT ROLE","SET NAMES","SET PASSWORD","SET RESOURCE GROUP","SET ROLE","SET TRANSACTION","SHOW","SHOW BINARY LOGS","SHOW BINLOG EVENTS","SHOW CHARACTER SET","SHOW COLLATION","SHOW COLUMNS","SHOW CREATE DATABASE","SHOW CREATE TABLE","SHOW CREATE USER","SHOW CREATE VIEW","SHOW DATABASES","SHOW ENGINE","SHOW ENGINES","SHOW ERRORS","SHOW EVENTS","SHOW GRANTS","SHOW INDEX","SHOW MASTER STATUS","SHOW OPEN TABLES","SHOW PLUGINS","SHOW PRIVILEGES","SHOW PROCESSLIST","SHOW PROFILE","SHOW PROFILES","SHOW STATUS","SHOW TABLE STATUS","SHOW TABLES","SHOW TRIGGERS","SHOW VARIABLES","SHOW WARNINGS","TABLE","UNINSTALL COMPONENT","UNINSTALL PLUGIN","UNLOCK INSTANCE","UNLOCK TABLES","USE"]),eH=j(["UNION [ALL | DISTINCT]"]),tH=j(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),nH=j(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),rH=j([]),oH={name:"tidb",tokenizerOptions:{reservedSelect:QG,reservedClauses:[...ZG,...Rf,...Wl],reservedSetOperations:eH,reservedJoins:tH,reservedKeywordPhrases:nH,reservedDataTypePhrases:rH,supportsXor:!0,reservedKeywords:KG,reservedDataTypes:qG,reservedFunctionNames:JG,stringTypes:['""-qq-bs',{quote:"''-qq-bs",prefixes:["N"]},{quote:"''-raw",prefixes:["B","X"],requirePrefix:!0}],identTypes:["``"],identChars:{first:"$",rest:"$",allowFirstCharNumber:!0},variableTypes:[{regex:"@@?[A-Za-z0-9_.$]+"},{quote:'""-qq-bs',prefixes:["@"],requirePrefix:!0},{quote:"''-qq-bs",prefixes:["@"],requirePrefix:!0},{quote:"``",prefixes:["@"],requirePrefix:!0}],paramTypes:{positional:!0},lineCommentTypes:["--","#"],operators:["%",":=","&","|","^","~","<<",">>","<=>","->","->>","&&","||","!","*.*"],postProcess:_a},formatOptions:{onelineClauses:[...Rf,...Wl],tabularOnelineClauses:Wl}},sH=["ABORT","ABS","ACOS","ADVISOR","ARRAY_AGG","ARRAY_AGG","ARRAY_APPEND","ARRAY_AVG","ARRAY_BINARY_SEARCH","ARRAY_CONCAT","ARRAY_CONTAINS","ARRAY_COUNT","ARRAY_DISTINCT","ARRAY_EXCEPT","ARRAY_FLATTEN","ARRAY_IFNULL","ARRAY_INSERT","ARRAY_INTERSECT","ARRAY_LENGTH","ARRAY_MAX","ARRAY_MIN","ARRAY_MOVE","ARRAY_POSITION","ARRAY_PREPEND","ARRAY_PUT","ARRAY_RANGE","ARRAY_REMOVE","ARRAY_REPEAT","ARRAY_REPLACE","ARRAY_REVERSE","ARRAY_SORT","ARRAY_STAR","ARRAY_SUM","ARRAY_SYMDIFF","ARRAY_SYMDIFF1","ARRAY_SYMDIFFN","ARRAY_UNION","ASIN","ATAN","ATAN2","AVG","BASE64","BASE64_DECODE","BASE64_ENCODE","BITAND ","BITCLEAR ","BITNOT ","BITOR ","BITSET ","BITSHIFT ","BITTEST ","BITXOR ","CEIL","CLOCK_LOCAL","CLOCK_MILLIS","CLOCK_STR","CLOCK_TZ","CLOCK_UTC","COALESCE","CONCAT","CONCAT2","CONTAINS","CONTAINS_TOKEN","CONTAINS_TOKEN_LIKE","CONTAINS_TOKEN_REGEXP","COS","COUNT","COUNT","COUNTN","CUME_DIST","CURL","DATE_ADD_MILLIS","DATE_ADD_STR","DATE_DIFF_MILLIS","DATE_DIFF_STR","DATE_FORMAT_STR","DATE_PART_MILLIS","DATE_PART_STR","DATE_RANGE_MILLIS","DATE_RANGE_STR","DATE_TRUNC_MILLIS","DATE_TRUNC_STR","DECODE","DECODE_JSON","DEGREES","DENSE_RANK","DURATION_TO_STR","ENCODED_SIZE","ENCODE_JSON","EXP","FIRST_VALUE","FLOOR","GREATEST","HAS_TOKEN","IFINF","IFMISSING","IFMISSINGORNULL","IFNAN","IFNANORINF","IFNULL","INITCAP","ISARRAY","ISATOM","ISBITSET","ISBOOLEAN","ISNUMBER","ISOBJECT","ISSTRING","LAG","LAST_VALUE","LEAD","LEAST","LENGTH","LN","LOG","LOWER","LTRIM","MAX","MEAN","MEDIAN","META","MILLIS","MILLIS_TO_LOCAL","MILLIS_TO_STR","MILLIS_TO_TZ","MILLIS_TO_UTC","MILLIS_TO_ZONE_NAME","MIN","MISSINGIF","NANIF","NEGINFIF","NOW_LOCAL","NOW_MILLIS","NOW_STR","NOW_TZ","NOW_UTC","NTH_VALUE","NTILE","NULLIF","NVL","NVL2","OBJECT_ADD","OBJECT_CONCAT","OBJECT_INNER_PAIRS","OBJECT_INNER_VALUES","OBJECT_LENGTH","OBJECT_NAMES","OBJECT_PAIRS","OBJECT_PUT","OBJECT_REMOVE","OBJECT_RENAME","OBJECT_REPLACE","OBJECT_UNWRAP","OBJECT_VALUES","PAIRS","PERCENT_RANK","PI","POLY_LENGTH","POSINFIF","POSITION","POWER","RADIANS","RANDOM","RANK","RATIO_TO_REPORT","REGEXP_CONTAINS","REGEXP_LIKE","REGEXP_MATCHES","REGEXP_POSITION","REGEXP_REPLACE","REGEXP_SPLIT","REGEX_CONTAINS","REGEX_LIKE","REGEX_MATCHES","REGEX_POSITION","REGEX_REPLACE","REGEX_SPLIT","REPEAT","REPLACE","REVERSE","ROUND","ROW_NUMBER","RTRIM","SEARCH","SEARCH_META","SEARCH_SCORE","SIGN","SIN","SPLIT","SQRT","STDDEV","STDDEV_POP","STDDEV_SAMP","STR_TO_DURATION","STR_TO_MILLIS","STR_TO_TZ","STR_TO_UTC","STR_TO_ZONE_NAME","SUBSTR","SUFFIXES","SUM","TAN","TITLE","TOARRAY","TOATOM","TOBOOLEAN","TOKENS","TOKENS","TONUMBER","TOOBJECT","TOSTRING","TRIM","TRUNC","UPPER","UUID","VARIANCE","VARIANCE_POP","VARIANCE_SAMP","VAR_POP","VAR_SAMP","WEEKDAY_MILLIS","WEEKDAY_STR","CAST"],iH=["ADVISE","ALL","ALTER","ANALYZE","AND","ANY","ARRAY","AS","ASC","AT","BEGIN","BETWEEN","BINARY","BOOLEAN","BREAK","BUCKET","BUILD","BY","CALL","CASE","CAST","CLUSTER","COLLATE","COLLECTION","COMMIT","COMMITTED","CONNECT","CONTINUE","CORRELATED","COVER","CREATE","CURRENT","DATABASE","DATASET","DATASTORE","DECLARE","DECREMENT","DELETE","DERIVED","DESC","DESCRIBE","DISTINCT","DO","DROP","EACH","ELEMENT","ELSE","END","EVERY","EXCEPT","EXCLUDE","EXECUTE","EXISTS","EXPLAIN","FALSE","FETCH","FILTER","FIRST","FLATTEN","FLUSH","FOLLOWING","FOR","FORCE","FROM","FTS","FUNCTION","GOLANG","GRANT","GROUP","GROUPS","GSI","HASH","HAVING","IF","IGNORE","ILIKE","IN","INCLUDE","INCREMENT","INDEX","INFER","INLINE","INNER","INSERT","INTERSECT","INTO","IS","ISOLATION","JAVASCRIPT","JOIN","KEY","KEYS","KEYSPACE","KNOWN","LANGUAGE","LAST","LEFT","LET","LETTING","LEVEL","LIKE","LIMIT","LSM","MAP","MAPPING","MATCHED","MATERIALIZED","MERGE","MINUS","MISSING","NAMESPACE","NEST","NL","NO","NOT","NTH_VALUE","NULL","NULLS","NUMBER","OBJECT","OFFSET","ON","OPTION","OPTIONS","OR","ORDER","OTHERS","OUTER","OVER","PARSE","PARTITION","PASSWORD","PATH","POOL","PRECEDING","PREPARE","PRIMARY","PRIVATE","PRIVILEGE","PROBE","PROCEDURE","PUBLIC","RANGE","RAW","REALM","REDUCE","RENAME","RESPECT","RETURN","RETURNING","REVOKE","RIGHT","ROLE","ROLLBACK","ROW","ROWS","SATISFIES","SAVEPOINT","SCHEMA","SCOPE","SELECT","SELF","SEMI","SET","SHOW","SOME","START","STATISTICS","STRING","SYSTEM","THEN","TIES","TO","TRAN","TRANSACTION","TRIGGER","TRUE","TRUNCATE","UNBOUNDED","UNDER","UNION","UNIQUE","UNKNOWN","UNNEST","UNSET","UPDATE","UPSERT","USE","USER","USING","VALIDATE","VALUE","VALUED","VALUES","VIA","VIEW","WHEN","WHERE","WHILE","WINDOW","WITH","WITHIN","WORK","XOR"],aH=[],lH=j(["SELECT [ALL | DISTINCT]"]),cH=j(["WITH","FROM","WHERE","GROUP BY","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT INTO","VALUES","SET","MERGE INTO","WHEN [NOT] MATCHED THEN","UPDATE SET","INSERT","NEST","UNNEST","RETURNING"]),hf=j(["UPDATE","DELETE FROM","SET SCHEMA","ADVISE","ALTER INDEX","BEGIN TRANSACTION","BUILD INDEX","COMMIT TRANSACTION","CREATE COLLECTION","CREATE FUNCTION","CREATE INDEX","CREATE PRIMARY INDEX","CREATE SCOPE","DROP COLLECTION","DROP FUNCTION","DROP INDEX","DROP PRIMARY INDEX","DROP SCOPE","EXECUTE","EXECUTE FUNCTION","EXPLAIN","GRANT","INFER","PREPARE","REVOKE","ROLLBACK TRANSACTION","SAVEPOINT","SET TRANSACTION","UPDATE STATISTICS","UPSERT","LET","SET CURRENT SCHEMA","SHOW","USE [PRIMARY] KEYS"]),dH=j(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),EH=j(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","INNER JOIN"]),uH=j(["{ROWS | RANGE | GROUPS} BETWEEN"]),TH=j([]),fH={name:"n1ql",tokenizerOptions:{reservedSelect:lH,reservedClauses:[...cH,...hf],reservedSetOperations:dH,reservedJoins:EH,reservedKeywordPhrases:uH,reservedDataTypePhrases:TH,supportsXor:!0,reservedKeywords:iH,reservedDataTypes:aH,reservedFunctionNames:sH,stringTypes:['""-bs',"''-bs"],identTypes:["``"],extraParens:["[]","{}"],paramTypes:{positional:!0,numbered:["$"],named:["$"]},lineCommentTypes:["#","--"],operators:["%","==",":","||"]},formatOptions:{onelineClauses:hf}},pH=["ADD","AGENT","AGGREGATE","ALL","ALTER","AND","ANY","ARROW","AS","ASC","AT","ATTRIBUTE","AUTHID","AVG","BEGIN","BETWEEN","BLOCK","BODY","BOTH","BOUND","BULK","BY","BYTE","CALL","CALLING","CASCADE","CASE","CHARSET","CHARSETFORM","CHARSETID","CHECK","CLOSE","CLUSTER","CLUSTERS","COLAUTH","COLLECT","COLUMNS","COMMENT","COMMIT","COMMITTED","COMPILED","COMPRESS","CONNECT","CONSTANT","CONSTRUCTOR","CONTEXT","CONVERT","COUNT","CRASH","CREATE","CURRENT","CURSOR","CUSTOMDATUM","DANGLING","DATA","DAY","DECLARE","DEFAULT","DEFINE","DELETE","DESC","DETERMINISTIC","DISTINCT","DROP","DURATION","ELEMENT","ELSE","ELSIF","EMPTY","END","ESCAPE","EXCEPT","EXCEPTION","EXCEPTIONS","EXCLUSIVE","EXECUTE","EXISTS","EXIT","EXTERNAL","FETCH","FINAL","FIXED","FOR","FORALL","FORCE","FORM","FROM","FUNCTION","GENERAL","GOTO","GRANT","GROUP","HASH","HAVING","HEAP","HIDDEN","HOUR","IDENTIFIED","IF","IMMEDIATE","IN","INCLUDING","INDEX","INDEXES","INDICATOR","INDICES","INFINITE","INSERT","INSTANTIABLE","INTERFACE","INTERSECT","INTERVAL","INTO","INVALIDATE","IS","ISOLATION","JAVA","LANGUAGE","LARGE","LEADING","LENGTH","LEVEL","LIBRARY","LIKE","LIKE2","LIKE4","LIKEC","LIMIT","LIMITED","LOCAL","LOCK","LOOP","MAP","MAX","MAXLEN","MEMBER","MERGE","MIN","MINUS","MINUTE","MOD","MODE","MODIFY","MONTH","MULTISET","NAME","NAN","NATIONAL","NATIVE","NEW","NOCOMPRESS","NOCOPY","NOT","NOWAIT","NULL","OBJECT","OCICOLL","OCIDATE","OCIDATETIME","OCIDURATION","OCIINTERVAL","OCILOBLOCATOR","OCINUMBER","OCIRAW","OCIREF","OCIREFCURSOR","OCIROWID","OCISTRING","OCITYPE","OF","ON","ONLY","OPAQUE","OPEN","OPERATOR","OPTION","OR","ORACLE","ORADATA","ORDER","OVERLAPS","ORGANIZATION","ORLANY","ORLVARY","OTHERS","OUT","OVERRIDING","PACKAGE","PARALLEL_ENABLE","PARAMETER","PARAMETERS","PARTITION","PASCAL","PIPE","PIPELINED","PRAGMA","PRIOR","PRIVATE","PROCEDURE","PUBLIC","RAISE","RANGE","READ","RECORD","REF","REFERENCE","REM","REMAINDER","RENAME","RESOURCE","RESULT","RETURN","RETURNING","REVERSE","REVOKE","ROLLBACK","ROW","SAMPLE","SAVE","SAVEPOINT","SB1","SB2","SB4","SECOND","SEGMENT","SELECT","SELF","SEPARATE","SEQUENCE","SERIALIZABLE","SET","SHARE","SHORT","SIZE","SIZE_T","SOME","SPARSE","SQL","SQLCODE","SQLDATA","SQLNAME","SQLSTATE","STANDARD","START","STATIC","STDDEV","STORED","STRING","STRUCT","STYLE","SUBMULTISET","SUBPARTITION","SUBSTITUTABLE","SUBTYPE","SUM","SYNONYM","TABAUTH","TABLE","TDO","THE","THEN","TIME","TIMEZONE_ABBR","TIMEZONE_HOUR","TIMEZONE_MINUTE","TIMEZONE_REGION","TO","TRAILING","TRANSAC","TRANSACTIONAL","TRUSTED","TYPE","UB1","UB2","UB4","UNDER","UNION","UNIQUE","UNSIGNED","UNTRUSTED","UPDATE","USE","USING","VALIST","VALUE","VALUES","VARIABLE","VARIANCE","VARRAY","VIEW","VIEWS","VOID","WHEN","WHERE","WHILE","WITH","WORK","WRAPPED","WRITE","YEAR","ZONE"],SH=["ARRAY","BFILE_BASE","BINARY","BLOB_BASE","CHAR VARYING","CHAR_BASE","CHAR","CHARACTER VARYING","CHARACTER","CLOB_BASE","DATE_BASE","DATE","DECIMAL","DOUBLE","FLOAT","INT","INTERVAL DAY","INTERVAL YEAR","LONG","NATIONAL CHAR VARYING","NATIONAL CHAR","NATIONAL CHARACTER VARYING","NATIONAL CHARACTER","NCHAR VARYING","NCHAR","NCHAR","NUMBER_BASE","NUMBER","NUMBERIC","NVARCHAR","PRECISION","RAW","TIMESTAMP","UROWID","VARCHAR","VARCHAR2"],RH=["ABS","ACOS","ASIN","ATAN","ATAN2","BITAND","CEIL","COS","COSH","EXP","FLOOR","LN","LOG","MOD","NANVL","POWER","REMAINDER","ROUND","SIGN","SIN","SINH","SQRT","TAN","TANH","TRUNC","WIDTH_BUCKET","CHR","CONCAT","INITCAP","LOWER","LPAD","LTRIM","NLS_INITCAP","NLS_LOWER","NLSSORT","NLS_UPPER","REGEXP_REPLACE","REGEXP_SUBSTR","REPLACE","RPAD","RTRIM","SOUNDEX","SUBSTR","TRANSLATE","TREAT","TRIM","UPPER","NLS_CHARSET_DECL_LEN","NLS_CHARSET_ID","NLS_CHARSET_NAME","ASCII","INSTR","LENGTH","REGEXP_INSTR","ADD_MONTHS","CURRENT_DATE","CURRENT_TIMESTAMP","DBTIMEZONE","EXTRACT","FROM_TZ","LAST_DAY","LOCALTIMESTAMP","MONTHS_BETWEEN","NEW_TIME","NEXT_DAY","NUMTODSINTERVAL","NUMTOYMINTERVAL","ROUND","SESSIONTIMEZONE","SYS_EXTRACT_UTC","SYSDATE","SYSTIMESTAMP","TO_CHAR","TO_TIMESTAMP","TO_TIMESTAMP_TZ","TO_DSINTERVAL","TO_YMINTERVAL","TRUNC","TZ_OFFSET","GREATEST","LEAST","ASCIISTR","BIN_TO_NUM","CAST","CHARTOROWID","COMPOSE","CONVERT","DECOMPOSE","HEXTORAW","NUMTODSINTERVAL","NUMTOYMINTERVAL","RAWTOHEX","RAWTONHEX","ROWIDTOCHAR","ROWIDTONCHAR","SCN_TO_TIMESTAMP","TIMESTAMP_TO_SCN","TO_BINARY_DOUBLE","TO_BINARY_FLOAT","TO_CHAR","TO_CLOB","TO_DATE","TO_DSINTERVAL","TO_LOB","TO_MULTI_BYTE","TO_NCHAR","TO_NCLOB","TO_NUMBER","TO_DSINTERVAL","TO_SINGLE_BYTE","TO_TIMESTAMP","TO_TIMESTAMP_TZ","TO_YMINTERVAL","TO_YMINTERVAL","TRANSLATE","UNISTR","BFILENAME","EMPTY_BLOB,","EMPTY_CLOB","CARDINALITY","COLLECT","POWERMULTISET","POWERMULTISET_BY_CARDINALITY","SET","SYS_CONNECT_BY_PATH","CLUSTER_ID","CLUSTER_PROBABILITY","CLUSTER_SET","FEATURE_ID","FEATURE_SET","FEATURE_VALUE","PREDICTION","PREDICTION_COST","PREDICTION_DETAILS","PREDICTION_PROBABILITY","PREDICTION_SET","APPENDCHILDXML","DELETEXML","DEPTH","EXTRACT","EXISTSNODE","EXTRACTVALUE","INSERTCHILDXML","INSERTXMLBEFORE","PATH","SYS_DBURIGEN","SYS_XMLAGG","SYS_XMLGEN","UPDATEXML","XMLAGG","XMLCDATA","XMLCOLATTVAL","XMLCOMMENT","XMLCONCAT","XMLFOREST","XMLPARSE","XMLPI","XMLQUERY","XMLROOT","XMLSEQUENCE","XMLSERIALIZE","XMLTABLE","XMLTRANSFORM","DECODE","DUMP","ORA_HASH","VSIZE","COALESCE","LNNVL","NULLIF","NVL","NVL2","SYS_CONTEXT","SYS_GUID","SYS_TYPEID","UID","USER","USERENV","AVG","COLLECT","CORR","CORR_S","CORR_K","COUNT","COVAR_POP","COVAR_SAMP","CUME_DIST","DENSE_RANK","FIRST","GROUP_ID","GROUPING","GROUPING_ID","LAST","MAX","MEDIAN","MIN","PERCENTILE_CONT","PERCENTILE_DISC","PERCENT_RANK","RANK","REGR_SLOPE","REGR_INTERCEPT","REGR_COUNT","REGR_R2","REGR_AVGX","REGR_AVGY","REGR_SXX","REGR_SYY","REGR_SXY","STATS_BINOMIAL_TEST","STATS_CROSSTAB","STATS_F_TEST","STATS_KS_TEST","STATS_MODE","STATS_MW_TEST","STATS_ONE_WAY_ANOVA","STATS_T_TEST_ONE","STATS_T_TEST_PAIRED","STATS_T_TEST_INDEP","STATS_T_TEST_INDEPU","STATS_WSR_TEST","STDDEV","STDDEV_POP","STDDEV_SAMP","SUM","VAR_POP","VAR_SAMP","VARIANCE","FIRST_VALUE","LAG","LAST_VALUE","LEAD","NTILE","RATIO_TO_REPORT","ROW_NUMBER","DEREF","MAKE_REF","REF","REFTOHEX","VALUE","CV","ITERATION_NUMBER","PRESENTNNV","PRESENTV","PREVIOUS"],hH=j(["SELECT [ALL | DISTINCT | UNIQUE]"]),AH=j(["WITH","FROM","WHERE","GROUP BY","HAVING","PARTITION BY","ORDER [SIBLINGS] BY","OFFSET","FETCH {FIRST | NEXT}","FOR UPDATE [OF]","INSERT [INTO | ALL INTO]","VALUES","SET","MERGE [INTO]","WHEN [NOT] MATCHED [THEN]","UPDATE SET","RETURNING"]),Af=j(["CREATE [GLOBAL TEMPORARY | PRIVATE TEMPORARY | SHARDED | DUPLICATED | IMMUTABLE BLOCKCHAIN | BLOCKCHAIN | IMMUTABLE] TABLE"]),$l=j(["CREATE [OR REPLACE] [NO FORCE | FORCE] [EDITIONING | EDITIONABLE | EDITIONABLE EDITIONING | NONEDITIONABLE] VIEW","CREATE MATERIALIZED VIEW","UPDATE [ONLY]","DELETE FROM [ONLY]","DROP TABLE","ALTER TABLE","ADD","DROP {COLUMN | UNUSED COLUMNS | COLUMNS CONTINUE}","MODIFY","RENAME TO","RENAME COLUMN","TRUNCATE TABLE","SET SCHEMA","BEGIN","CONNECT BY","DECLARE","EXCEPT","EXCEPTION","LOOP","START WITH"]),IH=j(["UNION [ALL]","MINUS","INTERSECT"]),mH=j(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | OUTER} APPLY"]),OH=j(["ON {UPDATE | DELETE} [SET NULL]","ON COMMIT","{ROWS | RANGE} BETWEEN"]),NH=j([]),gH={name:"plsql",tokenizerOptions:{reservedSelect:hH,reservedClauses:[...AH,...Af,...$l],reservedSetOperations:IH,reservedJoins:mH,reservedKeywordPhrases:OH,reservedDataTypePhrases:NH,supportsXor:!0,reservedKeywords:pH,reservedDataTypes:SH,reservedFunctionNames:RH,stringTypes:[{quote:"''-qq",prefixes:["N"]},{quote:"q''",prefixes:["N"]}],identTypes:['""-qq'],identChars:{rest:"$#"},variableTypes:[{regex:"&{1,2}[A-Za-z][A-Za-z0-9_$#]*"}],paramTypes:{numbered:[":"],named:[":"]},operators:["**",":=","%","~=","^=",">>","<<","=>","@","||"],postProcess:xH},formatOptions:{alwaysDenseOperators:["@"],onelineClauses:[...Af,...$l],tabularOnelineClauses:$l}};function xH(e){let t=hn;return e.map(n=>An.SET(n)&&An.BY(t)?Object.assign(Object.assign({},n),{type:K.RESERVED_KEYWORD}):(BI(n.type)&&(t=n),n))}const yH=["ABS","ACOS","ACOSD","ACOSH","ASIN","ASIND","ASINH","ATAN","ATAN2","ATAN2D","ATAND","ATANH","CBRT","CEIL","CEILING","COS","COSD","COSH","COT","COTD","DEGREES","DIV","EXP","FACTORIAL","FLOOR","GCD","LCM","LN","LOG","LOG10","MIN_SCALE","MOD","PI","POWER","RADIANS","RANDOM","ROUND","SCALE","SETSEED","SIGN","SIN","SIND","SINH","SQRT","TAN","TAND","TANH","TRIM_SCALE","TRUNC","WIDTH_BUCKET","ABS","ASCII","BIT_LENGTH","BTRIM","CHARACTER_LENGTH","CHAR_LENGTH","CHR","CONCAT","CONCAT_WS","FORMAT","INITCAP","LEFT","LENGTH","LOWER","LPAD","LTRIM","MD5","NORMALIZE","OCTET_LENGTH","OVERLAY","PARSE_IDENT","PG_CLIENT_ENCODING","POSITION","QUOTE_IDENT","QUOTE_LITERAL","QUOTE_NULLABLE","REGEXP_MATCH","REGEXP_MATCHES","REGEXP_REPLACE","REGEXP_SPLIT_TO_ARRAY","REGEXP_SPLIT_TO_TABLE","REPEAT","REPLACE","REVERSE","RIGHT","RPAD","RTRIM","SPLIT_PART","SPRINTF","STARTS_WITH","STRING_AGG","STRING_TO_ARRAY","STRING_TO_TABLE","STRPOS","SUBSTR","SUBSTRING","TO_ASCII","TO_HEX","TRANSLATE","TRIM","UNISTR","UPPER","BIT_COUNT","BIT_LENGTH","BTRIM","CONVERT","CONVERT_FROM","CONVERT_TO","DECODE","ENCODE","GET_BIT","GET_BYTE","LENGTH","LTRIM","MD5","OCTET_LENGTH","OVERLAY","POSITION","RTRIM","SET_BIT","SET_BYTE","SHA224","SHA256","SHA384","SHA512","STRING_AGG","SUBSTR","SUBSTRING","TRIM","BIT_COUNT","BIT_LENGTH","GET_BIT","LENGTH","OCTET_LENGTH","OVERLAY","POSITION","SET_BIT","SUBSTRING","REGEXP_MATCH","REGEXP_MATCHES","REGEXP_REPLACE","REGEXP_SPLIT_TO_ARRAY","REGEXP_SPLIT_TO_TABLE","TO_CHAR","TO_DATE","TO_NUMBER","TO_TIMESTAMP","CLOCK_TIMESTAMP","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","DATE_BIN","DATE_PART","DATE_TRUNC","EXTRACT","ISFINITE","JUSTIFY_DAYS","JUSTIFY_HOURS","JUSTIFY_INTERVAL","LOCALTIME","LOCALTIMESTAMP","MAKE_DATE","MAKE_INTERVAL","MAKE_TIME","MAKE_TIMESTAMP","MAKE_TIMESTAMPTZ","NOW","PG_SLEEP","PG_SLEEP_FOR","PG_SLEEP_UNTIL","STATEMENT_TIMESTAMP","TIMEOFDAY","TO_TIMESTAMP","TRANSACTION_TIMESTAMP","ENUM_FIRST","ENUM_LAST","ENUM_RANGE","AREA","BOUND_BOX","BOX","CENTER","CIRCLE","DIAGONAL","DIAMETER","HEIGHT","ISCLOSED","ISOPEN","LENGTH","LINE","LSEG","NPOINTS","PATH","PCLOSE","POINT","POLYGON","POPEN","RADIUS","SLOPE","WIDTH","ABBREV","BROADCAST","FAMILY","HOST","HOSTMASK","INET_MERGE","INET_SAME_FAMILY","MACADDR8_SET7BIT","MASKLEN","NETMASK","NETWORK","SET_MASKLEN","TRUNC","ARRAY_TO_TSVECTOR","GET_CURRENT_TS_CONFIG","JSONB_TO_TSVECTOR","JSON_TO_TSVECTOR","LENGTH","NUMNODE","PHRASETO_TSQUERY","PLAINTO_TSQUERY","QUERYTREE","SETWEIGHT","STRIP","TO_TSQUERY","TO_TSVECTOR","TSQUERY_PHRASE","TSVECTOR_TO_ARRAY","TS_DEBUG","TS_DELETE","TS_FILTER","TS_HEADLINE","TS_LEXIZE","TS_PARSE","TS_RANK","TS_RANK_CD","TS_REWRITE","TS_STAT","TS_TOKEN_TYPE","WEBSEARCH_TO_TSQUERY","GEN_RANDOM_UUID","UUIDV4","UUIDV7","UUID_EXTRACT_TIMESTAMP","UUID_EXTRACT_VERSION","CURSOR_TO_XML","CURSOR_TO_XMLSCHEMA","DATABASE_TO_XML","DATABASE_TO_XMLSCHEMA","DATABASE_TO_XML_AND_XMLSCHEMA","NEXTVAL","QUERY_TO_XML","QUERY_TO_XMLSCHEMA","QUERY_TO_XML_AND_XMLSCHEMA","SCHEMA_TO_XML","SCHEMA_TO_XMLSCHEMA","SCHEMA_TO_XML_AND_XMLSCHEMA","STRING","TABLE_TO_XML","TABLE_TO_XMLSCHEMA","TABLE_TO_XML_AND_XMLSCHEMA","XMLAGG","XMLCOMMENT","XMLCONCAT","XMLELEMENT","XMLEXISTS","XMLFOREST","XMLPARSE","XMLPI","XMLROOT","XMLSERIALIZE","XMLTABLE","XML_IS_WELL_FORMED","XML_IS_WELL_FORMED_CONTENT","XML_IS_WELL_FORMED_DOCUMENT","XPATH","XPATH_EXISTS","ARRAY_TO_JSON","JSONB_AGG","JSONB_ARRAY_ELEMENTS","JSONB_ARRAY_ELEMENTS_TEXT","JSONB_ARRAY_LENGTH","JSONB_BUILD_ARRAY","JSONB_BUILD_OBJECT","JSONB_EACH","JSONB_EACH_TEXT","JSONB_EXTRACT_PATH","JSONB_EXTRACT_PATH_TEXT","JSONB_INSERT","JSONB_OBJECT","JSONB_OBJECT_AGG","JSONB_OBJECT_KEYS","JSONB_PATH_EXISTS","JSONB_PATH_EXISTS_TZ","JSONB_PATH_MATCH","JSONB_PATH_MATCH_TZ","JSONB_PATH_QUERY","JSONB_PATH_QUERY_ARRAY","JSONB_PATH_QUERY_ARRAY_TZ","JSONB_PATH_QUERY_FIRST","JSONB_PATH_QUERY_FIRST_TZ","JSONB_PATH_QUERY_TZ","JSONB_POPULATE_RECORD","JSONB_POPULATE_RECORDSET","JSONB_PRETTY","JSONB_SET","JSONB_SET_LAX","JSONB_STRIP_NULLS","JSONB_TO_RECORD","JSONB_TO_RECORDSET","JSONB_TYPEOF","JSON_AGG","JSON_ARRAY_ELEMENTS","JSON_ARRAY_ELEMENTS_TEXT","JSON_ARRAY_LENGTH","JSON_BUILD_ARRAY","JSON_BUILD_OBJECT","JSON_EACH","JSON_EACH_TEXT","JSON_EXTRACT_PATH","JSON_EXTRACT_PATH_TEXT","JSON_OBJECT","JSON_OBJECT_AGG","JSON_OBJECT_KEYS","JSON_POPULATE_RECORD","JSON_POPULATE_RECORDSET","JSON_STRIP_NULLS","JSON_TO_RECORD","JSON_TO_RECORDSET","JSON_TYPEOF","ROW_TO_JSON","TO_JSON","TO_JSONB","TO_TIMESTAMP","CURRVAL","LASTVAL","NEXTVAL","SETVAL","COALESCE","GREATEST","LEAST","NULLIF","ARRAY_AGG","ARRAY_APPEND","ARRAY_CAT","ARRAY_DIMS","ARRAY_FILL","ARRAY_LENGTH","ARRAY_LOWER","ARRAY_NDIMS","ARRAY_POSITION","ARRAY_POSITIONS","ARRAY_PREPEND","ARRAY_REMOVE","ARRAY_REPLACE","ARRAY_TO_STRING","ARRAY_UPPER","CARDINALITY","STRING_TO_ARRAY","TRIM_ARRAY","UNNEST","ISEMPTY","LOWER","LOWER_INC","LOWER_INF","MULTIRANGE","RANGE_MERGE","UPPER","UPPER_INC","UPPER_INF","ARRAY_AGG","AVG","BIT_AND","BIT_OR","BIT_XOR","BOOL_AND","BOOL_OR","COALESCE","CORR","COUNT","COVAR_POP","COVAR_SAMP","CUME_DIST","DENSE_RANK","EVERY","GROUPING","JSONB_AGG","JSONB_OBJECT_AGG","JSON_AGG","JSON_OBJECT_AGG","MAX","MIN","MODE","PERCENTILE_CONT","PERCENTILE_DISC","PERCENT_RANK","RANGE_AGG","RANGE_INTERSECT_AGG","RANK","REGR_AVGX","REGR_AVGY","REGR_COUNT","REGR_INTERCEPT","REGR_R2","REGR_SLOPE","REGR_SXX","REGR_SXY","REGR_SYY","STDDEV","STDDEV_POP","STDDEV_SAMP","STRING_AGG","SUM","TO_JSON","TO_JSONB","VARIANCE","VAR_POP","VAR_SAMP","XMLAGG","CUME_DIST","DENSE_RANK","FIRST_VALUE","LAG","LAST_VALUE","LEAD","NTH_VALUE","NTILE","PERCENT_RANK","RANK","ROW_NUMBER","GENERATE_SERIES","GENERATE_SUBSCRIPTS","ACLDEFAULT","ACLEXPLODE","COL_DESCRIPTION","CURRENT_CATALOG","CURRENT_DATABASE","CURRENT_QUERY","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_SCHEMAS","CURRENT_USER","FORMAT_TYPE","HAS_ANY_COLUMN_PRIVILEGE","HAS_COLUMN_PRIVILEGE","HAS_DATABASE_PRIVILEGE","HAS_FOREIGN_DATA_WRAPPER_PRIVILEGE","HAS_FUNCTION_PRIVILEGE","HAS_LANGUAGE_PRIVILEGE","HAS_SCHEMA_PRIVILEGE","HAS_SEQUENCE_PRIVILEGE","HAS_SERVER_PRIVILEGE","HAS_TABLESPACE_PRIVILEGE","HAS_TABLE_PRIVILEGE","HAS_TYPE_PRIVILEGE","INET_CLIENT_ADDR","INET_CLIENT_PORT","INET_SERVER_ADDR","INET_SERVER_PORT","MAKEACLITEM","OBJ_DESCRIPTION","PG_BACKEND_PID","PG_BLOCKING_PIDS","PG_COLLATION_IS_VISIBLE","PG_CONF_LOAD_TIME","PG_CONTROL_CHECKPOINT","PG_CONTROL_INIT","PG_CONTROL_SYSTEM","PG_CONVERSION_IS_VISIBLE","PG_CURRENT_LOGFILE","PG_CURRENT_SNAPSHOT","PG_CURRENT_XACT_ID","PG_CURRENT_XACT_ID_IF_ASSIGNED","PG_DESCRIBE_OBJECT","PG_FUNCTION_IS_VISIBLE","PG_GET_CATALOG_FOREIGN_KEYS","PG_GET_CONSTRAINTDEF","PG_GET_EXPR","PG_GET_FUNCTIONDEF","PG_GET_FUNCTION_ARGUMENTS","PG_GET_FUNCTION_IDENTITY_ARGUMENTS","PG_GET_FUNCTION_RESULT","PG_GET_INDEXDEF","PG_GET_KEYWORDS","PG_GET_OBJECT_ADDRESS","PG_GET_OWNED_SEQUENCE","PG_GET_RULEDEF","PG_GET_SERIAL_SEQUENCE","PG_GET_STATISTICSOBJDEF","PG_GET_TRIGGERDEF","PG_GET_USERBYID","PG_GET_VIEWDEF","PG_HAS_ROLE","PG_IDENTIFY_OBJECT","PG_IDENTIFY_OBJECT_AS_ADDRESS","PG_INDEXAM_HAS_PROPERTY","PG_INDEX_COLUMN_HAS_PROPERTY","PG_INDEX_HAS_PROPERTY","PG_IS_OTHER_TEMP_SCHEMA","PG_JIT_AVAILABLE","PG_LAST_COMMITTED_XACT","PG_LISTENING_CHANNELS","PG_MY_TEMP_SCHEMA","PG_NOTIFICATION_QUEUE_USAGE","PG_OPCLASS_IS_VISIBLE","PG_OPERATOR_IS_VISIBLE","PG_OPFAMILY_IS_VISIBLE","PG_OPTIONS_TO_TABLE","PG_POSTMASTER_START_TIME","PG_SAFE_SNAPSHOT_BLOCKING_PIDS","PG_SNAPSHOT_XIP","PG_SNAPSHOT_XMAX","PG_SNAPSHOT_XMIN","PG_STATISTICS_OBJ_IS_VISIBLE","PG_TABLESPACE_DATABASES","PG_TABLESPACE_LOCATION","PG_TABLE_IS_VISIBLE","PG_TRIGGER_DEPTH","PG_TS_CONFIG_IS_VISIBLE","PG_TS_DICT_IS_VISIBLE","PG_TS_PARSER_IS_VISIBLE","PG_TS_TEMPLATE_IS_VISIBLE","PG_TYPEOF","PG_TYPE_IS_VISIBLE","PG_VISIBLE_IN_SNAPSHOT","PG_XACT_COMMIT_TIMESTAMP","PG_XACT_COMMIT_TIMESTAMP_ORIGIN","PG_XACT_STATUS","PQSERVERVERSION","ROW_SECURITY_ACTIVE","SESSION_USER","SHOBJ_DESCRIPTION","TO_REGCLASS","TO_REGCOLLATION","TO_REGNAMESPACE","TO_REGOPER","TO_REGOPERATOR","TO_REGPROC","TO_REGPROCEDURE","TO_REGROLE","TO_REGTYPE","TXID_CURRENT","TXID_CURRENT_IF_ASSIGNED","TXID_CURRENT_SNAPSHOT","TXID_SNAPSHOT_XIP","TXID_SNAPSHOT_XMAX","TXID_SNAPSHOT_XMIN","TXID_STATUS","TXID_VISIBLE_IN_SNAPSHOT","USER","VERSION","BRIN_DESUMMARIZE_RANGE","BRIN_SUMMARIZE_NEW_VALUES","BRIN_SUMMARIZE_RANGE","CONVERT_FROM","CURRENT_SETTING","GIN_CLEAN_PENDING_LIST","PG_ADVISORY_LOCK","PG_ADVISORY_LOCK_SHARED","PG_ADVISORY_UNLOCK","PG_ADVISORY_UNLOCK_ALL","PG_ADVISORY_UNLOCK_SHARED","PG_ADVISORY_XACT_LOCK","PG_ADVISORY_XACT_LOCK_SHARED","PG_BACKUP_START_TIME","PG_CANCEL_BACKEND","PG_COLLATION_ACTUAL_VERSION","PG_COLUMN_COMPRESSION","PG_COLUMN_SIZE","PG_COPY_LOGICAL_REPLICATION_SLOT","PG_COPY_PHYSICAL_REPLICATION_SLOT","PG_CREATE_LOGICAL_REPLICATION_SLOT","PG_CREATE_PHYSICAL_REPLICATION_SLOT","PG_CREATE_RESTORE_POINT","PG_CURRENT_WAL_FLUSH_LSN","PG_CURRENT_WAL_INSERT_LSN","PG_CURRENT_WAL_LSN","PG_DATABASE_SIZE","PG_DROP_REPLICATION_SLOT","PG_EXPORT_SNAPSHOT","PG_FILENODE_RELATION","PG_GET_WAL_REPLAY_PAUSE_STATE","PG_IMPORT_SYSTEM_COLLATIONS","PG_INDEXES_SIZE","PG_IS_IN_BACKUP","PG_IS_IN_RECOVERY","PG_IS_WAL_REPLAY_PAUSED","PG_LAST_WAL_RECEIVE_LSN","PG_LAST_WAL_REPLAY_LSN","PG_LAST_XACT_REPLAY_TIMESTAMP","PG_LOGICAL_EMIT_MESSAGE","PG_LOGICAL_SLOT_GET_BINARY_CHANGES","PG_LOGICAL_SLOT_GET_CHANGES","PG_LOGICAL_SLOT_PEEK_BINARY_CHANGES","PG_LOGICAL_SLOT_PEEK_CHANGES","PG_LOG_BACKEND_MEMORY_CONTEXTS","PG_LS_ARCHIVE_STATUSDIR","PG_LS_DIR","PG_LS_LOGDIR","PG_LS_TMPDIR","PG_LS_WALDIR","PG_PARTITION_ANCESTORS","PG_PARTITION_ROOT","PG_PARTITION_TREE","PG_PROMOTE","PG_READ_BINARY_FILE","PG_READ_FILE","PG_RELATION_FILENODE","PG_RELATION_FILEPATH","PG_RELATION_SIZE","PG_RELOAD_CONF","PG_REPLICATION_ORIGIN_ADVANCE","PG_REPLICATION_ORIGIN_CREATE","PG_REPLICATION_ORIGIN_DROP","PG_REPLICATION_ORIGIN_OID","PG_REPLICATION_ORIGIN_PROGRESS","PG_REPLICATION_ORIGIN_SESSION_IS_SETUP","PG_REPLICATION_ORIGIN_SESSION_PROGRESS","PG_REPLICATION_ORIGIN_SESSION_RESET","PG_REPLICATION_ORIGIN_SESSION_SETUP","PG_REPLICATION_ORIGIN_XACT_RESET","PG_REPLICATION_ORIGIN_XACT_SETUP","PG_REPLICATION_SLOT_ADVANCE","PG_ROTATE_LOGFILE","PG_SIZE_BYTES","PG_SIZE_PRETTY","PG_START_BACKUP","PG_STAT_FILE","PG_STOP_BACKUP","PG_SWITCH_WAL","PG_TABLESPACE_SIZE","PG_TABLE_SIZE","PG_TERMINATE_BACKEND","PG_TOTAL_RELATION_SIZE","PG_TRY_ADVISORY_LOCK","PG_TRY_ADVISORY_LOCK_SHARED","PG_TRY_ADVISORY_XACT_LOCK","PG_TRY_ADVISORY_XACT_LOCK_SHARED","PG_WALFILE_NAME","PG_WALFILE_NAME_OFFSET","PG_WAL_LSN_DIFF","PG_WAL_REPLAY_PAUSE","PG_WAL_REPLAY_RESUME","SET_CONFIG","SUPPRESS_REDUNDANT_UPDATES_TRIGGER","TSVECTOR_UPDATE_TRIGGER","TSVECTOR_UPDATE_TRIGGER_COLUMN","PG_EVENT_TRIGGER_DDL_COMMANDS","PG_EVENT_TRIGGER_DROPPED_OBJECTS","PG_EVENT_TRIGGER_TABLE_REWRITE_OID","PG_EVENT_TRIGGER_TABLE_REWRITE_REASON","PG_GET_OBJECT_ADDRESS","PG_MCV_LIST_ITEMS","CAST"],CH=["ALL","ANALYSE","ANALYZE","AND","ANY","AS","ASC","ASYMMETRIC","AUTHORIZATION","BETWEEN","BINARY","BOTH","CASE","CAST","CHECK","COLLATE","COLLATION","COLUMN","CONCURRENTLY","CONSTRAINT","CREATE","CROSS","CURRENT_CATALOG","CURRENT_DATE","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","DAY","DEFAULT","DEFERRABLE","DESC","DISTINCT","DO","ELSE","END","EXCEPT","EXISTS","FALSE","FETCH","FILTER","FOR","FOREIGN","FREEZE","FROM","FULL","GRANT","GROUP","HAVING","HOUR","ILIKE","IN","INITIALLY","INNER","INOUT","INTERSECT","INTO","IS","ISNULL","JOIN","LATERAL","LEADING","LEFT","LIKE","LIMIT","LOCALTIME","LOCALTIMESTAMP","MINUTE","MONTH","NATURAL","NOT","NOTNULL","NULL","NULLIF","OFFSET","ON","ONLY","OR","ORDER","OUT","OUTER","OVER","OVERLAPS","PLACING","PRIMARY","REFERENCES","RETURNING","RIGHT","ROW","SECOND","SELECT","SESSION_USER","SIMILAR","SOME","SYMMETRIC","TABLE","TABLESAMPLE","THEN","TO","TRAILING","TRUE","UNION","UNIQUE","USER","USING","VALUES","VARIADIC","VERBOSE","WHEN","WHERE","WINDOW","WITH","WITHIN","WITHOUT","YEAR"],LH=["ARRAY","BIGINT","BIT","BIT VARYING","BOOL","BOOLEAN","CHAR","CHARACTER","CHARACTER VARYING","DECIMAL","DEC","DOUBLE","ENUM","FLOAT","INT","INTEGER","INTERVAL","NCHAR","NUMERIC","JSON","JSONB","PRECISION","REAL","SMALLINT","TEXT","TIME","TIMESTAMP","TIMESTAMPTZ","UUID","VARCHAR","XML","ZONE"],_H=j(["SELECT [ALL | DISTINCT]"]),bH=j(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY [ALL | DISTINCT]","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","FETCH {FIRST | NEXT}","FOR {UPDATE | NO KEY UPDATE | SHARE | KEY SHARE} [OF]","INSERT INTO","VALUES","DEFAULT VALUES","SET","RETURNING"]),If=j(["CREATE [GLOBAL | LOCAL] [TEMPORARY | TEMP | UNLOGGED] TABLE [IF NOT EXISTS]"]),Vl=j(["CREATE [OR REPLACE] [TEMP | TEMPORARY] [RECURSIVE] VIEW","CREATE [MATERIALIZED] VIEW [IF NOT EXISTS]","UPDATE [ONLY]","WHERE CURRENT OF","ON CONFLICT","DELETE FROM [ONLY]","DROP TABLE [IF EXISTS]","ALTER TABLE [IF EXISTS] [ONLY]","ALTER TABLE ALL IN TABLESPACE","RENAME [COLUMN]","RENAME TO","ADD [COLUMN] [IF NOT EXISTS]","DROP [COLUMN] [IF EXISTS]","ALTER [COLUMN]","SET DATA TYPE","{SET | DROP} DEFAULT","{SET | DROP} NOT NULL","TRUNCATE [TABLE] [ONLY]","SET SCHEMA","AFTER","ABORT","ALTER AGGREGATE","ALTER COLLATION","ALTER CONVERSION","ALTER DATABASE","ALTER DEFAULT PRIVILEGES","ALTER DOMAIN","ALTER EVENT TRIGGER","ALTER EXTENSION","ALTER FOREIGN DATA WRAPPER","ALTER FOREIGN TABLE","ALTER FUNCTION","ALTER GROUP","ALTER INDEX","ALTER LANGUAGE","ALTER LARGE OBJECT","ALTER MATERIALIZED VIEW","ALTER OPERATOR","ALTER OPERATOR CLASS","ALTER OPERATOR FAMILY","ALTER POLICY","ALTER PROCEDURE","ALTER PUBLICATION","ALTER ROLE","ALTER ROUTINE","ALTER RULE","ALTER SCHEMA","ALTER SEQUENCE","ALTER SERVER","ALTER STATISTICS","ALTER SUBSCRIPTION","ALTER SYSTEM","ALTER TABLESPACE","ALTER TEXT SEARCH CONFIGURATION","ALTER TEXT SEARCH DICTIONARY","ALTER TEXT SEARCH PARSER","ALTER TEXT SEARCH TEMPLATE","ALTER TRIGGER","ALTER TYPE","ALTER USER","ALTER USER MAPPING","ALTER VIEW","ANALYZE","BEGIN","CALL","CHECKPOINT","CLOSE","CLUSTER","COMMENT ON","COMMIT","COMMIT PREPARED","COPY","CREATE ACCESS METHOD","CREATE [OR REPLACE] AGGREGATE","CREATE CAST","CREATE COLLATION","CREATE [DEFAULT] CONVERSION","CREATE DATABASE","CREATE DOMAIN","CREATE EVENT TRIGGER","CREATE EXTENSION","CREATE FOREIGN DATA WRAPPER","CREATE FOREIGN TABLE","CREATE [OR REPLACE] FUNCTION","CREATE GROUP","CREATE [UNIQUE] INDEX","CREATE [OR REPLACE] [TRUSTED] [PROCEDURAL] LANGUAGE","CREATE OPERATOR","CREATE OPERATOR CLASS","CREATE OPERATOR FAMILY","CREATE POLICY","CREATE [OR REPLACE] PROCEDURE","CREATE PUBLICATION","CREATE ROLE","CREATE [OR REPLACE] RULE","CREATE SCHEMA [AUTHORIZATION]","CREATE [TEMPORARY | TEMP | UNLOGGED] SEQUENCE","CREATE SERVER","CREATE STATISTICS","CREATE SUBSCRIPTION","CREATE TABLESPACE","CREATE TEXT SEARCH CONFIGURATION","CREATE TEXT SEARCH DICTIONARY","CREATE TEXT SEARCH PARSER","CREATE TEXT SEARCH TEMPLATE","CREATE [OR REPLACE] TRANSFORM","CREATE [OR REPLACE] [CONSTRAINT] TRIGGER","CREATE TYPE","CREATE USER","CREATE USER MAPPING","DEALLOCATE","DECLARE","DISCARD","DROP ACCESS METHOD","DROP AGGREGATE","DROP CAST","DROP COLLATION","DROP CONVERSION","DROP DATABASE","DROP DOMAIN","DROP EVENT TRIGGER","DROP EXTENSION","DROP FOREIGN DATA WRAPPER","DROP FOREIGN TABLE","DROP FUNCTION","DROP GROUP","DROP IDENTITY","DROP INDEX","DROP LANGUAGE","DROP MATERIALIZED VIEW [IF EXISTS]","DROP OPERATOR","DROP OPERATOR CLASS","DROP OPERATOR FAMILY","DROP OWNED","DROP POLICY","DROP PROCEDURE","DROP PUBLICATION","DROP ROLE","DROP ROUTINE","DROP RULE","DROP SCHEMA","DROP SEQUENCE","DROP SERVER","DROP STATISTICS","DROP SUBSCRIPTION","DROP TABLESPACE","DROP TEXT SEARCH CONFIGURATION","DROP TEXT SEARCH DICTIONARY","DROP TEXT SEARCH PARSER","DROP TEXT SEARCH TEMPLATE","DROP TRANSFORM","DROP TRIGGER","DROP TYPE","DROP USER","DROP USER MAPPING","DROP VIEW","EXECUTE","EXPLAIN","FETCH","GRANT","IMPORT FOREIGN SCHEMA","LISTEN","LOAD","LOCK","MOVE","NOTIFY","OVERRIDING SYSTEM VALUE","PREPARE","PREPARE TRANSACTION","REASSIGN OWNED","REFRESH MATERIALIZED VIEW","REINDEX","RELEASE SAVEPOINT","RESET [ALL|ROLE|SESSION AUTHORIZATION]","REVOKE","ROLLBACK","ROLLBACK PREPARED","ROLLBACK TO SAVEPOINT","SAVEPOINT","SECURITY LABEL","SELECT INTO","SET CONSTRAINTS","SET ROLE","SET SESSION AUTHORIZATION","SET TRANSACTION","SHOW","START TRANSACTION","UNLISTEN","VACUUM"]),DH=j(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),MH=j(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),vH=j(["PRIMARY KEY","GENERATED {ALWAYS | BY DEFAULT} AS IDENTITY","ON {UPDATE | DELETE} [NO ACTION | RESTRICT | CASCADE | SET NULL | SET DEFAULT]","DO {NOTHING | UPDATE}","AS MATERIALIZED","{ROWS | RANGE | GROUPS} BETWEEN","IS [NOT] DISTINCT FROM","NULLS {FIRST | LAST}","WITH ORDINALITY"]),PH=j(["[TIMESTAMP | TIME] {WITH | WITHOUT} TIME ZONE"]),wH={name:"postgresql",tokenizerOptions:{reservedSelect:_H,reservedClauses:[...bH,...If,...Vl],reservedSetOperations:DH,reservedJoins:MH,reservedKeywordPhrases:vH,reservedDataTypePhrases:PH,reservedKeywords:CH,reservedDataTypes:LH,reservedFunctionNames:yH,nestedBlockComments:!0,extraParens:["[]"],underscoresInNumbers:!0,stringTypes:["$$",{quote:"''-qq",prefixes:["U&"]},{quote:"''-qq-bs",prefixes:["E"],requirePrefix:!0},{quote:"''-raw",prefixes:["B","X"],requirePrefix:!0}],identTypes:[{quote:'""-qq',prefixes:["U&"]}],identChars:{rest:"$"},paramTypes:{numbered:["$"]},operators:["%","^","|/","||/","@",":=","&","|","#","~","<<",">>","~>~","~<~","~>=~","~<=~","@-@","@@","##","<->","&&","&<","&>","<<|","&<|","|>>","|&>","<^","^>","?#","?-","?|","?-|","?||","@>","<@","~=","?","@?","?&","->","->>","#>","#>>","#-","=>",">>=","<<=","~~","~~*","!~~","!~~*","~","~*","!~","!~*","-|-","||","@@@","!!","^@","<%","%>","<<%","%>>","<<->","<->>","<<<->","<->>>","::",":","<#>","<=>","<+>","<~>","<%>"],operatorKeyword:!0},formatOptions:{alwaysDenseOperators:["::",":"],onelineClauses:[...If,...Vl],tabularOnelineClauses:Vl}},UH=["ANY_VALUE","APPROXIMATE PERCENTILE_DISC","AVG","COUNT","LISTAGG","MAX","MEDIAN","MIN","PERCENTILE_CONT","STDDEV_SAMP","STDDEV_POP","SUM","VAR_SAMP","VAR_POP","array_concat","array_flatten","get_array_length","split_to_array","subarray","BIT_AND","BIT_OR","BOOL_AND","BOOL_OR","COALESCE","DECODE","GREATEST","LEAST","NVL","NVL2","NULLIF","ADD_MONTHS","AT TIME ZONE","CONVERT_TIMEZONE","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","DATE_CMP","DATE_CMP_TIMESTAMP","DATE_CMP_TIMESTAMPTZ","DATE_PART_YEAR","DATEADD","DATEDIFF","DATE_PART","DATE_TRUNC","EXTRACT","GETDATE","INTERVAL_CMP","LAST_DAY","MONTHS_BETWEEN","NEXT_DAY","SYSDATE","TIMEOFDAY","TIMESTAMP_CMP","TIMESTAMP_CMP_DATE","TIMESTAMP_CMP_TIMESTAMPTZ","TIMESTAMPTZ_CMP","TIMESTAMPTZ_CMP_DATE","TIMESTAMPTZ_CMP_TIMESTAMP","TIMEZONE","TO_TIMESTAMP","TRUNC","AddBBox","DropBBox","GeometryType","ST_AddPoint","ST_Angle","ST_Area","ST_AsBinary","ST_AsEWKB","ST_AsEWKT","ST_AsGeoJSON","ST_AsText","ST_Azimuth","ST_Boundary","ST_Collect","ST_Contains","ST_ContainsProperly","ST_ConvexHull","ST_CoveredBy","ST_Covers","ST_Crosses","ST_Dimension","ST_Disjoint","ST_Distance","ST_DistanceSphere","ST_DWithin","ST_EndPoint","ST_Envelope","ST_Equals","ST_ExteriorRing","ST_Force2D","ST_Force3D","ST_Force3DM","ST_Force3DZ","ST_Force4D","ST_GeometryN","ST_GeometryType","ST_GeomFromEWKB","ST_GeomFromEWKT","ST_GeomFromText","ST_GeomFromWKB","ST_InteriorRingN","ST_Intersects","ST_IsPolygonCCW","ST_IsPolygonCW","ST_IsClosed","ST_IsCollection","ST_IsEmpty","ST_IsSimple","ST_IsValid","ST_Length","ST_LengthSphere","ST_Length2D","ST_LineFromMultiPoint","ST_LineInterpolatePoint","ST_M","ST_MakeEnvelope","ST_MakeLine","ST_MakePoint","ST_MakePolygon","ST_MemSize","ST_MMax","ST_MMin","ST_Multi","ST_NDims","ST_NPoints","ST_NRings","ST_NumGeometries","ST_NumInteriorRings","ST_NumPoints","ST_Perimeter","ST_Perimeter2D","ST_Point","ST_PointN","ST_Points","ST_Polygon","ST_RemovePoint","ST_Reverse","ST_SetPoint","ST_SetSRID","ST_Simplify","ST_SRID","ST_StartPoint","ST_Touches","ST_Within","ST_X","ST_XMax","ST_XMin","ST_Y","ST_YMax","ST_YMin","ST_Z","ST_ZMax","ST_ZMin","SupportsBBox","CHECKSUM","FUNC_SHA1","FNV_HASH","MD5","SHA","SHA1","SHA2","HLL","HLL_CREATE_SKETCH","HLL_CARDINALITY","HLL_COMBINE","IS_VALID_JSON","IS_VALID_JSON_ARRAY","JSON_ARRAY_LENGTH","JSON_EXTRACT_ARRAY_ELEMENT_TEXT","JSON_EXTRACT_PATH_TEXT","JSON_PARSE","JSON_SERIALIZE","ABS","ACOS","ASIN","ATAN","ATAN2","CBRT","CEILING","CEIL","COS","COT","DEGREES","DEXP","DLOG1","DLOG10","EXP","FLOOR","LN","LOG","MOD","PI","POWER","RADIANS","RANDOM","ROUND","SIN","SIGN","SQRT","TAN","TO_HEX","TRUNC","EXPLAIN_MODEL","ASCII","BPCHARCMP","BTRIM","BTTEXT_PATTERN_CMP","CHAR_LENGTH","CHARACTER_LENGTH","CHARINDEX","CHR","COLLATE","CONCAT","CRC32","DIFFERENCE","INITCAP","LEFT","RIGHT","LEN","LENGTH","LOWER","LPAD","RPAD","LTRIM","OCTETINDEX","OCTET_LENGTH","POSITION","QUOTE_IDENT","QUOTE_LITERAL","REGEXP_COUNT","REGEXP_INSTR","REGEXP_REPLACE","REGEXP_SUBSTR","REPEAT","REPLACE","REPLICATE","REVERSE","RTRIM","SOUNDEX","SPLIT_PART","STRPOS","STRTOL","SUBSTRING","TEXTLEN","TRANSLATE","TRIM","UPPER","decimal_precision","decimal_scale","is_array","is_bigint","is_boolean","is_char","is_decimal","is_float","is_integer","is_object","is_scalar","is_smallint","is_varchar","json_typeof","AVG","COUNT","CUME_DIST","DENSE_RANK","FIRST_VALUE","LAST_VALUE","LAG","LEAD","LISTAGG","MAX","MEDIAN","MIN","NTH_VALUE","NTILE","PERCENT_RANK","PERCENTILE_CONT","PERCENTILE_DISC","RANK","RATIO_TO_REPORT","ROW_NUMBER","STDDEV_SAMP","STDDEV_POP","SUM","VAR_SAMP","VAR_POP","CAST","CONVERT","TO_CHAR","TO_DATE","TO_NUMBER","TEXT_TO_INT_ALT","TEXT_TO_NUMERIC_ALT","CHANGE_QUERY_PRIORITY","CHANGE_SESSION_PRIORITY","CHANGE_USER_PRIORITY","CURRENT_SETTING","PG_CANCEL_BACKEND","PG_TERMINATE_BACKEND","REBOOT_CLUSTER","SET_CONFIG","CURRENT_AWS_ACCOUNT","CURRENT_DATABASE","CURRENT_NAMESPACE","CURRENT_SCHEMA","CURRENT_SCHEMAS","CURRENT_USER","CURRENT_USER_ID","HAS_ASSUMEROLE_PRIVILEGE","HAS_DATABASE_PRIVILEGE","HAS_SCHEMA_PRIVILEGE","HAS_TABLE_PRIVILEGE","PG_BACKEND_PID","PG_GET_COLS","PG_GET_GRANTEE_BY_IAM_ROLE","PG_GET_IAM_ROLE_BY_USER","PG_GET_LATE_BINDING_VIEW_COLS","PG_LAST_COPY_COUNT","PG_LAST_COPY_ID","PG_LAST_UNLOAD_ID","PG_LAST_QUERY_ID","PG_LAST_UNLOAD_COUNT","SESSION_USER","SLICE_NUM","USER","VERSION"],BH=["AES128","AES256","ALL","ALLOWOVERWRITE","ANY","AS","ASC","AUTHORIZATION","BACKUP","BETWEEN","BINARY","BOTH","CHECK","COLUMN","CONSTRAINT","CREATE","CROSS","DEFAULT","DEFERRABLE","DEFLATE","DEFRAG","DESC","DISABLE","DISTINCT","DO","ENABLE","ENCODE","ENCRYPT","ENCRYPTION","EXPLICIT","FALSE","FOR","FOREIGN","FREEZE","FROM","FULL","GLOBALDICT256","GLOBALDICT64K","GROUP","IDENTITY","IGNORE","ILIKE","IN","INITIALLY","INNER","INTO","IS","ISNULL","LANGUAGE","LEADING","LIKE","LIMIT","LOCALTIME","LOCALTIMESTAMP","LUN","LUNS","MINUS","NATURAL","NEW","NOT","NOTNULL","NULL","NULLS","OFF","OFFLINE","OFFSET","OID","OLD","ON","ONLY","OPEN","ORDER","OUTER","OVERLAPS","PARALLEL","PARTITION","PERCENT","PERMISSIONS","PLACING","PRIMARY","RECOVER","REFERENCES","REJECTLOG","RESORT","RESPECT","RESTORE","SIMILAR","SNAPSHOT","SOME","SYSTEM","TABLE","TAG","TDES","THEN","TIMESTAMP","TO","TOP","TRAILING","TRUE","UNIQUE","USING","VERBOSE","WALLET","WITHOUT","ACCEPTANYDATE","ACCEPTINVCHARS","BLANKSASNULL","DATEFORMAT","EMPTYASNULL","ENCODING","ESCAPE","EXPLICIT_IDS","FILLRECORD","IGNOREBLANKLINES","IGNOREHEADER","REMOVEQUOTES","ROUNDEC","TIMEFORMAT","TRIMBLANKS","TRUNCATECOLUMNS","COMPROWS","COMPUPDATE","MAXERROR","NOLOAD","STATUPDATE","FORMAT","CSV","DELIMITER","FIXEDWIDTH","SHAPEFILE","AVRO","JSON","PARQUET","ORC","ACCESS_KEY_ID","CREDENTIALS","ENCRYPTED","IAM_ROLE","MASTER_SYMMETRIC_KEY","SECRET_ACCESS_KEY","SESSION_TOKEN","BZIP2","GZIP","LZOP","ZSTD","MANIFEST","READRATIO","REGION","SSH","RAW","AZ64","BYTEDICT","DELTA","DELTA32K","LZO","MOSTLY8","MOSTLY16","MOSTLY32","RUNLENGTH","TEXT255","TEXT32K","CATALOG_ROLE","SECRET_ARN","EXTERNAL","AUTO","EVEN","KEY","PREDICATE","COMPRESSION"],FH=["ARRAY","BIGINT","BPCHAR","CHAR","CHARACTER VARYING","CHARACTER","DECIMAL","INT","INT2","INT4","INT8","INTEGER","NCHAR","NUMERIC","NVARCHAR","SMALLINT","TEXT","VARBYTE","VARCHAR"],kH=j(["SELECT [ALL | DISTINCT]"]),jH=j(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","QUALIFY","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT INTO","VALUES","SET"]),mf=j(["CREATE [TEMPORARY | TEMP | LOCAL TEMPORARY | LOCAL TEMP] TABLE [IF NOT EXISTS]"]),Xl=j(["CREATE [OR REPLACE | MATERIALIZED] VIEW","UPDATE","DELETE [FROM]","DROP TABLE [IF EXISTS]","ALTER TABLE","ALTER TABLE APPEND","ADD [COLUMN]","DROP [COLUMN]","RENAME TO","RENAME COLUMN","ALTER COLUMN","TYPE","ENCODE","TRUNCATE [TABLE]","ABORT","ALTER DATABASE","ALTER DATASHARE","ALTER DEFAULT PRIVILEGES","ALTER GROUP","ALTER MATERIALIZED VIEW","ALTER PROCEDURE","ALTER SCHEMA","ALTER USER","ANALYSE","ANALYZE","ANALYSE COMPRESSION","ANALYZE COMPRESSION","BEGIN","CALL","CANCEL","CLOSE","COMMIT","COPY","CREATE DATABASE","CREATE DATASHARE","CREATE EXTERNAL FUNCTION","CREATE EXTERNAL SCHEMA","CREATE EXTERNAL TABLE","CREATE FUNCTION","CREATE GROUP","CREATE LIBRARY","CREATE MODEL","CREATE PROCEDURE","CREATE SCHEMA","CREATE USER","DEALLOCATE","DECLARE","DESC DATASHARE","DROP DATABASE","DROP DATASHARE","DROP FUNCTION","DROP GROUP","DROP LIBRARY","DROP MODEL","DROP MATERIALIZED VIEW","DROP PROCEDURE","DROP SCHEMA","DROP USER","DROP VIEW","DROP","EXECUTE","EXPLAIN","FETCH","GRANT","LOCK","PREPARE","REFRESH MATERIALIZED VIEW","RESET","REVOKE","ROLLBACK","SELECT INTO","SET SESSION AUTHORIZATION","SET SESSION CHARACTERISTICS","SHOW","SHOW EXTERNAL TABLE","SHOW MODEL","SHOW DATASHARES","SHOW PROCEDURE","SHOW TABLE","SHOW VIEW","START TRANSACTION","UNLOAD","VACUUM"]),GH=j(["UNION [ALL]","EXCEPT","INTERSECT","MINUS"]),HH=j(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),YH=j(["NULL AS","DATA CATALOG","HIVE METASTORE","{ROWS | RANGE} BETWEEN"]),WH=j([]),$H={name:"redshift",tokenizerOptions:{reservedSelect:kH,reservedClauses:[...jH,...mf,...Xl],reservedSetOperations:GH,reservedJoins:HH,reservedKeywordPhrases:YH,reservedDataTypePhrases:WH,reservedKeywords:BH,reservedDataTypes:FH,reservedFunctionNames:UH,extraParens:["[]"],stringTypes:["''-qq"],identTypes:['""-qq'],identChars:{first:"#"},paramTypes:{numbered:["$"]},operators:["^","%","@","|/","||/","&","|","~","<<",">>","||","::"]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...mf,...Xl],tabularOnelineClauses:Xl}},VH=["ADD","AFTER","ALL","ALTER","ANALYZE","AND","ANTI","ANY","ARCHIVE","AS","ASC","AT","AUTHORIZATION","BETWEEN","BOTH","BUCKET","BUCKETS","BY","CACHE","CASCADE","CAST","CHANGE","CHECK","CLEAR","CLUSTER","CLUSTERED","CODEGEN","COLLATE","COLLECTION","COLUMN","COLUMNS","COMMENT","COMMIT","COMPACT","COMPACTIONS","COMPUTE","CONCATENATE","CONSTRAINT","COST","CREATE","CROSS","CUBE","CURRENT","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","DATA","DATABASE","DATABASES","DAY","DBPROPERTIES","DEFINED","DELETE","DELIMITED","DESC","DESCRIBE","DFS","DIRECTORIES","DIRECTORY","DISTINCT","DISTRIBUTE","DIV","DROP","ESCAPE","ESCAPED","EXCEPT","EXCHANGE","EXISTS","EXPORT","EXTENDED","EXTERNAL","EXTRACT","FALSE","FETCH","FIELDS","FILTER","FILEFORMAT","FIRST","FIRST_VALUE","FOLLOWING","FOR","FOREIGN","FORMAT","FORMATTED","FULL","FUNCTION","FUNCTIONS","GLOBAL","GRANT","GROUP","GROUPING","HOUR","IF","IGNORE","IMPORT","IN","INDEX","INDEXES","INNER","INPATH","INPUTFORMAT","INTERSECT","INTO","IS","ITEMS","KEYS","LAST","LAST_VALUE","LATERAL","LAZY","LEADING","LEFT","LIKE","LINES","LIST","LOCAL","LOCATION","LOCK","LOCKS","LOGICAL","MACRO","MATCHED","MERGE","MINUTE","MONTH","MSCK","NAMESPACE","NAMESPACES","NATURAL","NO","NOT","NULL","NULLS","OF","ONLY","OPTION","OPTIONS","OR","ORDER","OUT","OUTER","OUTPUTFORMAT","OVER","OVERLAPS","OVERLAY","OVERWRITE","OWNER","PARTITION","PARTITIONED","PARTITIONS","PERCENT","PLACING","POSITION","PRECEDING","PRIMARY","PRINCIPALS","PROPERTIES","PURGE","QUERY","RANGE","RECORDREADER","RECORDWRITER","RECOVER","REDUCE","REFERENCES","RENAME","REPAIR","REPLACE","RESPECT","RESTRICT","REVOKE","RIGHT","RLIKE","ROLE","ROLES","ROLLBACK","ROLLUP","ROW","ROWS","SCHEMA","SECOND","SELECT","SEMI","SEPARATED","SERDE","SERDEPROPERTIES","SESSION_USER","SETS","SHOW","SKEWED","SOME","SORT","SORTED","START","STATISTICS","STORED","STRATIFY","SUBSTR","SUBSTRING","TABLE","TABLES","TBLPROPERTIES","TEMPORARY","TERMINATED","THEN","TO","TOUCH","TRAILING","TRANSACTION","TRANSACTIONS","TRIM","TRUE","TRUNCATE","UNARCHIVE","UNBOUNDED","UNCACHE","UNIQUE","UNKNOWN","UNLOCK","UNSET","USE","USER","USING","VIEW","WINDOW","YEAR","ANALYSE","ARRAY_ZIP","COALESCE","CONTAINS","CONVERT","DAYS","DAY_HOUR","DAY_MINUTE","DAY_SECOND","DECODE","DEFAULT","DISTINCTROW","ENCODE","EXPLODE","EXPLODE_OUTER","FIXED","GREATEST","GROUP_CONCAT","HOURS","HOUR_MINUTE","HOUR_SECOND","IFNULL","LEAST","LEVEL","MINUTE_SECOND","NULLIF","OFFSET","ON","OPTIMIZE","REGEXP","SEPARATOR","SIZE","TYPE","TYPES","UNSIGNED","VARIABLES","YEAR_MONTH"],XH=["ARRAY","BIGINT","BINARY","BOOLEAN","BYTE","CHAR","DATE","DEC","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","INTERVAL","LONG","MAP","NUMERIC","REAL","SHORT","SMALLINT","STRING","STRUCT","TIMESTAMP_LTZ","TIMESTAMP_NTZ","TIMESTAMP","TINYINT","VARCHAR"],zH=["APPROX_COUNT_DISTINCT","APPROX_PERCENTILE","AVG","BIT_AND","BIT_OR","BIT_XOR","BOOL_AND","BOOL_OR","COLLECT_LIST","COLLECT_SET","CORR","COUNT","COUNT","COUNT","COUNT_IF","COUNT_MIN_SKETCH","COVAR_POP","COVAR_SAMP","EVERY","FIRST","FIRST_VALUE","GROUPING","GROUPING_ID","KURTOSIS","LAST","LAST_VALUE","MAX","MAX_BY","MEAN","MIN","MIN_BY","PERCENTILE","PERCENTILE","PERCENTILE_APPROX","SKEWNESS","STD","STDDEV","STDDEV_POP","STDDEV_SAMP","SUM","VAR_POP","VAR_SAMP","VARIANCE","CUME_DIST","DENSE_RANK","LAG","LEAD","NTH_VALUE","NTILE","PERCENT_RANK","RANK","ROW_NUMBER","ARRAY","ARRAY_CONTAINS","ARRAY_DISTINCT","ARRAY_EXCEPT","ARRAY_INTERSECT","ARRAY_JOIN","ARRAY_MAX","ARRAY_MIN","ARRAY_POSITION","ARRAY_REMOVE","ARRAY_REPEAT","ARRAY_UNION","ARRAYS_OVERLAP","ARRAYS_ZIP","FLATTEN","SEQUENCE","SHUFFLE","SLICE","SORT_ARRAY","ELEMENT_AT","ELEMENT_AT","MAP_CONCAT","MAP_ENTRIES","MAP_FROM_ARRAYS","MAP_FROM_ENTRIES","MAP_KEYS","MAP_VALUES","STR_TO_MAP","ADD_MONTHS","CURRENT_DATE","CURRENT_DATE","CURRENT_TIMESTAMP","CURRENT_TIMESTAMP","CURRENT_TIMEZONE","DATE_ADD","DATE_FORMAT","DATE_FROM_UNIX_DATE","DATE_PART","DATE_SUB","DATE_TRUNC","DATEDIFF","DAY","DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","EXTRACT","FROM_UNIXTIME","FROM_UTC_TIMESTAMP","HOUR","LAST_DAY","MAKE_DATE","MAKE_DT_INTERVAL","MAKE_INTERVAL","MAKE_TIMESTAMP","MAKE_YM_INTERVAL","MINUTE","MONTH","MONTHS_BETWEEN","NEXT_DAY","NOW","QUARTER","SECOND","SESSION_WINDOW","TIMESTAMP_MICROS","TIMESTAMP_MILLIS","TIMESTAMP_SECONDS","TO_DATE","TO_TIMESTAMP","TO_UNIX_TIMESTAMP","TO_UTC_TIMESTAMP","TRUNC","UNIX_DATE","UNIX_MICROS","UNIX_MILLIS","UNIX_SECONDS","UNIX_TIMESTAMP","WEEKDAY","WEEKOFYEAR","WINDOW","YEAR","FROM_JSON","GET_JSON_OBJECT","JSON_ARRAY_LENGTH","JSON_OBJECT_KEYS","JSON_TUPLE","SCHEMA_OF_JSON","TO_JSON","ABS","ACOS","ACOSH","AGGREGATE","ARRAY_SORT","ASCII","ASIN","ASINH","ASSERT_TRUE","ATAN","ATAN2","ATANH","BASE64","BIN","BIT_COUNT","BIT_GET","BIT_LENGTH","BROUND","BTRIM","CARDINALITY","CBRT","CEIL","CEILING","CHAR_LENGTH","CHARACTER_LENGTH","CHR","CONCAT","CONCAT_WS","CONV","COS","COSH","COT","CRC32","CURRENT_CATALOG","CURRENT_DATABASE","CURRENT_USER","DEGREES","ELT","EXP","EXPM1","FACTORIAL","FIND_IN_SET","FLOOR","FORALL","FORMAT_NUMBER","FORMAT_STRING","FROM_CSV","GETBIT","HASH","HEX","HYPOT","INITCAP","INLINE","INLINE_OUTER","INPUT_FILE_BLOCK_LENGTH","INPUT_FILE_BLOCK_START","INPUT_FILE_NAME","INSTR","ISNAN","ISNOTNULL","ISNULL","JAVA_METHOD","LCASE","LEFT","LENGTH","LEVENSHTEIN","LN","LOCATE","LOG","LOG10","LOG1P","LOG2","LOWER","LPAD","LTRIM","MAP_FILTER","MAP_ZIP_WITH","MD5","MOD","MONOTONICALLY_INCREASING_ID","NAMED_STRUCT","NANVL","NEGATIVE","NVL","NVL2","OCTET_LENGTH","OVERLAY","PARSE_URL","PI","PMOD","POSEXPLODE","POSEXPLODE_OUTER","POSITION","POSITIVE","POW","POWER","PRINTF","RADIANS","RAISE_ERROR","RAND","RANDN","RANDOM","REFLECT","REGEXP_EXTRACT","REGEXP_EXTRACT_ALL","REGEXP_LIKE","REGEXP_REPLACE","REPEAT","REPLACE","REVERSE","RIGHT","RINT","ROUND","RPAD","RTRIM","SCHEMA_OF_CSV","SENTENCES","SHA","SHA1","SHA2","SHIFTLEFT","SHIFTRIGHT","SHIFTRIGHTUNSIGNED","SIGN","SIGNUM","SIN","SINH","SOUNDEX","SPACE","SPARK_PARTITION_ID","SPLIT","SQRT","STACK","SUBSTR","SUBSTRING","SUBSTRING_INDEX","TAN","TANH","TO_CSV","TRANSFORM_KEYS","TRANSFORM_VALUES","TRANSLATE","TRIM","TRY_ADD","TRY_DIVIDE","TYPEOF","UCASE","UNBASE64","UNHEX","UPPER","UUID","VERSION","WIDTH_BUCKET","XPATH","XPATH_BOOLEAN","XPATH_DOUBLE","XPATH_FLOAT","XPATH_INT","XPATH_LONG","XPATH_NUMBER","XPATH_SHORT","XPATH_STRING","XXHASH64","ZIP_WITH","CAST","COALESCE","NULLIF"],KH=j(["SELECT [ALL | DISTINCT]"]),qH=j(["WITH","FROM","WHERE","GROUP BY","HAVING","WINDOW","PARTITION BY","ORDER BY","SORT BY","CLUSTER BY","DISTRIBUTE BY","LIMIT","INSERT [INTO | OVERWRITE] [TABLE]","VALUES","INSERT OVERWRITE [LOCAL] DIRECTORY","LOAD DATA [LOCAL] INPATH","[OVERWRITE] INTO TABLE"]),Of=j(["CREATE [EXTERNAL] TABLE [IF NOT EXISTS]"]),zl=j(["CREATE [OR REPLACE] [GLOBAL TEMPORARY | TEMPORARY] VIEW [IF NOT EXISTS]","DROP TABLE [IF EXISTS]","ALTER TABLE","ADD COLUMNS","DROP {COLUMN | COLUMNS}","RENAME TO","RENAME COLUMN","ALTER COLUMN","TRUNCATE TABLE","LATERAL VIEW","ALTER DATABASE","ALTER VIEW","CREATE DATABASE","CREATE FUNCTION","DROP DATABASE","DROP FUNCTION","DROP VIEW","REPAIR TABLE","USE DATABASE","TABLESAMPLE","PIVOT","TRANSFORM","EXPLAIN","ADD FILE","ADD JAR","ANALYZE TABLE","CACHE TABLE","CLEAR CACHE","DESCRIBE DATABASE","DESCRIBE FUNCTION","DESCRIBE QUERY","DESCRIBE TABLE","LIST FILE","LIST JAR","REFRESH","REFRESH TABLE","REFRESH FUNCTION","RESET","SHOW COLUMNS","SHOW CREATE TABLE","SHOW DATABASES","SHOW FUNCTIONS","SHOW PARTITIONS","SHOW TABLE EXTENDED","SHOW TABLES","SHOW TBLPROPERTIES","SHOW VIEWS","UNCACHE TABLE"]),JH=j(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),QH=j(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN","[LEFT] {ANTI | SEMI} JOIN","NATURAL [LEFT] {ANTI | SEMI} JOIN"]),ZH=j(["ON DELETE","ON UPDATE","CURRENT ROW","{ROWS | RANGE} BETWEEN"]),eY=j([]),tY={name:"spark",tokenizerOptions:{reservedSelect:KH,reservedClauses:[...qH,...Of,...zl],reservedSetOperations:JH,reservedJoins:QH,reservedKeywordPhrases:ZH,reservedDataTypePhrases:eY,supportsXor:!0,reservedKeywords:VH,reservedDataTypes:XH,reservedFunctionNames:zH,extraParens:["[]"],stringTypes:["''-bs",'""-bs',{quote:"''-raw",prefixes:["R","X"],requirePrefix:!0},{quote:'""-raw',prefixes:["R","X"],requirePrefix:!0}],identTypes:["``"],identChars:{allowFirstCharNumber:!0},variableTypes:[{quote:"{}",prefixes:["$"],requirePrefix:!0}],operators:["%","~","^","|","&","<=>","==","!","||","->"],postProcess:nY},formatOptions:{onelineClauses:[...Of,...zl],tabularOnelineClauses:zl}};function nY(e){return e.map((t,n)=>{const r=e[n-1]||hn,o=e[n+1]||hn;return An.WINDOW(t)&&o.type===K.OPEN_PAREN?Object.assign(Object.assign({},t),{type:K.RESERVED_FUNCTION_NAME}):t.text==="ITEMS"&&t.type===K.RESERVED_KEYWORD&&!(r.text==="COLLECTION"&&o.text==="TERMINATED")?Object.assign(Object.assign({},t),{type:K.IDENTIFIER,text:t.raw}):t})}const rY=["ABS","CHANGES","CHAR","COALESCE","FORMAT","GLOB","HEX","IFNULL","IIF","INSTR","LAST_INSERT_ROWID","LENGTH","LIKE","LIKELIHOOD","LIKELY","LOAD_EXTENSION","LOWER","LTRIM","NULLIF","PRINTF","QUOTE","RANDOM","RANDOMBLOB","REPLACE","ROUND","RTRIM","SIGN","SOUNDEX","SQLITE_COMPILEOPTION_GET","SQLITE_COMPILEOPTION_USED","SQLITE_OFFSET","SQLITE_SOURCE_ID","SQLITE_VERSION","SUBSTR","SUBSTRING","TOTAL_CHANGES","TRIM","TYPEOF","UNICODE","UNLIKELY","UPPER","ZEROBLOB","AVG","COUNT","GROUP_CONCAT","MAX","MIN","SUM","TOTAL","DATE","TIME","DATETIME","JULIANDAY","UNIXEPOCH","STRFTIME","row_number","rank","dense_rank","percent_rank","cume_dist","ntile","lag","lead","first_value","last_value","nth_value","ACOS","ACOSH","ASIN","ASINH","ATAN","ATAN2","ATANH","CEIL","CEILING","COS","COSH","DEGREES","EXP","FLOOR","LN","LOG","LOG","LOG10","LOG2","MOD","PI","POW","POWER","RADIANS","SIN","SINH","SQRT","TAN","TANH","TRUNC","JSON","JSON_ARRAY","JSON_ARRAY_LENGTH","JSON_ARRAY_LENGTH","JSON_EXTRACT","JSON_INSERT","JSON_OBJECT","JSON_PATCH","JSON_REMOVE","JSON_REPLACE","JSON_SET","JSON_TYPE","JSON_TYPE","JSON_VALID","JSON_QUOTE","JSON_GROUP_ARRAY","JSON_GROUP_OBJECT","JSON_EACH","JSON_TREE","CAST"],oY=["ABORT","ACTION","ADD","AFTER","ALL","ALTER","AND","ARE","ALWAYS","ANALYZE","AS","ASC","ATTACH","AUTOINCREMENT","BEFORE","BEGIN","BETWEEN","BY","CASCADE","CASE","CAST","CHECK","COLLATE","COLUMN","COMMIT","CONFLICT","CONSTRAINT","CREATE","CROSS","CURRENT","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","DATABASE","DEFAULT","DEFERRABLE","DEFERRED","DELETE","DESC","DETACH","DISTINCT","DO","DROP","EACH","ELSE","END","ESCAPE","EXCEPT","EXCLUDE","EXCLUSIVE","EXISTS","EXPLAIN","FAIL","FILTER","FIRST","FOLLOWING","FOR","FOREIGN","FROM","FULL","GENERATED","GLOB","GROUP","HAVING","IF","IGNORE","IMMEDIATE","IN","INDEX","INDEXED","INITIALLY","INNER","INSERT","INSTEAD","INTERSECT","INTO","IS","ISNULL","JOIN","KEY","LAST","LEFT","LIKE","LIMIT","MATCH","MATERIALIZED","NATURAL","NO","NOT","NOTHING","NOTNULL","NULL","NULLS","OF","OFFSET","ON","ONLY","OPEN","OR","ORDER","OTHERS","OUTER","OVER","PARTITION","PLAN","PRAGMA","PRECEDING","PRIMARY","QUERY","RAISE","RANGE","RECURSIVE","REFERENCES","REGEXP","REINDEX","RELEASE","RENAME","REPLACE","RESTRICT","RETURNING","RIGHT","ROLLBACK","ROW","ROWS","SAVEPOINT","SELECT","SET","TABLE","TEMP","TEMPORARY","THEN","TIES","TO","TRANSACTION","TRIGGER","UNBOUNDED","UNION","UNIQUE","UPDATE","USING","VACUUM","VALUES","VIEW","VIRTUAL","WHEN","WHERE","WINDOW","WITH","WITHOUT"],sY=["ANY","ARRAY","BLOB","CHARACTER","DECIMAL","INT","INTEGER","NATIVE CHARACTER","NCHAR","NUMERIC","NVARCHAR","REAL","TEXT","VARCHAR","VARYING CHARACTER"],iY=j(["SELECT [ALL | DISTINCT]"]),aY=j(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT [OR ABORT | OR FAIL | OR IGNORE | OR REPLACE | OR ROLLBACK] INTO","REPLACE INTO","VALUES","SET","RETURNING"]),Nf=j(["CREATE [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),Kl=j(["CREATE [TEMPORARY | TEMP] VIEW [IF NOT EXISTS]","UPDATE [OR ABORT | OR FAIL | OR IGNORE | OR REPLACE | OR ROLLBACK]","ON CONFLICT","DELETE FROM","DROP TABLE [IF EXISTS]","ALTER TABLE","ADD [COLUMN]","DROP [COLUMN]","RENAME [COLUMN]","RENAME TO","SET SCHEMA"]),lY=j(["UNION [ALL]","EXCEPT","INTERSECT"]),cY=j(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),dY=j(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE | GROUPS} BETWEEN","DO UPDATE"]),EY=j([]),uY={name:"sqlite",tokenizerOptions:{reservedSelect:iY,reservedClauses:[...aY,...Nf,...Kl],reservedSetOperations:lY,reservedJoins:cY,reservedKeywordPhrases:dY,reservedDataTypePhrases:EY,reservedKeywords:oY,reservedDataTypes:sY,reservedFunctionNames:rY,stringTypes:["''-qq",{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``","[]"],paramTypes:{positional:!0,numbered:["?"],named:[":","@","$"]},operators:["%","~","&","|","<<",">>","==","->","->>","||"]},formatOptions:{onelineClauses:[...Nf,...Kl],tabularOnelineClauses:Kl}},TY=["GROUPING","RANK","DENSE_RANK","PERCENT_RANK","CUME_DIST","ROW_NUMBER","POSITION","OCCURRENCES_REGEX","POSITION_REGEX","EXTRACT","CHAR_LENGTH","CHARACTER_LENGTH","OCTET_LENGTH","CARDINALITY","ABS","MOD","LN","EXP","POWER","SQRT","FLOOR","CEIL","CEILING","WIDTH_BUCKET","SUBSTRING","SUBSTRING_REGEX","UPPER","LOWER","CONVERT","TRANSLATE","TRANSLATE_REGEX","TRIM","OVERLAY","NORMALIZE","SPECIFICTYPE","CURRENT_DATE","CURRENT_TIME","LOCALTIME","CURRENT_TIMESTAMP","LOCALTIMESTAMP","COUNT","AVG","MAX","MIN","SUM","STDDEV_POP","STDDEV_SAMP","VAR_SAMP","VAR_POP","COLLECT","FUSION","INTERSECTION","COVAR_POP","COVAR_SAMP","CORR","REGR_SLOPE","REGR_INTERCEPT","REGR_COUNT","REGR_R2","REGR_AVGX","REGR_AVGY","REGR_SXX","REGR_SYY","REGR_SXY","PERCENTILE_CONT","PERCENTILE_DISC","CAST","COALESCE","NULLIF","ROUND","SIN","COS","TAN","ASIN","ACOS","ATAN"],fY=["ALL","ALLOCATE","ALTER","ANY","ARE","AS","ASC","ASENSITIVE","ASYMMETRIC","AT","ATOMIC","AUTHORIZATION","BEGIN","BETWEEN","BOTH","BY","CALL","CALLED","CASCADED","CAST","CHECK","CLOSE","COALESCE","COLLATE","COLUMN","COMMIT","CONDITION","CONNECT","CONSTRAINT","CORRESPONDING","CREATE","CROSS","CUBE","CURRENT","CURRENT_CATALOG","CURRENT_DEFAULT_TRANSFORM_GROUP","CURRENT_PATH","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_TRANSFORM_GROUP_FOR_TYPE","CURRENT_USER","CURSOR","CYCLE","DEALLOCATE","DAY","DECLARE","DEFAULT","DELETE","DEREF","DESC","DESCRIBE","DETERMINISTIC","DISCONNECT","DISTINCT","DROP","DYNAMIC","EACH","ELEMENT","END-EXEC","ESCAPE","EVERY","EXCEPT","EXEC","EXECUTE","EXISTS","EXTERNAL","FALSE","FETCH","FILTER","FOR","FOREIGN","FREE","FROM","FULL","FUNCTION","GET","GLOBAL","GRANT","GROUP","HAVING","HOLD","HOUR","IDENTITY","IN","INDICATOR","INNER","INOUT","INSENSITIVE","INSERT","INTERSECT","INTO","IS","LANGUAGE","LARGE","LATERAL","LEADING","LEFT","LIKE","LIKE_REGEX","LOCAL","MATCH","MEMBER","MERGE","METHOD","MINUTE","MODIFIES","MODULE","MONTH","NATURAL","NEW","NO","NONE","NOT","NULL","NULLIF","OF","OLD","ON","ONLY","OPEN","ORDER","OUT","OUTER","OVER","OVERLAPS","PARAMETER","PARTITION","PRECISION","PREPARE","PRIMARY","PROCEDURE","RANGE","READS","REAL","RECURSIVE","REF","REFERENCES","REFERENCING","RELEASE","RESULT","RETURN","RETURNS","REVOKE","RIGHT","ROLLBACK","ROLLUP","ROW","ROWS","SAVEPOINT","SCOPE","SCROLL","SEARCH","SECOND","SELECT","SENSITIVE","SESSION_USER","SET","SIMILAR","SOME","SPECIFIC","SQL","SQLEXCEPTION","SQLSTATE","SQLWARNING","START","STATIC","SUBMULTISET","SYMMETRIC","SYSTEM","SYSTEM_USER","TABLE","TABLESAMPLE","THEN","TIMEZONE_HOUR","TIMEZONE_MINUTE","TO","TRAILING","TRANSLATION","TREAT","TRIGGER","TRUE","UESCAPE","UNION","UNIQUE","UNKNOWN","UNNEST","UPDATE","USER","USING","VALUE","VALUES","WHENEVER","WINDOW","WITHIN","WITHOUT","YEAR"],pY=["ARRAY","BIGINT","BINARY LARGE OBJECT","BINARY VARYING","BINARY","BLOB","BOOLEAN","CHAR LARGE OBJECT","CHAR VARYING","CHAR","CHARACTER LARGE OBJECT","CHARACTER VARYING","CHARACTER","CLOB","DATE","DEC","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","INTERVAL","MULTISET","NATIONAL CHAR VARYING","NATIONAL CHAR","NATIONAL CHARACTER LARGE OBJECT","NATIONAL CHARACTER VARYING","NATIONAL CHARACTER","NCHAR LARGE OBJECT","NCHAR VARYING","NCHAR","NCLOB","NUMERIC","SMALLINT","TIME","TIMESTAMP","VARBINARY","VARCHAR"],SY=j(["SELECT [ALL | DISTINCT]"]),RY=j(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY [ALL | DISTINCT]","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","FETCH {FIRST | NEXT}","INSERT INTO","VALUES","SET"]),gf=j(["CREATE [GLOBAL TEMPORARY | LOCAL TEMPORARY] TABLE"]),ql=j(["CREATE [RECURSIVE] VIEW","UPDATE","WHERE CURRENT OF","DELETE FROM","DROP TABLE","ALTER TABLE","ADD COLUMN","DROP [COLUMN]","RENAME COLUMN","RENAME TO","ALTER [COLUMN]","{SET | DROP} DEFAULT","ADD SCOPE","DROP SCOPE {CASCADE | RESTRICT}","RESTART WITH","TRUNCATE TABLE","SET SCHEMA"]),hY=j(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),AY=j(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),IY=j(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),mY=j([]),OY={name:"sql",tokenizerOptions:{reservedSelect:SY,reservedClauses:[...RY,...gf,...ql],reservedSetOperations:hY,reservedJoins:AY,reservedKeywordPhrases:IY,reservedDataTypePhrases:mY,reservedKeywords:fY,reservedDataTypes:pY,reservedFunctionNames:TY,stringTypes:[{quote:"''-qq-bs",prefixes:["N","U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``"],paramTypes:{positional:!0},operators:["||"]},formatOptions:{onelineClauses:[...gf,...ql],tabularOnelineClauses:ql}},NY=["ABS","ACOS","ALL_MATCH","ANY_MATCH","APPROX_DISTINCT","APPROX_MOST_FREQUENT","APPROX_PERCENTILE","APPROX_SET","ARBITRARY","ARRAYS_OVERLAP","ARRAY_AGG","ARRAY_DISTINCT","ARRAY_EXCEPT","ARRAY_INTERSECT","ARRAY_JOIN","ARRAY_MAX","ARRAY_MIN","ARRAY_POSITION","ARRAY_REMOVE","ARRAY_SORT","ARRAY_UNION","ASIN","ATAN","ATAN2","AT_TIMEZONE","AVG","BAR","BETA_CDF","BING_TILE","BING_TILES_AROUND","BING_TILE_AT","BING_TILE_COORDINATES","BING_TILE_POLYGON","BING_TILE_QUADKEY","BING_TILE_ZOOM_LEVEL","BITWISE_AND","BITWISE_AND_AGG","BITWISE_LEFT_SHIFT","BITWISE_NOT","BITWISE_OR","BITWISE_OR_AGG","BITWISE_RIGHT_SHIFT","BITWISE_RIGHT_SHIFT_ARITHMETIC","BITWISE_XOR","BIT_COUNT","BOOL_AND","BOOL_OR","CARDINALITY","CAST","CBRT","CEIL","CEILING","CHAR2HEXINT","CHECKSUM","CHR","CLASSIFY","COALESCE","CODEPOINT","COLOR","COMBINATIONS","CONCAT","CONCAT_WS","CONTAINS","CONTAINS_SEQUENCE","CONVEX_HULL_AGG","CORR","COS","COSH","COSINE_SIMILARITY","COUNT","COUNT_IF","COVAR_POP","COVAR_SAMP","CRC32","CUME_DIST","CURRENT_CATALOG","CURRENT_DATE","CURRENT_GROUPS","CURRENT_SCHEMA","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_TIMEZONE","CURRENT_USER","DATE","DATE_ADD","DATE_DIFF","DATE_FORMAT","DATE_PARSE","DATE_TRUNC","DAY","DAY_OF_MONTH","DAY_OF_WEEK","DAY_OF_YEAR","DEGREES","DENSE_RANK","DOW","DOY","E","ELEMENT_AT","EMPTY_APPROX_SET","EVALUATE_CLASSIFIER_PREDICTIONS","EVERY","EXP","EXTRACT","FEATURES","FILTER","FIRST_VALUE","FLATTEN","FLOOR","FORMAT","FORMAT_DATETIME","FORMAT_NUMBER","FROM_BASE","FROM_BASE32","FROM_BASE64","FROM_BASE64URL","FROM_BIG_ENDIAN_32","FROM_BIG_ENDIAN_64","FROM_ENCODED_POLYLINE","FROM_GEOJSON_GEOMETRY","FROM_HEX","FROM_IEEE754_32","FROM_IEEE754_64","FROM_ISO8601_DATE","FROM_ISO8601_TIMESTAMP","FROM_ISO8601_TIMESTAMP_NANOS","FROM_UNIXTIME","FROM_UNIXTIME_NANOS","FROM_UTF8","GEOMETRIC_MEAN","GEOMETRY_FROM_HADOOP_SHAPE","GEOMETRY_INVALID_REASON","GEOMETRY_NEAREST_POINTS","GEOMETRY_TO_BING_TILES","GEOMETRY_UNION","GEOMETRY_UNION_AGG","GREATEST","GREAT_CIRCLE_DISTANCE","HAMMING_DISTANCE","HASH_COUNTS","HISTOGRAM","HMAC_MD5","HMAC_SHA1","HMAC_SHA256","HMAC_SHA512","HOUR","HUMAN_READABLE_SECONDS","IF","INDEX","INFINITY","INTERSECTION_CARDINALITY","INVERSE_BETA_CDF","INVERSE_NORMAL_CDF","IS_FINITE","IS_INFINITE","IS_JSON_SCALAR","IS_NAN","JACCARD_INDEX","JSON_ARRAY_CONTAINS","JSON_ARRAY_GET","JSON_ARRAY_LENGTH","JSON_EXISTS","JSON_EXTRACT","JSON_EXTRACT_SCALAR","JSON_FORMAT","JSON_PARSE","JSON_QUERY","JSON_SIZE","JSON_VALUE","KURTOSIS","LAG","LAST_DAY_OF_MONTH","LAST_VALUE","LEAD","LEARN_CLASSIFIER","LEARN_LIBSVM_CLASSIFIER","LEARN_LIBSVM_REGRESSOR","LEARN_REGRESSOR","LEAST","LENGTH","LEVENSHTEIN_DISTANCE","LINE_INTERPOLATE_POINT","LINE_INTERPOLATE_POINTS","LINE_LOCATE_POINT","LISTAGG","LN","LOCALTIME","LOCALTIMESTAMP","LOG","LOG10","LOG2","LOWER","LPAD","LTRIM","LUHN_CHECK","MAKE_SET_DIGEST","MAP","MAP_AGG","MAP_CONCAT","MAP_ENTRIES","MAP_FILTER","MAP_FROM_ENTRIES","MAP_KEYS","MAP_UNION","MAP_VALUES","MAP_ZIP_WITH","MAX","MAX_BY","MD5","MERGE","MERGE_SET_DIGEST","MILLISECOND","MIN","MINUTE","MIN_BY","MOD","MONTH","MULTIMAP_AGG","MULTIMAP_FROM_ENTRIES","MURMUR3","NAN","NGRAMS","NONE_MATCH","NORMALIZE","NORMAL_CDF","NOW","NTH_VALUE","NTILE","NULLIF","NUMERIC_HISTOGRAM","OBJECTID","OBJECTID_TIMESTAMP","PARSE_DATA_SIZE","PARSE_DATETIME","PARSE_DURATION","PERCENT_RANK","PI","POSITION","POW","POWER","QDIGEST_AGG","QUARTER","RADIANS","RAND","RANDOM","RANK","REDUCE","REDUCE_AGG","REGEXP_COUNT","REGEXP_EXTRACT","REGEXP_EXTRACT_ALL","REGEXP_LIKE","REGEXP_POSITION","REGEXP_REPLACE","REGEXP_SPLIT","REGRESS","REGR_INTERCEPT","REGR_SLOPE","RENDER","REPEAT","REPLACE","REVERSE","RGB","ROUND","ROW_NUMBER","RPAD","RTRIM","SECOND","SEQUENCE","SHA1","SHA256","SHA512","SHUFFLE","SIGN","SIMPLIFY_GEOMETRY","SIN","SKEWNESS","SLICE","SOUNDEX","SPATIAL_PARTITIONING","SPATIAL_PARTITIONS","SPLIT","SPLIT_PART","SPLIT_TO_MAP","SPLIT_TO_MULTIMAP","SPOOKY_HASH_V2_32","SPOOKY_HASH_V2_64","SQRT","STARTS_WITH","STDDEV","STDDEV_POP","STDDEV_SAMP","STRPOS","ST_AREA","ST_ASBINARY","ST_ASTEXT","ST_BOUNDARY","ST_BUFFER","ST_CENTROID","ST_CONTAINS","ST_CONVEXHULL","ST_COORDDIM","ST_CROSSES","ST_DIFFERENCE","ST_DIMENSION","ST_DISJOINT","ST_DISTANCE","ST_ENDPOINT","ST_ENVELOPE","ST_ENVELOPEASPTS","ST_EQUALS","ST_EXTERIORRING","ST_GEOMETRIES","ST_GEOMETRYFROMTEXT","ST_GEOMETRYN","ST_GEOMETRYTYPE","ST_GEOMFROMBINARY","ST_INTERIORRINGN","ST_INTERIORRINGS","ST_INTERSECTION","ST_INTERSECTS","ST_ISCLOSED","ST_ISEMPTY","ST_ISRING","ST_ISSIMPLE","ST_ISVALID","ST_LENGTH","ST_LINEFROMTEXT","ST_LINESTRING","ST_MULTIPOINT","ST_NUMGEOMETRIES","ST_NUMINTERIORRING","ST_NUMPOINTS","ST_OVERLAPS","ST_POINT","ST_POINTN","ST_POINTS","ST_POLYGON","ST_RELATE","ST_STARTPOINT","ST_SYMDIFFERENCE","ST_TOUCHES","ST_UNION","ST_WITHIN","ST_X","ST_XMAX","ST_XMIN","ST_Y","ST_YMAX","ST_YMIN","SUBSTR","SUBSTRING","SUM","TAN","TANH","TDIGEST_AGG","TIMESTAMP_OBJECTID","TIMEZONE_HOUR","TIMEZONE_MINUTE","TO_BASE","TO_BASE32","TO_BASE64","TO_BASE64URL","TO_BIG_ENDIAN_32","TO_BIG_ENDIAN_64","TO_CHAR","TO_DATE","TO_ENCODED_POLYLINE","TO_GEOJSON_GEOMETRY","TO_GEOMETRY","TO_HEX","TO_IEEE754_32","TO_IEEE754_64","TO_ISO8601","TO_MILLISECONDS","TO_SPHERICAL_GEOGRAPHY","TO_TIMESTAMP","TO_UNIXTIME","TO_UTF8","TRANSFORM","TRANSFORM_KEYS","TRANSFORM_VALUES","TRANSLATE","TRIM","TRIM_ARRAY","TRUNCATE","TRY","TRY_CAST","TYPEOF","UPPER","URL_DECODE","URL_ENCODE","URL_EXTRACT_FRAGMENT","URL_EXTRACT_HOST","URL_EXTRACT_PARAMETER","URL_EXTRACT_PATH","URL_EXTRACT_PORT","URL_EXTRACT_PROTOCOL","URL_EXTRACT_QUERY","UUID","VALUES_AT_QUANTILES","VALUE_AT_QUANTILE","VARIANCE","VAR_POP","VAR_SAMP","VERSION","WEEK","WEEK_OF_YEAR","WIDTH_BUCKET","WILSON_INTERVAL_LOWER","WILSON_INTERVAL_UPPER","WITH_TIMEZONE","WORD_STEM","XXHASH64","YEAR","YEAR_OF_WEEK","YOW","ZIP","ZIP_WITH","CLASSIFIER","FIRST","LAST","MATCH_NUMBER","NEXT","PERMUTE","PREV"],gY=["ABSENT","ADD","ADMIN","AFTER","ALL","ALTER","ANALYZE","AND","ANY","AS","ASC","AT","AUTHORIZATION","BERNOULLI","BETWEEN","BOTH","BY","CALL","CASCADE","CASE","CATALOGS","COLUMN","COLUMNS","COMMENT","COMMIT","COMMITTED","CONDITIONAL","CONSTRAINT","COPARTITION","CREATE","CROSS","CUBE","CURRENT","CURRENT_PATH","CURRENT_ROLE","DATA","DEALLOCATE","DEFAULT","DEFINE","DEFINER","DELETE","DENY","DESC","DESCRIBE","DESCRIPTOR","DISTINCT","DISTRIBUTED","DOUBLE","DROP","ELSE","EMPTY","ENCODING","END","ERROR","ESCAPE","EXCEPT","EXCLUDING","EXECUTE","EXISTS","EXPLAIN","FALSE","FETCH","FINAL","FIRST","FOLLOWING","FOR","FROM","FULL","FUNCTIONS","GRANT","GRANTED","GRANTS","GRAPHVIZ","GROUP","GROUPING","GROUPS","HAVING","IGNORE","IN","INCLUDING","INITIAL","INNER","INPUT","INSERT","INTERSECT","INTERVAL","INTO","INVOKER","IO","IS","ISOLATION","JOIN","JSON","JSON_ARRAY","JSON_OBJECT","KEEP","KEY","KEYS","LAST","LATERAL","LEADING","LEFT","LEVEL","LIKE","LIMIT","LOCAL","LOGICAL","MATCH","MATCHED","MATCHES","MATCH_RECOGNIZE","MATERIALIZED","MEASURES","NATURAL","NEXT","NFC","NFD","NFKC","NFKD","NO","NONE","NOT","NULL","NULLS","OBJECT","OF","OFFSET","OMIT","ON","ONE","ONLY","OPTION","OR","ORDER","ORDINALITY","OUTER","OUTPUT","OVER","OVERFLOW","PARTITION","PARTITIONS","PASSING","PAST","PATH","PATTERN","PER","PERMUTE","PRECEDING","PRECISION","PREPARE","PRIVILEGES","PROPERTIES","PRUNE","QUOTES","RANGE","READ","RECURSIVE","REFRESH","RENAME","REPEATABLE","RESET","RESPECT","RESTRICT","RETURNING","REVOKE","RIGHT","ROLE","ROLES","ROLLBACK","ROLLUP","ROW","ROWS","RUNNING","SCALAR","SCHEMA","SCHEMAS","SECURITY","SEEK","SELECT","SERIALIZABLE","SESSION","SET","SETS","SHOW","SKIP","SOME","START","STATS","STRING","SUBSET","SYSTEM","TABLE","TABLES","TABLESAMPLE","TEXT","THEN","TIES","TIME","TIMESTAMP","TO","TRAILING","TRANSACTION","TRUE","TYPE","UESCAPE","UNBOUNDED","UNCOMMITTED","UNCONDITIONAL","UNION","UNIQUE","UNKNOWN","UNMATCHED","UNNEST","UPDATE","USE","USER","USING","UTF16","UTF32","UTF8","VALIDATE","VALUE","VALUES","VERBOSE","VIEW","WHEN","WHERE","WINDOW","WITH","WITHIN","WITHOUT","WORK","WRAPPER","WRITE","ZONE"],xY=["BIGINT","INT","INTEGER","SMALLINT","TINYINT","BOOLEAN","DATE","DECIMAL","REAL","DOUBLE","HYPERLOGLOG","QDIGEST","TDIGEST","P4HYPERLOGLOG","INTERVAL","TIMESTAMP","TIME","VARBINARY","VARCHAR","CHAR","ROW","ARRAY","MAP","JSON","JSON2016","IPADDRESS","GEOMETRY","UUID","SETDIGEST","JONIREGEXP","RE2JREGEXP","LIKEPATTERN","COLOR","CODEPOINTS","FUNCTION","JSONPATH"],yY=j(["SELECT [ALL | DISTINCT]"]),CY=j(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY [ALL | DISTINCT]","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","FETCH {FIRST | NEXT}","INSERT INTO","VALUES","SET","MATCH_RECOGNIZE","MEASURES","ONE ROW PER MATCH","ALL ROWS PER MATCH","AFTER MATCH","PATTERN","SUBSET","DEFINE"]),xf=j(["CREATE TABLE [IF NOT EXISTS]"]),Jl=j(["CREATE [OR REPLACE] [MATERIALIZED] VIEW","UPDATE","DELETE FROM","DROP TABLE [IF EXISTS]","ALTER TABLE [IF EXISTS]","ADD COLUMN [IF NOT EXISTS]","DROP COLUMN [IF EXISTS]","RENAME COLUMN [IF EXISTS]","RENAME TO","SET AUTHORIZATION [USER | ROLE]","SET PROPERTIES","EXECUTE","TRUNCATE TABLE","ALTER SCHEMA","ALTER MATERIALIZED VIEW","ALTER VIEW","CREATE SCHEMA","CREATE ROLE","DROP SCHEMA","DROP MATERIALIZED VIEW","DROP VIEW","DROP ROLE","EXPLAIN","ANALYZE","EXPLAIN ANALYZE","EXPLAIN ANALYZE VERBOSE","USE","DESCRIBE INPUT","DESCRIBE OUTPUT","REFRESH MATERIALIZED VIEW","RESET SESSION","SET SESSION","SET PATH","SET TIME ZONE","SHOW GRANTS","SHOW CREATE TABLE","SHOW CREATE SCHEMA","SHOW CREATE VIEW","SHOW CREATE MATERIALIZED VIEW","SHOW TABLES","SHOW SCHEMAS","SHOW CATALOGS","SHOW COLUMNS","SHOW STATS FOR","SHOW ROLES","SHOW CURRENT ROLES","SHOW ROLE GRANTS","SHOW FUNCTIONS","SHOW SESSION"]),LY=j(["UNION [ALL | DISTINCT] [CORRESPONDING]","EXCEPT [ALL | DISTINCT] [CORRESPONDING]","INTERSECT [ALL | DISTINCT] [CORRESPONDING]"]),_Y=j(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),bY=j(["{ROWS | RANGE | GROUPS} BETWEEN","IS [NOT] DISTINCT FROM"]),DY=j([]),MY={name:"trino",tokenizerOptions:{reservedSelect:yY,reservedClauses:[...CY,...xf,...Jl],reservedSetOperations:LY,reservedJoins:_Y,reservedKeywordPhrases:bY,reservedDataTypePhrases:DY,reservedKeywords:gY,reservedDataTypes:xY,reservedFunctionNames:NY,extraParens:["[]","{}"],stringTypes:[{quote:"''-qq",prefixes:["U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq'],paramTypes:{positional:!0},operators:["%","->","=>",":","||","|","^","$"]},formatOptions:{onelineClauses:[...xf,...Jl],tabularOnelineClauses:Jl}},vY=["APPROX_COUNT_DISTINCT","AVG","CHECKSUM_AGG","COUNT","COUNT_BIG","GROUPING","GROUPING_ID","MAX","MIN","STDEV","STDEVP","SUM","VAR","VARP","CUME_DIST","FIRST_VALUE","LAG","LAST_VALUE","LEAD","PERCENTILE_CONT","PERCENTILE_DISC","PERCENT_RANK","Collation - COLLATIONPROPERTY","Collation - TERTIARY_WEIGHTS","@@DBTS","@@LANGID","@@LANGUAGE","@@LOCK_TIMEOUT","@@MAX_CONNECTIONS","@@MAX_PRECISION","@@NESTLEVEL","@@OPTIONS","@@REMSERVER","@@SERVERNAME","@@SERVICENAME","@@SPID","@@TEXTSIZE","@@VERSION","CAST","CONVERT","PARSE","TRY_CAST","TRY_CONVERT","TRY_PARSE","ASYMKEY_ID","ASYMKEYPROPERTY","CERTPROPERTY","CERT_ID","CRYPT_GEN_RANDOM","DECRYPTBYASYMKEY","DECRYPTBYCERT","DECRYPTBYKEY","DECRYPTBYKEYAUTOASYMKEY","DECRYPTBYKEYAUTOCERT","DECRYPTBYPASSPHRASE","ENCRYPTBYASYMKEY","ENCRYPTBYCERT","ENCRYPTBYKEY","ENCRYPTBYPASSPHRASE","HASHBYTES","IS_OBJECTSIGNED","KEY_GUID","KEY_ID","KEY_NAME","SIGNBYASYMKEY","SIGNBYCERT","SYMKEYPROPERTY","VERIFYSIGNEDBYCERT","VERIFYSIGNEDBYASYMKEY","@@CURSOR_ROWS","@@FETCH_STATUS","CURSOR_STATUS","DATALENGTH","IDENT_CURRENT","IDENT_INCR","IDENT_SEED","IDENTITY","SQL_VARIANT_PROPERTY","@@DATEFIRST","CURRENT_TIMESTAMP","CURRENT_TIMEZONE","CURRENT_TIMEZONE_ID","DATEADD","DATEDIFF","DATEDIFF_BIG","DATEFROMPARTS","DATENAME","DATEPART","DATETIME2FROMPARTS","DATETIMEFROMPARTS","DATETIMEOFFSETFROMPARTS","DAY","EOMONTH","GETDATE","GETUTCDATE","ISDATE","MONTH","SMALLDATETIMEFROMPARTS","SWITCHOFFSET","SYSDATETIME","SYSDATETIMEOFFSET","SYSUTCDATETIME","TIMEFROMPARTS","TODATETIMEOFFSET","YEAR","JSON","ISJSON","JSON_VALUE","JSON_QUERY","JSON_MODIFY","ABS","ACOS","ASIN","ATAN","ATN2","CEILING","COS","COT","DEGREES","EXP","FLOOR","LOG","LOG10","PI","POWER","RADIANS","RAND","ROUND","SIGN","SIN","SQRT","SQUARE","TAN","CHOOSE","GREATEST","IIF","LEAST","@@PROCID","APP_NAME","APPLOCK_MODE","APPLOCK_TEST","ASSEMBLYPROPERTY","COL_LENGTH","COL_NAME","COLUMNPROPERTY","DATABASEPROPERTYEX","DB_ID","DB_NAME","FILE_ID","FILE_IDEX","FILE_NAME","FILEGROUP_ID","FILEGROUP_NAME","FILEGROUPPROPERTY","FILEPROPERTY","FILEPROPERTYEX","FULLTEXTCATALOGPROPERTY","FULLTEXTSERVICEPROPERTY","INDEX_COL","INDEXKEY_PROPERTY","INDEXPROPERTY","NEXT VALUE FOR","OBJECT_DEFINITION","OBJECT_ID","OBJECT_NAME","OBJECT_SCHEMA_NAME","OBJECTPROPERTY","OBJECTPROPERTYEX","ORIGINAL_DB_NAME","PARSENAME","SCHEMA_ID","SCHEMA_NAME","SCOPE_IDENTITY","SERVERPROPERTY","STATS_DATE","TYPE_ID","TYPE_NAME","TYPEPROPERTY","DENSE_RANK","NTILE","RANK","ROW_NUMBER","PUBLISHINGSERVERNAME","CERTENCODED","CERTPRIVATEKEY","CURRENT_USER","DATABASE_PRINCIPAL_ID","HAS_DBACCESS","HAS_PERMS_BY_NAME","IS_MEMBER","IS_ROLEMEMBER","IS_SRVROLEMEMBER","LOGINPROPERTY","ORIGINAL_LOGIN","PERMISSIONS","PWDENCRYPT","PWDCOMPARE","SESSION_USER","SESSIONPROPERTY","SUSER_ID","SUSER_NAME","SUSER_SID","SUSER_SNAME","SYSTEM_USER","USER","USER_ID","USER_NAME","ASCII","CHARINDEX","CONCAT","CONCAT_WS","DIFFERENCE","FORMAT","LEFT","LEN","LOWER","LTRIM","PATINDEX","QUOTENAME","REPLACE","REPLICATE","REVERSE","RIGHT","RTRIM","SOUNDEX","SPACE","STR","STRING_AGG","STRING_ESCAPE","STUFF","SUBSTRING","TRANSLATE","TRIM","UNICODE","UPPER","$PARTITION","@@ERROR","@@IDENTITY","@@PACK_RECEIVED","@@ROWCOUNT","@@TRANCOUNT","BINARY_CHECKSUM","CHECKSUM","COMPRESS","CONNECTIONPROPERTY","CONTEXT_INFO","CURRENT_REQUEST_ID","CURRENT_TRANSACTION_ID","DECOMPRESS","ERROR_LINE","ERROR_MESSAGE","ERROR_NUMBER","ERROR_PROCEDURE","ERROR_SEVERITY","ERROR_STATE","FORMATMESSAGE","GET_FILESTREAM_TRANSACTION_CONTEXT","GETANSINULL","HOST_ID","HOST_NAME","ISNULL","ISNUMERIC","MIN_ACTIVE_ROWVERSION","NEWID","NEWSEQUENTIALID","ROWCOUNT_BIG","SESSION_CONTEXT","XACT_STATE","@@CONNECTIONS","@@CPU_BUSY","@@IDLE","@@IO_BUSY","@@PACK_SENT","@@PACKET_ERRORS","@@TIMETICKS","@@TOTAL_ERRORS","@@TOTAL_READ","@@TOTAL_WRITE","TEXTPTR","TEXTVALID","COLUMNS_UPDATED","EVENTDATA","TRIGGER_NESTLEVEL","UPDATE","COALESCE","NULLIF"],PY=["ADD","ALL","ALTER","AND","ANY","AS","ASC","AUTHORIZATION","BACKUP","BEGIN","BETWEEN","BREAK","BROWSE","BULK","BY","CASCADE","CHECK","CHECKPOINT","CLOSE","CLUSTERED","COALESCE","COLLATE","COLUMN","COMMIT","COMPUTE","CONSTRAINT","CONTAINS","CONTAINSTABLE","CONTINUE","CONVERT","CREATE","CROSS","CURRENT","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURSOR","DATABASE","DBCC","DEALLOCATE","DECLARE","DEFAULT","DELETE","DENY","DESC","DISK","DISTINCT","DISTRIBUTED","DROP","DUMP","ERRLVL","ESCAPE","EXEC","EXECUTE","EXISTS","EXIT","EXTERNAL","FETCH","FILE","FILLFACTOR","FOR","FOREIGN","FREETEXT","FREETEXTTABLE","FROM","FULL","FUNCTION","GOTO","GRANT","GROUP","HAVING","HOLDLOCK","IDENTITY","IDENTITYCOL","IDENTITY_INSERT","IF","IN","INDEX","INNER","INSERT","INTERSECT","INTO","IS","JOIN","KEY","KILL","LEFT","LIKE","LINENO","LOAD","MERGE","NOCHECK","NONCLUSTERED","NOT","NULL","NULLIF","OF","OFF","OFFSETS","ON","OPEN","OPENDATASOURCE","OPENQUERY","OPENROWSET","OPENXML","OPTION","OR","ORDER","OUTER","OVER","PERCENT","PIVOT","PLAN","PRIMARY","PRINT","PROC","PROCEDURE","PUBLIC","RAISERROR","READ","READTEXT","RECONFIGURE","REFERENCES","REPLICATION","RESTORE","RESTRICT","RETURN","REVERT","REVOKE","RIGHT","ROLLBACK","ROWCOUNT","ROWGUIDCOL","RULE","SAVE","SCHEMA","SECURITYAUDIT","SELECT","SEMANTICKEYPHRASETABLE","SEMANTICSIMILARITYDETAILSTABLE","SEMANTICSIMILARITYTABLE","SESSION_USER","SET","SETUSER","SHUTDOWN","SOME","STATISTICS","SYSTEM_USER","TABLE","TABLESAMPLE","TEXTSIZE","THEN","TO","TOP","TRAN","TRANSACTION","TRIGGER","TRUNCATE","TRY_CONVERT","TSEQUAL","UNION","UNIQUE","UNPIVOT","UPDATE","UPDATETEXT","USE","USER","VALUES","VIEW","WAITFOR","WHERE","WHILE","WITH","WITHIN GROUP","WRITETEXT","$ACTION"],wY=["BINARY","BIT","CHAR","CHAR","CHARACTER","DATE","DATETIME2","DATETIMEOFFSET","DEC","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","NATIONAL","NCHAR","NUMERIC","NVARCHAR","PRECISION","REAL","SMALLINT","TIME","TIMESTAMP","VARBINARY","VARCHAR"],UY=j(["SELECT [ALL | DISTINCT]"]),BY=j(["WITH","INTO","FROM","WHERE","GROUP BY","HAVING","WINDOW","PARTITION BY","ORDER BY","OFFSET","FETCH {FIRST | NEXT}","FOR {BROWSE | XML | JSON}","OPTION","INSERT [INTO]","VALUES","SET","MERGE [INTO]","WHEN [NOT] MATCHED [BY TARGET | BY SOURCE] [THEN]","UPDATE SET"]),yf=j(["CREATE TABLE"]),Ql=j(["CREATE [OR ALTER] [MATERIALIZED] VIEW","UPDATE","WHERE CURRENT OF","DELETE [FROM]","DROP TABLE [IF EXISTS]","ALTER TABLE","ADD","DROP COLUMN [IF EXISTS]","ALTER COLUMN","TRUNCATE TABLE","CREATE [UNIQUE] [CLUSTERED] INDEX","CREATE DATABASE","ALTER DATABASE","DROP DATABASE [IF EXISTS]","CREATE [OR ALTER] [PARTITION] {FUNCTION | PROCEDURE | PROC}","ALTER [PARTITION] {FUNCTION | PROCEDURE | PROC}","DROP [PARTITION] {FUNCTION | PROCEDURE | PROC} [IF EXISTS]","GO","USE","ADD SENSITIVITY CLASSIFICATION","ADD SIGNATURE","AGGREGATE","ANSI_DEFAULTS","ANSI_NULLS","ANSI_NULL_DFLT_OFF","ANSI_NULL_DFLT_ON","ANSI_PADDING","ANSI_WARNINGS","APPLICATION ROLE","ARITHABORT","ARITHIGNORE","ASSEMBLY","ASYMMETRIC KEY","AUTHORIZATION","AVAILABILITY GROUP","BACKUP","BACKUP CERTIFICATE","BACKUP MASTER KEY","BACKUP SERVICE MASTER KEY","BEGIN CONVERSATION TIMER","BEGIN DIALOG CONVERSATION","BROKER PRIORITY","BULK INSERT","CERTIFICATE","CLOSE MASTER KEY","CLOSE SYMMETRIC KEY","COLUMN ENCRYPTION KEY","COLUMN MASTER KEY","COLUMNSTORE INDEX","CONCAT_NULL_YIELDS_NULL","CONTEXT_INFO","CONTRACT","CREDENTIAL","CRYPTOGRAPHIC PROVIDER","CURSOR_CLOSE_ON_COMMIT","DATABASE","DATABASE AUDIT SPECIFICATION","DATABASE ENCRYPTION KEY","DATABASE HADR","DATABASE SCOPED CONFIGURATION","DATABASE SCOPED CREDENTIAL","DATABASE SET","DATEFIRST","DATEFORMAT","DEADLOCK_PRIORITY","DENY","DENY XML","DISABLE TRIGGER","ENABLE TRIGGER","END CONVERSATION","ENDPOINT","EVENT NOTIFICATION","EVENT SESSION","EXECUTE AS","EXTERNAL DATA SOURCE","EXTERNAL FILE FORMAT","EXTERNAL LANGUAGE","EXTERNAL LIBRARY","EXTERNAL RESOURCE POOL","EXTERNAL TABLE","FIPS_FLAGGER","FMTONLY","FORCEPLAN","FULLTEXT CATALOG","FULLTEXT INDEX","FULLTEXT STOPLIST","GET CONVERSATION GROUP","GET_TRANSMISSION_STATUS","GRANT","GRANT XML","IDENTITY_INSERT","IMPLICIT_TRANSACTIONS","INDEX","LANGUAGE","LOCK_TIMEOUT","LOGIN","MASTER KEY","MESSAGE TYPE","MOVE CONVERSATION","NOCOUNT","NOEXEC","NUMERIC_ROUNDABORT","OFFSETS","OPEN MASTER KEY","OPEN SYMMETRIC KEY","PARSEONLY","PARTITION SCHEME","QUERY_GOVERNOR_COST_LIMIT","QUEUE","QUOTED_IDENTIFIER","RECEIVE","REMOTE SERVICE BINDING","REMOTE_PROC_TRANSACTIONS","RESOURCE GOVERNOR","RESOURCE POOL","RESTORE","RESTORE FILELISTONLY","RESTORE HEADERONLY","RESTORE LABELONLY","RESTORE MASTER KEY","RESTORE REWINDONLY","RESTORE SERVICE MASTER KEY","RESTORE VERIFYONLY","REVERT","REVOKE","REVOKE XML","ROLE","ROUTE","ROWCOUNT","RULE","SCHEMA","SEARCH PROPERTY LIST","SECURITY POLICY","SELECTIVE XML INDEX","SEND","SENSITIVITY CLASSIFICATION","SEQUENCE","SERVER AUDIT","SERVER AUDIT SPECIFICATION","SERVER CONFIGURATION","SERVER ROLE","SERVICE","SERVICE MASTER KEY","SETUSER","SHOWPLAN_ALL","SHOWPLAN_TEXT","SHOWPLAN_XML","SIGNATURE","SPATIAL INDEX","STATISTICS","STATISTICS IO","STATISTICS PROFILE","STATISTICS TIME","STATISTICS XML","SYMMETRIC KEY","SYNONYM","TABLE","TABLE IDENTITY","TEXTSIZE","TRANSACTION ISOLATION LEVEL","TRIGGER","TYPE","UPDATE STATISTICS","USER","WORKLOAD GROUP","XACT_ABORT","XML INDEX","XML SCHEMA COLLECTION"]),FY=j(["UNION [ALL]","EXCEPT","INTERSECT"]),kY=j(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","{CROSS | OUTER} APPLY"]),jY=j(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),GY=j([]),HY={name:"transactsql",tokenizerOptions:{reservedSelect:UY,reservedClauses:[...BY,...yf,...Ql],reservedSetOperations:FY,reservedJoins:kY,reservedKeywordPhrases:jY,reservedDataTypePhrases:GY,reservedKeywords:PY,reservedDataTypes:wY,reservedFunctionNames:vY,nestedBlockComments:!0,stringTypes:[{quote:"''-qq",prefixes:["N"]},"{}"],identTypes:['""-qq',"[]"],identChars:{first:"#@",rest:"#@$"},paramTypes:{named:["@"],quoted:["@"]},operators:["%","&","|","^","~","!<","!>","+=","-=","*=","/=","%=","|=","&=","^=","::",":"],propertyAccessOperators:[".."]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...yf,...Ql],tabularOnelineClauses:Ql}},YY=["ADD","ALL","ALTER","ANALYZE","AND","AS","ASC","ASENSITIVE","BEFORE","BETWEEN","_BINARY","BOTH","BY","CALL","CASCADE","CASE","CHANGE","CHECK","COLLATE","COLUMN","CONDITION","CONSTRAINT","CONTINUE","CONVERT","CREATE","CROSS","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURSOR","DATABASE","DATABASES","DAY_HOUR","DAY_MICROSECOND","DAY_MINUTE","DAY_SECOND","DECLARE","DEFAULT","DELAYED","DELETE","DESC","DESCRIBE","DETERMINISTIC","DISTINCT","DISTINCTROW","DIV","DROP","DUAL","EACH","ELSE","ELSEIF","ENCLOSED","ESCAPED","EXCEPT","EXISTS","EXIT","EXPLAIN","EXTRA_JOIN","FALSE","FETCH","FOR","FORCE","FORCE_COMPILED_MODE","FORCE_INTERPRETER_MODE","FOREIGN","FROM","FULL","FULLTEXT","GRANT","GROUP","HAVING","HEARTBEAT_NO_LOGGING","HIGH_PRIORITY","HOUR_MICROSECOND","HOUR_MINUTE","HOUR_SECOND","IF","IGNORE","IN","INDEX","INFILE","INNER","INOUT","INSENSITIVE","INSERT","IN","_INTERNAL_DYNAMIC_TYPECAST","INTERSECT","INTERVAL","INTO","ITERATE","JOIN","KEY","KEYS","KILL","LEADING","LEAVE","LEFT","LIKE","LIMIT","LINES","LOAD","LOCALTIME","LOCALTIMESTAMP","LOCK","LOOP","LOW_PRIORITY","MATCH","MAXVALUE","MINUS","MINUTE_MICROSECOND","MINUTE_SECOND","MOD","MODIFIES","NATURAL","NO_QUERY_REWRITE","NOT","NO_WRITE_TO_BINLOG","NO_QUERY_REWRITE","NULL","ON","OPTIMIZE","OPTION","OPTIONALLY","OR","ORDER","OUT","OUTER","OUTFILE","OVER","PRIMARY","PROCEDURE","PURGE","RANGE","READ","READS","REFERENCES","REGEXP","RELEASE","RENAME","REPEAT","REPLACE","REQUIRE","RESTRICT","RETURN","REVOKE","RIGHT","RIGHT_ANTI_JOIN","RIGHT_SEMI_JOIN","RIGHT_STRAIGHT_JOIN","RLIKE","SCHEMA","SCHEMAS","SECOND_MICROSECOND","SELECT","SEMI_JOIN","SENSITIVE","SEPARATOR","SET","SHOW","SIGNAL","SPATIAL","SPECIFIC","SQL","SQL_BIG_RESULT","SQL_BUFFER_RESULT","SQL_CACHE","SQL_CALC_FOUND_ROWS","SQLEXCEPTION","SQL_NO_CACHE","SQL_NO_LOGGING","SQL_SMALL_RESULT","SQLSTATE","SQLWARNING","STRAIGHT_JOIN","TABLE","TERMINATED","THEN","TO","TRAILING","TRIGGER","TRUE","UNBOUNDED","UNDO","UNION","UNIQUE","UNLOCK","UPDATE","USAGE","USE","USING","UTC_DATE","UTC_TIME","UTC_TIMESTAMP","_UTF8","VALUES","WHEN","WHERE","WHILE","WINDOW","WITH","WITHIN","WRITE","XOR","YEAR_MONTH","ZEROFILL"],WY=["BIGINT","BINARY","BIT","BLOB","CHAR","CHARACTER","DATETIME","DEC","DECIMAL","DOUBLE PRECISION","DOUBLE","ENUM","FIXED","FLOAT","FLOAT4","FLOAT8","INT","INT1","INT2","INT3","INT4","INT8","INTEGER","LONG","LONGBLOB","LONGTEXT","MEDIUMBLOB","MEDIUMINT","MEDIUMTEXT","MIDDLEINT","NATIONAL CHAR","NATIONAL VARCHAR","NUMERIC","PRECISION","REAL","SMALLINT","TEXT","TIME","TIMESTAMP","TINYBLOB","TINYINT","TINYTEXT","UNSIGNED","VARBINARY","VARCHAR","VARCHARACTER","YEAR"],$Y=["ABS","ACOS","ADDDATE","ADDTIME","AES_DECRYPT","AES_ENCRYPT","ANY_VALUE","APPROX_COUNT_DISTINCT","APPROX_COUNT_DISTINCT_ACCUMULATE","APPROX_COUNT_DISTINCT_COMBINE","APPROX_COUNT_DISTINCT_ESTIMATE","APPROX_GEOGRAPHY_INTERSECTS","APPROX_PERCENTILE","ASCII","ASIN","ATAN","ATAN2","AVG","BIN","BINARY","BIT_AND","BIT_COUNT","BIT_OR","BIT_XOR","CAST","CEIL","CEILING","CHAR","CHARACTER_LENGTH","CHAR_LENGTH","CHARSET","COALESCE","COERCIBILITY","COLLATION","COLLECT","CONCAT","CONCAT_WS","CONNECTION_ID","CONV","CONVERT","CONVERT_TZ","COS","COT","COUNT","CUME_DIST","CURDATE","CURRENT_DATE","CURRENT_ROLE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","CURTIME","DATABASE","DATE","DATE_ADD","DATEDIFF","DATE_FORMAT","DATE_SUB","DATE_TRUNC","DAY","DAYNAME","DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","DECODE","DEFAULT","DEGREES","DENSE_RANK","DIV","DOT_PRODUCT","ELT","EUCLIDEAN_DISTANCE","EXP","EXTRACT","FIELD","FIRST","FIRST_VALUE","FLOOR","FORMAT","FOUND_ROWS","FROM_BASE64","FROM_DAYS","FROM_UNIXTIME","GEOGRAPHY_AREA","GEOGRAPHY_CONTAINS","GEOGRAPHY_DISTANCE","GEOGRAPHY_INTERSECTS","GEOGRAPHY_LATITUDE","GEOGRAPHY_LENGTH","GEOGRAPHY_LONGITUDE","GEOGRAPHY_POINT","GEOGRAPHY_WITHIN_DISTANCE","GEOMETRY_AREA","GEOMETRY_CONTAINS","GEOMETRY_DISTANCE","GEOMETRY_FILTER","GEOMETRY_INTERSECTS","GEOMETRY_LENGTH","GEOMETRY_POINT","GEOMETRY_WITHIN_DISTANCE","GEOMETRY_X","GEOMETRY_Y","GREATEST","GROUPING","GROUP_CONCAT","HEX","HIGHLIGHT","HOUR","ICU_VERSION","IF","IFNULL","INET_ATON","INET_NTOA","INET6_ATON","INET6_NTOA","INITCAP","INSERT","INSTR","INTERVAL","IS","IS NULL","JSON_AGG","JSON_ARRAY_CONTAINS_DOUBLE","JSON_ARRAY_CONTAINS_JSON","JSON_ARRAY_CONTAINS_STRING","JSON_ARRAY_PUSH_DOUBLE","JSON_ARRAY_PUSH_JSON","JSON_ARRAY_PUSH_STRING","JSON_DELETE_KEY","JSON_EXTRACT_DOUBLE","JSON_EXTRACT_JSON","JSON_EXTRACT_STRING","JSON_EXTRACT_BIGINT","JSON_GET_TYPE","JSON_LENGTH","JSON_SET_DOUBLE","JSON_SET_JSON","JSON_SET_STRING","JSON_SPLICE_DOUBLE","JSON_SPLICE_JSON","JSON_SPLICE_STRING","LAG","LAST_DAY","LAST_VALUE","LCASE","LEAD","LEAST","LEFT","LENGTH","LIKE","LN","LOCALTIME","LOCALTIMESTAMP","LOCATE","LOG","LOG10","LOG2","LPAD","LTRIM","MATCH","MAX","MD5","MEDIAN","MICROSECOND","MIN","MINUTE","MOD","MONTH","MONTHNAME","MONTHS_BETWEEN","NOT","NOW","NTH_VALUE","NTILE","NULLIF","OCTET_LENGTH","PERCENT_RANK","PERCENTILE_CONT","PERCENTILE_DISC","PI","PIVOT","POSITION","POW","POWER","QUARTER","QUOTE","RADIANS","RAND","RANK","REGEXP","REPEAT","REPLACE","REVERSE","RIGHT","RLIKE","ROUND","ROW_COUNT","ROW_NUMBER","RPAD","RTRIM","SCALAR","SCHEMA","SEC_TO_TIME","SHA1","SHA2","SIGMOID","SIGN","SIN","SLEEP","SPLIT","SOUNDEX","SOUNDS LIKE","SOURCE_POS_WAIT","SPACE","SQRT","STDDEV","STDDEV_POP","STDDEV_SAMP","STR_TO_DATE","SUBDATE","SUBSTR","SUBSTRING","SUBSTRING_INDEX","SUM","SYS_GUID","TAN","TIME","TIMEDIFF","TIME_BUCKET","TIME_FORMAT","TIMESTAMP","TIMESTAMPADD","TIMESTAMPDIFF","TIME_TO_SEC","TO_BASE64","TO_CHAR","TO_DAYS","TO_JSON","TO_NUMBER","TO_SECONDS","TO_TIMESTAMP","TRIM","TRUNC","TRUNCATE","UCASE","UNHEX","UNIX_TIMESTAMP","UPDATEXML","UPPER","UTC_DATE","UTC_TIME","UTC_TIMESTAMP","UUID","VALUES","VARIANCE","VAR_POP","VAR_SAMP","VECTOR_SUB","VERSION","WEEK","WEEKDAY","WEEKOFYEAR","YEAR"],VY=j(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),XY=j(["WITH","FROM","WHERE","GROUP BY","HAVING","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT [IGNORE] [INTO]","VALUES","REPLACE [INTO]","ON DUPLICATE KEY UPDATE","SET","CREATE [OR REPLACE] [TEMPORARY] PROCEDURE [IF NOT EXISTS]","CREATE [OR REPLACE] [EXTERNAL] FUNCTION"]),Cf=j(["CREATE [ROWSTORE] [REFERENCE | TEMPORARY | GLOBAL TEMPORARY] TABLE [IF NOT EXISTS]"]),Zl=j(["CREATE VIEW","UPDATE","DELETE [FROM]","DROP [TEMPORARY] TABLE [IF EXISTS]","ALTER [ONLINE] TABLE","ADD [COLUMN]","ADD [UNIQUE] {INDEX | KEY}","DROP [COLUMN]","MODIFY [COLUMN]","CHANGE","RENAME [TO | AS]","TRUNCATE [TABLE]","ADD AGGREGATOR","ADD LEAF","AGGREGATOR SET AS MASTER","ALTER DATABASE","ALTER PIPELINE","ALTER RESOURCE POOL","ALTER USER","ALTER VIEW","ANALYZE TABLE","ATTACH DATABASE","ATTACH LEAF","ATTACH LEAF ALL","BACKUP DATABASE","BINLOG","BOOTSTRAP AGGREGATOR","CACHE INDEX","CALL","CHANGE","CHANGE MASTER TO","CHANGE REPLICATION FILTER","CHANGE REPLICATION SOURCE TO","CHECK BLOB CHECKSUM","CHECK TABLE","CHECKSUM TABLE","CLEAR ORPHAN DATABASES","CLONE","COMMIT","CREATE DATABASE","CREATE GROUP","CREATE INDEX","CREATE LINK","CREATE MILESTONE","CREATE PIPELINE","CREATE RESOURCE POOL","CREATE ROLE","CREATE USER","DEALLOCATE PREPARE","DESCRIBE","DETACH DATABASE","DETACH PIPELINE","DROP DATABASE","DROP FUNCTION","DROP INDEX","DROP LINK","DROP PIPELINE","DROP PROCEDURE","DROP RESOURCE POOL","DROP ROLE","DROP USER","DROP VIEW","EXECUTE","EXPLAIN","FLUSH","FORCE","GRANT","HANDLER","HELP","KILL CONNECTION","KILLALL QUERIES","LOAD DATA","LOAD INDEX INTO CACHE","LOAD XML","LOCK INSTANCE FOR BACKUP","LOCK TABLES","MASTER_POS_WAIT","OPTIMIZE TABLE","PREPARE","PURGE BINARY LOGS","REBALANCE PARTITIONS","RELEASE SAVEPOINT","REMOVE AGGREGATOR","REMOVE LEAF","REPAIR TABLE","REPLACE","REPLICATE DATABASE","RESET","RESET MASTER","RESET PERSIST","RESET REPLICA","RESET SLAVE","RESTART","RESTORE DATABASE","RESTORE REDUNDANCY","REVOKE","ROLLBACK","ROLLBACK TO SAVEPOINT","SAVEPOINT","SET CHARACTER SET","SET DEFAULT ROLE","SET NAMES","SET PASSWORD","SET RESOURCE GROUP","SET ROLE","SET TRANSACTION","SHOW","SHOW CHARACTER SET","SHOW COLLATION","SHOW COLUMNS","SHOW CREATE DATABASE","SHOW CREATE FUNCTION","SHOW CREATE PIPELINE","SHOW CREATE PROCEDURE","SHOW CREATE TABLE","SHOW CREATE USER","SHOW CREATE VIEW","SHOW DATABASES","SHOW ENGINE","SHOW ENGINES","SHOW ERRORS","SHOW FUNCTION CODE","SHOW FUNCTION STATUS","SHOW GRANTS","SHOW INDEX","SHOW MASTER STATUS","SHOW OPEN TABLES","SHOW PLUGINS","SHOW PRIVILEGES","SHOW PROCEDURE CODE","SHOW PROCEDURE STATUS","SHOW PROCESSLIST","SHOW PROFILE","SHOW PROFILES","SHOW RELAYLOG EVENTS","SHOW REPLICA STATUS","SHOW REPLICAS","SHOW SLAVE","SHOW SLAVE HOSTS","SHOW STATUS","SHOW TABLE STATUS","SHOW TABLES","SHOW VARIABLES","SHOW WARNINGS","SHUTDOWN","SNAPSHOT DATABASE","SOURCE_POS_WAIT","START GROUP_REPLICATION","START PIPELINE","START REPLICA","START SLAVE","START TRANSACTION","STOP GROUP_REPLICATION","STOP PIPELINE","STOP REPLICA","STOP REPLICATING","STOP SLAVE","TEST PIPELINE","UNLOCK INSTANCE","UNLOCK TABLES","USE","XA","ITERATE","LEAVE","LOOP","REPEAT","RETURN","WHILE"]),zY=j(["UNION [ALL | DISTINCT]","EXCEPT","INTERSECT","MINUS"]),KY=j(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),qY=j(["ON DELETE","ON UPDATE","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),JY=j([]),QY={name:"singlestoredb",tokenizerOptions:{reservedSelect:VY,reservedClauses:[...XY,...Cf,...Zl],reservedSetOperations:zY,reservedJoins:KY,reservedKeywordPhrases:qY,reservedDataTypePhrases:JY,reservedKeywords:YY,reservedDataTypes:WY,reservedFunctionNames:$Y,stringTypes:['""-qq-bs',"''-qq-bs",{quote:"''-raw",prefixes:["B","X"],requirePrefix:!0}],identTypes:["``"],identChars:{first:"$",rest:"$",allowFirstCharNumber:!0},variableTypes:[{regex:"@@?[A-Za-z0-9_$]+"},{quote:"``",prefixes:["@"],requirePrefix:!0}],lineCommentTypes:["--","#"],operators:[":=","&","|","^","~","<<",">>","<=>","&&","||","::","::$","::%",":>","!:>","*.*"],postProcess:_a},formatOptions:{alwaysDenseOperators:["::","::$","::%"],onelineClauses:[...Cf,...Zl],tabularOnelineClauses:Zl}},ZY=["ABS","ACOS","ACOSH","ADD_MONTHS","ALL_USER_NAMES","ANY_VALUE","APPROX_COUNT_DISTINCT","APPROX_PERCENTILE","APPROX_PERCENTILE_ACCUMULATE","APPROX_PERCENTILE_COMBINE","APPROX_PERCENTILE_ESTIMATE","APPROX_TOP_K","APPROX_TOP_K_ACCUMULATE","APPROX_TOP_K_COMBINE","APPROX_TOP_K_ESTIMATE","APPROXIMATE_JACCARD_INDEX","APPROXIMATE_SIMILARITY","ARRAY_AGG","ARRAY_APPEND","ARRAY_CAT","ARRAY_COMPACT","ARRAY_CONSTRUCT","ARRAY_CONSTRUCT_COMPACT","ARRAY_CONTAINS","ARRAY_INSERT","ARRAY_INTERSECTION","ARRAY_POSITION","ARRAY_PREPEND","ARRAY_SIZE","ARRAY_SLICE","ARRAY_TO_STRING","ARRAY_UNION_AGG","ARRAY_UNIQUE_AGG","ARRAYS_OVERLAP","AS_ARRAY","AS_BINARY","AS_BOOLEAN","AS_CHAR","AS_VARCHAR","AS_DATE","AS_DECIMAL","AS_NUMBER","AS_DOUBLE","AS_REAL","AS_INTEGER","AS_OBJECT","AS_TIME","AS_TIMESTAMP_LTZ","AS_TIMESTAMP_NTZ","AS_TIMESTAMP_TZ","ASCII","ASIN","ASINH","ATAN","ATAN2","ATANH","AUTO_REFRESH_REGISTRATION_HISTORY","AUTOMATIC_CLUSTERING_HISTORY","AVG","BASE64_DECODE_BINARY","BASE64_DECODE_STRING","BASE64_ENCODE","BIT_LENGTH","BITAND","BITAND_AGG","BITMAP_BIT_POSITION","BITMAP_BUCKET_NUMBER","BITMAP_CONSTRUCT_AGG","BITMAP_COUNT","BITMAP_OR_AGG","BITNOT","BITOR","BITOR_AGG","BITSHIFTLEFT","BITSHIFTRIGHT","BITXOR","BITXOR_AGG","BOOLAND","BOOLAND_AGG","BOOLNOT","BOOLOR","BOOLOR_AGG","BOOLXOR","BOOLXOR_AGG","BUILD_SCOPED_FILE_URL","BUILD_STAGE_FILE_URL","CASE","CAST","CBRT","CEIL","CHARINDEX","CHECK_JSON","CHECK_XML","CHR","CHAR","COALESCE","COLLATE","COLLATION","COMPLETE_TASK_GRAPHS","COMPRESS","CONCAT","CONCAT_WS","CONDITIONAL_CHANGE_EVENT","CONDITIONAL_TRUE_EVENT","CONTAINS","CONVERT_TIMEZONE","COPY_HISTORY","CORR","COS","COSH","COT","COUNT","COUNT_IF","COVAR_POP","COVAR_SAMP","CUME_DIST","CURRENT_ACCOUNT","CURRENT_AVAILABLE_ROLES","CURRENT_CLIENT","CURRENT_DATABASE","CURRENT_DATE","CURRENT_IP_ADDRESS","CURRENT_REGION","CURRENT_ROLE","CURRENT_SCHEMA","CURRENT_SCHEMAS","CURRENT_SECONDARY_ROLES","CURRENT_SESSION","CURRENT_STATEMENT","CURRENT_TASK_GRAPHS","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_TRANSACTION","CURRENT_USER","CURRENT_VERSION","CURRENT_WAREHOUSE","DATA_TRANSFER_HISTORY","DATABASE_REFRESH_HISTORY","DATABASE_REFRESH_PROGRESS","DATABASE_REFRESH_PROGRESS_BY_JOB","DATABASE_STORAGE_USAGE_HISTORY","DATE_FROM_PARTS","DATE_PART","DATE_TRUNC","DATEADD","DATEDIFF","DAYNAME","DECODE","DECOMPRESS_BINARY","DECOMPRESS_STRING","DECRYPT","DECRYPT_RAW","DEGREES","DENSE_RANK","DIV0","EDITDISTANCE","ENCRYPT","ENCRYPT_RAW","ENDSWITH","EQUAL_NULL","EXP","EXPLAIN_JSON","EXTERNAL_FUNCTIONS_HISTORY","EXTERNAL_TABLE_FILES","EXTERNAL_TABLE_FILE_REGISTRATION_HISTORY","EXTRACT","EXTRACT_SEMANTIC_CATEGORIES","FACTORIAL","FILTER","FIRST_VALUE","FLATTEN","FLOOR","GENERATE_COLUMN_DESCRIPTION","GENERATOR","GET","GET_ABSOLUTE_PATH","GET_DDL","GET_IGNORE_CASE","GET_OBJECT_REFERENCES","GET_PATH","GET_PRESIGNED_URL","GET_RELATIVE_PATH","GET_STAGE_LOCATION","GETBIT","GREATEST","GREATEST_IGNORE_NULLS","GROUPING","GROUPING_ID","HASH","HASH_AGG","HAVERSINE","HEX_DECODE_BINARY","HEX_DECODE_STRING","HEX_ENCODE","HLL","HLL_ACCUMULATE","HLL_COMBINE","HLL_ESTIMATE","HLL_EXPORT","HLL_IMPORT","HOUR","MINUTE","SECOND","IDENTIFIER","IFF","IFNULL","ILIKE","ILIKE ANY","INFER_SCHEMA","INITCAP","INSERT","INVOKER_ROLE","INVOKER_SHARE","IS_ARRAY","IS_BINARY","IS_BOOLEAN","IS_CHAR","IS_VARCHAR","IS_DATE","IS_DATE_VALUE","IS_DECIMAL","IS_DOUBLE","IS_REAL","IS_GRANTED_TO_INVOKER_ROLE","IS_INTEGER","IS_NULL_VALUE","IS_OBJECT","IS_ROLE_IN_SESSION","IS_TIME","IS_TIMESTAMP_LTZ","IS_TIMESTAMP_NTZ","IS_TIMESTAMP_TZ","JAROWINKLER_SIMILARITY","JSON_EXTRACT_PATH_TEXT","KURTOSIS","LAG","LAST_DAY","LAST_QUERY_ID","LAST_TRANSACTION","LAST_VALUE","LEAD","LEAST","LEFT","LENGTH","LEN","LIKE","LIKE ALL","LIKE ANY","LISTAGG","LN","LOCALTIME","LOCALTIMESTAMP","LOG","LOGIN_HISTORY","LOGIN_HISTORY_BY_USER","LOWER","LPAD","LTRIM","MATERIALIZED_VIEW_REFRESH_HISTORY","MD5","MD5_HEX","MD5_BINARY","MD5_NUMBER — Obsoleted","MD5_NUMBER_LOWER64","MD5_NUMBER_UPPER64","MEDIAN","MIN","MAX","MINHASH","MINHASH_COMBINE","MOD","MODE","MONTHNAME","MONTHS_BETWEEN","NEXT_DAY","NORMAL","NTH_VALUE","NTILE","NULLIF","NULLIFZERO","NVL","NVL2","OBJECT_AGG","OBJECT_CONSTRUCT","OBJECT_CONSTRUCT_KEEP_NULL","OBJECT_DELETE","OBJECT_INSERT","OBJECT_KEYS","OBJECT_PICK","OCTET_LENGTH","PARSE_IP","PARSE_JSON","PARSE_URL","PARSE_XML","PERCENT_RANK","PERCENTILE_CONT","PERCENTILE_DISC","PI","PIPE_USAGE_HISTORY","POLICY_CONTEXT","POLICY_REFERENCES","POSITION","POW","POWER","PREVIOUS_DAY","QUERY_ACCELERATION_HISTORY","QUERY_HISTORY","QUERY_HISTORY_BY_SESSION","QUERY_HISTORY_BY_USER","QUERY_HISTORY_BY_WAREHOUSE","RADIANS","RANDOM","RANDSTR","RANK","RATIO_TO_REPORT","REGEXP","REGEXP_COUNT","REGEXP_INSTR","REGEXP_LIKE","REGEXP_REPLACE","REGEXP_SUBSTR","REGEXP_SUBSTR_ALL","REGR_AVGX","REGR_AVGY","REGR_COUNT","REGR_INTERCEPT","REGR_R2","REGR_SLOPE","REGR_SXX","REGR_SXY","REGR_SYY","REGR_VALX","REGR_VALY","REPEAT","REPLACE","REPLICATION_GROUP_REFRESH_HISTORY","REPLICATION_GROUP_REFRESH_PROGRESS","REPLICATION_GROUP_REFRESH_PROGRESS_BY_JOB","REPLICATION_GROUP_USAGE_HISTORY","REPLICATION_USAGE_HISTORY","REST_EVENT_HISTORY","RESULT_SCAN","REVERSE","RIGHT","RLIKE","ROUND","ROW_NUMBER","RPAD","RTRIM","RTRIMMED_LENGTH","SEARCH_OPTIMIZATION_HISTORY","SEQ1","SEQ2","SEQ4","SEQ8","SERVERLESS_TASK_HISTORY","SHA1","SHA1_HEX","SHA1_BINARY","SHA2","SHA2_HEX","SHA2_BINARY","SIGN","SIN","SINH","SKEW","SOUNDEX","SPACE","SPLIT","SPLIT_PART","SPLIT_TO_TABLE","SQRT","SQUARE","ST_AREA","ST_ASEWKB","ST_ASEWKT","ST_ASGEOJSON","ST_ASWKB","ST_ASBINARY","ST_ASWKT","ST_ASTEXT","ST_AZIMUTH","ST_CENTROID","ST_COLLECT","ST_CONTAINS","ST_COVEREDBY","ST_COVERS","ST_DIFFERENCE","ST_DIMENSION","ST_DISJOINT","ST_DISTANCE","ST_DWITHIN","ST_ENDPOINT","ST_ENVELOPE","ST_GEOGFROMGEOHASH","ST_GEOGPOINTFROMGEOHASH","ST_GEOGRAPHYFROMWKB","ST_GEOGRAPHYFROMWKT","ST_GEOHASH","ST_GEOMETRYFROMWKB","ST_GEOMETRYFROMWKT","ST_HAUSDORFFDISTANCE","ST_INTERSECTION","ST_INTERSECTS","ST_LENGTH","ST_MAKEGEOMPOINT","ST_GEOM_POINT","ST_MAKELINE","ST_MAKEPOINT","ST_POINT","ST_MAKEPOLYGON","ST_POLYGON","ST_NPOINTS","ST_NUMPOINTS","ST_PERIMETER","ST_POINTN","ST_SETSRID","ST_SIMPLIFY","ST_SRID","ST_STARTPOINT","ST_SYMDIFFERENCE","ST_UNION","ST_WITHIN","ST_X","ST_XMAX","ST_XMIN","ST_Y","ST_YMAX","ST_YMIN","STAGE_DIRECTORY_FILE_REGISTRATION_HISTORY","STAGE_STORAGE_USAGE_HISTORY","STARTSWITH","STDDEV","STDDEV_POP","STDDEV_SAMP","STRIP_NULL_VALUE","STRTOK","STRTOK_SPLIT_TO_TABLE","STRTOK_TO_ARRAY","SUBSTR","SUBSTRING","SUM","SYSDATE","SYSTEM$ABORT_SESSION","SYSTEM$ABORT_TRANSACTION","SYSTEM$AUTHORIZE_PRIVATELINK","SYSTEM$AUTHORIZE_STAGE_PRIVATELINK_ACCESS","SYSTEM$BEHAVIOR_CHANGE_BUNDLE_STATUS","SYSTEM$CANCEL_ALL_QUERIES","SYSTEM$CANCEL_QUERY","SYSTEM$CLUSTERING_DEPTH","SYSTEM$CLUSTERING_INFORMATION","SYSTEM$CLUSTERING_RATIO ","SYSTEM$CURRENT_USER_TASK_NAME","SYSTEM$DATABASE_REFRESH_HISTORY ","SYSTEM$DATABASE_REFRESH_PROGRESS","SYSTEM$DATABASE_REFRESH_PROGRESS_BY_JOB ","SYSTEM$DISABLE_BEHAVIOR_CHANGE_BUNDLE","SYSTEM$DISABLE_DATABASE_REPLICATION","SYSTEM$ENABLE_BEHAVIOR_CHANGE_BUNDLE","SYSTEM$ESTIMATE_QUERY_ACCELERATION","SYSTEM$ESTIMATE_SEARCH_OPTIMIZATION_COSTS","SYSTEM$EXPLAIN_JSON_TO_TEXT","SYSTEM$EXPLAIN_PLAN_JSON","SYSTEM$EXTERNAL_TABLE_PIPE_STATUS","SYSTEM$GENERATE_SAML_CSR","SYSTEM$GENERATE_SCIM_ACCESS_TOKEN","SYSTEM$GET_AWS_SNS_IAM_POLICY","SYSTEM$GET_PREDECESSOR_RETURN_VALUE","SYSTEM$GET_PRIVATELINK","SYSTEM$GET_PRIVATELINK_AUTHORIZED_ENDPOINTS","SYSTEM$GET_PRIVATELINK_CONFIG","SYSTEM$GET_SNOWFLAKE_PLATFORM_INFO","SYSTEM$GET_TAG","SYSTEM$GET_TAG_ALLOWED_VALUES","SYSTEM$GET_TAG_ON_CURRENT_COLUMN","SYSTEM$GET_TAG_ON_CURRENT_TABLE","SYSTEM$GLOBAL_ACCOUNT_SET_PARAMETER","SYSTEM$LAST_CHANGE_COMMIT_TIME","SYSTEM$LINK_ACCOUNT_OBJECTS_BY_NAME","SYSTEM$MIGRATE_SAML_IDP_REGISTRATION","SYSTEM$PIPE_FORCE_RESUME","SYSTEM$PIPE_STATUS","SYSTEM$REVOKE_PRIVATELINK","SYSTEM$REVOKE_STAGE_PRIVATELINK_ACCESS","SYSTEM$SET_RETURN_VALUE","SYSTEM$SHOW_OAUTH_CLIENT_SECRETS","SYSTEM$STREAM_GET_TABLE_TIMESTAMP","SYSTEM$STREAM_HAS_DATA","SYSTEM$TASK_DEPENDENTS_ENABLE","SYSTEM$TYPEOF","SYSTEM$USER_TASK_CANCEL_ONGOING_EXECUTIONS","SYSTEM$VERIFY_EXTERNAL_OAUTH_TOKEN","SYSTEM$WAIT","SYSTEM$WHITELIST","SYSTEM$WHITELIST_PRIVATELINK","TAG_REFERENCES","TAG_REFERENCES_ALL_COLUMNS","TAG_REFERENCES_WITH_LINEAGE","TAN","TANH","TASK_DEPENDENTS","TASK_HISTORY","TIME_FROM_PARTS","TIME_SLICE","TIMEADD","TIMEDIFF","TIMESTAMP_FROM_PARTS","TIMESTAMPADD","TIMESTAMPDIFF","TO_ARRAY","TO_BINARY","TO_BOOLEAN","TO_CHAR","TO_VARCHAR","TO_DATE","DATE","TO_DECIMAL","TO_NUMBER","TO_NUMERIC","TO_DOUBLE","TO_GEOGRAPHY","TO_GEOMETRY","TO_JSON","TO_OBJECT","TO_TIME","TIME","TO_TIMESTAMP","TO_TIMESTAMP_LTZ","TO_TIMESTAMP_NTZ","TO_TIMESTAMP_TZ","TO_VARIANT","TO_XML","TRANSLATE","TRIM","TRUNCATE","TRUNC","TRUNC","TRY_BASE64_DECODE_BINARY","TRY_BASE64_DECODE_STRING","TRY_CAST","TRY_HEX_DECODE_BINARY","TRY_HEX_DECODE_STRING","TRY_PARSE_JSON","TRY_TO_BINARY","TRY_TO_BOOLEAN","TRY_TO_DATE","TRY_TO_DECIMAL","TRY_TO_NUMBER","TRY_TO_NUMERIC","TRY_TO_DOUBLE","TRY_TO_GEOGRAPHY","TRY_TO_GEOMETRY","TRY_TO_TIME","TRY_TO_TIMESTAMP","TRY_TO_TIMESTAMP_LTZ","TRY_TO_TIMESTAMP_NTZ","TRY_TO_TIMESTAMP_TZ","TYPEOF","UNICODE","UNIFORM","UPPER","UUID_STRING","VALIDATE","VALIDATE_PIPE_LOAD","VAR_POP","VAR_SAMP","VARIANCE","VARIANCE_SAMP","VARIANCE_POP","WAREHOUSE_LOAD_HISTORY","WAREHOUSE_METERING_HISTORY","WIDTH_BUCKET","XMLGET","YEAR","YEAROFWEEK","YEAROFWEEKISO","DAY","DAYOFMONTH","DAYOFWEEK","DAYOFWEEKISO","DAYOFYEAR","WEEK","WEEK","WEEKOFYEAR","WEEKISO","MONTH","QUARTER","ZEROIFNULL","ZIPF"],eW=["ACCOUNT","ALL","ALTER","AND","ANY","AS","BETWEEN","BY","CASE","CAST","CHECK","COLUMN","CONNECT","CONNECTION","CONSTRAINT","CREATE","CROSS","CURRENT","CURRENT_DATE","CURRENT_TIME","CURRENT_TIMESTAMP","CURRENT_USER","DATABASE","DELETE","DISTINCT","DROP","ELSE","EXISTS","FALSE","FOLLOWING","FOR","FROM","FULL","GRANT","GROUP","GSCLUSTER","HAVING","ILIKE","IN","INCREMENT","INNER","INSERT","INTERSECT","INTO","IS","ISSUE","JOIN","LATERAL","LEFT","LIKE","LOCALTIME","LOCALTIMESTAMP","MINUS","NATURAL","NOT","NULL","OF","ON","OR","ORDER","ORGANIZATION","QUALIFY","REGEXP","REVOKE","RIGHT","RLIKE","ROW","ROWS","SAMPLE","SCHEMA","SELECT","SET","SOME","START","TABLE","TABLESAMPLE","THEN","TO","TRIGGER","TRUE","TRY_CAST","UNION","UNIQUE","UPDATE","USING","VALUES","VIEW","WHEN","WHENEVER","WHERE","WITH","COMMENT"],tW=["NUMBER","DECIMAL","NUMERIC","INT","INTEGER","BIGINT","SMALLINT","TINYINT","BYTEINT","FLOAT","FLOAT4","FLOAT8","DOUBLE","DOUBLE PRECISION","REAL","VARCHAR","CHAR","CHARACTER","STRING","TEXT","BINARY","VARBINARY","BOOLEAN","DATE","DATETIME","TIME","TIMESTAMP","TIMESTAMP_LTZ","TIMESTAMP_NTZ","TIMESTAMP","TIMESTAMP_TZ","VARIANT","OBJECT","ARRAY","GEOGRAPHY","GEOMETRY"],nW=j(["SELECT [ALL | DISTINCT]"]),rW=j(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","PARTITION BY","ORDER BY","QUALIFY","LIMIT","OFFSET","FETCH [FIRST | NEXT]","INSERT [OVERWRITE] [ALL INTO | INTO | ALL | FIRST]","{THEN | ELSE} INTO","VALUES","SET","CLUSTER BY","[WITH] {MASKING POLICY | TAG | ROW ACCESS POLICY}","COPY GRANTS","USING TEMPLATE","MERGE INTO","WHEN MATCHED [AND]","THEN {UPDATE SET | DELETE}","WHEN NOT MATCHED THEN INSERT"]),Lf=j(["CREATE [OR REPLACE] [VOLATILE] TABLE [IF NOT EXISTS]","CREATE [OR REPLACE] [LOCAL | GLOBAL] {TEMP|TEMPORARY} TABLE [IF NOT EXISTS]"]),ec=j(["CREATE [OR REPLACE] [SECURE] [RECURSIVE] VIEW [IF NOT EXISTS]","UPDATE","DELETE FROM","DROP TABLE [IF EXISTS]","ALTER TABLE [IF EXISTS]","RENAME TO","SWAP WITH","[SUSPEND | RESUME] RECLUSTER","DROP CLUSTERING KEY","ADD [COLUMN]","RENAME COLUMN","{ALTER | MODIFY} [COLUMN]","DROP [COLUMN]","{ADD | ALTER | MODIFY | DROP} [CONSTRAINT]","RENAME CONSTRAINT","{ADD | DROP} SEARCH OPTIMIZATION","{SET | UNSET} TAG","{ADD | DROP} ROW ACCESS POLICY","DROP ALL ROW ACCESS POLICIES","{SET | DROP} DEFAULT","{SET | DROP} NOT NULL","SET DATA TYPE","UNSET COMMENT","{SET | UNSET} MASKING POLICY","TRUNCATE [TABLE] [IF EXISTS]","ALTER ACCOUNT","ALTER API INTEGRATION","ALTER CONNECTION","ALTER DATABASE","ALTER EXTERNAL TABLE","ALTER FAILOVER GROUP","ALTER FILE FORMAT","ALTER FUNCTION","ALTER INTEGRATION","ALTER MASKING POLICY","ALTER MATERIALIZED VIEW","ALTER NETWORK POLICY","ALTER NOTIFICATION INTEGRATION","ALTER PIPE","ALTER PROCEDURE","ALTER REPLICATION GROUP","ALTER RESOURCE MONITOR","ALTER ROLE","ALTER ROW ACCESS POLICY","ALTER SCHEMA","ALTER SECURITY INTEGRATION","ALTER SEQUENCE","ALTER SESSION","ALTER SESSION POLICY","ALTER SHARE","ALTER STAGE","ALTER STORAGE INTEGRATION","ALTER STREAM","ALTER TAG","ALTER TASK","ALTER USER","ALTER VIEW","ALTER WAREHOUSE","BEGIN","CALL","COMMIT","COPY INTO","CREATE ACCOUNT","CREATE API INTEGRATION","CREATE CONNECTION","CREATE DATABASE","CREATE EXTERNAL FUNCTION","CREATE EXTERNAL TABLE","CREATE FAILOVER GROUP","CREATE FILE FORMAT","CREATE FUNCTION","CREATE INTEGRATION","CREATE MANAGED ACCOUNT","CREATE MASKING POLICY","CREATE MATERIALIZED VIEW","CREATE NETWORK POLICY","CREATE NOTIFICATION INTEGRATION","CREATE PIPE","CREATE PROCEDURE","CREATE REPLICATION GROUP","CREATE RESOURCE MONITOR","CREATE ROLE","CREATE ROW ACCESS POLICY","CREATE SCHEMA","CREATE SECURITY INTEGRATION","CREATE SEQUENCE","CREATE SESSION POLICY","CREATE SHARE","CREATE STAGE","CREATE STORAGE INTEGRATION","CREATE STREAM","CREATE TAG","CREATE TASK","CREATE USER","CREATE WAREHOUSE","DELETE","DESCRIBE DATABASE","DESCRIBE EXTERNAL TABLE","DESCRIBE FILE FORMAT","DESCRIBE FUNCTION","DESCRIBE INTEGRATION","DESCRIBE MASKING POLICY","DESCRIBE MATERIALIZED VIEW","DESCRIBE NETWORK POLICY","DESCRIBE PIPE","DESCRIBE PROCEDURE","DESCRIBE RESULT","DESCRIBE ROW ACCESS POLICY","DESCRIBE SCHEMA","DESCRIBE SEQUENCE","DESCRIBE SESSION POLICY","DESCRIBE SHARE","DESCRIBE STAGE","DESCRIBE STREAM","DESCRIBE TABLE","DESCRIBE TASK","DESCRIBE TRANSACTION","DESCRIBE USER","DESCRIBE VIEW","DESCRIBE WAREHOUSE","DROP CONNECTION","DROP DATABASE","DROP EXTERNAL TABLE","DROP FAILOVER GROUP","DROP FILE FORMAT","DROP FUNCTION","DROP INTEGRATION","DROP MANAGED ACCOUNT","DROP MASKING POLICY","DROP MATERIALIZED VIEW","DROP NETWORK POLICY","DROP PIPE","DROP PROCEDURE","DROP REPLICATION GROUP","DROP RESOURCE MONITOR","DROP ROLE","DROP ROW ACCESS POLICY","DROP SCHEMA","DROP SEQUENCE","DROP SESSION POLICY","DROP SHARE","DROP STAGE","DROP STREAM","DROP TAG","DROP TASK","DROP USER","DROP VIEW","DROP WAREHOUSE","EXECUTE IMMEDIATE","EXECUTE TASK","EXPLAIN","GET","GRANT OWNERSHIP","GRANT ROLE","INSERT","LIST","MERGE","PUT","REMOVE","REVOKE ROLE","ROLLBACK","SHOW COLUMNS","SHOW CONNECTIONS","SHOW DATABASES","SHOW DATABASES IN FAILOVER GROUP","SHOW DATABASES IN REPLICATION GROUP","SHOW DELEGATED AUTHORIZATIONS","SHOW EXTERNAL FUNCTIONS","SHOW EXTERNAL TABLES","SHOW FAILOVER GROUPS","SHOW FILE FORMATS","SHOW FUNCTIONS","SHOW GLOBAL ACCOUNTS","SHOW GRANTS","SHOW INTEGRATIONS","SHOW LOCKS","SHOW MANAGED ACCOUNTS","SHOW MASKING POLICIES","SHOW MATERIALIZED VIEWS","SHOW NETWORK POLICIES","SHOW OBJECTS","SHOW ORGANIZATION ACCOUNTS","SHOW PARAMETERS","SHOW PIPES","SHOW PRIMARY KEYS","SHOW PROCEDURES","SHOW REGIONS","SHOW REPLICATION ACCOUNTS","SHOW REPLICATION DATABASES","SHOW REPLICATION GROUPS","SHOW RESOURCE MONITORS","SHOW ROLES","SHOW ROW ACCESS POLICIES","SHOW SCHEMAS","SHOW SEQUENCES","SHOW SESSION POLICIES","SHOW SHARES","SHOW SHARES IN FAILOVER GROUP","SHOW SHARES IN REPLICATION GROUP","SHOW STAGES","SHOW STREAMS","SHOW TABLES","SHOW TAGS","SHOW TASKS","SHOW TRANSACTIONS","SHOW USER FUNCTIONS","SHOW USERS","SHOW VARIABLES","SHOW VIEWS","SHOW WAREHOUSES","TRUNCATE MATERIALIZED VIEW","UNDROP DATABASE","UNDROP SCHEMA","UNDROP TABLE","UNDROP TAG","UNSET","USE DATABASE","USE ROLE","USE SCHEMA","USE SECONDARY ROLES","USE WAREHOUSE"]),oW=j(["UNION [ALL]","MINUS","EXCEPT","INTERSECT"]),sW=j(["[INNER] JOIN","[NATURAL] {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | NATURAL} JOIN"]),iW=j(["{ROWS | RANGE} BETWEEN","ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]"]),aW=j([]),lW={name:"snowflake",tokenizerOptions:{reservedSelect:nW,reservedClauses:[...rW,...Lf,...ec],reservedSetOperations:oW,reservedJoins:sW,reservedKeywordPhrases:iW,reservedDataTypePhrases:aW,reservedKeywords:eW,reservedDataTypes:tW,reservedFunctionNames:ZY,stringTypes:["$$","''-qq-bs"],identTypes:['""-qq'],variableTypes:[{regex:"[$][1-9]\\d*"},{regex:"[$][_a-zA-Z][_a-zA-Z0-9$]*"}],extraParens:["[]"],identChars:{rest:"$"},lineCommentTypes:["--","//"],operators:["%","::","||","=>",":=","->"],propertyAccessOperators:[":"]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...Lf,...ec],tabularOnelineClauses:ec}},cW=Object.freeze(Object.defineProperty({__proto__:null,bigquery:Lj,clickhouse:Gj,db2:Qj,db2i:lG,duckdb:hG,hive:LG,mariadb:FG,mysql:zG,n1ql:fH,plsql:gH,postgresql:wH,redshift:$H,singlestoredb:QY,snowflake:lW,spark:tY,sql:OY,sqlite:uY,tidb:oH,transactsql:HY,trino:MY},Symbol.toStringTag,{value:"Module"})),To=e=>e[e.length-1],FI=e=>e.sort((t,n)=>n.length-t.length||t.localeCompare(n)),ii=e=>e.replace(/\s+/gu," "),tc=e=>/\n/.test(e),pt=e=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),_f=/\s+/uy,Jn=e=>new RegExp(`(?:${e})`,"uy"),dW=e=>e.split("").map(t=>/ /gu.test(t)?"\\s+":`[${t.toUpperCase()}${t.toLowerCase()}]`).join(""),EW=e=>e+"(?:-"+e+")*",uW=({prefixes:e,requirePrefix:t})=>`(?:${e.map(dW).join("|")}${t?"":"|"})`,TW=e=>new RegExp(`(?:${e.map(pt).join("|")}).*?(?=\r
|
|
768
|
-
|\r|
|
|
769
|
-
|$)`,"uy"),bf=(e,t=[])=>{const n=e==="open"?0:1,r=["()",...t].map(o=>o[n]);return Jn(r.map(pt).join("|"))},Df=e=>Jn(`${FI(e).map(pt).join("|")}`),fW=({rest:e,dashes:t})=>e||t?`(?![${e||""}${t?"-":""}])`:"",Bt=(e,t={})=>{if(e.length===0)return/^\b$/u;const n=fW(t),r=FI(e).map(pt).join("|").replace(/ /gu,"\\s+");return new RegExp(`(?:${r})${n}\\b`,"iuy")},nc=(e,t)=>{if(!e.length)return;const n=e.map(pt).join("|");return Jn(`(?:${n})(?:${t})`)},pW=()=>{const e={"<":">","[":"]","(":")","{":"}"},t="{left}(?:(?!{right}').)*?{right}",n=Object.entries(e).map(([a,l])=>t.replace(/{left}/g,pt(a)).replace(/{right}/g,pt(l))),r=pt(Object.keys(e).join(""));return`[Qq]'(?:${String.raw`(?<tag>[^\s${r}])(?:(?!\k<tag>').)*?\k<tag>`}|${n.join("|")})'`},Mf={"``":"(?:`[^`]*`)+","[]":String.raw`(?:\[[^\]]*\])(?:\][^\]]*\])*`,'""-qq':String.raw`(?:"[^"]*")+`,'""-bs':String.raw`(?:"[^"\\]*(?:\\.[^"\\]*)*")`,'""-qq-bs':String.raw`(?:"[^"\\]*(?:\\.[^"\\]*)*")+`,'""-raw':String.raw`(?:"[^"]*")`,"''-qq":String.raw`(?:'[^']*')+`,"''-bs":String.raw`(?:'[^'\\]*(?:\\.[^'\\]*)*')`,"''-qq-bs":String.raw`(?:'[^'\\]*(?:\\.[^'\\]*)*')+`,"''-raw":String.raw`(?:'[^']*')`,$$:String.raw`(?<tag>\$\w*\$)[\s\S]*?\k<tag>`,"'''..'''":String.raw`'''[^\\]*?(?:\\.[^\\]*?)*?'''`,'""".."""':String.raw`"""[^\\]*?(?:\\.[^\\]*?)*?"""`,"{}":String.raw`(?:\{[^\}]*\})`,"q''":pW()},kI=e=>typeof e=="string"?Mf[e]:"regex"in e?e.regex:uW(e)+Mf[e.quote],SW=e=>Jn(e.map(t=>"regex"in t?t.regex:kI(t)).join("|")),jI=e=>e.map(kI).join("|"),vf=e=>Jn(jI(e)),RW=(e={})=>Jn(GI(e)),GI=({first:e,rest:t,dashes:n,allowFirstCharNumber:r}={})=>{const o="\\p{Alphabetic}\\p{Mark}_",i="\\p{Decimal_Number}",a=pt(e??""),l=pt(t??""),c=r?`[${o}${i}${a}][${o}${i}${l}]*`:`[${o}${a}][${o}${i}${l}]*`;return n?EW(c):c};function HI(e,t){const n=e.slice(0,t).split(/\n/);return{line:n.length,col:n[n.length-1].length+1}}class hW{constructor(t,n){this.rules=t,this.dialectName=n,this.input="",this.index=0}tokenize(t){this.input=t,this.index=0;const n=[];let r;for(;this.index<this.input.length;){const o=this.getWhitespace();if(this.index<this.input.length){if(r=this.getNextToken(),!r)throw this.createParseError();n.push(Object.assign(Object.assign({},r),{precedingWhitespace:o}))}}return n}createParseError(){const t=this.input.slice(this.index,this.index+10),{line:n,col:r}=HI(this.input,this.index);return new Error(`Parse error: Unexpected "${t}" at line ${n} column ${r}.
|
|
770
|
-
${this.dialectInfo()}`)}dialectInfo(){return this.dialectName==="sql"?`This likely happens because you're using the default "sql" dialect.
|
|
771
|
-
If possible, please select a more specific dialect (like sqlite, postgresql, etc).`:`SQL dialect used: "${this.dialectName}".`}getWhitespace(){_f.lastIndex=this.index;const t=_f.exec(this.input);if(t)return this.index+=t[0].length,t[0]}getNextToken(){for(const t of this.rules){const n=this.match(t);if(n)return n}}match(t){t.regex.lastIndex=this.index;const n=t.regex.exec(this.input);if(n){const r=n[0],o={type:t.type,raw:r,text:t.text?t.text(r):r,start:this.index};return t.key&&(o.key=t.key(r)),this.index+=r.length,o}}}const Pf=/\/\*/uy,AW=/[\s\S]/uy,IW=/\*\//uy;class mW{constructor(){this.lastIndex=0}exec(t){let n="",r,o=0;if(r=this.matchSection(Pf,t))n+=r,o++;else return null;for(;o>0;)if(r=this.matchSection(Pf,t))n+=r,o++;else if(r=this.matchSection(IW,t))n+=r,o--;else if(r=this.matchSection(AW,t))n+=r;else return null;return[n]}matchSection(t,n){t.lastIndex=this.lastIndex;const r=t.exec(n);return r&&(this.lastIndex+=r[0].length),r?r[0]:null}}class OW{constructor(t,n){this.cfg=t,this.dialectName=n,this.rulesBeforeParams=this.buildRulesBeforeParams(t),this.rulesAfterParams=this.buildRulesAfterParams(t)}tokenize(t,n){const r=[...this.rulesBeforeParams,...this.buildParamRules(this.cfg,n),...this.rulesAfterParams],o=new hW(r,this.dialectName).tokenize(t);return this.cfg.postProcess?this.cfg.postProcess(o):o}buildRulesBeforeParams(t){var n,r,o;return this.validRules([{type:K.DISABLE_COMMENT,regex:/(\/\* *sql-formatter-disable *\*\/[\s\S]*?(?:\/\* *sql-formatter-enable *\*\/|$))/uy},{type:K.BLOCK_COMMENT,regex:t.nestedBlockComments?new mW:/(\/\*[^]*?\*\/)/uy},{type:K.LINE_COMMENT,regex:TW((n=t.lineCommentTypes)!==null&&n!==void 0?n:["--"])},{type:K.QUOTED_IDENTIFIER,regex:vf(t.identTypes)},{type:K.NUMBER,regex:t.underscoresInNumbers?/(?:0x[0-9a-fA-F_]+|0b[01_]+|(?:-\s*)?(?:[0-9_]*\.[0-9_]+|[0-9_]+(?:\.[0-9_]*)?)(?:[eE][-+]?[0-9_]+(?:\.[0-9_]+)?)?)(?![\w\p{Alphabetic}])/uy:/(?:0x[0-9a-fA-F]+|0b[01]+|(?:-\s*)?(?:[0-9]*\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+(?:\.[0-9]+)?)?)(?![\w\p{Alphabetic}])/uy},{type:K.RESERVED_KEYWORD_PHRASE,regex:Bt((r=t.reservedKeywordPhrases)!==null&&r!==void 0?r:[],t.identChars),text:Me},{type:K.RESERVED_DATA_TYPE_PHRASE,regex:Bt((o=t.reservedDataTypePhrases)!==null&&o!==void 0?o:[],t.identChars),text:Me},{type:K.CASE,regex:/CASE\b/iuy,text:Me},{type:K.END,regex:/END\b/iuy,text:Me},{type:K.BETWEEN,regex:/BETWEEN\b/iuy,text:Me},{type:K.LIMIT,regex:t.reservedClauses.includes("LIMIT")?/LIMIT\b/iuy:void 0,text:Me},{type:K.RESERVED_CLAUSE,regex:Bt(t.reservedClauses,t.identChars),text:Me},{type:K.RESERVED_SELECT,regex:Bt(t.reservedSelect,t.identChars),text:Me},{type:K.RESERVED_SET_OPERATION,regex:Bt(t.reservedSetOperations,t.identChars),text:Me},{type:K.WHEN,regex:/WHEN\b/iuy,text:Me},{type:K.ELSE,regex:/ELSE\b/iuy,text:Me},{type:K.THEN,regex:/THEN\b/iuy,text:Me},{type:K.RESERVED_JOIN,regex:Bt(t.reservedJoins,t.identChars),text:Me},{type:K.AND,regex:/AND\b/iuy,text:Me},{type:K.OR,regex:/OR\b/iuy,text:Me},{type:K.XOR,regex:t.supportsXor?/XOR\b/iuy:void 0,text:Me},...t.operatorKeyword?[{type:K.OPERATOR,regex:/OPERATOR *\([^)]+\)/iuy}]:[],{type:K.RESERVED_FUNCTION_NAME,regex:Bt(t.reservedFunctionNames,t.identChars),text:Me},{type:K.RESERVED_DATA_TYPE,regex:Bt(t.reservedDataTypes,t.identChars),text:Me},{type:K.RESERVED_KEYWORD,regex:Bt(t.reservedKeywords,t.identChars),text:Me}])}buildRulesAfterParams(t){var n,r;return this.validRules([{type:K.VARIABLE,regex:t.variableTypes?SW(t.variableTypes):void 0},{type:K.STRING,regex:vf(t.stringTypes)},{type:K.IDENTIFIER,regex:RW(t.identChars)},{type:K.DELIMITER,regex:/[;]/uy},{type:K.COMMA,regex:/[,]/y},{type:K.OPEN_PAREN,regex:bf("open",t.extraParens)},{type:K.CLOSE_PAREN,regex:bf("close",t.extraParens)},{type:K.OPERATOR,regex:Df(["+","-","/",">","<","=","<>","<=",">=","!=",...(n=t.operators)!==null&&n!==void 0?n:[]])},{type:K.ASTERISK,regex:/[*]/uy},{type:K.PROPERTY_ACCESS_OPERATOR,regex:Df([".",...(r=t.propertyAccessOperators)!==null&&r!==void 0?r:[]])}])}buildParamRules(t,n){var r,o,i,a,l;const c={named:(n==null?void 0:n.named)||((r=t.paramTypes)===null||r===void 0?void 0:r.named)||[],quoted:(n==null?void 0:n.quoted)||((o=t.paramTypes)===null||o===void 0?void 0:o.quoted)||[],numbered:(n==null?void 0:n.numbered)||((i=t.paramTypes)===null||i===void 0?void 0:i.numbered)||[],positional:typeof(n==null?void 0:n.positional)=="boolean"?n.positional:(a=t.paramTypes)===null||a===void 0?void 0:a.positional,custom:(n==null?void 0:n.custom)||((l=t.paramTypes)===null||l===void 0?void 0:l.custom)||[]};return this.validRules([{type:K.NAMED_PARAMETER,regex:nc(c.named,GI(t.paramChars||t.identChars)),key:d=>d.slice(1)},{type:K.QUOTED_PARAMETER,regex:nc(c.quoted,jI(t.identTypes)),key:d=>(({tokenKey:E,quoteChar:u})=>E.replace(new RegExp(pt("\\"+u),"gu"),u))({tokenKey:d.slice(2,-1),quoteChar:d.slice(-1)})},{type:K.NUMBERED_PARAMETER,regex:nc(c.numbered,"[0-9]+"),key:d=>d.slice(1)},{type:K.POSITIONAL_PARAMETER,regex:c.positional?/[?]/y:void 0},...c.custom.map(d=>{var E;return{type:K.CUSTOM_PARAMETER,regex:Jn(d.regex),key:(E=d.key)!==null&&E!==void 0?E:(u=>u)}})])}validRules(t){return t.filter(n=>!!n.regex)}}const Me=e=>ii(e.toUpperCase()),wf=new Map,NW=e=>{let t=wf.get(e);return t||(t=gW(e),wf.set(e,t)),t},gW=e=>({tokenizer:new OW(e.tokenizerOptions,e.name),formatOptions:xW(e.formatOptions)}),xW=e=>{var t;return{alwaysDenseOperators:e.alwaysDenseOperators||[],onelineClauses:Object.fromEntries(e.onelineClauses.map(n=>[n,!0])),tabularOnelineClauses:Object.fromEntries(((t=e.tabularOnelineClauses)!==null&&t!==void 0?t:e.onelineClauses).map(n=>[n,!0]))}};function yW(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"?" ".repeat(10):e.useTabs?" ":" ".repeat(e.tabWidth)}function cr(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"}class CW{constructor(t){this.params=t,this.index=0}get({key:t,text:n}){return this.params?t?this.params[t]:this.params[this.index++]:n}getPositionalParameterIndex(){return this.index}setPositionalParameterIndex(t){this.index=t}}var ai={exports:{}},LW=ai.exports,Uf;function _W(){return Uf||(Uf=1,(function(e){(function(t,n){e.exports?e.exports=n():t.nearley=n()})(LW,function(){function t(d,E,u){return this.id=++t.highestId,this.name=d,this.symbols=E,this.postprocess=u,this}t.highestId=0,t.prototype.toString=function(d){var E=typeof d>"u"?this.symbols.map(c).join(" "):this.symbols.slice(0,d).map(c).join(" ")+" ● "+this.symbols.slice(d).map(c).join(" ");return this.name+" → "+E};function n(d,E,u,T){this.rule=d,this.dot=E,this.reference=u,this.data=[],this.wantedBy=T,this.isComplete=this.dot===d.symbols.length}n.prototype.toString=function(){return"{"+this.rule.toString(this.dot)+"}, from: "+(this.reference||0)},n.prototype.nextState=function(d){var E=new n(this.rule,this.dot+1,this.reference,this.wantedBy);return E.left=this,E.right=d,E.isComplete&&(E.data=E.build(),E.right=void 0),E},n.prototype.build=function(){var d=[],E=this;do d.push(E.right.data),E=E.left;while(E.left);return d.reverse(),d},n.prototype.finish=function(){this.rule.postprocess&&(this.data=this.rule.postprocess(this.data,this.reference,a.fail))};function r(d,E){this.grammar=d,this.index=E,this.states=[],this.wants={},this.scannable=[],this.completed={}}r.prototype.process=function(d){for(var E=this.states,u=this.wants,T=this.completed,p=0;p<E.length;p++){var h=E[p];if(h.isComplete){if(h.finish(),h.data!==a.fail){for(var A=h.wantedBy,S=A.length;S--;){var R=A[S];this.complete(R,h)}if(h.reference===this.index){var m=h.rule.name;(this.completed[m]=this.completed[m]||[]).push(h)}}}else{var m=h.rule.symbols[h.dot];if(typeof m!="string"){this.scannable.push(h);continue}if(u[m]){if(u[m].push(h),T.hasOwnProperty(m))for(var I=T[m],S=0;S<I.length;S++){var O=I[S];this.complete(h,O)}}else u[m]=[h],this.predict(m)}}},r.prototype.predict=function(d){for(var E=this.grammar.byName[d]||[],u=0;u<E.length;u++){var T=E[u],p=this.wants[d],h=new n(T,0,this.index,p);this.states.push(h)}},r.prototype.complete=function(d,E){var u=d.nextState(E);this.states.push(u)};function o(d,E){this.rules=d,this.start=E||this.rules[0].name;var u=this.byName={};this.rules.forEach(function(T){u.hasOwnProperty(T.name)||(u[T.name]=[]),u[T.name].push(T)})}o.fromCompiled=function(T,E){var u=T.Lexer;T.ParserStart&&(E=T.ParserStart,T=T.ParserRules);var T=T.map(function(h){return new t(h.name,h.symbols,h.postprocess)}),p=new o(T,E);return p.lexer=u,p};function i(){this.reset("")}i.prototype.reset=function(d,E){this.buffer=d,this.index=0,this.line=E?E.line:1,this.lastLineBreak=E?-E.col:0},i.prototype.next=function(){if(this.index<this.buffer.length){var d=this.buffer[this.index++];return d===`
|
|
772
|
-
`&&(this.line+=1,this.lastLineBreak=this.index),{value:d}}},i.prototype.save=function(){return{line:this.line,col:this.index-this.lastLineBreak}},i.prototype.formatError=function(d,E){var u=this.buffer;if(typeof u=="string"){var T=u.split(`
|
|
773
|
-
`).slice(Math.max(0,this.line-5),this.line),p=u.indexOf(`
|
|
774
|
-
`,this.index);p===-1&&(p=u.length);var h=this.index-this.lastLineBreak,A=String(this.line).length;return E+=" at line "+this.line+" col "+h+`:
|
|
775
|
-
|
|
776
|
-
`,E+=T.map(function(R,m){return S(this.line-T.length+m+1,A)+" "+R},this).join(`
|
|
777
|
-
`),E+=`
|
|
778
|
-
`+S("",A+h)+`^
|
|
779
|
-
`,E}else return E+" at index "+(this.index-1);function S(R,m){var I=String(R);return Array(m-I.length+1).join(" ")+I}};function a(d,E,u){if(d instanceof o)var T=d,u=E;else var T=o.fromCompiled(d,E);this.grammar=T,this.options={keepHistory:!1,lexer:T.lexer||new i};for(var p in u||{})this.options[p]=u[p];this.lexer=this.options.lexer,this.lexerState=void 0;var h=new r(T,0);this.table=[h],h.wants[T.start]=[],h.predict(T.start),h.process(),this.current=0}a.fail={},a.prototype.feed=function(d){var E=this.lexer;E.reset(d,this.lexerState);for(var u;;){try{if(u=E.next(),!u)break}catch(g){var A=new r(this.grammar,this.current+1);this.table.push(A);var T=new Error(this.reportLexerError(g));throw T.offset=this.current,T.token=g.token,T}var p=this.table[this.current];this.options.keepHistory||delete this.table[this.current-1];var h=this.current+1,A=new r(this.grammar,h);this.table.push(A);for(var S=u.text!==void 0?u.text:u.value,R=E.constructor===i?u.value:u,m=p.scannable,I=m.length;I--;){var O=m[I],N=O.rule.symbols[O.dot];if(N.test?N.test(R):N.type?N.type===u.type:N.literal===S){var x=O.nextState({data:R,token:u,isToken:!0,reference:h-1});A.states.push(x)}}if(A.process(),A.states.length===0){var T=new Error(this.reportError(u));throw T.offset=this.current,T.token=u,T}this.options.keepHistory&&(p.lexerState=E.save()),this.current++}return p&&(this.lexerState=E.save()),this.results=this.finish(),this},a.prototype.reportLexerError=function(d){var E,u,T=d.token;return T?(E="input "+JSON.stringify(T.text[0])+" (lexer error)",u=this.lexer.formatError(T,"Syntax error")):(E="input (lexer error)",u=d.message),this.reportErrorCommon(u,E)},a.prototype.reportError=function(d){var E=(d.type?d.type+" token: ":"")+JSON.stringify(d.value!==void 0?d.value:d),u=this.lexer.formatError(d,"Syntax error");return this.reportErrorCommon(u,E)},a.prototype.reportErrorCommon=function(d,E){var u=[];u.push(d);var T=this.table.length-2,p=this.table[T],h=p.states.filter(function(S){var R=S.rule.symbols[S.dot];return R&&typeof R!="string"});if(h.length===0)u.push("Unexpected "+E+`. I did not expect any more input. Here is the state of my parse table:
|
|
780
|
-
`),this.displayStateStack(p.states,u);else{u.push("Unexpected "+E+`. Instead, I was expecting to see one of the following:
|
|
781
|
-
`);var A=h.map(function(S){return this.buildFirstStateStack(S,[])||[S]},this);A.forEach(function(S){var R=S[0],m=R.rule.symbols[R.dot],I=this.getSymbolDisplay(m);u.push("A "+I+" based on:"),this.displayStateStack(S,u)},this)}return u.push(""),u.join(`
|
|
782
|
-
`)},a.prototype.displayStateStack=function(d,E){for(var u,T=0,p=0;p<d.length;p++){var h=d[p],A=h.rule.toString(h.dot);A===u?T++:(T>0&&E.push(" ^ "+T+" more lines identical to this"),T=0,E.push(" "+A)),u=A}},a.prototype.getSymbolDisplay=function(d){return l(d)},a.prototype.buildFirstStateStack=function(d,E){if(E.indexOf(d)!==-1)return null;if(d.wantedBy.length===0)return[d];var u=d.wantedBy[0],T=[d].concat(E),p=this.buildFirstStateStack(u,T);return p===null?null:[d].concat(p)},a.prototype.save=function(){var d=this.table[this.current];return d.lexerState=this.lexerState,d},a.prototype.restore=function(d){var E=d.index;this.current=E,this.table[E]=d,this.table.splice(E+1),this.lexerState=d.lexerState,this.results=this.finish()},a.prototype.rewind=function(d){if(!this.options.keepHistory)throw new Error("set option `keepHistory` to enable rewinding");this.restore(this.table[d])},a.prototype.finish=function(){var d=[],E=this.grammar.start,u=this.table[this.table.length-1];return u.states.forEach(function(T){T.rule.name===E&&T.dot===T.rule.symbols.length&&T.reference===0&&T.data!==a.fail&&d.push(T)}),d.map(function(T){return T.data})};function l(d){var E=typeof d;if(E==="string")return d;if(E==="object"){if(d.literal)return JSON.stringify(d.literal);if(d instanceof RegExp)return"character matching "+d;if(d.type)return d.type+" token";if(d.test)return"token matching "+String(d.test);throw new Error("Unknown symbol type: "+d)}}function c(d){var E=typeof d;if(E==="string")return d;if(E==="object"){if(d.literal)return JSON.stringify(d.literal);if(d instanceof RegExp)return d.toString();if(d.type)return"%"+d.type;if(d.test)return"<"+String(d.test)+">";throw new Error("Unknown symbol type: "+d)}}return{Parser:a,Grammar:o,Rule:t}})})(ai)),ai.exports}var bW=_W();const DW=Wi(bW);function MW(e){return e.map(vW).map(PW).map(wW).map(UW).map(BW)}const vW=(e,t,n)=>{if(BI(e.type)){const r=FW(n,t);if(r&&r.type===K.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:K.IDENTIFIER,text:e.raw});const o=Wr(n,t);if(o&&o.type===K.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:K.IDENTIFIER,text:e.raw})}return e},PW=(e,t,n)=>{if(e.type===K.RESERVED_FUNCTION_NAME){const r=Wr(n,t);if(!r||!YI(r))return Object.assign(Object.assign({},e),{type:K.IDENTIFIER,text:e.raw})}return e},wW=(e,t,n)=>{if(e.type===K.RESERVED_DATA_TYPE){const r=Wr(n,t);if(r&&YI(r))return Object.assign(Object.assign({},e),{type:K.RESERVED_PARAMETERIZED_DATA_TYPE})}return e},UW=(e,t,n)=>{if(e.type===K.IDENTIFIER){const r=Wr(n,t);if(r&&WI(r))return Object.assign(Object.assign({},e),{type:K.ARRAY_IDENTIFIER})}return e},BW=(e,t,n)=>{if(e.type===K.RESERVED_DATA_TYPE){const r=Wr(n,t);if(r&&WI(r))return Object.assign(Object.assign({},e),{type:K.ARRAY_KEYWORD})}return e},FW=(e,t)=>Wr(e,t,-1),Wr=(e,t,n=1)=>{let r=1;for(;e[t+r*n]&&kW(e[t+r*n]);)r++;return e[t+r*n]},YI=e=>e.type===K.OPEN_PAREN&&e.text==="(",WI=e=>e.type===K.OPEN_PAREN&&e.text==="[",kW=e=>e.type===K.BLOCK_COMMENT||e.type===K.LINE_COMMENT;class $I{constructor(t){this.tokenize=t,this.index=0,this.tokens=[],this.input=""}reset(t,n){this.input=t,this.index=0,this.tokens=this.tokenize(t)}next(){return this.tokens[this.index++]}save(){}formatError(t){const{line:n,col:r}=HI(this.input,t.start);return`Parse error at token: ${t.text} at line ${n} column ${r}`}has(t){return t in K}}var se;(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"})(se=se||(se={}));function rc(e){return e[0]}const Ee=new $I(e=>[]),_n=([[e]])=>e,ve=e=>({type:se.keyword,tokenType:e.type,text:e.text,raw:e.raw}),Bf=e=>({type:se.data_type,text:e.text,raw:e.raw}),Pe=(e,{leading:t,trailing:n})=>(t!=null&&t.length&&(e=Object.assign(Object.assign({},e),{leadingComments:t})),n!=null&&n.length&&(e=Object.assign(Object.assign({},e),{trailingComments:n})),e),jW=(e,{leading:t,trailing:n})=>{if(t!=null&&t.length){const[r,...o]=e;e=[Pe(r,{leading:t}),...o]}if(n!=null&&n.length){const r=e.slice(0,-1),o=e[e.length-1];e=[...r,Pe(o,{trailing:n})]}return e},GW={Lexer:Ee,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:[Ee.has("DELIMITER")?{type:"DELIMITER"}:DELIMITER]},{name:"statement$subexpression$1",symbols:[Ee.has("EOF")?{type:"EOF"}:EOF]},{name:"statement",symbols:["expressions_or_clauses","statement$subexpression$1"],postprocess:([e,[t]])=>({type:se.statement,children:e,hasSemicolon:t.type===K.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:_n},{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:[Ee.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:rc},{name:"limit_clause$ebnf$1",symbols:[],postprocess:()=>null},{name:"limit_clause",symbols:[Ee.has("LIMIT")?{type:"LIMIT"}:LIMIT,"_","expression_chain_","limit_clause$ebnf$1"],postprocess:([e,t,n,r])=>{if(r){const[o,i]=r;return{type:se.limit_clause,limitKw:Pe(ve(e),{trailing:t}),offset:n,count:i}}else return{type:se.limit_clause,limitKw:Pe(ve(e),{trailing:t}),count:n}}},{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:[Ee.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT,"select_clause$subexpression$1"],postprocess:([e,[t,n]])=>({type:se.clause,nameKw:ve(e),children:[t,...n]})},{name:"select_clause",symbols:[Ee.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT],postprocess:([e])=>({type:se.clause,nameKw:ve(e),children:[]})},{name:"all_columns_asterisk",symbols:[Ee.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK],postprocess:()=>({type:se.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:[Ee.has("RESERVED_CLAUSE")?{type:"RESERVED_CLAUSE"}:RESERVED_CLAUSE,"other_clause$ebnf$1"],postprocess:([e,t])=>({type:se.clause,nameKw:ve(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:[Ee.has("RESERVED_SET_OPERATION")?{type:"RESERVED_SET_OPERATION"}:RESERVED_SET_OPERATION,"set_operation$ebnf$1"],postprocess:([e,t])=>({type:se.set_operation,nameKw:ve(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:rc},{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])=>Pe(e,{trailing:t})},{name:"_expression_with_comments",symbols:["_","expression"],postprocess:([e,t])=>Pe(t,{leading:e})},{name:"_andless_expression_with_comments",symbols:["_","andless_expression"],postprocess:([e,t])=>Pe(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:_n},{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:_n},{name:"expression$subexpression$1",symbols:["andless_expression"]},{name:"expression$subexpression$1",symbols:["logic_operator"]},{name:"expression",symbols:["expression$subexpression$1"],postprocess:_n},{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:_n},{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:_n},{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:_n},{name:"array_subscript",symbols:[Ee.has("ARRAY_IDENTIFIER")?{type:"ARRAY_IDENTIFIER"}:ARRAY_IDENTIFIER,"_","square_brackets"],postprocess:([e,t,n])=>({type:se.array_subscript,array:Pe({type:se.identifier,quoted:!1,text:e.text},{trailing:t}),parenthesis:n})},{name:"array_subscript",symbols:[Ee.has("ARRAY_KEYWORD")?{type:"ARRAY_KEYWORD"}:ARRAY_KEYWORD,"_","square_brackets"],postprocess:([e,t,n])=>({type:se.array_subscript,array:Pe(ve(e),{trailing:t}),parenthesis:n})},{name:"function_call",symbols:[Ee.has("RESERVED_FUNCTION_NAME")?{type:"RESERVED_FUNCTION_NAME"}:RESERVED_FUNCTION_NAME,"_","parenthesis"],postprocess:([e,t,n])=>({type:se.function_call,nameKw:Pe(ve(e),{trailing:t}),parenthesis:n})},{name:"parenthesis",symbols:[{literal:"("},"expressions_or_clauses",{literal:")"}],postprocess:([e,t,n])=>({type:se.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,n])=>({type:se.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,n])=>({type:se.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","_",Ee.has("PROPERTY_ACCESS_OPERATOR")?{type:"PROPERTY_ACCESS_OPERATOR"}:PROPERTY_ACCESS_OPERATOR,"_","property_access$subexpression$1"],postprocess:([e,t,n,r,[o]])=>({type:se.property_access,object:Pe(e,{trailing:t}),operator:n.text,property:Pe(o,{leading:r})})},{name:"between_predicate",symbols:[Ee.has("BETWEEN")?{type:"BETWEEN"}:BETWEEN,"_","andless_expression_chain","_",Ee.has("AND")?{type:"AND"}:AND,"_","andless_expression"],postprocess:([e,t,n,r,o,i,a])=>({type:se.between_predicate,betweenKw:ve(e),expr1:jW(n,{leading:t,trailing:r}),andKw:ve(o),expr2:[Pe(a,{leading:i})]})},{name:"case_expression$ebnf$1",symbols:["expression_chain_"],postprocess:rc},{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:[Ee.has("CASE")?{type:"CASE"}:CASE,"_","case_expression$ebnf$1","case_expression$ebnf$2",Ee.has("END")?{type:"END"}:END],postprocess:([e,t,n,r,o])=>({type:se.case_expression,caseKw:Pe(ve(e),{trailing:t}),endKw:ve(o),expr:n||[],clauses:r})},{name:"case_clause",symbols:[Ee.has("WHEN")?{type:"WHEN"}:WHEN,"_","expression_chain_",Ee.has("THEN")?{type:"THEN"}:THEN,"_","expression_chain_"],postprocess:([e,t,n,r,o,i])=>({type:se.case_when,whenKw:Pe(ve(e),{trailing:t}),thenKw:Pe(ve(r),{trailing:o}),condition:n,result:i})},{name:"case_clause",symbols:[Ee.has("ELSE")?{type:"ELSE"}:ELSE,"_","expression_chain_"],postprocess:([e,t,n])=>({type:se.case_else,elseKw:Pe(ve(e),{trailing:t}),result:n})},{name:"comma$subexpression$1",symbols:[Ee.has("COMMA")?{type:"COMMA"}:COMMA]},{name:"comma",symbols:["comma$subexpression$1"],postprocess:([[e]])=>({type:se.comma})},{name:"asterisk$subexpression$1",symbols:[Ee.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK]},{name:"asterisk",symbols:["asterisk$subexpression$1"],postprocess:([[e]])=>({type:se.operator,text:e.text})},{name:"operator$subexpression$1",symbols:[Ee.has("OPERATOR")?{type:"OPERATOR"}:OPERATOR]},{name:"operator",symbols:["operator$subexpression$1"],postprocess:([[e]])=>({type:se.operator,text:e.text})},{name:"identifier$subexpression$1",symbols:[Ee.has("IDENTIFIER")?{type:"IDENTIFIER"}:IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[Ee.has("QUOTED_IDENTIFIER")?{type:"QUOTED_IDENTIFIER"}:QUOTED_IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[Ee.has("VARIABLE")?{type:"VARIABLE"}:VARIABLE]},{name:"identifier",symbols:["identifier$subexpression$1"],postprocess:([[e]])=>({type:se.identifier,quoted:e.type!=="IDENTIFIER",text:e.text})},{name:"parameter$subexpression$1",symbols:[Ee.has("NAMED_PARAMETER")?{type:"NAMED_PARAMETER"}:NAMED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[Ee.has("QUOTED_PARAMETER")?{type:"QUOTED_PARAMETER"}:QUOTED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[Ee.has("NUMBERED_PARAMETER")?{type:"NUMBERED_PARAMETER"}:NUMBERED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[Ee.has("POSITIONAL_PARAMETER")?{type:"POSITIONAL_PARAMETER"}:POSITIONAL_PARAMETER]},{name:"parameter$subexpression$1",symbols:[Ee.has("CUSTOM_PARAMETER")?{type:"CUSTOM_PARAMETER"}:CUSTOM_PARAMETER]},{name:"parameter",symbols:["parameter$subexpression$1"],postprocess:([[e]])=>({type:se.parameter,key:e.key,text:e.text})},{name:"literal$subexpression$1",symbols:[Ee.has("NUMBER")?{type:"NUMBER"}:NUMBER]},{name:"literal$subexpression$1",symbols:[Ee.has("STRING")?{type:"STRING"}:STRING]},{name:"literal",symbols:["literal$subexpression$1"],postprocess:([[e]])=>({type:se.literal,text:e.text})},{name:"keyword$subexpression$1",symbols:[Ee.has("RESERVED_KEYWORD")?{type:"RESERVED_KEYWORD"}:RESERVED_KEYWORD]},{name:"keyword$subexpression$1",symbols:[Ee.has("RESERVED_KEYWORD_PHRASE")?{type:"RESERVED_KEYWORD_PHRASE"}:RESERVED_KEYWORD_PHRASE]},{name:"keyword$subexpression$1",symbols:[Ee.has("RESERVED_JOIN")?{type:"RESERVED_JOIN"}:RESERVED_JOIN]},{name:"keyword",symbols:["keyword$subexpression$1"],postprocess:([[e]])=>ve(e)},{name:"data_type$subexpression$1",symbols:[Ee.has("RESERVED_DATA_TYPE")?{type:"RESERVED_DATA_TYPE"}:RESERVED_DATA_TYPE]},{name:"data_type$subexpression$1",symbols:[Ee.has("RESERVED_DATA_TYPE_PHRASE")?{type:"RESERVED_DATA_TYPE_PHRASE"}:RESERVED_DATA_TYPE_PHRASE]},{name:"data_type",symbols:["data_type$subexpression$1"],postprocess:([[e]])=>Bf(e)},{name:"data_type",symbols:[Ee.has("RESERVED_PARAMETERIZED_DATA_TYPE")?{type:"RESERVED_PARAMETERIZED_DATA_TYPE"}:RESERVED_PARAMETERIZED_DATA_TYPE,"_","parenthesis"],postprocess:([e,t,n])=>({type:se.parameterized_data_type,dataType:Pe(Bf(e),{trailing:t}),parenthesis:n})},{name:"logic_operator$subexpression$1",symbols:[Ee.has("AND")?{type:"AND"}:AND]},{name:"logic_operator$subexpression$1",symbols:[Ee.has("OR")?{type:"OR"}:OR]},{name:"logic_operator$subexpression$1",symbols:[Ee.has("XOR")?{type:"XOR"}:XOR]},{name:"logic_operator",symbols:["logic_operator$subexpression$1"],postprocess:([[e]])=>ve(e)},{name:"other_keyword$subexpression$1",symbols:[Ee.has("WHEN")?{type:"WHEN"}:WHEN]},{name:"other_keyword$subexpression$1",symbols:[Ee.has("THEN")?{type:"THEN"}:THEN]},{name:"other_keyword$subexpression$1",symbols:[Ee.has("ELSE")?{type:"ELSE"}:ELSE]},{name:"other_keyword$subexpression$1",symbols:[Ee.has("END")?{type:"END"}:END]},{name:"other_keyword",symbols:["other_keyword$subexpression$1"],postprocess:([[e]])=>ve(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:[Ee.has("LINE_COMMENT")?{type:"LINE_COMMENT"}:LINE_COMMENT],postprocess:([e])=>({type:se.line_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[Ee.has("BLOCK_COMMENT")?{type:"BLOCK_COMMENT"}:BLOCK_COMMENT],postprocess:([e])=>({type:se.block_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[Ee.has("DISABLE_COMMENT")?{type:"DISABLE_COMMENT"}:DISABLE_COMMENT],postprocess:([e])=>({type:se.disable_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})}],ParserStart:"main"},{Parser:HW,Grammar:YW}=DW;function WW(e){let t={};const n=new $I(o=>[...MW(e.tokenize(o,t)),UI(o.length)]),r=new HW(YW.fromCompiled(GW),{lexer:n});return{parse:(o,i)=>{t=i;const{results:a}=r.feed(o);if(a.length===1)return a[0];throw a.length===0?new Error("Parse error: Invalid SQL"):new Error(`Parse error: Ambiguous grammar
|
|
783
|
-
${JSON.stringify(a,void 0,2)}`)}}}var X;(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"})(X=X||(X={}));class VI{constructor(t){this.indentation=t,this.items=[]}add(...t){for(const n of t)switch(n){case X.SPACE:this.items.push(X.SPACE);break;case X.NO_SPACE:this.trimHorizontalWhitespace();break;case X.NO_NEWLINE:this.trimWhitespace();break;case X.NEWLINE:this.trimHorizontalWhitespace(),this.addNewline(X.NEWLINE);break;case X.MANDATORY_NEWLINE:this.trimHorizontalWhitespace(),this.addNewline(X.MANDATORY_NEWLINE);break;case X.INDENT:this.addIndentation();break;case X.SINGLE_INDENT:this.items.push(X.SINGLE_INDENT);break;default:this.items.push(n)}}trimHorizontalWhitespace(){for(;$W(To(this.items));)this.items.pop()}trimWhitespace(){for(;VW(To(this.items));)this.items.pop()}addNewline(t){if(this.items.length>0)switch(To(this.items)){case X.NEWLINE:this.items.pop(),this.items.push(t);break;case X.MANDATORY_NEWLINE:break;default:this.items.push(t);break}}addIndentation(){for(let t=0;t<this.indentation.getLevel();t++)this.items.push(X.SINGLE_INDENT)}toString(){return this.items.map(t=>this.itemToString(t)).join("")}getLayoutItems(){return this.items}itemToString(t){switch(t){case X.SPACE:return" ";case X.NEWLINE:case X.MANDATORY_NEWLINE:return`
|
|
784
|
-
`;case X.SINGLE_INDENT:return this.indentation.getSingleIndent();default:return t}}}const $W=e=>e===X.SPACE||e===X.SINGLE_INDENT,VW=e=>e===X.SPACE||e===X.SINGLE_INDENT||e===X.NEWLINE;function Ff(e,t){if(t==="standard")return e;let n=[];return e.length>=10&&e.includes(" ")&&([e,...n]=e.split(" ")),t==="tabularLeft"?e=e.padEnd(9," "):e=e.padStart(9," "),e+["",...n].join(" ")}function kf(e){return hj(e)||e===K.RESERVED_CLAUSE||e===K.RESERVED_SELECT||e===K.RESERVED_SET_OPERATION||e===K.RESERVED_JOIN||e===K.LIMIT}const oc="top-level",XW="block-level";class XI{constructor(t){this.indent=t,this.indentTypes=[]}getSingleIndent(){return this.indent}getLevel(){return this.indentTypes.length}increaseTopLevel(){this.indentTypes.push(oc)}increaseBlockLevel(){this.indentTypes.push(XW)}decreaseTopLevel(){this.indentTypes.length>0&&To(this.indentTypes)===oc&&this.indentTypes.pop()}decreaseBlockLevel(){for(;this.indentTypes.length>0&&this.indentTypes.pop()===oc;);}}class zW extends VI{constructor(t){super(new XI("")),this.expressionWidth=t,this.length=0,this.trailingSpace=!1}add(...t){if(t.forEach(n=>this.addToLength(n)),this.length>this.expressionWidth)throw new Zc;super.add(...t)}addToLength(t){if(typeof t=="string")this.length+=t.length,this.trailingSpace=!1;else{if(t===X.MANDATORY_NEWLINE||t===X.NEWLINE)throw new Zc;t===X.INDENT||t===X.SINGLE_INDENT||t===X.SPACE?this.trailingSpace||(this.length++,this.trailingSpace=!0):(t===X.NO_NEWLINE||t===X.NO_SPACE)&&this.trailingSpace&&(this.trailingSpace=!1,this.length--)}}}class Zc extends Error{}class ki{constructor({cfg:t,dialectCfg:n,params:r,layout:o,inline:i=!1}){this.inline=!1,this.nodes=[],this.index=-1,this.cfg=t,this.dialectCfg=n,this.inline=i,this.params=r,this.layout=o}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 se.function_call:return this.formatFunctionCall(t);case se.parameterized_data_type:return this.formatParameterizedDataType(t);case se.array_subscript:return this.formatArraySubscript(t);case se.property_access:return this.formatPropertyAccess(t);case se.parenthesis:return this.formatParenthesis(t);case se.between_predicate:return this.formatBetweenPredicate(t);case se.case_expression:return this.formatCaseExpression(t);case se.case_when:return this.formatCaseWhen(t);case se.case_else:return this.formatCaseElse(t);case se.clause:return this.formatClause(t);case se.set_operation:return this.formatSetOperation(t);case se.limit_clause:return this.formatLimitClause(t);case se.all_columns_asterisk:return this.formatAllColumnsAsterisk(t);case se.literal:return this.formatLiteral(t);case se.identifier:return this.formatIdentifier(t);case se.parameter:return this.formatParameter(t);case se.operator:return this.formatOperator(t);case se.comma:return this.formatComma(t);case se.line_comment:return this.formatLineComment(t);case se.block_comment:return this.formatBlockComment(t);case se.disable_comment:return this.formatBlockComment(t);case se.data_type:return this.formatDataType(t);case se.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 n;switch(t.array.type){case se.data_type:n=this.showDataType(t.array);break;case se.keyword:n=this.showKw(t.array);break;default:n=this.showIdentifier(t.array);break}this.withComments(t.array,()=>{this.layout.add(n)}),this.formatNode(t.parenthesis)}formatPropertyAccess(t){this.formatNode(t.object),this.layout.add(X.NO_SPACE,t.operator),this.formatNode(t.property)}formatParenthesis(t){const n=this.formatInlineExpression(t.children);n?(this.layout.add(t.openParen),this.layout.add(...n.getLayoutItems()),this.layout.add(X.NO_SPACE,t.closeParen,X.SPACE)):(this.layout.add(t.openParen,X.NEWLINE),cr(this.cfg)?(this.layout.add(X.INDENT),this.layout=this.formatSubExpression(t.children)):(this.layout.indentation.increaseBlockLevel(),this.layout.add(X.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseBlockLevel()),this.layout.add(X.NEWLINE,X.INDENT,t.closeParen,X.SPACE))}formatBetweenPredicate(t){this.layout.add(this.showKw(t.betweenKw),X.SPACE),this.layout=this.formatSubExpression(t.expr1),this.layout.add(X.NO_SPACE,X.SPACE,this.showNonTabularKw(t.andKw),X.SPACE),this.layout=this.formatSubExpression(t.expr2),this.layout.add(X.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(X.NEWLINE,X.INDENT),this.formatNode(t.endKw)}formatCaseWhen(t){this.layout.add(X.NEWLINE,X.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(X.NEWLINE,X.INDENT),this.formatNode(t.elseKw),this.layout=this.formatSubExpression(t.result)}formatClause(t){this.isOnelineClause(t)?this.formatClauseInOnelineStyle(t):cr(this.cfg)?this.formatClauseInTabularStyle(t):this.formatClauseInIndentedStyle(t)}isOnelineClause(t){return cr(this.cfg)?this.dialectCfg.tabularOnelineClauses[t.nameKw.text]:this.dialectCfg.onelineClauses[t.nameKw.text]}formatClauseInIndentedStyle(t){this.layout.add(X.NEWLINE,X.INDENT,this.showKw(t.nameKw),X.NEWLINE),this.layout.indentation.increaseTopLevel(),this.layout.add(X.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatClauseInOnelineStyle(t){this.layout.add(X.NEWLINE,X.INDENT,this.showKw(t.nameKw),X.SPACE),this.layout=this.formatSubExpression(t.children)}formatClauseInTabularStyle(t){this.layout.add(X.NEWLINE,X.INDENT,this.showKw(t.nameKw),X.SPACE),this.layout.indentation.increaseTopLevel(),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatSetOperation(t){this.layout.add(X.NEWLINE,X.INDENT,this.showKw(t.nameKw),X.NEWLINE),this.layout.add(X.INDENT),this.layout=this.formatSubExpression(t.children)}formatLimitClause(t){this.withComments(t.limitKw,()=>{this.layout.add(X.NEWLINE,X.INDENT,this.showKw(t.limitKw))}),this.layout.indentation.increaseTopLevel(),cr(this.cfg)?this.layout.add(X.SPACE):this.layout.add(X.NEWLINE,X.INDENT),t.offset?(this.layout=this.formatSubExpression(t.offset),this.layout.add(X.NO_SPACE,",",X.SPACE),this.layout=this.formatSubExpression(t.count)):this.layout=this.formatSubExpression(t.count),this.layout.indentation.decreaseTopLevel()}formatAllColumnsAsterisk(t){this.layout.add("*",X.SPACE)}formatLiteral(t){this.layout.add(t.text,X.SPACE)}formatIdentifier(t){this.layout.add(this.showIdentifier(t),X.SPACE)}formatParameter(t){this.layout.add(this.params.get(t),X.SPACE)}formatOperator({text:t}){this.cfg.denseOperators||this.dialectCfg.alwaysDenseOperators.includes(t)?this.layout.add(X.NO_SPACE,t):t===":"?this.layout.add(X.NO_SPACE,t,X.SPACE):this.layout.add(t,X.SPACE)}formatComma(t){this.inline?this.layout.add(X.NO_SPACE,",",X.SPACE):this.layout.add(X.NO_SPACE,",",X.NEWLINE,X.INDENT)}withComments(t,n){this.formatComments(t.leadingComments),n(),this.formatComments(t.trailingComments)}formatComments(t){t&&t.forEach(n=>{n.type===se.line_comment?this.formatLineComment(n):this.formatBlockComment(n)})}formatLineComment(t){tc(t.precedingWhitespace||"")?this.layout.add(X.NEWLINE,X.INDENT,t.text,X.MANDATORY_NEWLINE,X.INDENT):this.layout.getLayoutItems().length>0?this.layout.add(X.NO_NEWLINE,X.SPACE,t.text,X.MANDATORY_NEWLINE,X.INDENT):this.layout.add(t.text,X.MANDATORY_NEWLINE,X.INDENT)}formatBlockComment(t){t.type===se.block_comment&&this.isMultilineBlockComment(t)?(this.splitBlockComment(t.text).forEach(n=>{this.layout.add(X.NEWLINE,X.INDENT,n)}),this.layout.add(X.NEWLINE,X.INDENT)):this.layout.add(t.text,X.SPACE)}isMultilineBlockComment(t){return tc(t.text)||tc(t.precedingWhitespace||"")}isDocComment(t){const n=t.split(/\n/);return/^\/\*\*?$/.test(n[0])&&n.slice(1,n.length-1).every(r=>/^\s*\*/.test(r))&&/^\s*\*\/$/.test(To(n))}splitBlockComment(t){return this.isDocComment(t)?t.split(/\n/).map(n=>/^\s*\*/.test(n)?" "+n.replace(/^\s*/,""):n):t.split(/\n/).map(n=>n.replace(/^\s*/,""))}formatSubExpression(t){return new ki({cfg:this.cfg,dialectCfg:this.dialectCfg,params:this.params,layout:this.layout,inline:this.inline}).format(t)}formatInlineExpression(t){const n=this.params.getPositionalParameterIndex();try{return new ki({cfg:this.cfg,dialectCfg:this.dialectCfg,params:this.params,layout:new zW(this.cfg.expressionWidth),inline:!0}).format(t)}catch(r){if(r instanceof Zc){this.params.setPositionalParameterIndex(n);return}else throw r}}formatKeywordNode(t){switch(t.tokenType){case K.RESERVED_JOIN:return this.formatJoin(t);case K.AND:case K.OR:case K.XOR:return this.formatLogicalOperator(t);default:return this.formatKeyword(t)}}formatJoin(t){cr(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add(X.NEWLINE,X.INDENT,this.showKw(t),X.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add(X.NEWLINE,X.INDENT,this.showKw(t),X.SPACE)}formatKeyword(t){this.layout.add(this.showKw(t),X.SPACE)}formatLogicalOperator(t){this.cfg.logicalOperatorNewline==="before"?cr(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add(X.NEWLINE,X.INDENT,this.showKw(t),X.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add(X.NEWLINE,X.INDENT,this.showKw(t),X.SPACE):this.layout.add(this.showKw(t),X.NEWLINE,X.INDENT)}formatDataType(t){this.layout.add(this.showDataType(t),X.SPACE)}showKw(t){return kf(t.tokenType)?Ff(this.showNonTabularKw(t),this.cfg.indentStyle):this.showNonTabularKw(t)}showNonTabularKw(t){switch(this.cfg.keywordCase){case"preserve":return ii(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}showFunctionKw(t){return kf(t.tokenType)?Ff(this.showNonTabularFunctionKw(t),this.cfg.indentStyle):this.showNonTabularFunctionKw(t)}showNonTabularFunctionKw(t){switch(this.cfg.functionCase){case"preserve":return ii(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 ii(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}}class KW{constructor(t,n){this.dialect=t,this.cfg=n,this.params=new CW(this.cfg.params)}format(t){const n=this.parse(t);return this.formatAst(n).trimEnd()}parse(t){return WW(this.dialect.tokenizer).parse(t,this.cfg.paramTypes||{})}formatAst(t){return t.map(n=>this.formatStatement(n)).join(`
|
|
785
|
-
`.repeat(this.cfg.linesBetweenQueries+1))}formatStatement(t){const n=new ki({cfg:this.cfg,dialectCfg:this.dialect.formatOptions,params:this.params,layout:new VI(new XI(yW(this.cfg)))}).format(t.children);return t.hasSemicolon&&(this.cfg.newlineBeforeSemicolon?n.add(X.NEWLINE,";"):n.add(X.NO_NEWLINE,";")),n.toString()}}class li extends Error{}function qW(e){const t=["multilineLists","newlineBeforeOpenParen","newlineBeforeCloseParen","aliasAs","commaPosition","tabulateAlias"];for(const n of t)if(n in e)throw new li(`${n} config is no more supported.`);if(e.expressionWidth<=0)throw new li(`expressionWidth config must be positive number. Received ${e.expressionWidth} instead.`);if(e.params&&!JW(e.params)&&console.warn('WARNING: All "params" option values should be strings.'),e.paramTypes&&!QW(e.paramTypes))throw new li("Empty regex given in custom paramTypes. That would result in matching infinite amount of parameters.");return e}function JW(e){return(e instanceof Array?e:Object.values(e)).every(n=>typeof n=="string")}function QW(e){return e.custom&&Array.isArray(e.custom)?e.custom.every(t=>t.regex!==""):!0}var ZW=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n};const zI={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"},e$=Object.keys(zI),t$={tabWidth:2,useTabs:!1,keywordCase:"preserve",identifierCase:"preserve",dataTypeCase:"preserve",functionCase:"preserve",indentStyle:"standard",logicalOperatorNewline:"before",expressionWidth:50,linesBetweenQueries:1,denseOperators:!1,newlineBeforeSemicolon:!1},n$=(e,t={})=>{if(typeof t.language=="string"&&!e$.includes(t.language))throw new li(`Unsupported SQL dialect: ${t.language}`);const n=zI[t.language||"sql"];return r$(e,Object.assign(Object.assign({},t),{dialect:cW[n]}))},r$=(e,t)=>{var{dialect:n}=t,r=ZW(t,["dialect"]);if(typeof e!="string")throw new Error("Invalid query argument. Expected string, instead got "+typeof e);const o=qW(Object.assign(Object.assign({},t$),r));return new KW(NW(n),o).format(e)};function nn({cell:e,t,onRun:n,onMoveUp:r,onMoveDown:o,onDelete:i,children:a}){const[l,c]=f.useState(!1),d=JI(e,t),E=qI[e.type]??t.accent,u=e.name?s.jsx("span",{style:{color:t.textSecondary,fontSize:12,fontFamily:t.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:200},children:e.name}):void 0,T=l?s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[n&&s.jsx(gt,{title:"Run cell (Shift+Enter)",onClick:n,t,accent:!0,children:s.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:s.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})})}),s.jsx(gt,{title:"Move up",onClick:r,t,children:s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:s.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"})})}),s.jsx(gt,{title:"Move down",onClick:o,t,children:s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:s.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"})})}),s.jsx(gt,{title:"Delete cell",onClick:i,t,danger:!0,children:s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:s.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 s.jsx(mR,{typeLabel:KI[e.type]??e.type.toUpperCase(),typeColor:E,accent:d,idleBorder:t.cellBorder,background:t.cellBg,headerBackground:`${t.tableHeaderBg}80`,active:l||e.status!=="idle",title:u,actions:T,status:s.jsx(QI,{cell:e,t}),onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:a})}const KI={sql:"SQL",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 Ve(e,t){return typeof window>"u"?t:getComputedStyle(document.documentElement).getPropertyValue(e).trim()||t}function o$(){return{sql:Ve("--cell-sql","#3b8ef0"),markdown:Ve("--cell-md","#2fb97a"),dql:Ve("--cell-insight","#ffc857"),param:Ve("--cell-inputs","#9aa0ae"),chart:Ve("--cell-chart","#b067f7"),pivot:Ve("--cell-pivot","#e5a84d"),single_value:Ve("--cell-single","#b067f7"),filter:Ve("--cell-filter","#f26a6a"),table:Ve("--cell-table","#5dd1c8"),map:Ve("--cell-goal","#61d095"),writeback:Ve("--cell-callout","#ff7ac6"),python:Ve("--cell-sql","#3b8ef0"),chat:Ve("--cell-chat","#8a8f9b")}}const qI=new Proxy({},{get(e,t){return o$()[t]}}),s$={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",subtitle:"Python cell via Pyodide sidecar.",color:"#3572a5",badge:"v0.11"}};function JI(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 QI({cell:e,t}){var i;const{status:n}=e;if(n==="idle"&&e.executionCount===void 0)return null;let r=t.textMuted,o="";if(n==="running")r=t.cellBorderRunning,o="Running…";else if(n==="error")r=t.error,o="Error";else if(e.executionCount!==void 0)if(r=t.success,((i=e.result)==null?void 0:i.executionTime)!==void 0){const a=e.result.executionTime;o=a<1e3?`${Math.max(1,Math.round(a))}ms`:`${(a/1e3).toFixed(1)}s`}else o=`[${e.executionCount}]`;return s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:10,fontFamily:t.font,color:t.textMuted,flexShrink:0},children:[s.jsx("span",{"aria-hidden":!0,style:{width:6,height:6,borderRadius:999,background:r,boxShadow:n==="running"?`0 0 0 3px ${r}33`:void 0,animation:n==="running"?"pulse 1.2s ease-in-out infinite":void 0,flexShrink:0}}),o,s.jsx("style",{children:"@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.5} }"})]})}function i$(e){if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=o=>{var i;return((i=e.match(new RegExp(`\\b${o}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:i[1])??""},n=e.match(/\btags\s*=\s*\[([^\]]*)\]/i),r=n?(n[1].match(/"([^"]*)"/g)??[]).map(o=>o.slice(1,-1)):[];return{domain:t("domain"),owner:t("owner"),description:t("description"),blockType:t("type")||"custom",tags:r}}function sc(e,t,n){const r=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return r.test(e)?e.replace(r,`$1"${n.replace(/"/g,'\\"')}"`):e}function a$(e,t){const n=t.map(o=>`"${o}"`).join(", "),r=/(\btags\s*=\s*)\[[^\]]*\]/i;return r.test(e)?e.replace(r,`$1[${n}]`):e}function l$({binding:e,t,onRevert:n,onUnbind:r}){const o=e.state==="forked",i=o?t.warning:t.success,a=o?"FORKED":"BOUND",l=o?"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 s.jsxs("div",{title:l,style:{display:"flex",alignItems:"center",gap:8,padding:"4px 10px",borderBottom:`1px solid ${t.cellBorder}`,background:`${i}10`,fontFamily:t.fontMono,fontSize:11},children:[s.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:a}),s.jsx("span",{style:{color:t.textSecondary},children:e.path}),e.version&&s.jsxs("span",{style:{color:t.textMuted},children:["· v",e.version]}),!o&&s.jsx("span",{title:"Bound cells track the block file — edits fork locally",style:{color:t.textMuted},children:"🔒"}),s.jsx("div",{style:{flex:1}}),o&&s.jsx("button",{onClick:n,title:"Discard local edits and restore the block file body",style:jf(t,i),children:"Revert"}),s.jsx("button",{onClick:r,title:"Detach this cell from the block file",style:jf(t,t.btnBorder),children:"Unbind"})]})}function jf(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 c$({content:e,onChange:t,t:n}){const r=i$(e);if(!r)return null;const o={background:n.editorBg,border:`1px solid ${n.cellBorder}`,borderRadius:3,color:n.textSecondary,fontSize:11,fontFamily:n.fontMono,padding:"2px 6px",outline:"none"},i={fontSize:9,fontWeight:700,color:n.textMuted,fontFamily:n.font,letterSpacing:"0.05em",textTransform:"uppercase",marginRight:4,flexShrink:0},a={display:"flex",alignItems:"center",gap:4};return s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px",padding:"5px 10px",borderBottom:`1px solid ${n.cellBorder}`,background:`${n.tableHeaderBg}40`},children:[s.jsxs("div",{style:a,children:[s.jsx("span",{style:i,children:"domain"}),s.jsx("input",{style:{...o,width:80},value:r.domain,placeholder:"e.g. finance",onChange:l=>t(sc(e,"domain",l.target.value))})]}),s.jsxs("div",{style:a,children:[s.jsx("span",{style:i,children:"owner"}),s.jsx("input",{style:{...o,width:90},value:r.owner,placeholder:"e.g. data-team",onChange:l=>t(sc(e,"owner",l.target.value))})]}),s.jsxs("div",{style:a,children:[s.jsx("span",{style:i,children:"tags"}),s.jsx("input",{style:{...o,width:110},value:r.tags.join(", "),placeholder:"revenue, kpi",onChange:l=>{const c=l.target.value.split(",").map(d=>d.trim()).filter(Boolean);t(a$(e,c))}})]}),s.jsxs("div",{style:{...a,flex:1},children:[s.jsx("span",{style:i,children:"description"}),s.jsx("input",{style:{...o,flex:1,minWidth:120},value:r.description,placeholder:"What this block measures",onChange:l=>t(sc(e,"description",l.target.value))})]})]})}const d$=new Set(["sql","dql","param","writeback","python","chat"]);function E$({cell:e,index:t}){var oe;const{state:n,dispatch:r}=fe(),o=ie[n.themeMode],{executeCell:i,executeDependents:a,cancelCell:l}=ca(),[c,d]=f.useState(!1),[E,u]=f.useState(!1),[T,p]=f.useState(e.name??""),[h,A]=f.useState(!0),[S,R]=f.useState("table"),[m,I]=f.useState(null),[O,N]=f.useState(!1),[x,g]=f.useState(!1),[C,y]=f.useState(!1),w=f.useMemo(()=>C?gD(e,n.cells):null,[C,e,n.cells]),v=e.type==="sql"||e.type==="dql"||e.type==="chart"||e.type==="pivot"||e.type==="single_value"||e.type==="filter"||e.type==="table",B=JI(e,o),b=e.type!=="markdown"&&e.type!=="param",L=f.useRef(null),D=f.useRef(e.content),[M,U]=f.useState(!1),P=f.useMemo(()=>n.schemaTables.length>0?Object.fromEntries(n.schemaTables.map(V=>[V.name,V.columns.map(le=>le.name)])):void 0,[n.schemaTables]);f.useEffect(()=>{if(e.status==="success"&&e.result){const V=Cr(e.result,e.chartConfig);I(V!=="table"?V:null),R(V!=="table"?"chart":"table")}},[e.status,e.result,e.chartConfig]);const _=f.useCallback(()=>{b&&i(e.id)},[e.id,i,b]),F=f.useCallback(V=>{const le={content:V},Te=e.blockBinding;if((Te==null?void 0:Te.originalContent)!==void 0){const ne=V.trim()!==Te.originalContent.trim()?"forked":"bound";ne!==Te.state&&(le.blockBinding={...Te,state:ne})}r({type:"UPDATE_CELL",id:e.id,updates:le}),U(V!==D.current)},[e.id,e.blockBinding,r]),k=f.useCallback(()=>{var le;const V=D.current;r({type:"UPDATE_CELL",id:e.id,updates:{content:V}}),(le=L.current)==null||le.resetTo(V),U(!1)},[e.id,r]),H=f.useCallback(()=>{if(e.content.trim())try{const V=n$(e.content,{language:"sql",tabWidth:2,keywordCase:"upper",linesBetweenQueries:1});r({type:"UPDATE_CELL",id:e.id,updates:{content:V}})}catch{}},[e.content,e.id,r]),Q=f.useCallback(()=>{H(),setTimeout(()=>i(e.id),80)},[H,i,e.id]),q=f.useCallback(V=>r({type:"UPDATE_CELL",id:e.id,updates:V}),[r,e.id]),$=()=>{r({type:"DELETE_CELL",id:e.id})},Z=()=>{r({type:"MOVE_CELL",id:e.id,direction:"up"})},Y=()=>{r({type:"MOVE_CELL",id:e.id,direction:"down"})},G={cell:e,t:o,onMoveUp:Z,onMoveDown:Y,onDelete:$};if(n.appMode!=="studio"&&d$.has(e.type))return s.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:[s.jsx("span",{style:{opacity:.7},children:"◎"}),s.jsxs("span",{children:[e.type.toUpperCase()," cell hidden in App view",e.name?` · ${e.name}`:""]})]});if(e.type==="param")return s.jsx(nn,{...G,onRun:()=>a(e.id),children:s.jsx(r1,{cell:e,themeMode:n.themeMode,onApplyParam:a})});if(e.type==="pivot")return s.jsx(nn,{...G,children:s.jsx(z1,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:q})});if(e.type==="single_value")return s.jsx(nn,{...G,children:s.jsx($1,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:q})});if(e.type==="filter")return s.jsx(nn,{...G,children:s.jsx(k1,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:q})});if(e.type==="chart")return s.jsx(nn,{...G,children:s.jsx(w1,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:q})});if(e.type==="table")return s.jsx(nn,{...G,children:s.jsx(q1,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:q})});if(e.type==="chat")return s.jsx(nn,{...G,children:s.jsx(uD,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:q})});const J=s$[e.type];if(J)return s.jsx(nn,{...G,children:s.jsx(o1,{cell:e,themeMode:n.themeMode,title:J.title,subtitle:J.subtitle,color:J.color,badge:J.badge})});const te=()=>{u(!1),r({type:"UPDATE_CELL",id:e.id,updates:{name:T.trim()||void 0}})},re=(e.result||e.error)&&e.type!=="markdown";return e.result&&Cr(e.result,e.chartConfig),s.jsxs("div",{onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),style:{display:"flex",gap:0,marginBottom:2},children:[C&&w&&s.jsx(Sh,{cell:e,initialContent:w.derivedFromUpstream?w.content:void 0,initialName:w.suggestedName,initialDescription:w.suggestedDescription,onClose:()=>y(!1),onSaved:({path:V,name:le})=>{r({type:"FILE_ADDED",file:{name:le,path:V,type:"block",folder:"blocks"}})}}),s.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${c||e.status!=="idle"?B:o.cellBorder}`,background:o.cellBg,boxShadow:e.status!=="idle"?`0 0 0 3px ${B}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:[s.jsxs("div",{style:{minHeight:32,display:"flex",alignItems:"center",padding:"8px 14px",gap:8,background:"transparent"},children:[s.jsx("span",{"aria-hidden":!0,style:{width:6,height:6,borderRadius:999,background:qI[e.type]??o.accent,flexShrink:0}}),s.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:500,letterSpacing:"0.2px",color:o.textSecondary,flexShrink:0,whiteSpace:"nowrap"},children:KI[e.type]}),c&&(e.type==="sql"||e.type==="dql")&&s.jsx(AD,{themeMode:n.themeMode,cellType:e.type,onInsert:V=>F(V)}),c&&(e.type==="sql"||e.type==="dql")&&s.jsx("button",{title:"Format SQL (clean up whitespace & keywords)",onClick:H,style:{background:"transparent",border:`1px solid ${o.btnBorder}`,borderRadius:4,color:o.textMuted,fontSize:10,fontFamily:o.font,fontWeight:600,letterSpacing:"0.04em",padding:"1px 7px",cursor:"pointer",transition:"color 0.15s, border-color 0.15s"},onMouseEnter:V=>{V.currentTarget.style.color=o.textSecondary,V.currentTarget.style.borderColor=o.accent},onMouseLeave:V=>{V.currentTarget.style.color=o.textMuted,V.currentTarget.style.borderColor=o.btnBorder},children:"Format"}),M&&(e.type==="sql"||e.type==="dql")&&s.jsx("button",{title:"Reset to last saved version (discard changes)",onClick:k,style:{background:"transparent",border:`1px solid ${o.btnBorder}`,borderRadius:4,color:o.error,fontSize:10,fontFamily:o.font,fontWeight:600,letterSpacing:"0.04em",padding:"1px 7px",cursor:"pointer",transition:"color 0.15s, border-color 0.15s"},onMouseEnter:V=>{V.currentTarget.style.borderColor=o.error},onMouseLeave:V=>{V.currentTarget.style.borderColor=o.btnBorder},children:"↺ Reset"}),c&&v&&s.jsx("button",{title:"Save this cell as a reusable block",onClick:()=>y(!0),style:{background:"transparent",border:`1px solid ${o.btnBorder}`,borderRadius:4,color:o.textMuted,fontSize:10,fontFamily:o.font,fontWeight:600,letterSpacing:"0.04em",padding:"1px 7px",cursor:"pointer",transition:"color 0.15s, border-color 0.15s"},onMouseEnter:V=>{V.currentTarget.style.color=o.textSecondary,V.currentTarget.style.borderColor=o.accent},onMouseLeave:V=>{V.currentTarget.style.color=o.textMuted,V.currentTarget.style.borderColor=o.btnBorder},children:"Save as Block"}),(e.type==="sql"||e.type==="dql")&&s.jsx(i1,{cells:n.cells,index:t,content:e.content,themeMode:n.themeMode,onInsertHandle:V=>{const le=`{{${V}}}`,Te=e.content??"";if(Te.includes(le))return;const de=Te.trim().length===0?`SELECT * FROM ${le}`:`${Te.replace(/\s*$/,"")} ${le}`;F(de)}}),E?s.jsx("input",{autoFocus:!0,value:T,onChange:V=>p(V.target.value),onBlur:te,onKeyDown:V=>{V.key==="Enter"&&te(),V.key==="Escape"&&u(!1)},style:{background:"transparent",border:`1px solid ${o.cellBorderActive}`,borderRadius:4,color:o.textSecondary,fontSize:12,fontFamily:o.fontMono,padding:"1px 6px",outline:"none",width:140}}):e.name&&s.jsx("span",{onClick:()=>{p(e.name??""),u(!0)},title:"Click to rename",style:{color:o.textSecondary,fontSize:12,fontFamily:o.fontMono,cursor:"text",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:200},children:e.name}),s.jsx("div",{style:{flex:1}}),s.jsx(QI,{cell:e,t:o}),c&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[!e.name&&!E&&s.jsx(gt,{title:"Name this cell",onClick:()=>{p(""),u(!0)},t:o,children:s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:s.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"})})}),b&&e.status==="running"?s.jsx(gt,{title:"Cancel execution",onClick:()=>l(e.id),t:o,danger:!0,children:s.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:s.jsx("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1"})})}):b?s.jsx(gt,{title:"Run cell (Shift+Enter)",onClick:_,t:o,accent:!0,children:s.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:s.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})})}):null,s.jsx(gt,{title:"Move up",onClick:Z,t:o,children:s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:s.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"})})}),s.jsx(gt,{title:"Move down",onClick:Y,t:o,children:s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:s.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"})})}),s.jsx(gt,{title:"Delete cell",onClick:$,t:o,danger:!0,children:s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:s.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==="dql"&&s.jsx(c$,{content:e.content,onChange:F,t:o}),e.blockBinding&&s.jsx(l$,{binding:e.blockBinding,t:o,onRevert:async()=>{var le;const V=e.blockBinding;if(V)try{const Te=await z.openBlockStudio(V.path),de=Pd(Te.source)??Te.source;r({type:"UPDATE_CELL",id:e.id,updates:{content:de,blockBinding:{...V,state:"bound",originalContent:de}}}),(le=L.current)==null||le.resetTo(de)}catch(Te){console.error("Failed to revert bound cell",Te)}},onUnbind:()=>{r({type:"UPDATE_CELL",id:e.id,updates:{blockBinding:void 0}})}}),e.type==="markdown"?s.jsx(n1,{value:e.content,onChange:F,themeMode:n.themeMode}):s.jsx(jd,{value:e.content,onChange:F,onRun:_,themeMode:n.themeMode,schema:P,errorMessage:e.status==="error"?e.error:void 0,editorRef:L}),re&&s.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[s.jsxs("div",{style:{height:28,display:"flex",alignItems:"center",padding:"0 12px",gap:10,borderBottom:e.result&&h?`1px solid ${o.cellBorder}`:"none",background:`${o.tableHeaderBg}60`},children:[e.result&&s.jsxs("span",{style:{fontSize:11,fontFamily:o.font,color:o.textMuted},children:[(e.result.rowCount??e.result.rows.length).toLocaleString()," rows",e.result.executionTime!==void 0&&s.jsxs(s.Fragment,{children:[" · ",e.result.executionTime<1e3?`${e.result.executionTime}ms`:`${(e.result.executionTime/1e3).toFixed(2)}s`]})]}),e.fromSnapshot&&e.result&&s.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&&s.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.error},children:"Error"}),s.jsx("div",{style:{flex:1}}),e.result&&h&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:3,position:"relative"},children:[s.jsx("button",{onClick:()=>{R("table"),N(!1)},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${S==="table"?o.accent:o.btnBorder}`,background:S==="table"?`${o.accent}20`:"transparent",color:S==="table"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s"},children:"Table"}),s.jsxs("div",{style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>{S==="chart"&&O?N(!1):(R("chart"),N(V=>!V))},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${S==="chart"?o.accent:o.btnBorder}`,background:S==="chart"?`${o.accent}20`:"transparent",color:S==="chart"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s",display:"flex",alignItems:"center",gap:3},children:[m?((oe=da.find(V=>V.value===m))==null?void 0:oe.label)??"Chart":"Chart",s.jsx("svg",{width:"6",height:"6",viewBox:"0 0 8 8",fill:"currentColor",children:s.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),O&&s.jsx(u$,{selected:m,onSelect:V=>{I(V),R("chart"),N(!1)},onClose:()=>N(!1),t:o})]}),S==="chart"&&s.jsx("button",{onClick:()=>g(V=>!V),title:"Chart configuration",style:{padding:"1px 5px",fontSize:11,borderRadius:3,cursor:"pointer",border:`1px solid ${x?o.accent:o.btnBorder}`,background:x?`${o.accent}20`:"transparent",color:x?o.accent:o.textMuted,transition:"all 0.15s",display:"flex",alignItems:"center"},children:s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:s.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"})})})]}),s.jsxs("button",{onClick:()=>A(V=>!V),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:[s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:h?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.15s"},children:s.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})}),h?"Hide":"Show"]})]}),h&&s.jsxs(s.Fragment,{children:[e.error&&s.jsx(CD,{message:e.error,themeMode:n.themeMode,onFix:b?Q:void 0,schemaTables:n.schemaTables}),e.result&&!e.error&&(S==="chart"&&m?s.jsxs(s.Fragment,{children:[ua(m,e.result,n.themeMode,e.chartConfig),x&&s.jsx(T$,{columns:e.result.columns,chartConfig:e.chartConfig,onChange:V=>r({type:"UPDATE_CELL",id:e.id,updates:{chartConfig:{...e.chartConfig,...V}}}),t:o})]}):s.jsx(Kn,{result:e.result,themeMode:n.themeMode}))]})]}),b&&s.jsx(cj,{cellContent:e.content,cellType:e.type,cellName:e.name,themeMode:n.themeMode,t:o,onFocusNode:V=>{r({type:"SET_LINEAGE_FOCUS",nodeId:V}),n.lineageFullscreen||r({type:"TOGGLE_LINEAGE_FULLSCREEN"})}})]})]})}function gt({title:e,onClick:t,children:n,t:r,accent:o,danger:i}){const[a,l]=f.useState(!1);return s.jsx("button",{title:e,onClick:t,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",background:a?i?`${r.error}18`:o?`${r.accent}18`:r.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:a?i?r.error:o?r.accent:r.textSecondary:r.textMuted,transition:"all 0.15s",padding:0},children:n})}function u$({selected:e,onSelect:t,onClose:n,t:r}){const[o,i]=f.useState(null);return _e.useEffect(()=>{const a=l=>{setTimeout(()=>n(),0)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[n]),s.jsx("div",{onMouseDown:a=>a.stopPropagation(),style:{position:"absolute",top:24,right:0,zIndex:200,background:r.cellBg,border:`1px solid ${r.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:da.map(({value:a,label:l})=>s.jsx("button",{onClick:()=>t(a),onMouseEnter:()=>i(a),onMouseLeave:()=>i(null),style:{background:e===a?`${r.accent}20`:o===a?r.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:e===a?r.accent:r.textSecondary,fontSize:11,fontFamily:r.font,fontWeight:e===a?600:400,padding:"4px 10px",textAlign:"left",transition:"background 0.1s"},children:l},a))})}function T$({columns:e,chartConfig:t,onChange:n,t:r}){const o={background:r.inputBg,border:`1px solid ${r.inputBorder}`,borderRadius:4,color:r.textPrimary,fontSize:11,fontFamily:r.fontMono,padding:"3px 6px",outline:"none",minWidth:100,flex:1},i={fontSize:9,fontWeight:700,color:r.textMuted,fontFamily:r.font,letterSpacing:"0.05em",textTransform:"uppercase",minWidth:40,flexShrink:0};return s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px 16px",padding:"8px 12px",borderTop:`1px solid ${r.cellBorder}`,background:`${r.tableHeaderBg}40`},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{style:i,children:"X axis"}),s.jsxs("select",{style:o,value:(t==null?void 0:t.x)??"",onChange:a=>n({x:a.target.value||void 0}),children:[s.jsx("option",{value:"",children:"Auto"}),e.map(a=>s.jsx("option",{value:a,children:a},a))]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{style:i,children:"Y axis"}),s.jsxs("select",{style:o,value:(t==null?void 0:t.y)??"",onChange:a=>n({y:a.target.value||void 0}),children:[s.jsx("option",{value:"",children:"Auto"}),e.map(a=>s.jsx("option",{value:a,children:a},a))]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{style:i,children:"Color"}),s.jsxs("select",{style:o,value:(t==null?void 0:t.color)??"",onChange:a=>n({color:a.target.value||void 0}),children:[s.jsx("option",{value:"",children:"None"}),e.map(a=>s.jsx("option",{value:a,children:a},a))]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:150},children:[s.jsx("span",{style:i,children:"Title"}),s.jsx("input",{style:{...o,fontFamily:r.font},value:(t==null?void 0:t.title)??"",placeholder:"Chart title",onChange:a=>n({title:a.target.value||void 0})})]})]})}const f$={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149",pending_recertification:"#db6d28"};function p$({themeMode:e,onPick:t,autoFocus:n=!0,compact:r=!0}){const o=ie[e],[i,a]=f.useState([]),[l,c]=f.useState(!0),[d,E]=f.useState(""),[u,T]=f.useState(""),[p,h]=f.useState(""),A=f.useRef(null);f.useEffect(()=>{let O=!1;return c(!0),z.getBlockLibrary().then(N=>{O||a(N.blocks)}).finally(()=>{O||c(!1)}),()=>{O=!0}},[]),f.useEffect(()=>{if(n){const O=setTimeout(()=>{var N;return(N=A.current)==null?void 0:N.focus()},30);return()=>clearTimeout(O)}},[n]);const S=f.useMemo(()=>[...new Set(i.map(O=>O.domain))].sort(),[i]),R=f.useMemo(()=>[...new Set(i.map(O=>O.status))].sort(),[i]),m=f.useMemo(()=>i.filter(O=>{if(d){const N=d.toLowerCase();if(!O.name.toLowerCase().includes(N)&&!O.description.toLowerCase().includes(N))return!1}return!(u&&O.domain!==u||p&&O.status!==p)}),[i,d,u,p]),I={background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:4,color:o.textPrimary,fontSize:11,fontFamily:o.font,padding:"4px 6px",outline:"none"};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:r?340:void 0},children:[s.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[s.jsx("input",{ref:A,value:d,onChange:O=>E(O.target.value),placeholder:"Search blocks...",style:{...I,flex:1,padding:"6px 8px"}}),s.jsxs("select",{value:u,onChange:O=>T(O.target.value),style:I,children:[s.jsx("option",{value:"",children:"All domains"}),S.map(O=>s.jsx("option",{value:O,children:O},O))]}),s.jsxs("select",{value:p,onChange:O=>h(O.target.value),style:I,children:[s.jsx("option",{value:"",children:"Any"}),R.map(O=>s.jsx("option",{value:O,children:O},O))]})]}),s.jsx("div",{style:{maxHeight:r?220:420,overflowY:"auto",display:"flex",flexDirection:"column",border:`1px solid ${o.cellBorder}`,borderRadius:4},children:l?s.jsx(Gf,{t:o,children:"Loading blocks..."}):m.length===0?s.jsx(Gf,{t:o,children:i.length===0?"No blocks yet. Save a cell as a block to get started.":"No blocks match your filters."}):m.map(O=>s.jsx(S$,{block:O,onClick:()=>t(O),t:o,compact:r},O.path))})]})}function Gf({children:e,t}){return s.jsx("div",{style:{padding:16,textAlign:"center",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:e})}function S$({block:e,onClick:t,t:n,compact:r}){const[o,i]=f.useState(!1),a=f$[e.status]??n.textMuted;return s.jsxs("button",{onClick:t,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:o?`${n.accent}14`:"transparent",border:"none",borderBottom:`1px solid ${n.cellBorder}`,cursor:"pointer",padding:r?"8px 10px":"10px 12px",textAlign:"left",fontFamily:n.font},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:3},children:[s.jsx("span",{style:{fontSize:12,fontWeight:600,color:n.textPrimary},children:e.name}),s.jsx("span",{style:{fontSize:9,fontWeight:600,color:a,background:`${a}18`,padding:"1px 6px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em"},children:e.status})]}),e.description&&s.jsx("div",{style:{fontSize:11,color:n.textMuted,lineHeight:1.3,marginBottom:3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.description}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:10,color:n.textMuted},children:[s.jsx("span",{style:{background:n.pillBg,padding:"1px 6px",borderRadius:4},children:e.domain||"no domain"}),e.owner&&s.jsxs("span",{children:["by ",e.owner]})]})]})}const R$=[{type:"block",label:"Block",Icon:wR,color:"#6b8afd",group:"library"},{type:"chat",label:"Chat",Icon:p_,color:"#8a8f9b",group:"compute"},{type:"sql",label:"SQL",Icon:c_,color:"#3b8ef0",group:"compute"},{type:"markdown",label:"Text",Icon:_R,color:"#2fb97a",group:"compute"},{type:"chart",label:"Chart",Icon:d_,color:"#b067f7",group:"viz"},{type:"pivot",label:"Pivot",Icon:E_,color:"#e5a84d",group:"viz"},{type:"single_value",label:"Single value",Icon:u_,color:"#b067f7",group:"viz"},{type:"table",label:"Table",Icon:$L,color:"#5dd1c8",group:"viz"},{type:"param",label:"Inputs",Icon:T_,color:"#9aa0ae",group:"io"},{type:"filter",label:"Filter",Icon:f_,color:"#f26a6a",group:"transform"}];function ic({afterId:e}){const{state:t,dispatch:n}=fe(),r=ie[t.themeMode],[o,i]=f.useState(!1),[a,l]=f.useState(!1),[c,d]=f.useState(!1),[E,u]=f.useState(!1),T=f.useRef(null);f.useEffect(()=>{if(!a)return;function S(R){T.current&&!T.current.contains(R.target)&&(l(!1),d(!1))}return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[a]);const p=()=>{l(!1),d(!1)},h=S=>{const R=ze(S);n({type:"ADD_CELL",cell:R,afterId:e}),S==="sql"&&n({type:"SET_SIDEBAR_PANEL",panel:"schema"}),p()},A=async S=>{let R;try{R=await z.openBlockStudio(S.path)}catch(O){console.error("Failed to bind block cell",O),window.alert(`Couldn't load block ${S.path}. Check the console for details.`),p();return}const m=Pd(R.source)??R.source,I=ze("sql",m);I.name=S.name,I.blockBinding={path:S.path,state:"bound",originalContent:m},n({type:"ADD_CELL",cell:I,afterId:e}),p()};return s.jsxs("div",{ref:T,onDragOver:S=>{S.dataTransfer.types.includes(gi)&&(S.preventDefault(),u(!0))},onDragLeave:()=>u(!1),onDrop:S=>{const R=rh(S.dataTransfer.getData(gi));if(!R)return;S.preventDefault(),u(!1);const m=ze("sql",R.reference);n({type:"ADD_CELL",cell:m,afterId:e}),z.trackUsage(R.name),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:R.name}}))},onMouseEnter:()=>i(!0),onMouseLeave:()=>{i(!1),u(!1)},style:{position:"relative",height:28,display:"flex",alignItems:"center",justifyContent:"center",cursor:"default"},children:[(o||a||E)&&s.jsxs("button",{onClick:()=>l(S=>!S),style:{position:"relative",zIndex:2,height:22,padding:"0 10px",borderRadius:11,border:`1px solid ${E?r.accent:r.cellBorderActive}`,background:E?`${r.accent}28`:`${r.accent}18`,color:r.accent,cursor:"pointer",fontSize:12,fontFamily:r.font,fontWeight:500,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s"},children:[s.jsx("span",{style:{fontSize:14,lineHeight:1,marginTop:-1},children:"+"}),"Add cell"]}),a&&s.jsxs("div",{style:{position:"absolute",top:26,left:"50%",transform:"translateX(-50%)",zIndex:100,background:r.modalBg,border:`1px solid ${r.cellBorder}`,borderRadius:10,boxShadow:"0 12px 32px rgba(0,0,0,0.35)",padding:10,display:"flex",flexDirection:"column",gap:8,minWidth:760},children:[s.jsx("div",{style:{display:"flex",gap:6,flexWrap:"nowrap",alignItems:"center",justifyContent:"space-between"},children:R$.map(S=>s.jsx(h$,{entry:S,active:S.type==="block"&&c,onClick:()=>{if(S.type==="block"){d(R=>!R);return}h(S.type)},t:r},S.type))}),c&&s.jsx("div",{style:{padding:"6px 2px 2px",borderTop:`1px solid ${r.cellBorder}`},children:s.jsx(p$,{themeMode:t.themeMode,onPick:S=>void A(S)})})]})]})}function h$({entry:e,onClick:t,t:n,active:r=!1}){const[o,i]=f.useState(!1),a=r||o,l=e.Icon;return s.jsxs("button",{onClick:t,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),title:e.label,style:{background:a?`${e.color}18`:"transparent",border:`1px solid ${a?e.color:n.cellBorder}`,borderRadius:8,cursor:"pointer",color:a?e.color:n.textSecondary,fontSize:11,fontFamily:n.font,fontWeight:500,padding:"10px 6px",minWidth:76,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:6,transition:"all 0.12s"},children:[s.jsx("span",{style:{color:e.color,display:"flex",alignItems:"center",justifyContent:"center"},children:s.jsx(l,{size:18,strokeWidth:1.75})}),s.jsx("span",{style:{letterSpacing:"0.02em"},children:e.label})]})}function A$({registerCellRef:e}){const{state:t,dispatch:n}=fe(),{executeCell:r}=ca(),o=ie[t.themeMode],[i,a]=f.useState(null),l=f.useRef(0),[c,d]=f.useState(null),[E,u]=f.useState(null);f.useCallback(S=>{a(S)},[]),f.useEffect(()=>{i&&t.inspectorOpen&&n({type:"SET_INSPECTOR_CONTEXT",context:{kind:"cell",cellId:i}})},[i,t.inspectorOpen,n]),f.useEffect(()=>{function S(R){var N;if(!i)return;const m=R.target;if(m.tagName==="TEXTAREA"||m.tagName==="INPUT"||m.isContentEditable||m.closest(".cm-editor")){a(null);return}const I=t.cells,O=I.findIndex(x=>x.id===i);if(O!==-1)switch(R.key){case"a":{R.preventDefault();const x=ze("sql");if(O===0)n({type:"ADD_CELL",cell:x,afterId:I[0].id}),n({type:"MOVE_CELL",id:x.id,direction:"up"});else{const g=I[O-1].id;n({type:"ADD_CELL",cell:x,afterId:g})}a(x.id);break}case"b":{R.preventDefault();const x=ze("sql");n({type:"ADD_CELL",cell:x,afterId:i}),a(x.id);break}case"d":{R.preventDefault();const x=Date.now();if(x-l.current<=500){if(n({type:"DELETE_CELL",id:i}),I.length>1){const g=O>0?O-1:1;a(((N=I[g])==null?void 0:N.id)??null)}else a(null);l.current=0}else l.current=x;break}case"Enter":{if(R.shiftKey){R.preventDefault();const x=I[O];x&&x.type!=="markdown"&&r(x.id)}break}}}return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[i,t.cells,n,r]),f.useEffect(()=>{function S(R){R.target.closest("[data-cell-id]")||a(null)}return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[]);const T=f.useCallback((S,R)=>{d(R),S.dataTransfer.effectAllowed="move",S.dataTransfer.setData("text/plain",String(R));const m=S.currentTarget;setTimeout(()=>{m.style.opacity="0.4"},0)},[]),p=f.useCallback(S=>{S.currentTarget.style.opacity="1",d(null),u(null)},[]),h=f.useCallback((S,R)=>{S.preventDefault(),S.dataTransfer.dropEffect="move",u(R)},[]),A=f.useCallback((S,R)=>{S.preventDefault(),c!==null&&c!==R&&n({type:"REORDER_CELL",fromIndex:c,toIndex:R}),d(null),u(null)},[c,n]);return t.cells.length===0?s.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[t.appMode==="studio"&&s.jsx(ic,{}),s.jsx(I$,{t:o})]}):s.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[t.appMode==="studio"&&s.jsx(ic,{afterId:void 0}),t.cells.map((S,R)=>s.jsxs(_e.Fragment,{children:[s.jsxs("div",{ref:m=>e(S.id,m),"data-cell-id":S.id,draggable:t.appMode==="studio",onDragStart:t.appMode==="studio"?m=>T(m,R):void 0,onDragEnd:t.appMode==="studio"?p:void 0,onDragOver:t.appMode==="studio"?m=>h(m,R):void 0,onDrop:t.appMode==="studio"?m=>A(m,R):void 0,onClick:m=>{const I=m.target;!I.closest(".cm-editor")&&!I.closest("textarea")&&!I.closest("input")&&a(S.id)},style:{outline:i===S.id?`2px solid ${o.accent}40`:"none",outlineOffset:2,borderRadius:10,transition:"outline 0.1s, transform 0.15s",position:"relative",...E===R&&c!==null&&c!==R?{borderTop:`2px solid ${o.accent}`}:{}},children:[s.jsx("div",{style:{position:"absolute",left:-20,top:8,width:16,height:24,display:"flex",alignItems:"center",justifyContent:"center",cursor:"grab",color:o.textMuted,opacity:0,transition:"opacity 0.15s",zIndex:5},className:"drag-handle",children:s.jsxs("svg",{width:"8",height:"14",viewBox:"0 0 8 14",fill:"currentColor",children:[s.jsx("circle",{cx:"2",cy:"2",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"2",r:"1.2"}),s.jsx("circle",{cx:"2",cy:"7",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"7",r:"1.2"}),s.jsx("circle",{cx:"2",cy:"12",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"12",r:"1.2"})]})}),s.jsx(E$,{cell:S,index:R})]}),t.appMode==="studio"&&s.jsx(ic,{afterId:S.id})]},S.id)),s.jsx("style",{children:`
|
|
786
|
-
[data-cell-id]:hover .drag-handle { opacity: 0.5 !important; }
|
|
787
|
-
[data-cell-id]:hover .drag-handle:hover { opacity: 1 !important; }
|
|
788
|
-
`})]})}function I$({t:e}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"48px 0",gap:12,color:e.textMuted},children:[s.jsx("svg",{width:"40",height:"40",viewBox:"0 0 16 16",fill:"currentColor",style:{opacity:.3},children:s.jsx("path",{d:"M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 8.75 4.25V1.5ZM8.75 5.5h2.836L10.25 3.664V4.25c0 .138.112.25.25.25H8.75Z"})}),s.jsx("span",{style:{fontSize:13,fontFamily:e.font},children:"Empty notebook. Click + to add your first cell."})]})}function m$(){const{state:e}=fe(),t=ie[e.themeMode],n=e.cells.filter(r=>r.type==="markdown"||r.result&&r.status!=="running"||r.error);return s.jsx("div",{style:{flex:1,overflow:"auto",background:t.appBg,padding:"32px 24px 48px"},children:s.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",display:"flex",flexDirection:"column",gap:24},children:[s.jsxs("div",{style:{textAlign:"center",marginBottom:8},children:[s.jsx("h1",{style:{fontSize:28,fontWeight:700,color:t.textPrimary,fontFamily:t.font,letterSpacing:"-0.3px",margin:0},children:e.notebookTitle||"Untitled"}),s.jsxs("p",{style:{fontSize:12,color:t.textMuted,fontFamily:t.font,marginTop:6},children:[e.cells.filter(r=>r.result).length," results",e.activeFile?` · ${e.activeFile.path}`:""]})]}),n.length===0?s.jsx("div",{style:{textAlign:"center",padding:48,color:t.textMuted,fontSize:14,fontFamily:t.font},children:"No outputs to display. Run some cells first, then switch to dashboard mode."}):n.map(r=>s.jsx(O$,{cell:r},r.id))]})})}function O$({cell:e}){const{state:t}=fe(),n=ie[t.themeMode];if(e.type==="markdown")return s.jsx("div",{style:{background:n.cellBg,borderRadius:10,border:`1px solid ${n.cellBorder}`,padding:"16px 24px",fontSize:14,lineHeight:1.7,fontFamily:n.font,color:n.textSecondary,whiteSpace:"pre-wrap"},dangerouslySetInnerHTML:{__html:g$(e.content,n)}});if(e.error)return s.jsxs("div",{style:{background:n.cellBg,borderRadius:10,border:`1px solid ${n.error}40`,padding:"16px 24px"},children:[e.name&&s.jsx(N$,{name:e.name,t:n}),s.jsx("div",{style:{color:n.error,fontSize:12,fontFamily:n.fontMono,whiteSpace:"pre-wrap"},children:e.error})]});if(!e.result)return null;const r=Cr(e.result,e.chartConfig),o=r!=="table";return s.jsxs("div",{style:{background:n.cellBg,borderRadius:10,border:`1px solid ${n.cellBorder}`,overflow:"hidden"},children:[s.jsxs("div",{style:{padding:"10px 20px",borderBottom:`1px solid ${n.cellBorder}`,display:"flex",alignItems:"center",gap:8},children:[e.name?s.jsx("span",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,fontFamily:n.font,flex:1},children:e.name}):s.jsx("span",{style:{flex:1}}),s.jsxs("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.fontMono},children:[e.result.rowCount??e.result.rows.length," rows",e.result.executionTime!=null&&s.jsxs(s.Fragment,{children:[" · ",e.result.executionTime<1e3?`${e.result.executionTime}ms`:`${(e.result.executionTime/1e3).toFixed(1)}s`]})]})]}),s.jsx("div",{style:{padding:o?"16px 20px":0},children:o?ua(r,e.result,t.themeMode,e.chartConfig):s.jsx(Kn,{result:e.result,themeMode:t.themeMode})})]})}function N$({name:e,t}){return s.jsx("div",{style:{fontSize:13,fontWeight:600,color:t.textPrimary,fontFamily:t.font,marginBottom:8},children:e})}function g$(e,t){const n=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");return e.split(`
|
|
789
|
-
`).map(r=>{const o=r.trim(),i=o.match(/^(#{1,6})\s+(.+)$/);if(i){const l=i[1].length;return`<div style="font-size:${["28px","22px","18px","16px","14px","13px"][l-1]};font-weight:${l<=2?700:600};color:${t.textPrimary};margin:8px 0 4px">${n(i[2])}</div>`}if(/^[-*_]{3,}$/.test(o))return`<hr style="border:none;border-top:1px solid ${t.cellBorder};margin:8px 0"/>`;if(!o)return'<div style="height:6px"></div>';let a=n(o);return a=a.replace(/\*{2}(.+?)\*{2}/g,"<strong>$1</strong>"),a=a.replace(/\*(.+?)\*/g,"<em>$1</em>"),a=a.replace(/`(.+?)`/g,`<code style="background:${t.editorBg};padding:1px 4px;border-radius:3px;font-size:0.9em">$1</code>`),`<div style="margin-bottom:4px">${a}</div>`}).join("")}const ZI=[{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 x$(e){return e?ZI.find(t=>t.value===e)??{value:e,label:e,dot:"#888"}:null}function y$(){const{state:e,dispatch:t}=fe(),n=ie[e.themeMode],[r,o]=f.useState(null),i=f.useRef(null);if(f.useEffect(()=>{if(!r)return;const p=A=>{i.current&&!i.current.contains(A.target)&&o(null)},h=A=>{A.key==="Escape"&&o(null)};return document.addEventListener("mousedown",p),document.addEventListener("keydown",h),()=>{document.removeEventListener("mousedown",p),document.removeEventListener("keydown",h)}},[r]),!e.activeFile)return null;const a=e.activeFile.name.replace(/\.dqlnb$/,""),l=e.notebookMetadata,c=p=>{t({type:"UPDATE_NOTEBOOK_METADATA",updates:p})},d=x$(l.status),E=(l.categories??[]).length>0,u=!!l.description,T=!!l.projectFilter;return s.jsxs("div",{ref:i,style:{maxWidth:1080,margin:"0 auto",padding:"32px 48px 8px",display:"flex",flexDirection:"column",gap:12},children:[s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,alignItems:"center",position:"relative"},children:[s.jsx(Hs,{t:n,active:r==="status",filled:!!d,icon:s.jsx("span",{style:{color:(d==null?void 0:d.dot)??n.textMuted,fontSize:12},children:"●"}),label:(d==null?void 0:d.label)??"Add status",onClick:()=>o(r==="status"?null:"status"),children:r==="status"&&s.jsxs(Ys,{t:n,children:[ZI.map(p=>s.jsxs("button",{onClick:()=>{c({status:p.value}),o(null)},style:Wf(n,l.status===p.value),children:[s.jsx("span",{style:{color:p.dot,fontSize:12},children:"●"}),s.jsx("span",{children:p.label})]},p.value)),l.status&&s.jsx("button",{onClick:()=>{c({status:void 0}),o(null)},style:{...Wf(n,!1),color:n.textMuted},children:s.jsx("span",{children:"Clear"})})]})}),s.jsx(Hs,{t:n,active:r==="categories",filled:E,icon:s.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10},children:"#"}),label:E?(l.categories??[]).slice(0,3).join(", ")+((l.categories??[]).length>3?"…":""):"Add categories",onClick:()=>o(r==="categories"?null:"categories"),children:r==="categories"&&s.jsx(Ys,{t:n,width:260,children:s.jsx(L$,{t:n,value:l.categories??[],onChange:p=>c({categories:p.length?p:void 0})})})}),s.jsx(Hs,{t:n,active:r==="description",filled:u,icon:s.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10},children:"✎"}),label:u?Hf(l.description,48):"Add description",onClick:()=>o(r==="description"?null:"description"),children:r==="description"&&s.jsx(Ys,{t:n,width:320,children:s.jsx(Yf,{multiline:!0,initial:l.description??"",onCommit:p=>c({description:p||void 0}),placeholder:"What does this notebook answer?",style:C$(n)})})}),s.jsx(Hs,{t:n,active:r==="projectFilter",filled:T,icon:s.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10},children:"⌕"}),label:T?Hf(l.projectFilter,32):"Add project filter",onClick:()=>o(r==="projectFilter"?null:"projectFilter"),children:r==="projectFilter"&&s.jsx(Ys,{t:n,width:280,children:s.jsx(Yf,{initial:l.projectFilter??"",onCommit:p=>c({projectFilter:p||void 0}),placeholder:"e.g. team:analytics",style:em(n)})})})]}),s.jsx("div",{style:{fontSize:22,fontWeight:600,color:n.textPrimary,fontFamily:n.font,letterSpacing:"-0.01em"},children:a})]})}function Hf(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e}function Yf({initial:e,onCommit:t,multiline:n,placeholder:r,style:o}){const[i,a]=f.useState(e),l=f.useRef(i);l.current=i;const c=()=>{const d=l.current.trim();d!==e.trim()&&t(d)};return f.useEffect(()=>()=>c(),[]),n?s.jsx("textarea",{autoFocus:!0,value:i,onChange:d=>a(d.target.value),onBlur:c,placeholder:r,rows:4,style:o}):s.jsx("input",{autoFocus:!0,value:i,onChange:d=>a(d.target.value),onBlur:c,onKeyDown:d=>{d.key==="Enter"&&(d.preventDefault(),d.target.blur())},placeholder:r,style:o})}function Hs({t:e,active:t,filled:n,icon:r,label:o,onClick:i,children:a}){return s.jsxs("div",{style:{position:"relative"},children:[s.jsxs("button",{className:"dql-meta-pill",onClick:i,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"3px 9px",borderRadius:12,border:n?`1px solid ${e.cellBorder}`:`1px dashed ${e.cellBorder}`,background:t?`${e.accent}12`:n?e.pillBg:"transparent",color:n?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:[r,s.jsx("span",{children:o})]}),a]})}function Ys({t:e,width:t=200,children:n}){return s.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:n})}function Wf(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 C$(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 em(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 L$({t:e,value:t,onChange:n}){const[r,o]=f.useState(""),i=()=>{const a=r.trim();if(a){if(t.includes(a)){o("");return}n([...t,a]),o("")}};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.length>0&&s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:t.map(a=>s.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:[a,s.jsx("button",{onClick:()=>n(t.filter(l=>l!==a)),style:{background:"transparent",border:"none",color:e.textMuted,cursor:"pointer",padding:0,fontSize:12,lineHeight:1},"aria-label":`Remove ${a}`,children:"×"})]},a))}),s.jsx("input",{autoFocus:!0,value:r,onChange:a=>o(a.target.value),onKeyDown:a=>{a.key==="Enter"||a.key===","?(a.preventDefault(),i()):a.key==="Backspace"&&!r&&t.length>0&&n(t.slice(0,-1))},placeholder:"Add category, press Enter",style:em(e)})]})}function _$({onOpenFile:e,registerCellRef:t}){const{state:n}=fe(),r=ie[n.themeMode];return n.activeFile?n.dashboardMode?s.jsx(m$,{}):s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",background:r.appBg},children:[s.jsx(b$,{t:r}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"0 0 40px"},children:[s.jsx(y$,{}),s.jsx(A$,{registerCellRef:t})]})]}):s.jsx(Tb,{onOpenFile:e})}function b$({t:e}){const{state:t}=fe(),n=t.cells.length;return s.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:[s.jsx(D$,{t:e}),s.jsx("div",{style:{flex:1}}),s.jsxs("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.font,display:"flex",alignItems:"center",gap:12},children:[s.jsxs("span",{children:[n," ",n===1?"cell":"cells"]}),t.notebookDirty&&s.jsx("span",{style:{color:e.warning},children:"● unsaved"})]})]})}function D$({t:e}){const{state:t}=fe();if(!t.activeFile)return null;const n=t.activeFile.path.split("/").filter(Boolean);return s.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,fontSize:12,fontFamily:e.fontMono,color:e.textMuted,overflow:"hidden"},children:n.map((r,o)=>s.jsxs(_e.Fragment,{children:[o>0&&s.jsx("span",{style:{color:e.textMuted,opacity:.5},children:"/"}),s.jsx("span",{style:{color:o===n.length-1?e.textSecondary:e.textMuted,fontWeight:o===n.length-1?500:400,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:o===n.length-1?200:100},children:r})]},o))})}const $f={blank:"Blank",revenue:"Revenue Analysis",pipeline:"Pipeline Health"},M$={blank:"Start with an empty notebook.",revenue:"Pre-built queries for revenue metrics and trends.",pipeline:"Templates for data pipeline health monitoring."};function Vf(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function v$(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function P$(e){switch(e){case"revenue":return[ze("markdown",`# Revenue Analysis
|
|
790
|
-
|
|
791
|
-
This notebook analyzes revenue metrics and trends over time.`),{...ze("sql",`SELECT
|
|
792
|
-
DATE_TRUNC('month', order_date) AS month,
|
|
793
|
-
SUM(amount) AS revenue
|
|
794
|
-
FROM orders
|
|
795
|
-
GROUP BY 1
|
|
796
|
-
ORDER BY 1`),name:"monthly_revenue"},{...ze("sql",`SELECT
|
|
797
|
-
product_category,
|
|
798
|
-
SUM(amount) AS total_revenue,
|
|
799
|
-
COUNT(*) AS orders
|
|
800
|
-
FROM orders
|
|
801
|
-
GROUP BY 1
|
|
802
|
-
ORDER BY 2 DESC`),name:"revenue_by_category"}];case"pipeline":return[ze("markdown",`# Pipeline Health
|
|
803
|
-
|
|
804
|
-
Monitor data pipeline performance, SLA compliance, and error rates.`),{...ze("sql",`SELECT
|
|
805
|
-
pipeline_name,
|
|
806
|
-
COUNT(*) AS runs,
|
|
807
|
-
AVG(duration_seconds) AS avg_duration,
|
|
808
|
-
SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failures
|
|
809
|
-
FROM pipeline_runs
|
|
810
|
-
GROUP BY 1
|
|
811
|
-
ORDER BY 4 DESC`),name:"pipeline_summary"},{...ze("sql",`SELECT
|
|
812
|
-
*
|
|
813
|
-
FROM pipeline_runs
|
|
814
|
-
WHERE status = 'failed'
|
|
815
|
-
AND run_date >= CURRENT_DATE - INTERVAL '7 days'
|
|
816
|
-
ORDER BY run_date DESC`),name:"recent_failures"}];default:return[ze("sql")]}}function w$({onFileOpened:e}){const{state:t,dispatch:n}=fe(),r=ie[t.themeMode],[o,i]=f.useState(""),[a,l]=f.useState("blank"),[c,d]=f.useState(null),[E,u]=f.useState(!1),T=f.useRef(null);f.useEffect(()=>{var A;(A=T.current)==null||A.focus()},[]),f.useEffect(()=>{const A=S=>{S.key==="Escape"&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[n]);const p=async()=>{const A=v$(o);if(A){d(A);return}u(!0),d(null);const S=Vf(o),R=P$(a);try{const m=await z.createNotebook(S,a),I={name:`${S}.dqlnb`,path:m.path,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:I}),n({type:"OPEN_FILE",file:I,cells:R,title:o.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(I)}catch{const m=`notebooks/${S}.dqlnb`,I={name:`${S}.dqlnb`,path:m,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:I}),n({type:"OPEN_FILE",file:I,cells:R,title:o.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(I)}finally{u(!1)}},h=A=>{A.target===A.currentTarget&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return s.jsx("div",{onClick:h,style:{position:"fixed",inset:0,background:r.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:s.jsxs("div",{style:{background:r.modalBg,border:`1px solid ${r.cellBorder}`,borderRadius:12,width:480,maxWidth:"calc(100vw - 48px)",boxShadow:"0 20px 60px rgba(0,0,0,0.5)",overflow:"hidden"},children:[s.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s.jsx("h2",{style:{fontSize:16,fontWeight:600,color:r.textPrimary,fontFamily:r.font,margin:0},children:"New Notebook"}),s.jsx("button",{onClick:()=>n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),style:{background:"transparent",border:"none",cursor:"pointer",color:r.textMuted,fontSize:18,lineHeight:1,padding:"2px 4px",borderRadius:4},children:"×"})]}),s.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:20},children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Name"}),s.jsx("input",{ref:T,value:o,onChange:A=>{i(A.target.value),d(null)},onKeyDown:A=>{A.key==="Enter"&&p()},placeholder:"my-analysis",style:{background:r.inputBg,border:`1px solid ${c?r.error:r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:13,fontFamily:r.font,padding:"8px 12px",outline:"none",transition:"border-color 0.15s"}}),c&&s.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:c}),o&&!c&&s.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["File: ",Vf(o),".dqlnb"]})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Template"}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:Object.keys($f).map(A=>s.jsx(U$,{value:A,selected:a===A,onSelect:()=>l(A),label:$f[A],description:M$[A],t:r},A))})]})]}),s.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${r.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[s.jsx("button",{onClick:()=>n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),style:{background:r.btnBg,border:`1px solid ${r.btnBorder}`,borderRadius:6,color:r.textSecondary,cursor:"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 16px"},children:"Cancel"}),s.jsx("button",{onClick:p,disabled:E||!o.trim(),style:{background:r.accent,border:`1px solid ${r.accent}`,borderRadius:6,color:"#ffffff",cursor:E||!o.trim()?"not-allowed":"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 20px",opacity:E||!o.trim()?.6:1,display:"flex",alignItems:"center",gap:6},children:E?"Creating…":"Create Notebook"})]})]})})}function U$({value:e,selected:t,onSelect:n,label:r,description:o,t:i}){const[a,l]=f.useState(!1);return s.jsxs("div",{onClick:n,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{display:"flex",alignItems:"flex-start",gap:10,padding:"10px 12px",borderRadius:8,border:`1px solid ${t?i.cellBorderActive:a?i.textMuted:i.inputBorder}`,background:t?`${i.cellBorderActive}10`:a?i.sidebarItemHover:"transparent",cursor:"pointer",transition:"all 0.15s"},children:[s.jsx("div",{style:{width:16,height:16,borderRadius:8,border:`2px solid ${t?i.accent:i.textMuted}`,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:1,transition:"border-color 0.15s"},children:t&&s.jsx("div",{style:{width:8,height:8,borderRadius:4,background:i.accent}})}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:13,fontWeight:500,color:i.textPrimary,fontFamily:i.font,marginBottom:2},children:r}),s.jsx("div",{style:{fontSize:12,color:i.textSecondary,fontFamily:i.font},children:o})]})]})}function Xf(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function B$(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function F$({onFileOpened:e}){const{state:t,dispatch:n}=fe(),r=ie[t.themeMode],[o,i]=f.useState(""),[a,l]=f.useState(null),[c,d]=f.useState(!1),E=f.useRef(null);f.useEffect(()=>{var p;(p=E.current)==null||p.focus()},[]),f.useEffect(()=>{const p=h=>{h.key==="Escape"&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[n]);const u=async()=>{var A;const p=B$(o);if(p){l(p);return}d(!0),l(null);const h=Xf(o);try{const S=await z.createBlock(o.trim()),R={name:`${h}.dql`,path:S.path,type:"block",folder:"blocks",isNew:!0};n({type:"FILE_ADDED",file:R}),n({type:"CLOSE_NEW_BLOCK_MODAL"}),e(R)}catch(S){(A=S.message)!=null&&A.includes("already exists")?l("A block with this name already exists."):l(S.message??"Failed to create block.")}finally{d(!1)}},T=p=>{p.target===p.currentTarget&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return s.jsx("div",{onClick:T,style:{position:"fixed",inset:0,background:r.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:s.jsxs("div",{style:{background:r.modalBg,border:`1px solid ${r.cellBorder}`,borderRadius:12,width:420,maxWidth:"calc(100vw - 48px)",boxShadow:"0 20px 60px rgba(0,0,0,0.5)",overflow:"hidden"},children:[s.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s.jsx("h2",{style:{fontSize:16,fontWeight:600,color:r.textPrimary,fontFamily:r.font,margin:0},children:"New Block"}),s.jsx("button",{onClick:()=>n({type:"CLOSE_NEW_BLOCK_MODAL"}),style:{background:"transparent",border:"none",cursor:"pointer",color:r.textMuted,fontSize:18,lineHeight:1,padding:"2px 4px",borderRadius:4},children:"×"})]}),s.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Block Name"}),s.jsx("input",{ref:E,value:o,onChange:p=>{i(p.target.value),l(null)},onKeyDown:p=>{p.key==="Enter"&&u()},placeholder:"revenue-summary",style:{background:r.inputBg,border:`1px solid ${a?r.error:r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:13,fontFamily:r.font,padding:"8px 12px",outline:"none",transition:"border-color 0.15s"}}),a&&s.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:a}),o&&!a&&s.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["blocks/",Xf(o),".dql"]})]}),s.jsxs("div",{style:{fontSize:12,color:r.textMuted,fontFamily:r.font,lineHeight:1.5,padding:"8px 12px",background:r.pillBg,borderRadius:6},children:["Blocks are reusable SQL queries stored in the ",s.jsx("code",{style:{fontFamily:r.fontMono,fontSize:11},children:"blocks/"})," folder. They can be referenced from notebooks and other blocks."]})]}),s.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${r.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[s.jsx("button",{onClick:()=>n({type:"CLOSE_NEW_BLOCK_MODAL"}),style:{background:r.btnBg,border:`1px solid ${r.btnBorder}`,borderRadius:6,color:r.textSecondary,cursor:"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 16px"},children:"Cancel"}),s.jsx("button",{onClick:u,disabled:c||!o.trim(),style:{background:r.accent,border:`1px solid ${r.accent}`,borderRadius:6,color:"#ffffff",cursor:c||!o.trim()?"not-allowed":"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 20px",opacity:c||!o.trim()?.6:1,display:"flex",alignItems:"center",gap:6},children:c?"Creating...":"Create Block"})]})]})})}function k$({item:e,favorite:t,onInsert:n,onPreview:r,onCopySql:o,onToggleFavorite:i,t:a}){if(!e)return null;const l=e.kind==="metric"||e.kind==="dimension",c=!!e.sql,d=e.source?`${e.source.provider} · ${e.source.objectType}`:null;return s.jsxs("div",{style:{borderTop:`1px solid ${a.headerBorder}`,padding:"12px 10px",display:"flex",flexDirection:"column",gap:10,background:`${a.cellBg}cc`},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontSize:12,fontWeight:600,color:a.textPrimary,fontFamily:a.font},children:e.label||e.name}),s.jsxs("div",{style:{fontSize:10,color:a.textMuted,fontFamily:a.fontMono},children:[e.kind," · ",e.name]})]}),s.jsx("button",{onClick:i,style:{background:t?"#e3b34122":"transparent",border:`1px solid ${t?"#e3b34166":a.cellBorder}`,borderRadius:6,color:t?"#e3b341":a.textMuted,cursor:"pointer",fontSize:11,fontFamily:a.font,padding:"4px 8px"},children:t?"Favorited":"Favorite"})]}),e.description&&s.jsx("div",{style:{fontSize:12,color:a.textSecondary,fontFamily:a.font,lineHeight:1.5},children:e.description}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,fontSize:11,fontFamily:a.fontMono,color:a.textMuted},children:[s.jsxs("div",{children:["domain: ",e.domain||"uncategorized"]}),s.jsxs("div",{children:["owner: ",e.owner??"unassigned"]}),e.table?s.jsxs("div",{children:["table: ",e.table]}):s.jsx("div",{}),e.cube?s.jsxs("div",{children:["cube: ",e.cube]}):s.jsx("div",{}),e.type?s.jsxs("div",{children:["type: ",e.type]}):s.jsx("div",{}),d?s.jsxs("div",{children:["source: ",d]}):s.jsx("div",{})]}),e.tags.length>0&&s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:e.tags.map(E=>s.jsx("span",{style:{fontSize:10,color:a.textMuted,background:a.pillBg,borderRadius:999,padding:"2px 8px",fontFamily:a.font},children:E},E))}),e.sql&&s.jsxs("div",{style:{position:"relative"},children:[s.jsx("pre",{style:{margin:0,padding:"8px 10px",paddingRight:32,background:a.editorBg,border:`1px solid ${a.cellBorder}`,borderRadius:6,fontSize:10,fontFamily:a.fontMono,color:a.textSecondary,overflowX:"auto",whiteSpace:"pre-wrap"},children:e.sql}),s.jsx("button",{onClick:o,title:"Copy SQL",style:{position:"absolute",top:6,right:6,background:a.btnBg,border:`1px solid ${a.cellBorder}`,borderRadius:4,color:a.textMuted,cursor:"pointer",fontSize:10,fontFamily:a.font,padding:"2px 6px",opacity:.7,lineHeight:1},children:"Copy"})]}),e.joins&&e.joins.length>0&&s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("div",{style:{fontSize:11,fontWeight:600,color:a.textSecondary,fontFamily:a.font},children:"Joins"}),e.joins.map(E=>s.jsxs("div",{style:{fontSize:10,color:a.textMuted,fontFamily:a.fontMono},children:[E.left," ",E.type," ",E.right]},E.name))]}),e.levels&&e.levels.length>0&&s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("div",{style:{fontSize:11,fontWeight:600,color:a.textSecondary,fontFamily:a.font},children:"Levels"}),e.levels.map(E=>s.jsxs("div",{style:{fontSize:10,color:a.textMuted,fontFamily:a.fontMono},children:[E.order,". ",E.label," → ",E.dimension]},E.name))]}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("button",{onClick:r,disabled:!c,style:{flex:1,background:a.btnBg,border:`1px solid ${a.btnBorder}`,borderRadius:6,color:a.textSecondary,cursor:"pointer",fontSize:11,fontFamily:a.font,padding:"6px 10px"},children:"Preview Data"}),s.jsx("button",{onClick:o,disabled:!e.sql,style:{flex:1,background:a.btnBg,border:`1px solid ${a.btnBorder}`,borderRadius:6,color:a.textSecondary,cursor:"pointer",fontSize:11,fontFamily:a.font,padding:"6px 10px"},children:"Copy SQL"}),s.jsx("button",{onClick:n,disabled:!l,style:{flex:1,background:a.accent,border:`1px solid ${a.accent}`,borderRadius:6,color:"#fff",cursor:"pointer",fontSize:11,fontFamily:a.font,padding:"6px 10px"},children:l?"Insert":"Inspect"})]})]})}function j$({query:e,provider:t,cube:n,owner:r,domain:o,tag:i,type:a,providers:l,cubes:c,owners:d,domains:E,tags:u,onQueryChange:T,onProviderChange:p,onCubeChange:h,onOwnerChange:A,onDomainChange:S,onTagChange:R,onTypeChange:m,t:I}){const O=(t?1:0)+(o?1:0)+(n?1:0)+(r?1:0)+(i?1:0)+(a?1:0),[N,x]=f.useState(O>0),g={width:"100%",background:I.inputBg,border:`1px solid ${I.inputBorder}`,borderRadius:6,color:I.textPrimary,fontSize:12,fontFamily:I.font,padding:"7px 10px",outline:"none",boxSizing:"border-box"},C=()=>{p(""),S(""),h(""),A(""),R(""),m("")};return s.jsxs("div",{style:{padding:"10px",display:"flex",flexDirection:"column",gap:8,borderBottom:`1px solid ${I.headerBorder}`},children:[s.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[s.jsx("input",{value:e,onChange:y=>T(y.target.value),placeholder:"Search labels, cubes, owners, tags...",style:{...g,flex:1}}),s.jsxs("button",{onClick:()=>x(y=>!y),style:{background:O>0?`${I.accent}18`:"transparent",border:`1px solid ${O>0?I.accent:I.inputBorder}`,borderRadius:6,color:O>0?I.accent:I.textMuted,cursor:"pointer",fontSize:11,fontFamily:I.font,padding:"6px 10px",whiteSpace:"nowrap"},title:N?"Hide filters":"Show filters",children:["Filters",O>0?` · ${O}`:""]})]}),N&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:6},children:[s.jsxs("select",{value:t,onChange:y=>p(y.target.value),style:g,children:[s.jsx("option",{value:"",children:"All providers"}),l.map(y=>s.jsx("option",{value:y,children:y},y))]}),s.jsxs("select",{value:o,onChange:y=>S(y.target.value),style:g,children:[s.jsx("option",{value:"",children:"All domains"}),E.map(y=>s.jsx("option",{value:y,children:y},y))]}),s.jsxs("select",{value:n,onChange:y=>h(y.target.value),style:g,children:[s.jsx("option",{value:"",children:"All cubes"}),c.map(y=>s.jsx("option",{value:y,children:y},y))]}),s.jsxs("select",{value:r,onChange:y=>A(y.target.value),style:g,children:[s.jsx("option",{value:"",children:"All owners"}),d.map(y=>s.jsx("option",{value:y,children:y},y))]}),s.jsxs("select",{value:i,onChange:y=>R(y.target.value),style:g,children:[s.jsx("option",{value:"",children:"All tags"}),u.map(y=>s.jsx("option",{value:y,children:y},y))]}),s.jsxs("select",{value:a,onChange:y=>m(y.target.value),style:g,children:[s.jsx("option",{value:"",children:"All types"}),s.jsx("option",{value:"cube",children:"Cubes"}),s.jsx("option",{value:"metric",children:"Metrics"}),s.jsx("option",{value:"dimension",children:"Dimensions"}),s.jsx("option",{value:"hierarchy",children:"Hierarchies"}),s.jsx("option",{value:"segment",children:"Segments"}),s.jsx("option",{value:"pre_aggregation",children:"Pre-aggregations"})]})]}),O>0&&s.jsx("button",{onClick:C,style:{alignSelf:"flex-start",background:"transparent",border:"none",color:I.textMuted,cursor:"pointer",fontSize:11,fontFamily:I.font,padding:0,textDecoration:"underline"},children:"Clear filters"})]})]})}function ed({label:e,depth:t=0,badge:n,badgeColor:r,count:o,expanded:i,favorite:a,selected:l,onClick:c,onDoubleClick:d,onToggle:E,onFavoriteToggle:u,onDragStart:T,title:p,muted:h,t:A}){const[S,R]=f.useState(!1);return s.jsxs("button",{draggable:!!T,onDragStart:T,onClick:c,onDoubleClick:d,onMouseEnter:()=>R(!0),onMouseLeave:()=>R(!1),title:p,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:`5px 8px 5px ${10+t*14}px`,background:l?`${A.accent}18`:S?A.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:h?A.textMuted:A.textPrimary,fontSize:12,fontFamily:A.font,textAlign:"left"},children:[E?s.jsx("span",{onClick:m=>{m.stopPropagation(),E()},style:{display:"inline-flex",transform:i?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s",color:A.textMuted},children:s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:s.jsx("path",{d:"M3 2l4 3-4 3V2Z"})})}):s.jsx("span",{style:{width:10,flexShrink:0}}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),n&&s.jsx("span",{style:{fontSize:9,fontFamily:A.fontMono,color:r??A.accent,background:`${r??A.accent}18`,borderRadius:4,padding:"1px 4px",flexShrink:0},children:n}),typeof o=="number"&&s.jsx("span",{style:{fontSize:10,color:A.textMuted,background:A.pillBg,borderRadius:999,padding:"1px 6px",flexShrink:0},children:o}),typeof a=="boolean"&&s.jsx("span",{onClick:m=>{m.stopPropagation(),u==null||u()},style:{color:a?"#e3b341":A.textMuted,display:"inline-flex",flexShrink:0},children:s.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M8 1.25l1.938 3.927 4.335.63-3.136 3.056.74 4.318L8 11.143l-3.877 2.038.74-4.318L1.727 5.807l4.335-.63L8 1.25Z"})})})]})}const Ws=31,zf=10;function G$(){var cs,zr,ds,Es,us,Ts,fs,ps,Ss,Kr;const{state:e,dispatch:t}=fe(),n=ie[e.themeMode],[r,o]=f.useState("semantic"),[i,a]=f.useState("validate"),[l,c]=f.useState(""),[d,E]=f.useState(""),[u,T]=f.useState(""),[p,h]=f.useState(""),[A,S]=f.useState(""),[R,m]=f.useState(""),[I,O]=f.useState(""),[N,x]=f.useState({}),[g,C]=f.useState(null),[y,w]=f.useState(null),[v,B]=f.useState([]),[b,L]=f.useState({}),[D,M]=f.useState(""),[U,P]=f.useState(new Set),[_,F]=f.useState(!1),[k,H]=f.useState(!1),[Q,q]=f.useState(null),[$,Z]=f.useState(null),[Y,G]=f.useState([]),[J,te]=f.useState(!1),[re,oe]=f.useState(null),[V,le]=f.useState(!1),[Te,de]=f.useState(!1),[ne,Re]=f.useState(null),[Oe,Fe]=f.useState(null),[Nn,Vt]=f.useState(null),[Qn,Jo]=f.useState(!1),[Xt,vt]=f.useState(0),[zt,Qo]=f.useState(400),[Zo,$r]=f.useState(300),[es,ba]=f.useState(420),[Kt,ts]=f.useState(!1),[qt,ns]=f.useState(!1),[Da,Zn]=f.useState(!1),[Pt,rs]=f.useState(null),er=f.useRef(null);f.useEffect(()=>{t({type:"SET_BLOCK_STUDIO_CATALOG_LOADING",loading:!0}),Z(null),z.getBlockStudioCatalog().then(W=>{t({type:"SET_BLOCK_STUDIO_CATALOG",catalog:W}),B(W.databaseTree)}).catch(()=>{Z("Failed to load schema. Check your connection and try refreshing.")}).finally(()=>t({type:"SET_BLOCK_STUDIO_CATALOG_LOADING",loading:!1}))},[t]),f.useEffect(()=>{if(!g||g.startsWith("provider:")||g.startsWith("domain:")||g.startsWith("group:")){w(null);return}z.getSemanticObject(g).then(w).catch(()=>w(null))},[g]),f.useEffect(()=>{const W=window.setTimeout(()=>{e.blockStudioDraft.trim()&&z.validateBlockStudio(e.blockStudioDraft,e.activeBlockPath).then(ce=>t({type:"SET_BLOCK_STUDIO_VALIDATION",validation:ce})).catch(()=>{})},250);return()=>window.clearTimeout(W)},[e.blockStudioDraft,e.activeBlockPath,t]);const Vr=((cs=e.blockStudioCatalog)==null?void 0:cs.semanticTree)??null,at=f.useMemo(()=>nV(Vr)?Vr:rV(e.semanticLayer),[Vr,e.semanticLayer]),Ma=f.useMemo(()=>uc(at,"provider"),[at]),va=f.useMemo(()=>uc(at,"cube"),[at]),Pa=f.useMemo(()=>uc(at,"owner"),[at]),tr=f.useMemo(()=>at?nm(at,{query:l,provider:d,domain:u,cube:p,owner:A,tag:R,type:I}):null,[at,l,d,u,p,A,R,I]),gn=f.useMemo(()=>rm((tr==null?void 0:tr.children)??[],N),[tr,N]),wa=f.useMemo(()=>eV(v,D),[v,D]),Ua=f.useMemo(()=>tV(v),[v]),Jt={metrics:e.semanticLayer.metrics.length,measures:e.semanticLayer.measures.length,dimensions:e.semanticLayer.dimensions.length,timeDimensions:e.semanticLayer.timeDimensions.length,entities:e.semanticLayer.entities.length,hierarchies:e.semanticLayer.hierarchies.length,savedQueries:e.semanticLayer.savedQueries.length},Ba=gn.length*Ws,os=f.useMemo(()=>{const W=Math.max(0,Math.floor(Xt/Ws)-zf),ce=Math.min(gn.length,Math.ceil((Xt+zt)/Ws)+zf);return{offsetTop:W*Ws,rows:gn.slice(W,ce)}},[gn,Xt,zt]);f.useEffect(()=>{const W=er.current;if(!W)return;const ce=()=>Qo(W.clientHeight||400);if(ce(),typeof ResizeObserver>"u")return window.addEventListener("resize",ce),()=>window.removeEventListener("resize",ce);const ge=new ResizeObserver(()=>ce());return ge.observe(W),()=>ge.disconnect()},[]),f.useEffect(()=>{vt(0),er.current&&(er.current.scrollTop=0)},[l,d,u,p,A,R,I]);const Ze=f.useMemo(()=>{var ce;const W=pu(e.blockStudioDraft);return e.blockStudioMetadata?{...W,name:(W==null?void 0:W.name)||e.blockStudioMetadata.name,domain:(W==null?void 0:W.domain)||e.blockStudioMetadata.domain,description:(W==null?void 0:W.description)||e.blockStudioMetadata.description,owner:(W==null?void 0:W.owner)||e.blockStudioMetadata.owner,tags:(ce=W==null?void 0:W.tags)!=null&&ce.length?W.tags:e.blockStudioMetadata.tags,blockType:(W==null?void 0:W.blockType)||"custom"}:W},[e.blockStudioDraft,e.blockStudioMetadata]),Qt=(Ze==null?void 0:Ze.name)??((zr=e.blockStudioMetadata)==null?void 0:zr.name)??null;f.useEffect(()=>{if(!Qt)return;const W=`block:${Qt}`;t({type:"SET_LINEAGE_FOCUS",nodeId:W}),de(!0),Promise.all([z.fetchLineageNode(W),z.queryLineage({focus:W}),z.fetchLineagePaths(W)]).then(([ce,ge,Ne])=>{Re(ce),Fe(ge.graph??null),Vt(Ne)}).catch(()=>{Re(null),Fe(null),Vt(null)}).finally(()=>de(!1))},[Qt,t]);const lt=W=>{t({type:"SET_BLOCK_STUDIO_DRAFT",draft:W})},ss=async()=>{var W,ce,ge;F(!0);try{const Ne=await z.runBlockStudio(e.blockStudioDraft,e.activeBlockPath);t({type:"SET_BLOCK_STUDIO_PREVIEW",preview:Ne}),a("results")}catch(Ne){t({type:"SET_BLOCK_STUDIO_VALIDATION",validation:{valid:!1,chartConfig:(W=e.blockStudioValidation)==null?void 0:W.chartConfig,executableSql:((ce=e.blockStudioValidation)==null?void 0:ce.executableSql)??null,semanticRefs:((ge=e.blockStudioValidation)==null?void 0:ge.semanticRefs)??{metrics:[],dimensions:[],segments:[]},diagnostics:[{severity:"error",code:"block_run_failed",message:Ne instanceof Error?Ne.message:String(Ne)}]}}),a("validate")}finally{F(!1)}},Fa=async()=>{if(!e.blockStudioMetadata){t({type:"OPEN_NEW_BLOCK_MODAL"});return}H(!0),q(null);try{const W=await z.saveBlockStudio({path:e.activeBlockPath,source:e.blockStudioDraft,metadata:{name:e.blockStudioMetadata.name,domain:e.blockStudioMetadata.domain,description:e.blockStudioMetadata.description,owner:e.blockStudioMetadata.owner,tags:e.blockStudioMetadata.tags,sourceKind:e.blockStudioMetadata.sourceKind,sourcePath:e.blockStudioMetadata.sourcePath,importId:e.blockStudioMetadata.importId,candidateId:e.blockStudioMetadata.candidateId,lineage:e.blockStudioMetadata.lineage}});t({type:"OPEN_BLOCK_STUDIO",file:{name:`${W.metadata.name}.dql`,path:W.path,type:"block",folder:"blocks"},payload:W}),e.files.some(ge=>ge.path===W.path)||t({type:"FILE_ADDED",file:{name:`${W.metadata.name}.dql`,path:W.path,type:"block",folder:"blocks"}}),a("save")}catch(W){const ce=(W==null?void 0:W.message)??"Save failed";q(ce.includes("409")||ce.includes("BLOCK_EXISTS")?"A block with this name already exists. Rename and try again.":ce),setTimeout(()=>q(null),5e3)}finally{H(!1)}},ka=W=>{var ge,Ne;const ce={path:"",source:W.dqlSource,metadata:{name:W.name,path:null,domain:W.domain,description:W.description,owner:W.owner,tags:W.tags,reviewStatus:"draft",sourceKind:W.sourceKind,sourcePath:W.sourcePath,importId:Pt==null?void 0:Pt.id,candidateId:W.id,lineage:W.lineage.sourceTables},companionPath:null,validation:W.validation??{valid:!0,diagnostics:[],semanticRefs:{metrics:[],dimensions:[],segments:[]},executableSql:null}};t({type:"OPEN_BLOCK_STUDIO",file:{name:`${W.name}.dql`,path:"",type:"block",folder:"blocks",isNew:!0},payload:ce}),t({type:"SET_BLOCK_STUDIO_PREVIEW",preview:W.preview}),a((Ne=(ge=W.validation)==null?void 0:ge.diagnostics)!=null&&Ne.length?"validate":"results"),Zn(!1)},ja=(W,ce)=>{t({type:"OPEN_BLOCK_STUDIO",file:{name:`${ce.metadata.name}.dql`,path:ce.path,type:"block",folder:"blocks"},payload:ce}),e.files.some(Ne=>Ne.path===ce.path)||t({type:"FILE_ADDED",file:{name:`${ce.metadata.name}.dql`,path:ce.path,type:"block",folder:"blocks"}}),Pt&&rs({...Pt,candidates:Pt.candidates.map(Ne=>Ne.id===W.id?W:Ne)}),a("save"),Zn(!1)},Xr=W=>{var ce;if(W.kind==="metric"||W.kind==="dimension"){const ge=$0(W.kind==="metric"?"metric":"dimension",W.name);(((ce=pu(e.blockStudioDraft))==null?void 0:ce.blockType)??"custom")==="semantic"?lt(V0(e.blockStudioDraft,{kind:W.kind==="metric"?"metric":"dimension",name:W.name})):Wb(ge)||lt(X0(e.blockStudioDraft,ge)),t({type:"ADD_SEMANTIC_RECENT",name:W.name});return}if(W.kind==="segment"&&W.sql){lt($s(e.blockStudioDraft,`/* segment:${W.name} */ (${W.sql})`));return}W.kind==="pre_aggregation"&<($s(e.blockStudioDraft,`/* pre_aggregation:${W.name} */`))},is=W=>{lt($s(e.blockStudioDraft,W))},as=async W=>{if(!(!W.path||W.kind!=="table"||W.children&&W.children.length>0)){P(ce=>new Set(ce).add(W.id));try{const ce=await z.describeTable(W.path);B(ge=>om(ge,W.id,{...W,children:ce.map(Ne=>({id:`db-column:${W.path}:${Ne.name}`,label:Ne.name,kind:"column",path:W.path,type:Ne.type}))}))}finally{P(ce=>{const ge=new Set(ce);return ge.delete(W.id),ge})}}},ls=f.useCallback(async()=>{try{const W=await z.getBlockStudioCatalog();W!=null&&W.databaseTree&&B(W.databaseTree),t({type:"SET_BLOCK_STUDIO_CATALOG",catalog:W})}catch{}},[t]),Ga=((ds=e.blockStudioValidation)==null?void 0:ds.chartConfig)??((Es=e.blockStudioPreview)==null?void 0:Es.chartConfig)??{chart:"table"},Ha=e.blockStudioPreview?Cr(e.blockStudioPreview.result,e.blockStudioPreview.chartConfig):"table",Ya=W=>{W.preventDefault();const ce=W.clientX,ge=Zo,Ne=qr=>{const Jr=Math.min(520,Math.max(280,ge+qr.clientX-ce));$r(Jr)},xn=()=>{window.removeEventListener("mousemove",Ne),window.removeEventListener("mouseup",xn)};window.addEventListener("mousemove",Ne),window.addEventListener("mouseup",xn)},Wa=W=>{W.preventDefault();const ce=W.clientY,ge=es,Ne=qr=>{const Jr=Math.min(520,Math.max(180,ge-(qr.clientY-ce)));ba(Jr)},xn=()=>{window.removeEventListener("mousemove",Ne),window.removeEventListener("mouseup",xn)};window.addEventListener("mousemove",Ne),window.addEventListener("mouseup",xn)};return s.jsxs("div",{style:{flex:1,position:"relative",display:"grid",gridTemplateColumns:Kt?"0 0 minmax(0, 1fr)":`${Zo}px 6px minmax(0, 1fr)`,gridTemplateRows:qt?"minmax(0, 1fr) 0 0":`minmax(0, 1fr) 6px ${es}px`,overflow:"hidden",background:n.appBg},children:[s.jsxs("div",{style:{borderRight:Kt?"none":`1px solid ${n.headerBorder}`,display:Kt?"none":"flex",flexDirection:"column",overflow:"hidden",background:n.sidebarBg,minWidth:0},children:[s.jsxs("div",{style:{padding:"10px 14px",display:"flex",alignItems:"center",gap:10,borderBottom:`1px solid ${n.headerBorder}`},children:[s.jsx("span",{style:{fontSize:10,fontWeight:600,letterSpacing:"0.06em",color:n.textMuted,textTransform:"uppercase",fontFamily:n.font},children:"Explorer"}),s.jsxs("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:[Jt.metrics," metrics · ",Jt.measures," measures · ",Jt.dimensions+Jt.timeDimensions," dims · ",Jt.entities," entities · ",Jt.savedQueries," saved queries"]}),s.jsx("div",{style:{flex:1}}),e.semanticLayer.provider&&s.jsx("span",{style:{fontSize:9,fontWeight:700,color:n.accent,background:`${n.accent}18`,borderRadius:999,padding:"2px 7px",textTransform:"uppercase",letterSpacing:"0.04em"},children:e.semanticLayer.provider}),s.jsx("button",{onClick:()=>ts(!0),style:{background:"transparent",border:"none",color:n.textMuted,cursor:"pointer",fontSize:14,fontFamily:n.font,padding:0,lineHeight:1},title:"Collapse explorer",children:"‹"})]}),s.jsxs("div",{style:{display:"flex",padding:"0 14px",gap:16,borderBottom:`1px solid ${n.headerBorder}`},children:[s.jsx(Kf,{active:r==="semantic",onClick:()=>o("semantic"),label:"Semantic",t:n}),s.jsx(Kf,{active:r==="database",onClick:()=>o("database"),label:"Database",t:n})]}),r==="semantic"?s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{padding:12,borderBottom:`1px solid ${n.headerBorder}`,background:`${n.cellBg}66`},children:s.jsx(j$,{query:l,provider:d,cube:p,owner:A,domain:u,tag:R,type:I,providers:Ma,cubes:va,owners:Pa,domains:e.semanticLayer.domains,tags:e.semanticLayer.tags,onQueryChange:c,onProviderChange:E,onCubeChange:h,onOwnerChange:S,onDomainChange:T,onTagChange:m,onTypeChange:O,t:n})}),s.jsx("div",{ref:er,onScroll:W=>vt(W.currentTarget.scrollTop),style:{flex:1,overflowY:"auto",borderBottom:`1px solid ${n.headerBorder}`,background:n.cellBg},children:$?s.jsxs("div",{style:{padding:16,display:"grid",gap:8,textAlign:"center"},children:[s.jsx("div",{style:{fontSize:12,color:"#f85149",fontFamily:n.font},children:$}),s.jsx("button",{onClick:()=>{Z(null),ls()},style:{fontSize:11,color:n.accent,background:`${n.accent}18`,border:"none",borderRadius:6,padding:"6px 12px",cursor:"pointer",fontFamily:n.font},children:"Retry"})]}):e.blockStudioCatalogLoading?s.jsx(St,{message:"Loading semantic catalog…"}):gn.length===0?s.jsx(St,{message:"No semantic objects match the current filters."}):s.jsx("div",{style:{height:Ba,position:"relative"},children:s.jsx("div",{style:{position:"absolute",top:os.offsetTop,left:0,right:0},children:os.rows.map(W=>s.jsx(Z$,{row:W,selectedId:g,setSelectedId:C,expanded:N,setExpanded:x,onInsert:Xr,favorites:new Set(e.semanticLayer.favorites),dispatch:t,t:n},W.node.id))})})}),s.jsx(k$,{item:y,favorite:!!(y&&e.semanticLayer.favorites.includes(y.name)),onInsert:()=>y&&Xr(y),onPreview:()=>{y!=null&&y.sql&<($s(e.blockStudioDraft,y.sql))},onCopySql:()=>{y!=null&&y.sql&&navigator.clipboard.writeText(y.sql)},onToggleFavorite:()=>{!y||y.kind!=="metric"&&y.kind!=="dimension"||z.toggleFavorite(y.name).then(W=>t({type:"SET_SEMANTIC_FAVORITES",favorites:W}))},t:n})]}):s.jsx(Q$,{tree:wa,totalTree:v,expanded:b,setExpanded:L,onEnsureColumns:as,onInsert:is,query:D,onQueryChange:M,stats:Ua,connectionName:((us=e.blockStudioCatalog)==null?void 0:us.connection.current)??"default",loadingNodes:U,onRefresh:ls,t:n})]}),s.jsx("div",{onMouseDown:Kt?void 0:Ya,style:{display:Kt?"none":"block",cursor:"col-resize",background:n.headerBorder}}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden",gridColumn:"3",gridRow:"1"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 14px",borderBottom:`1px solid ${n.headerBorder}`,background:n.cellBg},children:[Kt&&s.jsx("button",{onClick:()=>ts(!1),style:{background:"transparent",border:"none",color:n.textMuted,cursor:"pointer",fontSize:14,fontFamily:n.font,padding:0,lineHeight:1},title:"Open explorer",children:"›"}),s.jsx("span",{style:{fontSize:10,fontWeight:600,letterSpacing:"0.06em",color:n.textMuted,textTransform:"uppercase",fontFamily:n.font},children:"Source"}),s.jsx("div",{style:{flex:1}}),s.jsx(ac,{label:"Import",onClick:()=>Zn(!0)}),s.jsx(ac,{label:"Run",onClick:()=>void ss(),busy:_}),s.jsx(ac,{label:"Save",onClick:()=>void Fa(),busy:k}),Q&&s.jsx("span",{style:{fontSize:11,color:"#f85149",fontFamily:n.font,padding:"4px 8px",background:"#f8514918",borderRadius:6},children:Q})]}),s.jsx("div",{style:{flex:1,overflow:"hidden"},children:s.jsx(jd,{value:e.blockStudioDraft,onChange:lt,onRun:()=>void ss(),themeMode:e.themeMode,autoFocus:!0,wrap:!1,errorMessage:(fs=(Ts=e.blockStudioValidation)==null?void 0:Ts.diagnostics.find(W=>W.severity==="error"))==null?void 0:fs.message})})]}),s.jsx("div",{onMouseDown:qt?void 0:Wa,style:{gridColumn:"1 / -1",gridRow:"2",display:qt?"none":"block",cursor:"row-resize",background:n.headerBorder}}),s.jsxs("div",{style:{gridColumn:"1 / -1",gridRow:"3",borderTop:qt?"none":`1px solid ${n.headerBorder}`,display:qt?"none":"flex",flexDirection:"column",overflow:"hidden",background:n.cellBg},children:[s.jsxs("div",{style:{padding:"10px 14px",display:"flex",gap:6,alignItems:"center",borderBottom:`1px solid ${n.headerBorder}`,flexWrap:"wrap"},children:[s.jsx("span",{style:{fontSize:10,fontWeight:600,letterSpacing:"0.06em",color:n.textMuted,textTransform:"uppercase",fontFamily:n.font,marginRight:4},children:"Output"}),s.jsx(sn,{active:i==="results",onClick:()=>a("results"),label:"Results"}),s.jsx(sn,{active:i==="visualization",onClick:()=>a("visualization"),label:"Visualization"}),s.jsx(sn,{active:i==="lineage",onClick:()=>a("lineage"),label:"Lineage"}),s.jsx("span",{style:{width:1,height:18,background:n.headerBorder,margin:"0 6px"}}),s.jsx("span",{style:{fontSize:10,fontWeight:600,letterSpacing:"0.06em",color:n.textMuted,textTransform:"uppercase",fontFamily:n.font,marginRight:4},children:"Governance"}),s.jsx(sn,{active:i==="validate",onClick:()=>a("validate"),label:"Validate"}),s.jsx(sn,{active:i==="tests",onClick:()=>a("tests"),label:"Tests"}),s.jsx(sn,{active:i==="history",onClick:()=>{a("history"),!J&&e.activeBlockPath&&z.getBlockHistory(e.activeBlockPath).then(W=>{G(W.entries),te(!0)})},label:"History"}),s.jsx(sn,{active:i==="save",onClick:()=>a("save"),label:"Metadata"}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:()=>ns(!0),style:{background:"transparent",border:`1px solid ${n.btnBorder}`,borderRadius:6,color:n.textMuted,cursor:"pointer",fontSize:11,fontFamily:n.font,padding:"4px 8px"},title:"Hide pane",children:"▾ Hide"})]}),s.jsxs("div",{style:{flex:1,overflow:"auto"},children:[i==="results"&&(e.blockStudioPreview?s.jsxs("div",{style:{display:"grid",gap:12,padding:12},children:[s.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.fontMono},children:e.blockStudioPreview.sql}),Ha==="table"?s.jsx(Kn,{result:e.blockStudioPreview.result,themeMode:e.themeMode}):s.jsx(Yd,{result:e.blockStudioPreview.result,chartConfig:e.blockStudioPreview.chartConfig,themeMode:e.themeMode})]}):s.jsx(St,{message:"Run the block to preview results and visualization."})),i==="visualization"&&s.jsx($$,{chartConfig:Ga,onChange:W=>lt(W0(e.blockStudioDraft,W)),t:n}),i==="lineage"&&s.jsx(V$,{blockName:Qt,loading:Te,detail:ne,graph:Oe,paths:Nn,onSelectNode:W=>{t({type:"SET_LINEAGE_FOCUS",nodeId:W}),e.lineageFullscreen||t({type:"TOGGLE_LINEAGE_FULLSCREEN"})},onOpenFull:()=>{Qt&&(t({type:"SET_LINEAGE_FOCUS",nodeId:`block:${Qt}`}),e.lineageFullscreen||t({type:"TOGGLE_LINEAGE_FULLSCREEN"}))},t:n}),i==="tests"&&s.jsx(q$,{source:e.blockStudioDraft,blockPath:e.activeBlockPath,testResults:re,running:V,onRunTests:async()=>{if(e.activeBlockPath){le(!0);try{const W=await z.runBlockTests(e.blockStudioDraft,e.activeBlockPath);oe(W.assertions??[])}catch{oe([])}finally{le(!1)}}},t:n}),i==="validate"&&s.jsx(W$,{diagnostics:((ps=e.blockStudioValidation)==null?void 0:ps.diagnostics)??[],t:n}),i==="history"&&s.jsx(J$,{entries:Y,t:n}),i==="save"&&s.jsxs("div",{style:{display:"grid",gap:12},children:[e.activeBlockPath&&e.blockStudioMetadata&&s.jsx("div",{style:{padding:"12px 12px 0"},children:s.jsx(K$,{currentStatus:e.blockStudioMetadata.reviewStatus??"draft",blockPath:e.activeBlockPath,onStatusChanged:W=>{e.blockStudioMetadata&&t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,reviewStatus:W}})},t:n})}),s.jsx(X$,{metadata:e.blockStudioMetadata,draftMetadata:Ze,onChange:W=>{if(!e.blockStudioMetadata)return;t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,...W}});let ce=e.blockStudioDraft;typeof W.name=="string"&&(ce=VR(ce,W.name)),typeof W.domain=="string"&&(ce=ul(ce,"domain",W.domain)),typeof W.owner=="string"&&(ce=ul(ce,"owner",W.owner)),typeof W.description=="string"&&(ce=ul(ce,"description",W.description)),W.tags&&(ce=Y0(ce,W.tags)),lt(ce)},t:n})]})]})]}),Da&&s.jsx(H$,{session:Pt,onSessionChange:rs,onClose:()=>Zn(!1),onSelectCandidate:ka,onSavedCandidate:ja,defaultDomain:(Ze==null?void 0:Ze.domain)||((Ss=e.blockStudioMetadata)==null?void 0:Ss.domain)||"imported",defaultOwner:(Ze==null?void 0:Ze.owner)||((Kr=e.blockStudioMetadata)==null?void 0:Kr.owner)||"",t:n}),qt&&s.jsx("div",{style:{position:"absolute",right:16,bottom:16},children:s.jsx("button",{onClick:()=>ns(!1),style:{background:n.btnBg,border:`1px solid ${n.btnBorder}`,borderRadius:6,color:n.textSecondary,cursor:"pointer",fontSize:12,fontFamily:n.font,padding:"8px 12px"},children:"Open Results"})})]})}function sn({active:e,onClick:t,label:n,busy:r}){const{state:o}=fe(),i=ie[o.themeMode];return s.jsx("button",{onClick:t,style:{background:e?`${i.accent}18`:i.btnBg,border:`1px solid ${e?i.accent:i.btnBorder}`,borderRadius:6,color:e?i.accent:i.textSecondary,cursor:"pointer",fontSize:11,fontFamily:i.font,padding:"6px 10px",opacity:r?.7:1},children:r?`${n}…`:n})}function ac(e){return s.jsx(sn,{active:!1,...e})}function Kf({active:e,onClick:t,label:n,t:r}){return s.jsx("button",{onClick:t,style:{background:"transparent",border:"none",borderBottom:`2px solid ${e?r.accent:"transparent"}`,color:e?r.textPrimary:r.textMuted,cursor:"pointer",fontSize:12,fontWeight:e?600:500,fontFamily:r.font,padding:"10px 2px",marginBottom:-1},children:n})}function H$({session:e,onSessionChange:t,onClose:n,onSelectCandidate:r,onSavedCandidate:o,defaultDomain:i,defaultOwner:a,t:l}){const[c,d]=f.useState(""),[E,u]=f.useState(i),[T,p]=f.useState(a),[h,A]=f.useState(!1),[S,R]=f.useState(null),[m,I]=f.useState(null),[O,N]=f.useState(null),x=(e==null?void 0:e.candidates.filter(b=>{var L;return((L=b.validation)==null?void 0:L.valid)!==!1}).length)??0,g=(e==null?void 0:e.candidates.filter(b=>b.reviewStatus==="saved").length)??0,C=e?g>0?3:2:1,y=b=>{e&&t({...e,candidates:e.candidates.map(L=>L.id===b.id?b:L)})},w=async()=>{A(!0),N(null);try{const b=await z.previewBlockStudioImport({path:c,sourceKind:"raw-sql",domain:E,owner:T});t(b)}catch(b){N((b==null?void 0:b.message)??"Import preview failed.")}finally{A(!1)}},v=async b=>{if(e){R(b.id),N(null);try{const L=await z.runBlockStudioImportCandidate(e.id,b.id);y(L)}catch(L){N((L==null?void 0:L.message)??"Candidate run failed.")}finally{R(null)}}},B=async b=>{if(e){I(b.id),N(null);try{const L=await z.saveBlockStudioImportCandidate(e.id,b.id);y(L.candidate),o(L.candidate,L.block)}catch(L){const D=(L==null?void 0:L.message)??"Candidate save failed.";N(D.includes("409")||D.includes("already exists")?"A block with this name already exists. Use Review in editor to rename it, then save.":D)}finally{I(null)}}};return s.jsx("div",{style:{position:"absolute",inset:0,zIndex:30,background:"rgba(0,0,0,0.28)",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:s.jsxs("div",{style:{width:820,maxWidth:"calc(100vw - 48px)",maxHeight:"calc(100vh - 72px)",background:l.cellBg,border:`1px solid ${l.headerBorder}`,borderRadius:10,boxShadow:"0 24px 70px rgba(0,0,0,0.35)",display:"flex",flexDirection:"column",overflow:"hidden"},children:[s.jsxs("div",{style:{padding:"14px 16px",borderBottom:`1px solid ${l.headerBorder}`,display:"flex",alignItems:"center",gap:12},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:14,fontWeight:700,color:l.textPrimary,fontFamily:l.font},children:"Import SQL into Block Studio"}),s.jsx("div",{style:{fontSize:11,color:l.textMuted,fontFamily:l.font,marginTop:2},children:"Scan existing SQL, review candidates, then save draft DQL blocks."})]}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:n,style:{background:"transparent",border:"none",color:l.textMuted,cursor:"pointer",fontSize:18,lineHeight:1},title:"Close import",children:"×"})]}),s.jsxs("div",{style:{padding:"12px 14px",borderBottom:`1px solid ${l.headerBorder}`,display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8,background:`${l.appBg}99`},children:[s.jsx(lc,{index:1,active:C===1,complete:!!e,title:"Choose source",detail:"SQL file or folder",t:l}),s.jsx(lc,{index:2,active:C===2,complete:g>0,title:"Review candidates",detail:e?`${e.candidates.length} found · ${x} ready`:"Validate metadata",t:l}),s.jsx(lc,{index:3,active:C===3,complete:g>0,title:"Save drafts",detail:g>0?`${g} saved`:"Open or save as block",t:l})]}),s.jsxs("div",{style:{padding:14,borderBottom:`1px solid ${l.headerBorder}`,display:"grid",gridTemplateColumns:"minmax(0, 1fr) 150px 150px auto",gap:8,alignItems:"end"},children:[s.jsx(cc,{label:"SQL file or folder",t:l,children:s.jsx("input",{value:c,onChange:b=>d(b.target.value),placeholder:"/path/to/sql or ./queries",style:dc(l)})}),s.jsx(cc,{label:"Domain",t:l,children:s.jsx("input",{value:E,onChange:b=>u(b.target.value),placeholder:"imported",style:dc(l)})}),s.jsx(cc,{label:"Owner",t:l,children:s.jsx("input",{value:T,onChange:b=>p(b.target.value),placeholder:"analytics",style:dc(l)})}),s.jsx("button",{onClick:()=>void w(),disabled:h||!c.trim(),style:{background:l.accent,border:`1px solid ${l.accent}`,borderRadius:6,color:"#fff",cursor:h||!c.trim()?"not-allowed":"pointer",fontSize:12,fontWeight:700,fontFamily:l.font,padding:"8px 12px",opacity:h||!c.trim()?.6:1},children:h?"Scanning…":"Preview"})]}),O&&s.jsx("div",{style:{padding:"10px 14px",color:"#f85149",background:"#f8514914",borderBottom:`1px solid ${l.headerBorder}`,fontSize:12,fontFamily:l.font},children:O}),s.jsx("div",{style:{flex:1,overflow:"auto",padding:14},children:e?e.candidates.length===0?s.jsx(St,{message:"No import candidates found."}):s.jsxs("div",{style:{display:"grid",gap:10},children:[s.jsxs("div",{style:{border:`1px solid ${l.headerBorder}`,borderRadius:8,padding:12,display:"grid",gap:6,background:l.appBg},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[s.jsx("span",{style:{fontSize:11,color:l.textMuted,fontFamily:l.fontMono},children:e.id}),s.jsx(bn,{label:`${e.candidates.length} candidates`,tone:"info",t:l}),s.jsx(bn,{label:`${x} ready`,tone:"ok",t:l}),g>0&&s.jsx(bn,{label:`${g} saved`,tone:"ok",t:l})]}),s.jsxs("div",{style:{fontSize:11,color:l.textMuted,fontFamily:l.font},children:["Source: ",s.jsx("span",{style:{fontFamily:l.fontMono},children:e.inputPath})]})]}),e.candidates.map(b=>{var M,U,P,_,F,k,H,Q;const L=((M=b.validation)==null?void 0:M.valid)!==!1,D=((P=(U=b.preview)==null?void 0:U.result)==null?void 0:P.rowCount)??((k=(F=(_=b.preview)==null?void 0:_.result)==null?void 0:F.rows)==null?void 0:k.length);return s.jsxs("div",{style:{border:`1px solid ${l.headerBorder}`,borderRadius:8,background:l.appBg,padding:12,display:"grid",gap:10},children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:10},children:[s.jsxs("div",{style:{minWidth:0,flex:1},children:[s.jsx("div",{style:{fontSize:13,fontWeight:700,color:l.textPrimary,fontFamily:l.font},children:b.name}),s.jsx("div",{style:{fontSize:11,color:l.textMuted,fontFamily:l.fontMono,marginTop:3},children:b.sourcePath})]}),s.jsx(bn,{label:`${Math.round(b.confidence*100)}%`,tone:"info",t:l}),s.jsx(bn,{label:L?"valid":"review",tone:L?"ok":"warn",t:l}),s.jsx(bn,{label:b.reviewStatus,tone:b.reviewStatus==="saved"?"ok":"info",t:l}),b.lineage.totalStatements>1&&s.jsx(bn,{label:`${b.lineage.statementIndex}/${b.lineage.totalStatements}`,tone:"info",t:l})]}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:b.lineage.sourceTables.length>0?b.lineage.sourceTables.map(q=>s.jsx("span",{style:{fontSize:11,color:l.textSecondary,background:l.pillBg,borderRadius:999,padding:"3px 8px",fontFamily:l.fontMono},children:q},q)):s.jsx("span",{style:{fontSize:11,color:l.textMuted,fontFamily:l.font},children:"No source tables detected"})}),b.lineage.parameters.length>0&&s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[s.jsx("span",{style:{fontSize:11,color:l.textMuted,fontFamily:l.font},children:"Parameters:"}),b.lineage.parameters.map(q=>s.jsx("span",{style:{fontSize:11,color:"#d29922",background:"#d2992218",borderRadius:999,padding:"3px 8px",fontFamily:l.fontMono},children:q},q))]}),b.lineage.warnings.length>0&&s.jsx("div",{style:{fontSize:11,color:"#d29922",fontFamily:l.font},children:b.lineage.warnings.join(" · ")}),((Q=(H=b.validation)==null?void 0:H.diagnostics)==null?void 0:Q.some(q=>q.severity==="error"))&&s.jsx("div",{style:{fontSize:11,color:"#f85149",fontFamily:l.font},children:b.validation.diagnostics.filter(q=>q.severity==="error").map(q=>q.message).join(" · ")}),b.preview&&s.jsxs("div",{style:{fontSize:11,color:l.textMuted,fontFamily:l.font,display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[s.jsx("span",{children:"Preview ready"}),typeof D=="number"&&s.jsxs("span",{children:["· ",D," rows"]}),s.jsx("span",{children:"· Open it to inspect SQL, data, visualization, and metadata."})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[s.jsx("button",{onClick:()=>void v(b),disabled:S===b.id,style:tm(l),children:S===b.id?"Running…":"Run preview"}),s.jsx("button",{onClick:()=>r(b),style:qf(l),children:"Review in editor"}),s.jsx("button",{onClick:()=>void B(b),disabled:m===b.id||b.reviewStatus==="saved",style:{...qf(l),opacity:m===b.id||b.reviewStatus==="saved"?.55:1,cursor:m===b.id||b.reviewStatus==="saved"?"not-allowed":"pointer"},children:b.reviewStatus==="saved"?"Saved":m===b.id?"Saving…":"Save draft"})]})]},b.id)})]}):s.jsx(Y$,{t:l})})]})})}function lc({index:e,active:t,complete:n,title:r,detail:o,t:i}){const a=n?"#2ea043":t?i.accent:i.textMuted;return s.jsxs("div",{style:{border:`1px solid ${t?i.accent:i.headerBorder}`,borderRadius:8,padding:"9px 10px",display:"grid",gridTemplateColumns:"24px minmax(0, 1fr)",gap:8,alignItems:"center",background:t?`${i.accent}10`:i.cellBg},children:[s.jsx("span",{style:{width:22,height:22,borderRadius:999,display:"inline-grid",placeItems:"center",background:`${a}18`,color:a,fontSize:11,fontWeight:800,fontFamily:i.font},children:n?"✓":e}),s.jsxs("span",{style:{minWidth:0},children:[s.jsx("span",{style:{display:"block",fontSize:12,fontWeight:700,color:i.textPrimary,fontFamily:i.font},children:r}),s.jsx("span",{style:{display:"block",fontSize:10,color:i.textMuted,fontFamily:i.font,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o})]})]})}function Y$({t:e}){const t=[["1","Choose source","Enter a local .sql file or a folder with SQL files."],["2","Review candidates","DQL detects statements, tables, parameters, and draft metadata."],["3","Save draft blocks","Open in Block Studio for edits or save directly as draft blocks."]];return s.jsxs("div",{style:{display:"grid",gap:12},children:[s.jsx(St,{message:"Choose a SQL file or folder to create import candidates."}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:10},children:t.map(([n,r,o])=>s.jsxs("div",{style:{border:`1px solid ${e.headerBorder}`,borderRadius:8,background:e.appBg,padding:12,display:"grid",gap:6},children:[s.jsx("span",{style:{width:22,height:22,borderRadius:999,display:"inline-grid",placeItems:"center",background:`${e.accent}18`,color:e.accent,fontSize:11,fontWeight:800,fontFamily:e.font},children:n}),s.jsx("span",{style:{fontSize:12,fontWeight:700,color:e.textPrimary,fontFamily:e.font},children:r}),s.jsx("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.font,lineHeight:1.4},children:o})]},r))})]})}function cc({label:e,children:t,t:n}){return s.jsxs("label",{style:{display:"grid",gap:5},children:[s.jsx("span",{style:{fontSize:10,fontWeight:700,color:n.textMuted,letterSpacing:"0.05em",textTransform:"uppercase",fontFamily:n.font},children:e}),t]})}function bn({label:e,tone:t,t:n}){const r=t==="ok"?"#2ea043":t==="warn"?"#d29922":n.accent;return s.jsx("span",{style:{fontSize:10,fontWeight:700,color:r,background:`${r}18`,borderRadius:999,padding:"3px 7px",fontFamily:n.font,textTransform:"uppercase"},children:e})}function dc(e){return{background:e.inputBg,border:`1px solid ${e.inputBorder}`,borderRadius:6,color:e.textPrimary,fontSize:12,fontFamily:e.font,padding:"8px 10px",outline:"none",minWidth:0}}function tm(e){return{background:e.btnBg,border:`1px solid ${e.btnBorder}`,borderRadius:6,color:e.textSecondary,cursor:"pointer",fontSize:11,fontFamily:e.font,padding:"6px 10px"}}function qf(e){return{...tm(e),background:`${e.accent}18`,border:`1px solid ${e.accent}`,color:e.accent,fontWeight:700}}function Ec({label:e,value:t,t:n}){return s.jsxs("div",{style:{background:n.cellBg,border:`1px solid ${n.headerBorder}`,borderRadius:10,padding:"10px 12px"},children:[s.jsx("div",{style:{fontSize:10,fontWeight:700,color:n.textMuted,fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em"},children:e}),s.jsx("div",{style:{fontSize:20,fontWeight:700,color:n.textPrimary,fontFamily:n.font,marginTop:4},children:t})]})}function W$({diagnostics:e,t}){return e.length===0?s.jsx(St,{message:"No validation messages."}):s.jsx("div",{style:{display:"grid",gap:8,padding:12},children:e.map((n,r)=>s.jsxs("div",{style:{padding:"10px 12px",borderRadius:8,border:`1px solid ${n.severity==="error"?t.error:n.severity==="warning"?t.warning:t.cellBorder}`,background:n.severity==="error"?`${t.error}12`:n.severity==="warning"?`${t.warning}12`:t.pillBg},children:[s.jsx("div",{style:{fontSize:10,fontWeight:700,color:n.severity==="error"?t.error:n.severity==="warning"?t.warning:t.textMuted,textTransform:"uppercase",letterSpacing:"0.04em"},children:n.severity}),s.jsx("div",{style:{fontSize:12,color:t.textPrimary,marginTop:4},children:n.message})]},`${n.code??n.message}-${r}`))})}function $$({chartConfig:e,onChange:t,t:n}){const r={width:"100%",background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:6,color:n.textPrimary,fontSize:12,fontFamily:n.font,padding:"8px 10px",outline:"none"};return s.jsxs("div",{style:{display:"grid",gap:10,padding:12},children:[s.jsxs("select",{value:e.chart??"table",onChange:o=>t({...e,chart:o.target.value}),style:r,children:[s.jsx("option",{value:"table",children:"Table"}),da.map(o=>s.jsx("option",{value:o.value,children:o.label},o.value))]}),s.jsx("input",{value:e.x??"",onChange:o=>t({...e,x:o.target.value}),placeholder:"x binding",style:r}),s.jsx("input",{value:e.y??"",onChange:o=>t({...e,y:o.target.value}),placeholder:"y binding",style:r}),s.jsx("input",{value:e.color??"",onChange:o=>t({...e,color:o.target.value}),placeholder:"color binding",style:r}),s.jsx("input",{value:e.title??"",onChange:o=>t({...e,title:o.target.value}),placeholder:"title",style:r})]})}function V$({blockName:e,loading:t,detail:n,graph:r,paths:o,onSelectNode:i,onOpenFull:a,t:l}){if(!e)return s.jsx(St,{message:"Lineage will appear once the block has a name."});if(t)return s.jsx(St,{message:"Loading block lineage…"});if(!(n!=null&&n.node))return s.jsxs("div",{style:{padding:12,display:"grid",gap:12},children:[s.jsx("div",{style:{fontSize:12,color:l.textMuted,fontFamily:l.font},children:"No lineage node was found for this block yet. Save the block or compile the project if you expect it to appear in the graph."}),s.jsx("div",{children:s.jsx("button",{onClick:a,style:{background:l.btnBg,border:`1px solid ${l.btnBorder}`,borderRadius:6,color:l.textPrimary,cursor:"pointer",fontSize:11,fontFamily:l.font,padding:"6px 10px"},children:"Open Full Lineage"})})]});const c=`block:${e}`;return s.jsxs("div",{style:{padding:12,display:"grid",gap:12,overflowY:"auto"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:12,fontWeight:700,color:l.textPrimary,fontFamily:l.font},children:n.node.name}),s.jsx("div",{style:{fontSize:11,color:l.textMuted,fontFamily:l.font},children:n.node.domain?`Domain: ${n.node.domain}`:"Block lineage focus"})]}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:a,style:{background:l.btnBg,border:`1px solid ${l.btnBorder}`,borderRadius:6,color:l.textPrimary,cursor:"pointer",fontSize:11,fontFamily:l.font,padding:"6px 10px"},children:"Open Full Lineage"})]}),(o==null?void 0:o.layerSummary)&&s.jsx(_D,{layerSummary:o.layerSummary,t:l}),r&&r.nodes.length>0&&s.jsx(pE,{nodes:r.nodes,edges:r.edges,focalNodeId:c,height:360,onNodeClick:i,layoutMode:"flow"}),o&&(o.upstreamPaths.length>0||o.downstreamPaths.length>0)&&s.jsxs("div",{style:{display:"grid",gap:10},children:[o.upstreamPaths.length>0&&s.jsx(Gu,{title:"Source to Block",paths:o.upstreamPaths,onNodeClick:i,focalNodeId:c,t:l}),o.downstreamPaths.length>0&&s.jsx(Gu,{title:"Block to Consumption",paths:o.downstreamPaths,onNodeClick:i,focalNodeId:c,t:l})]})]})}function X$({metadata:e,draftMetadata:t,onChange:n,t:r}){const o={width:"100%",background:r.inputBg,border:`1px solid ${r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:12,fontFamily:r.font,padding:"8px 10px",outline:"none"},i={name:(t==null?void 0:t.name)||(e==null?void 0:e.name)||"",domain:(t==null?void 0:t.domain)||(e==null?void 0:e.domain)||"uncategorized",description:(t==null?void 0:t.description)||(e==null?void 0:e.description)||"",owner:(t==null?void 0:t.owner)||(e==null?void 0:e.owner)||"",tags:(t==null?void 0:t.tags)||(e==null?void 0:e.tags)||[]};return s.jsxs("div",{style:{display:"grid",gap:10,padding:12},children:[s.jsx("input",{value:i.name,onChange:a=>n({name:a.target.value}),placeholder:"Block name",style:o}),s.jsx("input",{value:i.domain,onChange:a=>n({domain:a.target.value}),placeholder:"Domain",style:o}),s.jsx("input",{value:i.owner,onChange:a=>n({owner:a.target.value}),placeholder:"Owner",style:o}),s.jsx("input",{value:i.description,onChange:a=>n({description:a.target.value}),placeholder:"Description",style:o}),s.jsx("input",{value:i.tags.join(", "),onChange:a=>n({tags:a.target.value.split(",").map(l=>l.trim()).filter(Boolean)}),placeholder:"Tags",style:o})]})}function St({message:e}){const{state:t}=fe(),n=ie[t.themeMode];return s.jsx("div",{style:{padding:16,fontSize:12,color:n.textMuted},children:e})}const Jf={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149"},z$={draft:["review"],review:["certified","draft"],certified:["deprecated"],deprecated:["draft"]};function K$({currentStatus:e,blockPath:t,onStatusChanged:n,t:r}){const[o,i]=f.useState(!1),a=z$[e]??[],l=async c=>{if(t){i(!0);try{const d=await z.updateBlockStatus(t,c);d.ok&&d.status&&n(d.status)}finally{i(!1)}}};return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 12px",background:r.pillBg,borderRadius:8},children:[s.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:"Status:"}),s.jsx("span",{style:{fontSize:11,fontWeight:600,color:Jf[e]??r.textMuted,background:`${Jf[e]??r.textMuted}18`,padding:"2px 8px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em",fontFamily:r.font},children:e}),s.jsx("span",{style:{flex:1}}),a.map(c=>s.jsx("button",{onClick:()=>void l(c),disabled:o,style:{background:c==="certified"?"#3fb950":c==="deprecated"?"#f85149":r.btnBg,border:`1px solid ${c==="certified"?"#3fb950":c==="deprecated"?"#f85149":r.btnBorder}`,borderRadius:4,color:c==="certified"||c==="deprecated"?"#fff":r.textSecondary,cursor:o?"not-allowed":"pointer",fontSize:10,fontWeight:600,fontFamily:r.font,padding:"3px 10px",textTransform:"capitalize",opacity:o?.5:1},children:o?"...":c==="certified"?"Certify":c==="deprecated"?"Deprecate":`Move to ${c}`},c))]})}function q$({source:e,blockPath:t,testResults:n,running:r,onRunTests:o,t:i}){const l=[...e.matchAll(/assert\s+(\w+)\s*(>=?|<=?|==|!=|IN)\s*(\S+)/g)].map(c=>({field:c[1],operator:c[2],expected:c[3]}));return s.jsxs("div",{style:{padding:12,display:"grid",gap:10},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("span",{style:{fontSize:12,fontWeight:600,color:i.textPrimary,fontFamily:i.font},children:"Test Assertions"}),s.jsx("span",{style:{flex:1}}),s.jsx("button",{onClick:o,disabled:r||!t,style:{background:i.accent,border:"none",borderRadius:6,color:"#fff",cursor:r||!t?"not-allowed":"pointer",fontSize:11,fontWeight:600,fontFamily:i.font,padding:"5px 14px",opacity:r||!t?.5:1},children:r?"Running...":"Run Tests"})]}),l.length===0&&s.jsxs("div",{style:{fontSize:12,color:i.textMuted,fontFamily:i.font,lineHeight:1.5},children:["No test assertions found. Add assertions in your block:",s.jsx("pre",{style:{margin:"8px 0 0",padding:"8px 10px",background:i.editorBg,border:`1px solid ${i.cellBorder}`,borderRadius:6,fontSize:10,fontFamily:i.fontMono,color:i.textSecondary},children:`tests {
|
|
817
|
-
assert row_count > 0
|
|
818
|
-
assert max_value <= 1000000
|
|
819
|
-
}`})]}),l.map((c,d)=>{const E=n==null?void 0:n[d],u=E==null?void 0:E.passed;return s.jsxs("div",{style:{padding:"8px 12px",borderRadius:8,border:`1px solid ${E?u?"#3fb95040":"#f8514940":i.cellBorder}`,background:E?u?"#3fb95008":"#f8514908":"transparent",display:"flex",alignItems:"center",gap:8},children:[E&&s.jsx("span",{style:{fontSize:14,color:u?"#3fb950":"#f85149",fontWeight:700},children:u?"✓":"✗"}),s.jsxs("div",{style:{flex:1},children:[s.jsxs("div",{style:{fontSize:12,color:i.textPrimary,fontFamily:i.fontMono},children:[c.field," ",c.operator," ",c.expected]}),E&&!u&&E.actual&&s.jsxs("div",{style:{fontSize:11,color:"#f85149",fontFamily:i.font,marginTop:2},children:["Actual: ",E.actual]})]})]},d)}),n&&n.length>0&&s.jsxs("div",{style:{padding:"8px 12px",background:i.pillBg,borderRadius:8,fontSize:12,fontFamily:i.font,color:i.textSecondary},children:[n.filter(c=>c.passed).length,"/",n.length," passed"]})]})}function J$({entries:e,t}){return e.length===0?s.jsx(St,{message:"No version history available. Commit changes to build history."}):s.jsxs("div",{style:{padding:12,display:"grid",gap:8},children:[s.jsx("div",{style:{fontSize:12,fontWeight:600,color:t.textPrimary,fontFamily:t.font},children:"Version History"}),e.map(n=>s.jsxs("div",{style:{padding:"8px 12px",border:`1px solid ${t.cellBorder}`,borderRadius:8,background:t.inputBg},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[s.jsx("span",{style:{fontSize:10,fontFamily:t.fontMono,color:t.accent,background:`${t.accent}12`,padding:"1px 6px",borderRadius:4},children:n.hash.slice(0,7)}),s.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font},children:new Date(n.date).toLocaleDateString()}),s.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font,marginLeft:"auto"},children:n.author})]}),s.jsx("div",{style:{fontSize:12,color:t.textPrimary,fontFamily:t.font},children:n.message})]},n.hash))]})}function Q$({tree:e,totalTree:t,expanded:n,setExpanded:r,onEnsureColumns:o,onInsert:i,query:a,onQueryChange:l,stats:c,connectionName:d,loadingNodes:E,onRefresh:u,t:T}){const p={width:"100%",background:T.inputBg,border:`1px solid ${T.inputBorder}`,borderRadius:8,color:T.textPrimary,fontSize:12,fontFamily:T.font,padding:"8px 10px",outline:"none",boxSizing:"border-box"},h=(A,S=0)=>{var g,C,y;const R=A.kind!=="column",m=n[A.id]??S<1,I=E.has(A.id),O=A.kind==="schema"?(g=A.children)==null?void 0:g.length:A.kind==="table"?(C=A.children)==null?void 0:C.length:void 0,N=A.kind==="column"?A.type:A.kind,x=A.kind==="column"&&A.type?kR(A.type,T.accent):void 0;return s.jsxs("div",{children:[s.jsx(ed,{label:I?`${A.label} …`:A.label,depth:S,count:O,expanded:R?m:void 0,onToggle:R?()=>{r(w=>({...w,[A.id]:!m})),m||o(A)}:void 0,badge:N,badgeColor:x,onClick:()=>{if(A.kind==="table"&&A.path&&i(A.path),A.kind==="column"){const w=A.path?A.path.split(".").pop():"";i(w?`${w}.${A.label}`:A.label)}},onDoubleClick:()=>{A.kind==="table"&&A.path&&i(`SELECT *
|
|
820
|
-
FROM ${A.path}
|
|
821
|
-
LIMIT 100`)},t:T}),R&&m&&((y=A.children)==null?void 0:y.map(w=>h(w,S+1)))]},A.id)};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{padding:12,display:"grid",gap:12,borderBottom:`1px solid ${T.headerBorder}`,background:`${T.cellBg}66`},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:12,fontWeight:700,color:T.textPrimary,fontFamily:T.font},children:"Database Browser"}),s.jsx("div",{style:{fontSize:11,color:T.textMuted,fontFamily:T.font},children:"Browse the active connection, inspect schemas and columns, then insert tables or starter queries into the block."})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx("button",{onClick:u,title:"Refresh schema",style:{background:"none",border:"none",cursor:"pointer",padding:4,borderRadius:6,color:T.textMuted,fontSize:14,lineHeight:1},children:"↻"}),s.jsx("span",{style:{fontSize:10,fontWeight:700,color:T.accent,background:`${T.accent}18`,borderRadius:999,padding:"5px 9px",textTransform:"uppercase",letterSpacing:"0.04em"},children:d})]})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8},children:[s.jsx(Ec,{label:"Schemas",value:c.schemas,t:T}),s.jsx(Ec,{label:"Tables",value:c.tables,t:T}),s.jsx(Ec,{label:"Columns",value:c.columns,t:T})]}),s.jsx("input",{value:a,onChange:A=>l(A.target.value),placeholder:"Search schemas, tables, columns...",style:p})]}),s.jsx("div",{style:{flex:1,overflowY:"auto",padding:e.length>0?"6px 0 0":0},children:t.length===0?s.jsx(St,{message:"No schemas were found for the active connection yet."}):e.length===0?s.jsx(St,{message:"No database objects match the current search."}):e.map(A=>h(A))})]})}function Z$({row:e,selectedId:t,setSelectedId:n,expanded:r,setExpanded:o,onInsert:i,favorites:a,dispatch:l,t:c}){var h;const{node:d,depth:E,hasChildren:u,isExpanded:T}=e,p=d.id.split(":").slice(1).join(":");return u?s.jsx(ed,{label:d.label,depth:E,count:(h=d.children)==null?void 0:h.length,expanded:T,onToggle:()=>o(A=>({...A,[d.id]:!T})),onClick:()=>n(d.id),selected:t===d.id,t:c}):s.jsx(ed,{label:d.label,depth:E,badge:d.kind,selected:t===d.id,onClick:()=>n(d.id),onDoubleClick:()=>{z.getSemanticObject(d.id).then(i).catch(()=>{})},onFavoriteToggle:d.kind==="metric"||d.kind==="dimension"?()=>void z.toggleFavorite(p).then(A=>l({type:"SET_SEMANTIC_FAVORITES",favorites:A})):void 0,favorite:d.kind==="metric"||d.kind==="dimension"?a.has(p):void 0,t:c})}function $s(e,t){const n=e.match(/query\s*=\s*"""([\s\S]*?)"""/i);return n?e.replace(n[0],`query = """${n[1].trimEnd()}
|
|
822
|
-
${t}
|
|
823
|
-
"""`):/^\s*block\s+"/i.test(e.trim())?e.replace(/\n\}\s*$/,`
|
|
824
|
-
|
|
825
|
-
query = """
|
|
826
|
-
${t}
|
|
827
|
-
"""
|
|
828
|
-
}
|
|
829
|
-
`):`${e.trimEnd()}
|
|
830
|
-
${t}
|
|
831
|
-
`}function uc(e,t){if(!e)return[];const n=new Set,r=o=>{var a;const i=(a=o.meta)==null?void 0:a[t];typeof i=="string"&&i.trim()&&n.add(i.trim());for(const l of o.children??[])r(l)};return r(e),Array.from(n).sort((o,i)=>o.localeCompare(i))}function nm(e,t){var T,p,h,A,S;const n=t.query.trim().toLowerCase(),r=Object.values(e.meta??{}).filter(R=>R!=null).map(R=>String(R).toLowerCase()),o=!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||r.some(R=>R.includes(n)),i=!t.type||e.kind===t.type||e.kind==="provider"||e.kind==="domain"||e.kind==="group",a=!t.domain||e.kind==="provider"||e.kind==="group"||((T=e.meta)==null?void 0:T.domain)===t.domain||e.kind==="domain"&&e.label===t.domain,l=!t.provider||((p=e.meta)==null?void 0:p.provider)===t.provider||e.id===`provider:${t.provider}`,c=!t.cube||((h=e.meta)==null?void 0:h.cube)===t.cube,d=!t.owner||((A=e.meta)==null?void 0:A.owner)===t.owner,E=!t.tag||String(((S=e.meta)==null?void 0:S.tags)??"").split(",").filter(Boolean).includes(t.tag),u=(e.children??[]).map(R=>nm(R,t)).filter(R=>!!R);return u.length>0?{...e,children:u,count:e.kind==="provider"||e.kind==="domain"||e.kind==="group"?u.length:e.count}:o&&i&&a&&l&&c&&d&&E?{...e,children:[]}:null}function rm(e,t,n=0){const r=[];for(const o of e){const i=!!(o.children&&o.children.length>0),a=t[o.id]??n<3;r.push({node:o,depth:n,hasChildren:i,isExpanded:a}),i&&a&&r.push(...rm(o.children??[],t,n+1))}return r}function om(e,t,n){return e.map(r=>r.id===t?n:r.children?{...r,children:om(r.children,t,n)}:r)}function eV(e,t){const n=t.trim().toLowerCase();if(!n)return e;const r=o=>{const i=[o.label,o.path,o.type].filter(l=>!!l).some(l=>l.toLowerCase().includes(n)),a=(o.children??[]).map(l=>r(l)).filter(l=>!!l);return i||a.length>0?{...o,children:a}:null};return e.map(o=>r(o)).filter(o=>!!o)}function tV(e){let t=0,n=0,r=0;const o=i=>{i.kind==="schema"&&(t+=1),i.kind==="table"&&(n+=1),i.kind==="column"&&(r+=1);for(const a of i.children??[])o(a)};for(const i of e)o(i);return{schemas:t,tables:n,columns:r}}function nV(e){return!!(e&&e.children&&e.children.length>0)}function rV(e){if(e.metrics.length===0&&e.measures.length===0&&e.dimensions.length===0&&e.timeDimensions.length===0&&e.entities.length===0&&e.hierarchies.length===0&&e.semanticModels.length===0&&e.savedQueries.length===0)return null;const t=e.provider??"dql",n=new Map,r=(i,a)=>{const l=n.get(i)??[];l.push(a),n.set(i,l)};for(const i of e.metrics){const a=i.domain||"uncategorized";r(a,{id:`metric:${i.name}`,label:i.label||i.name,kind:"metric",meta:{provider:t,domain:a,cube:i.table,owner:i.owner??"",tags:i.tags.join(",")}})}for(const i of e.measures){const a=i.domain||"uncategorized";r(a,{id:`measure:${i.name}`,label:i.label||i.name,kind:"measure",meta:{provider:t,domain:a,cube:i.cube??i.table,owner:i.owner??"",tags:i.tags.join(","),agg:i.agg}})}for(const i of e.dimensions){const a=i.domain||"uncategorized";r(a,{id:`dimension:${i.name}`,label:i.label||i.name,kind:"dimension",meta:{provider:t,domain:a,cube:i.table,owner:i.owner??"",tags:i.tags.join(",")}})}for(const i of e.timeDimensions){const a=i.domain||"uncategorized";r(a,{id:`time_dimension:${i.name}`,label:i.label||i.name,kind:"time_dimension",meta:{provider:t,domain:a,cube:i.cube??i.table,owner:i.owner??"",tags:i.tags.join(",")}})}for(const i of e.entities){const a=i.domain||"uncategorized";r(a,{id:`entity:${i.name}`,label:i.label||i.name,kind:"entity",meta:{provider:t,domain:a,cube:i.cube??i.table,owner:i.owner??"",tags:i.tags.join(","),type:i.type}})}for(const i of e.semanticModels){const a=i.domain||"uncategorized";r(a,{id:`semantic_model:${i.name}`,label:i.label||i.name,kind:"semantic_model",meta:{provider:t,domain:a,table:i.table,owner:i.owner??"",tags:i.tags.join(",")}})}for(const i of e.savedQueries){const a=i.domain||"uncategorized";r(a,{id:`saved_query:${i.name}`,label:i.label||i.name,kind:"saved_query",meta:{provider:t,domain:a,owner:i.owner??"",tags:i.tags.join(",")}})}for(const i of e.hierarchies){const a=i.domain||"uncategorized";r(a,{id:`hierarchy:${i.name}`,label:i.label||i.name,kind:"hierarchy",meta:{provider:t,domain:a}})}const o=Array.from(n.entries()).sort((i,a)=>i[0].localeCompare(a[0])).map(([i,a])=>{const l=a.filter(R=>R.kind==="metric"),c=a.filter(R=>R.kind==="measure"),d=a.filter(R=>R.kind==="dimension"),E=a.filter(R=>R.kind==="time_dimension"),u=a.filter(R=>R.kind==="entity"),T=a.filter(R=>R.kind==="hierarchy"),p=a.filter(R=>R.kind==="semantic_model"),h=a.filter(R=>R.kind==="saved_query"),A=[],S=(R,m,I)=>{I.length!==0&&A.push({id:`group:${i}:${m.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,label:m,kind:"group",count:I.length,meta:{provider:t,domain:i,objectKind:R},children:I.sort((O,N)=>O.label.localeCompare(N.label))})};return l.length>0&&S("metric","Metrics",l),S("measure","Measures",c),d.length>0&&S("dimension","Dimensions",d),S("time_dimension","Time Dimensions",E),S("entity","Entities",u),T.length>0&&S("hierarchy","Hierarchies",T),S("semantic_model","Semantic Models",p),S("saved_query","Saved Queries",h),{id:`domain:${t}:${i}`,label:i,kind:"domain",count:A.length,meta:{provider:t,domain:i},children:A}});return{id:"root:semantic",label:"Semantic Layer",kind:"group",children:[{id:`provider:${t}`,label:t.toUpperCase(),kind:"provider",count:o.length,meta:{provider:t},children:o}]}}const sm={source_table:"TABLE",dbt_model:"DBT",dbt_source:"SOURCE",block:"BLOCK",metric:"METRIC",dimension:"DIM",domain:"DOMAIN",chart:"CHART",dashboard:"NOTEBOOK"};function oV(e,t,n="flow",r="LR"){var a;const o=new Fi.graphlib.Graph().setDefaultEdgeLabel(()=>({})),i=r==="LR";o.setGraph({rankdir:r,ranksep:n==="layered"?120:i?80:60,nodesep:i?40:50,marginx:32,marginy:32});for(const l of e){const c={width:190,height:58};if(n==="layered"&&((a=l.data)!=null&&a.layer)){const d=hi.indexOf(l.data.layer);d>=0&&(c.rank=d)}o.setNode(l.id,c)}for(const l of t)o.setEdge(l.source,l.target);return Fi.layout(o),e.map(l=>{const c=o.node(l.id);return{...l,position:{x:c.x-95,y:c.y-29},data:{...l.data,direction:r}}})}function sV({data:e,selected:t}){const n=e.nodeType,r=we[n]??"var(--color-text-tertiary)",o=sm[n]??n.toUpperCase(),i=e.direction??"LR",a=i==="LR"?ae.Left:ae.Top,l=i==="LR"?ae.Right:ae.Bottom;return s.jsxs("div",{style:{minWidth:156,maxWidth:220,background:"var(--color-bg-card)",border:`2px solid ${t?"var(--color-accent-blue)":r}`,borderRadius:10,padding:"8px 10px",boxShadow:t?"0 0 0 1px color-mix(in srgb, var(--color-accent-blue) 25%, transparent)":"none"},children:[s.jsx(Rn,{type:"target",position:a,style:{width:7,height:7,background:r,border:"none"}}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[s.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.04em",color:"var(--color-bg-primary)",background:r,borderRadius:4,padding:"2px 6px"},children:o}),e.domain&&s.jsx("span",{style:{color:"var(--color-text-tertiary)",fontSize:10},children:e.domain})]}),s.jsx("div",{style:{color:"var(--color-text-primary)",fontSize:11,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.label,children:e.label}),s.jsx("div",{style:{color:"var(--color-text-tertiary)",fontSize:10,marginTop:3},children:la[n]??n}),s.jsx(Rn,{type:"source",position:l,style:{width:7,height:7,background:r,border:"none"}})]})}const iV={dagNode:sV};function rn({label:e,active:t,color:n,onClick:r}){return s.jsx("button",{onClick:r,style:{borderRadius:999,border:`1px solid ${t?n:"var(--color-border-primary)"}`,background:t?`color-mix(in srgb, ${n} 13%, transparent)`:"transparent",color:t?n:"var(--color-text-tertiary)",fontSize:10,fontWeight:700,padding:"4px 8px",cursor:"pointer"},children:e})}function aV(){const{state:e,dispatch:t}=fe(),n=ie[e.themeMode],[r,o]=f.useState(!0),[i,a]=f.useState({nodes:[],edges:[]}),[l,c]=f.useState({nodes:[],edges:[]}),[d,E]=f.useState(null),[u,T]=f.useState(null),[p,h]=f.useState(""),[A,S]=f.useState([]),[R,m]=f.useState({source_table:!0,dbt_model:!0,dbt_source:!0,block:!0,notebook:!0,dashboard:!0,app:!0,domain:!0}),[I,O]=f.useState("flow"),[N,x]=f.useState("LR"),[g,C,y]=oI([]),[w,v,B]=sI([]),b=f.useCallback(async()=>{o(!0);const _=await z.fetchLineage(),F={nodes:_.nodes??[],edges:_.edges??[]};a(F),c(F),o(!1)},[]);f.useEffect(()=>{b()},[b]),f.useEffect(()=>{let _=!1;if(p.trim().length<2){S([]);return}return z.searchLineage(p.trim()).then(F=>{_||S(F.matches??[])}),()=>{_=!0}},[p]);const L=f.useMemo(()=>{const _=new Set(l.nodes.filter(F=>R[F.type]??!1).map(F=>F.id));return{nodes:l.nodes.filter(F=>_.has(F.id)),edges:l.edges.filter(F=>_.has(F.source)&&_.has(F.target))}},[l,R]);f.useEffect(()=>{const _=L.nodes.map(k=>({id:k.id,type:"dagNode",position:{x:0,y:0},data:{label:k.name,nodeType:k.type,domain:k.domain,layer:vd(k)}})),F=L.edges.map((k,H)=>({id:`edge-${H}-${k.source}-${k.target}-${k.type}`,source:k.source,target:k.target,style:{stroke:co[k.type]??"var(--color-text-tertiary)",strokeWidth:1.6},markerEnd:{type:Dr.ArrowClosed,color:co[k.type]??"var(--color-text-tertiary)",width:12,height:12}}));C(oV(_,F,I,N)),v(F)},[L,I,N,v,C]);const D=f.useCallback(async _=>{const F=await z.queryLineage({focus:_});c(F.graph??{nodes:[],edges:[]}),E(F.focalNode??null),T(F.focalNode??null),t({type:"SET_LINEAGE_FOCUS",nodeId:_}),h(""),S([])},[t]);f.useEffect(()=>{e.lineageFocusNodeId&&D(e.lineageFocusNodeId)},[D,e.lineageFocusNodeId]);const M=f.useCallback(()=>{c(i),E(null),T(null),t({type:"SET_LINEAGE_FOCUS",nodeId:null})},[t,i]),U=f.useCallback(async(_,F)=>{await D(F.id)},[D]),P=f.useMemo(()=>{if(!u)return null;const _=l.edges.filter(k=>k.target===u.id).length,F=l.edges.filter(k=>k.source===u.id).length;return{incoming:_,outgoing:F}},[l.edges,u]);return r?s.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"Loading lineage graph..."}):i.nodes.length===0?s.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"No lineage graph available yet."}):s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",background:"var(--color-bg-primary)"},children:[s.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`,background:n.sidebarBg},children:[s.jsxs("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap",alignItems:"center"},children:[s.jsxs("div",{style:{display:"flex",borderRadius:6,border:`1px solid ${n.headerBorder}`,overflow:"hidden"},children:[s.jsx("button",{onClick:()=>O("flow"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",cursor:"pointer",background:I==="flow"?"var(--color-bg-tertiary)":"transparent",color:I==="flow"?"var(--color-text-primary)":"var(--color-text-tertiary)"},children:"Flow"}),s.jsx("button",{onClick:()=>O("layered"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",borderLeft:`1px solid ${n.headerBorder}`,cursor:"pointer",background:I==="layered"?"var(--color-bg-tertiary)":"transparent",color:I==="layered"?"var(--color-text-primary)":"var(--color-text-tertiary)"},children:"Layered"})]}),s.jsxs("div",{style:{display:"flex",borderRadius:6,border:`1px solid ${n.headerBorder}`,overflow:"hidden",marginRight:4},children:[s.jsxs("button",{title:"Horizontal layout (left → right)",onClick:()=>x("LR"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",cursor:"pointer",background:N==="LR"?"var(--color-bg-tertiary)":"transparent",color:N==="LR"?"var(--color-text-primary)":"var(--color-text-tertiary)",display:"flex",alignItems:"center",gap:3},children:[s.jsxs("svg",{width:"14",height:"10",viewBox:"0 0 14 10",fill:"none",children:[s.jsx("rect",{x:"0",y:"2",width:"4",height:"6",rx:"1",fill:"currentColor",opacity:"0.7"}),s.jsx("line",{x1:"4",y1:"5",x2:"10",y2:"5",stroke:"currentColor",strokeWidth:"1.2"}),s.jsx("path",{d:"M9 3l2 2-2 2",stroke:"currentColor",strokeWidth:"1.2",fill:"none"}),s.jsx("rect",{x:"10",y:"2",width:"4",height:"6",rx:"1",fill:"currentColor"})]}),"LR"]}),s.jsxs("button",{title:"Vertical layout (top → bottom)",onClick:()=>x("TB"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",borderLeft:`1px solid ${n.headerBorder}`,cursor:"pointer",background:N==="TB"?"var(--color-bg-tertiary)":"transparent",color:N==="TB"?"var(--color-text-primary)":"var(--color-text-tertiary)",display:"flex",alignItems:"center",gap:3},children:[s.jsxs("svg",{width:"10",height:"14",viewBox:"0 0 10 14",fill:"none",children:[s.jsx("rect",{x:"2",y:"0",width:"6",height:"4",rx:"1",fill:"currentColor",opacity:"0.7"}),s.jsx("line",{x1:"5",y1:"4",x2:"5",y2:"10",stroke:"currentColor",strokeWidth:"1.2"}),s.jsx("path",{d:"M3 9l2 2 2-2",stroke:"currentColor",strokeWidth:"1.2",fill:"none"}),s.jsx("rect",{x:"2",y:"10",width:"6",height:"4",rx:"1",fill:"currentColor"})]}),"TB"]})]}),s.jsx(rn,{label:"Tables",active:R.source_table,color:we.source_table,onClick:()=>m(_=>({..._,source_table:!_.source_table}))}),s.jsx(rn,{label:"dbt Models",active:R.dbt_model,color:we.dbt_model,onClick:()=>m(_=>({..._,dbt_model:!_.dbt_model}))}),s.jsx(rn,{label:"dbt Sources",active:R.dbt_source,color:we.dbt_source,onClick:()=>m(_=>({..._,dbt_source:!_.dbt_source}))}),s.jsx(rn,{label:"DQL Blocks",active:R.block,color:we.block,onClick:()=>m(_=>({..._,block:!_.block}))}),s.jsx(rn,{label:"Notebooks",active:R.notebook,color:we.notebook,onClick:()=>m(_=>({..._,notebook:!_.notebook}))}),s.jsx(rn,{label:"Dashboards",active:R.dashboard,color:we.dashboard,onClick:()=>m(_=>({..._,dashboard:!_.dashboard}))}),s.jsx(rn,{label:"Apps",active:R.app,color:we.app,onClick:()=>m(_=>({..._,app:!_.app}))}),s.jsx(rn,{label:"Domains",active:R.domain,color:we.domain,onClick:()=>m(_=>({..._,domain:!_.domain}))})]}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("input",{value:p,onChange:_=>h(_.target.value),placeholder:"Search lineage and focus the graph...",style:{flex:1,padding:"8px 10px",borderRadius:6,border:`1px solid ${n.headerBorder}`,background:"var(--color-bg-sunken)",color:n.textPrimary,fontSize:12,outline:"none"}}),d&&s.jsx("button",{onClick:M,style:{borderRadius:6,border:`1px solid ${n.headerBorder}`,background:"transparent",color:n.textPrimary,cursor:"pointer",fontSize:12,fontWeight:600,padding:"8px 10px"},children:"Show All"})]}),s.jsx("div",{style:{marginTop:8,color:n.textMuted,fontSize:11,lineHeight:1.5},children:"This graph connects raw source tables and dbt DAGs to DQL blocks and the notebooks that consume them. Search to focus on a single path instead of scanning the full project graph."}),A.length>0&&s.jsx("div",{style:{marginTop:8,border:`1px solid ${n.headerBorder}`,borderRadius:8,overflow:"hidden"},children:A.slice(0,8).map(_=>s.jsxs("button",{onClick:()=>void D(_.node.id),style:{width:"100%",textAlign:"left",padding:"8px 10px",background:"transparent",border:"none",borderTop:`1px solid ${n.headerBorder}`,color:n.textPrimary,cursor:"pointer"},children:[s.jsx("span",{style:{color:we[_.node.type]??"var(--color-text-tertiary)",fontSize:10,fontWeight:700,marginRight:8},children:sm[_.node.type]??_.node.type.toUpperCase()}),_.node.name]},_.node.id))})]}),s.jsx("div",{style:{flex:1,position:"relative"},children:s.jsxs(rI,{nodes:g,edges:w,onNodesChange:y,onEdgesChange:B,onNodeClick:U,nodeTypes:iV,fitView:!0,fitViewOptions:{padding:.18},proOptions:{hideAttribution:!0},style:{background:"var(--color-bg-primary)"},children:[s.jsx(aI,{color:"var(--color-border-secondary)",gap:24,size:1}),s.jsx(pF,{showInteractive:!1}),s.jsx(LF,{nodeColor:_=>{var F;return we[((F=_.data)==null?void 0:F.nodeType)??"source_table"]??"var(--color-text-tertiary)"},maskColor:"color-mix(in srgb, var(--color-bg-primary) 55%, transparent)",style:{background:"var(--color-bg-sunken)",border:"1px solid var(--color-border-primary)"}}),s.jsx(Ur,{position:"top-left",children:s.jsxs("div",{style:{background:"color-mix(in srgb, var(--color-bg-card) 92%, transparent)",border:"1px solid var(--color-border-primary)",borderRadius:8,padding:"8px 10px",minWidth:220,color:"var(--color-text-primary)",fontSize:12},children:[s.jsx("div",{style:{fontWeight:700,marginBottom:4},children:d?d.name:"Full Lineage View"}),s.jsxs("div",{style:{color:"var(--color-text-tertiary)",fontSize:11},children:[l.nodes.length," node(s), ",l.edges.length," edge(s)"]}),s.jsx("div",{style:{color:"var(--color-text-tertiary)",fontSize:11,marginTop:6,lineHeight:1.5},children:d?`Focused on ${la[d.type]??d.type}. Upstream shows provenance from tables/dbt; downstream shows DQL and notebook consumption.`:"Full project lineage across source tables, dbt, DQL blocks, and notebooks."}),u&&P&&s.jsxs("div",{style:{marginTop:8,color:"var(--color-text-tertiary)",fontSize:11},children:[P.incoming," upstream, ",P.outgoing," downstream"]})]})}),s.jsx(Ur,{position:"bottom-left",children:s.jsx("div",{style:{display:"flex",gap:10,background:"color-mix(in srgb, var(--color-bg-card) 92%, transparent)",border:"1px solid var(--color-border-primary)",borderRadius:8,padding:"6px 10px",color:"var(--color-text-tertiary)",fontSize:10},children:Object.entries(co).map(([_,F])=>s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[s.jsx("span",{style:{width:10,height:2,background:F,display:"inline-block"}}),n0[_]??_]},_))})})]})})]})}const lV=[{key:"all",label:"All changes"},{key:"M",label:"Modified"},{key:"A",label:"Added"},{key:"D",label:"Deleted"},{key:"R",label:"Renamed"},{key:"?",label:"Untracked"}];function cV(e){const t=e;return t.trim()==="??"?"?":t[0]==="R"||t[1]==="R"?"R":t.includes("A")?"A":t.includes("D")?"D":"M"}function dV(e){const t=[];for(const n of e){const r=n.status[0]??" ",o=n.status[1]??" ",i=cV(n.status);if(n.status==="??"){t.push({path:n.path,status:"?",staged:!1,partiallyStaged:!1});continue}const a=r!==" "&&r!=="?";a&&(o!==" "&&o!=="?")?(t.push({path:n.path,status:i,staged:!0,partiallyStaged:!0}),t.push({path:n.path,status:i,staged:!1,partiallyStaged:!0})):a?t.push({path:n.path,status:i,staged:!0,partiallyStaged:!1}):t.push({path:n.path,status:i,staged:!1,partiallyStaged:!1})}return t}function EV(){const{state:e}=fe(),t=ie[e.themeMode],[n,r]=f.useState(null),[o,i]=f.useState({current:null,branches:[]}),[a,l]=f.useState({url:null,name:null}),[c,d]=f.useState(null),[E,u]=f.useState(!1),[T,p]=f.useState(null),[h,A]=f.useState(""),[S,R]=f.useState("all"),[m,I]=f.useState(""),[O,N]=f.useState(null),[x,g]=f.useState(null),[C,y]=f.useState(!1),[w,v]=f.useState(!1),[B,b]=f.useState(!1),[L,D]=f.useState(""),M=f.useRef(null),U=f.useCallback(async()=>{y(!0);try{const[ne,Re,Oe]=await Promise.all([z.fetchGitStatus(),z.fetchGitBranches(),z.fetchGitRemote()]);r(ne),i({current:Re.current,branches:Re.branches}),l({url:Oe.url,name:Oe.name})}finally{window.setTimeout(()=>y(!1),350)}},[]);f.useEffect(()=>{U()},[U]),f.useEffect(()=>{const ne=window.setInterval(()=>{U()},4e3);return()=>window.clearInterval(ne)},[U]),f.useEffect(()=>{if(!w)return;const ne=Re=>{M.current&&!M.current.contains(Re.target)&&(v(!1),b(!1))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[w]),f.useEffect(()=>{if(!c){p(null);return}let ne=!1;return z.fetchGitDiff(c,E).then(Re=>{ne||p(Re)}),()=>{ne=!0}},[c,E,n]);const P=f.useMemo(()=>dV((n==null?void 0:n.changes)??[]),[n==null?void 0:n.changes]),_=P.filter(ne=>ne.staged),F=P.filter(ne=>!ne.staged),k=f.useCallback(ne=>!(S!=="all"&&ne.status!==S||h&&!ne.path.toLowerCase().includes(h.toLowerCase())),[S,h]),H=_.filter(k),Q=F.filter(k);f.useEffect(()=>{if(c&&P.some(Oe=>Oe.path===c&&Oe.staged===E))return;const ne=Q[0]??H[0];ne?(d(ne.path),u(ne.staged)):d(null)},[P,c,E,H,Q]);const q=f.useCallback((ne,Re)=>{g({kind:ne,text:Re}),window.setTimeout(()=>g(null),3e3)},[]),$=f.useCallback(async(ne,Re,Oe)=>{N(ne);try{const Fe=await Re();return Fe.ok?(Oe&&q("ok",Oe),await U()):q("err",Fe.error??`${ne} failed`),Fe}finally{N(null)}},[q,U]),Z=ne=>$("stage",()=>z.gitStage([ne])),Y=ne=>$("unstage",()=>z.gitUnstage([ne])),G=ne=>{window.confirm(`Discard local changes to ${ne}? This cannot be undone.`)&&$("discard",()=>z.gitDiscard([ne]),"Discarded local changes")},J=()=>$("stage",async()=>{const ne=F.map(Re=>Re.path);return ne.length===0?{ok:!0}:z.gitStage(ne)}),te=async()=>{const ne=m.trim();if(!ne)return q("err","Commit message required");const Re=_.length===0;(await $("commit",()=>z.gitCommit(ne,Re),"Committed")).ok&&I("")},re=async()=>{const ne=m.trim();if(!ne)return q("err","Commit message required");const Re=_.length===0;(await $("commit",()=>z.gitCommit(ne,Re))).ok&&(I(""),await $("push",()=>z.gitPush(),"Pushed to remote"))},oe=()=>$("pull",()=>z.gitPull(),"Pulled from remote"),V=()=>$("push",()=>z.gitPush(),"Pushed to remote"),le=ne=>{v(!1),$("checkout",()=>z.gitCheckout(ne),`Switched to ${ne}`)},Te=async()=>{const ne=L.trim();ne&&(v(!1),b(!1),D(""),$("branch",()=>z.gitCreateBranch(ne,!0),`Created and switched to ${ne}`))},de=P.find(ne=>ne.path===c&&ne.staged===E)??null;return n&&!n.inRepo?s.jsx(OV,{t}):s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,background:t.appBg},children:[s.jsx(uV,{t,branchCurrent:o.current,branches:o.branches,ahead:(n==null?void 0:n.ahead)??0,behind:(n==null?void 0:n.behind)??0,remoteUrl:a.url,refreshing:C,busy:O,onPull:oe,onPush:V,onRefresh:()=>void U(),onCheckout:le,branchMenuOpen:w,setBranchMenuOpen:v,newBranchOpen:B,setNewBranchOpen:b,newBranchName:L,setNewBranchName:D,onCreateBranch:Te,branchMenuRef:M}),s.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,overflow:"hidden"},children:[s.jsx(fV,{t,stagedFiles:H,unstagedFiles:Q,totalCount:P.length,selectedPath:c,selectedStaged:E,onSelect:(ne,Re)=>{d(ne),u(Re)},query:h,setQuery:A,statusFilter:S,setStatusFilter:R,onStage:Z,onUnstage:Y,onStageAll:J,ahead:(n==null?void 0:n.ahead)??0,behind:(n==null?void 0:n.behind)??0,branchCurrent:o.current}),s.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",overflow:"hidden",background:t.appBg},children:[de&&T?s.jsxs(s.Fragment,{children:[s.jsx(pV,{t,entry:de,onStage:()=>Z(de.path),onUnstage:()=>Y(de.path),onDiscard:()=>G(de.path),stagedView:E}),s.jsx(SV,{t,diff:T.diff})]}):s.jsx(AV,{t,hasFiles:P.length>0}),s.jsx(IV,{t,commitMsg:m,setCommitMsg:I,stagedCount:_.length,unstagedCount:F.length,onCommit:te,onCommitAndPush:re,busy:O})]})]}),x&&s.jsx(mV,{t,kind:x.kind,text:x.text})]})}function uV(e){const{t}=e;return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 20px",borderBottom:`1px solid ${t.headerBorder}`,background:t.appBg,flexShrink:0,whiteSpace:"nowrap"},children:[s.jsx("span",{style:{fontFamily:t.fontMono,fontSize:10,fontWeight:700,letterSpacing:"0.08em",padding:"3px 7px",borderRadius:3,background:`${t.accent}1f`,color:t.accent,border:`1px solid ${t.accent}40`},children:"GIT"}),s.jsx("span",{style:{fontSize:14,fontWeight:500,color:t.textPrimary},children:"Source control"}),s.jsxs("div",{ref:e.branchMenuRef,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>e.setBranchMenuOpen(!e.branchMenuOpen),style:{display:"inline-flex",alignItems:"center",gap:5,background:t.cellBg,border:`1px solid ${t.cellBorder}`,color:t.textPrimary,padding:"3px 8px",borderRadius:4,fontSize:11,fontFamily:t.fontMono,cursor:"pointer"},children:[s.jsx(Gr,{size:11,strokeWidth:1.75}),e.branchCurrent??"detached",s.jsx(GC,{size:10,strokeWidth:1.75,style:{opacity:.6}})]}),e.branchMenuOpen&&s.jsxs("div",{style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:220,maxHeight:360,overflow:"auto",background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:6,boxShadow:"0 8px 24px rgba(0,0,0,0.18)",padding:"6px 0",zIndex:100},children:[e.branches.map(n=>s.jsxs("button",{onClick:()=>e.onCheckout(n),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"5px 10px",background:"transparent",border:"none",fontFamily:t.fontMono,fontSize:12,color:t.textPrimary,cursor:"pointer",textAlign:"left"},onMouseEnter:r=>r.currentTarget.style.background=t.btnHover,onMouseLeave:r=>r.currentTarget.style.background="transparent",children:[n===e.branchCurrent?s.jsx(kC,{size:11,strokeWidth:2,color:t.success}):s.jsx("span",{style:{width:11,display:"inline-block"}}),n]},n)),s.jsx("div",{style:{borderTop:`1px solid ${t.cellBorder}`,margin:"4px 0"}}),e.newBranchOpen?s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px"},children:[s.jsx("input",{autoFocus:!0,value:e.newBranchName,onChange:n=>e.setNewBranchName(n.target.value),onKeyDown:n=>{n.key==="Enter"&&e.onCreateBranch(),n.key==="Escape"&&(e.setNewBranchOpen(!1),e.setNewBranchName(""))},placeholder:"new-branch-name",style:{flex:1,background:t.appBg,color:t.textPrimary,border:`1px solid ${t.cellBorder}`,borderRadius:4,padding:"4px 7px",fontSize:12,fontFamily:t.fontMono,outline:"none"}}),s.jsx("button",{onClick:e.onCreateBranch,style:mr(t,"primary"),children:"Create"})]}):s.jsxs("button",{onClick:()=>e.setNewBranchOpen(!0),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"6px 10px",background:"transparent",border:"none",fontSize:12,color:t.accent,cursor:"pointer",textAlign:"left"},onMouseEnter:n=>n.currentTarget.style.background=t.btnHover,onMouseLeave:n=>n.currentTarget.style.background="transparent",children:[s.jsx(UL,{size:11,strokeWidth:1.75}),"Create new branch…"]})]})]}),e.remoteUrl&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontSize:11,color:t.textMuted},children:"·"}),s.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.fontMono,maxWidth:360,overflow:"hidden",textOverflow:"ellipsis"},title:e.remoteUrl,children:TV(e.remoteUrl)})]}),s.jsx("span",{style:{fontSize:11,color:t.textMuted},children:"·"}),s.jsxs("span",{style:{fontSize:11,color:t.success,display:"inline-flex",alignItems:"center",gap:5},children:[s.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:t.success}}),"ready"]}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:e.onRefresh,title:"Refresh",style:{background:"transparent",border:`1px solid ${t.btnBorder}`,padding:"6px 8px",borderRadius:5,cursor:"pointer",color:t.textMuted},children:s.jsx(vR,{size:12,strokeWidth:1.75,style:{animation:e.refreshing?"dql-spin 0.6s linear":void 0}})}),s.jsx("style",{children:"@keyframes dql-spin { to { transform: rotate(360deg); } }"}),s.jsxs("button",{onClick:e.onPull,disabled:!!e.busy,style:Qf(t),children:[s.jsx(gR,{size:12,strokeWidth:1.75,color:t.warning}),"Pull",e.behind>0&&s.jsx("span",{style:{fontFamily:t.fontMono,fontSize:10,color:t.textMuted,marginLeft:2},children:e.behind})]}),s.jsxs("button",{onClick:e.onPush,disabled:!!e.busy,style:Qf(t,!0),children:[s.jsx(xR,{size:12,strokeWidth:1.75}),"Push",e.ahead>0&&s.jsx("span",{style:{fontFamily:t.fontMono,fontSize:10,opacity:.75,marginLeft:2},children:e.ahead})]})]})}function Qf(e,t=!1){return{display:"inline-flex",alignItems:"center",gap:5,background:t?e.accent:e.cellBg,color:t?"#fff":e.textPrimary,border:`1px solid ${t?e.accent:e.btnBorder}`,padding:"5px 12px",borderRadius:6,fontSize:12,fontFamily:e.font,fontWeight:t?500:400,cursor:"pointer",whiteSpace:"nowrap"}}function mr(e,t="default"){return{background:t==="primary"?e.accent:e.cellBg,color:t==="primary"?"#fff":e.textPrimary,border:`1px solid ${t==="primary"?e.accent:e.btnBorder}`,padding:"4px 9px",borderRadius:4,fontSize:11,cursor:"pointer",whiteSpace:"nowrap",fontFamily:e.font}}function TV(e){return e.replace(/^git@([^:]+):/,"$1/").replace(/^https?:\/\//,"").replace(/\.git$/,"")}function fV(e){const{t}=e;return s.jsxs("div",{style:{width:300,flexShrink:0,background:t.sidebarBg,borderRight:`1px solid ${t.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden"},children:[s.jsxs("div",{style:{padding:"12px 14px 10px",borderBottom:`1px solid ${t.headerBorder}`},children:[s.jsx("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:8,fontSize:10,fontWeight:600,letterSpacing:"0.08em",textTransform:"uppercase",color:t.textMuted},children:"Source control"}),s.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[s.jsx("span",{style:{fontSize:18,fontWeight:700,letterSpacing:"-0.01em",color:t.textPrimary},children:"Changes"}),s.jsxs("span",{style:{fontSize:11,color:t.textMuted},children:[e.totalCount," files"]}),s.jsx("div",{style:{flex:1}}),e.unstagedFiles.length>0&&s.jsx("button",{onClick:e.onStageAll,style:mr(t),children:"Stage all"})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:6,padding:"5px 9px",marginBottom:7},children:[s.jsx(kL,{size:11,strokeWidth:1.75,color:t.textMuted}),s.jsx("input",{value:e.query,onChange:n=>e.setQuery(n.target.value),placeholder:"Filter by path…",style:{background:"transparent",border:"none",outline:"none",color:t.textPrimary,fontSize:12,flex:1,width:"100%",fontFamily:t.font}}),e.query&&s.jsx("button",{onClick:()=>e.setQuery(""),style:{background:"transparent",border:"none",color:t.textMuted,cursor:"pointer",padding:0},children:s.jsx(Md,{size:11,strokeWidth:1.75})})]}),s.jsx("select",{value:e.statusFilter,onChange:n=>e.setStatusFilter(n.target.value),style:{width:"100%",background:t.cellBg,color:t.textPrimary,border:`1px solid ${t.cellBorder}`,borderRadius:6,padding:"5px 9px",fontSize:12,cursor:"pointer",fontFamily:t.font},children:lV.map(n=>s.jsx("option",{value:n.key,children:n.label},n.key))})]}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"6px 8px"},children:[s.jsx(Zf,{t,label:"Staged",count:e.stagedFiles.length}),e.stagedFiles.length===0?s.jsx("div",{style:{fontSize:11,color:t.textMuted,padding:"4px 10px",fontStyle:"italic"},children:"No staged changes"}):e.stagedFiles.map(n=>s.jsx(ep,{t,file:n,active:e.selectedPath===n.path&&e.selectedStaged===!0,onClick:()=>e.onSelect(n.path,!0),actionLabel:"Unstage",onAction:()=>e.onUnstage(n.path)},`staged-${n.path}`)),s.jsx("div",{style:{height:8}}),s.jsx(Zf,{t,label:"Changes",count:e.unstagedFiles.length}),e.unstagedFiles.length===0?s.jsx("div",{style:{fontSize:11,color:t.textMuted,padding:"4px 10px",fontStyle:"italic"},children:e.totalCount===0?"Working tree clean":"No unstaged changes"}):e.unstagedFiles.map(n=>s.jsx(ep,{t,file:n,active:e.selectedPath===n.path&&e.selectedStaged===!1,onClick:()=>e.onSelect(n.path,!1),actionLabel:"Stage",onAction:()=>e.onStage(n.path)},`unstaged-${n.path}`))]}),s.jsxs("div",{style:{padding:"10px 14px",borderTop:`1px solid ${t.headerBorder}`,fontSize:10,color:t.textMuted,display:"flex",alignItems:"center",gap:6},children:[s.jsx(Gr,{size:11,strokeWidth:1.75}),s.jsx("span",{style:{fontFamily:t.fontMono,color:t.textPrimary},children:e.branchCurrent??"detached"}),s.jsx("span",{children:"·"}),e.behind>0&&s.jsxs("span",{style:{color:t.warning},children:["↓",e.behind]}),e.ahead>0&&s.jsxs("span",{style:{color:t.success},children:["↑",e.ahead]}),e.behind===0&&e.ahead===0&&s.jsx("span",{children:"up to date"})]})]})}function Zf({t:e,label:t,count:n}){return s.jsxs("div",{style:{fontSize:10,color:e.textMuted,fontWeight:600,letterSpacing:"0.07em",textTransform:"uppercase",padding:"6px 8px 4px",display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{children:t}),s.jsx("span",{style:{color:e.textMuted,opacity:.7},children:"·"}),s.jsx("span",{style:{color:e.textMuted},children:n})]})}function ep({t:e,file:t,active:n,onClick:r,actionLabel:o,onAction:i}){const[a,l]=f.useState(!1),c=t.path.split("/").slice(0,-1).join("/"),d=t.path.split("/").pop()??t.path;return s.jsxs("div",{onClick:r,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",borderRadius:5,marginBottom:1,cursor:"pointer",background:n?`${e.accent}18`:a?e.btnHover:"transparent",border:n?`1px solid ${e.accent}45`:"1px solid transparent"},children:[s.jsx(im,{t:e,status:t.status}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontSize:12,color:e.textPrimary,fontFamily:e.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d}),c&&s.jsx("div",{style:{fontSize:10,color:e.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c})]}),a&&s.jsx("button",{onClick:E=>{E.stopPropagation(),i()},style:{background:e.cellBg,border:`1px solid ${e.btnBorder}`,color:e.textPrimary,padding:"2px 7px",borderRadius:3,fontSize:10,cursor:"pointer",flexShrink:0,fontFamily:e.font},children:o})]})}function im({t:e,status:t}){const r={M:e.warning,A:e.success,D:e.error,R:e.accent,"?":e.textMuted}[t];return s.jsx("span",{style:{width:18,height:18,borderRadius:3,flexShrink:0,background:`${r}1a`,color:r,border:`1px solid ${r}40`,display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:10,fontWeight:700,fontFamily:e.fontMono},children:t})}function pV({t:e,entry:t,stagedView:n,onStage:r,onUnstage:o,onDiscard:i}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"12px 20px",borderBottom:`1px solid ${e.headerBorder}`,background:e.cellBg,flexShrink:0},children:[s.jsx(im,{t:e,status:t.status}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0,flex:1},children:[s.jsx("div",{style:{fontSize:13,fontWeight:500,color:e.textPrimary,fontFamily:e.fontMono},children:t.path}),s.jsxs("div",{style:{fontSize:11,color:e.textMuted,display:"flex",gap:8},children:[s.jsx("span",{children:n?"Staged changes":"Unstaged changes"}),t.partiallyStaged&&s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"·"}),s.jsx("span",{style:{color:e.warning},children:"partially staged"})]})]})]}),!n&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:i,style:mr(e),children:"Discard"}),s.jsx("button",{onClick:r,style:mr(e,"primary"),children:"Stage"})]}),n&&s.jsx("button",{onClick:o,style:mr(e),children:"Unstage"})]})}function SV({t:e,diff:t}){return t.trim()?s.jsx("div",{style:{flex:1,overflow:"auto",background:e.cellBg,fontFamily:e.fontMono,fontSize:12,lineHeight:"20px"},children:RV(t).map((n,r)=>s.jsx(hV,{t:e,line:n},r))}):s.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",color:e.textMuted,fontSize:13,background:e.appBg},children:"No textual diff (binary file or empty change)"})}function RV(e){const t=[];let n=0,r=0;const o=e.split(`
|
|
832
|
-
`);let i=0;for(const a of o){if(i++>1e3){t.push({kind:"meta",text:"… diff truncated (over 1000 lines)",oldNum:null,newNum:null});break}if(!(a.startsWith("diff --git")||a.startsWith("index ")||a.startsWith("+++ ")||a.startsWith("--- "))){if(a.startsWith("@@")){const l=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(a);l&&(n=Number(l[1]),r=Number(l[2])),t.push({kind:"hunk",text:a,oldNum:null,newNum:null});continue}a.startsWith("+")?t.push({kind:"add",text:a.slice(1),oldNum:null,newNum:r++}):a.startsWith("-")?t.push({kind:"del",text:a.slice(1),oldNum:n++,newNum:null}):a.startsWith("\\")?t.push({kind:"meta",text:a,oldNum:null,newNum:null}):t.push({kind:"ctx",text:a.startsWith(" ")?a.slice(1):a,oldNum:n++,newNum:r++})}}return t}function hV({t:e,line:t}){if(t.kind==="hunk")return s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"80px 1fr",background:`${e.accent}14`,borderTop:`1px solid ${e.accent}30`,borderBottom:`1px solid ${e.accent}30`,color:e.accent},children:[s.jsx("div",{style:{padding:"2px 10px",textAlign:"right",borderRight:`1px solid ${e.accent}30`,color:e.textMuted},children:"⋯"}),s.jsx("div",{style:{padding:"2px 12px",whiteSpace:"pre"},children:t.text})]});if(t.kind==="meta")return s.jsx("div",{style:{padding:"2px 12px",color:e.textMuted,fontStyle:"italic"},children:t.text});const n={add:{bg:`${e.success}18`,gutter:`${e.success}55`,ch:"+",chColor:e.success},del:{bg:`${e.error}18`,gutter:`${e.error}55`,ch:"−",chColor:e.error},ctx:{bg:"transparent",gutter:e.cellBorder,ch:" ",chColor:e.textMuted}}[t.kind];return s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"40px 40px 20px 1fr",background:n.bg,borderLeft:`3px solid ${n.gutter}`},children:[s.jsx("div",{style:{padding:"0 6px",color:e.textMuted,textAlign:"right",userSelect:"none"},children:t.oldNum??""}),s.jsx("div",{style:{padding:"0 6px",color:e.textMuted,textAlign:"right",userSelect:"none",borderRight:`1px solid ${e.cellBorder}`},children:t.newNum??""}),s.jsx("div",{style:{padding:"0 4px",color:n.chColor,textAlign:"center",userSelect:"none"},children:n.ch}),s.jsx("div",{style:{padding:"0 10px",whiteSpace:"pre",color:e.textPrimary,overflow:"hidden"},children:t.text})]})}function AV({t:e,hasFiles:t}){return s.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:8,color:e.textMuted,fontSize:13,background:e.appBg},children:[s.jsx(bR,{size:28,strokeWidth:1.5,color:e.textMuted,style:{opacity:.4}}),t?"Select a file to view its diff":"Working tree clean — no changes to review"]})}function IV({t:e,commitMsg:t,setCommitMsg:n,stagedCount:r,unstagedCount:o,onCommit:i,onCommitAndPush:a,busy:l}){const c=r===0&&o>0,d=r===0&&o===0,E=c?`Will stage all ${o} change${o===1?"":"s"} and commit`:r>0?`Committing ${r} staged file${r===1?"":"s"}`:"Nothing to commit";return s.jsxs("div",{style:{padding:"12px 20px",borderTop:`1px solid ${e.headerBorder}`,background:e.cellBg,flexShrink:0,display:"flex",flexDirection:"column",gap:6},children:[s.jsx("div",{style:{fontSize:10,color:e.textMuted,letterSpacing:"0.04em"},children:E}),s.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center"},children:[s.jsx("input",{value:t,onChange:u=>n(u.target.value),onKeyDown:u=>{(u.metaKey||u.ctrlKey)&&u.key==="Enter"&&(u.preventDefault(),i())},placeholder:"Commit message (⌘↵ to commit)…",style:{flex:1,background:e.appBg,color:e.textPrimary,border:`1px solid ${e.cellBorder}`,borderRadius:6,padding:"7px 10px",fontSize:12,outline:"none",fontFamily:e.font}}),s.jsx("button",{onClick:i,disabled:!!l||d||!t.trim(),style:{...mr(e),padding:"7px 12px",fontSize:12,opacity:d||!t.trim()?.45:1},children:"Commit"}),s.jsx("button",{onClick:a,disabled:!!l||d||!t.trim(),style:{background:e.success,color:"#fff",border:`1px solid ${e.success}`,padding:"7px 14px",borderRadius:6,fontSize:12,fontWeight:500,cursor:"pointer",opacity:d||!t.trim()?.5:1,fontFamily:e.font},children:"Commit & Push"})]})]})}function mV({t:e,kind:t,text:n}){const r=t==="ok"?e.success:e.error;return s.jsx("div",{style:{position:"absolute",bottom:80,right:24,background:e.cellBg,border:`1px solid ${r}55`,borderLeft:`3px solid ${r}`,borderRadius:6,padding:"8px 14px",fontSize:12,color:e.textPrimary,boxShadow:"0 8px 24px rgba(0,0,0,0.18)",maxWidth:420,zIndex:200},children:n})}function OV({t:e}){return s.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:12,padding:40,background:e.appBg},children:[s.jsx(Gr,{size:36,strokeWidth:1.5,color:e.textMuted,style:{opacity:.5}}),s.jsx("div",{style:{fontSize:16,fontWeight:600,color:e.textPrimary},children:"Not a git repository"}),s.jsxs("div",{style:{fontSize:13,color:e.textMuted,maxWidth:420,textAlign:"center"},children:["Initialize this folder with ",s.jsx("code",{style:{fontFamily:e.fontMono},children:"git init"})," to start tracking changes."]})]})}function NV({app:e}){var l,c;const{state:t,dispatch:n}=fe(),[r,o]=f.useState(!1),i=f.useRef(null);f.useEffect(()=>{if(!r)return;const d=E=>{var u;(u=i.current)!=null&&u.contains(E.target)||o(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[r]);const a=t.activePersona?`${t.activePersona.displayName??t.activePersona.userId} [${t.activePersona.roles.join(", ")}]`:"View as: Owner";return!e||e.members.length===0?s.jsx("span",{style:{fontSize:12,opacity:.6},children:a}):s.jsxs("div",{ref:i,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>o(d=>!d),style:{padding:"6px 12px",fontSize:12,background:"var(--surface, rgba(0,0,0,0.04))",border:"1px solid var(--border-color, rgba(0,0,0,0.1))",borderRadius:6,cursor:"pointer",color:"inherit",display:"inline-flex",alignItems:"center",gap:6},"aria-haspopup":"menu","aria-expanded":r,children:[s.jsx("span",{style:{fontSize:11,opacity:.65},children:"View as:"}),s.jsx("span",{style:{fontWeight:600},children:((l=t.activePersona)==null?void 0:l.displayName)??((c=t.activePersona)==null?void 0:c.userId)??"Owner"}),t.activePersona&&s.jsxs("span",{style:{fontSize:11,opacity:.7},children:["[",t.activePersona.roles.join(", "),"]"]}),s.jsx("span",{style:{fontSize:10,opacity:.6},children:"▾"})]}),r&&s.jsxs("div",{role:"menu",style:{position:"absolute",top:"100%",right:0,marginTop:4,minWidth:240,background:"var(--surface-elevated, #fff)",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,boxShadow:"0 4px 12px rgba(0,0,0,0.08)",zIndex:50},children:[s.jsxs("button",{role:"menuitem",onClick:async()=>{await z.clearPersona(),n({type:"SET_ACTIVE_PERSONA",persona:null}),o(!1)},style:tp(t.activePersona===null),children:[s.jsx("div",{style:{fontWeight:500},children:"Owner (local)"}),s.jsx("div",{style:{fontSize:11,opacity:.65},children:"Default — no RLS narrowing"})]}),s.jsx("div",{style:{height:1,background:"var(--border-color, rgba(0,0,0,0.08))",margin:"4px 0"}}),e.members.map(d=>{var E;return s.jsxs("button",{role:"menuitem",onClick:async()=>{const u=await z.setPersona(d.userId,e.id);n({type:"SET_ACTIVE_PERSONA",persona:u}),o(!1)},style:tp(((E=t.activePersona)==null?void 0:E.userId)===d.userId),children:[s.jsx("div",{style:{fontWeight:500},children:d.displayName??d.userId}),s.jsxs("div",{style:{fontSize:11,opacity:.65},children:["[",d.roles.join(", "),"]",d.attributes&&Object.keys(d.attributes).length>0?` · ${Object.entries(d.attributes).map(([u,T])=>`${u}=${T}`).join(", ")}`:""]})]},d.userId)})]})]})}function tp(e){return{display:"block",width:"100%",textAlign:"left",padding:"8px 12px",background:e?"var(--surface-hover, rgba(0,0,0,0.06))":"transparent",border:"none",cursor:"pointer",color:"inherit",fontSize:13}}function gV({title:e,scopeHint:t,upstreamContext:n,themeMode:r,hideSqlByDefault:o=!1,addToAppTarget:i,expanded:a=!1,onToggleExpanded:l,onClose:c}){const d=ie[r],[E,u]=f.useState([]),[T,p]=f.useState(""),[h,A]=f.useState(!1),[S,R]=f.useState(""),[m,I]=f.useState([]),[O,N]=f.useState(null),x=f.useRef(null),g=async()=>{const C=T.trim();if(!C||h)return;const y=[...E,{role:"user",content:C}];u(y),p(""),N(null),R(""),I([]),A(!0);const w=new AbortController;x.current=w;let v="";const B=[];try{await ph({messages:y.map(b=>({role:b.role,content:b.content})),upstream:{cellId:`scope:${e}`,sql:n},signal:w.signal},b=>{B.push(b),I([...B]),b.kind==="text"&&(v+=o?xV(b.text):b.text,R(v)),b.kind==="error"&&N(b.message)}),u([...y,{role:"assistant",content:v,events:B}])}catch(b){N(b instanceof Error?b.message:String(b))}finally{A(!1),R(""),I([]),x.current=null}};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,background:d.cellBg},children:[s.jsx("div",{style:{padding:12,borderBottom:`1px solid ${d.headerBorder}`},children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontSize:13,fontWeight:700},children:e}),s.jsxs("div",{style:{fontSize:11,color:d.textSecondary,marginTop:2},children:[t," · Provider from Settings"]})]}),l&&s.jsx("button",{type:"button",onClick:l,title:a?"Collapse chat":"Expand chat",style:rp(d),children:a?s.jsx(xL,{size:14}):s.jsx(DR,{size:14})}),c&&s.jsx("button",{type:"button",onClick:c,title:"Close chat",style:rp(d),children:s.jsx(Md,{size:14})})]})}),s.jsxs("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:12,display:"flex",flexDirection:"column",gap:10},children:[E.length===0&&!h?s.jsx("div",{style:{fontSize:12,color:d.textSecondary,lineHeight:1.45},children:"Ask about metric definitions, filters, tile results, or where to find certified analysis."}):null,E.map((C,y)=>s.jsx(np,{message:C,t:d,themeMode:r,hideSqlByDefault:o,addToAppTarget:i},y)),h&&s.jsx(np,{message:{role:"assistant",content:S||"Thinking...",events:m},t:d,live:!0,themeMode:r,hideSqlByDefault:o,addToAppTarget:i})]}),O&&s.jsx("div",{style:{margin:"0 12px 8px",color:"#ff7b72",fontSize:12},children:O}),s.jsxs("div",{style:{padding:12,borderTop:`1px solid ${d.headerBorder}`,display:"flex",gap:8,alignItems:"flex-end"},children:[s.jsx("textarea",{value:T,onChange:C=>p(C.target.value),rows:2,placeholder:"Ask this context...",onKeyDown:C=>{C.key==="Enter"&&(C.metaKey||C.ctrlKey)&&(C.preventDefault(),g())},style:{flex:1,resize:"vertical",minHeight:42,...yV(d)}}),h?s.jsx("button",{type:"button",onClick:()=>{var C;return(C=x.current)==null?void 0:C.abort()},style:op(d,!1),children:"Stop"}):s.jsx("button",{type:"button",onClick:()=>void g(),disabled:!T.trim(),style:op(d,!0),children:"Ask"})]})]})}function np({message:e,t,live:n,themeMode:r,hideSqlByDefault:o,addToAppTarget:i}){const a=e.role==="user",l=a?null:$d(e.events??[]);return l?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[s.jsx("div",{style:{fontSize:10,color:n?t.accent:t.textMuted,textTransform:"uppercase",fontWeight:700},children:"DQL Agent"}),s.jsx(Vd,{answer:l,themeMode:r,showSql:!o,compact:!0,addToAppTarget:i})]}):s.jsxs("div",{style:{border:`1px solid ${a?`${t.accent}55`:t.headerBorder}`,borderRadius:8,padding:10,background:a?`${t.accent}12`:t.appBg,whiteSpace:l?"normal":"pre-wrap",fontSize:12,lineHeight:1.5},children:[s.jsx("div",{style:{fontSize:10,color:n?t.accent:t.textMuted,textTransform:"uppercase",fontWeight:700,marginBottom:4},children:a?"You":"DQL Agent"}),e.content]})}function xV(e){return e.replace(/Proposed SQL:\s*```sql[\s\S]*?```/gi,"Proposed SQL hidden in dashboard mode. Send to analyst review to inspect.")}function yV(e){return{border:`1px solid ${e.headerBorder}`,borderRadius:6,background:e.appBg,color:e.textPrimary,fontSize:12,padding:"7px 8px",fontFamily:e.font}}function rp(e){return{width:28,height:28,border:`1px solid ${e.headerBorder}`,borderRadius:6,background:e.appBg,color:e.textPrimary,cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0}}function op(e,t){return{border:`1px solid ${t?e.accent:e.headerBorder}`,borderRadius:6,background:t?`${e.accent}22`:e.appBg,color:t?e.accent:e.textPrimary,padding:"8px 12px",cursor:"pointer",fontSize:12}}const sp="clamp(320px, calc(100vh - 220px), 760px)";function CV({appId:e,dashboard:t,editable:n=!1,onDashboardChanged:r}){var Z;const{state:o}=fe(),[i,a]=f.useState(null),[l,c]=f.useState(!1),[d,E]=f.useState(null),[u,T]=f.useState(!1),[p,h]=f.useState(!1),[A,S]=f.useState([]),[R,m]=f.useState(""),[I,O]=f.useState(!1),[N,x]=f.useState(null),[g,C]=f.useState(!1),[y,w]=f.useState(!1),[v,B]=f.useState(!1),b=f.useRef(null),L=t.layout.cols,D=t.layout.rowHeight,M=f.useMemo(()=>{const Y=new Map;for(const G of(i==null?void 0:i.tiles)??[])Y.set(G.tileId,G);return Y},[i]);f.useEffect(()=>{let Y=!1;return c(!0),E(null),z.runDashboard(e,t.id).then(G=>{Y||(a(G),G||E("Dashboard run failed."))}).catch(G=>{Y||E(G instanceof Error?G.message:String(G))}).finally(()=>{Y||c(!1)}),()=>{Y=!0}},[e,t.id,t.layout.items.length,(Z=o.activePersona)==null?void 0:Z.userId]),f.useEffect(()=>{const Y=G=>{const J=G.detail;(J==null?void 0:J.appId)!==e||J.dashboardId!==t.id||(z.getDashboard(e,t.id).then(te=>{te!=null&&te.dashboard&&(r==null||r(te.dashboard))}),z.runDashboard(e,t.id).then(te=>{te&&a(te)}))};return window.addEventListener("dql-app-dashboard-updated",Y),()=>window.removeEventListener("dql-app-dashboard-updated",Y)},[e,t.id,r]);const U=f.useMemo(()=>{const Y=t.layout.items.map(G=>{var re;const J=M.get(G.i),te=G.block?"blockId"in G.block?G.block.blockId:G.block.ref:G.aiPin?`aiPin:${G.aiPin.id}`:"text";return{title:G.title,blockRef:te,viz:G.viz.type,certificationStatus:J==null?void 0:J.certificationStatus,status:J==null?void 0:J.status,rowCount:(re=J==null?void 0:J.result)==null?void 0:re.rowCount}});return JSON.stringify({scope:"dashboard",appId:e,dashboardId:t.id,title:t.metadata.title,description:t.metadata.description,domain:t.metadata.domain,filters:t.filters,tiles:Y},null,2)},[e,t,M]),P=f.useCallback(async Y=>{C(!0);const G={...t,layout:{...t.layout,items:Y}},J=await z.patchDashboardLayout(e,t.id,G.layout);C(!1),J.ok?r==null||r(J.dashboard):E(J.error)},[e,t,r]),_=f.useCallback(async()=>{h(!0);const Y=await z.getAppEditorCatalog(e);S((Y==null?void 0:Y.blocks)??[])},[e]),F=f.useCallback(async Y=>{const G={i:fc(t,Y.name),...Tc(t),block:{blockId:Y.name},viz:{type:FV(Y.chartType)},title:Y.name};await P([...t.layout.items,G]),h(!1)},[t,P]),k=f.useCallback(async()=>{var J;const Y=window.prompt("Text for this App tile");if(!(Y!=null&&Y.trim()))return;const G=((J=Y.trim().split(/\r?\n/)[0])==null?void 0:J.slice(0,60))||"Summary";await P([...t.layout.items,{i:fc(t,"text"),...Tc(t),text:{markdown:Y.trim()},viz:{type:"text"},title:G}])},[t,P]),H=f.useCallback(async()=>{const Y=window.prompt("Section heading");Y!=null&&Y.trim()&&await P([...t.layout.items,{i:fc(t,"section"),...Tc(t,{w:12,h:1}),text:{markdown:Y.trim()},viz:{type:"heading"},title:Y.trim()}])},[t,P]),Q=f.useCallback(async(Y,G)=>{const J=G===null?t.layout.items.filter(te=>te.i!==Y):t.layout.items.map(te=>te.i===Y?{...te,...G}:te);await P(Ep(J,L))},[L,t.layout.items,P]),q=f.useCallback(async(Y,G)=>{const J=b.current,te=t.layout.items.find(Fe=>Fe.i===Y);if(!J||!te)return;const re=J.getBoundingClientRect(),oe=12,le=(re.width-oe*(L-1))/L+oe,Te=D+oe,de=Math.round((G.clientX-re.left)/le),ne=Math.round((G.clientY-re.top)/Te),Re={...te,x:RE(de,0,Math.max(0,L-te.w)),y:Math.max(0,ne)},Oe=BV(t.layout.items,Re,L);await P(Ep(Oe,L))},[L,t.layout.items,D,P]),$=f.useCallback(async()=>{if(O(Y=>!Y),!N){const Y=await z.fetchScopedLineage({domain:t.metadata.domain,appId:e,dashboardId:t.id});x(Y)}},[e,t.id,t.metadata.domain,N]);return s.jsxs("div",{style:{display:"flex",gap:16,minHeight:0,alignItems:"flex-start"},children:[s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,marginBottom:16},children:[s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("h2",{style:{margin:0,fontSize:18},children:t.metadata.title}),t.metadata.description?s.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:4},children:t.metadata.description}):null]}),n&&t.layout.items.length>0&&s.jsx(ip,{open:y,onToggle:()=>w(Y=>!Y),onCertifiedBlock:()=>{w(!1),_()},onText:()=>{w(!1),k()},onHeading:()=>{w(!1),H()},onAi:()=>{w(!1),T(!0)}}),s.jsx("button",{type:"button",onClick:()=>{w(!1),T(Y=>!Y)},style:ji(u),children:u?"Hide AI":"Ask AI"}),s.jsx("button",{type:"button",onClick:()=>void $(),style:ji(I),children:"Lineage"})]}),n&&s.jsxs("div",{style:{marginBottom:12,display:"flex",gap:8,alignItems:"center",fontSize:12,color:"var(--color-text-secondary, rgba(0,0,0,0.64))"},children:[s.jsx("span",{children:g?"Saving layout...":"Edit layout"}),s.jsxs("span",{children:[t.layout.items.length," tile",t.layout.items.length===1?"":"s"]})]}),t.layout.items.length===0?s.jsxs("div",{style:{border:"1px dashed var(--border-color, rgba(0,0,0,0.15))",borderRadius:8,padding:36,textAlign:"center",fontSize:13,minHeight:260,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:[s.jsx("div",{style:{fontSize:16,fontWeight:700,marginBottom:6},children:"Build this App tab"}),s.jsx("div",{style:{maxWidth:520,opacity:.68,lineHeight:1.45},children:"Add certified domain blocks, narrative text, or use the scoped AI drawer and pin an answer into this layout."}),s.jsx("div",{style:{marginTop:18,display:"flex",gap:8,flexWrap:"wrap",justifyContent:"center"},children:s.jsx(ip,{open:y,onToggle:()=>w(Y=>!Y),buttonLabel:"+ Add",buttonStyle:wV,onCertifiedBlock:()=>{w(!1),_()},onText:()=>{w(!1),k()},onHeading:()=>{w(!1),H()},onAi:()=>{w(!1),T(!0)}})})]}):s.jsx("div",{ref:b,style:{display:"grid",gridTemplateColumns:`repeat(${L}, 1fr)`,gridAutoRows:`${D}px`,gap:12},children:t.layout.items.map(Y=>s.jsx(LV,{item:Y,tile:M.get(Y.i),loading:l,error:d,themeMode:o.themeMode,editable:n,cols:L,onMove:G=>void q(Y.i,G),onPatch:G=>void Q(Y.i,G)},Y.i))})]}),I&&s.jsx("aside",{style:{width:340,minWidth:300,maxWidth:"34vw",border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:8,overflow:"auto",alignSelf:"flex-start",height:sp,position:"sticky",top:12,padding:12},children:s.jsx(PV,{lineage:N})}),u&&s.jsx("aside",{style:{width:v?"min(720px, 52vw)":390,minWidth:v?520:340,maxWidth:v?"58vw":"40vw",border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:8,overflow:"hidden",alignSelf:"flex-start",height:sp,position:"sticky",top:12},children:s.jsx(gV,{title:"Dashboard AI",scopeHint:"Scoped to this App dashboard first",upstreamContext:U,themeMode:o.themeMode,hideSqlByDefault:!0,addToAppTarget:{appId:e,dashboardId:t.id},expanded:v,onToggleExpanded:()=>B(Y=>!Y),onClose:()=>{T(!1),B(!1)}})}),p&&s.jsx(vV,{blocks:A,search:R,onSearch:m,onClose:()=>h(!1),onAdd:Y=>void F(Y)})]})}function LV({item:e,tile:t,loading:n,error:r,themeMode:o,editable:i,cols:a,onMove:l,onPatch:c}){const d=f.useRef(null),[E,u]=f.useState(null),T=e.block?"blockId"in e.block?`block:${e.block.blockId}`:e.block.ref??"(unknown)":e.aiPin?`aiPin:${e.aiPin.id}`:"text",p=h=>{const A=d.current;if(!A)return;h.preventDefault(),h.stopPropagation();const S=A.getBoundingClientRect(),R={x:h.clientX-S.left,y:h.clientY-S.top},m={x:h.clientX,y:h.clientY},I=N=>{u({x:N.clientX-m.x,y:N.clientY-m.y})},O=N=>{window.removeEventListener("pointermove",I),window.removeEventListener("pointerup",O),u(null),l({clientX:N.clientX-R.x,clientY:N.clientY-R.y})};window.addEventListener("pointermove",I),window.addEventListener("pointerup",O,{once:!0})};return s.jsxs("div",{ref:d,style:{gridColumn:`${e.x+1} / span ${e.w}`,gridRow:`${e.y+1} / span ${e.h}`,transform:E?`translate(${E.x}px, ${E.y}px)`:void 0,opacity:E?.72:1,zIndex:E?20:void 0,position:"relative",background:"var(--surface, rgba(0,0,0,0.02))",border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:8,padding:12,display:"flex",flexDirection:"column",gap:6,minHeight:0,overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("div",{style:{fontSize:13,fontWeight:600},children:e.title??T}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[s.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:999,background:"var(--surface-hover, rgba(0,0,0,0.06))",opacity:.85},children:e.viz.type}),i&&s.jsx(bV,{item:e,cols:a,onDragStart:p,onPatch:c})]})]}),s.jsx("div",{style:{fontSize:11,opacity:.6,fontFamily:"monospace"},children:T}),s.jsx("div",{style:{flex:1,minHeight:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,opacity:(t==null?void 0:t.status)==="ok"?1:.7,fontStyle:(t==null?void 0:t.status)==="ok"?"normal":"italic"},children:s.jsx(_V,{tile:t,loading:n,error:r,themeMode:o})})]})}function _V({tile:e,loading:t,error:n,themeMode:r}){var i,a,l,c,d;return t&&!e?s.jsx("span",{children:"Loading data..."}):(e==null?void 0:e.tileType)==="text"?s.jsx(DV,{markdown:((i=e.text)==null?void 0:i.markdown)??"",variant:((a=e.viz)==null?void 0:a.type)==="heading"?"heading":"text"}):(e==null?void 0:e.tileType)==="aiPin"&&e.aiPin&&!e.result?s.jsx(MV,{pin:e.aiPin}):n&&!e?s.jsx("span",{children:n}):e?e.status==="unauthorized"?s.jsx("span",{children:"Not authorized."}):e.status==="unresolved"?s.jsx("span",{children:e.error??"Block reference unresolved."}):e.status==="error"?s.jsx("span",{children:e.error??"Tile failed."}):e.result?String(((l=e.chartConfig)==null?void 0:l.chart)??((c=e.viz)==null?void 0:c.type)??"").toLowerCase()==="table"||((d=e.viz)==null?void 0:d.type)==="table"?s.jsx("div",{style:{width:"100%",alignSelf:"stretch"},children:s.jsx(Kn,{result:e.result,themeMode:r})}):s.jsx("div",{style:{width:"100%",alignSelf:"stretch"},children:s.jsx(Yd,{result:e.result,themeMode:r,chartConfig:e.chartConfig})}):s.jsx("span",{children:"No result."}):s.jsx("span",{children:"No run result."})}function bV({item:e,cols:t,onDragStart:n,onPatch:r}){const o=a=>{const l=Math.max(1,Math.floor(t/a));r({w:l,x:RE(e.x,0,Math.max(0,t-l))})},i=a=>r({h:a});return s.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center",flexWrap:"wrap",justifyContent:"flex-end"},children:[s.jsx("button",{type:"button",title:"Drag tile",onPointerDown:n,style:lp,children:s.jsx(IL,{size:13,strokeWidth:2})}),s.jsxs("div",{style:cp,"aria-label":"Tile width",children:[s.jsx("button",{type:"button",title:"One tile per row",onClick:()=>o(1),style:dr(e.w===t),children:"1"}),s.jsx("button",{type:"button",title:"Two tiles per row",onClick:()=>o(2),style:dr(e.w===Math.floor(t/2)),children:"2"}),s.jsx("button",{type:"button",title:"Three tiles per row",onClick:()=>o(3),style:dr(e.w===Math.floor(t/3)),children:"3"})]}),s.jsxs("div",{style:cp,"aria-label":"Tile height",children:[s.jsx("button",{type:"button",title:"Compact height",onClick:()=>i(2),style:dr(e.h===2),children:"S"}),s.jsx("button",{type:"button",title:"Standard height",onClick:()=>i(3),style:dr(e.h===3),children:"M"}),s.jsx("button",{type:"button",title:"Large height",onClick:()=>i(5),style:dr(e.h>=5),children:"L"})]}),s.jsx("button",{type:"button",title:"Remove tile",onClick:()=>r(null),style:lp,children:s.jsx(KL,{size:13,strokeWidth:2})})]})}function ip({open:e,onToggle:t,onCertifiedBlock:n,onText:r,onHeading:o,onAi:i,buttonLabel:a="+ Add",buttonStyle:l}){return s.jsxs("div",{style:{position:"relative",display:"inline-flex"},children:[s.jsx("button",{type:"button",onClick:t,style:l??ji(e),children:a}),e&&s.jsxs("div",{style:{position:"absolute",top:"calc(100% + 6px)",right:0,zIndex:30,width:260,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:8,background:"var(--color-bg, #fff)",boxShadow:"0 14px 38px rgba(0,0,0,0.16)",padding:6,display:"grid",gap:4,textAlign:"left"},children:[s.jsx(Vs,{title:"Certified block",description:"Chart, table, or KPI from this App domain",onClick:n}),s.jsx(Vs,{title:"Text / summary",description:"Narrative, notes, caveats, or CXO context",onClick:r}),s.jsx(Vs,{title:"Section heading",description:"Separate an App page into readable groups",onClick:o}),s.jsx(Vs,{title:"AI answer",description:"Open scoped AI, then pin the answer to this App",onClick:i})]})]})}function Vs({title:e,description:t,onClick:n}){return s.jsxs("button",{type:"button",onClick:n,style:UV,children:[s.jsx("span",{style:{fontSize:12,fontWeight:700},children:e}),s.jsx("span",{style:{fontSize:11,opacity:.66},children:t})]})}function DV({markdown:e,variant:t="text"}){return s.jsx("div",{style:{width:"100%",alignSelf:"stretch",overflow:"auto",whiteSpace:"pre-wrap",lineHeight:1.45,fontStyle:"normal",opacity:1,fontSize:t==="heading"?18:void 0,fontWeight:t==="heading"?800:void 0,display:t==="heading"?"flex":void 0,alignItems:t==="heading"?"center":void 0},children:e})}function MV({pin:e}){const[t,n]=f.useState(null),r=async()=>{n("Refreshing...");const i=await z.refreshAiPin(e.appId,e.id);n(i.ok?"Refreshed.":i.error??"Refresh failed."),window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:{appId:e.appId,dashboardId:e.dashboardId}}))},o=async()=>{n("Creating draft...");const i=await z.promoteAiPin(e.appId,e.id);n(i.ok?`Draft created: ${i.blockPath}`:i.error??"Promotion failed."),window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:{appId:e.appId,dashboardId:e.dashboardId}}))};return s.jsxs("div",{style:{width:"100%",alignSelf:"stretch",overflow:"auto",fontStyle:"normal",lineHeight:1.45},children:[s.jsx("div",{style:{fontSize:11,fontWeight:700,color:e.certification==="certified"?"#3fb950":"#f0883e",marginBottom:6},children:e.certification==="certified"?"Certified":"AI generated / needs review"}),s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e.answer}),s.jsxs("div",{style:{display:"flex",gap:6,marginTop:8,flexWrap:"wrap"},children:[e.sql&&s.jsx("button",{type:"button",onClick:()=>void r(),style:dp,children:"Refresh"}),e.sql&&e.reviewStatus==="needs_review"&&s.jsx("button",{type:"button",onClick:()=>void o(),style:dp,children:"Promote"}),e.refreshCadence==="daily"&&s.jsx("span",{style:{fontSize:11,opacity:.62},children:"daily"})]}),t&&s.jsx("div",{style:{marginTop:6,fontSize:11,opacity:.72},children:t}),e.lastRefreshError&&s.jsx("div",{style:{marginTop:8,color:"#f85149"},children:e.lastRefreshError})]})}function vV({blocks:e,search:t,onSearch:n,onClose:r,onAdd:o}){const i=e.filter(a=>{const l=t.trim().toLowerCase();return l?[a.name,a.description,a.domain,...a.tags??[]].join(" ").toLowerCase().includes(l):!0});return s.jsx("div",{style:{position:"fixed",inset:0,zIndex:90,background:"rgba(0,0,0,0.36)",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:s.jsxs("div",{style:{width:"min(860px, 94vw)",maxHeight:"86vh",display:"flex",flexDirection:"column",background:"var(--color-bg, #fff)",color:"inherit",borderRadius:8,overflow:"hidden",boxShadow:"0 18px 60px rgba(0,0,0,0.35)"},children:[s.jsxs("div",{style:{padding:14,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.1))",display:"flex",gap:10,alignItems:"center"},children:[s.jsx("div",{style:{fontSize:15,fontWeight:700,flex:1},children:"Add Certified Block"}),s.jsx("button",{type:"button",onClick:r,style:ji(!1),children:"Close"})]}),s.jsx("div",{style:{padding:14,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.08))"},children:s.jsx("input",{value:t,onChange:a=>n(a.target.value),placeholder:"Search domain blocks...",style:{width:"100%",boxSizing:"border-box",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,padding:"8px 10px",background:"var(--surface, transparent)",color:"inherit"}})}),s.jsx("div",{style:{overflow:"auto",padding:12,display:"grid",gap:8},children:i.length===0?s.jsx("div",{style:{padding:18,fontSize:12,opacity:.66},children:"No certified blocks match this App scope."}):i.map(a=>s.jsxs("button",{type:"button",onClick:()=>o(a),style:{textAlign:"left",border:"1px solid var(--border-color, rgba(0,0,0,0.1))",borderRadius:7,background:"transparent",color:"inherit",padding:10,cursor:"pointer"},children:[s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:4},children:[s.jsx("span",{style:{fontSize:13,fontWeight:700},children:a.name}),s.jsx("span",{style:{fontSize:10,padding:"2px 6px",borderRadius:999,background:"rgba(63,185,80,0.14)",color:"#2ea043"},children:a.status}),s.jsx("span",{style:{fontSize:10,opacity:.68},children:a.domain}),s.jsx("span",{style:{fontSize:10,opacity:.68},children:a.chartType??"table"})]}),s.jsx("div",{style:{fontSize:12,opacity:.72},children:a.description||a.path})]},a.id))})]})})}function PV({lineage:e}){var o,i;const t=((o=e==null?void 0:e.graph)==null?void 0:o.nodes)??[],n=((i=e==null?void 0:e.graph)==null?void 0:i.edges)??[],r=(e==null?void 0:e.breadcrumbs)??[];return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:12,fontWeight:800,textTransform:"uppercase",opacity:.62,marginBottom:6},children:"App Lineage"}),s.jsx("div",{style:{fontSize:12,opacity:.72},children:"Domain > App > Dashboard tab > Tile > Block > dbt/source"})]}),r.length>0&&s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:r.map((a,l)=>s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"64px 1fr",gap:8,fontSize:12},children:[s.jsx("span",{style:{fontFamily:"monospace",opacity:.6},children:a.type}),s.jsx("span",{children:a.name})]},`${a.id}-${l}`))}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[s.jsx(ap,{label:"Nodes",value:t.length}),s.jsx(ap,{label:"Edges",value:n.length})]}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t.slice(0,18).map(a=>s.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,padding:8},children:[s.jsx("div",{style:{fontSize:12,fontWeight:700},children:a.name}),s.jsxs("div",{style:{fontSize:11,opacity:.62,fontFamily:"monospace"},children:[a.type," · ",a.id]})]},a.id))})]})}function ap({label:e,value:t}){return s.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,padding:8},children:[s.jsx("div",{style:{fontSize:11,opacity:.62},children:e}),s.jsx("div",{style:{fontSize:18,fontWeight:800},children:t})]})}function ji(e){return{border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,background:e?"var(--surface-hover, rgba(0,0,0,0.06))":"var(--surface, rgba(0,0,0,0.02))",color:"inherit",padding:"7px 10px",cursor:"pointer",fontSize:12}}const wV={border:"1px solid var(--accent, #4f46e5)",borderRadius:6,background:"var(--accent, #4f46e5)",color:"#fff",padding:"7px 11px",cursor:"pointer",fontSize:12,fontWeight:700},UV={border:"none",borderRadius:6,background:"transparent",color:"inherit",padding:"9px 10px",cursor:"pointer",textAlign:"left",display:"grid",gap:2},lp={width:24,height:24,borderRadius:5,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",background:"var(--surface, rgba(255,255,255,0.72))",color:"inherit",cursor:"grab",padding:0,display:"inline-flex",alignItems:"center",justifyContent:"center"},cp={display:"inline-flex",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:5,overflow:"hidden",background:"var(--surface, rgba(255,255,255,0.66))"};function dr(e){return{width:24,height:24,border:"none",borderRight:"1px solid var(--border-color, rgba(0,0,0,0.08))",background:e?"var(--accent, #4f46e5)":"transparent",color:e?"#fff":"inherit",padding:0,cursor:"pointer",fontSize:11,fontWeight:e?800:600}}const dp={border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:4,background:"var(--surface, rgba(0,0,0,0.02))",color:"inherit",padding:"3px 7px",cursor:"pointer",fontSize:11};function Tc(e,t={w:6,h:3}){return{x:0,y:e.layout.items.reduce((r,o)=>Math.max(r,o.y+o.h),0),w:t.w,h:t.h}}function fc(e,t){const n=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tile",r=new Set(e.layout.items.map(o=>o.i));if(!r.has(n))return n;for(let o=2;o<1e3;o++){const i=`${n}-${o}`;if(!r.has(i))return i}return`${n}-${Date.now()}`}function Ep(e,t){let n=0,r=0,o=0;return e.map(i=>{const a=RE(Math.round(i.w||1),1,t),l=Math.max(1,Math.round(i.h||1));n>0&&n+a>t&&(r+=o,n=0,o=0);const c={...i,x:n,y:r,w:a,h:l};return n+=a,o=Math.max(o,l),n>=t&&(r+=o,n=0,o=0),c})}function BV(e,t,n){const r=e.filter(a=>a.i!==t.i).sort((a,l)=>Xs(a,n)-Xs(l,n)),o=Xs(t,n),i=r.findIndex(a=>Xs(a,n)>o);return i===-1?[...r,t]:[...r.slice(0,i),t,...r.slice(i)]}function Xs(e,t){return e.y*t+e.x}function FV(e){const t=(e??"table").toLowerCase().replace(/-/g,"_");return t==="single_value"||t==="kpi"||t==="line"||t==="bar"||t==="area"||t==="pie"||t==="pivot"||t==="map"||t==="funnel"?t:"table"}function RE(e,t,n){return Math.min(n,Math.max(t,e))}function kV(){const{state:e,dispatch:t}=fe(),[n,r]=f.useState(null),[o,i]=f.useState(null),[a,l]=f.useState(!1),[c,d]=f.useState(!1),[E,u]=f.useState(""),[T,p]=f.useState(""),[h,A]=f.useState(""),[S,R]=f.useState(""),[m,I]=f.useState(""),[O,N]=f.useState(""),[x,g]=f.useState("all"),[C,y]=f.useState(!1),w=async(D,M)=>{t({type:"SET_APPS_LOADING",loading:!0});const U=await z.listApps();t({type:"SET_APPS",apps:U}),t({type:"SET_APPS_LOADING",loading:!1}),D?t({type:"OPEN_APP",appId:D,dashboardId:M??void 0}):U.length>0&&!e.activeAppId&&t({type:"OPEN_APP",appId:U[0].id})};f.useEffect(()=>{let D=!1;return t({type:"SET_APPS_LOADING",loading:!0}),z.listApps().then(M=>{D||(t({type:"SET_APPS",apps:M}),t({type:"SET_APPS_LOADING",loading:!1}),M.length>0&&!e.activeAppId&&t({type:"OPEN_APP",appId:M[0].id}))}),()=>{D=!0}},[]),f.useEffect(()=>{if(!e.activeAppId){r(null),i(null);return}let D=!1;return l(!0),z.getApp(e.activeAppId).then(M=>{D||r(M)}),e.activeDashboardId?z.getDashboard(e.activeAppId,e.activeDashboardId).then(M=>{D||(i(M),l(!1))}):(i(null),l(!1)),()=>{D=!0}},[e.activeAppId,e.activeDashboardId]),f.useEffect(()=>{z.getPersona().then(D=>t({type:"SET_ACTIVE_PERSONA",persona:D}))},[]);const v=f.useMemo(()=>({domains:zs(e.apps.map(D=>D.domain).filter(Boolean)),tags:zs(e.apps.flatMap(D=>D.tags??[]).filter(D=>!D.startsWith("audience:"))),owners:zs(e.apps.flatMap(D=>D.owners??[])),audiences:zs(e.apps.map(D=>D.audience).filter(Boolean))}),[e.apps]),B=f.useMemo(()=>{const D=E.trim().toLowerCase();return e.apps.filter(M=>!(D&&![M.name,M.description??"",M.domain,...M.tags??[],...M.owners??[]].join(" ").toLowerCase().includes(D)||T&&M.domain!==T||h&&!(M.tags??[]).includes(h)||S&&!(M.owners??[]).includes(S)||m&&M.audience!==m||O&&M.status!==O||x!=="all"&&(M.storage??"shared")!==x))},[e.apps,E,T,h,S,m,O,x]),b=f.useMemo(()=>e.apps.find(D=>D.id===e.activeAppId)??null,[e.apps,e.activeAppId]),L=async()=>{if(!e.activeAppId)return;const D=window.prompt("New App tab name");if(!(D!=null&&D.trim()))return;const M=await z.createAppDashboard(e.activeAppId,{title:D.trim()});M.ok?(y(!0),n&&i({app:n.app,dashboard:M.dashboard}),t({type:"OPEN_APP",appId:e.activeAppId,dashboardId:M.dashboard.id}),await w(e.activeAppId,M.dashboard.id),t({type:"OPEN_DASHBOARD",dashboardId:M.dashboard.id})):window.alert(M.error)};return e.appsLoading&&e.apps.length===0?s.jsx(no,{message:"Loading apps...",onCreate:()=>d(!0)}):e.apps.length===0?s.jsxs(s.Fragment,{children:[s.jsx(no,{message:"Create your first governed App.",hint:"Package certified blocks into a business dashboard with local persona preview.",onCreate:()=>d(!0)}),c&&s.jsx(up,{onClose:()=>d(!1),onCreated:(D,M)=>void w(D,M)})]}):s.jsxs("div",{style:{display:"flex",height:"100%",minHeight:0},children:[s.jsxs("aside",{style:{width:292,borderRight:"1px solid var(--border-color, rgba(0,0,0,0.08))",display:"flex",flexDirection:"column",minHeight:0},children:[s.jsxs("div",{style:{padding:12,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.06))"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[s.jsx("div",{style:{fontSize:11,fontWeight:700,opacity:.65,textTransform:"uppercase",letterSpacing:.5,flex:1},children:"Apps Command Center"}),s.jsx("button",{onClick:()=>d(!0),style:Gi,children:"Create App"})]}),s.jsxs("div",{style:{display:"grid",gap:6},children:[s.jsx("input",{value:E,onChange:D=>u(D.target.value),placeholder:"Search apps, tags, owners...",style:nt}),s.jsxs("select",{value:T,onChange:D=>p(D.target.value),style:nt,children:[s.jsx("option",{value:"",children:"All domains"}),v.domains.map(D=>s.jsx("option",{value:D,children:D},D))]}),s.jsxs("select",{value:h,onChange:D=>A(D.target.value),style:nt,children:[s.jsx("option",{value:"",children:"All tags"}),v.tags.map(D=>s.jsx("option",{value:D,children:D},D))]}),s.jsxs("select",{value:S,onChange:D=>R(D.target.value),style:nt,children:[s.jsx("option",{value:"",children:"All owners"}),v.owners.map(D=>s.jsx("option",{value:D,children:D},D))]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:6},children:[s.jsxs("select",{value:m,onChange:D=>I(D.target.value),style:nt,children:[s.jsx("option",{value:"",children:"Audience"}),v.audiences.map(D=>s.jsx("option",{value:D,children:D},D))]}),s.jsxs("select",{value:O,onChange:D=>N(D.target.value),style:nt,children:[s.jsx("option",{value:"",children:"Status"}),s.jsx("option",{value:"ready",children:"ready"}),s.jsx("option",{value:"empty",children:"empty"})]})]}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:4},children:["all","mine","shared","template"].map(D=>s.jsx("button",{onClick:()=>g(D),style:JV(x===D),children:D==="all"?"All":D==="template"?"Templates":D==="mine"?"Mine":"Shared"},D))})]})]}),s.jsx("div",{style:{overflowY:"auto",minHeight:0,padding:"8px 0"},children:B.length===0?s.jsx("div",{style:{padding:16,fontSize:12,opacity:.65},children:"No Apps match the current filters."}):B.map(D=>s.jsx(jV,{app:D,active:D.id===e.activeAppId,onClick:()=>t({type:"OPEN_APP",appId:D.id})},D.id))})]}),s.jsxs("main",{style:{flex:1,display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden"},children:[s.jsxs("header",{style:{display:"flex",alignItems:"center",gap:12,padding:"12px 16px",borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.08))"},children:[s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontWeight:600,fontSize:16},children:(b==null?void 0:b.name)??"-"}),s.jsxs("div",{style:{fontSize:12,opacity:.7},children:[b!=null&&b.domain?`domain: ${b.domain}`:"",b!=null&&b.audience?` · audience: ${b.audience}`:"",b!=null&&b.description?` · ${b.description}`:""]})]}),s.jsx(NV,{app:(n==null?void 0:n.app)??null}),s.jsxs("div",{style:{display:"flex",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,overflow:"hidden"},children:[s.jsx("button",{onClick:()=>y(!1),style:fp(!C),children:"View"}),s.jsx("button",{onClick:()=>y(!0),style:fp(C),children:"Edit"})]}),s.jsx("button",{onClick:()=>void L(),disabled:!e.activeAppId,style:td,children:"+ Add tab"})]}),n&&n.dashboards.length>0&&s.jsx("nav",{style:{display:"flex",gap:4,padding:"8px 16px",borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.06))",overflowX:"auto"},children:n.dashboards.map(D=>s.jsxs("button",{onClick:()=>t({type:"OPEN_DASHBOARD",dashboardId:D.id}),style:qV(D.id===e.activeDashboardId),children:[D.title,D.itemCount>0?s.jsxs("span",{style:{opacity:.6,marginLeft:6},children:["· ",D.itemCount]}):null]},D.id))}),s.jsx("div",{style:{flex:1,overflow:"auto",padding:16,minHeight:0},children:a?s.jsx(no,{message:"Loading dashboard..."}):o&&e.activeAppId?s.jsx(CV,{appId:e.activeAppId,dashboard:o.dashboard,editable:C||o.dashboard.layout.items.length===0,onDashboardChanged:D=>{i(M=>M&&{...M,dashboard:D}),w(e.activeAppId??void 0,D.id)}}):n&&n.dashboards.length===0?s.jsx(no,{message:"This App has no dashboards.",hint:"Create a dashboard from selected certified blocks.",onCreate:()=>d(!0)}):s.jsx(no,{message:"Select a dashboard."})})]}),c&&s.jsx(up,{onClose:()=>d(!1),onCreated:(D,M)=>void w(D,M)})]})}function up({onClose:e,onCreated:t}){const[n,r]=f.useState(0),[o,i]=f.useState(""),[a,l]=f.useState(""),[c,d]=f.useState(""),[E,u]=f.useState("executive"),[T,p]=f.useState(""),[h,A]=f.useState(`${window.DQL_USER??"owner"}@local`),[S,R]=f.useState(!0),[m,I]=f.useState([]),[O,N]=f.useState(new Set),[x,g]=f.useState(!1),[C,y]=f.useState(null),w=f.useMemo(()=>T.split(",").map(b=>b.trim()).filter(Boolean),[T]),v=n===0?!!(o.trim()&&a.trim()):!0;f.useEffect(()=>{n===2&&(g(!0),z.recommendAppBlocks({domain:a,tags:w,purpose:c,audience:E,certifiedOnly:S}).then(b=>{I(b),N(new Set(b.slice(0,6).map(L=>L.id)))}).finally(()=>g(!1)))},[n,a,w.join(","),c,E,S]);const B=async()=>{g(!0),y(null);try{const b=await z.createApp({name:o,domain:a,purpose:c,audience:E,tags:w,owners:[h],selectedBlockIds:Array.from(O)});t(b.app.id,b.dashboardId),e()}catch(b){y(b instanceof Error?b.message:String(b))}finally{g(!1)}};return s.jsx("div",{style:XV,children:s.jsxs("div",{style:zV,children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.08))",padding:16},children:[s.jsxs("div",{style:{flex:1},children:[s.jsx("div",{style:{fontSize:18,fontWeight:700},children:"Create App"}),s.jsx("div",{style:{fontSize:12,opacity:.65},children:"Package certified blocks into a governed domain App."})]}),s.jsx("button",{onClick:e,style:td,children:"Close"})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"190px 1fr",minHeight:480},children:[s.jsx("aside",{style:{borderRight:"1px solid var(--border-color, rgba(0,0,0,0.08))",padding:12},children:["Business Context","Governance","Recommended Blocks","Starter Dashboard","Review & Create"].map((b,L)=>s.jsxs("button",{onClick:()=>r(L),style:KV(L===n),children:[s.jsx("span",{style:{fontWeight:700},children:L+1}),s.jsx("span",{children:b})]},b))}),s.jsxs("section",{style:{padding:16,overflow:"auto"},children:[n===0&&s.jsxs("div",{style:VV,children:[s.jsx(Er,{label:"App name",children:s.jsx("input",{value:o,onChange:b=>i(b.target.value),placeholder:"Growth CXO",style:nt})}),s.jsx(Er,{label:"Domain",children:s.jsx("input",{value:a,onChange:b=>l(b.target.value),placeholder:"growth",style:nt})}),s.jsx(Er,{label:"Business purpose",children:s.jsx("textarea",{value:c,onChange:b=>d(b.target.value),placeholder:"Top-line KPIs and operating dashboard for the growth team.",style:{...nt,minHeight:86,resize:"vertical"}})}),s.jsx(Er,{label:"Audience",children:s.jsx("input",{value:E,onChange:b=>u(b.target.value),placeholder:"executive, ops, analyst",style:nt})}),s.jsx(Er,{label:"Tags",children:s.jsx("input",{value:T,onChange:b=>p(b.target.value),placeholder:"cxo, weekly, revenue",style:nt})}),s.jsx(Er,{label:"Owner",children:s.jsx("input",{value:h,onChange:b=>A(b.target.value),placeholder:"owner@local",style:nt})})]}),n===1&&s.jsxs("div",{style:{display:"grid",gap:12},children:[s.jsx(Or,{title:"Single-user OSS governance",text:"The wizard scaffolds owner, analyst, and viewer roles in dql.app.json. Persona switching previews real policy/RLS enforcement without adding login, SSO, or multi-tenant auth."}),s.jsx(HV,{})]}),n===2&&s.jsxs("div",{style:{display:"grid",gap:10},children:[s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12},children:[s.jsx("input",{type:"checkbox",checked:S,onChange:b=>R(b.target.checked)}),"Certified blocks only"]}),x?s.jsx("div",{style:Tp,children:"Finding matching blocks..."}):m.length===0?s.jsx("div",{style:Tp,children:"No matching blocks found. The App can still be created with an empty dashboard."}):m.map(b=>s.jsx(GV,{block:b,selected:O.has(b.id),onToggle:()=>N(L=>WV(L,b.id))},b.id))]}),n===3&&s.jsxs("div",{style:{display:"grid",gap:12},children:[s.jsx(Or,{title:"Generated dashboard",text:"The wizard will create dashboards/overview.dqld and place approved blocks into a responsive grid. Certified shared blocks stay under root blocks/."}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(12, 1fr)",gap:8},children:m.filter(b=>O.has(b.id)).map(b=>s.jsxs("div",{style:{gridColumn:b.chartType==="single_value"||b.chartType==="kpi"?"span 3":"span 6",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,padding:10,minHeight:80},children:[s.jsx("div",{style:{fontSize:12,fontWeight:700},children:b.name}),s.jsxs("div",{style:{fontSize:11,opacity:.65},children:[b.chartType??"table"," · ",b.status]})]},b.id))})]}),n===4&&s.jsxs("div",{style:{display:"grid",gap:12},children:[s.jsx(Or,{title:"Files to create",text:`apps/${$V(o)||"<app-id>"}/dql.app.json, README.md, dashboards/overview.dqld, notebooks/, and drafts/.`}),s.jsx(YV,{name:o,domain:a,audience:E,owner:h,tags:w,selectedCount:O.size}),C&&s.jsx("div",{style:{color:"#f85149",fontSize:12},children:C})]})]})]}),s.jsxs("footer",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:16,borderTop:"1px solid var(--border-color, rgba(0,0,0,0.08))"},children:[s.jsx("button",{onClick:()=>r(b=>Math.max(0,b-1)),disabled:n===0,style:td,children:"Back"}),n<4?s.jsx("button",{onClick:()=>r(b=>Math.min(4,b+1)),disabled:!v,style:Gi,children:"Next"}):s.jsx("button",{onClick:B,disabled:x||!o.trim()||!a.trim(),style:Gi,children:x?"Creating...":"Create App"})]})]})})}function jV({app:e,active:t,onClick:n}){return s.jsxs("button",{onClick:n,style:{display:"block",width:"100%",textAlign:"left",padding:"10px 14px",background:t?"var(--surface-hover, rgba(0,0,0,0.06))":"transparent",border:"none",borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.04))",cursor:"pointer",color:"inherit",fontSize:13},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{style:{fontWeight:t?700:600,flex:1},children:e.name}),s.jsx("span",{style:{fontSize:10,opacity:.65},children:e.status??"ready"})]}),s.jsxs("div",{style:{fontSize:11,opacity:.65,marginTop:3},children:[e.domain," · ",e.dashboards.length," dashboard",e.dashboards.length===1?"":"s"]}),s.jsx("div",{style:{display:"flex",gap:4,flexWrap:"wrap",marginTop:6},children:(e.tags??[]).filter(r=>!r.startsWith("audience:")).slice(0,3).map(r=>s.jsx(ci,{children:r},r))})]})}function GV({block:e,selected:t,onToggle:n}){return s.jsxs("button",{onClick:n,style:{display:"grid",gridTemplateColumns:"24px 1fr auto",gap:10,alignItems:"start",textAlign:"left",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",background:t?"rgba(79,70,229,0.10)":"transparent",borderRadius:6,padding:10,color:"inherit"},children:[s.jsx("input",{type:"checkbox",checked:t,onChange:n,onClick:r=>r.stopPropagation()}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:13,fontWeight:700},children:e.name}),s.jsx("div",{style:{fontSize:11,opacity:.7,marginTop:2},children:e.description||e.path}),s.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",marginTop:6},children:[s.jsx(ci,{children:e.domain}),s.jsx(ci,{children:e.status}),(e.tags??[]).slice(0,4).map(r=>s.jsx(ci,{children:r},r))]})]}),s.jsx("div",{style:{fontSize:10,opacity:.7,maxWidth:150},children:e.reasons.join(", ")})]})}function no({message:e,hint:t,onCreate:n}){return s.jsxs("div",{style:{display:"flex",flex:1,minHeight:260,alignItems:"center",justifyContent:"center",flexDirection:"column",gap:10,opacity:.8,fontSize:14},children:[s.jsx("div",{children:e}),t?s.jsx("div",{style:{fontSize:12,opacity:.7},children:t}):null,n?s.jsx("button",{onClick:n,style:Gi,children:"Create App"}):null]})}function Er({label:e,children:t}){return s.jsxs("label",{style:{display:"grid",gap:5,fontSize:12,fontWeight:600},children:[e,t]})}function Or({title:e,text:t}){return s.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,padding:12},children:[s.jsx("div",{style:{fontSize:13,fontWeight:700,marginBottom:4},children:e}),s.jsx("div",{style:{fontSize:12,opacity:.72,lineHeight:1.45},children:t})]})}function HV(){return s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:10},children:[s.jsx(Or,{title:"Owner",text:"Full App configuration and execution access."}),s.jsx(Or,{title:"Analyst",text:"Can execute dashboards and review generated drafts."}),s.jsx(Or,{title:"Viewer",text:"Read-oriented persona for stakeholder preview."})]})}function YV({name:e,domain:t,audience:n,owner:r,tags:o,selectedCount:i}){const a=[["Name",e||"-"],["Domain",t||"-"],["Audience",n||"-"],["Owner",r||"-"],["Tags",o.join(", ")||"-"],["Selected blocks",String(i)]];return s.jsx("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,overflow:"hidden"},children:a.map(([l,c])=>s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"150px 1fr",borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.06))"},children:[s.jsx("div",{style:{padding:8,fontSize:11,opacity:.65},children:l}),s.jsx("div",{style:{padding:8,fontSize:12},children:c})]},l))})}function ci({children:e}){return s.jsx("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:4,background:"var(--surface-hover, rgba(0,0,0,0.06))",opacity:.82},children:e})}function WV(e,t){const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function zs(e){return Array.from(new Set(e.filter(Boolean))).sort((t,n)=>t.localeCompare(n))}function $V(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}const nt={width:"100%",boxSizing:"border-box",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:5,background:"var(--surface, transparent)",color:"inherit",fontSize:12,padding:"7px 8px"},Gi={border:"1px solid var(--accent, #4f46e5)",background:"var(--accent, #4f46e5)",color:"#fff",borderRadius:5,padding:"6px 10px",fontSize:12,fontWeight:600,cursor:"pointer"},td={border:"1px solid var(--border-color, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",borderRadius:5,padding:"6px 10px",fontSize:12,cursor:"pointer"},Tp={fontSize:12,opacity:.65,padding:12},VV={display:"grid",gap:12,maxWidth:680},XV={position:"fixed",inset:0,zIndex:80,background:"rgba(0,0,0,0.36)",display:"flex",alignItems:"center",justifyContent:"center",padding:24},zV={width:"min(980px, 96vw)",maxHeight:"92vh",overflow:"hidden",display:"flex",flexDirection:"column",background:"var(--color-bg, #fff)",color:"inherit",borderRadius:8,boxShadow:"0 18px 60px rgba(0,0,0,0.35)"};function KV(e){return{width:"100%",display:"flex",gap:8,alignItems:"center",border:"none",borderRadius:5,background:e?"rgba(79,70,229,0.12)":"transparent",color:"inherit",padding:"8px 9px",textAlign:"left",cursor:"pointer",fontSize:12}}function qV(e){return{padding:"6px 12px",background:e?"var(--accent, #4f46e5)":"transparent",color:e?"#fff":"inherit",border:"1px solid var(--border-color, rgba(0,0,0,0.1))",borderRadius:6,fontSize:13,cursor:"pointer"}}function fp(e){return{border:"none",borderRight:"1px solid var(--border-color, rgba(0,0,0,0.10))",background:e?"var(--accent, #4f46e5)":"transparent",color:e?"#fff":"inherit",padding:"6px 10px",fontSize:12,fontWeight:e?700:500,cursor:"pointer"}}function JV(e){return{border:"1px solid var(--border-color, rgba(0,0,0,0.10))",borderRadius:5,background:e?"var(--accent, #4f46e5)":"transparent",color:e?"#fff":"inherit",padding:"5px 4px",fontSize:11,cursor:"pointer"}}const pp=["anthropic","openai","gemini","ollama","custom-openai"];function QV(){const{state:e}=fe(),t=ie[e.themeMode],[n,r]=f.useState([]),[o,i]=f.useState([]),[a,l]=f.useState([]),[c,d]=f.useState(!0),[E,u]=f.useState(null),T=async()=>{d(!0);try{const[h,A,S]=await Promise.all([z.getSettingsEnvStatus(),z.getProviderSettings(),z.listAgentMemory()]);r(h.groups),i(A.providers),l(S.memories)}finally{d(!1)}};f.useEffect(()=>{T()},[]);const p=f.useMemo(()=>o.filter(h=>h.enabled&&(h.hasApiKey||h.id==="ollama")).length,[o]);return s.jsxs("div",{style:{padding:24,maxWidth:1180},children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:16},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:18,fontWeight:700},children:"AI & Memory Settings"}),s.jsxs("div",{style:{color:t.textSecondary,fontSize:13,marginTop:6,lineHeight:1.5,maxWidth:820},children:["Configure local AI providers and the project memory used by governed analytics chat. Secrets stay under ",s.jsx("code",{children:".dql/"})," and are never returned raw."]})]}),s.jsx(n5,{configured:p,total:o.length||pp.length,t})]}),E&&s.jsx("div",{style:{marginTop:14,border:`1px solid ${t.headerBorder}`,borderRadius:8,padding:"10px 12px",fontSize:12,color:t.textSecondary,background:t.cellBg},children:E}),c?s.jsx("div",{style:{marginTop:24,color:t.textSecondary},children:"Loading settings..."}):s.jsxs(s.Fragment,{children:[s.jsxs("section",{style:{marginTop:22},children:[s.jsx(pc,{title:"Provider Setup",detail:"Use env vars or save project-local provider settings.",t}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:pp.map(h=>{const A=o.find(S=>S.id===h);return A?s.jsx(ZV,{provider:A,t,onSaved:S=>i(S),onStatus:u},h):null})})]}),s.jsxs("section",{style:{marginTop:22},children:[s.jsx(pc,{title:"Local Agent Memory",detail:"Memory helps interpret business language but never overrides certified metadata.",t}),s.jsx(e5,{memories:a,t,onChange:l,onStatus:u})]}),s.jsxs("section",{style:{marginTop:22},children:[s.jsx(pc,{title:"Environment Status",detail:"Runtime variables remain supported for Docker, CI, and shell-based setup.",t}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:n.map(h=>s.jsx(t5,{group:h,t},h.id))})]})]})]})}function ZV({provider:e,t,onSaved:n,onStatus:r}){const[o,i]=f.useState(e.enabled),[a,l]=f.useState(""),[c,d]=f.useState(e.baseUrl??""),[E,u]=f.useState(e.model??""),[T,p]=f.useState(!1);f.useEffect(()=>{i(e.enabled),d(e.baseUrl??""),u(e.model??""),l("")},[e.id,e.enabled,e.baseUrl,e.model]);const h=async()=>{p(!0);try{const S=await z.saveProviderSettings({id:e.id,enabled:o,apiKey:a||void 0,baseUrl:c,model:E});n(S.providers),r(`${e.label} settings saved.`)}catch(S){r(S instanceof Error?S.message:String(S))}finally{p(!1)}},A=async()=>{p(!0);try{const S=await z.testProviderSettings(e.id);r(S.message)}catch(S){r(S instanceof Error?S.message:String(S))}finally{p(!1)}};return s.jsxs("section",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.cellBg,padding:14},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[s.jsxs("div",{style:{flex:1},children:[s.jsx("div",{style:{fontSize:14,fontWeight:700},children:e.label}),s.jsxs("div",{style:{fontSize:11,color:t.textSecondary,marginTop:3},children:[e.source==="local"?"Project local":e.source==="env"?"Environment":"Not configured",e.apiKeyPreview?` · ${e.apiKeyPreview}`:""]})]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12,color:t.textSecondary},children:[s.jsx("input",{type:"checkbox",checked:o,onChange:S=>i(S.target.checked)}),"Enabled"]})]}),s.jsxs("div",{style:{display:"grid",gap:8,marginTop:12},children:[e.id!=="ollama"&&s.jsx("input",{value:a,onChange:S=>l(S.target.value),type:"password",placeholder:e.hasApiKey?"Leave blank to keep existing key":"API key",style:Pn(t)}),(e.id==="openai"||e.id==="ollama"||e.id==="custom-openai")&&s.jsx("input",{value:c,onChange:S=>d(S.target.value),placeholder:e.id==="ollama"?"http://host.docker.internal:11434 or http://127.0.0.1:11434":"Base URL",style:Pn(t)}),s.jsx("input",{value:E,onChange:S=>u(S.target.value),placeholder:"Default model",style:Pn(t)})]}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[s.jsx("button",{type:"button",onClick:h,disabled:T,style:Hi(t,!0),children:"Save"}),s.jsx("button",{type:"button",onClick:A,disabled:T,style:Hi(t,!1),children:"Test"})]}),e.envVars.length>0&&s.jsxs("div",{style:{marginTop:10,color:t.textSecondary,fontSize:11,lineHeight:1.4},children:["Env: ",e.envVars.join(", ")]})]})}function e5({memories:e,t,onChange:n,onStatus:r}){const[o,i]=f.useState("project"),[a,l]=f.useState(""),[c,d]=f.useState(""),[E,u]=f.useState(""),T=async()=>{const S=await z.listAgentMemory();n(S.memories)},p=async()=>{!a.trim()||!c.trim()||(await z.saveAgentMemory({scope:o,title:a,content:c,tags:E.split(",").map(S=>S.trim()).filter(Boolean),source:"settings-ui",confidence:.8,importance:o==="project"?.7:.5,enabled:!0}),l(""),d(""),u(""),await T(),r("Memory saved."))},h=async()=>{const S=await z.ensureAgentMemoryFiles();r(`Memory files ready: ${S.files.join(", ")}`)},A=async S=>{await z.deleteAgentMemory(S),await T(),r("Memory deleted.")};return s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:[s.jsxs("section",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.cellBg,padding:14},children:[s.jsxs("div",{style:{display:"grid",gap:8},children:[s.jsxs("select",{value:o,onChange:S=>i(S.target.value),style:Pn(t),children:[s.jsx("option",{value:"project",children:"Project context"}),s.jsx("option",{value:"user",children:"User preference"}),s.jsx("option",{value:"artifact",children:"Artifact note"}),s.jsx("option",{value:"notebook",children:"Notebook context"}),s.jsx("option",{value:"thread",children:"Thread summary"})]}),s.jsx("input",{value:a,onChange:S=>l(S.target.value),placeholder:"Memory title",style:Pn(t)}),s.jsx("textarea",{value:c,onChange:S=>d(S.target.value),placeholder:"Business context, glossary term, rule, or analyst correction",rows:5,style:{...Pn(t),resize:"vertical"}}),s.jsx("input",{value:E,onChange:S=>u(S.target.value),placeholder:"Tags, comma separated",style:Pn(t)})]}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[s.jsx("button",{type:"button",onClick:p,disabled:!a.trim()||!c.trim(),style:Hi(t,!0),children:"Save Memory"}),s.jsx("button",{type:"button",onClick:h,style:Hi(t,!1),children:"Create .dql/memory"})]})]}),s.jsx("section",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.cellBg,overflow:"hidden"},children:e.length===0?s.jsx("div",{style:{padding:14,color:t.textSecondary,fontSize:12},children:"No local memory yet."}):e.slice(0,20).map(S=>s.jsxs("div",{style:{padding:12,borderBottom:`1px solid ${t.headerBorder}`},children:[s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[s.jsx("span",{style:{fontSize:10,fontFamily:t.fontMono,color:t.accent,textTransform:"uppercase"},children:S.scope}),s.jsx("strong",{style:{fontSize:13},children:S.title}),s.jsx("button",{type:"button",onClick:()=>A(S.id),style:{marginLeft:"auto",border:0,background:"transparent",color:t.textMuted,cursor:"pointer"},children:"Delete"})]}),s.jsx("div",{style:{marginTop:6,fontSize:12,color:t.textSecondary,whiteSpace:"pre-wrap",lineHeight:1.45},children:S.content}),S.tags.length>0&&s.jsx("div",{style:{marginTop:6,fontSize:11,color:t.textMuted},children:S.tags.join(", ")})]},S.id))})]})}function t5({group:e,t}){return s.jsxs("section",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.cellBg,overflow:"hidden"},children:[s.jsxs("div",{style:{padding:"14px 14px 10px",borderBottom:`1px solid ${t.headerBorder}`},children:[s.jsx("div",{style:{fontSize:14,fontWeight:700},children:e.title}),s.jsx("div",{style:{color:t.textSecondary,fontSize:12,lineHeight:1.45,marginTop:4},children:e.description})]}),e.vars.map(n=>s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:10,padding:"11px 14px",borderBottom:`1px solid ${t.headerBorder}`},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsx("code",{style:{fontSize:12,color:t.textPrimary},children:n.key}),s.jsx("div",{style:{color:t.textSecondary,fontSize:12,lineHeight:1.4,marginTop:4},children:n.description})]}),s.jsx(r5,{present:n.present})]},n.key))]})}function pc({title:e,detail:t,t:n}){return s.jsxs("div",{style:{marginBottom:10},children:[s.jsx("div",{style:{fontSize:14,fontWeight:700},children:e}),s.jsx("div",{style:{fontSize:12,color:n.textSecondary,marginTop:3},children:t})]})}function n5({configured:e,total:t,t:n}){return s.jsxs("div",{style:{border:`1px solid ${n.headerBorder}`,borderRadius:8,padding:"10px 12px",minWidth:132,textAlign:"right",background:n.cellBg},children:[s.jsxs("div",{style:{fontSize:20,fontWeight:700},children:[e,"/",t]}),s.jsx("div",{style:{fontSize:12,color:n.textSecondary},children:"providers ready"})]})}function r5({present:e}){return s.jsx("span",{style:{alignSelf:"start",fontSize:11,fontWeight:700,borderRadius:999,padding:"3px 8px",color:e?"#12613a":"#7a4a00",background:e?"#d9f8e6":"#fff0cc",whiteSpace:"nowrap"},children:e?"Set":"Optional"})}function Pn(e){return{minHeight:32,border:`1px solid ${e.headerBorder}`,borderRadius:6,background:e.appBg,color:e.textPrimary,padding:"7px 9px",fontSize:12,fontFamily:e.font}}function Hi(e,t){return{height:30,border:`1px solid ${t?e.accent:e.headerBorder}`,background:t?`${e.accent}24`:e.appBg,color:t?e.accent:e.textPrimary,borderRadius:6,padding:"0 10px",cursor:"pointer",fontSize:12}}const o5=380;function s5(){var m;const{state:e,dispatch:t}=fe(),n=ie[e.themeMode],r=e.lineageDrawerNodeId,[o,i]=f.useState({nodes:[],edges:[],focalNode:null}),[a,l]=f.useState(!1),c=f.useRef(null),[d,E]=f.useState(360);if(f.useEffect(()=>{const I=c.current;if(!I)return;const O=new ResizeObserver(N=>{for(const x of N){const g=Math.max(160,x.contentRect.height);E(g)}});return O.observe(I),()=>O.disconnect()},[]),f.useEffect(()=>{if(!r)return;let I=!1;return l(!0),z.queryLineage({focus:r,upstreamDepth:2,downstreamDepth:2}).then(O=>{var N,x;I||(i({nodes:((N=O.graph)==null?void 0:N.nodes)??[],edges:((x=O.graph)==null?void 0:x.edges)??[],focalNode:O.focalNode??null}),l(!1))}).catch(()=>{I||l(!1)}),()=>{I=!0}},[r]),!r)return null;const u=o.focalNode,T=u?o.edges.filter(I=>I.target===u.id).length:0,p=u?o.edges.filter(I=>I.source===u.id).length:0,h=u?we[u.type]??n.textSecondary:n.textSecondary,A=u?aa[u.type]??u.type.toUpperCase():"",S=I=>{I!==r&&t({type:"OPEN_LINEAGE_DRAWER",nodeId:I})},R=()=>{t({type:"SET_LINEAGE_FOCUS",nodeId:r}),t({type:"CLOSE_LINEAGE_DRAWER"}),e.lineageFullscreen||t({type:"TOGGLE_LINEAGE_FULLSCREEN"})};return s.jsxs("aside",{"aria-label":"Lineage drawer",style:{width:o5,flexShrink:0,borderLeft:`1px solid ${n.headerBorder}`,background:n.appBg,color:n.textPrimary,display:"flex",flexDirection:"column",overflow:"hidden",animation:"dql-drawer-slide-in 180ms cubic-bezier(0.22, 0.61, 0.36, 1)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 14px",borderBottom:`1px solid ${n.headerBorder}`},children:[s.jsx("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:38,padding:"2px 6px",background:h,color:n.appBg,fontSize:10,fontWeight:700,letterSpacing:"0.04em",borderRadius:4},title:u?la[u.type]??u.type:"",children:A||"NODE"}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:(u==null?void 0:u.name)??r,children:(u==null?void 0:u.name)??r}),s.jsxs("div",{style:{fontSize:11,color:n.textMuted,marginTop:2},children:["Lineage · ↑ ",T," · ↓ ",p]})]}),s.jsx(Sp,{title:"Open full graph",onClick:R,t:n,children:s.jsx(DR,{size:14,strokeWidth:1.75})}),s.jsx(Sp,{title:"Close",onClick:()=>t({type:"CLOSE_LINEAGE_DRAWER"}),t:n,children:s.jsx(Md,{size:14,strokeWidth:2})})]}),s.jsx("div",{ref:c,style:{flex:1,minHeight:0,padding:12,overflow:"hidden",display:"flex"},children:a?s.jsx("div",{style:{color:n.textMuted,fontSize:12,padding:8},children:"Loading lineage…"}):o.nodes.length===0?s.jsx("div",{style:{color:n.textMuted,fontSize:12,padding:8},children:"No lineage available for this node."}):s.jsx("div",{style:{flex:1,minWidth:0},children:s.jsx(pE,{nodes:o.nodes,edges:o.edges,focalNodeId:r,height:Math.max(0,d-24),onNodeClick:S,interactive:!0})})}),((m=u==null?void 0:u.metadata)==null?void 0:m.path)!=null&&typeof u.metadata.path=="string"&&s.jsxs("div",{style:{padding:"8px 14px",borderTop:`1px solid ${n.headerBorder}`,fontSize:11,color:n.textMuted,display:"flex",alignItems:"center",gap:6},children:[s.jsx(QC,{size:11,strokeWidth:1.75}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:u.metadata.path,children:u.metadata.path})]})]})}function Sp({title:e,onClick:t,children:n,t:r}){return s.jsx("button",{"aria-label":e,title:e,onClick:t,style:{width:26,height:26,display:"inline-flex",alignItems:"center",justifyContent:"center",background:"transparent",border:`1px solid ${r.headerBorder}`,borderRadius:5,color:r.textSecondary,cursor:"pointer"},onMouseEnter:o=>{o.currentTarget.style.color=r.textPrimary,o.currentTarget.style.background=r.textPrimary+"0f"},onMouseLeave:o=>{o.currentTarget.style.color=r.textSecondary,o.currentTarget.style.background="transparent"},children:n})}function i5(){const{state:e,dispatch:t}=fe(),{executeAll:n}=ca();f.useEffect(()=>{const r=o=>{const i=o.metaKey||o.ctrlKey;if(i&&o.key==="b"&&!o.shiftKey){o.preventDefault(),t({type:"TOGGLE_SIDEBAR"});return}if(i&&o.shiftKey&&o.key==="Enter"){o.preventDefault(),e.activeFile&&n();return}if(i&&o.key==="j"&&!o.shiftKey){o.preventDefault(),t({type:"TOGGLE_DEV_PANEL"});return}if(i&&o.key==="d"&&!o.shiftKey){o.preventDefault(),e.activeFile&&t({type:"TOGGLE_DASHBOARD_MODE"});return}if(o.key==="Escape"){if(e.dashboardMode){t({type:"TOGGLE_DASHBOARD_MODE"});return}if(e.newNotebookModalOpen){t({type:"CLOSE_NEW_NOTEBOOK_MODAL"});return}if(e.newBlockModalOpen){t({type:"CLOSE_NEW_BLOCK_MODAL"});return}}};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[t,n,e.activeFile,e.newNotebookModalOpen,e.newBlockModalOpen,e.dashboardMode])}const a5=600;function l5(e,t){const n=t.filter(r=>r.result||r.error||(r.executionCount??0)>0).map(r=>({cellId:r.id,status:r.status,result:r.result,error:r.error,executionCount:r.executionCount,executedAt:new Date().toISOString()}));return{version:1,notebookPath:e,capturedAt:new Date().toISOString(),cells:n}}function Rp(e){return e.map(t=>{var n;return`${t.id}:${t.executionCount??0}:${((n=t.result)==null?void 0:n.rowCount)??-1}:${(t.error??"").length}`}).join("|")}function c5(){var o;const{state:e}=fe(),t=f.useRef(null),n=f.useRef(""),r=f.useRef(null);f.useEffect(()=>{var l;const i=((l=e.activeFile)==null?void 0:l.path)??null;if(!i)return;if(i!==r.current){r.current=i,n.current=Rp(e.cells);return}const a=Rp(e.cells);return a!==n.current&&(n.current=a,t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{const c=l5(i,e.cells);z.saveRunSnapshot(i,c).catch(()=>{})},a5)),()=>{t.current&&(clearTimeout(t.current),t.current=null)}},[e.cells,(o=e.activeFile)==null?void 0:o.path])}function d5(){const{state:e,dispatch:t}=fe(),n=ie[e.themeMode],r=f.useRef({}),[o,i]=f.useState(!1);i5(),c5(),f.useEffect(()=>{const c=d=>{(d.metaKey||d.ctrlKey)&&d.key.toLowerCase()==="k"&&!d.shiftKey&&(d.preventDefault(),i(E=>!E)),(d.metaKey||d.ctrlKey)&&d.shiftKey&&d.key.toLowerCase()==="i"&&(d.preventDefault(),t({type:"TOGGLE_INSPECTOR"}))};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[t]);const a=f.useCallback(async c=>{try{if(c.type==="block"){const A=await z.openBlockStudio(c.path);t({type:"OPEN_BLOCK_STUDIO",file:c,payload:A});return}const{content:d}=await z.readNotebook(c.path),{title:E,cells:u,metadata:T}=U0(c.path,d),p=c.path.endsWith(".dqlnb")?await z.fetchRunSnapshot(c.path):null;let h=u;if(p!=null&&p.found&&p.snapshot){const A=new Map(p.snapshot.cells.map(S=>[S.cellId,S]));h=u.map(S=>{const R=A.get(S.id);return R?{...S,status:R.status??S.status,result:R.result??S.result,error:R.error??S.error,executionCount:R.executionCount??S.executionCount,fromSnapshot:R.result!=null}:S})}t({type:"OPEN_FILE",file:c,cells:h,title:E,metadata:T}),e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"})}catch(d){if(console.error("Failed to open file:",d),c.type==="block")try{const{content:E}=await z.readNotebook(c.path);t({type:"OPEN_BLOCK_STUDIO",file:c,payload:{path:c.path,source:E,companionPath:null,metadata:{name:c.name.replace(/\.dql$/i,""),path:c.path,domain:c.path.split("/").slice(1,-1).join("/")||"uncategorized",description:"",owner:"",tags:[]},validation:{valid:!1,diagnostics:[{severity:"warning",message:"Opened block without studio metadata. Save once to normalize it."}],semanticRefs:{metrics:[],dimensions:[],segments:[]}}}});return}catch(E){console.error("Failed to open block fallback:",E)}else t({type:"OPEN_FILE",file:c,cells:[ze("sql")],title:c.name})}},[t,e.sidebarPanel]);f.useCallback(c=>{const d=r.current[c];d&&d.scrollIntoView({behavior:"smooth",block:"start"})},[]);const l=f.useCallback((c,d)=>{d?r.current[c]=d:delete r.current[c]},[]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100vh",width:"100vw",background:n.appBg,fontFamily:n.font,color:n.textPrimary,overflow:"hidden"},children:[s.jsx(ib,{}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[e.appMode==="studio"&&s.jsx(h_,{}),e.appMode==="studio"&&e.sidebarOpen&&s.jsx(b0,{onOpenFile:a}),s.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:e.lineageFullscreen?s.jsx(aV,{}):e.mainView==="connection"?s.jsx(Sc,{title:"Connections",description:"Manage database connections, edit driver settings, and test connectivity in a full-page workspace.",children:s.jsx(jR,{})}):e.mainView==="reference"?s.jsx(Sc,{title:"Quick Reference",description:"Browse the complete DQL guide, semantic workflows, and authoring patterns in a documentation-style view.",children:s.jsx(GR,{themeMode:e.themeMode})}):e.mainView==="git"?s.jsx(EV,{}):e.mainView==="apps"?s.jsx(kV,{}):e.mainView==="settings"?s.jsx(Sc,{title:"Settings",description:"Check local environment keys for AI chat, Slack, email schedules, and Docker/native runtime setup.",children:s.jsx(QV,{})}):s.jsx(s.Fragment,{children:e.mainView==="block_studio"?s.jsx(G$,{}):s.jsxs(s.Fragment,{children:[s.jsx(_$,{onOpenFile:a,registerCellRef:l}),e.appMode==="studio"&&s.jsx(Eb,{})]})})}),e.appMode==="studio"&&e.lineageDrawerOpen&&!e.lineageFullscreen&&!e.dashboardMode&&s.jsx(s5,{}),e.appMode==="studio"&&e.inspectorOpen&&!e.lineageFullscreen&&!e.lineageDrawerOpen&&!e.dashboardMode&&s.jsx(e_,{})]}),e.newNotebookModalOpen&&s.jsx(w$,{onFileOpened:a}),e.newBlockModalOpen&&s.jsx(F$,{onFileOpened:a}),s.jsx(ZL,{open:o,onClose:()=>i(!1)})]})}function Sc({title:e,description:t,children:n}){return s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden"},children:[s.jsxs("div",{style:{padding:"18px 24px 12px",borderBottom:"1px solid rgba(127, 127, 127, 0.16)"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700},children:e}),s.jsx("div",{style:{fontSize:13,opacity:.72,marginTop:6,maxWidth:760,lineHeight:1.5},children:t})]}),s.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:n})]})}function E5(){const{state:e,dispatch:t}=fe(),n=f.useRef(null),r=f.useRef(null);f.useEffect(()=>{var o;n.current=((o=e.activeFile)==null?void 0:o.path)??null},[e.activeFile]),f.useEffect(()=>{if(typeof EventSource>"u")return;const o=()=>{const i=new EventSource(`${window.location.origin}/api/watch`);r.current=i,i.addEventListener("change",a=>{try{const l=JSON.parse(a.data);(l.type==="file-added"||l.type==="file-deleted")&&z.listNotebooks().then(c=>{t({type:"SET_FILES",files:c})}),l.type==="file-changed"&&z.listNotebooks().then(c=>{t({type:"SET_FILES",files:c})}),l.type==="semantic-reload"&&(t({type:"SET_SEMANTIC_LOADING",loading:!0}),z.getSemanticLayer().then(c=>{t({type:"SET_SEMANTIC_LAYER",layer:c})}))}catch{}}),i.addEventListener("error",()=>{i.close(),setTimeout(o,5e3)})};return o(),()=>{var i;(i=r.current)==null||i.close(),r.current=null}},[t])}function u5(){const{state:e,dispatch:t}=fe(),n=ie[e.themeMode];return f.useEffect(()=>{const r="dql-global-styles";let o=document.getElementById(r);o||(o=document.createElement("style"),o.id=r,document.head.appendChild(o)),o.textContent=`
|
|
833
|
-
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
834
|
-
body {
|
|
835
|
-
font-family: var(--font-ui, ${n.font});
|
|
836
|
-
overflow: hidden;
|
|
837
|
-
background: var(--color-bg-primary);
|
|
838
|
-
color: var(--color-text-primary);
|
|
839
|
-
}
|
|
840
|
-
::-webkit-scrollbar { width: 6px; height: 6px; }
|
|
841
|
-
::-webkit-scrollbar-track { background: transparent; }
|
|
842
|
-
::-webkit-scrollbar-thumb {
|
|
843
|
-
background: var(--color-border-secondary);
|
|
844
|
-
border-radius: 3px;
|
|
845
|
-
}
|
|
846
|
-
::-webkit-scrollbar-thumb:hover {
|
|
847
|
-
background: var(--color-text-tertiary);
|
|
848
|
-
}
|
|
849
|
-
::selection {
|
|
850
|
-
background: color-mix(in srgb, var(--color-accent-blue) 25%, transparent);
|
|
851
|
-
color: var(--color-text-primary);
|
|
852
|
-
}
|
|
853
|
-
.dql-meta-pill:hover {
|
|
854
|
-
background: var(--dql-pill-hover-bg) !important;
|
|
855
|
-
border-color: var(--dql-pill-hover-border) !important;
|
|
856
|
-
}
|
|
857
|
-
`},[n]),f.useEffect(()=>{const r=e.themeMode==="dark"||e.themeMode==="midnight"?"obsidian":e.themeMode==="light"?"paper":e.themeMode==="arctic"?"white":e.themeMode;document.documentElement.setAttribute("data-theme",r)},[e.themeMode]),f.useEffect(()=>{t({type:"SET_FILES_LOADING",loading:!0}),z.listNotebooks().then(r=>{t({type:"SET_FILES",files:r}),t({type:"SET_FILES_LOADING",loading:!1})})},[t]),f.useEffect(()=>{t({type:"SET_SCHEMA_LOADING",loading:!0}),z.getSchema().then(r=>{t({type:"SET_SCHEMA",tables:r}),t({type:"SET_SCHEMA_LOADING",loading:!1})})},[t]),E5(),s.jsx(Zm,{theme:e.themeMode,applyGlobal:!0,children:s.jsx(dg,{delayDuration:200,skipDelayDuration:400,children:s.jsx(d5,{})})})}function T5(){return s.jsx(NC,{children:s.jsx(u5,{})})}qm.createRoot(document.getElementById("root")).render(s.jsx(T5,{}));
|