@duckcodeailabs/dql-cli 0.11.0 → 1.0.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.
@@ -0,0 +1,623 @@
1
+ import{r as ii,a as yT,g as ai}from"./react-CRB3T2We.js";import{S as li,g as DT,E as it,s as Qp,a as be,b as MT,c as Zp,P as eI,d as tI,e as nI,F as rI,f as oI,h as PT,V as sI,D as un,R as iI,i as aI,C as Xt,j as bT,k as ze,r as lI,l as cI,m as EI,u as dI,n as uI,t as TI,o as SI,p as RI,q as fI,v as AI,w as pI,x as II,y as Wo,z as OI,A as NI,B as hI,G as mI,H as CI,I as gI,J as LI,K as _I,L as xI,M as yI,N as DI,O as MI}from"./codemirror-BqWuFwtC.js";function PI(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 s=Object.getOwnPropertyDescriptor(r,o);s&&Object.defineProperty(e,o,s.get?s:{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 s of o)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();var ra={exports:{}},Lr={};/**
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 cE;function bI(){if(cE)return Lr;cE=1;var e=ii(),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,s={key:!0,ref:!0,__self:!0,__source:!0};function a(l,E,c){var d,u={},T=null,S=null;c!==void 0&&(T=""+c),E.key!==void 0&&(T=""+E.key),E.ref!==void 0&&(S=E.ref);for(d in E)r.call(E,d)&&!s.hasOwnProperty(d)&&(u[d]=E[d]);if(l&&l.defaultProps)for(d in E=l.defaultProps,E)u[d]===void 0&&(u[d]=E[d]);return{$$typeof:t,type:l,key:T,ref:S,props:u,_owner:o.current}}return Lr.Fragment=n,Lr.jsx=a,Lr.jsxs=a,Lr}var EE;function vI(){return EE||(EE=1,ra.exports=bI()),ra.exports}var i=vI(),Vo={},dE;function UI(){if(dE)return Vo;dE=1;var e=yT();return Vo.createRoot=e.createRoot,Vo.hydrateRoot=e.hydrateRoot,Vo}var wI=UI(),R=ii();const me=ai(R),vT=PI({__proto__:null,default:me},[R]),fe={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"},pe={1:"4px",2:"8px",3:"12px",4:"16px"},mn={sm:"4px",md:"6px",lg:"8px"},ve={xs:"11px",sm:"12px",md:"14px"},Ql={medium:"500",semibold:"600"},kr={overlay:1e3,modal:1100,popover:1200,tooltip:1300},BI={surfaceBase:fe.gray1000,surfaceRaised:fe.gray975,surfaceElevated:fe.gray950,surfaceOverlay:"rgba(0,0,0,0.7)",surfaceHover:fe.gray900,surfaceActive:"#1f2d3d",surfaceSunken:fe.gray1000,borderSubtle:"#21262d",borderDefault:"#30363d",borderStrong:"#484f58",borderFocus:fe.blue500,textPrimary:"#e6edf3",textSecondary:"#8b949e",textMuted:"#484f58",textDisabled:"#32383f",textInverse:fe.gray1000,accent:fe.blue500,accentHover:fe.blue400,accentMuted:"rgba(56,139,253,0.15)",accentContrast:"#ffffff",success:fe.green500,warning:fe.yellow500,danger:fe.red500,info:fe.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)"},FI={surfaceBase:fe.gray0,surfaceRaised:fe.gray50,surfaceElevated:fe.gray0,surfaceOverlay:"rgba(0,0,0,0.4)",surfaceHover:fe.gray100,surfaceActive:"#dbeafe",surfaceSunken:fe.gray50,borderSubtle:fe.gray100,borderDefault:fe.gray200,borderStrong:fe.gray300,borderFocus:fe.blue600,textPrimary:"#1f2328",textSecondary:fe.gray600,textMuted:fe.gray400,textDisabled:fe.gray300,textInverse:fe.gray0,accent:fe.blue600,accentHover:fe.blue700,accentMuted:"rgba(9,105,218,0.12)",accentContrast:"#ffffff",success:fe.green600,warning:fe.yellow600,danger:fe.red600,info:fe.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)"},GI={dark:BI,light:FI};function UT(e){return`--dql-${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function uE(e){const t={};for(const[n,r]of Object.entries(e))t[UT(n)]=r;return t}function Te(e){return`var(${UT(e)})`}const HI=R.createContext(null);function kI({theme:e,defaultTheme:t="dark",onThemeChange:n,applyGlobal:r=!1,children:o}){const[s,a]=R.useState(t),l=e??s,E=GI[l],c=R.useCallback(T=>{e===void 0&&a(T),n==null||n(T)},[e,n]);R.useEffect(()=>{if(!r)return;const T=uE(E),S=document.documentElement;for(const[A,f]of Object.entries(T))S.style.setProperty(A,f);return S.setAttribute("data-theme",l),()=>{for(const A of Object.keys(T))S.style.removeProperty(A);S.removeAttribute("data-theme")}},[r,l,E]);const d=R.useMemo(()=>({theme:l,tokens:E,setTheme:c}),[l,E,c]),u=r?void 0:uE(E);return i.jsx(HI.Provider,{value:d,children:i.jsx("div",{"data-theme":l,style:u,children:o})})}function ae(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 TE(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ci(...e){return t=>{let n=!1;const r=e.map(o=>{const s=TE(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():TE(e[o],null)}}}}function Ce(...e){return R.useCallback(ci(...e),e)}function YI(e,t){const n=R.createContext(t),r=s=>{const{children:a,...l}=s,E=R.useMemo(()=>l,Object.values(l));return i.jsx(n.Provider,{value:E,children:a})};r.displayName=e+"Provider";function o(s){const a=R.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function on(e,t=[]){let n=[];function r(s,a){const l=R.createContext(a),E=n.length;n=[...n,a];const c=u=>{var p;const{scope:T,children:S,...A}=u,f=((p=T==null?void 0:T[e])==null?void 0:p[E])||l,I=R.useMemo(()=>A,Object.values(A));return i.jsx(f.Provider,{value:I,children:S})};c.displayName=s+"Provider";function d(u,T){var f;const S=((f=T==null?void 0:T[e])==null?void 0:f[E])||l,A=R.useContext(S);if(A)return A;if(a!==void 0)return a;throw new Error(`\`${u}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(a=>R.createContext(a));return function(l){const E=(l==null?void 0:l[e])||s;return R.useMemo(()=>({[`__scope${e}`]:{...l,[e]:E}}),[l,E])}};return o.scopeName=e,[r,jI(o,...t)]}function jI(...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(s){const a=r.reduce((l,{useScope:E,scopeName:c})=>{const u=E(s)[`__scope${c}`];return{...l,...u}},{});return R.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}var Zl=yT();const WI=ai(Zl);function er(e){const t=VI(e),n=R.forwardRef((r,o)=>{const{children:s,...a}=r,l=R.Children.toArray(s),E=l.find(XI);if(E){const c=E.props.children,d=l.map(u=>u===E?R.Children.count(c)>1?R.Children.only(null):R.isValidElement(c)?c.props.children:null:u);return i.jsx(t,{...a,ref:o,children:R.isValidElement(c)?R.cloneElement(c,void 0,d):null})}return i.jsx(t,{...a,ref:o,children:s})});return n.displayName=`${e}.Slot`,n}function VI(e){const t=R.forwardRef((n,r)=>{const{children:o,...s}=n;if(R.isValidElement(o)){const a=zI(o),l=KI(s,o.props);return o.type!==R.Fragment&&(l.ref=r?ci(r,a):a),R.cloneElement(o,l)}return R.Children.count(o)>1?R.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var wT=Symbol("radix.slottable");function $I(e){const t=({children:n})=>i.jsx(i.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=wT,t}function XI(e){return R.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===wT}function KI(e,t){const n={...t};for(const r in t){const o=e[r],s=t[r];/^on[A-Z]/.test(r)?o&&s?n[r]=(...l)=>{const E=s(...l);return o(...l),E}:o&&(n[r]=o):r==="style"?n[r]={...o,...s}:r==="className"&&(n[r]=[o,s].filter(Boolean).join(" "))}return{...e,...n}}function zI(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 JI=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Oe=JI.reduce((e,t)=>{const n=er(`Primitive.${t}`),r=R.forwardRef((o,s)=>{const{asChild:a,...l}=o,E=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),i.jsx(E,{...l,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function BT(e,t){e&&Zl.flushSync(()=>e.dispatchEvent(t))}function qt(e){const t=R.useRef(e);return R.useEffect(()=>{t.current=e}),R.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function qI(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e);R.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 QI="DismissableLayer",fl="dismissableLayer.update",ZI="dismissableLayer.pointerDownOutside",eO="dismissableLayer.focusOutside",SE,FT=R.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),io=R.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:a,onDismiss:l,...E}=e,c=R.useContext(FT),[d,u]=R.useState(null),T=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,S]=R.useState({}),A=Ce(t,g=>u(g)),f=Array.from(c.layers),[I]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),p=f.indexOf(I),O=d?f.indexOf(d):-1,N=c.layersWithOutsidePointerEventsDisabled.size>0,h=O>=p,C=rO(g=>{const y=g.target,_=[...c.branches].some(U=>U.contains(y));!h||_||(o==null||o(g),a==null||a(g),g.defaultPrevented||l==null||l())},T),m=oO(g=>{const y=g.target;[...c.branches].some(U=>U.contains(y))||(s==null||s(g),a==null||a(g),g.defaultPrevented||l==null||l())},T);return qI(g=>{O===c.layers.size-1&&(r==null||r(g),!g.defaultPrevented&&l&&(g.preventDefault(),l()))},T),R.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(SE=T.body.style.pointerEvents,T.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),RE(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(T.body.style.pointerEvents=SE)}},[d,T,n,c]),R.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),RE())},[d,c]),R.useEffect(()=>{const g=()=>S({});return document.addEventListener(fl,g),()=>document.removeEventListener(fl,g)},[]),i.jsx(Oe.div,{...E,ref:A,style:{pointerEvents:N?h?"auto":"none":void 0,...e.style},onFocusCapture:ae(e.onFocusCapture,m.onFocusCapture),onBlurCapture:ae(e.onBlurCapture,m.onBlurCapture),onPointerDownCapture:ae(e.onPointerDownCapture,C.onPointerDownCapture)})});io.displayName=QI;var tO="DismissableLayerBranch",nO=R.forwardRef((e,t)=>{const n=R.useContext(FT),r=R.useRef(null),o=Ce(t,r);return R.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),i.jsx(Oe.div,{...e,ref:o})});nO.displayName=tO;function rO(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e),r=R.useRef(!1),o=R.useRef(()=>{});return R.useEffect(()=>{const s=l=>{if(l.target&&!r.current){let E=function(){GT(ZI,n,c,{discrete:!0})};const c={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=E,t.addEventListener("click",o.current,{once:!0})):E()}else t.removeEventListener("click",o.current);r.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function oO(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e),r=R.useRef(!1);return R.useEffect(()=>{const o=s=>{s.target&&!r.current&&GT(eO,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function RE(){const e=new CustomEvent(fl);document.dispatchEvent(e)}function GT(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?BT(o,s):o.dispatchEvent(s)}var Qt=globalThis!=null&&globalThis.document?R.useLayoutEffect:()=>{},sO=vT[" useId ".trim().toString()]||(()=>{}),iO=0;function wr(e){const[t,n]=R.useState(sO());return Qt(()=>{n(r=>r??String(iO++))},[e]),t?`radix-${t}`:""}const aO=["top","right","bottom","left"],Zt=Math.min,Ve=Math.max,Ds=Math.round,$o=Math.floor,pt=e=>({x:e,y:e}),lO={left:"right",right:"left",bottom:"top",top:"bottom"};function Al(e,t,n){return Ve(e,Zt(t,n))}function Pt(e,t){return typeof e=="function"?e(t):e}function bt(e){return e.split("-")[0]}function Sr(e){return e.split("-")[1]}function ec(e){return e==="x"?"y":"x"}function tc(e){return e==="y"?"height":"width"}function ft(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function nc(e){return ec(ft(e))}function cO(e,t,n){n===void 0&&(n=!1);const r=Sr(e),o=nc(e),s=tc(o);let a=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(a=Ms(a)),[a,Ms(a)]}function EO(e){const t=Ms(e);return[pl(e),t,pl(t)]}function pl(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const fE=["left","right"],AE=["right","left"],dO=["top","bottom"],uO=["bottom","top"];function TO(e,t,n){switch(e){case"top":case"bottom":return n?t?AE:fE:t?fE:AE;case"left":case"right":return t?dO:uO;default:return[]}}function SO(e,t,n,r){const o=Sr(e);let s=TO(bt(e),n==="start",r);return o&&(s=s.map(a=>a+"-"+o),t&&(s=s.concat(s.map(pl)))),s}function Ms(e){const t=bt(e);return lO[t]+e.slice(t.length)}function RO(e){return{top:0,right:0,bottom:0,left:0,...e}}function HT(e){return typeof e!="number"?RO(e):{top:e,right:e,bottom:e,left:e}}function Ps(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 pE(e,t,n){let{reference:r,floating:o}=e;const s=ft(t),a=nc(t),l=tc(a),E=bt(t),c=s==="y",d=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 S;switch(E){case"top":S={x:d,y:r.y-o.height};break;case"bottom":S={x:d,y:r.y+r.height};break;case"right":S={x:r.x+r.width,y:u};break;case"left":S={x:r.x-o.width,y:u};break;default:S={x:r.x,y:r.y}}switch(Sr(t)){case"start":S[a]-=T*(n&&c?-1:1);break;case"end":S[a]+=T*(n&&c?-1:1);break}return S}async function fO(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:a,elements:l,strategy:E}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:T=!1,padding:S=0}=Pt(t,e),A=HT(S),I=l[T?u==="floating"?"reference":"floating":u],p=Ps(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(I)))==null||n?I:I.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(l.floating)),boundary:c,rootBoundary:d,strategy:E})),O=u==="floating"?{x:r,y:o,width:a.floating.width,height:a.floating.height}:a.reference,N=await(s.getOffsetParent==null?void 0:s.getOffsetParent(l.floating)),h=await(s.isElement==null?void 0:s.isElement(N))?await(s.getScale==null?void 0:s.getScale(N))||{x:1,y:1}:{x:1,y:1},C=Ps(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:O,offsetParent:N,strategy:E}):O);return{top:(p.top-C.top+A.top)/h.y,bottom:(C.bottom-p.bottom+A.bottom)/h.y,left:(p.left-C.left+A.left)/h.x,right:(C.right-p.right+A.right)/h.x}}const AO=50,pO=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:a}=n,l=a.detectOverflow?a:{...a,detectOverflow:fO},E=await(a.isRTL==null?void 0:a.isRTL(t));let c=await a.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:u}=pE(c,r,E),T=r,S=0;const A={};for(let f=0;f<s.length;f++){const I=s[f];if(!I)continue;const{name:p,fn:O}=I,{x:N,y:h,data:C,reset:m}=await O({x:d,y:u,initialPlacement:r,placement:T,strategy:o,middlewareData:A,rects:c,platform:l,elements:{reference:e,floating:t}});d=N??d,u=h??u,A[p]={...A[p],...C},m&&S<AO&&(S++,typeof m=="object"&&(m.placement&&(T=m.placement),m.rects&&(c=m.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:o}):m.rects),{x:d,y:u}=pE(c,T,E)),f=-1)}return{x:d,y:u,placement:T,strategy:o,middlewareData:A}},IO=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:a,elements:l,middlewareData:E}=t,{element:c,padding:d=0}=Pt(e,t)||{};if(c==null)return{};const u=HT(d),T={x:n,y:r},S=nc(o),A=tc(S),f=await a.getDimensions(c),I=S==="y",p=I?"top":"left",O=I?"bottom":"right",N=I?"clientHeight":"clientWidth",h=s.reference[A]+s.reference[S]-T[S]-s.floating[A],C=T[S]-s.reference[S],m=await(a.getOffsetParent==null?void 0:a.getOffsetParent(c));let g=m?m[N]:0;(!g||!await(a.isElement==null?void 0:a.isElement(m)))&&(g=l.floating[N]||s.floating[A]);const y=h/2-C/2,_=g/2-f[A]/2-1,U=Zt(u[p],_),D=Zt(u[O],_),b=U,F=g-f[A]-D,L=g/2-f[A]/2+y,P=Al(b,L,F),M=!E.arrow&&Sr(o)!=null&&L!==P&&s.reference[A]/2-(L<b?U:D)-f[A]/2<0,w=M?L<b?L-b:L-F:0;return{[S]:T[S]+w,data:{[S]:P,centerOffset:L-P-w,...M&&{alignmentOffset:w}},reset:M}}}),OO=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:a,initialPlacement:l,platform:E,elements:c}=t,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:T,fallbackStrategy:S="bestFit",fallbackAxisSideDirection:A="none",flipAlignment:f=!0,...I}=Pt(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const p=bt(o),O=ft(l),N=bt(l)===l,h=await(E.isRTL==null?void 0:E.isRTL(c.floating)),C=T||(N||!f?[Ms(l)]:EO(l)),m=A!=="none";!T&&m&&C.push(...SO(l,f,A,h));const g=[l,...C],y=await E.detectOverflow(t,I),_=[];let U=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&_.push(y[p]),u){const L=cO(o,a,h);_.push(y[L[0]],y[L[1]])}if(U=[...U,{placement:o,overflows:_}],!_.every(L=>L<=0)){var D,b;const L=(((D=s.flip)==null?void 0:D.index)||0)+1,P=g[L];if(P&&(!(u==="alignment"?O!==ft(P):!1)||U.every(v=>ft(v.placement)===O?v.overflows[0]>0:!0)))return{data:{index:L,overflows:U},reset:{placement:P}};let M=(b=U.filter(w=>w.overflows[0]<=0).sort((w,v)=>w.overflows[1]-v.overflows[1])[0])==null?void 0:b.placement;if(!M)switch(S){case"bestFit":{var F;const w=(F=U.filter(v=>{if(m){const x=ft(v.placement);return x===O||x==="y"}return!0}).map(v=>[v.placement,v.overflows.filter(x=>x>0).reduce((x,B)=>x+B,0)]).sort((v,x)=>v[1]-x[1])[0])==null?void 0:F[0];w&&(M=w);break}case"initialPlacement":M=l;break}if(o!==M)return{reset:{placement:M}}}return{}}}};function IE(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function OE(e){return aO.some(t=>e[t]>=0)}const NO=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:o="referenceHidden",...s}=Pt(e,t);switch(o){case"referenceHidden":{const a=await r.detectOverflow(t,{...s,elementContext:"reference"}),l=IE(a,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:OE(l)}}}case"escaped":{const a=await r.detectOverflow(t,{...s,altBoundary:!0}),l=IE(a,n.floating);return{data:{escapedOffsets:l,escaped:OE(l)}}}default:return{}}}}},kT=new Set(["left","top"]);async function hO(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),a=bt(n),l=Sr(n),E=ft(n)==="y",c=kT.has(a)?-1:1,d=s&&E?-1:1,u=Pt(t,e);let{mainAxis:T,crossAxis:S,alignmentAxis:A}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return l&&typeof A=="number"&&(S=l==="end"?A*-1:A),E?{x:S*d,y:T*c}:{x:T*c,y:S*d}}const mO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:a,middlewareData:l}=t,E=await hO(t,e);return a===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:o+E.x,y:s+E.y,data:{...E,placement:a}}}}},CO=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o,platform:s}=t,{mainAxis:a=!0,crossAxis:l=!1,limiter:E={fn:p=>{let{x:O,y:N}=p;return{x:O,y:N}}},...c}=Pt(e,t),d={x:n,y:r},u=await s.detectOverflow(t,c),T=ft(bt(o)),S=ec(T);let A=d[S],f=d[T];if(a){const p=S==="y"?"top":"left",O=S==="y"?"bottom":"right",N=A+u[p],h=A-u[O];A=Al(N,A,h)}if(l){const p=T==="y"?"top":"left",O=T==="y"?"bottom":"right",N=f+u[p],h=f-u[O];f=Al(N,f,h)}const I=E.fn({...t,[S]:A,[T]:f});return{...I,data:{x:I.x-n,y:I.y-r,enabled:{[S]:a,[T]:l}}}}}},gO=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:a}=t,{offset:l=0,mainAxis:E=!0,crossAxis:c=!0}=Pt(e,t),d={x:n,y:r},u=ft(o),T=ec(u);let S=d[T],A=d[u];const f=Pt(l,t),I=typeof f=="number"?{mainAxis:f,crossAxis:0}:{mainAxis:0,crossAxis:0,...f};if(E){const N=T==="y"?"height":"width",h=s.reference[T]-s.floating[N]+I.mainAxis,C=s.reference[T]+s.reference[N]-I.mainAxis;S<h?S=h:S>C&&(S=C)}if(c){var p,O;const N=T==="y"?"width":"height",h=kT.has(bt(o)),C=s.reference[u]-s.floating[N]+(h&&((p=a.offset)==null?void 0:p[u])||0)+(h?0:I.crossAxis),m=s.reference[u]+s.reference[N]+(h?0:((O=a.offset)==null?void 0:O[u])||0)-(h?I.crossAxis:0);A<C?A=C:A>m&&(A=m)}return{[T]:S,[u]:A}}}},LO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:a,elements:l}=t,{apply:E=()=>{},...c}=Pt(e,t),d=await a.detectOverflow(t,c),u=bt(o),T=Sr(o),S=ft(o)==="y",{width:A,height:f}=s.floating;let I,p;u==="top"||u==="bottom"?(I=u,p=T===(await(a.isRTL==null?void 0:a.isRTL(l.floating))?"start":"end")?"left":"right"):(p=u,I=T==="end"?"top":"bottom");const O=f-d.top-d.bottom,N=A-d.left-d.right,h=Zt(f-d[I],O),C=Zt(A-d[p],N),m=!t.middlewareData.shift;let g=h,y=C;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(y=N),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(g=O),m&&!T){const U=Ve(d.left,0),D=Ve(d.right,0),b=Ve(d.top,0),F=Ve(d.bottom,0);S?y=A-2*(U!==0||D!==0?U+D:Ve(d.left,d.right)):g=f-2*(b!==0||F!==0?b+F:Ve(d.top,d.bottom))}await E({...t,availableWidth:y,availableHeight:g});const _=await a.getDimensions(l.floating);return A!==_.width||f!==_.height?{reset:{rects:!0}}:{}}}};function Ei(){return typeof window<"u"}function Rr(e){return YT(e)?(e.nodeName||"").toLowerCase():"#document"}function Xe(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Nt(e){var t;return(t=(YT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function YT(e){return Ei()?e instanceof Node||e instanceof Xe(e).Node:!1}function at(e){return Ei()?e instanceof Element||e instanceof Xe(e).Element:!1}function Ut(e){return Ei()?e instanceof HTMLElement||e instanceof Xe(e).HTMLElement:!1}function NE(e){return!Ei()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Xe(e).ShadowRoot}function ao(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=lt(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&o!=="inline"&&o!=="contents"}function _O(e){return/^(table|td|th)$/.test(Rr(e))}function di(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const xO=/transform|translate|scale|rotate|perspective|filter/,yO=/paint|layout|strict|content/,cn=e=>!!e&&e!=="none";let oa;function rc(e){const t=at(e)?lt(e):e;return cn(t.transform)||cn(t.translate)||cn(t.scale)||cn(t.rotate)||cn(t.perspective)||!oc()&&(cn(t.backdropFilter)||cn(t.filter))||xO.test(t.willChange||"")||yO.test(t.contain||"")}function DO(e){let t=en(e);for(;Ut(t)&&!tr(t);){if(rc(t))return t;if(di(t))return null;t=en(t)}return null}function oc(){return oa==null&&(oa=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),oa}function tr(e){return/^(html|body|#document)$/.test(Rr(e))}function lt(e){return Xe(e).getComputedStyle(e)}function ui(e){return at(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function en(e){if(Rr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||NE(e)&&e.host||Nt(e);return NE(t)?t.host:t}function jT(e){const t=en(e);return tr(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ut(t)&&ao(t)?t:jT(t)}function Yr(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=jT(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),a=Xe(o);if(s){const l=Il(a);return t.concat(a,a.visualViewport||[],ao(o)?o:[],l&&n?Yr(l):[])}else return t.concat(o,Yr(o,[],n))}function Il(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function WT(e){const t=lt(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ut(e),s=o?e.offsetWidth:n,a=o?e.offsetHeight:r,l=Ds(n)!==s||Ds(r)!==a;return l&&(n=s,r=a),{width:n,height:r,$:l}}function sc(e){return at(e)?e:e.contextElement}function Kn(e){const t=sc(e);if(!Ut(t))return pt(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=WT(t);let a=(s?Ds(n.width):n.width)/r,l=(s?Ds(n.height):n.height)/o;return(!a||!Number.isFinite(a))&&(a=1),(!l||!Number.isFinite(l))&&(l=1),{x:a,y:l}}const MO=pt(0);function VT(e){const t=Xe(e);return!oc()||!t.visualViewport?MO:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function PO(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Xe(e)?!1:t}function fn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=sc(e);let a=pt(1);t&&(r?at(r)&&(a=Kn(r)):a=Kn(e));const l=PO(s,n,r)?VT(s):pt(0);let E=(o.left+l.x)/a.x,c=(o.top+l.y)/a.y,d=o.width/a.x,u=o.height/a.y;if(s){const T=Xe(s),S=r&&at(r)?Xe(r):r;let A=T,f=Il(A);for(;f&&r&&S!==A;){const I=Kn(f),p=f.getBoundingClientRect(),O=lt(f),N=p.left+(f.clientLeft+parseFloat(O.paddingLeft))*I.x,h=p.top+(f.clientTop+parseFloat(O.paddingTop))*I.y;E*=I.x,c*=I.y,d*=I.x,u*=I.y,E+=N,c+=h,A=Xe(f),f=Il(A)}}return Ps({width:d,height:u,x:E,y:c})}function Ti(e,t){const n=ui(e).scrollLeft;return t?t.left+n:fn(Nt(e)).left+n}function $T(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Ti(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function bO(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",a=Nt(r),l=t?di(t.floating):!1;if(r===a||l&&s)return n;let E={scrollLeft:0,scrollTop:0},c=pt(1);const d=pt(0),u=Ut(r);if((u||!u&&!s)&&((Rr(r)!=="body"||ao(a))&&(E=ui(r)),u)){const S=fn(r);c=Kn(r),d.x=S.x+r.clientLeft,d.y=S.y+r.clientTop}const T=a&&!u&&!s?$T(a,E):pt(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-E.scrollLeft*c.x+d.x+T.x,y:n.y*c.y-E.scrollTop*c.y+d.y+T.y}}function vO(e){return Array.from(e.getClientRects())}function UO(e){const t=Nt(e),n=ui(e),r=e.ownerDocument.body,o=Ve(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Ve(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+Ti(e);const l=-n.scrollTop;return lt(r).direction==="rtl"&&(a+=Ve(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:a,y:l}}const hE=25;function wO(e,t){const n=Xe(e),r=Nt(e),o=n.visualViewport;let s=r.clientWidth,a=r.clientHeight,l=0,E=0;if(o){s=o.width,a=o.height;const d=oc();(!d||d&&t==="fixed")&&(l=o.offsetLeft,E=o.offsetTop)}const c=Ti(r);if(c<=0){const d=r.ownerDocument,u=d.body,T=getComputedStyle(u),S=d.compatMode==="CSS1Compat"&&parseFloat(T.marginLeft)+parseFloat(T.marginRight)||0,A=Math.abs(r.clientWidth-u.clientWidth-S);A<=hE&&(s-=A)}else c<=hE&&(s+=c);return{width:s,height:a,x:l,y:E}}function BO(e,t){const n=fn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=Ut(e)?Kn(e):pt(1),a=e.clientWidth*s.x,l=e.clientHeight*s.y,E=o*s.x,c=r*s.y;return{width:a,height:l,x:E,y:c}}function mE(e,t,n){let r;if(t==="viewport")r=wO(e,n);else if(t==="document")r=UO(Nt(e));else if(at(t))r=BO(t,n);else{const o=VT(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Ps(r)}function XT(e,t){const n=en(e);return n===t||!at(n)||tr(n)?!1:lt(n).position==="fixed"||XT(n,t)}function FO(e,t){const n=t.get(e);if(n)return n;let r=Yr(e,[],!1).filter(l=>at(l)&&Rr(l)!=="body"),o=null;const s=lt(e).position==="fixed";let a=s?en(e):e;for(;at(a)&&!tr(a);){const l=lt(a),E=rc(a);!E&&l.position==="fixed"&&(o=null),(s?!E&&!o:!E&&l.position==="static"&&!!o&&(o.position==="absolute"||o.position==="fixed")||ao(a)&&!E&&XT(e,a))?r=r.filter(d=>d!==a):o=l,a=en(a)}return t.set(e,r),r}function GO(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const a=[...n==="clippingAncestors"?di(t)?[]:FO(t,this._c):[].concat(n),r],l=mE(t,a[0],o);let E=l.top,c=l.right,d=l.bottom,u=l.left;for(let T=1;T<a.length;T++){const S=mE(t,a[T],o);E=Ve(S.top,E),c=Zt(S.right,c),d=Zt(S.bottom,d),u=Ve(S.left,u)}return{width:c-u,height:d-E,x:u,y:E}}function HO(e){const{width:t,height:n}=WT(e);return{width:t,height:n}}function kO(e,t,n){const r=Ut(t),o=Nt(t),s=n==="fixed",a=fn(e,!0,s,t);let l={scrollLeft:0,scrollTop:0};const E=pt(0);function c(){E.x=Ti(o)}if(r||!r&&!s)if((Rr(t)!=="body"||ao(o))&&(l=ui(t)),r){const S=fn(t,!0,s,t);E.x=S.x+t.clientLeft,E.y=S.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?$T(o,l):pt(0),u=a.left+l.scrollLeft-E.x-d.x,T=a.top+l.scrollTop-E.y-d.y;return{x:u,y:T,width:a.width,height:a.height}}function sa(e){return lt(e).position==="static"}function CE(e,t){if(!Ut(e)||lt(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Nt(e)===n&&(n=n.ownerDocument.body),n}function KT(e,t){const n=Xe(e);if(di(e))return n;if(!Ut(e)){let o=en(e);for(;o&&!tr(o);){if(at(o)&&!sa(o))return o;o=en(o)}return n}let r=CE(e,t);for(;r&&_O(r)&&sa(r);)r=CE(r,t);return r&&tr(r)&&sa(r)&&!rc(r)?n:r||DO(e)||n}const YO=async function(e){const t=this.getOffsetParent||KT,n=this.getDimensions,r=await n(e.floating);return{reference:kO(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function jO(e){return lt(e).direction==="rtl"}const WO={convertOffsetParentRelativeRectToViewportRelativeRect:bO,getDocumentElement:Nt,getClippingRect:GO,getOffsetParent:KT,getElementRects:YO,getClientRects:vO,getDimensions:HO,getScale:Kn,isElement:at,isRTL:jO};function zT(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function VO(e,t){let n=null,r;const o=Nt(e);function s(){var l;clearTimeout(r),(l=n)==null||l.disconnect(),n=null}function a(l,E){l===void 0&&(l=!1),E===void 0&&(E=1),s();const c=e.getBoundingClientRect(),{left:d,top:u,width:T,height:S}=c;if(l||t(),!T||!S)return;const A=$o(u),f=$o(o.clientWidth-(d+T)),I=$o(o.clientHeight-(u+S)),p=$o(d),N={rootMargin:-A+"px "+-f+"px "+-I+"px "+-p+"px",threshold:Ve(0,Zt(1,E))||1};let h=!0;function C(m){const g=m[0].intersectionRatio;if(g!==E){if(!h)return a();g?a(!1,g):r=setTimeout(()=>{a(!1,1e-7)},1e3)}g===1&&!zT(c,e.getBoundingClientRect())&&a(),h=!1}try{n=new IntersectionObserver(C,{...N,root:o.ownerDocument})}catch{n=new IntersectionObserver(C,N)}n.observe(e)}return a(!0),s}function $O(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:E=!1}=r,c=sc(e),d=o||s?[...c?Yr(c):[],...t?Yr(t):[]]:[];d.forEach(p=>{o&&p.addEventListener("scroll",n,{passive:!0}),s&&p.addEventListener("resize",n)});const u=c&&l?VO(c,n):null;let T=-1,S=null;a&&(S=new ResizeObserver(p=>{let[O]=p;O&&O.target===c&&S&&t&&(S.unobserve(t),cancelAnimationFrame(T),T=requestAnimationFrame(()=>{var N;(N=S)==null||N.observe(t)})),n()}),c&&!E&&S.observe(c),t&&S.observe(t));let A,f=E?fn(e):null;E&&I();function I(){const p=fn(e);f&&!zT(f,p)&&n(),f=p,A=requestAnimationFrame(I)}return n(),()=>{var p;d.forEach(O=>{o&&O.removeEventListener("scroll",n),s&&O.removeEventListener("resize",n)}),u==null||u(),(p=S)==null||p.disconnect(),S=null,E&&cancelAnimationFrame(A)}}const XO=mO,KO=CO,zO=OO,JO=LO,qO=NO,gE=IO,QO=gO,ZO=(e,t,n)=>{const r=new Map,o={platform:WO,...n},s={...o.platform,_c:r};return pO(e,t,{...o,platform:s})};var eN=typeof document<"u",tN=function(){},fs=eN?R.useLayoutEffect:tN;function bs(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(!bs(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 s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!bs(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function JT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function LE(e,t){const n=JT(e);return Math.round(t*n)/n}function ia(e){const t=R.useRef(e);return fs(()=>{t.current=e}),t}function nN(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:a}={},transform:l=!0,whileElementsMounted:E,open:c}=e,[d,u]=R.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[T,S]=R.useState(r);bs(T,r)||S(r);const[A,f]=R.useState(null),[I,p]=R.useState(null),O=R.useCallback(v=>{v!==m.current&&(m.current=v,f(v))},[]),N=R.useCallback(v=>{v!==g.current&&(g.current=v,p(v))},[]),h=s||A,C=a||I,m=R.useRef(null),g=R.useRef(null),y=R.useRef(d),_=E!=null,U=ia(E),D=ia(o),b=ia(c),F=R.useCallback(()=>{if(!m.current||!g.current)return;const v={placement:t,strategy:n,middleware:T};D.current&&(v.platform=D.current),ZO(m.current,g.current,v).then(x=>{const B={...x,isPositioned:b.current!==!1};L.current&&!bs(y.current,B)&&(y.current=B,Zl.flushSync(()=>{u(B)}))})},[T,t,n,D,b]);fs(()=>{c===!1&&y.current.isPositioned&&(y.current.isPositioned=!1,u(v=>({...v,isPositioned:!1})))},[c]);const L=R.useRef(!1);fs(()=>(L.current=!0,()=>{L.current=!1}),[]),fs(()=>{if(h&&(m.current=h),C&&(g.current=C),h&&C){if(U.current)return U.current(h,C,F);F()}},[h,C,F,U,_]);const P=R.useMemo(()=>({reference:m,floating:g,setReference:O,setFloating:N}),[O,N]),M=R.useMemo(()=>({reference:h,floating:C}),[h,C]),w=R.useMemo(()=>{const v={position:n,left:0,top:0};if(!M.floating)return v;const x=LE(M.floating,d.x),B=LE(M.floating,d.y);return l?{...v,transform:"translate("+x+"px, "+B+"px)",...JT(M.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:x,top:B}},[n,l,M.floating,d.x,d.y]);return R.useMemo(()=>({...d,update:F,refs:P,elements:M,floatingStyles:w}),[d,F,P,M,w])}const rN=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?gE({element:r.current,padding:o}).fn(n):{}:r?gE({element:r,padding:o}).fn(n):{}}}},oN=(e,t)=>{const n=XO(e);return{name:n.name,fn:n.fn,options:[e,t]}},sN=(e,t)=>{const n=KO(e);return{name:n.name,fn:n.fn,options:[e,t]}},iN=(e,t)=>({fn:QO(e).fn,options:[e,t]}),aN=(e,t)=>{const n=zO(e);return{name:n.name,fn:n.fn,options:[e,t]}},lN=(e,t)=>{const n=JO(e);return{name:n.name,fn:n.fn,options:[e,t]}},cN=(e,t)=>{const n=qO(e);return{name:n.name,fn:n.fn,options:[e,t]}},EN=(e,t)=>{const n=rN(e);return{name:n.name,fn:n.fn,options:[e,t]}};var dN="Arrow",qT=R.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return i.jsx(Oe.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:i.jsx("polygon",{points:"0,0 30,0 15,10"})})});qT.displayName=dN;var uN=qT;function TN(e){const[t,n]=R.useState(void 0);return Qt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let a,l;if("borderBoxSize"in s){const E=s.borderBoxSize,c=Array.isArray(E)?E[0]:E;a=c.inlineSize,l=c.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 ic="Popper",[QT,fr]=on(ic),[SN,ZT]=QT(ic),eS=e=>{const{__scopePopper:t,children:n}=e,[r,o]=R.useState(null);return i.jsx(SN,{scope:t,anchor:r,onAnchorChange:o,children:n})};eS.displayName=ic;var tS="PopperAnchor",nS=R.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=ZT(tS,n),a=R.useRef(null),l=Ce(t,a),E=R.useRef(null);return R.useEffect(()=>{const c=E.current;E.current=(r==null?void 0:r.current)||a.current,c!==E.current&&s.onAnchorChange(E.current)}),r?null:i.jsx(Oe.div,{...o,ref:l})});nS.displayName=tS;var ac="PopperContent",[RN,fN]=QT(ac),rS=R.forwardRef((e,t)=>{var Z,$,z,ce,se,V;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:a=0,arrowPadding:l=0,avoidCollisions:E=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:u="partial",hideWhenDetached:T=!1,updatePositionStrategy:S="optimized",onPlaced:A,...f}=e,I=ZT(ac,n),[p,O]=R.useState(null),N=Ce(t,J=>O(J)),[h,C]=R.useState(null),m=TN(h),g=(m==null?void 0:m.width)??0,y=(m==null?void 0:m.height)??0,_=r+(s!=="center"?"-"+s:""),U=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},D=Array.isArray(c)?c:[c],b=D.length>0,F={padding:U,boundary:D.filter(pN),altBoundary:b},{refs:L,floatingStyles:P,placement:M,isPositioned:w,middlewareData:v}=nN({strategy:"fixed",placement:_,whileElementsMounted:(...J)=>$O(...J,{animationFrame:S==="always"}),elements:{reference:I.anchor},middleware:[oN({mainAxis:o+y,alignmentAxis:a}),E&&sN({mainAxis:!0,crossAxis:!1,limiter:u==="partial"?iN():void 0,...F}),E&&aN({...F}),lN({...F,apply:({elements:J,rects:Ee,availableWidth:Ae,availableHeight:ue})=>{const{width:Re,height:He}=Ee.reference,Pe=J.floating.style;Pe.setProperty("--radix-popper-available-width",`${Ae}px`),Pe.setProperty("--radix-popper-available-height",`${ue}px`),Pe.setProperty("--radix-popper-anchor-width",`${Re}px`),Pe.setProperty("--radix-popper-anchor-height",`${He}px`)}}),h&&EN({element:h,padding:l}),IN({arrowWidth:g,arrowHeight:y}),T&&cN({strategy:"referenceHidden",...F})]}),[x,B]=iS(M),H=qt(A);Qt(()=>{w&&(H==null||H())},[w,H]);const Y=(Z=v.arrow)==null?void 0:Z.x,K=($=v.arrow)==null?void 0:$.y,X=((z=v.arrow)==null?void 0:z.centerOffset)!==0,[q,ee]=R.useState();return Qt(()=>{p&&ee(window.getComputedStyle(p).zIndex)},[p]),i.jsx("div",{ref:L.setFloating,"data-radix-popper-content-wrapper":"",style:{...P,transform:w?P.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:q,"--radix-popper-transform-origin":[(ce=v.transformOrigin)==null?void 0:ce.x,(se=v.transformOrigin)==null?void 0:se.y].join(" "),...((V=v.hide)==null?void 0:V.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:i.jsx(RN,{scope:n,placedSide:x,onArrowChange:C,arrowX:Y,arrowY:K,shouldHideArrow:X,children:i.jsx(Oe.div,{"data-side":x,"data-align":B,...f,ref:N,style:{...f.style,animation:w?void 0:"none"}})})})});rS.displayName=ac;var oS="PopperArrow",AN={top:"bottom",right:"left",bottom:"top",left:"right"},sS=R.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=fN(oS,r),a=AN[s.placedSide];return i.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:i.jsx(uN,{...o,ref:n,style:{...o.style,display:"block"}})})});sS.displayName=oS;function pN(e){return e!==null}var IN=e=>({name:"transformOrigin",options:e,fn(t){var I,p,O;const{placement:n,rects:r,middlewareData:o}=t,a=((I=o.arrow)==null?void 0:I.centerOffset)!==0,l=a?0:e.arrowWidth,E=a?0:e.arrowHeight,[c,d]=iS(n),u={start:"0%",center:"50%",end:"100%"}[d],T=(((p=o.arrow)==null?void 0:p.x)??0)+l/2,S=(((O=o.arrow)==null?void 0:O.y)??0)+E/2;let A="",f="";return c==="bottom"?(A=a?u:`${T}px`,f=`${-E}px`):c==="top"?(A=a?u:`${T}px`,f=`${r.floating.height+E}px`):c==="right"?(A=`${-E}px`,f=a?u:`${S}px`):c==="left"&&(A=`${r.floating.width+E}px`,f=a?u:`${S}px`),{data:{x:A,y:f}}}});function iS(e){const[t,n="center"]=e.split("-");return[t,n]}var ON=eS,Si=nS,lc=rS,cc=sS,NN="Portal",lo=R.forwardRef((e,t)=>{var l;const{container:n,...r}=e,[o,s]=R.useState(!1);Qt(()=>s(!0),[]);const a=n||o&&((l=globalThis==null?void 0:globalThis.document)==null?void 0:l.body);return a?WI.createPortal(i.jsx(Oe.div,{...r,ref:t}),a):null});lo.displayName=NN;function hN(e,t){return R.useReducer((n,r)=>t[n][r]??n,e)}var qe=e=>{const{present:t,children:n}=e,r=mN(t),o=typeof n=="function"?n({present:r.isPresent}):R.Children.only(n),s=Ce(r.ref,CN(o));return typeof n=="function"||r.isPresent?R.cloneElement(o,{ref:s}):null};qe.displayName="Presence";function mN(e){const[t,n]=R.useState(),r=R.useRef(null),o=R.useRef(e),s=R.useRef("none"),a=e?"mounted":"unmounted",[l,E]=hN(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return R.useEffect(()=>{const c=Xo(r.current);s.current=l==="mounted"?c:"none"},[l]),Qt(()=>{const c=r.current,d=o.current;if(d!==e){const T=s.current,S=Xo(c);e?E("MOUNT"):S==="none"||(c==null?void 0:c.display)==="none"?E("UNMOUNT"):E(d&&T!==S?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,E]),Qt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,u=S=>{const f=Xo(r.current).includes(CSS.escape(S.animationName));if(S.target===t&&f&&(E("ANIMATION_END"),!o.current)){const I=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=I)})}},T=S=>{S.target===t&&(s.current=Xo(r.current))};return t.addEventListener("animationstart",T),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",T),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else E("ANIMATION_END")},[t,E]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:R.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Xo(e){return(e==null?void 0:e.animationName)||"none"}function CN(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 gN=vT[" useInsertionEffect ".trim().toString()]||Qt;function Ec({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,a]=LN({defaultProp:t,onChange:n}),l=e!==void 0,E=l?e:o;{const d=R.useRef(e!==void 0);R.useEffect(()=>{const u=d.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.`),d.current=l},[l,r])}const c=R.useCallback(d=>{var u;if(l){const T=_N(d)?d(e):d;T!==e&&((u=a.current)==null||u.call(a,T))}else s(d)},[l,e,s,a]);return[E,c]}function LN({defaultProp:e,onChange:t}){const[n,r]=R.useState(e),o=R.useRef(n),s=R.useRef(t);return gN(()=>{s.current=t},[t]),R.useEffect(()=>{var a;o.current!==n&&((a=s.current)==null||a.call(s,n),o.current=n)},[n,o]),[n,r,s]}function _N(e){return typeof e=="function"}var xN=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"}),yN="VisuallyHidden",aS=R.forwardRef((e,t)=>i.jsx(Oe.span,{...e,ref:t,style:{...xN,...e.style}}));aS.displayName=yN;var DN=aS,[Ri]=on("Tooltip",[fr]),fi=fr(),lS="TooltipProvider",MN=700,Ol="tooltip.open",[PN,dc]=Ri(lS),cS=e=>{const{__scopeTooltip:t,delayDuration:n=MN,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:s}=e,a=R.useRef(!0),l=R.useRef(!1),E=R.useRef(0);return R.useEffect(()=>{const c=E.current;return()=>window.clearTimeout(c)},[]),i.jsx(PN,{scope:t,isOpenDelayedRef:a,delayDuration:n,onOpen:R.useCallback(()=>{window.clearTimeout(E.current),a.current=!1},[]),onClose:R.useCallback(()=>{window.clearTimeout(E.current),E.current=window.setTimeout(()=>a.current=!0,r)},[r]),isPointerInTransitRef:l,onPointerInTransitChange:R.useCallback(c=>{l.current=c},[]),disableHoverableContent:o,children:s})};cS.displayName=lS;var jr="Tooltip",[bN,co]=Ri(jr),ES=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o,onOpenChange:s,disableHoverableContent:a,delayDuration:l}=e,E=dc(jr,e.__scopeTooltip),c=fi(t),[d,u]=R.useState(null),T=wr(),S=R.useRef(0),A=a??E.disableHoverableContent,f=l??E.delayDuration,I=R.useRef(!1),[p,O]=Ec({prop:r,defaultProp:o??!1,onChange:g=>{g?(E.onOpen(),document.dispatchEvent(new CustomEvent(Ol))):E.onClose(),s==null||s(g)},caller:jr}),N=R.useMemo(()=>p?I.current?"delayed-open":"instant-open":"closed",[p]),h=R.useCallback(()=>{window.clearTimeout(S.current),S.current=0,I.current=!1,O(!0)},[O]),C=R.useCallback(()=>{window.clearTimeout(S.current),S.current=0,O(!1)},[O]),m=R.useCallback(()=>{window.clearTimeout(S.current),S.current=window.setTimeout(()=>{I.current=!0,O(!0),S.current=0},f)},[f,O]);return R.useEffect(()=>()=>{S.current&&(window.clearTimeout(S.current),S.current=0)},[]),i.jsx(ON,{...c,children:i.jsx(bN,{scope:t,contentId:T,open:p,stateAttribute:N,trigger:d,onTriggerChange:u,onTriggerEnter:R.useCallback(()=>{E.isOpenDelayedRef.current?m():h()},[E.isOpenDelayedRef,m,h]),onTriggerLeave:R.useCallback(()=>{A?C():(window.clearTimeout(S.current),S.current=0)},[C,A]),onOpen:h,onClose:C,disableHoverableContent:A,children:n})})};ES.displayName=jr;var Nl="TooltipTrigger",dS=R.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=co(Nl,n),s=dc(Nl,n),a=fi(n),l=R.useRef(null),E=Ce(t,l,o.onTriggerChange),c=R.useRef(!1),d=R.useRef(!1),u=R.useCallback(()=>c.current=!1,[]);return R.useEffect(()=>()=>document.removeEventListener("pointerup",u),[u]),i.jsx(Si,{asChild:!0,...a,children:i.jsx(Oe.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...r,ref:E,onPointerMove:ae(e.onPointerMove,T=>{T.pointerType!=="touch"&&!d.current&&!s.isPointerInTransitRef.current&&(o.onTriggerEnter(),d.current=!0)}),onPointerLeave:ae(e.onPointerLeave,()=>{o.onTriggerLeave(),d.current=!1}),onPointerDown:ae(e.onPointerDown,()=>{o.open&&o.onClose(),c.current=!0,document.addEventListener("pointerup",u,{once:!0})}),onFocus:ae(e.onFocus,()=>{c.current||o.onOpen()}),onBlur:ae(e.onBlur,o.onClose),onClick:ae(e.onClick,o.onClose)})})});dS.displayName=Nl;var uc="TooltipPortal",[vN,UN]=Ri(uc,{forceMount:void 0}),uS=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:o}=e,s=co(uc,t);return i.jsx(vN,{scope:t,forceMount:n,children:i.jsx(qe,{present:n||s.open,children:i.jsx(lo,{asChild:!0,container:o,children:r})})})};uS.displayName=uc;var nr="TooltipContent",TS=R.forwardRef((e,t)=>{const n=UN(nr,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...s}=e,a=co(nr,e.__scopeTooltip);return i.jsx(qe,{present:r||a.open,children:a.disableHoverableContent?i.jsx(SS,{side:o,...s,ref:t}):i.jsx(wN,{side:o,...s,ref:t})})}),wN=R.forwardRef((e,t)=>{const n=co(nr,e.__scopeTooltip),r=dc(nr,e.__scopeTooltip),o=R.useRef(null),s=Ce(t,o),[a,l]=R.useState(null),{trigger:E,onClose:c}=n,d=o.current,{onPointerInTransitChange:u}=r,T=R.useCallback(()=>{l(null),u(!1)},[u]),S=R.useCallback((A,f)=>{const I=A.currentTarget,p={x:A.clientX,y:A.clientY},O=kN(p,I.getBoundingClientRect()),N=YN(p,O),h=jN(f.getBoundingClientRect()),C=VN([...N,...h]);l(C),u(!0)},[u]);return R.useEffect(()=>()=>T(),[T]),R.useEffect(()=>{if(E&&d){const A=I=>S(I,d),f=I=>S(I,E);return E.addEventListener("pointerleave",A),d.addEventListener("pointerleave",f),()=>{E.removeEventListener("pointerleave",A),d.removeEventListener("pointerleave",f)}}},[E,d,S,T]),R.useEffect(()=>{if(a){const A=f=>{const I=f.target,p={x:f.clientX,y:f.clientY},O=(E==null?void 0:E.contains(I))||(d==null?void 0:d.contains(I)),N=!WN(p,a);O?T():N&&(T(),c())};return document.addEventListener("pointermove",A),()=>document.removeEventListener("pointermove",A)}},[E,d,a,c,T]),i.jsx(SS,{...e,ref:s})}),[BN,FN]=Ri(jr,{isInside:!1}),GN=$I("TooltipContent"),SS=R.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:s,onPointerDownOutside:a,...l}=e,E=co(nr,n),c=fi(n),{onClose:d}=E;return R.useEffect(()=>(document.addEventListener(Ol,d),()=>document.removeEventListener(Ol,d)),[d]),R.useEffect(()=>{if(E.trigger){const u=T=>{const S=T.target;S!=null&&S.contains(E.trigger)&&d()};return window.addEventListener("scroll",u,{capture:!0}),()=>window.removeEventListener("scroll",u,{capture:!0})}},[E.trigger,d]),i.jsx(io,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:a,onFocusOutside:u=>u.preventDefault(),onDismiss:d,children:i.jsxs(lc,{"data-state":E.stateAttribute,...c,...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:[i.jsx(GN,{children:r}),i.jsx(BN,{scope:n,isInside:!0,children:i.jsx(DN,{id:E.contentId,role:"tooltip",children:o||r})})]})})});TS.displayName=nr;var RS="TooltipArrow",HN=R.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=fi(n);return FN(RS,n).isInside?null:i.jsx(cc,{...o,...r,ref:t})});HN.displayName=RS;function kN(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),s=Math.abs(t.left-e.x);switch(Math.min(n,r,o,s)){case s:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function YN(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 jN(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 WN(e,t){const{x:n,y:r}=e;let o=!1;for(let s=0,a=t.length-1;s<t.length;a=s++){const l=t[s],E=t[a],c=l.x,d=l.y,u=E.x,T=E.y;d>r!=T>r&&n<(u-c)*(r-d)/(T-d)+c&&(o=!o)}return o}function VN(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),$N(t)}function $N(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 s=t[t.length-1],a=t[t.length-2];if((s.x-a.x)*(o.y-a.y)>=(s.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 s=n[n.length-1],a=n[n.length-2];if((s.x-a.x)*(o.y-a.y)>=(s.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 XN=cS,KN=ES,zN=dS,JN=uS,qN=TS;function QN({content:e,children:t,side:n="right",align:r="center",sideOffset:o=6,delayMs:s=200,container:a}){return i.jsxs(KN,{delayDuration:s,children:[i.jsx(zN,{asChild:!0,children:t}),i.jsx(JN,{container:a,children:i.jsx(qN,{side:n,align:r,sideOffset:o,style:{background:Te("surfaceElevated"),color:Te("textPrimary"),border:`1px solid ${Te("borderDefault")}`,borderRadius:mn.sm,padding:`${pe[1]} ${pe[2]}`,fontSize:ve.sm,boxShadow:Te("shadowMd"),zIndex:kr.tooltip,userSelect:"none"},children:e})})]})}const ZN=XN;var aa="focusScope.autoFocusOnMount",la="focusScope.autoFocusOnUnmount",_E={bubbles:!1,cancelable:!0},eh="FocusScope",Ai=R.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...a}=e,[l,E]=R.useState(null),c=qt(o),d=qt(s),u=R.useRef(null),T=Ce(t,f=>E(f)),S=R.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;R.useEffect(()=>{if(r){let f=function(N){if(S.paused||!l)return;const h=N.target;l.contains(h)?u.current=h:Vt(u.current,{select:!0})},I=function(N){if(S.paused||!l)return;const h=N.relatedTarget;h!==null&&(l.contains(h)||Vt(u.current,{select:!0}))},p=function(N){if(document.activeElement===document.body)for(const C of N)C.removedNodes.length>0&&Vt(l)};document.addEventListener("focusin",f),document.addEventListener("focusout",I);const O=new MutationObserver(p);return l&&O.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",f),document.removeEventListener("focusout",I),O.disconnect()}}},[r,l,S.paused]),R.useEffect(()=>{if(l){yE.add(S);const f=document.activeElement;if(!l.contains(f)){const p=new CustomEvent(aa,_E);l.addEventListener(aa,c),l.dispatchEvent(p),p.defaultPrevented||(th(ih(fS(l)),{select:!0}),document.activeElement===f&&Vt(l))}return()=>{l.removeEventListener(aa,c),setTimeout(()=>{const p=new CustomEvent(la,_E);l.addEventListener(la,d),l.dispatchEvent(p),p.defaultPrevented||Vt(f??document.body,{select:!0}),l.removeEventListener(la,d),yE.remove(S)},0)}}},[l,c,d,S]);const A=R.useCallback(f=>{if(!n&&!r||S.paused)return;const I=f.key==="Tab"&&!f.altKey&&!f.ctrlKey&&!f.metaKey,p=document.activeElement;if(I&&p){const O=f.currentTarget,[N,h]=nh(O);N&&h?!f.shiftKey&&p===h?(f.preventDefault(),n&&Vt(N,{select:!0})):f.shiftKey&&p===N&&(f.preventDefault(),n&&Vt(h,{select:!0})):p===O&&f.preventDefault()}},[n,r,S.paused]);return i.jsx(Oe.div,{tabIndex:-1,...a,ref:T,onKeyDown:A})});Ai.displayName=eh;function th(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Vt(r,{select:t}),document.activeElement!==n)return}function nh(e){const t=fS(e),n=xE(t,e),r=xE(t.reverse(),e);return[n,r]}function fS(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 xE(e,t){for(const n of e)if(!rh(n,{upTo:t}))return n}function rh(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 oh(e){return e instanceof HTMLInputElement&&"select"in e}function Vt(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&oh(e)&&t&&e.select()}}var yE=sh();function sh(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=DE(e,t),e.unshift(t)},remove(t){var n;e=DE(e,t),(n=e[0])==null||n.resume()}}}function DE(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function ih(e){return e.filter(t=>t.tagName!=="A")}var ca=0;function Tc(){R.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??ME()),document.body.insertAdjacentElement("beforeend",e[1]??ME()),ca++,()=>{ca===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),ca--}},[])}function ME(){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 Rt=function(){return Rt=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},Rt.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 ah(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}var As="right-scroll-bar-position",ps="width-before-scroll-bar",lh="with-scroll-bars-hidden",ch="--removed-body-scroll-bar-size";function Ea(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Eh(e,t){var n=R.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 dh=typeof window<"u"?R.useLayoutEffect:R.useEffect,PE=new WeakMap;function uh(e,t){var n=Eh(null,function(r){return e.forEach(function(o){return Ea(o,r)})});return dh(function(){var r=PE.get(n);if(r){var o=new Set(r),s=new Set(e),a=n.current;o.forEach(function(l){s.has(l)||Ea(l,null)}),s.forEach(function(l){o.has(l)||Ea(l,a)})}PE.set(n,e)},[e]),n}function Th(e){return e}function Sh(e,t){t===void 0&&(t=Th);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(s){var a=t(s,r);return n.push(a),function(){n=n.filter(function(l){return l!==a})}},assignSyncMedium:function(s){for(r=!0;n.length;){var a=n;n=[],a.forEach(s)}n={push:function(l){return s(l)},filter:function(){return n}}},assignMedium:function(s){r=!0;var a=[];if(n.length){var l=n;n=[],l.forEach(s),a=n}var E=function(){var d=a;a=[],d.forEach(s)},c=function(){return Promise.resolve().then(E)};c(),n={push:function(d){a.push(d),c()},filter:function(d){return a=a.filter(d),n}}}};return o}function Rh(e){e===void 0&&(e={});var t=Sh(null);return t.options=Rt({async:!0,ssr:!1},e),t}var pS=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 R.createElement(r,Rt({},n))};pS.isSideCarExport=!0;function fh(e,t){return e.useMedium(t),pS}var IS=Rh(),da=function(){},pi=R.forwardRef(function(e,t){var n=R.useRef(null),r=R.useState({onScrollCapture:da,onWheelCapture:da,onTouchMoveCapture:da}),o=r[0],s=r[1],a=e.forwardProps,l=e.children,E=e.className,c=e.removeScrollBar,d=e.enabled,u=e.shards,T=e.sideCar,S=e.noRelative,A=e.noIsolation,f=e.inert,I=e.allowPinchZoom,p=e.as,O=p===void 0?"div":p,N=e.gapMode,h=AS(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=T,m=uh([n,t]),g=Rt(Rt({},h),o);return R.createElement(R.Fragment,null,d&&R.createElement(C,{sideCar:IS,removeScrollBar:c,shards:u,noRelative:S,noIsolation:A,inert:f,setCallbacks:s,allowPinchZoom:!!I,lockRef:n,gapMode:N}),a?R.cloneElement(R.Children.only(l),Rt(Rt({},g),{ref:m})):R.createElement(O,Rt({},g,{className:E,ref:m}),l))});pi.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};pi.classNames={fullWidth:ps,zeroRight:As};var Ah=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function ph(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Ah();return t&&e.setAttribute("nonce",t),e}function Ih(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Oh(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Nh=function(){var e=0,t=null;return{add:function(n){e==0&&(t=ph())&&(Ih(t,n),Oh(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},hh=function(){var e=Nh();return function(t,n){R.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},OS=function(){var e=hh(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},mh={left:0,top:0,right:0,gap:0},ua=function(e){return parseInt(e||"",10)||0},Ch=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[ua(n),ua(r),ua(o)]},gh=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return mh;var t=Ch(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])}},Lh=OS(),zn="data-scroll-locked",_h=function(e,t,n,r){var o=e.left,s=e.top,a=e.right,l=e.gap;return n===void 0&&(n="margin"),`
10
+ .`.concat(lh,` {
11
+ overflow: hidden `).concat(r,`;
12
+ padding-right: `).concat(l,"px ").concat(r,`;
13
+ }
14
+ body[`).concat(zn,`] {
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(s,`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(As,` {
28
+ right: `).concat(l,"px ").concat(r,`;
29
+ }
30
+
31
+ .`).concat(ps,` {
32
+ margin-right: `).concat(l,"px ").concat(r,`;
33
+ }
34
+
35
+ .`).concat(As," .").concat(As,` {
36
+ right: 0 `).concat(r,`;
37
+ }
38
+
39
+ .`).concat(ps," .").concat(ps,` {
40
+ margin-right: 0 `).concat(r,`;
41
+ }
42
+
43
+ body[`).concat(zn,`] {
44
+ `).concat(ch,": ").concat(l,`px;
45
+ }
46
+ `)},bE=function(){var e=parseInt(document.body.getAttribute(zn)||"0",10);return isFinite(e)?e:0},xh=function(){R.useEffect(function(){return document.body.setAttribute(zn,(bE()+1).toString()),function(){var e=bE()-1;e<=0?document.body.removeAttribute(zn):document.body.setAttribute(zn,e.toString())}},[])},yh=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;xh();var s=R.useMemo(function(){return gh(o)},[o]);return R.createElement(Lh,{styles:_h(s,!t,o,n?"":"!important")})},hl=!1;if(typeof window<"u")try{var Ko=Object.defineProperty({},"passive",{get:function(){return hl=!0,!0}});window.addEventListener("test",Ko,Ko),window.removeEventListener("test",Ko,Ko)}catch{hl=!1}var vn=hl?{passive:!1}:!1,Dh=function(e){return e.tagName==="TEXTAREA"},NS=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Dh(e)&&n[t]==="visible")},Mh=function(e){return NS(e,"overflowY")},Ph=function(e){return NS(e,"overflowX")},vE=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=hS(e,r);if(o){var s=mS(e,r),a=s[1],l=s[2];if(a>l)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},bh=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},vh=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},hS=function(e,t){return e==="v"?Mh(t):Ph(t)},mS=function(e,t){return e==="v"?bh(t):vh(t)},Uh=function(e,t){return e==="h"&&t==="rtl"?-1:1},wh=function(e,t,n,r,o){var s=Uh(e,window.getComputedStyle(t).direction),a=s*r,l=n.target,E=t.contains(l),c=!1,d=a>0,u=0,T=0;do{if(!l)break;var S=mS(e,l),A=S[0],f=S[1],I=S[2],p=f-I-s*A;(A||p)&&hS(e,l)&&(u+=p,T+=A);var O=l.parentNode;l=O&&O.nodeType===Node.DOCUMENT_FRAGMENT_NODE?O.host:O}while(!E&&l!==document.body||E&&(t.contains(l)||t===l));return(d&&Math.abs(u)<1||!d&&Math.abs(T)<1)&&(c=!0),c},zo=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},UE=function(e){return[e.deltaX,e.deltaY]},wE=function(e){return e&&"current"in e?e.current:e},Bh=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Fh=function(e){return`
47
+ .block-interactivity-`.concat(e,` {pointer-events: none;}
48
+ .allow-interactivity-`).concat(e,` {pointer-events: all;}
49
+ `)},Gh=0,Un=[];function Hh(e){var t=R.useRef([]),n=R.useRef([0,0]),r=R.useRef(),o=R.useState(Gh++)[0],s=R.useState(OS)[0],a=R.useRef(e);R.useEffect(function(){a.current=e},[e]),R.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var f=ah([e.lockRef.current],(e.shards||[]).map(wE),!0).filter(Boolean);return f.forEach(function(I){return I.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),f.forEach(function(I){return I.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=R.useCallback(function(f,I){if("touches"in f&&f.touches.length===2||f.type==="wheel"&&f.ctrlKey)return!a.current.allowPinchZoom;var p=zo(f),O=n.current,N="deltaX"in f?f.deltaX:O[0]-p[0],h="deltaY"in f?f.deltaY:O[1]-p[1],C,m=f.target,g=Math.abs(N)>Math.abs(h)?"h":"v";if("touches"in f&&g==="h"&&m.type==="range")return!1;var y=window.getSelection(),_=y&&y.anchorNode,U=_?_===m||_.contains(m):!1;if(U)return!1;var D=vE(g,m);if(!D)return!0;if(D?C=g:(C=g==="v"?"h":"v",D=vE(g,m)),!D)return!1;if(!r.current&&"changedTouches"in f&&(N||h)&&(r.current=C),!C)return!0;var b=r.current||C;return wh(b,I,f,b==="h"?N:h)},[]),E=R.useCallback(function(f){var I=f;if(!(!Un.length||Un[Un.length-1]!==s)){var p="deltaY"in I?UE(I):zo(I),O=t.current.filter(function(C){return C.name===I.type&&(C.target===I.target||I.target===C.shadowParent)&&Bh(C.delta,p)})[0];if(O&&O.should){I.cancelable&&I.preventDefault();return}if(!O){var N=(a.current.shards||[]).map(wE).filter(Boolean).filter(function(C){return C.contains(I.target)}),h=N.length>0?l(I,N[0]):!a.current.noIsolation;h&&I.cancelable&&I.preventDefault()}}},[]),c=R.useCallback(function(f,I,p,O){var N={name:f,delta:I,target:p,should:O,shadowParent:kh(p)};t.current.push(N),setTimeout(function(){t.current=t.current.filter(function(h){return h!==N})},1)},[]),d=R.useCallback(function(f){n.current=zo(f),r.current=void 0},[]),u=R.useCallback(function(f){c(f.type,UE(f),f.target,l(f,e.lockRef.current))},[]),T=R.useCallback(function(f){c(f.type,zo(f),f.target,l(f,e.lockRef.current))},[]);R.useEffect(function(){return Un.push(s),e.setCallbacks({onScrollCapture:u,onWheelCapture:u,onTouchMoveCapture:T}),document.addEventListener("wheel",E,vn),document.addEventListener("touchmove",E,vn),document.addEventListener("touchstart",d,vn),function(){Un=Un.filter(function(f){return f!==s}),document.removeEventListener("wheel",E,vn),document.removeEventListener("touchmove",E,vn),document.removeEventListener("touchstart",d,vn)}},[]);var S=e.removeScrollBar,A=e.inert;return R.createElement(R.Fragment,null,A?R.createElement(s,{styles:Fh(o)}):null,S?R.createElement(yh,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function kh(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Yh=fh(IS,Hh);var Ii=R.forwardRef(function(e,t){return R.createElement(pi,Rt({},e,{ref:t,sideCar:Yh}))});Ii.classNames=pi.classNames;var jh=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},wn=new WeakMap,Jo=new WeakMap,qo={},Ta=0,CS=function(e){return e&&(e.host||CS(e.parentNode))},Wh=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=CS(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})},Vh=function(e,t,n,r){var o=Wh(t,Array.isArray(e)?e:[e]);qo[n]||(qo[n]=new WeakMap);var s=qo[n],a=[],l=new Set,E=new Set(o),c=function(u){!u||l.has(u)||(l.add(u),c(u.parentNode))};o.forEach(c);var d=function(u){!u||E.has(u)||Array.prototype.forEach.call(u.children,function(T){if(l.has(T))d(T);else try{var S=T.getAttribute(r),A=S!==null&&S!=="false",f=(wn.get(T)||0)+1,I=(s.get(T)||0)+1;wn.set(T,f),s.set(T,I),a.push(T),f===1&&A&&Jo.set(T,!0),I===1&&T.setAttribute(n,"true"),A||T.setAttribute(r,"true")}catch(p){console.error("aria-hidden: cannot operate on ",T,p)}})};return d(t),l.clear(),Ta++,function(){a.forEach(function(u){var T=wn.get(u)-1,S=s.get(u)-1;wn.set(u,T),s.set(u,S),T||(Jo.has(u)||u.removeAttribute(r),Jo.delete(u)),S||u.removeAttribute(n)}),Ta--,Ta||(wn=new WeakMap,wn=new WeakMap,Jo=new WeakMap,qo={})}},Sc=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=jh(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),Vh(r,o,n,"aria-hidden")):function(){return null}},Oi="Dialog",[gS]=on(Oi),[$h,ct]=gS(Oi),LS=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:s,modal:a=!0}=e,l=R.useRef(null),E=R.useRef(null),[c,d]=Ec({prop:r,defaultProp:o??!1,onChange:s,caller:Oi});return i.jsx($h,{scope:t,triggerRef:l,contentRef:E,contentId:wr(),titleId:wr(),descriptionId:wr(),open:c,onOpenChange:d,onOpenToggle:R.useCallback(()=>d(u=>!u),[d]),modal:a,children:n})};LS.displayName=Oi;var _S="DialogTrigger",Xh=R.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ct(_S,n),s=Ce(t,o.triggerRef);return i.jsx(Oe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ac(o.open),...r,ref:s,onClick:ae(e.onClick,o.onOpenToggle)})});Xh.displayName=_S;var Rc="DialogPortal",[Kh,xS]=gS(Rc,{forceMount:void 0}),yS=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,s=ct(Rc,t);return i.jsx(Kh,{scope:t,forceMount:n,children:R.Children.map(r,a=>i.jsx(qe,{present:n||s.open,children:i.jsx(lo,{asChild:!0,container:o,children:a})}))})};yS.displayName=Rc;var vs="DialogOverlay",DS=R.forwardRef((e,t)=>{const n=xS(vs,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=ct(vs,e.__scopeDialog);return s.modal?i.jsx(qe,{present:r||s.open,children:i.jsx(Jh,{...o,ref:t})}):null});DS.displayName=vs;var zh=er("DialogOverlay.RemoveScroll"),Jh=R.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ct(vs,n);return i.jsx(Ii,{as:zh,allowPinchZoom:!0,shards:[o.contentRef],children:i.jsx(Oe.div,{"data-state":Ac(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),An="DialogContent",MS=R.forwardRef((e,t)=>{const n=xS(An,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=ct(An,e.__scopeDialog);return i.jsx(qe,{present:r||s.open,children:s.modal?i.jsx(qh,{...o,ref:t}):i.jsx(Qh,{...o,ref:t})})});MS.displayName=An;var qh=R.forwardRef((e,t)=>{const n=ct(An,e.__scopeDialog),r=R.useRef(null),o=Ce(t,n.contentRef,r);return R.useEffect(()=>{const s=r.current;if(s)return Sc(s)},[]),i.jsx(PS,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ae(e.onCloseAutoFocus,s=>{var a;s.preventDefault(),(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:ae(e.onPointerDownOutside,s=>{const a=s.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0;(a.button===2||l)&&s.preventDefault()}),onFocusOutside:ae(e.onFocusOutside,s=>s.preventDefault())})}),Qh=R.forwardRef((e,t)=>{const n=ct(An,e.__scopeDialog),r=R.useRef(!1),o=R.useRef(!1);return i.jsx(PS,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var a,l;(a=e.onCloseAutoFocus)==null||a.call(e,s),s.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),s.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:s=>{var E,c;(E=e.onInteractOutside)==null||E.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const a=s.target;((c=n.triggerRef.current)==null?void 0:c.contains(a))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),PS=R.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,...a}=e,l=ct(An,n),E=R.useRef(null),c=Ce(t,E);return Tc(),i.jsxs(i.Fragment,{children:[i.jsx(Ai,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:i.jsx(io,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Ac(l.open),...a,ref:c,onDismiss:()=>l.onOpenChange(!1)})}),i.jsxs(i.Fragment,{children:[i.jsx(tm,{titleId:l.titleId}),i.jsx(rm,{contentRef:E,descriptionId:l.descriptionId})]})]})}),fc="DialogTitle",bS=R.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ct(fc,n);return i.jsx(Oe.h2,{id:o.titleId,...r,ref:t})});bS.displayName=fc;var vS="DialogDescription",Zh=R.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ct(vS,n);return i.jsx(Oe.p,{id:o.descriptionId,...r,ref:t})});Zh.displayName=vS;var US="DialogClose",em=R.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ct(US,n);return i.jsx(Oe.button,{type:"button",...r,ref:t,onClick:ae(e.onClick,()=>o.onOpenChange(!1))})});em.displayName=US;function Ac(e){return e?"open":"closed"}var wS="DialogTitleWarning",[Hk,BS]=YI(wS,{contentName:An,titleName:fc,docsSlug:"dialog"}),tm=({titleId:e})=>{const t=BS(wS),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 R.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},nm="DialogDescriptionWarning",rm=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${BS(nm).contentName}}.`;return R.useEffect(()=>{var s;const o=(s=e.current)==null?void 0:s.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},om=LS,sm=yS,im=DS,am=MS,lm=bS;function FS(e){const t=e+"CollectionProvider",[n,r]=on(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),a=f=>{const{scope:I,children:p}=f,O=me.useRef(null),N=me.useRef(new Map).current;return i.jsx(o,{scope:I,itemMap:N,collectionRef:O,children:p})};a.displayName=t;const l=e+"CollectionSlot",E=er(l),c=me.forwardRef((f,I)=>{const{scope:p,children:O}=f,N=s(l,p),h=Ce(I,N.collectionRef);return i.jsx(E,{ref:h,children:O})});c.displayName=l;const d=e+"CollectionItemSlot",u="data-radix-collection-item",T=er(d),S=me.forwardRef((f,I)=>{const{scope:p,children:O,...N}=f,h=me.useRef(null),C=Ce(I,h),m=s(d,p);return me.useEffect(()=>(m.itemMap.set(h,{ref:h,...N}),()=>void m.itemMap.delete(h))),i.jsx(T,{[u]:"",ref:C,children:O})});S.displayName=d;function A(f){const I=s(e+"CollectionConsumer",f);return me.useCallback(()=>{const O=I.collectionRef.current;if(!O)return[];const N=Array.from(O.querySelectorAll(`[${u}]`));return Array.from(I.itemMap.values()).sort((m,g)=>N.indexOf(m.ref.current)-N.indexOf(g.ref.current))},[I.collectionRef,I.itemMap])}return[{Provider:a,Slot:c,ItemSlot:S},A,r]}var cm=R.createContext(void 0);function Em(e){const t=R.useContext(cm);return e||t||"ltr"}var Sa="rovingFocusGroup.onEntryFocus",dm={bubbles:!1,cancelable:!0},Eo="RovingFocusGroup",[ml,GS,um]=FS(Eo),[Tm,HS]=on(Eo,[um]),[Sm,Rm]=Tm(Eo),kS=R.forwardRef((e,t)=>i.jsx(ml.Provider,{scope:e.__scopeRovingFocusGroup,children:i.jsx(ml.Slot,{scope:e.__scopeRovingFocusGroup,children:i.jsx(fm,{...e,ref:t})})}));kS.displayName=Eo;var fm=R.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:a,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:E,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...u}=e,T=R.useRef(null),S=Ce(t,T),A=Em(s),[f,I]=Ec({prop:a,defaultProp:l??null,onChange:E,caller:Eo}),[p,O]=R.useState(!1),N=qt(c),h=GS(n),C=R.useRef(!1),[m,g]=R.useState(0);return R.useEffect(()=>{const y=T.current;if(y)return y.addEventListener(Sa,N),()=>y.removeEventListener(Sa,N)},[N]),i.jsx(Sm,{scope:n,orientation:r,dir:A,loop:o,currentTabStopId:f,onItemFocus:R.useCallback(y=>I(y),[I]),onItemShiftTab:R.useCallback(()=>O(!0),[]),onFocusableItemAdd:R.useCallback(()=>g(y=>y+1),[]),onFocusableItemRemove:R.useCallback(()=>g(y=>y-1),[]),children:i.jsx(Oe.div,{tabIndex:p||m===0?-1:0,"data-orientation":r,...u,ref:S,style:{outline:"none",...e.style},onMouseDown:ae(e.onMouseDown,()=>{C.current=!0}),onFocus:ae(e.onFocus,y=>{const _=!C.current;if(y.target===y.currentTarget&&_&&!p){const U=new CustomEvent(Sa,dm);if(y.currentTarget.dispatchEvent(U),!U.defaultPrevented){const D=h().filter(M=>M.focusable),b=D.find(M=>M.active),F=D.find(M=>M.id===f),P=[b,F,...D].filter(Boolean).map(M=>M.ref.current);WS(P,d)}}C.current=!1}),onBlur:ae(e.onBlur,()=>O(!1))})})}),YS="RovingFocusGroupItem",jS=R.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:a,...l}=e,E=wr(),c=s||E,d=Rm(YS,n),u=d.currentTabStopId===c,T=GS(n),{onFocusableItemAdd:S,onFocusableItemRemove:A,currentTabStopId:f}=d;return R.useEffect(()=>{if(r)return S(),()=>A()},[r,S,A]),i.jsx(ml.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:i.jsx(Oe.span,{tabIndex:u?0:-1,"data-orientation":d.orientation,...l,ref:t,onMouseDown:ae(e.onMouseDown,I=>{r?d.onItemFocus(c):I.preventDefault()}),onFocus:ae(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:ae(e.onKeyDown,I=>{if(I.key==="Tab"&&I.shiftKey){d.onItemShiftTab();return}if(I.target!==I.currentTarget)return;const p=Im(I,d.orientation,d.dir);if(p!==void 0){if(I.metaKey||I.ctrlKey||I.altKey||I.shiftKey)return;I.preventDefault();let N=T().filter(h=>h.focusable).map(h=>h.ref.current);if(p==="last")N.reverse();else if(p==="prev"||p==="next"){p==="prev"&&N.reverse();const h=N.indexOf(I.currentTarget);N=d.loop?Om(N,h+1):N.slice(h+1)}setTimeout(()=>WS(N))}}),children:typeof a=="function"?a({isCurrentTabStop:u,hasTabStop:f!=null}):a})})});jS.displayName=YS;var Am={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function pm(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Im(e,t,n){const r=pm(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Am[r]}function WS(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Om(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Nm=kS,hm=jS,Cl=["Enter"," "],mm=["ArrowDown","PageUp","Home"],VS=["ArrowUp","PageDown","End"],Cm=[...mm,...VS],gm={ltr:[...Cl,"ArrowRight"],rtl:[...Cl,"ArrowLeft"]},Lm={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Ni="Menu",[Wr,_m,xm]=FS(Ni),[Cn,$S]=on(Ni,[xm,fr,HS]),pc=fr(),XS=HS(),[kk,gn]=Cn(Ni),[Yk,uo]=Cn(Ni),ym="MenuAnchor",Ic=R.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=pc(n);return i.jsx(Si,{...o,...r,ref:t})});Ic.displayName=ym;var Oc="MenuPortal",[Dm,KS]=Cn(Oc,{forceMount:void 0}),zS=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,s=gn(Oc,t);return i.jsx(Dm,{scope:t,forceMount:n,children:i.jsx(qe,{present:n||s.open,children:i.jsx(lo,{asChild:!0,container:o,children:r})})})};zS.displayName=Oc;var Je="MenuContent",[Mm,Nc]=Cn(Je),JS=R.forwardRef((e,t)=>{const n=KS(Je,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=gn(Je,e.__scopeMenu),a=uo(Je,e.__scopeMenu);return i.jsx(Wr.Provider,{scope:e.__scopeMenu,children:i.jsx(qe,{present:r||s.open,children:i.jsx(Wr.Slot,{scope:e.__scopeMenu,children:a.modal?i.jsx(Pm,{...o,ref:t}):i.jsx(bm,{...o,ref:t})})})})}),Pm=R.forwardRef((e,t)=>{const n=gn(Je,e.__scopeMenu),r=R.useRef(null),o=Ce(t,r);return R.useEffect(()=>{const s=r.current;if(s)return Sc(s)},[]),i.jsx(hc,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ae(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),bm=R.forwardRef((e,t)=>{const n=gn(Je,e.__scopeMenu);return i.jsx(hc,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),vm=er("MenuContent.ScrollLock"),hc=R.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:s,onCloseAutoFocus:a,disableOutsidePointerEvents:l,onEntryFocus:E,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:T,onDismiss:S,disableOutsideScroll:A,...f}=e,I=gn(Je,n),p=uo(Je,n),O=pc(n),N=XS(n),h=_m(n),[C,m]=R.useState(null),g=R.useRef(null),y=Ce(t,g,I.onContentChange),_=R.useRef(0),U=R.useRef(""),D=R.useRef(0),b=R.useRef(null),F=R.useRef("right"),L=R.useRef(0),P=A?Ii:R.Fragment,M=A?{as:vm,allowPinchZoom:!0}:void 0,w=x=>{var Z,$;const B=U.current+x,H=h().filter(z=>!z.disabled),Y=document.activeElement,K=(Z=H.find(z=>z.ref.current===Y))==null?void 0:Z.textValue,X=H.map(z=>z.textValue),q=$m(X,B,K),ee=($=H.find(z=>z.textValue===q))==null?void 0:$.ref.current;(function z(ce){U.current=ce,window.clearTimeout(_.current),ce!==""&&(_.current=window.setTimeout(()=>z(""),1e3))})(B),ee&&setTimeout(()=>ee.focus())};R.useEffect(()=>()=>window.clearTimeout(_.current),[]),Tc();const v=R.useCallback(x=>{var H,Y;return F.current===((H=b.current)==null?void 0:H.side)&&Km(x,(Y=b.current)==null?void 0:Y.area)},[]);return i.jsx(Mm,{scope:n,searchRef:U,onItemEnter:R.useCallback(x=>{v(x)&&x.preventDefault()},[v]),onItemLeave:R.useCallback(x=>{var B;v(x)||((B=g.current)==null||B.focus(),m(null))},[v]),onTriggerLeave:R.useCallback(x=>{v(x)&&x.preventDefault()},[v]),pointerGraceTimerRef:D,onPointerGraceIntentChange:R.useCallback(x=>{b.current=x},[]),children:i.jsx(P,{...M,children:i.jsx(Ai,{asChild:!0,trapped:o,onMountAutoFocus:ae(s,x=>{var B;x.preventDefault(),(B=g.current)==null||B.focus({preventScroll:!0})}),onUnmountAutoFocus:a,children:i.jsx(io,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:T,onDismiss:S,children:i.jsx(Nm,{asChild:!0,...N,dir:p.dir,orientation:"vertical",loop:r,currentTabStopId:C,onCurrentTabStopIdChange:m,onEntryFocus:ae(E,x=>{p.isUsingKeyboardRef.current||x.preventDefault()}),preventScrollOnEntryFocus:!0,children:i.jsx(lc,{role:"menu","aria-orientation":"vertical","data-state":uR(I.open),"data-radix-menu-content":"",dir:p.dir,...O,...f,ref:y,style:{outline:"none",...f.style},onKeyDown:ae(f.onKeyDown,x=>{const H=x.target.closest("[data-radix-menu-content]")===x.currentTarget,Y=x.ctrlKey||x.altKey||x.metaKey,K=x.key.length===1;H&&(x.key==="Tab"&&x.preventDefault(),!Y&&K&&w(x.key));const X=g.current;if(x.target!==X||!Cm.includes(x.key))return;x.preventDefault();const ee=h().filter(Z=>!Z.disabled).map(Z=>Z.ref.current);VS.includes(x.key)&&ee.reverse(),Wm(ee)}),onBlur:ae(e.onBlur,x=>{x.currentTarget.contains(x.target)||(window.clearTimeout(_.current),U.current="")}),onPointerMove:ae(e.onPointerMove,Vr(x=>{const B=x.target,H=L.current!==x.clientX;if(x.currentTarget.contains(B)&&H){const Y=x.clientX>L.current?"right":"left";F.current=Y,L.current=x.clientX}}))})})})})})})});JS.displayName=Je;var Um="MenuGroup",mc=R.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return i.jsx(Oe.div,{role:"group",...r,ref:t})});mc.displayName=Um;var wm="MenuLabel",qS=R.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return i.jsx(Oe.div,{...r,ref:t})});qS.displayName=wm;var Us="MenuItem",BE="menu.itemSelect",hi=R.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,s=R.useRef(null),a=uo(Us,e.__scopeMenu),l=Nc(Us,e.__scopeMenu),E=Ce(t,s),c=R.useRef(!1),d=()=>{const u=s.current;if(!n&&u){const T=new CustomEvent(BE,{bubbles:!0,cancelable:!0});u.addEventListener(BE,S=>r==null?void 0:r(S),{once:!0}),BT(u,T),T.defaultPrevented?c.current=!1:a.onClose()}};return i.jsx(QS,{...o,ref:E,disabled:n,onClick:ae(e.onClick,d),onPointerDown:u=>{var T;(T=e.onPointerDown)==null||T.call(e,u),c.current=!0},onPointerUp:ae(e.onPointerUp,u=>{var T;c.current||(T=u.currentTarget)==null||T.click()}),onKeyDown:ae(e.onKeyDown,u=>{const T=l.searchRef.current!=="";n||T&&u.key===" "||Cl.includes(u.key)&&(u.currentTarget.click(),u.preventDefault())})})});hi.displayName=Us;var QS=R.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...s}=e,a=Nc(Us,n),l=XS(n),E=R.useRef(null),c=Ce(t,E),[d,u]=R.useState(!1),[T,S]=R.useState("");return R.useEffect(()=>{const A=E.current;A&&S((A.textContent??"").trim())},[s.children]),i.jsx(Wr.ItemSlot,{scope:n,disabled:r,textValue:o??T,children:i.jsx(hm,{asChild:!0,...l,focusable:!r,children:i.jsx(Oe.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:c,onPointerMove:ae(e.onPointerMove,Vr(A=>{r?a.onItemLeave(A):(a.onItemEnter(A),A.defaultPrevented||A.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:ae(e.onPointerLeave,Vr(A=>a.onItemLeave(A))),onFocus:ae(e.onFocus,()=>u(!0)),onBlur:ae(e.onBlur,()=>u(!1))})})})}),Bm="MenuCheckboxItem",ZS=R.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return i.jsx(oR,{scope:e.__scopeMenu,checked:n,children:i.jsx(hi,{role:"menuitemcheckbox","aria-checked":ws(n)?"mixed":n,...o,ref:t,"data-state":gc(n),onSelect:ae(o.onSelect,()=>r==null?void 0:r(ws(n)?!0:!n),{checkForDefaultPrevented:!1})})})});ZS.displayName=Bm;var eR="MenuRadioGroup",[Fm,Gm]=Cn(eR,{value:void 0,onValueChange:()=>{}}),tR=R.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,s=qt(r);return i.jsx(Fm,{scope:e.__scopeMenu,value:n,onValueChange:s,children:i.jsx(mc,{...o,ref:t})})});tR.displayName=eR;var nR="MenuRadioItem",rR=R.forwardRef((e,t)=>{const{value:n,...r}=e,o=Gm(nR,e.__scopeMenu),s=n===o.value;return i.jsx(oR,{scope:e.__scopeMenu,checked:s,children:i.jsx(hi,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":gc(s),onSelect:ae(r.onSelect,()=>{var a;return(a=o.onValueChange)==null?void 0:a.call(o,n)},{checkForDefaultPrevented:!1})})})});rR.displayName=nR;var Cc="MenuItemIndicator",[oR,Hm]=Cn(Cc,{checked:!1}),sR=R.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,s=Hm(Cc,n);return i.jsx(qe,{present:r||ws(s.checked)||s.checked===!0,children:i.jsx(Oe.span,{...o,ref:t,"data-state":gc(s.checked)})})});sR.displayName=Cc;var km="MenuSeparator",iR=R.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return i.jsx(Oe.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});iR.displayName=km;var Ym="MenuArrow",aR=R.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=pc(n);return i.jsx(cc,{...o,...r,ref:t})});aR.displayName=Ym;var jm="MenuSub",[jk,lR]=Cn(jm),Pr="MenuSubTrigger",cR=R.forwardRef((e,t)=>{const n=gn(Pr,e.__scopeMenu),r=uo(Pr,e.__scopeMenu),o=lR(Pr,e.__scopeMenu),s=Nc(Pr,e.__scopeMenu),a=R.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:E}=s,c={__scopeMenu:e.__scopeMenu},d=R.useCallback(()=>{a.current&&window.clearTimeout(a.current),a.current=null},[]);return R.useEffect(()=>d,[d]),R.useEffect(()=>{const u=l.current;return()=>{window.clearTimeout(u),E(null)}},[l,E]),i.jsx(Ic,{asChild:!0,...c,children:i.jsx(QS,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":uR(n.open),...e,ref:ci(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:ae(e.onPointerMove,Vr(u=>{s.onItemEnter(u),!u.defaultPrevented&&!e.disabled&&!n.open&&!a.current&&(s.onPointerGraceIntentChange(null),a.current=window.setTimeout(()=>{n.onOpenChange(!0),d()},100))})),onPointerLeave:ae(e.onPointerLeave,Vr(u=>{var S,A;d();const T=(S=n.content)==null?void 0:S.getBoundingClientRect();if(T){const f=(A=n.content)==null?void 0:A.dataset.side,I=f==="right",p=I?-5:5,O=T[I?"left":"right"],N=T[I?"right":"left"];s.onPointerGraceIntentChange({area:[{x:u.clientX+p,y:u.clientY},{x:O,y:T.top},{x:N,y:T.top},{x:N,y:T.bottom},{x:O,y:T.bottom}],side:f}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(u),u.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:ae(e.onKeyDown,u=>{var S;const T=s.searchRef.current!=="";e.disabled||T&&u.key===" "||gm[r.dir].includes(u.key)&&(n.onOpenChange(!0),(S=n.content)==null||S.focus(),u.preventDefault())})})})});cR.displayName=Pr;var ER="MenuSubContent",dR=R.forwardRef((e,t)=>{const n=KS(Je,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=gn(Je,e.__scopeMenu),a=uo(Je,e.__scopeMenu),l=lR(ER,e.__scopeMenu),E=R.useRef(null),c=Ce(t,E);return i.jsx(Wr.Provider,{scope:e.__scopeMenu,children:i.jsx(qe,{present:r||s.open,children:i.jsx(Wr.Slot,{scope:e.__scopeMenu,children:i.jsx(hc,{id:l.contentId,"aria-labelledby":l.triggerId,...o,ref:c,align:"start",side:a.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:d=>{var u;a.isUsingKeyboardRef.current&&((u=E.current)==null||u.focus()),d.preventDefault()},onCloseAutoFocus:d=>d.preventDefault(),onFocusOutside:ae(e.onFocusOutside,d=>{d.target!==l.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:ae(e.onEscapeKeyDown,d=>{a.onClose(),d.preventDefault()}),onKeyDown:ae(e.onKeyDown,d=>{var S;const u=d.currentTarget.contains(d.target),T=Lm[a.dir].includes(d.key);u&&T&&(s.onOpenChange(!1),(S=l.trigger)==null||S.focus(),d.preventDefault())})})})})})});dR.displayName=ER;function uR(e){return e?"open":"closed"}function ws(e){return e==="indeterminate"}function gc(e){return ws(e)?"indeterminate":e?"checked":"unchecked"}function Wm(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Vm(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function $m(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let a=Vm(e,Math.max(s,0));o.length===1&&(a=a.filter(c=>c!==n));const E=a.find(c=>c.toLowerCase().startsWith(o.toLowerCase()));return E!==n?E:void 0}function Xm(e,t){const{x:n,y:r}=e;let o=!1;for(let s=0,a=t.length-1;s<t.length;a=s++){const l=t[s],E=t[a],c=l.x,d=l.y,u=E.x,T=E.y;d>r!=T>r&&n<(u-c)*(r-d)/(T-d)+c&&(o=!o)}return o}function Km(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Xm(n,t)}function Vr(e){return t=>t.pointerType==="mouse"?e(t):void 0}var zm=Ic,Jm=zS,qm=JS,Qm=mc,Zm=qS,eC=hi,tC=ZS,nC=tR,rC=rR,oC=sR,sC=iR,iC=aR,aC=cR,lC=dR,TR="DropdownMenu",[cC]=on(TR,[$S]),Ge=$S(),[Wk,SR]=cC(TR),RR="DropdownMenuTrigger",EC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,s=SR(RR,n),a=Ge(n);return i.jsx(zm,{asChild:!0,...a,children:i.jsx(Oe.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...o,ref:ci(t,s.triggerRef),onPointerDown:ae(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(s.onOpenToggle(),s.open||l.preventDefault())}),onKeyDown:ae(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&s.onOpenToggle(),l.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});EC.displayName=RR;var dC="DropdownMenuPortal",fR=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Ge(t);return i.jsx(Jm,{...r,...n})};fR.displayName=dC;var AR="DropdownMenuContent",pR=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=SR(AR,n),s=Ge(n),a=R.useRef(!1);return i.jsx(qm,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...r,ref:t,onCloseAutoFocus:ae(e.onCloseAutoFocus,l=>{var E;a.current||(E=o.triggerRef.current)==null||E.focus(),a.current=!1,l.preventDefault()}),onInteractOutside:ae(e.onInteractOutside,l=>{const E=l.detail.originalEvent,c=E.button===0&&E.ctrlKey===!0,d=E.button===2||c;(!o.modal||d)&&(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)"}})});pR.displayName=AR;var uC="DropdownMenuGroup",TC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return i.jsx(Qm,{...o,...r,ref:t})});TC.displayName=uC;var SC="DropdownMenuLabel",IR=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return i.jsx(Zm,{...o,...r,ref:t})});IR.displayName=SC;var RC="DropdownMenuItem",NR=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return i.jsx(eC,{...o,...r,ref:t})});NR.displayName=RC;var fC="DropdownMenuCheckboxItem",AC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return i.jsx(tC,{...o,...r,ref:t})});AC.displayName=fC;var pC="DropdownMenuRadioGroup",IC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return i.jsx(nC,{...o,...r,ref:t})});IC.displayName=pC;var OC="DropdownMenuRadioItem",NC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return i.jsx(rC,{...o,...r,ref:t})});NC.displayName=OC;var hC="DropdownMenuItemIndicator",mC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return i.jsx(oC,{...o,...r,ref:t})});mC.displayName=hC;var CC="DropdownMenuSeparator",hR=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return i.jsx(sC,{...o,...r,ref:t})});hR.displayName=CC;var gC="DropdownMenuArrow",LC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return i.jsx(iC,{...o,...r,ref:t})});LC.displayName=gC;var _C="DropdownMenuSubTrigger",xC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return i.jsx(aC,{...o,...r,ref:t})});xC.displayName=_C;var yC="DropdownMenuSubContent",DC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return i.jsx(lC,{...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)"}})});DC.displayName=yC;var MC=fR,PC=pR,bC=IR,vC=NR,UC=hR;const wC=R.forwardRef(({container:e,style:t,sideOffset:n=4,...r},o)=>i.jsx(MC,{container:e,children:i.jsx(PC,{ref:o,sideOffset:n,style:{minWidth:180,background:Te("surfaceElevated"),color:Te("textPrimary"),border:`1px solid ${Te("borderDefault")}`,borderRadius:mn.md,boxShadow:Te("shadowMd"),padding:pe[1],zIndex:kr.popover,...t},...r})}));wC.displayName="DropdownMenuContent";const BC=R.forwardRef(({style:e,...t},n)=>i.jsx(vC,{ref:n,style:{display:"flex",alignItems:"center",gap:pe[2],padding:`${pe[1]} ${pe[2]}`,fontSize:ve.sm,borderRadius:mn.sm,cursor:"default",outline:"none",userSelect:"none",...e},...t}));BC.displayName="DropdownMenuItem";const FC=R.forwardRef(({style:e,...t},n)=>i.jsx(UC,{ref:n,style:{height:1,background:Te("borderSubtle"),margin:`${pe[1]} 0`,...e},...t}));FC.displayName="DropdownMenuSeparator";const GC=R.forwardRef(({style:e,...t},n)=>i.jsx(bC,{ref:n,style:{padding:`${pe[1]} ${pe[2]}`,fontSize:ve.xs,color:Te("textMuted"),textTransform:"uppercase",letterSpacing:"0.04em",...e},...t}));GC.displayName="DropdownMenuLabel";var mR="Popover",[CR]=on(mR,[fr]),mi=fr(),[Vk,sn]=CR(mR),gR="PopoverAnchor",HC=R.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=sn(gR,n),s=mi(n),{onCustomAnchorAdd:a,onCustomAnchorRemove:l}=o;return R.useEffect(()=>(a(),()=>l()),[a,l]),i.jsx(Si,{...s,...r,ref:t})});HC.displayName=gR;var LR="PopoverTrigger",kC=R.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=sn(LR,n),s=mi(n),a=Ce(t,o.triggerRef),l=i.jsx(Oe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":MR(o.open),...r,ref:a,onClick:ae(e.onClick,o.onOpenToggle)});return o.hasCustomAnchor?l:i.jsx(Si,{asChild:!0,...s,children:l})});kC.displayName=LR;var Lc="PopoverPortal",[YC,jC]=CR(Lc,{forceMount:void 0}),_R=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,s=sn(Lc,t);return i.jsx(YC,{scope:t,forceMount:n,children:i.jsx(qe,{present:n||s.open,children:i.jsx(lo,{asChild:!0,container:o,children:r})})})};_R.displayName=Lc;var rr="PopoverContent",xR=R.forwardRef((e,t)=>{const n=jC(rr,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,s=sn(rr,e.__scopePopover);return i.jsx(qe,{present:r||s.open,children:s.modal?i.jsx(VC,{...o,ref:t}):i.jsx($C,{...o,ref:t})})});xR.displayName=rr;var WC=er("PopoverContent.RemoveScroll"),VC=R.forwardRef((e,t)=>{const n=sn(rr,e.__scopePopover),r=R.useRef(null),o=Ce(t,r),s=R.useRef(!1);return R.useEffect(()=>{const a=r.current;if(a)return Sc(a)},[]),i.jsx(Ii,{as:WC,allowPinchZoom:!0,children:i.jsx(yR,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ae(e.onCloseAutoFocus,a=>{var l;a.preventDefault(),s.current||(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:ae(e.onPointerDownOutside,a=>{const l=a.detail.originalEvent,E=l.button===0&&l.ctrlKey===!0,c=l.button===2||E;s.current=c},{checkForDefaultPrevented:!1}),onFocusOutside:ae(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),$C=R.forwardRef((e,t)=>{const n=sn(rr,e.__scopePopover),r=R.useRef(!1),o=R.useRef(!1);return i.jsx(yR,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var a,l;(a=e.onCloseAutoFocus)==null||a.call(e,s),s.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),s.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:s=>{var E,c;(E=e.onInteractOutside)==null||E.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const a=s.target;((c=n.triggerRef.current)==null?void 0:c.contains(a))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),yR=R.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,disableOutsidePointerEvents:a,onEscapeKeyDown:l,onPointerDownOutside:E,onFocusOutside:c,onInteractOutside:d,...u}=e,T=sn(rr,n),S=mi(n);return Tc(),i.jsx(Ai,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:i.jsx(io,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:d,onEscapeKeyDown:l,onPointerDownOutside:E,onFocusOutside:c,onDismiss:()=>T.onOpenChange(!1),children:i.jsx(lc,{"data-state":MR(T.open),role:"dialog",id:T.contentId,...S,...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)"}})})})}),DR="PopoverClose",XC=R.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=sn(DR,n);return i.jsx(Oe.button,{type:"button",...r,ref:t,onClick:ae(e.onClick,()=>o.onOpenChange(!1))})});XC.displayName=DR;var KC="PopoverArrow",zC=R.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=mi(n);return i.jsx(cc,{...o,...r,ref:t})});zC.displayName=KC;function MR(e){return e?"open":"closed"}var JC=_R,qC=xR;const QC=R.forwardRef(({container:e,style:t,sideOffset:n=6,...r},o)=>i.jsx(JC,{container:e,children:i.jsx(qC,{ref:o,sideOffset:n,style:{background:Te("surfaceElevated"),color:Te("textPrimary"),border:`1px solid ${Te("borderDefault")}`,borderRadius:mn.md,boxShadow:Te("shadowMd"),padding:pe[3],zIndex:kr.popover,minWidth:220,...t},...r})}));QC.displayName="PopoverContent";const FE=e=>{let t;const n=new Set,r=(c,d)=>{const u=typeof c=="function"?c(t):c;if(!Object.is(u,t)){const T=t;t=d??(typeof u!="object"||u===null)?u:Object.assign({},t,u),n.forEach(S=>S(t,T))}},o=()=>t,l={setState:r,getState:o,getInitialState:()=>E,subscribe:c=>(n.add(c),()=>n.delete(c))},E=t=e(r,o,l);return l},ZC=(e=>e?FE(e):FE),eg=e=>e;function tg(e,t=eg){const n=me.useSyncExternalStore(e.subscribe,me.useCallback(()=>t(e.getState()),[e,t]),me.useCallback(()=>t(e.getInitialState()),[e,t]));return me.useDebugValue(n),n}const GE=e=>{const t=ZC(e),n=r=>tg(t,r);return Object.assign(n,t),n},ng=(e=>e?GE(e):GE),HE=e=>Symbol.iterator in e,kE=e=>"entries"in e,YE=(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,s]of n)if(!r.has(o)||!Object.is(s,r.get(o)))return!1;return!0},rg=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let o=n.next(),s=r.next();for(;!o.done&&!s.done;){if(!Object.is(o.value,s.value))return!1;o=n.next(),s=r.next()}return!!o.done&&!!s.done};function og(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:HE(e)&&HE(t)?kE(e)&&kE(t)?YE(e,t):rg(e,t):YE({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function sg(e){const t=me.useRef(void 0);return n=>{const r=e(n);return og(t.current,r)?t.current:t.current=r}}const ig={mainView:"notebook",themeMode:"dark",sidebarPanel:"files",sidebarOpen:!0,files:[],filesLoading:!1,activeFile:null,cells:[],notebookTitle:"",notebookMetadata:{},notebookDirty:!1,schemaTables:[],schemaLoading:!1,semanticLayer:{available:!1,provider:null,metrics:[],dimensions:[],hierarchies:[],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,dashboardMode:!1,activeBlockPath:null,blockStudioDraft:"",blockStudioDirty:!1,blockStudioPreview:null,blockStudioValidation:null,blockStudioMetadata:null,blockStudioCatalog:null,blockStudioCatalogLoading:!1,inspectorOpen:!1,inspectorContext:null};function ag(e,t){var n,r;switch(t.type){case"SET_MAIN_VIEW":return{...e,mainView:t.view,lineageFullscreen:!1,lineageFocusNodeId:null};case"SET_THEME":return{...e,themeMode:t.mode};case"SET_SIDEBAR_PANEL":return{...e,sidebarPanel:t.panel,sidebarOpen:t.panel!==null&&t.panel!=="connection"&&t.panel!=="reference",lineageFullscreen:!1,lineageFocusNodeId:null,mainView:t.panel==="connection"?"connection":t.panel==="reference"?"reference":((n=e.activeFile)==null?void 0:n.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:(r=t.payload.metadata)!=null&&r.name?`block:${t.payload.metadata.name}`:null};case"SET_CELLS":return{...e,cells:t.cells,notebookDirty:!0};case"UPDATE_NOTEBOOK_METADATA":{const o=e.notebookMetadata;let s=!1;for(const a of Object.keys(t.updates))if(o[a]!==t.updates[a]){s=!0;break}return s?{...e,notebookMetadata:{...o,...t.updates},notebookDirty:!0}:e}case"ADD_CELL":{if(!t.afterId)return{...e,cells:[...e.cells,t.cell],notebookDirty:!0};const o=e.cells.findIndex(a=>a.id===t.afterId);if(o===-1)return{...e,cells:[...e.cells,t.cell],notebookDirty:!0};const s=[...e.cells];return s.splice(o+1,0,t.cell),{...e,cells:s,notebookDirty:!0}}case"UPDATE_CELL":{const o=e.cells.map(a=>a.id===t.id?{...a,...t.updates}:a),s=t.updates.executionCount!==void 0?e.executionCounter+1:e.executionCounter;return{...e,cells:o,notebookDirty:!0,executionCounter:s}}case"DELETE_CELL":return{...e,cells:e.cells.filter(o=>o.id!==t.id),notebookDirty:!0};case"MOVE_CELL":{const o=e.cells.findIndex(a=>a.id===t.id);if(o===-1)return e;const s=[...e.cells];return t.direction==="up"&&o>0?[s[o-1],s[o]]=[s[o],s[o-1]]:t.direction==="down"&&o<s.length-1&&([s[o],s[o+1]]=[s[o+1],s[o]]),{...e,cells:s,notebookDirty:!0}}case"REORDER_CELL":{const{fromIndex:o,toIndex:s}=t;if(o===s||o<0||s<0||o>=e.cells.length||s>=e.cells.length)return e;const a=[...e.cells],[l]=a.splice(o,1);return a.splice(s,0,l),{...e,cells:a,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(o=>o.name===t.tableName?{...o,expanded:!o.expanded}:o)};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(o=>o.name===t.tableName?{...o,columns:t.columns}:o)};case"SET_PARAM_VALUE":return{...e,cells:e.cells.map(o=>o.id===t.id?{...o,paramValue:t.value}:o),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 o=[t.name,...e.semanticLayer.recentlyUsed.filter(s=>s!==t.name)].slice(0,12);return{...e,semanticLayer:{...e.semanticLayer,recentlyUsed:o}}}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"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};default:return e}}const jE=ng((e,t)=>({...ig,dispatch:n=>{const r=ag(t(),n);e(r)}})),lg=R.createContext(null);function cg({children:e}){return i.jsx(i.Fragment,{children:e})}function de(){const e=jE(sg(r=>{const{dispatch:o,...s}=r;return s})),t=jE(r=>r.dispatch);return R.useContext(lg)??{state:e,dispatch:t}}function yt(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function We(e,t=""){const n={id:yt(),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={}),n}function Eg(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 s of n)if(s===r[o]&&o++,o===r.length)return 10;return 0}function dg({open:e,onClose:t}){const{state:n,dispatch:r}=de(),[o,s]=R.useState(""),[a,l]=R.useState(0),E=R.useRef(null);R.useEffect(()=>{e&&(s(""),l(0))},[e]);const c=R.useMemo(()=>{const S=O=>r(O),A=()=>t(),f=O=>()=>{O(),A()},I=[["Files","files"],["Schema","schema"],["Lineage","lineage"],["Git","git"],["Block Library","block_library"],["Connections","connection"],["Reference","reference"]];return[{id:"sidebar.toggle",label:n.sidebarOpen?"Hide sidebar":"Show sidebar",group:"View",shortcut:"⌘B",run:f(()=>S({type:"TOGGLE_SIDEBAR"}))},{id:"theme.toggle",label:n.themeMode==="dark"?"Switch to light theme":"Switch to dark theme",group:"View",keywords:"appearance color mode",run:f(()=>S({type:"SET_THEME",mode:n.themeMode==="dark"?"light":"dark"}))},{id:"inspector.toggle",label:n.inspectorOpen?"Hide inspector":"Show inspector",group:"View",shortcut:"⌘⇧I",run:f(()=>S({type:"TOGGLE_INSPECTOR"}))},{id:"dashboard.toggle",label:n.dashboardMode?"Exit dashboard mode":"Enter dashboard mode",group:"View",shortcut:"⌘D",run:f(()=>S({type:"TOGGLE_DASHBOARD_MODE"}))},{id:"dev.toggle",label:"Toggle dev panel",group:"View",shortcut:"⌘J",run:f(()=>S({type:"TOGGLE_DEV_PANEL"}))},{id:"lineage.fullscreen",label:n.lineageFullscreen?"Exit full-screen lineage":"Open full-screen lineage",group:"Lineage",keywords:"graph dag",run:f(()=>S({type:"TOGGLE_LINEAGE_FULLSCREEN"}))},...I.map(([O,N])=>({id:`panel.${N}`,label:`Go to ${O}`,group:"Navigate",run:f(()=>{S({type:"SET_SIDEBAR_PANEL",panel:N}),n.sidebarOpen||S({type:"TOGGLE_SIDEBAR"})})})),{id:"notebook.new",label:"New notebook…",group:"Create",run:f(()=>S({type:"OPEN_NEW_NOTEBOOK_MODAL"}))},{id:"block.new",label:"New block…",group:"Create",run:f(()=>S({type:"OPEN_NEW_BLOCK_MODAL"}))}]},[n.sidebarOpen,n.themeMode,n.dashboardMode,n.lineageFullscreen,n.inspectorOpen,r,t]),d=R.useMemo(()=>{const S=c.map(A=>({a:A,s:Eg(A,o)})).filter(A=>A.s>0);return S.sort((A,f)=>f.s-A.s),S.map(A=>A.a)},[c,o]);R.useEffect(()=>{l(0)},[o]),R.useEffect(()=>{var A;const S=(A=E.current)==null?void 0:A.querySelector(`[data-palette-idx="${a}"]`);S==null||S.scrollIntoView({block:"nearest"})},[a]);const u=S=>{var A;S.key==="ArrowDown"?(S.preventDefault(),l(f=>Math.min(d.length-1,f+1))):S.key==="ArrowUp"?(S.preventDefault(),l(f=>Math.max(0,f-1))):S.key==="Enter"&&(S.preventDefault(),(A=d[a])==null||A.run())};let T="";return i.jsx(om,{open:e,onOpenChange:S=>!S&&t(),children:i.jsxs(sm,{children:[i.jsx(im,{style:{position:"fixed",inset:0,background:Te("surfaceOverlay"),zIndex:kr.overlay}}),i.jsxs(am,{"aria-label":"Command palette",style:{position:"fixed",top:"18vh",left:"50%",transform:"translateX(-50%)",width:"92vw",maxWidth:620,background:Te("surfaceRaised"),color:Te("textPrimary"),border:`1px solid ${Te("borderDefault")}`,borderRadius:mn.lg,boxShadow:Te("shadowLg"),zIndex:kr.modal,display:"flex",flexDirection:"column",overflow:"hidden"},onKeyDown:u,children:[i.jsx(lm,{style:{position:"absolute",left:-9999},children:"Command palette"}),i.jsx("input",{autoFocus:!0,value:o,onChange:S=>s(S.target.value),placeholder:"Type a command…",style:{padding:`${pe[3]}px ${pe[4]}px`,border:"none",outline:"none",background:"transparent",color:Te("textPrimary"),fontSize:ve.md,borderBottom:`1px solid ${Te("borderSubtle")}`}}),i.jsxs("div",{ref:E,style:{maxHeight:360,overflowY:"auto",padding:`${pe[1]}px 0`},children:[d.length===0&&i.jsx("div",{style:{padding:pe[4],fontSize:ve.sm,color:Te("textMuted"),textAlign:"center"},children:"No matching commands"}),d.map((S,A)=>{const f=S.group!==T;T=S.group;const I=A===a;return i.jsxs(me.Fragment,{children:[f&&i.jsx("div",{style:{padding:`${pe[2]}px ${pe[4]}px ${pe[1]}px`,fontSize:ve.xs,fontWeight:Ql.medium,textTransform:"uppercase",letterSpacing:.5,color:Te("textMuted")},children:S.group}),i.jsxs("div",{"data-palette-idx":A,role:"option","aria-selected":I,onMouseEnter:()=>l(A),onMouseDown:p=>{p.preventDefault(),S.run()},style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:`${pe[2]}px ${pe[4]}px`,fontSize:ve.sm,cursor:"pointer",background:I?Te("surfaceHover"):"transparent",color:Te("textPrimary")},children:[i.jsx("span",{children:S.label}),S.shortcut&&i.jsx("span",{style:{fontSize:ve.xs,color:Te("textMuted"),fontFamily:"var(--dql-font-mono, monospace)"},children:S.shortcut})]})]},S.id)})]})]})]})})}const ug=window.location.origin;async function oe(e,t){const n=await fetch(`${ug}${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()}const Q={async listNotebooks(){try{return await oe("/api/notebooks")}catch{return[]}},async readNotebook(e){return oe(`/api/notebook-content?path=${encodeURIComponent(e)}`)},async createNotebook(e,t){return oe("/api/notebooks",{method:"POST",body:JSON.stringify({name:e,template:t})})},async createBlock(e){return oe("/api/blocks",{method:"POST",body:JSON.stringify({name:e})})},async getBlockLibrary(){try{return await oe("/api/blocks/library")}catch{return{blocks:[]}}},async updateBlockStatus(e,t){return oe("/api/blocks/status",{method:"POST",body:JSON.stringify({path:e,newStatus:t})})},async getBlockHistory(e){try{return await oe(`/api/blocks/history?path=${encodeURIComponent(e)}`)}catch{return{entries:[]}}},async runBlockTests(e,t){return oe("/api/blocks/run-tests",{method:"POST",body:JSON.stringify({source:e,path:t})})},async getBlockStudioCatalog(){return oe("/api/block-studio/catalog")},async openBlockStudio(e){return oe(`/api/block-studio/open?path=${encodeURIComponent(e)}`)},async validateBlockStudio(e,t){return oe("/api/block-studio/validate",{method:"POST",body:JSON.stringify({source:e,path:t})})},async runBlockStudio(e,t){return oe("/api/block-studio/run",{method:"POST",body:JSON.stringify({source:e,path:t})})},async saveBlockStudio(e){return oe("/api/block-studio/save",{method:"POST",body:JSON.stringify(e)})},async saveAsBlock(e){return oe("/api/blocks/save-from-cell",{method:"POST",body:JSON.stringify(e)})},async getBlockTemplates(){try{return(await oe("/api/blocks/templates")).templates}catch{return[]}},async listBlocks(e){try{return(await oe("/api/notebooks")).filter(n=>n.type==="block"&&(!e||n.path.startsWith(`blocks/${e}/`)))}catch{return[]}},async saveNotebook(e,t){return oe("/api/notebook-content",{method:"PUT",body:JSON.stringify({path:e,content:t})})},async executeQuery(e,t){var o;const n=await oe("/api/query",{method:"POST",body:JSON.stringify({sql:e}),signal:t});return{columns:Array.isArray(n==null?void 0:n.columns)?n.columns.map(s=>typeof s=="string"?s:typeof(s==null?void 0:s.name)=="string"?s.name:String(s)):[],rows:Array.isArray(n==null?void 0:n.rows)?n.rows:[],rowCount:(n==null?void 0:n.rowCount)??((o=n==null?void 0:n.rows)==null?void 0:o.length)??0,executionTime:(n==null?void 0:n.executionTime)??(n==null?void 0:n.executionTimeMs)??0}},async getSchema(){try{return await oe("/api/schema")}catch{return[]}},async getConnections(){try{return await oe("/api/connections")}catch{return{default:"unknown",connections:{}}}},async saveConnections(e){return oe("/api/connections",{method:"PUT",body:JSON.stringify({connections:e})})},async testConnection(){try{return await oe("/api/test-connection",{method:"POST",body:JSON.stringify({})})}catch(e){return{ok:!1,message:e.message??"Connection failed"}}},async getSemanticLayer(){try{return await oe("/api/semantic-layer")}catch{return{available:!1,provider:null,metrics:[],dimensions:[],hierarchies:[],domains:[],tags:[],favorites:[],recentlyUsed:[],lastSyncTime:null}}},async getSemanticTree(){return(await oe("/api/semantic-layer/tree")).tree},async getSemanticObject(e){return oe(`/api/semantic-layer/object/${encodeURIComponent(e)}`)},async importSemanticLayer(e){return oe("/api/semantic-layer/import",{method:"POST",body:JSON.stringify(e)})},async syncSemanticLayer(){return oe("/api/semantic-layer/sync",{method:"POST",body:JSON.stringify({})})},async previewSemanticImport(e){return oe("/api/semantic-layer/import-preview",{method:"POST",body:JSON.stringify(e)})},async previewSyncDiff(){return oe("/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 oe(`/api/semantic-layer/search?${t.toString()}`)}catch{return{metrics:[],dimensions:[],hierarchies:[]}}},async getFavorites(){try{return(await oe("/api/user-prefs/favorites")).favorites}catch{return[]}},async toggleFavorite(e){return(await oe("/api/user-prefs/favorites",{method:"POST",body:JSON.stringify({name:e})})).favorites},async getRecentlyUsed(){try{return(await oe("/api/user-prefs/recent")).recentlyUsed}catch{return[]}},async trackUsage(e){try{return(await oe("/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 oe(`/api/semantic-layer/compatible-dims?${t.toString()}`)).dimensions}catch{return[]}},async composeQuery(e,t,n){try{return await oe("/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 oe("/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 oe("/api/semantic-builder/save",{method:"POST",body:JSON.stringify(e)})},async createMetric(e){try{return await oe("/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 oe(`/api/describe-table?${o.toString()}`)}catch{return[]}},async fetchLineage(){try{return await oe("/api/lineage")}catch{return{nodes:[],edges:[]}}},async searchLineage(e){try{return await oe(`/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 oe(`/api/lineage/query?${t.toString()}`)}catch{return{graph:{nodes:[],edges:[]},matches:[]}}},async fetchLineageNode(e){try{return await oe(`/api/lineage/node/${encodeURIComponent(e)}`)}catch{return null}},async fetchBlockLineage(e){try{return await oe(`/api/lineage/block/${encodeURIComponent(e)}`)}catch{return null}},async fetchImpactAnalysis(e){try{return await oe(`/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 oe(o)}catch{return null}},async fetchGitStatus(){try{return await oe("/api/git/status")}catch{return{inRepo:!1,branch:null,ahead:0,behind:0,changes:[]}}},async fetchGitLog(e=20){try{return await oe(`/api/git/log?limit=${e}`)}catch{return{inRepo:!1,commits:[]}}},async fetchRunSnapshot(e){try{return await oe(`/api/run-snapshot?path=${encodeURIComponent(e)}`)}catch{return{found:!1,snapshot:null}}},async saveRunSnapshot(e,t){await oe("/api/run-snapshot",{method:"PUT",body:JSON.stringify({path:e,snapshot:t})})},async fetchGitDiff(e){try{const t=e?`?path=${encodeURIComponent(e)}`:"";return await oe(`/api/git/diff${t}`)}catch{return{inRepo:!1,diff:""}}}};function Tg(){const{state:e,dispatch:t}=de(),n=e.inspectorContext;return i.jsxs("aside",{"aria-label":"Inspector",style:{width:320,borderLeft:`1px solid ${Te("borderSubtle")}`,background:Te("surfaceBase"),color:Te("textPrimary"),display:"flex",flexDirection:"column",overflow:"hidden",flexShrink:0},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:`${pe[3]}px ${pe[4]}px`,borderBottom:`1px solid ${Te("borderSubtle")}`},children:[i.jsx("div",{style:{fontSize:ve.sm,fontWeight:Ql.semibold},children:n?Sg(n):"Inspector"}),i.jsx("button",{onClick:()=>t({type:"SET_INSPECTOR",open:!1}),"aria-label":"Close inspector",style:{background:"transparent",border:"none",color:Te("textMuted"),cursor:"pointer",fontSize:ve.md,padding:2,borderRadius:mn.sm},children:"×"})]}),i.jsx("div",{style:{flex:1,overflow:"auto",padding:pe[4]},children:n?i.jsx(Rg,{context:n}):i.jsx(Ig,{})})]})}function Sg(e){switch(e.kind){case"cell":return"Cell";case"lineage-node":return"Lineage node";case"metric":return"Metric"}}function Rg({context:e}){return e.kind==="cell"?i.jsx(fg,{cellId:e.cellId}):e.kind==="lineage-node"?i.jsx(Ag,{nodeId:e.nodeId}):i.jsx(pg,{name:e.name})}function fg({cellId:e}){const{state:t}=de(),n=t.cells.find(r=>r.id===e);return n?i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:pe[3],fontSize:ve.sm},children:[i.jsx(je,{label:"Type",children:n.type}),i.jsx(je,{label:"ID",children:i.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:n.id})}),i.jsxs(je,{label:"Length",children:[n.content.length," chars"]}),n.status&&i.jsx(je,{label:"Status",children:n.status})]}):i.jsx(Bs,{children:"No matching cell in the active notebook."})}function Ag({nodeId:e}){const[t,n]=R.useState(null),[r,o]=R.useState(!0);if(R.useEffect(()=>{let a=!1;return o(!0),Q.fetchLineageNode(e).then(l=>{a||(n(l),o(!1))}).catch(()=>{a||o(!1)}),()=>{a=!0}},[e]),r)return i.jsx(Bs,{children:"Loading node…"});if(!t||!t.node)return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:pe[3]},children:[i.jsx(je,{label:"Node ID",children:i.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:e})}),i.jsx(Bs,{children:"No metadata available for this node."})]});const s=t.node;return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:pe[3]},children:[i.jsx(je,{label:"Name",children:s.name??e}),i.jsx(je,{label:"Type",children:s.type}),s.domain&&i.jsx(je,{label:"Domain",children:s.domain}),s.layer&&i.jsx(je,{label:"Layer",children:s.layer}),i.jsx(je,{label:"Upstream",children:t.incoming.length}),i.jsx(je,{label:"Downstream",children:t.outgoing.length}),s.path&&i.jsx(je,{label:"Path",children:i.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)",fontSize:ve.xs},children:s.path})})]})}function pg({name:e}){return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:pe[3]},children:[i.jsx(je,{label:"Metric",children:e}),i.jsx(Bs,{children:"Definition, dimensions, and governance surface will render here."})]})}function je({label:e,children:t}){return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[i.jsx("div",{style:{fontSize:ve.xs,color:Te("textMuted"),textTransform:"uppercase",letterSpacing:.5,fontWeight:Ql.medium},children:e}),i.jsx("div",{style:{fontSize:ve.sm,color:Te("textPrimary")},children:t})]})}function Bs({children:e}){return i.jsx("div",{style:{fontSize:ve.sm,color:Te("textSecondary"),lineHeight:1.5,background:Te("surfaceSunken"),border:`1px solid ${Te("borderSubtle")}`,borderRadius:mn.md,padding:pe[3]},children:e})}function Ig(){return i.jsx("div",{style:{fontSize:ve.sm,color:Te("textMuted"),lineHeight:1.5},children:"Select a cell, lineage node, or metric to inspect its details here."})}const Og={appBg:"#0a0a0c",sidebarBg:"#111114",activityBarBg:"#08080a",headerBg:"#111114",headerBorder:"#1d1d22",cellBg:"#131317",cellBorder:"#26262d",cellBorderActive:"#5b8def",cellBorderRunning:"#4ade80",textPrimary:"#f4f4f5",textSecondary:"#a0a0a8",textMuted:"#5a5a65",editorBg:"#0a0a0c",editorBorder:"#26262d",tableBorder:"#26262d",tableHeaderBg:"#17171c",tableRowHover:"#1a1a20",accent:"#5b8def",accentHover:"#7aa5ff",success:"#4ade80",error:"#f87171",warning:"#fbbf24",btnBg:"#1a1a1f",btnBorder:"#26262d",btnHover:"#26262d",sidebarItemHover:"#1a1a20",sidebarItemActive:"#1f2937",scrollbarThumb:"#26262d",modalBg:"#111114",modalOverlay:"rgba(0,0,0,0.75)",inputBg:"#0a0a0c",inputBorder:"#26262d",pillBg:"#1a1a1f",font:"Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontMono:"'JetBrains Mono', 'Fira Code', Consolas, monospace",fontSerif:"Georgia, 'Times New Roman', serif"},Ng={appBg:"#fafafa",sidebarBg:"#f3f4f6",activityBarBg:"#ececef",headerBg:"#ffffff",headerBorder:"#e4e4e7",cellBg:"#ffffff",cellBorder:"#e4e4e7",cellBorderActive:"#4f46e5",cellBorderRunning:"#16a34a",textPrimary:"#18181b",textSecondary:"#52525b",textMuted:"#a1a1aa",editorBg:"#fafafa",editorBorder:"#e4e4e7",tableBorder:"#e4e4e7",tableHeaderBg:"#f3f4f6",tableRowHover:"#f3f4f6",accent:"#4f46e5",accentHover:"#4338ca",success:"#16a34a",error:"#dc2626",warning:"#ca8a04",btnBg:"#f3f4f6",btnBorder:"#e4e4e7",btnHover:"#e4e4e7",sidebarItemHover:"#e4e4e7",sidebarItemActive:"#e0e7ff",scrollbarThumb:"#d4d4d8",modalBg:"#ffffff",modalOverlay:"rgba(0,0,0,0.4)",inputBg:"#ffffff",inputBorder:"#e4e4e7",pillBg:"#f3f4f6",font:"Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontMono:"'JetBrains Mono', 'Fira Code', Consolas, monospace",fontSerif:"Georgia, 'Times New Roman', serif"},re={dark:Og,light:Ng};function Ct({title:e,active:t,onClick:n,children:r,t:o}){const[s,a]=R.useState(!1);return i.jsx(QN,{content:e,side:"right",children:i.jsx("button",{"aria-label":e,onClick:n,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{width:32,height:32,display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",borderLeft:t?`2px solid ${o.accent}`:"2px solid transparent",cursor:"pointer",color:t?o.textPrimary:s?o.textSecondary:o.textMuted,transition:"color 0.15s, border-color 0.15s",padding:0,flexShrink:0},children:r})})}function hg(){return i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"})})}function mg(){return i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M8 0C3.58 0 0 1.567 0 3.5v9C0 14.433 3.58 16 8 16s8-1.567 8-3.5v-9C16 1.567 12.42 0 8 0ZM1.5 7.784V5.716C3.05 6.51 5.404 7 8 7s4.95-.49 6.5-1.284v2.068C12.95 8.578 10.596 9 8 9s-4.95-.422-6.5-1.216ZM8 1.5c3.17 0 5.854 1.116 6.357 2.5H1.643C2.146 2.616 4.83 1.5 8 1.5Zm0 13c-3.17 0-5.854-1.116-6.357-2.5h12.714C13.854 13.384 11.17 14.5 8 14.5Zm6.5-3.284C12.95 11.01 10.596 11.5 8 11.5s-4.95-.49-6.5-1.284V8.216C3.05 9.01 5.404 9.5 8 9.5s4.95-.49 6.5-1.284v2.5Z"})})}function Cg(){return i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M4 2a2 2 0 1 1 0 4 2 2 0 0 1 0-4Zm8 4a2 2 0 1 1 0 4 2 2 0 0 1 0-4Zm-8 4a2 2 0 1 1 0 4 2 2 0 0 1 0-4ZM6 4h4l2 4-2 4H6",stroke:"currentColor",strokeWidth:"1.2",fill:"none"})})}function gg(){return i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M1 2.75C1 1.784 1.784 1 2.75 1h2.5C6.216 1 7 1.784 7 2.75v2.5C7 6.216 6.216 7 5.25 7h-2.5C1.784 7 1 6.216 1 5.25Zm1.75-.25a.25.25 0 0 0-.25.25v2.5c0 .138.112.25.25.25h2.5A.25.25 0 0 0 6 5.25v-2.5A.25.25 0 0 0 5.25 2.5ZM9 2.75C9 1.784 9.784 1 10.75 1h2.5C14.216 1 15 1.784 15 2.75v2.5C15 6.216 14.216 7 13.25 7h-2.5C9.784 7 9 6.216 9 5.25Zm1.75-.25a.25.25 0 0 0-.25.25v2.5c0 .138.112.25.25.25h2.5a.25.25 0 0 0 .25-.25v-2.5a.25.25 0 0 0-.25-.25ZM1 10.75C1 9.784 1.784 9 2.75 9h2.5C6.216 9 7 9.784 7 10.75v2.5C7 14.216 6.216 15 5.25 15h-2.5C1.784 15 1 14.216 1 13.25Zm1.75-.25a.25.25 0 0 0-.25.25v2.5c0 .138.112.25.25.25h2.5a.25.25 0 0 0 .25-.25v-2.5a.25.25 0 0 0-.25-.25ZM13 9.75a.75.75 0 0 1 .75.75v1.75H15.5a.75.75 0 0 1 0 1.5h-1.75V15.5a.75.75 0 0 1-1.5 0v-1.75H10.5a.75.75 0 0 1 0-1.5h1.75V10.5A.75.75 0 0 1 13 9.75Z"})})}function Lg(){return i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:i.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.06 0l-.622-.621A2.25 2.25 0 0 0 5.258 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.5v9h3.757a3.75 3.75 0 0 1 1.994.574ZM8.755 4.75l-.004 7.322a3.752 3.752 0 0 1 1.992-.572H14.5v-9h-3.495a2.25 2.25 0 0 0-2.25 2.25Z"})})}function _g(){return i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm8-6.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM6.92 6.085h.001a.749.749 0 1 1-1.342-.67C6.03 4.26 6.88 3.75 8 3.75c1.463 0 2.5 1.008 2.5 2.25 0 1.133-.67 1.8-1.4 2.25-.487.3-.6.47-.6.75V9.5a.75.75 0 0 1-1.5 0v-.5c0-.833.585-1.33 1.1-1.65.387-.24.9-.597.9-1.35 0-.65-.53-1.25-1.5-1.25-.74 0-1.163.353-1.58.835ZM8 12a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z"})})}function xg(){return i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M11.75 2.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm-2.25.75a2.25 2.25 0 1 1 3 2.122V6a2.5 2.5 0 0 1-2.5 2.5h-2.5v2.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.628h2.5a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM3.5 3.25a.75.75 0 1 1 1.5 0 .75.75 0 0 1-1.5 0Z"})})}function yg(){return i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:i.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.103-.303c-.066-.019-.176-.011-.299.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.103.303c.066.019.176.011.299-.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-.147a6.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"})})}function Dg(){const{state:e,dispatch:t}=de(),n=re[e.themeMode];function r(o){if(o==="connection"||o==="reference"){t({type:"SET_SIDEBAR_PANEL",panel:o});return}e.sidebarPanel===o&&e.sidebarOpen?t({type:"TOGGLE_SIDEBAR"}):t({type:"SET_SIDEBAR_PANEL",panel:o})}return i.jsxs("div",{style:{width:32,flexShrink:0,background:n.activityBarBg,borderRight:`1px solid ${n.headerBorder}`,display:"flex",flexDirection:"column",alignItems:"center",paddingTop:8,paddingBottom:8,gap:2,userSelect:"none"},children:[i.jsx(Ct,{title:"Files",active:e.sidebarPanel==="files"&&e.sidebarOpen,onClick:()=>r("files"),t:n,children:i.jsx(hg,{})}),i.jsx(Ct,{title:"Schema",active:e.sidebarPanel==="schema"&&e.sidebarOpen,onClick:()=>r("schema"),t:n,children:i.jsx(mg,{})}),i.jsx(Ct,{title:"Block Library",active:e.sidebarPanel==="block_library"&&e.sidebarOpen,onClick:()=>r("block_library"),t:n,children:i.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",children:[i.jsx("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",stroke:"currentColor",strokeWidth:"1.3"}),i.jsx("rect",{x:"10",y:"2",width:"6",height:"6",rx:"1",stroke:"currentColor",strokeWidth:"1.3"}),i.jsx("rect",{x:"2",y:"10",width:"6",height:"6",rx:"1",stroke:"currentColor",strokeWidth:"1.3"}),i.jsx("rect",{x:"10",y:"10",width:"6",height:"6",rx:"1",stroke:"currentColor",strokeWidth:"1.3"})]})}),i.jsx(Ct,{title:"Lineage",active:e.sidebarPanel==="lineage"&&e.sidebarOpen,onClick:()=>r("lineage"),t:n,children:i.jsx(Cg,{})}),i.jsx(Ct,{title:"Connection",active:e.mainView==="connection",onClick:()=>r("connection"),t:n,children:i.jsx(gg,{})}),i.jsx(Ct,{title:"Reference",active:e.mainView==="reference",onClick:()=>r("reference"),t:n,children:i.jsx(Lg,{})}),i.jsx(Ct,{title:"Git",active:e.sidebarPanel==="git"&&e.sidebarOpen,onClick:()=>r("git"),t:n,children:i.jsx(xg,{})}),i.jsx("div",{style:{flex:1}}),i.jsx(Ct,{title:"Help & Reference",active:e.mainView==="reference",onClick:()=>r("reference"),t:n,children:i.jsx(_g,{})}),i.jsx(Ct,{title:"Settings",active:!1,onClick:()=>{},t:n,children:i.jsx(yg,{})})]})}const Ra={notebooks:"Notebooks",workbooks:"Workbooks",blocks:"Blocks",dashboards:"Dashboards"};function Mg({type:e}){switch(e){case"notebook":return i.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"workbook":return i.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:i.jsx("path",{d:"M2 1.75C2 .784 2.784 0 3.75 0h8.5C13.216 0 14 .784 14 1.75v12.5A1.75 1.75 0 0 1 12.25 16h-8.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25Zm2 3.5a.75.75 0 0 1 .75-.75h3a.75.75 0 0 1 0 1.5h-3a.75.75 0 0 1-.75-.75ZM6.5 7.25a.75.75 0 0 0 0 1.5h3a.75.75 0 0 0 0-1.5Zm-.75 3.5a.75.75 0 0 1 .75-.75h3a.75.75 0 0 1 0 1.5h-3a.75.75 0 0 1-.75-.75Z"})});case"block":return i.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 i.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 Pg({expanded:e}){return i.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:e?i.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"}):i.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 bg(e){return e.name.replace(/\.(dqlnb|dql)$/,"")}function vg({onOpenFile:e}){const{state:t,dispatch:n}=de(),r=re[t.themeMode],[o,s]=R.useState({notebooks:!0,workbooks:!0,blocks:!1,dashboards:!1}),[a,l]=R.useState(!1),E={notebooks:[],workbooks:[],blocks:[],dashboards:[]};for(const d of t.files){const u=d.folder.toLowerCase();u in E&&E[u].push(d)}const c=d=>{s(u=>({...u,[d]:!u[d]}))};return i.jsxs("div",{style:{flex:1,overflow:"auto",padding:"8px 0",display:"flex",flexDirection:"column",gap:0},children:[i.jsx("div",{style:{padding:"0 8px 8px"},children:i.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:[i.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"New Notebook"]})}),t.filesLoading&&i.jsx("div",{style:{padding:"8px 14px",color:r.textMuted,fontSize:12,fontFamily:r.font},children:"Loading files…"}),Object.keys(Ra).map(d=>{const u=E[d],T=o[d],S=d==="notebooks"?()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}):d==="blocks"?()=>n({type:"OPEN_NEW_BLOCK_MODAL"}):void 0;return i.jsxs("div",{children:[i.jsx(Ug,{label:Ra[d],count:u.length,expanded:T,onToggle:()=>c(d),onAdd:S,t:r}),T&&i.jsx("div",{children:u.length===0?i.jsxs("div",{style:{padding:"4px 14px 4px 32px",fontSize:12,color:r.textMuted,fontFamily:r.font,fontStyle:"italic"},children:["No ",Ra[d].toLowerCase()]}):u.map(A=>{var f;return i.jsx(wg,{file:A,active:((f=t.activeFile)==null?void 0:f.path)===A.path,onClick:()=>e(A),t:r},A.path)})})]},d)})]})}function Ug({label:e,count:t,expanded:n,onToggle:r,onAdd:o,t:s}){const[a,l]=R.useState(!1),[E,c]=R.useState(!1);return i.jsxs("div",{onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{display:"flex",alignItems:"center",background:a?s.sidebarItemHover:"transparent",transition:"background 0.1s"},children:[i.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:s.textSecondary,fontSize:11,fontWeight:600,fontFamily:s.font,letterSpacing:"0.04em",textTransform:"uppercase",textAlign:"left"},children:[i.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:i.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),i.jsx(Pg,{expanded:n}),i.jsx("span",{style:{flex:1},children:e}),t>0&&i.jsx("span",{style:{background:s.pillBg,color:s.textMuted,borderRadius:10,padding:"0 5px",fontSize:10,fontWeight:500},children:t})]}),o&&a&&i.jsx("button",{onClick:d=>{d.stopPropagation(),o()},onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),title:`New ${e.slice(0,-1)}`,style:{background:E?s.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:E?s.accent:s.textMuted,fontSize:14,lineHeight:1,padding:"2px 8px",marginRight:4,flexShrink:0,transition:"color 0.1s"},children:"+"})]})}function wg({file:e,active:t,onClick:n,t:r}){const[o,s]=R.useState(!1);return i.jsxs("button",{onClick:n,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 8px 4px 26px",background:t?r.sidebarItemActive:o?r.sidebarItemHover:"transparent",border:"none",borderLeft:t?`2px solid ${r.accent}`:"2px solid transparent",cursor:"pointer",color:t||o?r.textPrimary:r.textSecondary,fontSize:13,fontFamily:r.font,textAlign:"left",transition:"background 0.1s, color 0.1s",overflow:"hidden"},children:[i.jsx("span",{style:{flexShrink:0,color:t?r.accent:r.textMuted},children:i.jsx(Mg,{type:e.type})}),i.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:bg(e)}),e.isNew&&i.jsx("span",{style:{fontSize:9,fontWeight:600,color:r.accent,background:r.sidebarItemActive,borderRadius:4,padding:"1px 4px",flexShrink:0},children:"NEW"})]})}const Bg={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 gl(e,t){const n=e.toLowerCase().split("(")[0].trim();return Bg[n]??t}function Fg({t:e}){return i.jsxs("div",{style:{padding:"8px 12px",display:"flex",flexDirection:"column",gap:8},children:[[1,2,3].map(t=>i.jsx("div",{style:{height:28,borderRadius:4,background:e.pillBg,opacity:.6,animation:"pulse 1.5s ease-in-out infinite"}},t)),i.jsx("style",{children:"@keyframes pulse { 0%,100%{opacity:.6} 50%{opacity:.3} }"})]})}function Gg(){const{state:e,dispatch:t}=de(),n=re[e.themeMode],[r,o]=R.useState(!1),[s,a]=R.useState(""),l=async()=>{t({type:"SET_SCHEMA_LOADING",loading:!0});try{const T=await Q.getSchema();t({type:"SET_SCHEMA",tables:T})}catch(T){console.error("Schema refresh failed:",T)}finally{t({type:"SET_SCHEMA_LOADING",loading:!1})}},E=R.useMemo(()=>{const T=s.trim().toLowerCase();return T?e.schemaTables.filter(S=>{const A=[S.name,S.path,S.objectType].filter(I=>!!I).some(I=>I.toLowerCase().includes(T)),f=S.columns.some(I=>I.name.toLowerCase().includes(T)||I.type.toLowerCase().includes(T));return A||f}):e.schemaTables},[s,e.schemaTables]),c=R.useMemo(()=>{const T=new Map;for(const S of E){const[A,...f]=S.name.split("."),I=f.length>0?A:S.source==="file"?"files":"default",p=T.get(I)??[];p.push(S),T.set(I,p)}return Array.from(T.entries()).sort((S,A)=>S[0].localeCompare(A[0]))},[E]),d={schemas:c.length,tables:e.schemaTables.length,columns:e.schemaTables.reduce((T,S)=>T+S.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"};return i.jsxs("div",{style:{flex:1,overflow:"auto",display:"flex",flexDirection:"column"},children:[i.jsxs("div",{style:{padding:"10px",display:"grid",gap:10,borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:700,color:n.textPrimary,fontFamily:n.font},children:"Database Catalog"}),i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:"Browse schemas, tables, views, and loaded columns from the active connection."})]}),i.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:[i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"]})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8},children:[i.jsx(fa,{label:"Schemas",value:d.schemas,t:n}),i.jsx(fa,{label:"Tables",value:d.tables,t:n}),i.jsx(fa,{label:"Columns",value:d.columns,t:n})]}),i.jsx("input",{value:s,onChange:T=>a(T.target.value),placeholder:"Search schemas, tables, columns...",style:u})]}),e.schemaLoading?i.jsx(Fg,{t:n}):e.schemaTables.length===0?i.jsxs("div",{style:{padding:"24px 14px",color:n.textMuted,fontSize:12,fontFamily:n.font,textAlign:"center",fontStyle:"italic"},children:["No tables found.",i.jsx("br",{}),"Connect a data source to explore schema."]}):E.length===0?i.jsx("div",{style:{padding:"24px 14px",color:n.textMuted,fontSize:12,fontFamily:n.font,textAlign:"center",fontStyle:"italic"},children:"No database objects match the current search."}):i.jsx("div",{style:{overflow:"auto",flex:1},children:c.map(([T,S])=>i.jsxs("div",{children:[i.jsxs("div",{style:{padding:"8px 10px 4px",fontSize:10,fontWeight:700,color:n.textMuted,fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em"},children:[T," · ",S.length]}),S.map(A=>i.jsx(Hg,{table:A,t:n},A.name))]},T))})]})}function fa({label:e,value:t,t:n}){return i.jsxs("div",{style:{background:n.cellBg,border:`1px solid ${n.headerBorder}`,borderRadius:8,padding:"8px 10px"},children:[i.jsx("div",{style:{fontSize:9,fontWeight:700,color:n.textMuted,fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em"},children:e}),i.jsx("div",{style:{fontSize:18,fontWeight:700,color:n.textPrimary,fontFamily:n.font,marginTop:2},children:t})]})}function Hg({table:e,t}){var E;const{dispatch:n}=de(),[r,o]=R.useState(!1),[s,a]=R.useState(!1),l=async()=>{if(n({type:"TOGGLE_SCHEMA_TABLE",tableName:e.name}),!e.expanded&&e.columns.length===0){a(!0);try{const c=await Q.describeTable(e.path);c.length>0&&n({type:"SET_TABLE_COLUMNS",tableName:e.name,columns:c})}catch(c){console.error("describeTable failed:",c)}finally{a(!1)}}};return i.jsxs("div",{children:[i.jsxs("button",{onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onClick:l,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"5px 10px",background:r?t.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:t.textPrimary,fontSize:12,fontFamily:t.font,fontWeight:500,textAlign:"left",transition:"background 0.1s"},children:[i.jsx("svg",{width:"10",height:"10",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:i.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),e.source==="database"?i.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",style:{color:"#56d364",flexShrink:0},children:i.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"})}):i.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",style:{color:t.accent,flexShrink:0},children:i.jsx("path",{d:"M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v1.5A1.75 1.75 0 0 1 14.25 5H1.75A1.75 1.75 0 0 1 0 3.25Zm1.75-.25a.25.25 0 0 0-.25.25v1.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-1.5a.25.25 0 0 0-.25-.25Zm-1.75 6C0 6.784.784 6 1.75 6h12.5c.966 0 1.75.784 1.75 1.75v1.5A1.75 1.75 0 0 1 14.25 11H1.75A1.75 1.75 0 0 1 0 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v1.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-1.5a.25.25 0 0 0-.25-.25Zm-1.75 6c0-.966.784-1.75 1.75-1.75h12.5c.966 0 1.75.784 1.75 1.75v1.5A1.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.25v1.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-1.5a.25.25 0 0 0-.25-.25Z"})}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),e.objectType&&i.jsx("span",{style:{fontSize:9,fontFamily:t.fontMono,color:t.accent,background:`${t.accent}18`,borderRadius:4,padding:"1px 4px",flexShrink:0},children:e.objectType.toLowerCase().includes("view")?"view":"table"}),((E=e.governance)==null?void 0:E.status)&&i.jsx(jg,{status:e.governance.status,t}),e.columns.length>0&&i.jsx("span",{style:{fontSize:10,color:t.textMuted,background:t.pillBg,borderRadius:8,padding:"1px 5px",flexShrink:0},children:e.columns.length})]}),e.expanded&&i.jsxs("div",{style:{paddingLeft:26},children:[e.governance&&(e.governance.owner||e.governance.domain)&&i.jsxs("div",{style:{padding:"3px 10px",display:"flex",gap:8,flexWrap:"wrap"},children:[e.governance.domain&&i.jsxs("span",{style:{fontSize:9,fontFamily:t.font,color:t.textMuted},children:[i.jsx("span",{style:{fontWeight:600},children:"domain:"})," ",e.governance.domain]}),e.governance.owner&&i.jsxs("span",{style:{fontSize:9,fontFamily:t.font,color:t.textMuted},children:[i.jsx("span",{style:{fontWeight:600},children:"owner:"})," ",e.governance.owner]})]}),s?i.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:"..."}):e.columns.length===0?i.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:"No columns"}):e.columns.map(c=>i.jsx(kg,{col:c,t},c.name))]})]})}function kg({col:e,t}){const[n,r]=R.useState(!1);return i.jsxs("div",{onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),style:{display:"flex",alignItems:"center",gap:8,padding:"3px 10px 3px 8px",background:n?t.sidebarItemHover:"transparent",cursor:"default",transition:"background 0.1s"},children:[i.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",style:{color:t.textMuted,flexShrink:0},children:i.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"})}),i.jsx("span",{style:{flex:1,fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),i.jsx("span",{style:{fontSize:10,fontFamily:t.fontMono,color:gl(e.type,t.accent),background:`${gl(e.type,t.accent)}18`,borderRadius:4,padding:"1px 5px",flexShrink:0},children:e.type.toLowerCase()})]})}const Yg={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 jg({status:e,t}){const n=Yg[e];return n?i.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 Ll={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"},Aa={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"},Wg={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"]},Vg=[{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 PR(){const{state:e}=de(),t=re[e.themeMode],[n,r]=R.useState(null),[o,s]=R.useState(!1),[a,l]=R.useState(null),[E,c]=R.useState(null),[d,u]=R.useState(!1),[T,S]=R.useState(!1),[A,f]=R.useState(null),[I,p]=R.useState(""),[O,N]=R.useState("duckdb"),[h,C]=R.useState({});R.useEffect(()=>{Q.getConnections().then(M=>{r(M),Object.keys(M.connections).length>0&&Q.testConnection().then(l)})},[]);const m=async()=>{s(!0),l(null);const M=await Q.testConnection();l(M),s(!1)},g=(M,w)=>{c(M),u(!1),p(M),N((w==null?void 0:w.driver)??"duckdb");const v={};Object.entries(w??{}).forEach(([x,B])=>{x!=="driver"&&x!=="type"&&(v[x]=String(B??""))}),C(v)},y=()=>{u(!0),c(null),p(""),N("duckdb"),C({})},_=()=>{c(null),u(!1)},U=async()=>{if(!n)return;S(!0),f(null);const M=I.trim()||(E??"default"),w={driver:O};Object.entries(h).forEach(([x,B])=>{B.trim()&&(x==="port"&&!isNaN(Number(B))?w[x]=Number(B):w[x]=B)});const v={...n.connections};E&&E!==M&&delete v[E],v[M]=w;try{await Q.saveConnections(v);const x=await Q.getConnections();r(x),f("Saved"),setTimeout(()=>f(null),2e3),c(null),u(!1);try{s(!0);const B=await Q.testConnection();l(B)}catch{}finally{s(!1)}}catch(x){f(`Error: ${x.message}`)}finally{S(!1)}},D=async M=>{if(!n)return;const w={...n.connections};delete w[M],S(!0);try{await Q.saveConnections(w);const v=await Q.getConnections();r(v),c(null)}finally{S(!1)}},b={fontSize:10,fontWeight:600,letterSpacing:"0.07em",textTransform:"uppercase",color:t.textMuted,fontFamily:t.font,marginBottom:6},F={background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:7,padding:"10px 12px",marginBottom:10},L=(n==null?void 0:n.connections)??{},P=(n==null?void 0:n.default)??"";return i.jsxs("div",{style:{flex:1,overflow:"auto",padding:"12px 12px 20px"},children:[a&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",marginBottom:10,borderRadius:6,background:a.ok?`${t.success}12`:`${t.error}12`,border:`1px solid ${a.ok?t.success:t.error}30`},children:[i.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:a.ok?t.success:t.error,flexShrink:0}}),i.jsx("span",{style:{fontSize:11,fontFamily:t.font,color:a.ok?t.success:t.error},children:a.ok?"Connected":"Disconnected"})]}),i.jsx("div",{style:b,children:"Connections"}),n===null?i.jsx("div",{style:{fontSize:12,color:t.textMuted,fontFamily:t.font},children:"Loading…"}):Object.entries(L).map(([M,w])=>{const v=(w==null?void 0:w.driver)??(w==null?void 0:w.type)??"unknown",x=M===P||Object.keys(L).length===1,B=Aa[v]??t.accent;return E===M?i.jsx(WE,{t,editName:I,setEditName:p,editDriver:O,setEditDriver:N,editFields:h,setEditFields:C,onSave:U,onCancel:_,onDelete:()=>D(M),saving:T,isNew:!1},M):i.jsxs("div",{style:{...F,borderLeft:x?`3px solid ${B}`:`1px solid ${t.cellBorder}`},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[i.jsx("span",{style:{fontSize:10,fontWeight:700,fontFamily:t.fontMono,color:B,background:`${B}18`,border:`1px solid ${B}40`,borderRadius:4,padding:"1px 6px",letterSpacing:"0.05em",textTransform:"uppercase"},children:Ll[v]??v}),i.jsx("span",{style:{fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,fontWeight:500},children:M}),x&&i.jsx("span",{style:{fontSize:9,color:t.accent,fontFamily:t.font,fontWeight:600},children:"DEFAULT"}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{onClick:()=>g(M,w),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"})]}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:3},children:Object.entries(w??{}).filter(([H])=>H!=="driver"&&H!=="type").map(([H,Y])=>i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"baseline"},children:[i.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.fontMono,minWidth:70,flexShrink:0},children:H}),i.jsx("span",{style:{fontSize:11,color:t.textSecondary,fontFamily:t.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:H.toLowerCase().includes("password")||H.toLowerCase().includes("token")?"••••••••":String(Y)})]},H))})]},M)}),!d&&!E&&Object.keys(L).length===0&&i.jsxs(i.Fragment,{children:[i.jsx("div",{style:{...b,marginTop:8},children:"Quick Connect"}),i.jsx("div",{style:{display:"grid",gap:6,marginBottom:12},children:Vg.map(M=>i.jsxs("button",{onClick:async()=>{S(!0);try{const w={...L,[M.name]:M.config};await Q.saveConnections(w);const v=await Q.getConnections();r(v),s(!0);const x=await Q.testConnection();l(x),s(!1)}finally{S(!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:[i.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:Aa[M.config.driver]??t.accent,flexShrink:0}}),i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:600,color:t.textPrimary,fontFamily:t.font},children:M.label}),i.jsx("div",{style:{fontSize:10,color:t.textMuted,fontFamily:t.font},children:M.description})]})]},M.name))})]}),d?i.jsx(WE,{t,editName:I,setEditName:p,editDriver:O,setEditDriver:N,editFields:h,setEditFields:C,onSave:U,onCancel:_,saving:T,isNew:!0}):i.jsxs("button",{onClick:y,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:[i.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"Add Connection"]}),A&&i.jsx("div",{style:{fontSize:11,fontFamily:t.font,padding:"4px 10px",borderRadius:4,marginBottom:8,color:A.startsWith("Error")?t.error:t.success,background:A.startsWith("Error")?`${t.error}12`:`${t.success}12`},children:A}),i.jsx("button",{onClick:m,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&&i.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]}),i.jsx("div",{style:{...b,marginTop:4},children:"Supported Drivers"}),i.jsx("div",{style:{...F,display:"flex",flexDirection:"column",gap:4},children:Object.entries(Ll).map(([M,w])=>i.jsxs("div",{style:{display:"flex",gap:8,alignItems:"baseline"},children:[i.jsx("code",{style:{fontSize:10,fontFamily:t.fontMono,color:Aa[M]??t.textMuted,minWidth:80,flexShrink:0},children:M}),i.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font},children:w})]},M))})]})}function WE({t:e,editName:t,setEditName:n,editDriver:r,setEditDriver:o,editFields:s,setEditFields:a,onSave:l,onCancel:E,onDelete:c,saving:d,isNew:u}){const T=Wg[r]??[],S={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%"},A={fontSize:9,fontWeight:600,color:e.textMuted,fontFamily:e.font,letterSpacing:"0.05em",textTransform:"uppercase",marginBottom:2};return i.jsxs("div",{style:{background:e.cellBg,border:`1px solid ${e.accent}40`,borderRadius:7,padding:"10px 12px",marginBottom:10},children:[i.jsx("div",{style:{fontSize:11,fontWeight:600,color:e.accent,fontFamily:e.font,marginBottom:8},children:u?"New Connection":"Edit Connection"}),i.jsxs("div",{style:{marginBottom:6},children:[i.jsx("div",{style:A,children:"Name"}),i.jsx("input",{style:S,value:t,onChange:f=>n(f.target.value),placeholder:"e.g. production"})]}),i.jsxs("div",{style:{marginBottom:6},children:[i.jsx("div",{style:A,children:"Driver"}),i.jsx("select",{style:{...S,fontFamily:e.font},value:r,onChange:f=>{o(f.target.value),a({})},children:Object.entries(Ll).map(([f,I])=>i.jsx("option",{value:f,children:I},f))})]}),T.map(f=>i.jsxs("div",{style:{marginBottom:6},children:[i.jsx("div",{style:A,children:f}),i.jsx("input",{style:S,type:f.toLowerCase().includes("password")||f.toLowerCase().includes("token")?"password":"text",value:s[f]??"",placeholder:f==="port"?"5432":f==="filepath"?":memory:":"",onChange:I=>a({...s,[f]:I.target.value})})]},f)),i.jsxs("div",{style:{display:"flex",gap:6,marginTop:8},children:[i.jsx("button",{onClick:l,disabled:d,style:{flex:1,padding:"5px 0",borderRadius:5,border:"none",background:e.accent,color:"#fff",fontSize:11,fontFamily:e.font,fontWeight:600,cursor:d?"not-allowed":"pointer",opacity:d?.6:1},children:d?"Saving…":"Save"}),i.jsx("button",{onClick:E,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"}),c&&!u&&i.jsx("button",{onClick:c,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 gt({title:e,defaultOpen:t=!1,children:n,t:r}){const[o,s]=R.useState(t),[a,l]=R.useState(!1);return i.jsxs("div",{style:{borderBottom:`1px solid ${r.headerBorder}`},children:[i.jsxs("button",{onClick:()=>s(E=>!E),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:[i.jsx("span",{style:{fontSize:9,color:r.textMuted,display:"inline-block",transition:"transform 0.15s",transform:o?"rotate(90deg)":"rotate(0deg)",lineHeight:1},children:"▶"}),i.jsx("span",{style:{fontSize:11,fontWeight:600,fontFamily:r.font,color:r.textSecondary,letterSpacing:"0.04em"},children:e})]}),o&&i.jsx("div",{style:{padding:"4px 12px 10px"},children:n})]})}function $g({code:e,t}){const[n,r]=R.useState(!1);async function o(){try{await navigator.clipboard.writeText(e)}catch{const s=document.createElement("textarea");s.value=e,document.body.appendChild(s),s.select(),document.execCommand("copy"),document.body.removeChild(s)}r(!0),setTimeout(()=>r(!1),1500)}return i.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 De({code:e,t}){return i.jsxs("div",{style:{position:"relative",marginTop:6},children:[i.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}),i.jsx($g,{code:e,t})]})}function VE({rows:e,t}){return i.jsx("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11,fontFamily:t.font,marginTop:6},children:i.jsx("tbody",{children:e.map(([n,r],o)=>i.jsxs("tr",{style:{borderBottom:`1px solid ${t.tableBorder}`},children:[i.jsx("td",{style:{padding:"5px 6px 5px 0",fontFamily:t.fontMono,fontSize:11,color:t.accent,whiteSpace:"nowrap",verticalAlign:"top",width:"45%"},children:n}),i.jsx("td",{style:{padding:"5px 0",color:t.textSecondary,verticalAlign:"top",lineHeight:1.5},children:r})]},o))})})}const Xg=`block "Revenue by Channel" {
54
+ domain = "revenue"
55
+ type = "custom"
56
+ description = "Revenue grouped by sales channel"
57
+ owner = "data-team"
58
+ tags = ["revenue"]
59
+
60
+ params {
61
+ period = "current_quarter"
62
+ }
63
+
64
+ query = """
65
+ SELECT channel,
66
+ SUM(order_total) AS revenue
67
+ FROM read_csv_auto('data/orders.csv')
68
+ WHERE fiscal_period = \${period}
69
+ GROUP BY channel
70
+ ORDER BY revenue DESC
71
+ """
72
+
73
+ visualization {
74
+ chart = "bar"
75
+ x = channel
76
+ y = revenue
77
+ }
78
+
79
+ tests {
80
+ assert row_count > 0
81
+ }
82
+ }`,Kg=`# semantic-layer/metrics/total_revenue.yaml
83
+ name: total_revenue
84
+ label: Total Revenue
85
+ description: Sum of all recognized revenue.
86
+ domain: finance
87
+ sql: SUM(amount)
88
+ type: sum # sum|count|count_distinct|avg|min|max|custom
89
+ table: fct_revenue
90
+ tags:
91
+ - revenue
92
+ - kpi`,zg=`# semantic-layer/dimensions/segment.yaml
93
+ name: segment
94
+ label: Customer Segment
95
+ description: Customer segment tier.
96
+ sql: segment_tier
97
+ type: string # string|number|date|boolean
98
+ table: fct_revenue`,Jg=`# semantic-layer/hierarchies/time.yaml
99
+ name: fiscal_time
100
+ label: Fiscal Time
101
+ description: Drill from year to quarter.
102
+ domain: finance
103
+ levels:
104
+ - name: fiscal_year
105
+ dimension: fiscal_year
106
+ order: 1
107
+ - name: fiscal_quarter
108
+ dimension: fiscal_quarter
109
+ order: 2
110
+ defaultRollup: sum`,qg=`# semantic-layer/cubes/revenue_cube.yaml
111
+ name: revenue
112
+ label: Revenue Cube
113
+ table: fct_revenue
114
+ domain: finance
115
+
116
+ measures:
117
+ - name: total_revenue
118
+ sql: SUM(amount)
119
+ type: sum
120
+ - name: deal_count
121
+ sql: COUNT(*)
122
+ type: count
123
+
124
+ dimensions:
125
+ - name: segment_tier
126
+ sql: segment_tier
127
+ type: string
128
+
129
+ time_dimensions:
130
+ - name: recognized_at
131
+ sql: recognized_at
132
+ primary_time: true
133
+ granularities: [day, month, quarter, year]
134
+
135
+ joins:
136
+ - name: customers
137
+ type: left
138
+ sql: "\${left}.customer_id = \${right}.id"`,Qg=`{
139
+ "semanticLayer": {
140
+ "provider": "dql"
141
+ }
142
+ }`,Zg=`{
143
+ "semanticLayer": {
144
+ "provider": "dbt",
145
+ "projectPath": "/path/to/your/dbt-project"
146
+ }
147
+ }`,eL=`{
148
+ "semanticLayer": {
149
+ "provider": "cubejs",
150
+ "projectPath": "/path/to/your/cube-project"
151
+ }
152
+ }`,tL=`{
153
+ "defaultConnection": {
154
+ "driver": "file",
155
+ "filepath": ":memory:"
156
+ }
157
+ }`,nL=`{
158
+ "defaultConnection": {
159
+ "driver": "snowflake",
160
+ "account": "acme.snowflakecomputing.com",
161
+ "username": "your_user",
162
+ "password": "\${SNOWFLAKE_PASSWORD}",
163
+ "database": "ANALYTICS",
164
+ "schema": "PUBLIC",
165
+ "warehouse": "COMPUTE_WH",
166
+ "role": "ANALYST"
167
+ }
168
+ }`,rL=`{
169
+ "defaultConnection": {
170
+ "driver": "bigquery",
171
+ "project": "your-gcp-project-id",
172
+ "dataset": "analytics",
173
+ "keyFilename": "./service-account.json"
174
+ }
175
+ }`,oL=`{
176
+ "defaultConnection": {
177
+ "driver": "postgres",
178
+ "host": "localhost",
179
+ "port": 5432,
180
+ "database": "analytics",
181
+ "username": "your_user",
182
+ "password": "\${POSTGRES_PASSWORD}"
183
+ }
184
+ }`,sL=`-- Primary workflow: use Compose Query in the Semantic Layer panel
185
+ -- 1. Pick metrics + dimensions (+ optional time dimension)
186
+ -- 2. Click "Compose SQL"
187
+ -- 3. Click "+ Insert as Cell" → edit and run
188
+
189
+ -- Advanced: reference metrics inline in any SQL cell
190
+ -- DQL resolves @metric() and @dim() at query time
191
+ SELECT
192
+ @dim(segment_tier),
193
+ @metric(total_revenue)
194
+ FROM fct_revenue
195
+ GROUP BY @dim(segment_tier)
196
+ ORDER BY @metric(total_revenue) DESC`,iL=`{
197
+ "semanticLayer": {
198
+ "provider": "snowflake",
199
+ "projectPath": "MY_DATABASE"
200
+ }
201
+ }`;function bR({themeMode:e}){const t=re[e];return i.jsxs("div",{style:{flex:1,overflowY:"auto",fontFamily:t.font},children:[i.jsx(gt,{title:"SQL Essentials",defaultOpen:!0,t,children:i.jsx(De,{t,code:`-- Basic select
202
+ SELECT col1, col2
203
+ FROM table_name
204
+ WHERE condition
205
+ ORDER BY col1 DESC
206
+ LIMIT 100
207
+
208
+ -- GROUP BY
209
+ SELECT col, COUNT(*), SUM(val)
210
+ FROM table_name
211
+ GROUP BY col
212
+
213
+ -- JOIN
214
+ SELECT a.*, b.col
215
+ FROM table_a AS a
216
+ JOIN table_b AS b ON a.id = b.id
217
+
218
+ -- CTE (WITH)
219
+ WITH cte AS (
220
+ SELECT * FROM table_name WHERE val > 0
221
+ )
222
+ SELECT * FROM cte
223
+
224
+ -- Window function
225
+ SELECT *,
226
+ ROW_NUMBER() OVER (
227
+ PARTITION BY group_col
228
+ ORDER BY val DESC
229
+ ) AS rank
230
+ FROM table_name`})}),i.jsx(gt,{title:"DuckDB Functions",defaultOpen:!1,t,children:i.jsx(VE,{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"]]})}),i.jsxs(gt,{title:"DQL Block Structure",defaultOpen:!0,t,children:[i.jsx(De,{t,code:Xg}),i.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.6},children:["Run ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql certify <file> --connection duckdb"})," to execute ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"tests {}"})," assertions against live data. Use ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"--skip-tests"})," to check governance fields only."]})]}),i.jsxs(gt,{title:"DQL Chart Types",defaultOpen:!1,t,children:[i.jsx(VE,{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)"]]}),i.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.6},children:["Set chart type inside the"," ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:'visualization { chart = "pie"; x = label_col; y = value_col }'})," ","block."]})]}),i.jsxs(gt,{title:"Semantic Layer Usage",defaultOpen:!1,t,children:[i.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:6},children:["Primary workflow: open the ",i.jsx("strong",{children:"Semantic Layer"})," panel → Compose Query → pick metrics and dimensions → Compose SQL → + Insert as Cell. Advanced: use ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"@metric(name)"})," and ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"@dim(name)"})," refs directly in any SQL cell."]}),i.jsx(De,{t,code:sL})]}),i.jsxs(gt,{title:"Semantic Layer",defaultOpen:!1,t,children:[i.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"," ",i.jsx("strong",{style:{color:t.textPrimary},children:"Semantic Layer"})," sidebar panel."]}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"10px 0 4px",letterSpacing:"0.03em"},children:"Directory Structure"}),i.jsx(De,{t,code:`my-project/
231
+ ├── dql.config.json
232
+ └── semantic-layer/
233
+ ├── metrics/ ← one YAML per metric
234
+ ├── dimensions/ ← one YAML per dimension
235
+ ├── hierarchies/ ← optional drill paths
236
+ └── cubes/ ← optional (groups all into one)`}),i.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:[i.jsx("strong",{style:{color:t.textPrimary},children:"Recommended:"})," For multi-table projects, use a ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"cubes/"})," file — it keeps metrics, dimensions, and joins together. Use standalone ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"metrics/"})," and ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dimensions/"})," files only for simple single-table projects."]}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Metric YAML"}),i.jsx(De,{t,code:Kg}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Dimension YAML"}),i.jsx(De,{t,code:zg}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Hierarchy YAML"}),i.jsx(De,{t,code:Jg}),i.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)"}),i.jsx(De,{t,code:qg})]}),i.jsxs(gt,{title:"Semantic Layer Providers",defaultOpen:!1,t,children:[i.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Add to your ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"})," to connect a semantic layer provider."]}),i.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/)"}),i.jsx(De,{t,code:Qg}),i.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)"}),i.jsx(De,{t,code:Zg}),i.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 ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dbt_project.yml"}),"). Reads ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"semantic_models"})," and"," ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"metrics"})," blocks (dbt 1.6+)."]}),i.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/)"}),i.jsx(De,{t,code:eL}),i.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"," ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"cubes:"})," blocks from YAML schema files."]}),i.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)"}),i.jsx(De,{t,code:iL}),i.jsxs("div",{style:{marginTop:4,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Introspects Snowflake semantic views via"," ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"SHOW SEMANTIC VIEWS"}),". Set ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"projectPath"})," to your database name to scope discovery. Requires a Snowflake connection in ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"defaultConnection"}),"."]})]}),i.jsxs(gt,{title:"Connection Setup",defaultOpen:!1,t,children:[i.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Configure ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"defaultConnection"})," in"," ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"}),"."]}),i.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)"}),i.jsx(De,{t,code:tL}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Snowflake"}),i.jsx(De,{t,code:nL}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"BigQuery"}),i.jsx(De,{t,code:rL}),i.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"PostgreSQL"}),i.jsx(De,{t,code:oL}),i.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Use ",i.jsxs("code",{style:{fontFamily:t.fontMono,fontSize:10},children:["$","${ENV_VAR}"]})," syntax for secrets. Run ",i.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dql doctor"})," to verify your connection."]})]}),i.jsxs(gt,{title:"Variable References",defaultOpen:!1,t,children:[i.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Use"," ",i.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"{{cell_name}}"})," ","to reference other cells:",i.jsxs("ul",{style:{margin:"6px 0 0",paddingLeft:18},children:[i.jsxs("li",{children:[i.jsx("strong",{children:"Param cell"})," → substituted as a SQL literal value"]}),i.jsxs("li",{children:[i.jsx("strong",{children:"SQL cell"})," → injected as a CTE"]})]})]}),i.jsx(De,{t,code:`-- Param cell named "start_date" holds '2024-01-01'
237
+ SELECT *
238
+ FROM read_csv_auto('data/sales.csv')
239
+ WHERE date >= {{start_date}}
240
+
241
+ -- SQL cell named "base_query" used as CTE
242
+ SELECT segment, SUM(revenue) AS total
243
+ FROM {{base_query}}
244
+ GROUP BY segment`})]})]})}const we={source_table:"#8b949e",dbt_model:"#ff7b72",dbt_source:"#79c0ff",block:"#56d364",metric:"#388bfd",dimension:"#e3b341",domain:"#d2a8ff",chart:"#f778ba",dashboard:"#d2a8ff"},_c={source_table:"TBL",dbt_model:"DBT",dbt_source:"SRC",block:"BLK",metric:"MET",dimension:"DIM",domain:"DOM",chart:"CHT",dashboard:"DASH"},Ci={source_table:"Source Table",dbt_model:"dbt Model",dbt_source:"dbt Source",block:"DQL Block",metric:"Metric",dimension:"Dimension",domain:"Domain",chart:"Chart",dashboard:"Notebook"},Br={reads_from:"#8b949e",feeds_into:"#56d364",aggregates:"#388bfd",visualizes:"#f778ba",depends_on:"#ff7b72",contains:"#d2a8ff",crosses_domain:"#d2a8ff"},aL={reads_from:"reads from",feeds_into:"feeds into",aggregates:"aggregates into",visualizes:"visualizes",depends_on:"dbt depends on",contains:"contains",crosses_domain:"crosses domain"},lL={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},$E={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"},Fs=["source","transform","answer","consumption"];function xc(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"dashboard":return"consumption";default:return"answer"}}function vR({type:e}){const t=we[e]??"#8b949e";return i.jsx("span",{style:{color:t,fontSize:10,fontWeight:700,textTransform:"uppercase",minWidth:34},title:Ci[e]??e,children:_c[e]??e.slice(0,4).toUpperCase()})}function cL({value:e,onChange:t,placeholder:n,t:r}){return i.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 UR({node:e,t,onClick:n,secondary:r}){return i.jsxs("button",{onClick:n,style:{width:"100%",textAlign:"left",background:"transparent",border:"none",borderRadius:6,padding:"6px 8px",cursor:"pointer",color:t.textPrimary},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx(vR,{type:e.type}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},title:e.name,children:e.name})]}),(r||e.domain)&&i.jsx("div",{style:{marginLeft:40,marginTop:2,color:t.textMuted,fontSize:11},children:r??e.domain})]})}const EL=30,pa=200;function Lt({title:e,nodes:t,t:n,onSelect:r}){const o=t.length>EL,[s,a]=R.useState(!o),[l,E]=R.useState(pa);if(t.length===0)return null;const c=s?Math.min(l,t.length):0,d=Math.max(0,t.length-c);return i.jsxs("div",{style:{padding:"8px 0",borderTop:`1px solid ${n.headerBorder}`},children:[i.jsxs("button",{onClick:()=>a(u=>!u),"aria-expanded":s,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:[i.jsx("span",{style:{display:"inline-block",width:10},children:s?"▾":"▸"}),i.jsx("span",{children:e}),i.jsx("span",{style:{marginLeft:"auto",fontWeight:500},children:t.length})]}),s&&t.slice(0,c).map(u=>i.jsx(UR,{node:u,t:n,onClick:()=>r(u)},u.id)),s&&d>0&&i.jsxs("button",{onClick:()=>E(u=>u+pa),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(pa,d)," more (",d," hidden)"]})]})}function dL(){const{state:e,dispatch:t}=de(),n=re[e.themeMode],[r,o]=R.useState(!0),[s,a]=R.useState([]),[l,E]=R.useState([]),[c,d]=R.useState(""),[u,T]=R.useState([]),[S,A]=R.useState(null),[f,I]=R.useState(null),p=R.useCallback(async()=>{o(!0);const _=await Q.fetchLineage();a(_.nodes??[]),E(_.edges??[]),o(!1)},[]);R.useEffect(()=>{p()},[p]),R.useEffect(()=>{let _=!1;if(c.trim().length<2){T([]);return}return Q.searchLineage(c.trim()).then(U=>{_||T(U.matches??[])}),()=>{_=!0}},[c]);const O=R.useCallback(async _=>{const U=await Q.queryLineage({focus:_.id});A(U.focalNode??_),I(U.graph??{nodes:[],edges:[]}),t({type:"SET_LINEAGE_FOCUS",nodeId:_.id}),t({type:"SET_INSPECTOR_CONTEXT",context:{kind:"lineage-node",nodeId:_.id}}),e.lineageFullscreen||t({type:"TOGGLE_LINEAGE_FULLSCREEN"})},[t,e.lineageFullscreen]),N=R.useCallback(()=>{A(null),I(null),d(""),T([]),t({type:"SET_LINEAGE_FOCUS",nodeId:null})},[t]),[h,C]=R.useState("type"),m=R.useMemo(()=>({dashboards:s.filter(_=>_.type==="dashboard"),blocks:s.filter(_=>_.type==="block"),dbtModels:s.filter(_=>_.type==="dbt_model"),dbtSources:s.filter(_=>_.type==="dbt_source"),tables:s.filter(_=>_.type==="source_table"),domains:s.filter(_=>_.type==="domain")}),[s]),g=R.useMemo(()=>{const _={source:[],transform:[],answer:[],consumption:[]};for(const U of s){const D=xc(U);_[D].push(U)}return _},[s]),y=R.useMemo(()=>{if(!S||!f)return{upstream:[],downstream:[]};const _=new Set(f.edges.filter(D=>D.target===S.id).map(D=>D.source)),U=new Set(f.edges.filter(D=>D.source===S.id).map(D=>D.target));return{upstream:f.nodes.filter(D=>_.has(D.id)),downstream:f.nodes.filter(D=>U.has(D.id))}},[f,S]);return r?i.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"Loading lineage..."}):s.length===0?i.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"No lineage data found yet. Run `dql compile` or add notebooks/blocks first."}):i.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[i.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[i.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",marginBottom:8},children:e.lineageFullscreen?"Close Graph View":"Open Graph View"}),i.jsx(cL,{value:c,onChange:d,placeholder:"Search blocks, tables, dbt models, notebooks...",t:n}),i.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."})]}),i.jsxs("div",{style:{flex:1,overflow:"auto"},children:[c.trim().length>=2&&u.length>0&&i.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsx("div",{style:{color:n.textMuted,fontSize:11,fontWeight:700,textTransform:"uppercase",marginBottom:6},children:"Search Results"}),u.slice(0,8).map(_=>i.jsx(UR,{node:_.node,t:n,onClick:()=>O(_.node),secondary:_.node.domain},_.node.id))]}),S&&f&&i.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[i.jsx(vR,{type:S.type}),i.jsxs("div",{style:{flex:1,minWidth:0},children:[i.jsx("div",{style:{color:n.textPrimary,fontSize:13,fontWeight:700},children:S.name}),i.jsx("div",{style:{color:n.textMuted,fontSize:11},children:S.domain??Ci[S.type]??S.type})]}),i.jsx("button",{onClick:N,style:{border:`1px solid ${n.headerBorder}`,background:"transparent",color:n.textPrimary,borderRadius:6,padding:"6px 8px",cursor:"pointer",fontSize:11},children:"Show All"})]}),i.jsxs("div",{style:{color:n.textMuted,fontSize:11,marginBottom:6},children:[f.nodes.length," node(s), ",f.edges.length," edge(s)"]}),i.jsx("div",{style:{color:n.textMuted,fontSize:11,marginBottom:6,lineHeight:1.5},children:"Focused lineage shows the path into this item from raw tables/dbt and the downstream notebooks or analytics objects that consume it."}),i.jsx(Lt,{title:"Upstream",nodes:y.upstream,t:n,onSelect:O}),i.jsx(Lt,{title:"Downstream",nodes:y.downstream,t:n,onSelect:O})]}),!S&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:{padding:"6px 8px",display:"flex",gap:8,flexWrap:"wrap",borderBottom:`1px solid ${n.headerBorder}`},children:[Fs.map(_=>{const U=g[_].length;return U===0?null:i.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:10,color:n.textMuted},children:[i.jsx("span",{style:{width:8,height:8,borderRadius:2,background:lL[_],display:"inline-block"}}),$E[_],": ",U]},_)}),i.jsx("span",{style:{flex:1}}),i.jsxs("div",{style:{display:"flex",borderRadius:4,border:`1px solid ${n.headerBorder}`,overflow:"hidden"},children:[i.jsx("button",{onClick:()=>C("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"}),i.jsx("button",{onClick:()=>C("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"?i.jsxs(i.Fragment,{children:[i.jsx(Lt,{title:"Notebooks",nodes:m.dashboards,t:n,onSelect:O}),i.jsx(Lt,{title:"DQL Blocks",nodes:m.blocks,t:n,onSelect:O}),i.jsx(Lt,{title:"dbt Models",nodes:m.dbtModels,t:n,onSelect:O}),i.jsx(Lt,{title:"dbt Sources",nodes:m.dbtSources,t:n,onSelect:O}),i.jsx(Lt,{title:"Source Tables",nodes:m.tables,t:n,onSelect:O}),i.jsx(Lt,{title:"Business Domains",nodes:m.domains,t:n,onSelect:O})]}):i.jsx(i.Fragment,{children:Fs.map(_=>i.jsx(Lt,{title:$E[_],nodes:g[_],t:n,onSelect:O},_))})]})]})]})}const XE={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149",pending_recertification:"#db6d28"};function uL(){const{state:e,dispatch:t}=de(),n=re[e.themeMode],[r,o]=R.useState([]),[s,a]=R.useState(!0),[l,E]=R.useState(""),[c,d]=R.useState(""),[u,T]=R.useState("");R.useEffect(()=>{a(!0),Q.getBlockLibrary().then(O=>o(O.blocks)).finally(()=>a(!1))},[]);const S=[...new Set(r.map(O=>O.domain))].sort(),A=[...new Set(r.map(O=>O.status))].sort(),f=r.filter(O=>!(l&&!O.name.toLowerCase().includes(l.toLowerCase())&&!O.description.toLowerCase().includes(l.toLowerCase())||c&&O.domain!==c||u&&O.status!==u)),I=O=>{const N={name:O.path.split("/").pop()??O.name,path:O.path,type:"block",folder:"blocks"};e.files.some(h=>h.path===O.path)||t({type:"FILE_ADDED",file:N}),Q.openBlockStudio(O.path).then(h=>{t({type:"OPEN_BLOCK_STUDIO",file:N,payload:h})})},p={background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:4,color:n.textPrimary,fontSize:11,fontFamily:n.font,padding:"4px 6px",outline:"none"};return i.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[i.jsxs("div",{style:{padding:"10px 12px",borderBottom:`1px solid ${n.headerBorder}`,display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{fontSize:12,fontWeight:600,color:n.textPrimary,fontFamily:n.font},children:"Blocks"}),i.jsx("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:f.length}),i.jsx("span",{style:{flex:1}}),i.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"}),i.jsx("button",{onClick:()=>{a(!0),Q.getBlockLibrary().then(O=>o(O.blocks)).finally(()=>a(!1))},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"})]}),i.jsxs("div",{style:{padding:"8px 12px",borderBottom:`1px solid ${n.headerBorder}`,display:"flex",gap:6,flexWrap:"wrap"},children:[i.jsx("input",{value:l,onChange:O=>E(O.target.value),placeholder:"Search blocks...",style:{...p,flex:1,minWidth:100}}),i.jsxs("select",{value:c,onChange:O=>d(O.target.value),style:p,children:[i.jsx("option",{value:"",children:"All domains"}),S.map(O=>i.jsx("option",{value:O,children:O},O))]}),i.jsxs("select",{value:u,onChange:O=>T(O.target.value),style:p,children:[i.jsx("option",{value:"",children:"All statuses"}),A.map(O=>i.jsx("option",{value:O,children:O},O))]})]}),i.jsx("div",{style:{flex:1,overflowY:"auto"},children:s?i.jsx("div",{style:{padding:20,textAlign:"center",fontSize:12,color:n.textMuted,fontFamily:n.font},children:"Loading blocks..."}):f.length===0?i.jsx("div",{style:{padding:20,textAlign:"center",fontSize:12,color:n.textMuted,fontFamily:n.font},children:r.length===0?"No blocks found. Create your first block to get started.":"No blocks match your filters."}):f.map(O=>i.jsxs("button",{onClick:()=>I(O),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:N=>{N.currentTarget.style.background=`${n.accent}0a`},onMouseLeave:N=>{N.currentTarget.style.background="transparent"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[i.jsx("span",{style:{fontSize:12,fontWeight:600,color:n.textPrimary,fontFamily:n.font},children:O.name}),i.jsx("span",{style:{fontSize:9,fontWeight:600,color:XE[O.status]??n.textMuted,background:`${XE[O.status]??n.textMuted}18`,padding:"1px 6px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em",fontFamily:n.font},children:O.status})]}),O.description&&i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font,lineHeight:1.3,marginBottom:4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:O.description}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:n.textMuted,fontFamily:n.font},children:[i.jsx("span",{style:{background:n.pillBg,padding:"1px 6px",borderRadius:4},children:O.domain}),O.owner&&i.jsxs("span",{children:["by ",O.owner]}),i.jsx("span",{style:{marginLeft:"auto"},children:new Date(O.lastModified).toLocaleDateString()})]})]},O.path))})]})}function TL(){var I;const{state:e}=de(),t=re[e.themeMode],[n,r]=R.useState("status"),[o,s]=R.useState(null),[a,l]=R.useState(null),[E,c]=R.useState(""),[d,u]=R.useState(null),[T,S]=R.useState(!1),A=R.useCallback(async()=>{S(!0);try{if(n==="status")s(await Q.fetchGitStatus());else if(n==="log")l(await Q.fetchGitLog(30));else{const p=await Q.fetchGitDiff(d??void 0);c(p.diff)}}finally{S(!1)}},[n,d]);R.useEffect(()=>{A()},[A]);const f=((I=e.activeFile)==null?void 0:I.path)??null;return i.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",color:t.textPrimary,fontFamily:t.font},children:[i.jsxs("div",{style:{display:"flex",gap:4,padding:"8px 10px",borderBottom:`1px solid ${t.headerBorder}`},children:[i.jsx(Ia,{t,active:n==="status",onClick:()=>r("status"),children:"Status"}),i.jsx(Ia,{t,active:n==="log",onClick:()=>r("log"),children:"Log"}),i.jsx(Ia,{t,active:n==="diff",onClick:()=>r("diff"),children:"Diff"}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{onClick:()=>void A(),title:"Refresh",style:{background:"transparent",border:"none",cursor:"pointer",color:t.textMuted,padding:"2px 6px",borderRadius:4,fontSize:12},children:"↻"})]}),i.jsxs("div",{style:{flex:1,overflow:"auto",padding:10,fontSize:12},children:[T&&i.jsx("div",{style:{color:t.textMuted},children:"Loading…"}),!T&&n==="status"&&o&&i.jsx(SL,{status:o,t}),!T&&n==="log"&&a&&i.jsx(RL,{log:a,t}),!T&&n==="diff"&&i.jsx(fL,{diff:E,activeFilePath:f,diffPath:d,onScopeToFile:()=>u(f),onClearScope:()=>u(null),t})]})]})}function SL({status:e,t}){return e.inRepo?i.jsxs("div",{children:[i.jsxs("div",{style:{marginBottom:10},children:[i.jsx("span",{style:{color:t.textMuted},children:"Branch"})," ",i.jsx("span",{style:{color:t.accent,fontWeight:600},children:e.branch??"detached"}),e.ahead>0&&i.jsxs("span",{style:{marginLeft:8,color:t.textMuted},children:["↑ ",e.ahead]}),e.behind>0&&i.jsxs("span",{style:{marginLeft:8,color:t.textMuted},children:["↓ ",e.behind]})]}),e.changes.length===0?i.jsx("div",{style:{color:t.textMuted},children:"Working tree clean."}):i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:2,fontFamily:t.fontMono,fontSize:11},children:e.changes.map(n=>i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx("span",{style:{color:AL(n.status,t),width:22},children:n.status.trim()||"??"}),i.jsx("span",{style:{color:t.textPrimary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.path})]},n.path))})]}):i.jsx("div",{style:{color:t.textMuted},children:"Not a git repository."})}function RL({log:e,t}){return e.inRepo?e.commits.length===0?i.jsx("div",{style:{color:t.textMuted},children:"No commits."}):i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:e.commits.map(n=>i.jsxs("div",{style:{borderLeft:`2px solid ${t.headerBorder}`,paddingLeft:8},children:[i.jsx("div",{style:{color:t.textPrimary,fontSize:12},children:n.subject}),i.jsxs("div",{style:{color:t.textMuted,fontSize:10,marginTop:2,fontFamily:t.fontMono},children:[n.hash.slice(0,7)," · ",n.author," · ",n.date]})]},n.hash))}):i.jsx("div",{style:{color:t.textMuted},children:"Not a git repository."})}function fL({diff:e,activeFilePath:t,diffPath:n,onScopeToFile:r,onClearScope:o,t:s}){return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[i.jsxs("div",{style:{display:"flex",gap:6,fontSize:11},children:[i.jsx("button",{onClick:o,style:KE(n==null,s),children:"All"}),t&&i.jsx("button",{onClick:r,style:KE(n===t,s),children:"Active file"}),n&&i.jsx("span",{style:{color:s.textMuted,fontSize:10,alignSelf:"center",fontFamily:s.fontMono},children:n})]}),e.trim()===""?i.jsx("div",{style:{color:s.textMuted},children:"No unstaged changes."}):i.jsx("pre",{style:{fontFamily:s.fontMono,fontSize:11,margin:0,padding:8,background:s.editorBg,border:`1px solid ${s.editorBorder}`,borderRadius:6,overflow:"auto",whiteSpace:"pre",color:s.textPrimary},children:e.split(`
245
+ `).map((a,l)=>i.jsx("div",{style:{color:pL(a,s)},children:a||" "},l))})]})}function Ia({active:e,onClick:t,children:n,t:r}){return i.jsx("button",{onClick:t,style:{background:e?r.btnHover:"transparent",color:e?r.textPrimary:r.textMuted,border:"none",padding:"3px 10px",borderRadius:4,fontSize:11,fontWeight:600,cursor:"pointer"},children:n})}function KE(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 AL(e,t){const n=e.trim();return n==="M"||n==="MM"?t.warning:n==="A"||n==="??"?t.success:n==="D"?t.error:n.startsWith("R")?t.accent:t.textMuted}function pL(e,t){return e.startsWith("+++")||e.startsWith("---")?t.textMuted:e.startsWith("+")?t.success:e.startsWith("-")?t.error:e.startsWith("@@")?t.accent:t.textPrimary}const IL={files:"Explorer",schema:"Schema",block_library:"Block Library",lineage:"Lineage",connection:"Connection",reference:"Quick Reference",git:"Git"};function OL({onOpenFile:e}){const{state:t,dispatch:n}=de(),r=re[t.themeMode],[o,s]=R.useState(!1),a=t.sidebarPanel;return i.jsxs("div",{style:{width:240,flexShrink:0,background:r.sidebarBg,borderRight:`1px solid ${r.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden"},children:[i.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:[i.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",color:r.textSecondary,fontFamily:r.font},children:IL[a??""]??""}),i.jsx("button",{title:"Collapse sidebar",onClick:()=>n({type:"TOGGLE_SIDEBAR"}),onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!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:"‹"})]}),i.jsxs("div",{style:{flex:1,overflow:"hidden",display:"flex",flexDirection:"column"},children:[a==="files"&&i.jsx(vg,{onOpenFile:e}),a==="schema"&&i.jsx(Gg,{}),a==="block_library"&&i.jsx(uL,{}),a==="lineage"&&i.jsx(dL,{}),a==="connection"&&i.jsx(PR,{}),a==="reference"&&i.jsx(bR,{themeMode:t.themeMode}),a==="git"&&i.jsx(TL,{})]})]})}function NL(e){try{const t=e.match(/workbook\s+"([^"]+)"/i),n=t?t[1]:"Untitled Workbook",r=[],o=/page\s+"([^"]+)"\s*\{([\s\S]*?)\}/gi;let s;for(;(s=o.exec(e))!==null;){const a=s[1],l=s[2].trim();r.push({id:yt(),type:"markdown",content:`# ${a}`,status:"idle"}),l&&r.push({id:yt(),type:"dql",name:a.toLowerCase().replace(/\s+/g,"_"),content:l,status:"idle"})}return r.length===0&&r.push({id:yt(),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:yt(),type:"dql",content:e.trim(),status:"idle"}]}}}function hL(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||yt(),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}:{}})),{title:s,...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:yt(),type:"sql",content:e,status:"idle"}]}}}function mL(e,t,n){const r={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}:{}}))};return JSON.stringify(r,null,2)}function CL(e,t){return e.endsWith(".dql")?NL(t):hL(t)}const wR=/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g;function gL(e){const t=new Set;for(const n of e.matchAll(wR))t.add(n[1]);return[...t]}function LL(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(E=>{const c=a[E];return c==null?"NULL":typeof c=="number"?String(c):typeof c=="boolean"?c?"TRUE":"FALSE":`'${String(c).replace(/'/g,"''")}'`}).join(", ")})`).join(`,
246
+ `),s=n.map(a=>`"${a.replace(/"/g,'""')}"`).join(", ");return`${e} AS (
247
+ SELECT * FROM (VALUES
248
+ ${o}
249
+ ) AS _t(${s})
250
+ )`}function _L(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function xL(){const{state:e}=de();return{substituteVariables:R.useCallback(n=>{var c;const r=[...n.matchAll(wR)];if(r.length===0)return{sql:n,substituted:[]};const o=[],s=[];let a=n;const l=new Map,E=new Map;for(const d of e.cells){const u=(c=d.name)==null?void 0:c.trim();u&&(d.type==="param"?l.set(u,d):d.status==="success"&&d.result&&E.set(u,d.result))}for(const d of r){const u=d[1];if(l.has(u)){const T=l.get(u),S=T.paramConfig,A=T.paramValue??(S==null?void 0:S.defaultValue)??"",f=(S==null?void 0:S.paramType)??"text",I=_L(A,f);a=a.replace(d[0],I),o.push(u)}else E.has(u)&&(s.push(LL(u,E.get(u))),a=a.replace(d[0],`"${u}"`),o.push(u))}if(s.length===0&&o.length===0)return{sql:n,substituted:[]};if(s.length>0){const d=a.trimStart();/^WITH\s+/i.test(d)?a=a.replace(/^(\s*WITH\s+)/i,`$1${s.join(`,
251
+ `)},
252
+ `):a=`WITH ${s.join(`,
253
+ `)}
254
+ ${a}`}return{sql:a,substituted:o}},[e.cells])}}function yL(e){var s;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:(s=n.match(/\btitle\s*=\s*"([^"]+)"/i))==null?void 0:s[1]}}function DL(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 s=o[0];const a=s.search(/\b(visualization|tests|block)\s*\{/i);return a>0&&(s=s.slice(0,a)),s=ML(s),s.trim()||null}return null}function ML(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 s=o;for(;s<e.length&&/\s/.test(e[s]);)s++;if(s<e.length&&e[s]==="="&&e[s+1]!=="=")return e.slice(0,n)}}}return e}function zE(e){const t=Ln(e);return t?{name:t.name,domain:t.domain,owner:t.owner,description:t.description,blockType:t.blockType,tags:t.tags}:null}function Oa(e,t,n){const r=Ln(e);if(!r){const s=n.replace(/"/g,'\\"'),a=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return a.test(e)?e.replace(a,`$1"${s}"`):yc(e,` ${t} = "${s}"`)}const o={...r};return t==="domain"&&(o.domain=n),t==="owner"&&(o.owner=n),t==="description"&&(o.description=n),t==="type"&&(o.blockType=n),Ar(o)}function BR(e,t){const n=Ln(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 Ar({...n,name:t})}function PL(e,t){const n=Ln(e);if(!n){const r=t.map(s=>`"${s.replace(/"/g,'\\"')}"`).join(", "),o=/(\btags\s*=\s*)\[[^\]]*\]/i;return o.test(e)?e.replace(o,`$1[${r}]`):yc(e,` tags = [${r}]`)}return Ar({...n,tags:t})}function bL(e,t){const n=Ln(e),r=BL(t);return n?Ar({...n,visualization:r}):/visualization\s*\{[\s\S]*?\n\s*\}/i.test(e)?e.replace(/visualization\s*\{[\s\S]*?\n\s*\}/i,r):yc(e,` ${r.replace(/\n/g,`
255
+ `)}`,!0)}function vL(e,t){return e==="metric"?`@metric(${t})`:`@dim(${t})`}function UL(e,t){const n=Ln(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 s=Array.from(o);r.metric=s.length===1?s[0]:"",r.metrics=s.length>1?s:[]}else r.dimensions.includes(t.name)||(r.dimensions=[...r.dimensions,t.name]);return Ar(r)}function wL(e,t){const n=Ln(e);if(!n||n.blockType!=="custom")return`${e.trimEnd()}
256
+ ${t}
257
+ `;const r=n.query.trimEnd(),o=r?`${r}
258
+ ${t}`:t;return Ar({...n,query:o})}function Ln(e){var s,a;if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=l=>{var E;return((E=e.match(new RegExp(`\\b${l}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:E[1])??""},n=((s=e.match(/^\s*block\s+"([^"]+)"/i))==null?void 0:s[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:JE(e,"metrics"),dimensions:JE(e,"dimensions"),timeDimension:t("time_dimension"),granularity:t("granularity"),query:((a=o==null?void 0:o[1])==null?void 0:a.trim())??"",visualization:qE(e,"visualization"),tests:qE(e,"tests")}}function JE(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 qE(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 s=n.index;s<e.length;s++){const a=e[s];if(a==="{")r===0&&(o=s),r++;else if(a==="}"&&(r--,r===0&&o>=0))return e.slice(n.index,s+1).trim()}return""}function Ar(e){const t=[`block "${et(e.name||"New Block")}" {`,` domain = "${et(e.domain||"uncategorized")}"`,` type = "${e.blockType}"`,` description = "${et(e.description)}"`,` owner = "${et(e.owner)}"`,` tags = [${e.tags.map(n=>`"${et(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 = "${et(n[0])}"`):n.length>1&&t.push(` metrics = [${n.map(r=>`"${et(r)}"`).join(", ")}]`),e.dimensions.length>0&&t.push(` dimensions = [${Array.from(new Set(e.dimensions)).map(r=>`"${et(r)}"`).join(", ")}]`),e.timeDimension&&t.push(` time_dimension = "${et(e.timeDimension)}"`),e.granularity&&t.push(` granularity = "${et(e.granularity)}"`)}return e.blockType==="custom"&&(t.push(""),t.push(' query = """'),t.push(...FL(e.query.trim(),4)),t.push(' """')),e.visualization&&(t.push(""),t.push(...QE(e.visualization,2))),e.tests&&(t.push(""),t.push(...QE(e.tests,2))),t.push("}"),t.join(`
259
+ `)+`
260
+ `}function BL(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 = "${et(e.title)}"`),t.push("}"),t.join(`
261
+ `)}function FL(e,t){const n=" ".repeat(t);return(e?e.split(`
262
+ `):[""]).map(o=>`${n}${o}`)}function QE(e,t){const n=" ".repeat(t);return e.split(`
263
+ `).map(r=>`${n}${r.trimEnd()}`)}function et(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function yc(e,t,n=!1){const r=e.trimEnd();if(!/^\s*block\s+"/i.test(r))return`${r}
264
+ ${t}
265
+ `;const o=n?`
266
+
267
+ ${t}
268
+ `:`
269
+ ${t}`;return r.replace(/\n\}\s*$/,`${o}
270
+ }`)}const _r=new Map;function GL(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?DL(t):null}function gi(){const{state:e,dispatch:t}=de(),{substituteVariables:n}=xL(),r=R.useCallback(async l=>{const E=e.cells.find(A=>A.id===l);if(!E)return;const c=GL(E);if(!c)return;if(E.type==="dql"){const A=yL(E.content);A&&JSON.stringify(A)!==JSON.stringify(E.chartConfig)&&t({type:"UPDATE_CELL",id:l,updates:{chartConfig:A}})}const{sql:d}=n(c),u=Date.now(),T=_r.get(l);T&&T.abort();const S=new AbortController;_r.set(l,S),t({type:"UPDATE_CELL",id:l,updates:{status:"running",error:void 0,result:void 0}});try{const A=await Q.executeQuery(d,S.signal),f=Date.now()-u,I=(E.executionCount??0)+1;t({type:"UPDATE_CELL",id:l,updates:{status:"success",result:{...A,executionTime:A.executionTime??f,rowCount:A.rowCount??A.rows.length},executionCount:I}}),t({type:"APPEND_QUERY_LOG",entry:{id:yt(),cellName:E.name??E.id,rows:A.rowCount??A.rows.length,time:A.executionTime??f,ts:new Date}}),setTimeout(()=>{t({type:"UPDATE_CELL",id:l,updates:{status:"idle"}})},2e3)}catch(A){if(S.signal.aborted){t({type:"UPDATE_CELL",id:l,updates:{status:"idle",error:void 0}});return}const f=Date.now()-u,I=A instanceof Error?A.message:String(A);t({type:"UPDATE_CELL",id:l,updates:{status:"error",error:I,executionCount:(E.executionCount??0)+1}}),t({type:"APPEND_QUERY_LOG",entry:{id:yt(),cellName:E.name??E.id,rows:0,time:f,ts:new Date,error:I}})}finally{_r.delete(l)}},[e.cells,t]),o=R.useCallback(async()=>{for(const l of e.cells)l.type!=="markdown"&&await r(l.id)},[e.cells,r]),s=R.useCallback(async l=>{if(!l)return;const E=`{{${l}}}`;for(const c of e.cells)c.type==="markdown"||c.type==="param"||c.content.includes(E)&&await r(c.id)},[e.cells,r]),a=R.useCallback(l=>{const E=_r.get(l);E&&(E.abort(),_r.delete(l)),t({type:"UPDATE_CELL",id:l,updates:{status:"idle"}})},[t]);return{executeCell:r,executeAll:o,executeDependents:s,cancelCell:a}}function Be(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function HL(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 kL(e){const t=e.split(`
271
+ `),n=[];let r=!1,o=!1;for(const s of t){const a=s;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(Be(a));continue}if(a.startsWith("### ")){o&&(n.push("</ul>"),o=!1),n.push(`<h3>${Be(a.slice(4))}</h3>`);continue}if(a.startsWith("## ")){o&&(n.push("</ul>"),o=!1),n.push(`<h2>${Be(a.slice(3))}</h2>`);continue}if(a.startsWith("# ")){o&&(n.push("</ul>"),o=!1),n.push(`<h1>${Be(a.slice(2))}</h1>`);continue}if(a.startsWith("> ")){o&&(n.push("</ul>"),o=!1),n.push(`<blockquote><p>${Be(a.slice(2))}</p></blockquote>`);continue}if(a.startsWith("- ")||a.startsWith("* ")){o||(n.push("<ul>"),o=!0),n.push(`<li>${ZE(a.slice(2))}</li>`);continue}if(o&&(n.push("</ul>"),o=!1),a.trim()===""){n.push("<br>");continue}n.push(`<p>${ZE(a)}</p>`)}return o&&n.push("</ul>"),r&&n.push("</code></pre>"),n.join(`
272
+ `)}function ZE(e){return Be(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>")}function YL(e){const{columns:t,rows:n}=e,r=n.slice(0,200),o=n.length>200,s=t.map(l=>`<th>${Be(l)}</th>`).join(""),a=r.map(l=>`<tr>${t.map(c=>{const d=l[c],u=typeof d=="number",T=d==null?"—":String(d);return`<td${u?' class="num"':""}>${Be(T)}</td>`}).join("")}</tr>`).join("");return`
273
+ <div class="table-wrap">
274
+ <table>
275
+ <thead><tr>${s}</tr></thead>
276
+ <tbody>${a}</tbody>
277
+ </table>
278
+ ${o?`<p class="truncated">Showing first 200 of ${n.length.toLocaleString()} rows</p>`:""}
279
+ </div>`}function jL(e){const{columns:t,rows:n}=e;if(t.length<2||n.length===0)return null;const r=t.find(s=>typeof n[0][s]=="number"),o=t.find(s=>s!==r);return!r||!o?null:{labelCol:o,valueCol:r}}function WL(e){const t=jL(e);if(!t)return null;const n=e.rows.slice(0,20).map(d=>({label:String(d[t.labelCol]??""),value:Number(d[t.valueCol]??0)})),r=Math.max(...n.map(d=>d.value),1),o=28,s=6,a=140,l=440,E=n.length*(o+s)+40,c=n.map((d,u)=>{const T=u*(o+s)+20,S=Math.max(d.value/r*l,2);return`
280
+ <text x="${a-6}" y="${T+o/2+4}" text-anchor="end" font-size="11" fill="#8b949e">${Be(d.label.slice(0,20))}</text>
281
+ <rect x="${a}" y="${T}" width="${S}" height="${o}" rx="3" fill="#388bfd" />
282
+ <text x="${a+S+5}" y="${T+o/2+4}" font-size="11" fill="#e6edf3">${HL(d.value)}</text>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" width="${a+l+80}" height="${E}" style="max-width:100%">${c}</svg>`}function VL(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${kL(r.content)}</section>`;const o=r.name?`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span><span class="cell-name">${Be(r.name)}</span></div>`:`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span></div>`,s=`<pre class="cell-code"><code>${Be(r.content)}</code></pre>`;let a="";if(r.result&&r.result.rows.length>0){const l=WL(r.result),E=YL(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?"":E}</div>`}else r.error&&(a=`<div class="cell-error">⚠ ${Be(r.error)}</div>`);return`<section class="cell sql-cell">${o}${s}${a}</section>`}).join(`
283
+ `);return`<!DOCTYPE html>
284
+ <html lang="en">
285
+ <head>
286
+ <meta charset="UTF-8">
287
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
288
+ <title>${Be(e)}</title>
289
+ <style>
290
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
291
+ body {
292
+ font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
293
+ background: #0d1117; color: #e6edf3;
294
+ line-height: 1.6; padding: 0;
295
+ }
296
+ .page-header {
297
+ background: #161b22; border-bottom: 1px solid #21262d;
298
+ padding: 16px 32px; display: flex; align-items: center; gap: 12px;
299
+ }
300
+ .logo {
301
+ width: 28px; height: 28px; border-radius: 6px;
302
+ background: linear-gradient(135deg, #388bfd, #1f6feb);
303
+ display: flex; align-items: center; justify-content: center;
304
+ font-size: 10px; font-weight: 700; color: #fff;
305
+ font-family: monospace; letter-spacing: -0.5px; flex-shrink: 0;
306
+ }
307
+ .page-title { font-size: 18px; font-weight: 600; color: #e6edf3; }
308
+ .page-meta { font-size: 12px; color: #8b949e; margin-left: auto; }
309
+ .content { max-width: 900px; margin: 0 auto; padding: 32px 24px; display: flex; flex-direction: column; gap: 24px; }
310
+ .cell { border-radius: 8px; overflow: hidden; }
311
+ .md-cell { padding: 4px 0; }
312
+ .md-cell h1 { font-size: 26px; font-weight: 700; color: #e6edf3; margin: 0 0 12px; }
313
+ .md-cell h2 { font-size: 20px; font-weight: 600; color: #e6edf3; margin: 20px 0 10px; }
314
+ .md-cell h3 { font-size: 16px; font-weight: 600; color: #e6edf3; margin: 16px 0 8px; }
315
+ .md-cell p { color: #c9d1d9; margin-bottom: 8px; }
316
+ .md-cell ul { padding-left: 20px; color: #c9d1d9; margin-bottom: 8px; }
317
+ .md-cell code { background: #21262d; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 13px; }
318
+ .md-cell pre { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 14px; overflow-x: auto; margin-bottom: 8px; }
319
+ .md-cell pre code { background: none; padding: 0; }
320
+ .md-cell blockquote { border-left: 3px solid #388bfd; padding-left: 14px; color: #8b949e; }
321
+ .sql-cell { background: #161b22; border: 1px solid #30363d; }
322
+ .cell-header { display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-bottom: 1px solid #21262d; background: #1c2128; }
323
+ .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; }
324
+ .cell-name { font-size: 12px; color: #388bfd; font-family: monospace; }
325
+ .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; }
326
+ .cell-output { padding: 14px; }
327
+ .output-meta { font-size: 11px; color: #8b949e; margin-bottom: 10px; }
328
+ .table-wrap { overflow-x: auto; }
329
+ table { width: 100%; border-collapse: collapse; font-size: 12px; }
330
+ th { background: #1c2128; color: #8b949e; font-weight: 600; text-align: left; padding: 7px 12px; border-bottom: 1px solid #30363d; white-space: nowrap; }
331
+ td { padding: 6px 12px; border-bottom: 1px solid #21262d; color: #e6edf3; }
332
+ td.num { text-align: right; font-family: monospace; }
333
+ tr:last-child td { border-bottom: none; }
334
+ .truncated { font-size: 11px; color: #8b949e; margin-top: 8px; }
335
+ .cell-error { padding: 12px 14px; background: #3d1a1a; border-top: 1px solid #f85149; color: #f85149; font-size: 13px; }
336
+ .exported-by { text-align: center; color: #484f58; font-size: 11px; padding: 40px 0 24px; }
337
+ </style>
338
+ </head>
339
+ <body>
340
+ <div class="page-header">
341
+ <div class="logo">DQL</div>
342
+ <span class="page-title">${Be(e)}</span>
343
+ <span class="page-meta">Exported ${new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}</span>
344
+ </div>
345
+ <div class="content">
346
+ ${n}
347
+ </div>
348
+ <p class="exported-by">Built with DQL Notebook</p>
349
+ </body>
350
+ </html>`}function $L(e,t){const n=VL(e,t),r=new Blob([n],{type:"text/html;charset=utf-8"}),o=URL.createObjectURL(r),s=document.createElement("a");s.href=o,s.download=`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-dashboard.html`,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(o)}function XL(e,t){var s,a;const n=[];n.push(`workbook "${e}" {`);let r=0,o=0;for(const l of t)if(l.type!=="param"){if(l.type==="markdown"){o++;const E=`Markdown ${o}`;n.push(""),n.push(` page "${E}" {`);const c=l.content.split(`
351
+ `);for(const d of c)n.push(` // ${d}`);n.push(" }")}else if(l.type==="sql"){r++;const E=((s=l.name)==null?void 0:s.trim())||`Query ${r}`;n.push(""),n.push(` page "${E}" {`);const d=l.content.trim().split(`
352
+ `).map(u=>` ${u}`).join(`
353
+ `);n.push(" chart.table("),n.push(d+","),n.push(` title = "${E}"`),n.push(" )"),n.push(" }")}else if(l.type==="dql"){r++;const E=((a=l.name)==null?void 0:a.trim())||`Query ${r}`;n.push(""),n.push(` page "${E}" {`);const c=l.content.trim().split(`
354
+ `);for(const d of c)n.push(` ${d}`);n.push(" }")}}return n.push("}"),n.join(`
355
+ `)}function KL(e,t){const n=XL(e,t),r=new Blob([n],{type:"text/plain;charset=utf-8"}),o=URL.createObjectURL(r),s=document.createElement("a"),a=e.replace(/[^a-zA-Z0-9_-]/g,"_")+".dql";s.href=o,s.download=a,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(o)}function zL({t:e}){return i.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"linear-gradient(135deg, #388bfd 0%, #1f6feb 100%)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:i.jsx("span",{style:{color:"#ffffff",fontSize:10,fontWeight:700,fontFamily:e.fontMono,letterSpacing:"-0.5px"},children:"DQL"})})}function JL(){const{state:e,dispatch:t}=de(),n=re[e.themeMode],{executeAll:r}=gi(),[o,s]=R.useState(!1),[a,l]=R.useState(""),[E,c]=R.useState(!1),[d,u]=R.useState(!1),[T,S]=R.useState(!1),[A,f]=R.useState(!1),[I,p]=R.useState(!1),[O,N]=R.useState(!1),h=R.useRef(null),C=R.useRef(null),m=e.mainView==="block_studio"?e.blockStudioDirty:e.notebookDirty,g=e.mainView==="notebook",y=e.mainView==="connection"?"Connections":e.mainView==="reference"?"Quick Reference":e.notebookTitle||"Untitled";R.useEffect(()=>{o&&C.current&&(C.current.focus(),C.current.select())},[o]),R.useEffect(()=>{if(!O)return;function L(P){h.current&&!h.current.contains(P.target)&&N(!1)}return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},[O]);const _=()=>{l(e.notebookTitle),s(!0)},U=()=>{s(!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:BR(e.blockStudioDraft,a.trim())})):t({type:"SET_NOTEBOOK_DIRTY",dirty:!0}))},D=R.useCallback(async()=>{var L;if(e.activeFile){t({type:"SET_SAVING",saving:!0});try{if(e.mainView==="block_studio"){if(!e.blockStudioMetadata)return;const P=await Q.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:`${P.metadata.name}.dql`,path:P.path,type:"block",folder:"blocks"},payload:P}),e.files.some(M=>M.path===P.path)||t({type:"FILE_ADDED",file:{name:`${P.metadata.name}.dql`,path:P.path,type:"block",folder:"blocks"}})}else{const P=e.activeFile.type==="block"?((L=e.cells[0])==null?void 0:L.content)??"":mL(e.notebookTitle,e.cells,e.notebookMetadata);await Q.saveNotebook(e.activeFile.path,P),t({type:"SET_NOTEBOOK_DIRTY",dirty:!1})}c(!0),setTimeout(()=>c(!1),2e3)}catch(P){console.error("Save failed:",P)}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]);R.useEffect(()=>{const L=P=>{(P.metaKey||P.ctrlKey)&&P.key==="s"&&(P.preventDefault(),D())};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[D]),R.useEffect(()=>{if(!e.autoSave||!m||!e.activeFile)return;const L=setTimeout(()=>{D()},2e3);return()=>clearTimeout(L)},[e.autoSave,m,e.activeFile,e.cells,e.blockStudioDraft,D]);const b=()=>{t({type:"SET_THEME",mode:e.themeMode==="dark"?"light":"dark"})},F={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 i.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:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[i.jsx(zL,{t:n}),i.jsx("div",{style:{width:1,height:20,background:n.headerBorder,flexShrink:0}}),e.activeFile&&i.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?i.jsx("input",{ref:C,value:a,onChange:L=>l(L.target.value),onBlur:U,onKeyDown:L=>{L.key==="Enter"&&U(),L.key==="Escape"&&s(!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}}):i.jsxs("span",{onClick:_,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:[y,m&&i.jsx("span",{style:{color:n.textMuted,marginLeft:4},children:"●"})]}):i.jsx("span",{style:{color:n.textSecondary,fontSize:13,fontFamily:n.font,padding:"2px 4px"},children:y})]}),i.jsx("div",{style:{flex:1}}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsxs("button",{onClick:g?r:void 0,disabled:!e.activeFile||!g,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...F,background:(d&&e.activeFile,n.accent),color:"#ffffff",border:`1px solid ${n.accent}`,opacity:!e.activeFile||!g?.4:d?.9:1},children:[i.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:i.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})}),"Run All"]}),i.jsx("div",{style:{width:1,height:20,background:n.headerBorder}}),i.jsx("button",{onClick:b,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),title:e.themeMode==="dark"?"Switch to light mode":"Switch to dark mode",style:{...F,background:A?n.btnHover:n.btnBg,color:n.textSecondary,padding:"0 8px",fontSize:14},children:e.themeMode==="dark"?"☀":"☾"}),i.jsx("button",{onClick:D,disabled:!e.activeFile||e.savingFile,onMouseEnter:()=>S(!0),onMouseLeave:()=>S(!1),title:"Save (Cmd+S)",style:{...F,background:T&&e.activeFile?n.btnHover:n.btnBg,color:E?n.success:n.textSecondary,opacity:e.activeFile?1:.4},children:e.savingFile?i.jsxs(i.Fragment,{children:[i.jsx(qL,{}),"Saving…"]}):E?i.jsx(i.Fragment,{children:"✓ Saved"}):i.jsx(i.Fragment,{children:"Save"})}),i.jsx("button",{onClick:()=>t({type:"SET_AUTO_SAVE",enabled:!e.autoSave}),title:e.autoSave?"Auto-save on":"Auto-save off",style:{...F,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"}),i.jsxs("button",{onClick:()=>t({type:"TOGGLE_DASHBOARD_MODE"}),disabled:!e.activeFile,title:e.dashboardMode?"Switch to editor mode":"Switch to dashboard mode",style:{...F,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:[i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:e.dashboardMode?i.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"}):i.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"]}),i.jsx("div",{style:{width:1,height:20,background:n.headerBorder}}),i.jsxs("div",{ref:h,style:{position:"relative"},children:[i.jsxs("button",{onClick:()=>{e.activeFile&&N(L=>!L)},disabled:!e.activeFile,onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),title:"Export options",style:{...F,background:(I||O)&&e.activeFile?n.btnHover:n.btnBg,color:n.textSecondary,opacity:e.activeFile?1:.4},children:[i.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:[i.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"}),i.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"})]}),"Export",i.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"currentColor",style:{marginLeft:1},children:i.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),O&&i.jsxs("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:[i.jsx(ed,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{$L(e.notebookTitle||"dashboard",e.cells),N(!1)}}),i.jsx(ed,{label:"Export .dql",description:"DQL workbook file",t:n,onClick:()=>{KL(e.notebookTitle||"notebook",e.cells),N(!1)}})]})]})]})]})}function ed({label:e,description:t,t:n,onClick:r}){const[o,s]=R.useState(!1);return i.jsxs("button",{onClick:r,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!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:[i.jsx("span",{style:{fontSize:12,fontWeight:500,color:n.textPrimary,fontFamily:n.font},children:e}),i.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:t})]})}function qL(){return i.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",style:{animation:"spin 0.8s linear infinite"},children:[i.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"}),i.jsx("circle",{cx:"6",cy:"6",r:"4.5",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"14 7"})]})}function QL(e){return e.toTimeString().slice(0,8)}function ZL(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function e_(){const{state:e,dispatch:t}=de(),n=re[e.themeMode],[r,o]=R.useState(!1),s=e.queryLog.filter(l=>l.error),a=l=>t({type:"SET_DEV_PANEL_TAB",tab:l});return i.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&&i.jsxs(i.Fragment,{children:[i.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=>i.jsx(t_,{label:l==="errors"?`Errors${s.length>0?` (${s.length})`:""}`:`Logs (${e.queryLog.length})`,active:e.devPanelTab===l,onClick:()=>a(l),t:n},l)),i.jsx("div",{style:{flex:1}}),i.jsx("button",{onClick:()=>t({type:"SET_CELLS",cells:e.cells}),title:"Clear logs",style:{background:"transparent",border:"none",cursor:"pointer",color:n.textMuted,fontSize:11,fontFamily:n.font,padding:"2px 6px",borderRadius:4},children:"Clear"})]}),i.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[e.devPanelTab==="logs"&&(e.queryLog.length===0?i.jsx(td,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(l=>i.jsx(nd,{entry:l,t:n},l.id))),e.devPanelTab==="errors"&&(s.length===0?i.jsx(td,{t:n,message:"No errors."}):[...s].reverse().map(l=>i.jsx(nd,{entry:l,t:n},l.id)))]})]}),i.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",border:`1px solid ${n.headerBorder}`,borderBottom:e.devPanelOpen?`1px solid ${n.sidebarBg}`:void 0,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:[i.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:i.jsx("path",{d:e.devPanelOpen?"M1 7l4-4 4 4":"M1 3l4 4 4-4",strokeWidth:"1.5",stroke:"currentColor",fill:"none"})}),"Dev"]})]})}function t_({label:e,active:t,onClick:n,t:r}){const[o,s]=R.useState(!1);return i.jsx("button",{onClick:n,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{background:"transparent",border:"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 td({t:e,message:t}){return i.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:e.textMuted,fontSize:12,fontFamily:e.font,fontStyle:"italic"},children:t})}function nd({entry:e,t}){return i.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:[i.jsx("span",{style:{color:t.textMuted,flexShrink:0},children:QL(e.ts)}),i.jsx("span",{style:{flexShrink:0,color:t.textPrimary,maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.cellName}),e.error?i.jsx("span",{style:{color:t.error,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.error}):i.jsxs(i.Fragment,{children:[i.jsxs("span",{style:{color:t.textMuted},children:[e.rows.toLocaleString()," rows"]}),i.jsx("span",{style:{color:t.textMuted},children:ZL(e.time)})]})]})}function n_({onOpenFile:e}){const{state:t,dispatch:n}=de(),r=re[t.themeMode],o=t.files.slice(0,3);return i.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",background:r.appBg,padding:40,overflow:"auto"},children:i.jsxs("div",{style:{maxWidth:720,width:"100%",display:"flex",flexDirection:"column",alignItems:"center",gap:48},children:[i.jsxs("div",{style:{textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[i.jsx("div",{style:{width:72,height:72,borderRadius:16,background:"linear-gradient(135deg, #388bfd 0%, #1f6feb 60%, #0d419d 100%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 8px 32px rgba(56,139,253,0.3)"},children:i.jsx("span",{style:{color:"#fff",fontSize:26,fontWeight:800,fontFamily:r.fontMono,letterSpacing:"-1px"},children:"DQL"})}),i.jsxs("div",{children:[i.jsx("h1",{style:{fontSize:32,fontWeight:700,color:r.textPrimary,fontFamily:r.font,marginBottom:8,letterSpacing:"-0.5px"},children:"DQL Notebook"}),i.jsx("p",{style:{fontSize:15,color:r.textSecondary,fontFamily:r.font,letterSpacing:"0.02em"},children:"Analytics as Code"})]})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16,width:"100%"},children:[i.jsx(rd,{title:"New Notebook",description:"Start a fresh analysis with an empty notebook.",icon:i.jsx(s_,{}),accent:r.accent,onClick:()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}),t:r}),i.jsx(r_,{recentFiles:o,onOpenFile:e,t:r}),i.jsx(rd,{title:"New Block",description:"Create a reusable SQL block file.",icon:i.jsx(a_,{}),accent:"#e3b341",onClick:()=>n({type:"OPEN_NEW_BLOCK_MODAL"}),t:r})]}),i.jsxs("div",{style:{width:"100%",borderRadius:10,border:`1px solid ${r.cellBorder}`,padding:"16px 20px",background:r.cellBg},children:[i.jsx("div",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.08em",textTransform:"uppercase",color:r.textMuted,fontFamily:r.font,marginBottom:12},children:"Quick Tips"}),i.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(([s,a])=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.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:s}),i.jsx("span",{style:{fontSize:12,color:r.textMuted,fontFamily:r.font},children:a})]},s))})]})]})})}function rd({title:e,description:t,icon:n,accent:r,onClick:o,t:s}){const[a,l]=R.useState(!1);return i.jsxs("button",{onClick:o,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{background:a?s.cellBg:"transparent",border:`1px solid ${a?r:s.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:[i.jsx("div",{style:{width:36,height:36,borderRadius:8,background:`${r}18`,display:"flex",alignItems:"center",justifyContent:"center",color:r},children:n}),i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:13,fontWeight:600,color:s.textPrimary,fontFamily:s.font,marginBottom:4},children:e}),i.jsx("div",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font,lineHeight:1.5},children:t})]})]})}function r_({recentFiles:e,onOpenFile:t,t:n}){const[r,o]=R.useState(!1);return i.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:[i.jsx("div",{style:{width:36,height:36,borderRadius:8,background:`${n.warning}18`,display:"flex",alignItems:"center",justifyContent:"center",color:n.warning},children:i.jsx(i_,{})}),i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,fontFamily:n.font,marginBottom:8},children:"Open Recent"}),e.length===0?i.jsx("div",{style:{fontSize:12,color:n.textMuted,fontFamily:n.font,fontStyle:"italic"},children:"No recent files."}):i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:e.map(s=>i.jsx(o_,{file:s,onClick:()=>t(s),t:n},s.path))})]})]})}function o_({file:e,onClick:t,t:n}){const[r,o]=R.useState(!1);return i.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 s_(){return i.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 i_(){return i.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 a_(){return i.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 od=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class $r{constructor(t,n,r=0,o=t.length,s,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=s?l=>s(od(l)):od,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 tI(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=aI(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=nI(t);let o=this.normalize(n);if(o.length)for(let s=0,a=r;;s++){let l=o.charCodeAt(s),E=this.match(l,a,this.bufferPos+this.bufferStart);if(s==o.length-1){if(E)return this.value=E,this;break}a==r&&s<n.length&&n.charCodeAt(s)==l&&a++}}}match(t,n,r){let o=null;for(let s=0;s<this.matches.length;s+=2){let a=this.matches[s],l=!1;this.query.charCodeAt(a)==t&&(a==this.query.length-1?o={from:this.matches[s+1],to:r}:(this.matches[s]++,l=!0)),l||(this.matches.splice(s,2),s-=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"&&($r.prototype[Symbol.iterator]=function(){return this});const FR={from:-1,to:-1,match:/.*/.exec("")},Dc="gm"+(/x/.unicode==null?"":"u");class GR{constructor(t,n,r,o=0,s=t.length){if(this.text=t,this.to=s,this.curLine="",this.done=!1,this.value=FR,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new HR(t,n,r,o,s);this.re=new RegExp(n,Dc+(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=Gs(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=Gs(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 Na=new WeakMap;class Jn{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let o=Na.get(t);if(!o||o.from>=r||o.to<=n){let l=new Jn(n,t.sliceString(n,r));return Na.set(t,l),l}if(o.from==n&&o.to==r)return o;let{text:s,from:a}=o;return a>n&&(s=t.sliceString(n,a)+s,a=n),o.to<r&&(s+=t.sliceString(o.to,r)),Na.set(t,new Jn(a,s)),new Jn(n,s.slice(n-a,r-a))}}class HR{constructor(t,n,r,o,s){this.text=t,this.to=s,this.done=!1,this.value=FR,this.matchPos=Gs(t,o),this.re=new RegExp(n,Dc+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=Jn.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=Gs(this.text,o+(r==o?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Jn.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(GR.prototype[Symbol.iterator]=HR.prototype[Symbol.iterator]=function(){return this});function l_(e){try{return new RegExp(e,Dc),!0}catch{return!1}}function Gs(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 c_=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:o}=Qp(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return o.then(s=>{let a=s&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(s.elements.line.value);if(!a){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,E,c,d,u]=a,T=d?+d.slice(1):0,S=c?+c:l.number;if(c&&u){let I=S/100;E&&(I=I*(E=="-"?-1:1)+l.number/t.doc.lines),S=Math.round(t.doc.lines*I)}else c&&E&&(S=S*(E=="-"?-1:1)+l.number);let A=t.doc.line(Math.max(1,Math.min(t.doc.lines,S))),f=it.cursor(A.from+Math.max(0,Math.min(T,A.length)));e.dispatch({effects:[r,be.scrollIntoView(f.from,{y:"center"})],selection:f})}),!0},E_=({state:e,dispatch:t})=>{let{selection:n}=e,r=it.create(n.ranges.map(o=>e.wordAt(o.head)||it.cursor(o.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function d_(e,t){let{main:n,ranges:r}=e.selection,o=e.wordAt(n.head),s=o&&o.from==n.from&&o.to==n.to;for(let a=!1,l=new $r(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(a)return null;l=new $r(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),a=!0}else{if(a&&r.some(E=>E.from==l.value.from))continue;if(s){let E=e.wordAt(l.value.from);if(!E||E.from!=l.value.from||E.to!=l.value.to)continue}return l.value}}const u_=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(s=>s.from===s.to))return E_({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(s=>e.sliceDoc(s.from,s.to)!=r))return!1;let o=d_(e,r);return o?(t(e.update({selection:e.selection.addRange(it.range(o.from,o.to),!1),effects:be.scrollIntoView(o.to)})),!0):!1},_n=rI.define({combine(e){return oI(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new __(t),scrollToMatch:t=>be.scrollIntoView(t)})}});function T_(e){return e?[_n.of(e),xl]:xl}class kR{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||l_(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"?`
356
+ `: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 I_(this):new f_(this)}getCursor(t,n=0,r){let o=t.doc?t:PT.create({doc:t});return r==null&&(r=o.doc.length),this.regexp?Vn(this,o,n,r):Wn(this,o,n,r)}}class YR{constructor(t){this.spec=t}}function S_(e,t,n){return(r,o,s,a)=>{if(n&&!n(r,o,s,a))return!1;let l=r>=a&&o<=a+s.length?s.slice(r-a,o-a):t.doc.sliceString(r,o);return e(l,t,r,o)}}function Wn(e,t,n,r){let o;return e.wholeWord&&(o=R_(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(o=S_(e.test,t,o)),new $r(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:s=>s.toLowerCase(),o)}function R_(e,t){return(n,r,o,s)=>((s>n||s+o.length<r)&&(s=Math.max(0,n-2),o=e.sliceString(s,Math.min(e.length,r+2))),(t(Hs(o,n-s))!=Xt.Word||t(ks(o,n-s))!=Xt.Word)&&(t(ks(o,r-s))!=Xt.Word||t(Hs(o,r-s))!=Xt.Word))}class f_ extends YR{constructor(t){super(t)}nextMatch(t,n,r){let o=Wn(this.spec,t,r,t.doc.length).nextOverlapping();if(o.done){let s=Math.min(t.doc.length,n+this.spec.unquoted.length);o=Wn(this.spec,t,0,s).nextOverlapping()}return o.done||o.value.from==n&&o.value.to==r?null:o.value}prevMatchInRange(t,n,r){for(let o=r;;){let s=Math.max(n,o-1e4-this.spec.unquoted.length),a=Wn(this.spec,t,s,o),l=null;for(;!a.nextOverlapping().done;)l=a.value;if(l)return l;if(s==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=Wn(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 s=Wn(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!s.next().done;)o(s.value.from,s.value.to)}}function A_(e,t,n){return(r,o,s)=>(!n||n(r,o,s))&&e(s[0],t,r,o)}function Vn(e,t,n,r){let o;return e.wholeWord&&(o=p_(t.charCategorizer(t.selection.main.head))),e.test&&(o=A_(e.test,t,o)),new GR(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:o},n,r)}function Hs(e,t){return e.slice(bT(e,t,!1),t)}function ks(e,t){return e.slice(t,bT(e,t))}function p_(e){return(t,n,r)=>!r[0].length||(e(Hs(r.input,r.index))!=Xt.Word||e(ks(r.input,r.index))!=Xt.Word)&&(e(ks(r.input,r.index+r[0].length))!=Xt.Word||e(Hs(r.input,r.index+r[0].length))!=Xt.Word)}class I_ extends YR{nextMatch(t,n,r){let o=Vn(this.spec,t,r,t.doc.length).next();return o.done&&(o=Vn(this.spec,t,0,n).next()),o.done?null:o.value}prevMatchInRange(t,n,r){for(let o=1;;o++){let s=Math.max(n,r-o*1e4),a=Vn(this.spec,t,s,r),l=null;for(;!a.next().done;)l=a.value;if(l&&(s==n||l.from>s+10))return l;if(s==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 s=+r.slice(0,o);if(s>0&&s<t.match.length)return t.match[s]+r.slice(o)}return n})}matchAll(t,n){let r=Vn(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 s=Vn(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!s.next().done;)o(s.value.from,s.value.to)}}const Xr=li.define(),Mc=li.define(),Kt=MT.define({create(e){return new ha(_l(e).create(),null)},update(e,t){for(let n of t.effects)n.is(Xr)?e=new ha(n.value.create(),e.panel):n.is(Mc)&&(e=new ha(e.query,n.value?Pc:null));return e},provide:e=>Zp.from(e,t=>t.panel)});class ha{constructor(t,n){this.query=t,this.panel=n}}const O_=un.mark({class:"cm-searchMatch"}),N_=un.mark({class:"cm-searchMatch cm-searchMatch-selected"}),h_=sI.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Kt))}update(e){let t=e.state.field(Kt);(t!=e.startState.field(Kt)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return un.none;let{view:n}=this,r=new iI;for(let o=0,s=n.visibleRanges,a=s.length;o<a;o++){let{from:l,to:E}=s[o];for(;o<a-1&&E>s[o+1].from-500;)E=s[++o].to;e.highlight(n.state,l,E,(c,d)=>{let u=n.state.selection.ranges.some(T=>T.from==c&&T.to==d);r.add(c,d,u?N_:O_)})}return r.finish()}},{decorations:e=>e.decorations});function To(e){return t=>{let n=t.state.field(Kt,!1);return n&&n.query.spec.valid?e(t,n):VR(t)}}const Ys=To((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let o=it.single(r.from,r.to),s=e.state.facet(_n);return e.dispatch({selection:o,effects:[bc(e,r),s.scrollToMatch(o.main,e)],userEvent:"select.search"}),WR(e),!0}),js=To((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,o=t.prevMatch(n,r,r);if(!o)return!1;let s=it.single(o.from,o.to),a=e.state.facet(_n);return e.dispatch({selection:s,effects:[bc(e,o),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),WR(e),!0}),m_=To((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:it.create(n.map(r=>it.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),C_=({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,s=[],a=0;for(let l=new $r(e.doc,e.sliceDoc(r,o));!l.next().done;){if(s.length>1e3)return!1;l.value.from==r&&(a=s.length),s.push(it.range(l.value.from,l.value.to))}return t(e.update({selection:it.create(s,a),userEvent:"select.search.matches"})),!0},sd=To((e,{query:t})=>{let{state:n}=e,{from:r,to:o}=n.selection.main;if(n.readOnly)return!1;let s=t.nextMatch(n,r,r);if(!s)return!1;let a=s,l=[],E,c,d=[];a.from==r&&a.to==o&&(c=n.toText(t.getReplacement(a)),l.push({from:a.from,to:a.to,insert:c}),a=t.nextMatch(n,a.from,a.to),d.push(be.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+".")));let u=e.state.changes(l);return a&&(E=it.single(a.from,a.to).map(u),d.push(bc(e,a)),d.push(n.facet(_n).scrollToMatch(E.main,e))),e.dispatch({changes:u,selection:E,effects:d,userEvent:"input.replace"}),!0}),g_=To((e,{query:t})=>{if(e.state.readOnly)return!1;let n=t.matchAll(e.state,1e9).map(o=>{let{from:s,to:a}=o;return{from:s,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:be.announce.of(r),userEvent:"input.replace.all"}),!0});function Pc(e){return e.state.facet(_n).createPanel(e)}function _l(e,t){var n,r,o,s,a;let l=e.selection.main,E=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!E)return t;let c=e.facet(_n);return new kR({search:((n=t==null?void 0:t.literal)!==null&&n!==void 0?n:c.literal)?E:E.replace(/\n/g,"\\n"),caseSensitive:(r=t==null?void 0:t.caseSensitive)!==null&&r!==void 0?r:c.caseSensitive,literal:(o=t==null?void 0:t.literal)!==null&&o!==void 0?o:c.literal,regexp:(s=t==null?void 0:t.regexp)!==null&&s!==void 0?s:c.regexp,wholeWord:(a=t==null?void 0:t.wholeWord)!==null&&a!==void 0?a:c.wholeWord})}function jR(e){let t=DT(e,Pc);return t&&t.dom.querySelector("[main-field]")}function WR(e){let t=jR(e);t&&t==e.root.activeElement&&t.select()}const VR=e=>{let t=e.state.field(Kt,!1);if(t&&t.panel){let n=jR(e);if(n&&n!=e.root.activeElement){let r=_l(e.state,t.query.spec);r.valid&&e.dispatch({effects:Xr.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Mc.of(!0),t?Xr.of(_l(e.state,t.query.spec)):li.appendConfig.of(xl)]});return!0},$R=e=>{let t=e.state.field(Kt,!1);if(!t||!t.panel)return!1;let n=DT(e,Pc);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Mc.of(!1)}),!0},L_=[{key:"Mod-f",run:VR,scope:"editor search-panel"},{key:"F3",run:Ys,shift:js,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:Ys,shift:js,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:$R,scope:"editor search-panel"},{key:"Mod-Shift-l",run:C_},{key:"Mod-Alt-g",run:c_},{key:"Mod-d",run:u_,preventDefault:!0}];class __{constructor(t){this.view=t;let n=this.query=t.state.field(Kt).query.spec;this.commit=this.commit.bind(this),this.searchField=ze("input",{value:n.search,placeholder:Ye(t,"Find"),"aria-label":Ye(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=ze("input",{value:n.replace,placeholder:Ye(t,"Replace"),"aria-label":Ye(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=ze("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=ze("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=ze("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(o,s,a){return ze("button",{class:"cm-button",name:o,onclick:s,type:"button"},a)}this.dom=ze("div",{onkeydown:o=>this.keydown(o),class:"cm-search"},[this.searchField,r("next",()=>Ys(t),[Ye(t,"next")]),r("prev",()=>js(t),[Ye(t,"previous")]),r("select",()=>m_(t),[Ye(t,"all")]),ze("label",null,[this.caseField,Ye(t,"match case")]),ze("label",null,[this.reField,Ye(t,"regexp")]),ze("label",null,[this.wordField,Ye(t,"by word")]),...t.state.readOnly?[]:[ze("br"),this.replaceField,r("replace",()=>sd(t),[Ye(t,"replace")]),r("replaceAll",()=>g_(t),[Ye(t,"replace all")])],ze("button",{name:"close",onclick:()=>$R(t),"aria-label":Ye(t,"close"),type:"button"},["×"])])}commit(){let t=new kR({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:Xr.of(t)}))}keydown(t){lI(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?js:Ys)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),sd(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(Xr)&&!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(_n).top}}function Ye(e,t){return e.state.phrase(t)}const Qo=30,Zo=/[\s\.,:;?!]/;function bc(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),o=e.state.doc.lineAt(n).to,s=Math.max(r.from,t-Qo),a=Math.min(o,n+Qo),l=e.state.sliceDoc(s,a);if(s!=r.from){for(let E=0;E<Qo;E++)if(!Zo.test(l[E+1])&&Zo.test(l[E])){l=l.slice(E);break}}if(a!=o){for(let E=l.length-1;E>l.length-Qo;E--)if(!Zo.test(l[E-1])&&Zo.test(l[E])){l=l.slice(0,E);break}}return be.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const x_=be.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"}}),xl=[Kt,eI.low(h_),x_],y_=3e4,Ws="application/dql-semantic-ref";let es=[],id=0,Kr=null;function D_(e){Q.trackUsage(e),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:e}}))}async function ad(){if(Date.now()<id&&es.length>0)return es;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 es=Array.isArray(t.completions)?t.completions:[],id=Date.now()+y_,es}function XR(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 M_(e){Kr=e}function P_(e){Kr===e&&(Kr=null)}function b_(e){return Kr?(XR(Kr,e),!0):!1}function v_(e,t,n){const r=n?e.posAtCoords(n)??e.state.selection.main.from:e.state.selection.main.from;XR(e,t,r)}function ld(e,t,n){return{label:e.name,detail:e.type==="metric"?"@metric":"@dim",type:e.type==="metric"?"function":"variable",info:`${e.label}${e.description?`
357
+ ${e.description}`:""}${e.sql?`
358
+ ${e.sql}`:""}`,apply(r){const s=r.state.sliceDoc(n,n+1)===")"?e.name:`${e.name})`;r.dispatch({changes:{from:t,to:n,insert:s},selection:{anchor:t+s.length}}),D_(e.name)}}}function U_(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 w_=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(),E=n-o[1].length,c=(await ad()).filter(d=>d.type==="metric").filter(d=>!l||d.name.toLowerCase().includes(l)||d.label.toLowerCase().includes(l)||(d.domain??"").toLowerCase().includes(l)||d.tags.some(u=>u.toLowerCase().includes(l))).slice(0,50);return{from:E,options:c.map(d=>ld(d,E,n)),validFor:/^[\w-]*$/}}const s=/@dim\(([^)]*)$/i.exec(r);if(s){const l=s[1].trim().toLowerCase(),E=n-s[1].length,c=(await ad()).filter(d=>d.type==="dimension").filter(d=>!l||d.name.toLowerCase().includes(l)||d.label.toLowerCase().includes(l)||(d.domain??"").toLowerCase().includes(l)||d.tags.some(u=>u.toLowerCase().includes(l))).slice(0,50);return{from:E,options:c.map(d=>ld(d,E,n)),validFor:/^[\w-]*$/}}const a=/@([md][a-z_]*)?$/i.exec(r);return a?U_(n-a[0].length):(e.explicit,null)};function KR(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 B_(e){const t=e.match(/LINE\s+(\d+)/i);if(t){const o=parseInt(t[1],10),s=e.match(/\n(\s*)\^/),a=s?s[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 Is=li.define(),F_=MT.define({create(){return un.none},update(e,t){for(const n of t.effects)if(n.is(Is)){if(!n.value)return un.none;const{from:r,to:o,message:s}=n.value;return un.set([un.mark({class:"cm-sql-error",attributes:{title:s}}).range(r,o)])}return e},provide:e=>be.decorations.from(e)}),G_=be.baseTheme({".cm-sql-error":{textDecoration:"underline wavy #f85149",textUnderlineOffset:"3px",background:"rgba(248, 81, 73, 0.08)"}}),H_=be.theme({"&":{background:"#f6f8fa",color:"#1f2328"},".cm-content":{caretColor:"#1f2328"},".cm-cursor":{borderLeftColor:"#1f2328"},".cm-selectionBackground":{background:"#b3d4fc"},"&.cm-focused .cm-selectionBackground":{background:"#b3d4fc"},".cm-gutters":{background:"#f0f2f5",color:"#8c959f",border:"none",borderRight:"1px solid #d0d7de"},".cm-activeLineGutter":{background:"#e8f0fe"},".cm-activeLine":{background:"#eaf0fb"},".cm-matchingBracket":{background:"#c8e6c9",outline:"1px solid #66bb6a"},".cm-foldPlaceholder":{background:"#eaeef2",border:"1px solid #d0d7de",color:"#57606a",borderRadius:3,padding:"0 4px"},".cm-tooltip":{background:"#ffffff",border:"1px solid #d0d7de",borderRadius:6,boxShadow:"0 4px 12px rgba(0,0,0,0.12)"},".cm-tooltip.cm-tooltip-autocomplete":{"& > ul > li":{padding:"3px 8px"},"& > ul > li[aria-selected]":{background:"#dbeafe",color:"#0550ae"}},".cm-searchMatch":{background:"#fff3b0",outline:"1px solid #f5c518"},".cm-searchMatch.cm-searchMatch-selected":{background:"#f5c518"},".cm-panels":{background:"#f0f2f5",borderTop:"1px solid #d0d7de"},".cm-panel":{padding:"6px 8px"},".cm-panel input":{background:"#fff",border:"1px solid #d0d7de",borderRadius:4,padding:"2px 6px",fontSize:12},".cm-panel button":{background:"#f6f8fa",border:"1px solid #d0d7de",borderRadius:4,padding:"2px 8px",cursor:"pointer",fontSize:12,marginLeft:4}},{dark:!1}),k_=be.theme({".cm-panels":{background:"#161b22",borderTop:"1px solid #30363d"},".cm-panel input":{background:"#0d1117",border:"1px solid #30363d",color:"#e6edf3",borderRadius:4,padding:"2px 6px",fontSize:12},".cm-panel button":{background:"#21262d",border:"1px solid #30363d",color:"#e6edf3",borderRadius:4,padding:"2px 8px",cursor:"pointer",fontSize:12,marginLeft:4},".cm-tooltip":{background:"#1c2128",border:"1px solid #30363d",borderRadius:6,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"},".cm-tooltip.cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{background:"#1f3858",color:"#58a6ff"}},".cm-matchingBracket":{background:"#1f3858",outline:"1px solid #388bfd"},".cm-searchMatch":{background:"#3d3000",outline:"1px solid #e3b341"},".cm-searchMatch.cm-searchMatch-selected":{background:"#6a4e00"}},{dark:!0});function vc({value:e,onChange:t,onRun:n,themeMode:r,autoFocus:o,schema:s,errorMessage:a,editorRef:l}){const E=re[r],c=R.useRef(null),d=R.useRef(null),[u,T]=R.useState(!1),S=R.useRef(n),A=R.useRef(t),f=R.useRef(new cI);return S.current=n,A.current=t,R.useEffect(()=>{l&&(l.current={undo:()=>{d.current&&dI(d.current)},redo:()=>{d.current&&EI(d.current)},resetTo:I=>{const p=d.current;p&&p.dispatch({changes:{from:0,to:p.state.doc.length,insert:I}})}})}),R.useEffect(()=>{if(!c.current)return;const I=uI.of([{key:"Shift-Enter",run:()=>(S.current(),!0)},{key:"Ctrl-Enter",mac:"Cmd-Enter",run:()=>(S.current(),!0)},{key:"Ctrl-/",mac:"Cmd-/",run:TI},SI,...RI,...fI,...AI,...L_,...pI,...II]),p=be.updateListener.of(y=>{y.docChanged&&A.current(y.state.doc.toString())}),O=be.domEventHandlers({focus:(y,_)=>{M_(_)},blur:(y,_)=>{P_(_)}}),N=be.theme({"&":{background:E.editorBg,fontFamily:E.fontMono,fontSize:"13px",minHeight:"80px",maxHeight:"480px"},".cm-scroller":{overflow:"auto",fontFamily:"inherit"},".cm-content":{padding:"10px 0",minHeight:"80px"},".cm-focused":{outline:"none"},".cm-editor":{border:"none"},".cm-gutters":{minWidth:40},".cm-foldGutter":{cursor:"pointer"}}),h=s?Wo({schema:s,upperCaseKeywords:!1}):Wo({upperCaseKeywords:!1}),C=[I,p,O,N,f.current.of(h),NI({closeOnBlur:!1,override:[w_]}),hI(),mI(),CI(),gI(),LI(),_I(),xI(),yI(),be.lineWrapping,T_({top:!0}),F_,G_,...r==="dark"?[OI,k_]:[H_,DI(MI)]],m=PT.create({doc:e,extensions:C}),g=new be({state:m,parent:c.current});return d.current=g,o&&g.focus(),()=>{g.destroy(),d.current=null}},[r]),R.useEffect(()=>{const I=d.current;if(!I)return;const p=s?Wo({schema:s,upperCaseKeywords:!1}):Wo({upperCaseKeywords:!1});I.dispatch({effects:f.current.reconfigure(p)})},[s]),R.useEffect(()=>{const I=d.current;if(!I)return;const p=I.state.doc.toString();p!==e&&I.dispatch({changes:{from:0,to:p.length,insert:e}})},[e]),R.useEffect(()=>{const I=d.current;if(!I)return;if(!a){I.dispatch({effects:Is.of(null)});return}const p=B_(a),O=I.state.doc;if(p&&p.line>=1&&p.line<=O.lines){const N=O.line(p.line),h=N.from+Math.max(0,p.col-1),C=Math.max(h+1,N.to);I.dispatch({effects:Is.of({from:Math.min(h,O.length),to:Math.min(C,O.length),message:a})})}else if(O.lines>=1){const N=O.line(1);I.dispatch({effects:Is.of({from:N.from,to:Math.max(N.from+1,N.to),message:a})})}},[a]),i.jsx("div",{onDragOver:I=>{I.dataTransfer.types.includes(Ws)&&(I.preventDefault(),T(!0))},onDragLeave:()=>T(!1),onDrop:I=>{const p=d.current;if(!p)return;const O=KR(I.dataTransfer.getData(Ws));O&&(I.preventDefault(),T(!1),v_(p,O.reference,{x:I.clientX,y:I.clientY}),Q.trackUsage(O.name),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:O.name}})))},style:{background:E.editorBg,minHeight:80,border:u?`1px solid ${E.accent}`:"1px solid transparent",borderRadius:6,transition:"border-color 0.15s"},children:i.jsx("div",{ref:c,style:{minHeight:80}})})}vc.displayName="SQLCellEditor";function Y_(e,t){const n=e.split(`
359
+ `),r=[];let o=0;for(;o<n.length;){const s=n[o],a=s.match(/^(#{1,6})\s+(.+)$/);if(a){const l=a[1].length,E=a[2],d=[28,22,18,16,14,13][l-1];r.push(i.jsx("div",{style:{fontSize:d,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:xr(E,t)},o)),o++;continue}if(/^[-*_]{3,}$/.test(s.trim())){r.push(i.jsx("hr",{style:{border:"none",borderTop:`1px solid ${t.cellBorder}`,margin:"12px 0"}},o)),o++;continue}if(s.startsWith("> ")){r.push(i.jsx("div",{style:{borderLeft:`3px solid ${t.textMuted}`,paddingLeft:12,marginLeft:4,color:t.textSecondary,fontStyle:"italic",fontFamily:t.fontSerif,fontSize:14},children:xr(s.slice(2),t)},o)),o++;continue}if(s.startsWith("```")){const l=[];for(o++;o<n.length&&!n[o].startsWith("```");)l.push(n[o]),o++;r.push(i.jsx("pre",{style:{background:t.editorBg,border:`1px solid ${t.cellBorder}`,borderRadius:6,padding:"10px 12px",fontSize:12,fontFamily:t.fontMono,color:t.textPrimary,overflow:"auto",margin:"8px 0",lineHeight:1.6},children:l.join(`
360
+ `)},o)),o++;continue}if(/^[-*+]\s/.test(s)){const l=[];for(;o<n.length&&/^[-*+]\s/.test(n[o]);)l.push(n[o].replace(/^[-*+]\s/,"")),o++;r.push(i.jsx("ul",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:l.map((E,c)=>i.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:xr(E,t)},c))},o));continue}if(/^\d+\.\s/.test(s)){const l=[];for(;o<n.length&&/^\d+\.\s/.test(n[o]);)l.push(n[o].replace(/^\d+\.\s/,"")),o++;r.push(i.jsx("ol",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:l.map((E,c)=>i.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:xr(E,t)},c))},o));continue}if(!s.trim()){r.push(i.jsx("div",{style:{height:8}},o)),o++;continue}r.push(i.jsx("p",{style:{fontSize:14,lineHeight:1.7,fontFamily:t.fontSerif,color:t.textSecondary,marginBottom:6},children:xr(s,t)},o)),o++}return r}function xr(e,t){const n=[];let r=e,o=0;for(;r.length>0;){const s=r.match(/\*{3}(.+?)\*{3}/),a=r.match(/\*{2}(.+?)\*{2}/),l=r.match(/\*(.+?)\*/),E=r.match(/`(.+?)`/),c=r.match(/\[(.+?)\]\((.+?)\)/),d=[s?{match:s,type:"boldItalic"}:null,a?{match:a,type:"bold"}:null,l?{match:l,type:"italic"}:null,E?{match:E,type:"code"}:null,c?{match:c,type:"link"}:null].filter(Boolean);if(d.length===0){n.push(i.jsx(me.Fragment,{children:r},o++));break}const u=d.reduce((S,A)=>(S.match.index??0)<(A.match.index??0)?S:A),T=u.match.index??0;switch(T>0&&n.push(i.jsx(me.Fragment,{children:r.slice(0,T)},o++)),u.type){case"boldItalic":n.push(i.jsx("strong",{style:{fontStyle:"italic"},children:u.match[1]},o++));break;case"bold":n.push(i.jsx("strong",{children:u.match[1]},o++));break;case"italic":n.push(i.jsx("em",{children:u.match[1]},o++));break;case"code":n.push(i.jsx("code",{style:{background:t.editorBg,border:`1px solid ${t.cellBorder}`,borderRadius:4,padding:"1px 5px",fontSize:"0.9em",fontFamily:t.fontMono,color:t.accent},children:u.match[1]},o++));break;case"link":n.push(i.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 i.jsx(i.Fragment,{children:n})}function j_({value:e,onChange:t,onRun:n,themeMode:r}){const o=re[r],[s,a]=R.useState(!1),l=R.useRef(null);R.useEffect(()=>{if(s&&l.current){l.current.focus();const u=l.current;u.style.height="auto",u.style.height=`${Math.max(u.scrollHeight,80)}px`}},[s]);const E=()=>{a(!1)},c=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,S=T.selectionStart,A=T.selectionEnd,f=e.slice(0,S)+" "+e.slice(A);t(f),requestAnimationFrame(()=>{T.selectionStart=T.selectionEnd=S+2})}},d=u=>{t(u.target.value);const T=u.target;T.style.height="auto",T.style.height=`${Math.max(T.scrollHeight,80)}px`};return s?i.jsx("textarea",{ref:l,value:e,onChange:d,onBlur:E,onKeyDown:c,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()?i.jsx("div",{onDoubleClick:()=>a(!0),title:"Double-click to edit",style:{padding:"12px 16px",cursor:"text",minHeight:48},children:Y_(e,o)}):i.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 W_({cell:e,themeMode:t,onApplyParam:n}){const{dispatch:r}=de(),o=re[t],[s,a]=R.useState(!1),l=e.paramConfig??{paramType:"text",label:"Parameter",defaultValue:"",options:[]},E=e.paramValue??l.defaultValue,c=S=>{r({type:"UPDATE_CELL",id:e.id,updates:{paramConfig:{...l,...S}}})},d=S=>{r({type:"SET_PARAM_VALUE",id:e.id,value:S})},u=(l.options??[]).map(S=>S.trim()).filter(Boolean),T=e.name?`{{${e.name}}}`:null;return i.jsxs("div",{style:{background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderLeft:"3px solid #e3b341",borderRadius:8,overflow:"hidden"},children:[s&&i.jsxs("div",{style:{background:o.tableHeaderBg,borderBottom:`1px solid ${o.cellBorder}`,padding:"12px 14px",display:"flex",flexDirection:"column",gap:10},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:2},children:[i.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",color:"#e3b341",fontFamily:o.fontMono,textTransform:"uppercase"},children:"Configure Parameter"}),i.jsx("button",{onClick:()=>a(!1),title:"Done",style:{background:"#e3b341",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"})]}),i.jsxs("div",{style:{display:"flex",gap:10,flexWrap:"wrap"},children:[i.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[i.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Variable name"}),i.jsx("input",{value:e.name??"",onChange:S=>r({type:"UPDATE_CELL",id:e.id,updates:{name:S.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"}})]}),i.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[i.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Display label"}),i.jsx("input",{value:l.label,onChange:S=>c({label:S.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"}})]}),i.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 100px"},children:[i.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Type"}),i.jsxs("select",{value:l.paramType,onChange:S=>c({paramType:S.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:[i.jsx("option",{value:"text",children:"Text"}),i.jsx("option",{value:"number",children:"Number"}),i.jsx("option",{value:"date",children:"Date"}),i.jsx("option",{value:"select",children:"Select"})]})]}),i.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[i.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Default value"}),i.jsx("input",{type:l.paramType==="number"?"number":l.paramType==="date"?"date":"text",value:l.defaultValue,onChange:S=>c({defaultValue:S.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"&&i.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3},children:[i.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Options (one per line)"}),i.jsx("textarea",{value:(l.options??[]).join(`
361
+ `),onChange:S=>c({options:S.target.value.split(`
362
+ `)}),rows:4,placeholder:`Option A
363
+ Option B
364
+ 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"}})]})]}),i.jsxs("div",{style:{padding:"12px 14px",display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[i.jsx("button",{onClick:()=>a(S=>!S),title:s?"Close config":"Configure parameter",style:{background:s?"#e3b34118":"transparent",border:`1px solid ${s?"#e3b341":o.cellBorder}`,borderRadius:5,cursor:"pointer",color:s?"#e3b341":o.textMuted,width:26,height:26,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,transition:"all 0.15s"},children:s?i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})}):i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})})}),i.jsx("span",{style:{fontSize:13,fontWeight:500,fontFamily:o.font,color:o.textSecondary,flexShrink:0},children:l.label}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[l.paramType==="select"?i.jsx("select",{value:E,onChange:S=>d(S.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?i.jsx("option",{value:"",children:"— no options configured —"}):u.map(S=>i.jsx("option",{value:S,children:S},S))}):i.jsx("input",{type:l.paramType,value:E,onChange:S=>d(S.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&&i.jsx("span",{style:{fontSize:10,fontFamily:o.fontMono,color:"#e3b341",opacity:.8},children:T})]}),E&&i.jsx("span",{style:{fontSize:12,fontFamily:o.fontMono,color:o.textPrimary,background:"#e3b34118",border:"1px solid #e3b34140",borderRadius:4,padding:"2px 8px",flexShrink:0},children:E}),e.name&&n&&i.jsx("button",{onClick:()=>n(e.name),title:`Re-run cells that use {{${e.name}}}`,style:{background:"#e3b341",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 V_({cell:e,themeMode:t,title:n,subtitle:r,color:o,badge:s}){const a=re[t];return i.jsxs("div",{style:{display:"flex",flexDirection:"column",background:a.cellBg,border:`1px solid ${a.cellBorder}`,borderLeft:`3px solid ${o}`,borderRadius:6,padding:"14px 16px",gap:8,fontFamily:a.font},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{fontSize:10,fontFamily:a.fontMono,fontWeight:700,letterSpacing:"0.08em",color:o,textTransform:"uppercase",padding:"2px 6px",borderRadius:3,background:`${o}18`},children:n}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:a.fontMono,color:a.textSecondary},children:e.name}),s&&i.jsx("span",{style:{fontSize:9,fontFamily:a.fontMono,fontWeight:600,letterSpacing:"0.1em",color:a.textMuted,textTransform:"uppercase",marginLeft:"auto",padding:"2px 6px",border:`1px solid ${a.cellBorder}`,borderRadius:3},children:s})]}),i.jsx("div",{style:{fontSize:12,color:a.textSecondary,lineHeight:1.5},children:r})]})}function $_(e){return e.type==="param"?"param":e.type.toUpperCase()}function X_({cells:e,index:t,content:n,themeMode:r,onInsertHandle:o}){const s=re[r],[a,l]=R.useState(!1),E=R.useRef(null),c=R.useMemo(()=>e.slice(0,t).filter(T=>T.name&&T.name.trim().length>0),[e,t]),d=R.useMemo(()=>gL(n),[n]);R.useEffect(()=>{if(!a)return;const T=S=>{var A;(A=E.current)!=null&&A.contains(S.target)||l(!1)};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[a]);const u=d.length===0?"df":d.length===1?`df: ${d[0]}`:`df: ${d[0]} +${d.length-1}`;return i.jsxs("div",{ref:E,style:{position:"relative",flexShrink:0},children:[i.jsxs("button",{onClick:()=>l(T=>!T),title:"Insert an upstream dataframe handle ({{name}})",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:10,fontFamily:s.fontMono,fontWeight:600,letterSpacing:"0.04em",color:d.length>0?s.accent:s.textMuted,background:d.length>0?`${s.accent}14`:"transparent",border:`1px solid ${d.length>0?`${s.accent}55`:s.btnBorder}`,borderRadius:4,padding:"1px 6px",cursor:"pointer",textTransform:"lowercase",transition:"border-color 0.15s, color 0.15s"},children:[u,i.jsx("span",{style:{fontSize:8,opacity:.7},children:"▾"})]}),a&&i.jsxs("div",{style:{position:"absolute",top:"calc(100% + 4px)",left:0,zIndex:20,minWidth:220,maxWidth:280,background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderRadius:6,boxShadow:"0 6px 16px rgba(0,0,0,0.25)",padding:4,display:"flex",flexDirection:"column",gap:2},children:[i.jsx("div",{style:{fontSize:9,fontFamily:s.font,fontWeight:700,letterSpacing:"0.1em",color:s.textMuted,textTransform:"uppercase",padding:"4px 8px 2px"},children:"Upstream dataframes"}),c.length===0&&i.jsx("div",{style:{fontSize:11,fontFamily:s.font,color:s.textMuted,padding:"6px 8px 8px",lineHeight:1.4},children:"No named upstream cells yet. Name a cell (click its header) to expose it here."}),c.map(T=>{const S=T.name?d.includes(T.name):!1;return i.jsxs("button",{onClick:()=>{T.name&&o(T.name),l(!1)},style:{display:"flex",alignItems:"center",gap:8,padding:"5px 8px",background:S?`${s.accent}14`:"transparent",border:"none",borderRadius:4,cursor:"pointer",textAlign:"left",color:s.textPrimary,fontFamily:s.fontMono,fontSize:11},onMouseEnter:A=>{S||(A.currentTarget.style.background=s.tableRowHover)},onMouseLeave:A=>{S||(A.currentTarget.style.background="transparent")},children:[i.jsx("span",{style:{fontSize:9,fontFamily:s.fontMono,fontWeight:700,color:s.textMuted,minWidth:36},children:$_(T)}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T.name}),S&&i.jsx("span",{style:{fontSize:9,color:s.accent,fontWeight:700,letterSpacing:"0.08em"},children:"IN USE"})]},T.id)})]})]})}const K_=/date|time|_at$|_on$|timestamp/i;function z_(e){return typeof e=="number"||typeof e=="string"&&e!==""&&!isNaN(Number(e))}function zR(e,t){if(K_.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(z_).length/n.length>.8?"numeric":"string"}function J_(e){return e==="numeric"?"measure":e==="date"?"temporal":"dimension"}const q_=[25,50,100,500];function yl(e){return typeof e=="number"?!0:typeof e=="string"?!isNaN(Number(e))&&e.trim()!=="":!1}function Q_(e){switch(e){case"numeric":return{icon:"#",color:"#79c0ff"};case"date":return{icon:"📅",color:"#e3b341"};case"bool":return{icon:"T/F",color:"#a371f7"};case"json":return{icon:"{}",color:"#ff7b72"};case"string":default:return{icon:"A",color:"#56d364"}}}function JR(e){return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function Z_(e,t){return e==null?1:t==null?-1:yl(e)&&yl(t)?Number(e)-Number(t):String(e).localeCompare(String(t))}function ex(e,t){const n=a=>a.includes(",")||a.includes('"')||a.includes(`
365
+ `)?`"${a.replace(/"/g,'""')}"`:a,r=e.columns.map(n).join(","),o=e.rows.map(a=>e.columns.map(l=>n(JR(a[l]))).join(",")),s=[r,...o].join(`
366
+ `);qR(s,"export.csv","text/csv")}function tx(e,t){const n=JSON.stringify(e.rows,null,2);qR(n,"export.json","application/json")}function qR(e,t,n){const r=new Blob([e],{type:n}),o=URL.createObjectURL(r),s=document.createElement("a");s.href=o,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(o)}function nx({dir:e,color:t}){return e?i.jsx("svg",{width:"8",height:"10",viewBox:"0 0 8 10",fill:t,style:{marginLeft:3,flexShrink:0},children:e==="asc"?i.jsx("path",{d:"M4 0L7 4H1L4 0Z"}):i.jsx("path",{d:"M4 10L1 6H7L4 10Z"})}):i.jsxs("svg",{width:"8",height:"10",viewBox:"0 0 8 10",fill:t,opacity:.3,style:{marginLeft:3,flexShrink:0},children:[i.jsx("path",{d:"M4 0L7 3.5H1L4 0Z"}),i.jsx("path",{d:"M4 10L1 6.5H7L4 10Z"})]})}function Li({result:e,themeMode:t}){const n=re[t],[r,o]=R.useState(null),[s,a]=R.useState(null),[l,E]=R.useState(null),[c,d]=R.useState(""),[u,T]=R.useState(50),[S,A]=R.useState(0),f=R.useCallback(m=>{s===m?l==="asc"?E("desc"):l==="desc"?(a(null),E(null)):E("asc"):(a(m),E("asc")),A(0)},[s,l]),I=R.useMemo(()=>{if(!c.trim())return e.rows;const m=c.toLowerCase();return e.rows.filter(g=>e.columns.some(y=>{const _=g[y];return _==null?!1:String(_).toLowerCase().includes(m)}))},[e.rows,e.columns,c]),p=R.useMemo(()=>{if(!s||!l)return I;const m=[...I];return m.sort((g,y)=>{const _=Z_(g[s],y[s]);return l==="desc"?-_:_}),m},[I,s,l]),O=R.useMemo(()=>{const m=new Map;for(const g of e.columns)m.set(g,zR(g,e.rows));return m},[e.columns,e.rows]),N=Math.max(1,Math.ceil(p.length/u)),h=Math.min(S,N-1),C=p.slice(h*u,(h+1)*u);return e.columns.length===0?i.jsx("div",{style:{padding:"12px 16px",color:n.textMuted,fontSize:12,fontFamily:n.font,fontStyle:"italic"},children:"Query executed successfully. No columns to display."}):i.jsxs("div",{children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 8px",borderBottom:`1px solid ${n.tableBorder}`,background:`${n.tableHeaderBg}60`,flexWrap:"wrap"},children:[i.jsxs("div",{style:{position:"relative",flex:"0 1 200px",minWidth:120},children:[i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:n.textMuted,style:{position:"absolute",left:6,top:6},children:i.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"})}),i.jsx("input",{value:c,onChange:m=>{d(m.target.value),A(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"}}),c&&i.jsx("button",{onClick:()=>d(""),style:{position:"absolute",right:4,top:3,background:"none",border:"none",color:n.textMuted,cursor:"pointer",fontSize:12,padding:"0 2px"},children:"×"})]}),i.jsxs("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:[c?`${p.length} of ${e.rows.length}`:`${e.rows.length}`," rows"]}),i.jsx("div",{style:{flex:1}}),i.jsx(cd,{label:"CSV",onClick:()=>ex(e),t:n}),i.jsx(cd,{label:"JSON",onClick:()=>tx(e),t:n}),i.jsx("select",{value:u,onChange:m=>{T(Number(m.target.value)),A(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:q_.map(m=>i.jsxs("option",{value:m,children:[m," / page"]},m))}),N>1&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[i.jsx(Bn,{disabled:h===0,onClick:()=>A(0),t:n,children:"«"}),i.jsx(Bn,{disabled:h===0,onClick:()=>A(h-1),t:n,children:"‹"}),i.jsxs("span",{style:{fontSize:10,color:n.textSecondary,fontFamily:n.font,padding:"0 4px"},children:[h+1,"/",N]}),i.jsx(Bn,{disabled:h>=N-1,onClick:()=>A(h+1),t:n,children:"›"}),i.jsx(Bn,{disabled:h>=N-1,onClick:()=>A(N-1),t:n,children:"»"})]})]}),i.jsx("div",{style:{maxHeight:400,overflow:"auto",position:"relative"},children:i.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",tableLayout:"auto",fontSize:12,fontFamily:n.fontMono},children:[i.jsx("thead",{children:i.jsx("tr",{children:e.columns.map(m=>i.jsx("th",{onClick:()=>f(m),style:{background:n.tableHeaderBg,color:n.textSecondary,fontWeight:600,fontSize:11,textAlign:"left",padding:"6px 12px",borderBottom:`1px solid ${n.tableBorder}`,borderRight:`1px solid ${n.tableBorder}`,minWidth:80,maxWidth:300,whiteSpace:"nowrap",position:"sticky",top:0,zIndex:1,fontFamily:n.font,letterSpacing:"0.03em",overflow:"hidden",textOverflow:"ellipsis",cursor:"pointer",userSelect:"none",transition:"background 0.1s"},children:i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6},children:[(()=>{const g=Q_(O.get(m)??"string");return i.jsx("span",{title:O.get(m)??"string",style:{fontSize:9,fontFamily:n.fontMono,fontWeight:700,color:g.color,background:`${g.color}15`,border:`1px solid ${g.color}40`,borderRadius:3,padding:"0 4px",minWidth:14,textAlign:"center",lineHeight:"14px",flexShrink:0},children:g.icon})})(),i.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:m}),i.jsx(nx,{dir:s===m?l:null,color:s===m?n.accent:n.textMuted})]})},m))})}),i.jsx("tbody",{children:C.map((m,g)=>i.jsx("tr",{onMouseEnter:()=>o(g),onMouseLeave:()=>o(null),style:{background:r===g?n.tableRowHover:"transparent",transition:"background 0.1s"},children:e.columns.map(y=>{const _=m[y],U=_==null,D=yl(_);return i.jsx("td",{style:{padding:"5px 12px",borderBottom:`1px solid ${n.tableBorder}`,borderRight:`1px solid ${n.tableBorder}`,color:U?n.textMuted:n.textPrimary,fontStyle:U?"italic":"normal",textAlign:D?"right":"left",whiteSpace:"nowrap",maxWidth:300,overflow:"hidden",textOverflow:"ellipsis"},children:U?"—":JR(_)},y)})},g))})]})}),i.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&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[i.jsx(Bn,{disabled:h===0,onClick:()=>A(h-1),t:n,children:"‹"}),rx(N,h).map((m,g)=>m==="…"?i.jsx("span",{style:{color:n.textMuted,fontSize:10,padding:"0 2px"},children:"…"},`gap-${g}`):i.jsx("button",{onClick:()=>A(m-1),style:{background:m-1===h?`${n.accent}20`:"transparent",border:"none",color:m-1===h?n.accent:n.textSecondary,fontSize:10,fontFamily:n.font,fontWeight:m-1===h?700:400,padding:"1px 6px",borderRadius:3,cursor:"pointer",minWidth:20},children:m},m)),i.jsx(Bn,{disabled:h>=N-1,onClick:()=>A(h+1),t:n,children:"›"})]}),i.jsx("div",{style:{flex:1}}),i.jsx(ts,{label:"View",t:n}),i.jsx(ts,{label:"Format",t:n}),i.jsx(ts,{label:"Columns",t:n}),i.jsx(ts,{label:"Totals",t:n}),i.jsxs("span",{style:{fontSize:10,color:n.textSecondary,fontFamily:n.font,marginLeft:6,whiteSpace:"nowrap"},children:[p.length.toLocaleString()," ",p.length===1?"row":"rows",c&&e.rows.length!==p.length&&` of ${e.rows.length.toLocaleString()}`]})]})]})}function rx(e,t){if(e<=7)return Array.from({length:e},(o,s)=>s+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 ts({label:e,t}){const[n,r]=R.useState(!1);return i.jsx("button",{onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),title:`${e} (coming in v0.11)`,style:{background:n?t.btnHover:"transparent",border:`1px solid ${n?t.btnBorder:"transparent"}`,borderRadius:3,color:n?t.textSecondary:t.textMuted,fontSize:10,fontFamily:t.font,fontWeight:600,padding:"2px 8px",cursor:"pointer",transition:"all 0.15s"},children:e})}function cd({label:e,onClick:t,t:n}){const[r,o]=R.useState(!1);return i.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:[i.jsxs("svg",{width:"9",height:"9",viewBox:"0 0 16 16",fill:"currentColor",children:[i.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"}),i.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 Bn({disabled:e,onClick:t,children:n,t:r}){return i.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 _i=[{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"}],ox=/date|time|at|day|month|year/i,QR=/^(label|name|category|status|type|group)$/i,ZR=/^(value|count|total|revenue|amount|sum|avg|price|quantity|sales)$/i;function zt(e){return typeof e=="number"?!0:typeof e=="string"?e.trim()!==""&&!isNaN(Number(e)):!1}function sx(e){return typeof e=="string"||typeof e=="number"}const ix=new Set(["bar","line","area","pie","donut","scatter","heatmap","funnel","waterfall","histogram","gauge","stacked-bar","grouped-bar","kpi","table"]);function zr(e,t){if(t!=null&&t.chart){const n=t.chart.toLowerCase().replace(/_/g,"-");if(ix.has(n))return n}return ax(e)}function ax(e){const{columns:t,rows:n}=e;if(t.length<2||n.length===0)return"table";const r=t[0],o=t[1],s=n.slice(0,5),a=s.every(u=>zt(u[o])),l=s.every(u=>sx(u[r]));if(ox.test(r)&&a&&l)return"line";const E=t.find(u=>QR.test(u)),c=t.find(u=>ZR.test(u));return E&&c&&s.every(T=>zt(T[c]))?"bar":s.every(u=>zt(u[r]))&&a&&t.length>=2?"scatter":t.length===2&&l&&a?"bar":"table"}const ef={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"]},Ue=ef.default;function Me(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 lx(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 xi(e,t){const n=(t!=null&&t.x&&e.columns.includes(t.x)?t.x:void 0)??e.columns.find(o=>QR.test(o))??e.columns[0],r=(t!=null&&t.y&&e.columns.includes(t.y)?t.y:void 0)??e.columns.find(o=>ZR.test(o))??e.columns[1];return{labelCol:n,valueCol:r}}const pn=20;function Uc({result:e,themeMode:t,chartConfig:n}){const r=re[t],[o,s]=R.useState(null),{labelCol:a,valueCol:l}=xi(e,n),E=(n==null?void 0:n.maxItems)??pn,c=e.rows.slice(0,E).map(p=>({label:String(p[a]??""),value:Number(p[l]??0)})),d=e.rows.length>E,u=Math.max(...c.map(p=>p.value),1),T=28,S=120,A=6,f=12,I=c.length*(T+A)+f*2;return i.jsxs("div",{style:{padding:"8px 0"},children:[i.jsx("svg",{width:"100%",height:I,viewBox:`0 0 600 ${I}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:c.map((p,O)=>{const N=f+O*(T+A),h=600-S-84,C=Math.max(p.value/u*h,2),m=o===O;return i.jsxs("g",{onMouseEnter:()=>s(O),onMouseLeave:()=>s(null),style:{cursor:"default"},children:[i.jsx("text",{x:S-8,y:N+T/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:p.label.length>16?p.label.slice(0,15)+"…":p.label}),i.jsx("rect",{x:S,y:N,width:C,height:T,rx:3,fill:m?r.accentHover:r.accent,style:{transition:"fill 0.15s"}}),i.jsx("text",{x:S+C+6,y:N+T/2+4,textAnchor:"start",fontSize:11,fontFamily:r.fontMono,fill:r.textMuted,children:Me(p.value)})]},O)})}),d&&i.jsxs("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,fontStyle:"italic",padding:"4px 12px"},children:["Showing ",pn," of ",e.rows.length," rows"]})]})}function cx({result:e,themeMode:t,chartConfig:n}){const r=re[t],[o,s]=R.useState(null),a=n!=null&&n.x&&e.columns.includes(n.x)?n.x:e.columns[0],l=e.rows.slice(0,5),E=e.columns.filter(p=>p!==a&&l.some(O=>zt(O[p])));if(E.length===0)return i.jsx(Uc,{result:e,themeMode:t,chartConfig:n});const c=e.rows.slice(0,pn).map(p=>String(p[a]??"")),d=Math.max(...e.rows.slice(0,pn).flatMap(p=>E.map(O=>Math.abs(Number(p[O]??0)))),1),u=24,T=u/E.length,S=120,A=12,f=8,I=c.length*(u+f)+A*2;return i.jsxs("div",{style:{padding:"8px 0"},children:[i.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:E.map((p,O)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[i.jsx("div",{style:{width:10,height:10,borderRadius:2,background:Ue[O%Ue.length]}}),i.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:p})]},p))}),i.jsx("svg",{width:"100%",height:I,viewBox:`0 0 600 ${I}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:c.map((p,O)=>{const N=A+O*(u+f),h=e.rows[O];return i.jsxs("g",{children:[i.jsx("text",{x:S-8,y:N+u/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:p.length>16?p.slice(0,15)+"…":p}),E.map((C,m)=>{const g=Number(h[C]??0),y=600-S-60,_=Math.max(Math.abs(g)/d*y,1),U=N+m*T,D=`${O}-${m}`;return i.jsxs("g",{onMouseEnter:()=>s(D),onMouseLeave:()=>s(null),children:[i.jsx("rect",{x:S,y:U,width:_,height:T-1,rx:2,fill:Ue[m%Ue.length],opacity:o===D?1:.85,style:{transition:"opacity 0.15s"}}),o===D&&i.jsx("text",{x:S+_+4,y:U+T/2+3,fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Me(g)})]},m)})]},O)})})]})}function Ex({result:e,themeMode:t,chartConfig:n}){const r=re[t],[o,s]=R.useState(null),a=n!=null&&n.x&&e.columns.includes(n.x)?n.x:e.columns[0],l=e.rows.slice(0,5),E=e.columns.filter(p=>p!==a&&l.some(O=>zt(O[p])));if(E.length===0)return i.jsx(Uc,{result:e,themeMode:t,chartConfig:n});const c=e.rows.slice(0,pn),d=c.map(p=>String(p[a]??"")),u=Math.max(...c.map(p=>E.reduce((O,N)=>O+Math.abs(Number(p[N]??0)),0)),1),T=28,S=120,A=12,f=6,I=d.length*(T+f)+A*2;return i.jsxs("div",{style:{padding:"8px 0"},children:[i.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:E.map((p,O)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[i.jsx("div",{style:{width:10,height:10,borderRadius:2,background:Ue[O%Ue.length]}}),i.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:p})]},p))}),i.jsx("svg",{width:"100%",height:I,viewBox:`0 0 600 ${I}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:d.map((p,O)=>{const N=A+O*(T+f),h=c[O],C=600-S-60;let m=S;return i.jsxs("g",{children:[i.jsx("text",{x:S-8,y:N+T/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:p.length>16?p.slice(0,15)+"…":p}),E.map((g,y)=>{const _=Math.abs(Number(h[g]??0)),U=Math.max(_/u*C,0),D=m;m+=U;const b=`${O}-${y}`;return i.jsxs("g",{onMouseEnter:()=>s(b),onMouseLeave:()=>s(null),children:[i.jsx("rect",{x:D,y:N,width:U,height:T,rx:y===0?3:0,fill:Ue[y%Ue.length],opacity:o===b?1:.85,style:{transition:"opacity 0.15s"}}),o===b&&U>30&&i.jsx("text",{x:D+U/2,y:N+T/2+4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:"#fff",fontWeight:600,children:Me(_)})]},y)})]},O)})})]})}function Ed({result:e,themeMode:t,showArea:n}){const r=re[t],[o,s]=R.useState(null),a=e.columns[0],l=e.columns[1],E=e.rows.map(L=>({label:String(L[a]??""),value:Number(L[l]??0)}));if(E.length<2)return null;const c=560,d=200,u=52,T=16,S=16,A=36,f=c-u-T,I=d-S-A,p=Math.min(...E.map(L=>L.value)),N=Math.max(...E.map(L=>L.value))-p||1,h=f/(E.length-1),C=L=>u+L*h,m=L=>S+I-(L-p)/N*I,g=E.map((L,P)=>({x:C(P),y:m(L.value)})),y=g.reduce((L,P,M)=>{if(M===0)return`M ${P.x},${P.y}`;const w=g[M-1],v=w.x+(P.x-w.x)/2;return`${L} C ${v},${w.y} ${v},${P.y} ${P.x},${P.y}`},""),_=`${y} L ${g[g.length-1].x},${S+I} L ${u},${S+I} Z`,U=5,D=Array.from({length:U+1},(L,P)=>{const M=p+N*P/U;return{val:M,y:m(M)}}),b=Math.ceil(E.length/8),F=E.filter((L,P)=>P%b===0||P===E.length-1);return i.jsx("div",{style:{position:"relative",padding:"8px 0"},children:i.jsxs("svg",{width:"100%",height:d,viewBox:`0 0 ${c} ${d}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},onMouseLeave:()=>s(null),children:[D.map((L,P)=>i.jsxs("g",{children:[i.jsx("line",{x1:u,y1:L.y,x2:u+f,y2:L.y,stroke:r.tableBorder,strokeWidth:.5}),i.jsx("text",{x:u-6,y:L.y+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Me(L.val)})]},P)),i.jsx("path",{d:_,fill:r.accent,opacity:n?.3:.15}),i.jsx("path",{d:y,fill:"none",stroke:r.accent,strokeWidth:2,strokeLinejoin:"round"}),g.map((L,P)=>i.jsx("circle",{cx:L.x,cy:L.y,r:3,fill:r.accent,style:{cursor:"crosshair"},onMouseEnter:()=>s({x:L.x,y:L.y,label:E[P].label,value:E[P].value})},P)),F.map((L,P)=>{const M=E.indexOf(L);return i.jsx("text",{x:C(M),y:S+I+16,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:lx(L.label)},P)}),i.jsx("line",{x1:u,y1:S,x2:u,y2:S+I,stroke:r.tableBorder,strokeWidth:1}),i.jsx("line",{x1:u,y1:S+I,x2:u+f,y2:S+I,stroke:r.tableBorder,strokeWidth:1}),o&&i.jsxs("g",{children:[i.jsx("rect",{x:o.x+8,y:o.y-20,width:90,height:32,rx:4,fill:r.cellBg,stroke:r.cellBorder,strokeWidth:1}),i.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}),i.jsx("text",{x:o.x+13,y:o.y+6,fontSize:11,fontFamily:r.fontMono,fill:r.textPrimary,fontWeight:600,children:Me(o.value)})]})]})})}function dx({result:e,themeMode:t,chartConfig:n}){const r=re[t],[o,s]=R.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],E=n!=null&&n.color&&e.columns.includes(n.color)?n.color:void 0,c=e.rows.slice(0,200).map(D=>({x:Number(D[a]??0),y:Number(D[l]??0),color:E?String(D[E]??""):void 0})),d=560,u=300,T=52,S=16,A=16,f=36,I=d-T-S,p=u-A-f,O=Math.min(...c.map(D=>D.x)),N=Math.max(...c.map(D=>D.x)),h=Math.min(...c.map(D=>D.y)),C=Math.max(...c.map(D=>D.y)),m=N-O||1,g=C-h||1,y=D=>T+(D-O)/m*I,_=D=>A+p-(D-h)/g*p,U=E?[...new Set(c.map(D=>D.color))]:[];return i.jsxs("div",{style:{padding:"8px 0"},children:[E&&U.length>0&&i.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:U.slice(0,12).map((D,b)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[i.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:Ue[b%Ue.length]}}),i.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:D})]},D))}),i.jsxs("svg",{width:"100%",height:u,viewBox:`0 0 ${d} ${u}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:6},(D,b)=>{const F=h+g*b/5,L=_(F);return i.jsxs("g",{children:[i.jsx("line",{x1:T,y1:L,x2:T+I,y2:L,stroke:r.tableBorder,strokeWidth:.5}),i.jsx("text",{x:T-6,y:L+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Me(F)})]},b)}),Array.from({length:6},(D,b)=>{const F=O+m*b/5,L=y(F);return i.jsx("text",{x:L,y:A+p+16,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Me(F)},b)}),i.jsx("line",{x1:T,y1:A,x2:T,y2:A+p,stroke:r.tableBorder,strokeWidth:1}),i.jsx("line",{x1:T,y1:A+p,x2:T+I,y2:A+p,stroke:r.tableBorder,strokeWidth:1}),i.jsx("text",{x:T+I/2,y:u-2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:a}),i.jsx("text",{x:10,y:A+p/2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,transform:`rotate(-90, 10, ${A+p/2})`,children:l}),c.map((D,b)=>{const F=E?U.indexOf(D.color):0;return i.jsx("circle",{cx:y(D.x),cy:_(D.y),r:o===b?5:3.5,fill:Ue[F%Ue.length],opacity:o===b?1:.7,style:{cursor:"crosshair",transition:"r 0.1s, opacity 0.1s"},onMouseEnter:()=>s(b),onMouseLeave:()=>s(null)},b)}),o!==null&&i.jsxs("g",{children:[i.jsx("rect",{x:y(c[o].x)+8,y:_(c[o].y)-24,width:100,height:28,rx:4,fill:r.cellBg,stroke:r.cellBorder,strokeWidth:1}),i.jsxs("text",{x:y(c[o].x)+13,y:_(c[o].y)-8,fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:["(",Me(c[o].x),", ",Me(c[o].y),")"]})]})]})]})}const ux=12;function dd({result:e,themeMode:t,chartConfig:n,isDonut:r}){const o=re[t],[s,a]=R.useState(null),{labelCol:l,valueCol:E}=xi(e,n),c=e.rows.slice(0,ux).map(O=>({label:String(O[l]??""),value:Math.abs(Number(O[E]??0))})),d=c.reduce((O,N)=>O+N.value,0)||1,u=90,T=90,S=70,A=r?40:0,f=[];let I=-Math.PI/2;c.forEach((O,N)=>{const h=O.value/d*2*Math.PI,C=I,m=I+h,g=u+S*Math.cos(C),y=T+S*Math.sin(C),_=u+S*Math.cos(m),U=T+S*Math.sin(m),D=h>Math.PI?1:0;let b;if(A>0){const F=u+A*Math.cos(C),L=T+A*Math.sin(C),P=u+A*Math.cos(m),M=T+A*Math.sin(m);b=`M ${g} ${y} A ${S} ${S} 0 ${D} 1 ${_} ${U} L ${P} ${M} A ${A} ${A} 0 ${D} 0 ${F} ${L} Z`}else b=`M ${u} ${T} L ${g} ${y} A ${S} ${S} 0 ${D} 1 ${_} ${U} Z`;f.push({path:b,color:Ue[N%Ue.length],label:O.label,value:O.value,pct:O.value/d*100}),I=m});const p=s!==null?f[s]:null;return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,padding:"8px 12px",flexWrap:"wrap"},children:[i.jsxs("svg",{width:180,height:180,style:{flexShrink:0},onMouseLeave:()=>a(null),children:[f.map((O,N)=>i.jsx("path",{d:O.path,fill:O.color,opacity:s===null||s===N?1:.55,style:{cursor:"pointer",transition:"opacity 0.15s"},onMouseEnter:()=>a(N)},N)),r&&i.jsxs(i.Fragment,{children:[i.jsx("text",{x:u,y:T-5,textAnchor:"middle",fontSize:11,fontFamily:o.fontMono,fill:o.textSecondary,children:Me(p?p.value:d)}),i.jsx("text",{x:u,y:T+9,textAnchor:"middle",fontSize:9,fontFamily:o.font,fill:o.textMuted,children:p?`${p.pct.toFixed(1)}%`:"total"})]})]}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,maxHeight:180,overflowY:"auto",flex:1},children:f.map((O,N)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,cursor:"default",opacity:s===null||s===N?1:.5},onMouseEnter:()=>a(N),onMouseLeave:()=>a(null),children:[i.jsx("div",{style:{width:10,height:10,borderRadius:2,background:O.color,flexShrink:0}}),i.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:O.label}),i.jsxs("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textMuted,marginLeft:"auto",flexShrink:0},children:[O.pct.toFixed(1),"%"]})]},N))})]})}function Tx({result:e,themeMode:t}){const n=re[t],[r,o]=R.useState(null),s=e.columns[0],a=e.columns.slice(1),l=e.rows.slice(0,30),E=l.flatMap(I=>a.map(p=>Number(I[p]??0))),c=Math.min(...E),u=Math.max(...E)-c||1,T=Math.min(50,480/a.length),S=24,A=100;function f(I){const p=(I-c)/u,O=Math.round(56+p*192),N=Math.round(139+p*-58),h=Math.round(253+p*-180);return`rgb(${O},${N},${h})`}return i.jsx("div",{style:{padding:"8px 0",overflowX:"auto"},children:i.jsxs("svg",{width:A+a.length*T+20,height:l.length*S+S+16,style:{display:"block",overflow:"visible"},children:[a.map((I,p)=>i.jsx("text",{x:A+p*T+T/2,y:14,textAnchor:"middle",fontSize:9,fontFamily:n.font,fill:n.textMuted,transform:`rotate(-30, ${A+p*T+T/2}, 14)`,children:I.length>8?I.slice(0,7)+"…":I},p)),l.map((I,p)=>{const O=String(I[s]??""),N=S+p*S;return i.jsxs("g",{children:[i.jsx("text",{x:A-6,y:N+S/2+4,textAnchor:"end",fontSize:10,fontFamily:n.font,fill:n.textSecondary,children:O.length>14?O.slice(0,13)+"…":O}),a.map((h,C)=>{const m=Number(I[h]??0),g=(r==null?void 0:r.r)===p&&(r==null?void 0:r.c)===C;return i.jsxs("g",{onMouseEnter:()=>o({r:p,c:C}),onMouseLeave:()=>o(null),children:[i.jsx("rect",{x:A+C*T,y:N,width:T-1,height:S-1,rx:2,fill:f(m),opacity:g?1:.85,stroke:g?n.accent:"none",strokeWidth:g?1.5:0}),g&&i.jsx("text",{x:A+C*T+T/2,y:N+S/2+4,textAnchor:"middle",fontSize:10,fontFamily:n.fontMono,fill:"#fff",fontWeight:600,children:Me(m)})]},C)})]},p)})]})})}function Sx({result:e,themeMode:t,chartConfig:n}){const r=re[t],[o,s]=R.useState(null),a=(n!=null&&n.x&&e.columns.includes(n.x)?n.x:void 0)??e.columns.find(y=>e.rows.slice(0,5).some(_=>zt(_[y])))??e.columns[0],l=e.rows.map(y=>Number(y[a]??0)).filter(y=>!isNaN(y));if(l.length===0)return null;const E=Math.min(20,Math.max(5,Math.ceil(Math.sqrt(l.length)))),c=Math.min(...l),T=(Math.max(...l)-c||1)/E,S=Array.from({length:E},(y,_)=>({low:c+_*T,high:c+(_+1)*T,count:0}));l.forEach(y=>{const _=Math.min(Math.floor((y-c)/T),E-1);S[_].count++});const A=Math.max(...S.map(y=>y.count),1),f=560,I=200,p=52,O=16,N=16,h=36,C=f-p-O,m=I-N-h,g=C/E;return i.jsx("div",{style:{padding:"8px 0"},children:i.jsxs("svg",{width:"100%",height:I,viewBox:`0 0 ${f} ${I}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:5},(y,_)=>{const U=A*(_+1)/5,D=N+m-U/A*m;return i.jsxs("g",{children:[i.jsx("line",{x1:p,y1:D,x2:p+C,y2:D,stroke:r.tableBorder,strokeWidth:.5}),i.jsx("text",{x:p-6,y:D+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Math.round(U)})]},_)}),S.map((y,_)=>{const U=y.count/A*m,D=p+_*g,b=N+m-U,F=o===_;return i.jsxs("g",{onMouseEnter:()=>s(_),onMouseLeave:()=>s(null),children:[i.jsx("rect",{x:D+1,y:b,width:g-2,height:U,rx:1,fill:F?r.accentHover:r.accent,opacity:F?1:.85,style:{transition:"fill 0.1s"}}),F&&i.jsx("text",{x:D+g/2,y:b-4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:y.count})]},_)}),S.filter((y,_)=>_%Math.ceil(E/6)===0).map((y,_)=>{const U=S.indexOf(y);return i.jsx("text",{x:p+U*g+g/2,y:N+m+16,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Me(y.low)},_)}),i.jsx("line",{x1:p,y1:N,x2:p,y2:N+m,stroke:r.tableBorder,strokeWidth:1}),i.jsx("line",{x1:p,y1:N+m,x2:p+C,y2:N+m,stroke:r.tableBorder,strokeWidth:1}),i.jsx("text",{x:p+C/2,y:I-2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:a})]})})}function Rx({result:e,themeMode:t,chartConfig:n}){const r=re[t],[o,s]=R.useState(null),{labelCol:a,valueCol:l}=xi(e,n),E=e.rows.slice(0,10).map(I=>({label:String(I[a]??""),value:Math.abs(Number(I[l]??0))}));if(E.length===0)return null;const c=E[0].value||1,d=400,u=36,T=4,S=16,A=E.length*(u+T)+S*2,f=d/2;return i.jsx("div",{style:{padding:"8px 0",display:"flex",justifyContent:"center"},children:i.jsx("svg",{width:d,height:A,style:{display:"block"},children:E.map((I,p)=>{const O=S+p*(u+T),N=I.value/c,h=Math.max(N*(d-80),40),C=o===p,m=p<E.length-1?E[p+1].value/c:N*.8,g=Math.max(m*(d-80),40),y=f-h/2,_=f+h/2,U=f+g/2,D=f-g/2,b=`M ${y} ${O} L ${_} ${O} L ${U} ${O+u} L ${D} ${O+u} Z`;return i.jsxs("g",{onMouseEnter:()=>s(p),onMouseLeave:()=>s(null),style:{cursor:"default"},children:[i.jsx("path",{d:b,fill:Ue[p%Ue.length],opacity:C?1:.85,style:{transition:"opacity 0.15s"}}),i.jsx("text",{x:f,y:O+u/2+1,textAnchor:"middle",fontSize:11,fontFamily:r.font,fill:"#fff",fontWeight:500,children:I.label}),i.jsxs("text",{x:f,y:O+u/2+13,textAnchor:"middle",fontSize:9,fontFamily:r.fontMono,fill:"rgba(255,255,255,0.7)",children:[Me(I.value)," (",(N*100).toFixed(0),"%)"]})]},p)})})})}function fx({result:e,themeMode:t,chartConfig:n}){const r=re[t],[o,s]=R.useState(null),{labelCol:a,valueCol:l}=xi(e,n),E=e.rows.slice(0,15).map(_=>({label:String(_[a]??""),value:Number(_[l]??0)}));if(E.length===0)return null;let c=0;const d=E.map(_=>{const U=c;return c+=_.value,{..._,start:U,end:c}}),u=d.flatMap(_=>[_.start,_.end]),T=Math.min(0,...u),A=Math.max(0,...u)-T||1,f=560,I=240,p=52,O=16,N=16,h=44,C=f-p-O,m=I-N-h,g=C/d.length,y=_=>N+m-(_-T)/A*m;return i.jsx("div",{style:{padding:"8px 0"},children:i.jsxs("svg",{width:"100%",height:I,viewBox:`0 0 ${f} ${I}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:6},(_,U)=>{const D=T+A*U/5,b=y(D);return i.jsxs("g",{children:[i.jsx("line",{x1:p,y1:b,x2:p+C,y2:b,stroke:r.tableBorder,strokeWidth:.5}),i.jsx("text",{x:p-6,y:b+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Me(D)})]},U)}),i.jsx("line",{x1:p,y1:y(0),x2:p+C,y2:y(0),stroke:r.textMuted,strokeWidth:1,strokeDasharray:"3,3"}),d.map((_,U)=>{const D=p+U*g,b=y(Math.max(_.start,_.end)),L=y(Math.min(_.start,_.end))-b,P=_.value>=0,M=o===U;return i.jsxs("g",{onMouseEnter:()=>s(U),onMouseLeave:()=>s(null),children:[U<d.length-1&&i.jsx("line",{x1:D+g-2,y1:y(_.end),x2:D+g+2,y2:y(_.end),stroke:r.textMuted,strokeWidth:1,strokeDasharray:"2,2"}),i.jsx("rect",{x:D+4,y:b,width:g-8,height:Math.max(L,1),rx:2,fill:P?r.success:r.error,opacity:M?1:.8,style:{transition:"opacity 0.1s"}}),M&&i.jsxs("text",{x:D+g/2,y:b-4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:[_.value>=0?"+":"",Me(_.value)]})]},U)}),d.map((_,U)=>i.jsx("text",{x:p+U*g+g/2,y:I-6,textAnchor:"middle",fontSize:9,fontFamily:r.font,fill:r.textMuted,transform:`rotate(-20, ${p+U*g+g/2}, ${I-6})`,children:_.label.length>8?_.label.slice(0,7)+"…":_.label},U)),i.jsx("line",{x1:p,y1:N,x2:p,y2:N+m,stroke:r.tableBorder,strokeWidth:1}),i.jsx("line",{x1:p,y1:N+m,x2:p+C,y2:N+m,stroke:r.tableBorder,strokeWidth:1})]})})}function Ax({result:e,themeMode:t,chartConfig:n}){const r=re[t],o=e.rows[0];if(!o)return null;const s=(n!=null&&n.y&&e.columns.includes(n.y)?n.y:void 0)??e.columns.find(y=>zt(o[y]))??e.columns[0],a=Number(o[s]??0),l=(n==null?void 0:n.title)??s,E=a>100?a*1.2:100,c=Math.min(Math.max(a/E,0),1),d=120,u=110,T=80,S=Math.PI,A=0,f=S-(S-A)*c,I=d+T*Math.cos(S),p=u+T*Math.sin(S),O=d+T*Math.cos(f),N=u+T*Math.sin(f),h=c>.5?1:0,C=d+T*Math.cos(A),m=u+T*Math.sin(A),g=c<.33?r.error:c<.66?r.warning:r.success;return i.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:"16px 24px"},children:i.jsxs("svg",{width:240,height:140,style:{display:"block",overflow:"visible"},children:[i.jsx("path",{d:`M ${I} ${p} A ${T} ${T} 0 1 1 ${C} ${m}`,fill:"none",stroke:r.tableBorder,strokeWidth:12,strokeLinecap:"round"}),c>0&&i.jsx("path",{d:`M ${I} ${p} A ${T} ${T} 0 ${h} 1 ${O} ${N}`,fill:"none",stroke:g,strokeWidth:12,strokeLinecap:"round"}),i.jsx("text",{x:d,y:u-4,textAnchor:"middle",fontSize:28,fontFamily:r.fontMono,fill:g,fontWeight:700,children:Me(a)}),i.jsx("text",{x:d,y:u+16,textAnchor:"middle",fontSize:11,fontFamily:r.font,fill:r.textMuted,children:l})]})})}function tf({result:e,themeMode:t,chartConfig:n}){const r=re[t],o=e.rows[0];if(!o)return null;const s=n!=null&&n.y&&e.columns.includes(n.y)?n.y:e.columns.find(d=>zt(o[d]))??e.columns[0],a=o[s],l=Number(a),E=isNaN(l)?String(a):l.toLocaleString(void 0,{maximumFractionDigits:2}),c=(n==null?void 0:n.title)??(n!=null&&n.x&&o[n.x]?String(o[n.x]):s);return i.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"32px 24px",gap:8},children:[i.jsx("span",{style:{fontSize:40,fontWeight:700,fontFamily:r.fontMono,color:r.accent,lineHeight:1.1},children:E}),i.jsx("span",{style:{fontSize:13,fontFamily:r.font,color:r.textMuted,textTransform:"uppercase",letterSpacing:"0.08em",fontWeight:500},children:c})]})}function px({config:e,columns:t,onChange:n,onClose:r,t:o}){const s={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 i.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:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i.jsx("span",{style:{fontSize:11,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:"Chart Settings"}),i.jsx("button",{onClick:r,style:{background:"none",border:"none",color:o.textMuted,cursor:"pointer",fontSize:14},children:"×"})]}),i.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Title",i.jsx("input",{value:e.title??"",onChange:a=>n({title:a.target.value||void 0}),placeholder:"Chart title",style:{...s,marginTop:2}})]}),i.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["X-axis label",i.jsx("input",{value:e.xLabel??"",onChange:a=>n({xLabel:a.target.value||void 0}),placeholder:"Auto",style:{...s,marginTop:2}})]}),i.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Y-axis label",i.jsx("input",{value:e.yLabel??"",onChange:a=>n({yLabel:a.target.value||void 0}),placeholder:"Auto",style:{...s,marginTop:2}})]}),i.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Legend",i.jsxs("select",{value:e.legendPosition??"top",onChange:a=>n({legendPosition:a.target.value}),style:{...s,marginTop:2},children:[i.jsx("option",{value:"top",children:"Top"}),i.jsx("option",{value:"bottom",children:"Bottom"}),i.jsx("option",{value:"left",children:"Left"}),i.jsx("option",{value:"right",children:"Right"}),i.jsx("option",{value:"none",children:"Hidden"})]})]}),i.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Color palette",i.jsx("select",{value:e.colorPalette??"default",onChange:a=>n({colorPalette:a.target.value}),style:{...s,marginTop:2},children:Object.keys(ef).map(a=>i.jsx("option",{value:a,children:a.charAt(0).toUpperCase()+a.slice(1)},a))})]}),i.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Max items",i.jsx("input",{type:"number",value:e.maxItems??pn,min:5,max:200,onChange:a=>n({maxItems:parseInt(a.target.value)||pn}),style:{...s,marginTop:2}})]})]})}function Ix({result:e,themeMode:t,chartConfig:n,onConfigChange:r}){const o=re[t],s=zr(e,n),[a,l]=R.useState(!1);return s==="kpi"?i.jsx(tf,{result:e,themeMode:t,chartConfig:n}):i.jsxs("div",{style:{position:"relative"},children:[(n==null?void 0:n.title)&&i.jsx("div",{style:{padding:"8px 12px 0",fontSize:13,fontWeight:600,color:o.textPrimary,fontFamily:o.font,textAlign:"center"},children:n.title}),r&&i.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&&i.jsx(px,{config:n??{},columns:e.columns,onChange:E=>r(E),onClose:()=>l(!1),t:o}),yi(s,e,t,n)]})}function yi(e,t,n,r){const o=r!=null&&r.x&&t.columns.includes(r.x)?r.x:void 0,s=r!=null&&r.y&&t.columns.includes(r.y)?r.y:void 0,a=o||s?Ox(t,o,s):t;switch(e){case"line":return i.jsx(Ed,{result:a,themeMode:n});case"area":return i.jsx(Ed,{result:a,themeMode:n,showArea:!0});case"bar":return i.jsx(Uc,{result:a,themeMode:n,chartConfig:r});case"grouped-bar":return i.jsx(cx,{result:a,themeMode:n,chartConfig:r});case"stacked-bar":return i.jsx(Ex,{result:a,themeMode:n,chartConfig:r});case"scatter":return i.jsx(dx,{result:t,themeMode:n,chartConfig:r});case"pie":return i.jsx(dd,{result:t,themeMode:n,chartConfig:r,isDonut:!1});case"donut":return i.jsx(dd,{result:t,themeMode:n,chartConfig:r,isDonut:!0});case"heatmap":return i.jsx(Tx,{result:t,themeMode:n});case"histogram":return i.jsx(Sx,{result:t,themeMode:n,chartConfig:r});case"funnel":return i.jsx(Rx,{result:t,themeMode:n,chartConfig:r});case"waterfall":return i.jsx(fx,{result:t,themeMode:n,chartConfig:r});case"gauge":return i.jsx(Ax,{result:t,themeMode:n,chartConfig:r});case"kpi":return i.jsx(tf,{result:t,themeMode:n,chartConfig:r});default:return i.jsx(Li,{result:t,themeMode:n})}}function Ox(e,t,n){const r=e.columns,o=[];t&&r.includes(t)&&o.push(t),n&&r.includes(n)&&o.push(n);for(const s of r)o.includes(s)||o.push(s);return o.join(",")===r.join(",")?e:{...e,columns:o,rows:e.rows.map(s=>{const a={};for(const l of o)a[l]=s[l];return a})}}function Dl(e){return e==="measure"?"#":e==="temporal"?"📅":"A"}function Ml(e,t){return e==="measure"?t.accent:e==="temporal"?"#e3b341":"#56d364"}const Nx=[{key:"x",label:"X-axis"},{key:"y",label:"Y-axis"},{key:"color",label:"Color"},{key:"facet",label:"Faceting"}],hx={chart:"bar"},wc="application/x-dql-chart-column";function nf(e,t){e.effectAllowed="move",e.setData(wc,JSON.stringify(t)),e.setData("text/plain",t.column)}function mx(e){const t=e.getData(wc);if(!t)return null;try{return JSON.parse(t)}catch{return null}}function Cx({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const s=re[r],a=e.chartConfig??hx,l=a.chart??"bar",E=R.useMemo(()=>{const f=e.upstream;if(f)return t.find(I=>I.name===f)},[e.upstream,t]),c=R.useMemo(()=>t.slice(0,n).filter(f=>f.name&&f.status==="success"&&f.result),[t,n]),d=E==null?void 0:E.result,u=R.useMemo(()=>{if(!d)return new Map;const f=new Map;for(const I of d.columns)f.set(I,J_(zR(I,d.rows)));return f},[d]),T=R.useMemo(()=>d?d.columns.filter(f=>u.get(f)==="measure"):[],[d,u]),S=R.useMemo(()=>d?d.columns.filter(f=>u.get(f)!=="measure"):[],[d,u]),A=f=>{o({chartConfig:{...a,...f}})};return!e.upstream||!d?i.jsxs("div",{style:{display:"flex",flexDirection:"column",background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,padding:"18px 20px",gap:12,fontFamily:s.font},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Chart"}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.textSecondary},children:e.name})]}),i.jsx("div",{style:{fontSize:12,color:s.textSecondary},children:"Pick an upstream dataframe to chart."}),c.length===0?i.jsx("div",{style:{fontSize:11,color:s.textMuted},children:"No successful upstream cells yet. Run a SQL/DQL cell above and name it, then come back."}):i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:c.map(f=>i.jsx("button",{onClick:()=>o({upstream:f.name}),style:{fontSize:11,fontFamily:s.fontMono,color:s.accent,background:`${s.accent}14`,border:`1px solid ${s.accent}55`,borderRadius:4,padding:"3px 10px",cursor:"pointer"},children:f.name},f.id))})]}):i.jsxs("div",{style:{display:"flex",flexDirection:"column",background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,overflow:"hidden",fontFamily:s.font},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${s.cellBorder}`,background:`${s.tableHeaderBg}60`},children:[i.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Chart"}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.textSecondary},children:e.name}),i.jsxs("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.fontMono},children:["· df: ",e.upstream]}),i.jsx("button",{onClick:()=>o({upstream:void 0}),title:"Change upstream dataframe",style:{fontSize:10,background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:3,color:s.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:s.fontMono},children:"change"}),i.jsx("div",{style:{flex:1}}),i.jsx("select",{value:l,onChange:f=>A({chart:f.target.value}),style:{fontSize:11,fontFamily:s.font,background:s.editorBg,color:s.textSecondary,border:`1px solid ${s.cellBorder}`,borderRadius:3,padding:"2px 6px",outline:"none"},children:_i.map(f=>i.jsx("option",{value:f.value,children:f.label},f.value))})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"200px 240px 1fr",minHeight:320},children:[i.jsxs("div",{style:{borderRight:`1px solid ${s.cellBorder}`,padding:10,display:"flex",flexDirection:"column",gap:12,overflow:"auto"},children:[i.jsx(ud,{label:"Measures",columns:T,kinds:u,theme:s,onPick:f=>A({y:f}),pickHint:"Y-axis"}),i.jsx(ud,{label:"Dimensions",columns:S,kinds:u,theme:s,onPick:f=>A({x:f}),pickHint:"X-axis"})]}),i.jsxs("div",{style:{borderRight:`1px solid ${s.cellBorder}`,padding:10,display:"flex",flexDirection:"column",gap:8},children:[i.jsxs("div",{style:{display:"flex",gap:4,borderBottom:`1px solid ${s.cellBorder}`,paddingBottom:4},children:[i.jsx(Td,{label:"Data",active:!0,theme:s}),i.jsx(Td,{label:"Style",theme:s})]}),Nx.map(f=>i.jsx(gx,{slotKey:f.key,label:f.label,value:a[f.key],columns:d.columns,kinds:u,theme:s,onAssign:(I,p)=>{const O={[f.key]:I};p&&p!==f.key&&(O[p]=void 0),A(O)},onClear:()=>A({[f.key]:void 0})},f.key))]}),i.jsx("div",{style:{padding:10,minWidth:0,overflow:"hidden"},children:yi(l,d,r,a)})]})]})}function ud({label:e,columns:t,kinds:n,theme:r,onPick:o,pickHint:s}){return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[i.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&&i.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 i.jsxs("button",{onClick:()=>o(a),draggable:!0,onDragStart:E=>nf(E.dataTransfer,{column:a}),title:`Drag to an axis slot, or click to set as ${s}`,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:E=>{E.currentTarget.style.borderColor=r.cellBorder,E.currentTarget.style.background=r.tableRowHover},onMouseLeave:E=>{E.currentTarget.style.borderColor="transparent",E.currentTarget.style.background="transparent"},children:[i.jsx("span",{style:{fontSize:9,fontFamily:r.fontMono,fontWeight:700,color:Ml(l,r),width:14,textAlign:"center"},children:Dl(l)}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a})]},a)})]})}function Td({label:e,active:t,theme:n}){return i.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 gx({slotKey:e,label:t,value:n,columns:r,kinds:o,theme:s,onAssign:a,onClear:l}){const[E,c]=R.useState(!1),[d,u]=R.useState(!1),T=R.useRef(null);R.useEffect(()=>{if(!E)return;const O=N=>{var h;(h=T.current)!=null&&h.contains(N.target)||c(!1)};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[E]);const S=O=>{O.dataTransfer.types.includes(wc)&&(O.preventDefault(),O.dataTransfer.dropEffect="move",d||u(!0))},A=()=>u(!1),f=O=>{u(!1);const N=mx(O.dataTransfer);N&&(O.preventDefault(),a(N.column,N.fromSlot),c(!1))},I=d?s.accent:n?`${s.accent}77`:s.cellBorder,p=d?`${s.accent}22`:n?`${s.accent}10`:s.editorBg;return i.jsxs("div",{ref:T,style:{position:"relative"},children:[i.jsx("div",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:s.textMuted,textTransform:"uppercase",fontFamily:s.font,marginBottom:3},children:t}),i.jsx("button",{onClick:()=>c(O=>!O),onDragOver:S,onDragEnter:S,onDragLeave:A,onDrop:f,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"5px 8px",background:p,border:`1px dashed ${I}`,borderRadius:4,cursor:"pointer",color:n?s.textPrimary:s.textMuted,fontFamily:s.fontMono,fontSize:11,textAlign:"left",transition:"background 0.1s, border-color 0.1s"},children:n?i.jsxs(i.Fragment,{children:[i.jsxs("span",{draggable:!0,onDragStart:O=>{O.stopPropagation(),nf(O.dataTransfer,{column:n,fromSlot:e})},style:{display:"inline-flex",alignItems:"center",gap:6,flex:1,cursor:"grab",minWidth:0},children:[i.jsx("span",{style:{color:Ml(o.get(n)??"dimension",s),fontWeight:700,width:14},children:Dl(o.get(n)??"dimension")}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]}),i.jsx("span",{onClick:O=>{O.stopPropagation(),l(),c(!1)},title:"Clear",style:{color:s.textMuted,fontSize:10,padding:"0 4px"},children:"✕"})]}):i.jsx("span",{children:d?"drop to set":"+ drop column"})}),E&&i.jsx("div",{style:{position:"absolute",top:"calc(100% + 2px)",left:0,right:0,zIndex:10,background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderRadius:6,boxShadow:"0 6px 16px rgba(0,0,0,0.25)",padding:4,maxHeight:220,overflow:"auto"},children:r.map(O=>i.jsxs("button",{onClick:()=>{a(O),c(!1)},style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 6px",background:"transparent",border:"none",borderRadius:3,cursor:"pointer",textAlign:"left",color:s.textPrimary,fontFamily:s.fontMono,fontSize:11},onMouseEnter:N=>{N.currentTarget.style.background=s.tableRowHover},onMouseLeave:N=>{N.currentTarget.style.background="transparent"},children:[i.jsx("span",{style:{color:Ml(o.get(O)??"dimension",s),fontWeight:700,width:14},children:Dl(o.get(O)??"dimension")}),i.jsx("span",{children:O})]},O))})]})}const Os=[{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 Pl(e){return`${e}_${Math.random().toString(36).slice(2,10)}`}function Lx(){return{mode:"keep",groups:[{id:Pl("g"),combinator:"and",rules:[]}]}}function _x(e){const t=Os.find(n=>n.value===e.operation);return t?e.column?t.needsValue?`${e.column} ${t.label} ${e.value||"…"}`:`${e.column} ${t.label}`:"…":""}function xx({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const s=re[r],a=R.useMemo(Lx,[e.id]),l=e.filterConfig??a,E=R.useMemo(()=>{const h=e.upstream??l.upstream;if(h)return t.find(C=>C.name===h)},[e.upstream,l.upstream,t]),c=R.useMemo(()=>t.slice(0,n).filter(h=>h.name&&h.status==="success"&&h.result),[t,n]),d=E==null?void 0:E.result,u=(d==null?void 0:d.columns)??[],T=h=>{o({filterConfig:h})},S=(h,C)=>{T({...l,groups:l.groups.map(m=>m.id===h?{...m,...C}:m)})},A=(h,C,m)=>{T({...l,groups:l.groups.map(g=>g.id===h?{...g,rules:g.rules.map(y=>y.id===C?{...y,...m}:y)}:g)})},f=h=>{T({...l,groups:l.groups.map(C=>C.id===h?{...C,rules:[...C.rules,{id:Pl("r"),column:u[0]??"",operation:"eq",value:""}]}:C)})},I=(h,C)=>{T({...l,groups:l.groups.map(m=>m.id===h?{...m,rules:m.rules.filter(g=>g.id!==C)}:m)})},p=()=>{T({...l,groups:[...l.groups,{id:Pl("g"),combinator:"and",rules:[]}]})},O=h=>{T({...l,groups:l.groups.filter(C=>C.id!==h)})};if(!E||!d)return i.jsxs("div",{style:{background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderLeft:"3px solid #ff7b72",borderRadius:6,padding:"18px 20px",fontFamily:s.font},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[i.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#ff7b72",background:"#ff7b7218",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Filter"}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.textSecondary},children:e.name})]}),i.jsx("div",{style:{fontSize:12,color:s.textSecondary,marginBottom:10},children:"Pick an upstream dataframe to filter."}),c.length===0?i.jsx("div",{style:{fontSize:11,color:s.textMuted},children:"No successful upstream cells yet. Run a SQL/DQL cell above and name it, then come back."}):i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:c.map(h=>i.jsx("button",{onClick:()=>o({upstream:h.name}),style:{fontSize:11,fontFamily:s.fontMono,color:"#ff7b72",background:"#ff7b7214",border:"1px solid #ff7b7255",borderRadius:4,padding:"3px 10px",cursor:"pointer"},children:h.name},h.id))})]});const N={background:s.editorBg,border:`1px solid ${s.cellBorder}`,borderRadius:3,color:s.textPrimary,fontSize:11,fontFamily:s.fontMono,padding:"3px 6px",outline:"none"};return i.jsxs("div",{style:{background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderLeft:"3px solid #ff7b72",borderRadius:6,fontFamily:s.font,overflow:"hidden"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${s.cellBorder}`,background:`${s.tableHeaderBg}60`},children:[i.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#ff7b72",background:"#ff7b7218",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Filter"}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.textSecondary},children:e.name}),i.jsxs("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.fontMono},children:["· df: ",E.name]}),i.jsx("button",{onClick:()=>o({upstream:void 0}),style:{fontSize:10,background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:3,color:s.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:s.fontMono},children:"change"}),i.jsx("div",{style:{flex:1}}),i.jsx("div",{style:{display:"inline-flex",border:`1px solid ${s.cellBorder}`,borderRadius:3,overflow:"hidden"},children:["keep","drop"].map(h=>i.jsx("button",{onClick:()=>T({...l,mode:h}),style:{fontSize:10,fontFamily:s.font,fontWeight:600,letterSpacing:"0.04em",padding:"3px 10px",background:l.mode===h?`${s.accent}20`:"transparent",color:l.mode===h?s.accent:s.textMuted,border:"none",cursor:"pointer",textTransform:"uppercase"},children:h==="keep"?"Keep rows":"Drop rows"},h))})]}),i.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:10},children:[l.groups.map((h,C)=>i.jsxs("div",{style:{border:`1px solid ${s.cellBorder}`,borderRadius:6,padding:10,background:`${s.tableHeaderBg}30`,display:"flex",flexDirection:"column",gap:8},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsxs("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:s.textMuted,textTransform:"uppercase",fontFamily:s.font},children:["Group ",C+1]}),i.jsx("div",{style:{display:"inline-flex",border:`1px solid ${s.cellBorder}`,borderRadius:3,overflow:"hidden"},children:["and","or"].map(m=>i.jsx("button",{onClick:()=>S(h.id,{combinator:m}),style:{fontSize:10,fontFamily:s.fontMono,padding:"2px 8px",background:h.combinator===m?`${s.accent}20`:"transparent",color:h.combinator===m?s.accent:s.textMuted,border:"none",cursor:"pointer",textTransform:"uppercase",fontWeight:700},children:m},m))}),i.jsx("div",{style:{flex:1}}),l.groups.length>1&&i.jsx("button",{onClick:()=>O(h.id),style:{fontSize:10,background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:3,color:s.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:s.font},children:"Remove group"})]}),h.rules.length===0&&i.jsx("div",{style:{fontSize:11,color:s.textMuted,fontFamily:s.font,padding:"4px 2px"},children:"No rules yet — add one below."}),h.rules.map(m=>{const g=Os.find(y=>y.value===m.operation)??Os[0];return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsxs("select",{value:m.column,onChange:y=>A(h.id,m.id,{column:y.target.value}),style:{...N,minWidth:140},children:[i.jsx("option",{value:"",children:"Select column"}),u.map(y=>i.jsx("option",{value:y,children:y},y))]}),i.jsx("select",{value:m.operation,onChange:y=>A(h.id,m.id,{operation:y.target.value}),style:{...N,minWidth:120},children:Os.map(y=>i.jsx("option",{value:y.value,children:y.label},y.value))}),g.needsValue&&i.jsx("input",{value:m.value,onChange:y=>A(h.id,m.id,{value:y.target.value}),placeholder:"Value",style:{...N,flex:1,minWidth:100}}),i.jsx("button",{onClick:()=>I(h.id,m.id),title:"Remove rule",style:{background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:3,color:s.textMuted,fontSize:10,padding:"2px 6px",cursor:"pointer"},children:"✕"})]},m.id)}),i.jsx("div",{children:i.jsx("button",{onClick:()=>f(h.id),style:{fontSize:10,fontFamily:s.font,color:s.accent,background:"transparent",border:`1px dashed ${s.accent}55`,borderRadius:3,padding:"3px 10px",cursor:"pointer",letterSpacing:"0.04em"},children:"+ Add filter"})})]},h.id)),i.jsx("div",{children:i.jsx("button",{onClick:p,style:{fontSize:10,fontFamily:s.font,color:s.textMuted,background:"transparent",border:`1px dashed ${s.btnBorder}`,borderRadius:3,padding:"3px 10px",cursor:"pointer",letterSpacing:"0.04em"},children:"+ Add filter group"})})]}),i.jsxs("div",{style:{padding:"6px 12px",borderTop:`1px solid ${s.cellBorder}`,background:`${s.tableHeaderBg}40`,fontSize:10,fontFamily:s.fontMono,color:s.textMuted,letterSpacing:"0.04em",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},children:[l.mode==="keep"?"KEEP WHERE ":"DROP WHERE ",l.groups.map(h=>h.rules.map(_x).join(` ${h.combinator.toUpperCase()} `)).filter(Boolean).map(h=>`(${h})`).join(" AND ")||"—"]})]})}function Sd(e){return typeof e=="number"?e:typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e))?Number(e):null}function bl(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 Sd(r)}const n=e.map(Sd).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 yx=[{value:"sum",label:"Sum"},{value:"avg",label:"Average"},{value:"count",label:"Count"},{value:"min",label:"Min"},{value:"max",label:"Max"},{value:"last",label:"Last"}],Dx=[{value:"number",label:"Number"},{value:"currency",label:"Currency"},{value:"percent",label:"Percent"},{value:"duration",label:"Duration"}],Mx={aggregation:"count",format:"number"};function Px(e,t,n){return n==="count"?bl(e.rows,"count"):!t||!e.columns.includes(t)?null:bl(e.rows.map(r=>r[t]),n)}function bx(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 vx({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const s=re[r],a=e.singleValueConfig??Mx,l=a.aggregation??"count",E=a.format??"number",c=R.useMemo(()=>{const p=e.upstream??a.upstream;if(p)return t.find(O=>O.name===p)},[e.upstream,a.upstream,t]),d=R.useMemo(()=>t.slice(0,n).filter(p=>p.name&&p.status==="success"&&p.result),[t,n]),u=c==null?void 0:c.result,T=(u==null?void 0:u.columns)??[],S=R.useMemo(()=>u?Px(u,a.metric,l):null,[u,a.metric,l]),A=p=>{o({singleValueConfig:{...a,...p}})};if(!c||!u)return i.jsxs("div",{style:{background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,padding:"18px 20px",fontFamily:s.font},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[i.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Single value"}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.textSecondary},children:e.name})]}),i.jsx("div",{style:{fontSize:12,color:s.textSecondary,marginBottom:10},children:"Pick an upstream dataframe to compute a single value."}),d.length===0?i.jsx("div",{style:{fontSize:11,color:s.textMuted},children:"No successful upstream cells yet."}):i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:d.map(p=>i.jsx("button",{onClick:()=>o({upstream:p.name}),style:{fontSize:11,fontFamily:s.fontMono,color:"#a371f7",background:"#a371f714",border:"1px solid #a371f755",borderRadius:4,padding:"3px 10px",cursor:"pointer"},children:p.name},p.id))})]});const f=bx(S,E),I={background:s.editorBg,border:`1px solid ${s.cellBorder}`,borderRadius:3,color:s.textPrimary,fontSize:11,fontFamily:s.fontMono,padding:"3px 6px",outline:"none"};return i.jsxs("div",{style:{background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,fontFamily:s.font,overflow:"hidden"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${s.cellBorder}`,background:`${s.tableHeaderBg}60`},children:[i.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Single value"}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.textSecondary},children:e.name}),i.jsxs("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.fontMono},children:["· df: ",c.name]}),i.jsx("button",{onClick:()=>o({upstream:void 0}),style:{fontSize:10,background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:3,color:s.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:s.fontMono},children:"change"})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"280px 1fr"},children:[i.jsxs("div",{style:{padding:12,display:"flex",flexDirection:"column",gap:8,borderRight:`1px solid ${s.cellBorder}`},children:[i.jsx(ns,{label:"Aggregation",theme:s,children:i.jsx("select",{value:l,onChange:p=>A({aggregation:p.target.value}),style:{...I,width:"100%"},children:yx.map(p=>i.jsx("option",{value:p.value,children:p.label},p.value))})}),l!=="count"&&i.jsx(ns,{label:"Metric column",theme:s,children:i.jsxs("select",{value:a.metric??"",onChange:p=>A({metric:p.target.value||void 0}),style:{...I,width:"100%"},children:[i.jsx("option",{value:"",children:"Select column"}),T.map(p=>i.jsx("option",{value:p,children:p},p))]})}),i.jsx(ns,{label:"Format",theme:s,children:i.jsx("select",{value:E,onChange:p=>A({format:p.target.value}),style:{...I,width:"100%"},children:Dx.map(p=>i.jsx("option",{value:p.value,children:p.label},p.value))})}),i.jsx(ns,{label:"Label",theme:s,children:i.jsx("input",{value:a.label??"",onChange:p=>A({label:p.target.value||void 0}),placeholder:"e.g. Total revenue",style:{...I,width:"100%"}})})]}),i.jsxs("div",{style:{padding:"24px 20px",display:"flex",flexDirection:"column",justifyContent:"center",gap:6},children:[i.jsx("div",{style:{fontSize:11,fontFamily:s.font,color:s.textMuted,letterSpacing:"0.06em",textTransform:"uppercase",fontWeight:600},children:a.label??`${l.toUpperCase()}${a.metric?` · ${a.metric}`:""}`}),i.jsx("div",{style:{fontSize:42,fontWeight:700,fontFamily:s.font,color:s.textPrimary,lineHeight:1.1,letterSpacing:"-0.02em"},children:f}),i.jsxs("div",{style:{fontSize:10,color:s.textMuted,fontFamily:s.fontMono},children:["from ",u.rows.length.toLocaleString()," rows"]})]})]})]})}function ns({label:e,theme:t,children:n}){return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[i.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:t.textMuted,textTransform:"uppercase",fontFamily:t.font},children:e}),n]})}const Ux=["sum","avg","count","min","max","count_distinct"],wx={rows:[],columns:[],values:[]};function Rd(e,t){return t.map(n=>String(e[n]??"")).join("|")}function Bx({cell:e,cells:t,index:n,themeMode:r,onUpdate:o}){const s=re[r],a=e.pivotConfig??wx,l=R.useMemo(()=>{const S=e.upstream??a.upstream;if(S)return t.find(A=>A.name===S)},[e.upstream,a.upstream,t]),E=R.useMemo(()=>t.slice(0,n).filter(S=>S.name&&S.status==="success"&&S.result),[t,n]),c=l==null?void 0:l.result,d=(c==null?void 0:c.columns)??[],u=S=>o({pivotConfig:S}),T=R.useMemo(()=>{if(!c||a.rows.length===0&&a.columns.length===0||a.values.length===0)return null;const S=new Set,A=new Map;for(const O of c.rows){const N=Rd(O,a.rows),h=Rd(O,a.columns);S.add(h);let C=A.get(N);if(!C){const g={};for(const y of a.rows)g[y]=O[y];C={row:g,groups:new Map},A.set(N,C)}const m=C.groups.get(h)??[];m.push(O),C.groups.set(h,m)}const f=[...S].sort(),I=f.map(O=>O===""?"value":O),p=[];for(const[,O]of A){const N=O,h=f.map(C=>{const m=N.groups.get(C)??[],g={};for(const y of a.values){const _=m.map(U=>U[y.column]);g[`${y.aggregation}(${y.column})`]=bl(_,y.aggregation)}return g});p.push({rowDims:N.row,values:h})}return{columnKeys:f,columnHeaders:I,body:p}},[a,c]);return!l||!c?i.jsxs("div",{style:{background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,padding:"18px 20px",fontFamily:s.font},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10},children:[i.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Pivot"}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.textSecondary},children:e.name})]}),i.jsx("div",{style:{fontSize:12,color:s.textSecondary,marginBottom:10},children:"Pick an upstream dataframe to pivot."}),E.length===0?i.jsx("div",{style:{fontSize:11,color:s.textMuted},children:"No successful upstream cells yet."}):i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:E.map(S=>i.jsx("button",{onClick:()=>o({upstream:S.name}),style:{fontSize:11,fontFamily:s.fontMono,color:"#a371f7",background:"#a371f714",border:"1px solid #a371f755",borderRadius:4,padding:"3px 10px",cursor:"pointer"},children:S.name},S.id))})]}):i.jsxs("div",{style:{background:s.cellBg,border:`1px solid ${s.cellBorder}`,borderLeft:"3px solid #a371f7",borderRadius:6,fontFamily:s.font,overflow:"hidden"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",borderBottom:`1px solid ${s.cellBorder}`,background:`${s.tableHeaderBg}60`},children:[i.jsx("span",{style:{fontSize:10,fontFamily:s.fontMono,fontWeight:700,letterSpacing:"0.08em",color:"#a371f7",background:"#a371f718",padding:"2px 6px",borderRadius:3,textTransform:"uppercase"},children:"Pivot"}),e.name&&i.jsx("span",{style:{fontSize:12,fontFamily:s.fontMono,color:s.textSecondary},children:e.name}),i.jsxs("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.fontMono},children:["· df: ",l.name]}),i.jsx("button",{onClick:()=>o({upstream:void 0}),style:{fontSize:10,background:"transparent",border:`1px solid ${s.btnBorder}`,borderRadius:3,color:s.textMuted,padding:"1px 6px",cursor:"pointer",fontFamily:s.fontMono},children:"change"})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",padding:12,gap:10,borderBottom:`1px solid ${s.cellBorder}`},children:[i.jsx(fd,{label:"Rows",selected:a.rows,availableColumns:d,theme:s,onAdd:S=>u({...a,rows:[...a.rows,S]}),onRemove:S=>u({...a,rows:a.rows.filter(A=>A!==S)})}),i.jsx(fd,{label:"Columns",selected:a.columns,availableColumns:d,theme:s,onAdd:S=>u({...a,columns:[...a.columns,S]}),onRemove:S=>u({...a,columns:a.columns.filter(A=>A!==S)})}),i.jsx(Fx,{values:a.values,availableColumns:d,theme:s,onAdd:S=>u({...a,values:[...a.values,{column:S,aggregation:"sum"}]}),onUpdate:(S,A)=>u({...a,values:a.values.map((f,I)=>I===S?{...f,...A}:f)}),onRemove:S=>u({...a,values:a.values.filter((A,f)=>f!==S)})})]}),i.jsx("div",{style:{padding:12,overflowX:"auto"},children:!T||T.body.length===0?i.jsx("div",{style:{fontSize:11,color:s.textMuted,fontFamily:s.font},children:"Pick at least one row/column dimension and one value to see a preview."}):i.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontFamily:s.fontMono,fontSize:11},children:[i.jsx("thead",{children:i.jsxs("tr",{children:[a.rows.map(S=>i.jsx("th",{style:{textAlign:"left",padding:"4px 8px",borderBottom:`1px solid ${s.cellBorder}`,color:s.textSecondary,fontWeight:600},children:S},S)),T.columnHeaders.map((S,A)=>i.jsx("th",{style:{textAlign:"right",padding:"4px 8px",borderBottom:`1px solid ${s.cellBorder}`,color:s.textSecondary,fontWeight:600},children:S},A))]})}),i.jsx("tbody",{children:T.body.slice(0,50).map((S,A)=>i.jsxs("tr",{children:[a.rows.map(f=>i.jsx("td",{style:{padding:"3px 8px",color:s.textPrimary,borderBottom:`1px solid ${s.cellBorder}30`},children:String(S.rowDims[f]??"")},f)),S.values.map((f,I)=>i.jsx("td",{style:{padding:"3px 8px",color:s.textPrimary,textAlign:"right",borderBottom:`1px solid ${s.cellBorder}30`},children:Object.values(f).map((p,O)=>i.jsx("div",{children:p===null?"—":typeof p=="number"?p.toLocaleString(void 0,{maximumFractionDigits:2}):String(p)},O))},I))]},A))})]})})]})}function fd({label:e,selected:t,availableColumns:n,theme:r,onAdd:o,onRemove:s}){return i.jsx(rf,{label:e,theme:r,availableColumns:n.filter(a=>!t.includes(a)),onAdd:o,children:t.length===0?i.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:"+ add column"}):t.map(a=>i.jsxs("div",{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,margin:2},children:[a,i.jsx("span",{onClick:()=>s(a),style:{cursor:"pointer",color:r.textMuted,fontSize:10},title:"Remove",children:"✕"})]},a))})}function Fx({values:e,availableColumns:t,theme:n,onAdd:r,onUpdate:o,onRemove:s}){return i.jsx(rf,{label:"Values",theme:n,availableColumns:t,onAdd:r,children:e.length===0?i.jsx("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:"+ add value"}):e.map((a,l)=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,margin:2},children:[i.jsx("select",{value:a.aggregation,onChange:E=>o(l,{aggregation:E.target.value}),style:{background:n.editorBg,border:`1px solid ${n.cellBorder}`,borderRadius:3,color:n.textSecondary,fontSize:10,fontFamily:n.fontMono,padding:"1px 4px"},children:Ux.map(E=>i.jsx("option",{value:E,children:E},E))}),i.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 6px",background:`${n.accent}14`,border:`1px solid ${n.accent}55`,borderRadius:3,fontSize:11,fontFamily:n.fontMono,color:n.textPrimary},children:[a.column,i.jsx("span",{onClick:()=>s(l),style:{cursor:"pointer",color:n.textMuted,fontSize:10},children:"✕"})]})]},l))})}function rf({label:e,theme:t,availableColumns:n,onAdd:r,children:o}){const[s,a]=R.useState(!1),l=R.useRef(null);return R.useEffect(()=>{if(!s)return;const E=c=>{var d;(d=l.current)!=null&&d.contains(c.target)||a(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[s]),i.jsxs("div",{ref:l,style:{position:"relative",display:"flex",flexDirection:"column",gap:4},children:[i.jsx("div",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.1em",color:t.textMuted,textTransform:"uppercase",fontFamily:t.font},children:e}),i.jsx("div",{onClick:()=>a(E=>!E),style:{minHeight:42,border:`1px dashed ${t.cellBorder}`,borderRadius:4,padding:4,cursor:"pointer",display:"flex",flexWrap:"wrap",alignItems:"center"},children:o}),s&&n.length>0&&i.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(E=>i.jsx("button",{onClick:()=>{r(E),a(!1)},style:{width:"100%",padding:"4px 8px",background:"transparent",border:"none",borderRadius:3,cursor:"pointer",textAlign:"left",color:t.textPrimary,fontFamily:t.fontMono,fontSize:11},onMouseEnter:c=>{c.currentTarget.style.background=t.tableRowHover},onMouseLeave:c=>{c.currentTarget.style.background="transparent"},children:E},E))})]})}const Gx=[{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
367
+ category,
368
+ COUNT(*) AS count,
369
+ SUM(amount) AS total
370
+ FROM read_csv_auto('data/filename.csv')
371
+ GROUP BY category
372
+ ORDER BY total DESC`},{id:"filter-date",label:"Filter by date range",description:"Filter rows between two dates",category:"SQL",code:`SELECT *
373
+ FROM read_csv_auto('data/filename.csv')
374
+ WHERE date_column >= '2024-01-01'
375
+ 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
376
+ *,
377
+ ROW_NUMBER() OVER (PARTITION BY category ORDER BY amount DESC) AS rank
378
+ 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 (
379
+ SELECT *
380
+ FROM read_csv_auto('data/filename.csv')
381
+ WHERE amount > 0
382
+ )
383
+ SELECT
384
+ category,
385
+ SUM(amount) AS total
386
+ FROM base
387
+ 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
388
+ FROM read_csv_auto('data/table_a.csv') AS a
389
+ JOIN read_csv_auto('data/table_b.csv') AS b
390
+ ON a.id = b.id`},{id:"pivot",label:"Pivot / unpivot",description:"Pivot a column into multiple columns",category:"SQL",code:`SELECT *
391
+ FROM (
392
+ SELECT category, quarter, amount
393
+ FROM read_csv_auto('data/filename.csv')
394
+ ) 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" {
395
+ domain = "analytics"
396
+ type = "custom"
397
+ description = "Describe what this block does"
398
+ owner = "data-team"
399
+ tags = ["analytics"]
400
+
401
+ query = """
402
+ SELECT *
403
+ FROM read_csv_auto('data/filename.csv')
404
+ LIMIT 100
405
+ """
406
+
407
+ visualization {
408
+ chart = "table"
409
+ }
410
+ }`},{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" {
411
+ domain = "revenue"
412
+ type = "custom"
413
+ description = "Revenue grouped by segment"
414
+ owner = "data-team"
415
+ tags = ["revenue"]
416
+
417
+ params {
418
+ period = "current_quarter"
419
+ }
420
+
421
+ query = """
422
+ SELECT
423
+ segment_tier AS segment,
424
+ SUM(amount) AS revenue
425
+ FROM read_csv_auto('data/revenue.csv')
426
+ WHERE fiscal_period = \${period}
427
+ GROUP BY segment_tier
428
+ ORDER BY revenue DESC
429
+ """
430
+
431
+ visualization {
432
+ chart = "bar"
433
+ x = segment
434
+ y = revenue
435
+ }
436
+
437
+ tests {
438
+ assert row_count > 0
439
+ }
440
+ }`},{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)
441
+ FROM fct_revenue
442
+ GROUP BY @dim(segment)
443
+ 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" {
444
+ domain = "revenue"
445
+ type = "semantic"
446
+ owner = "data-team"
447
+ description = "Annual Recurring Revenue by subscription plan tier"
448
+ tags = ["arr", "revenue", "saas"]
449
+
450
+ metric = "arr"
451
+ dimensions = ["plan_tier"]
452
+
453
+ visualization {
454
+ chart = "bar"
455
+ x = plan_tier
456
+ y = arr
457
+ }
458
+
459
+ tests {
460
+ assert row_count > 0
461
+ }
462
+ }`},{id:"revenue-by-segment",label:"Revenue by segment",description:"Aggregate revenue totals, deal count, and average deal size per segment",category:"Analysis",code:`SELECT
463
+ segment_tier,
464
+ SUM(amount) AS total_revenue,
465
+ COUNT(*) AS deals,
466
+ ROUND(AVG(amount), 0) AS avg_deal
467
+ FROM read_csv_auto('data/revenue.csv')
468
+ GROUP BY segment_tier
469
+ ORDER BY total_revenue DESC`},{id:"quarterly-trend",label:"Quarterly trend",description:"Revenue totals grouped by fiscal year and quarter",category:"Analysis",code:`SELECT
470
+ fiscal_year || ' ' || fiscal_quarter AS period,
471
+ SUM(amount) AS revenue
472
+ FROM read_csv_auto('data/revenue.csv')
473
+ GROUP BY fiscal_year, fiscal_quarter
474
+ ORDER BY fiscal_year, fiscal_quarter`}];function Hx({onInsert:e,themeMode:t,cellType:n}){const r=re[t],[o,s]=R.useState(!1),[a,l]=R.useState(null),E=R.useRef(null),c=Gx.filter(T=>n==="dql"?T.category==="DQL":T.category==="SQL"||T.category==="Analysis"),d=Array.from(new Set(c.map(T=>T.category)));R.useEffect(()=>{if(!o)return;function T(S){E.current&&!E.current.contains(S.target)&&s(!1)}return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[o]);function u(T){e(T),s(!1)}return i.jsxs("div",{ref:E,style:{position:"relative",display:"inline-block"},children:[i.jsxs("button",{title:"Insert template snippet",onClick:()=>s(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:[i.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:i.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&&i.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:d.map(T=>i.jsxs("div",{children:[i.jsx("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:700,fontFamily:r.font,letterSpacing:"0.08em",textTransform:"uppercase",color:r.textMuted},children:T}),c.filter(S=>S.category===T).map(S=>i.jsxs("button",{onMouseEnter:()=>l(S.id),onMouseLeave:()=>l(null),onClick:()=>u(S.code),style:{width:"100%",padding:"7px 12px",textAlign:"left",background:a===S.id?r.sidebarItemHover:"transparent",border:"none",cursor:"pointer",display:"flex",flexDirection:"column",gap:2,transition:"background 0.1s"},children:[i.jsx("span",{style:{fontSize:12,fontWeight:600,fontFamily:r.font,color:r.textPrimary,lineHeight:1.4},children:S.label}),i.jsx("span",{style:{fontSize:11,fontFamily:r.font,color:r.textMuted,lineHeight:1.4},children:S.description})]},S.id))]},T))})]})}function ma(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function kx(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 Yx({cell:e,onClose:t,onSaved:n,initialContent:r,initialName:o,initialDescription:s,initialTags:a}){const{state:l,dispatch:E}=de(),c=re[l.themeMode],d=R.useRef(null),[u,T]=R.useState(o||e.name||"new_block"),[S,A]=R.useState(""),[f,I]=R.useState(s??l.notebookMetadata.description??""),[p,O]=R.useState((a??l.notebookMetadata.categories??[]).join(", ")),[N,h]=R.useState(r??e.content),[C,m]=R.useState(!1),[g,y]=R.useState(null),_=R.useMemo(()=>kx(N),[N]);R.useEffect(()=>{var L;(L=d.current)==null||L.focus()},[]),R.useEffect(()=>{const L=P=>{P.key==="Escape"&&t()};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[t]);const U=l.semanticLayer.domains,D=`${S.trim()?`blocks/${ma(S)}/`:"blocks/"}${ma(u)||"new-block"}.dql`,b=async()=>{var L;if(!u.trim()){y("Block name is required.");return}if(!N.trim()){y("Block content is required.");return}m(!0),y(null);try{const P=await Q.saveAsBlock({cellId:e.id,notebookPath:((L=l.activeFile)==null?void 0:L.path)??null,name:u.trim(),domain:S.trim()||void 0,content:N,description:f.trim()||void 0,tags:p.split(",").map(v=>v.trim()).filter(Boolean),metricRefs:_}),M={name:`${ma(u)||"new-block"}.dql`,path:P.path,type:"block",folder:"blocks"};l.files.some(v=>v.path===P.path)||E({type:"FILE_ADDED",file:M});const w=await Q.openBlockStudio(P.path);E({type:"OPEN_BLOCK_STUDIO",file:M,payload:w}),n==null||n({...P,name:u.trim()}),t()}catch(P){y(P instanceof Error?P.message:String(P))}finally{m(!1)}},F={width:"100%",background:c.inputBg,border:`1px solid ${g?c.error:c.inputBorder}`,borderRadius:6,color:c.textPrimary,fontSize:13,fontFamily:c.font,padding:"8px 12px",outline:"none",boxSizing:"border-box"};return i.jsx("div",{onClick:L=>{L.target===L.currentTarget&&t()},style:{position:"fixed",inset:0,background:c.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1100,backdropFilter:"blur(4px)"},children:i.jsxs("div",{style:{width:760,maxWidth:"calc(100vw - 48px)",maxHeight:"calc(100vh - 48px)",overflow:"auto",background:c.modalBg,border:`1px solid ${c.cellBorder}`,borderRadius:12,boxShadow:"0 20px 60px rgba(0,0,0,0.5)"},children:[i.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[i.jsx("h2",{style:{margin:0,fontSize:16,fontWeight:600,color:c.textPrimary,fontFamily:c.font},children:"Save as Block"}),i.jsx("button",{onClick:t,style:{background:"transparent",border:"none",color:c.textMuted,cursor:"pointer",fontSize:18},children:"×"})]}),i.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},children:[i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:c.textSecondary,fontFamily:c.font},children:"Block Name"}),i.jsx("input",{ref:d,value:u,onChange:L=>T(L.target.value),style:F})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:c.textSecondary,fontFamily:c.font},children:"Domain"}),i.jsx("input",{value:S,onChange:L=>A(L.target.value),list:"semantic-domain-options",style:F,placeholder:"finance"}),i.jsx("datalist",{id:"semantic-domain-options",children:U.map(L=>i.jsx("option",{value:L},L))})]})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:c.textSecondary,fontFamily:c.font},children:"Description"}),i.jsx("input",{value:f,onChange:L=>I(L.target.value),style:F})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:c.textSecondary,fontFamily:c.font},children:"Tags"}),i.jsx("input",{value:p,onChange:L=>O(L.target.value),style:F,placeholder:"revenue, dashboard"})]})]}),i.jsx("div",{style:{fontSize:12,color:c.textMuted,fontFamily:c.fontMono,padding:"8px 12px",background:c.pillBg,borderRadius:6},children:D}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:c.textSecondary,fontFamily:c.font},children:"Content Preview"}),i.jsx("textarea",{value:N,onChange:L=>h(L.target.value),style:{...F,minHeight:220,resize:"vertical",fontFamily:c.fontMono,lineHeight:1.5}})]}),_.length>0&&i.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,padding:"10px 12px",background:c.pillBg,borderRadius:6},children:[i.jsx("span",{style:{fontSize:11,color:c.textMuted,fontFamily:c.font},children:"Detected semantic refs:"}),_.map(L=>i.jsx("span",{style:{fontSize:11,color:c.accent,fontFamily:c.fontMono,background:`${c.accent}18`,borderRadius:999,padding:"2px 8px"},children:L},L))]}),g&&i.jsx("div",{style:{fontSize:12,color:c.error,fontFamily:c.font},children:g})]}),i.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${c.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[i.jsx("button",{onClick:t,style:{background:c.btnBg,border:`1px solid ${c.btnBorder}`,borderRadius:6,color:c.textSecondary,cursor:"pointer",fontSize:13,fontFamily:c.font,padding:"7px 16px"},children:"Cancel"}),i.jsx("button",{onClick:b,disabled:C,style:{background:c.accent,border:`1px solid ${c.accent}`,borderRadius:6,color:"#fff",cursor:C?"not-allowed":"pointer",fontSize:13,fontFamily:c.font,padding:"7px 20px",opacity:C?.6:1},children:C?"Saving...":"Save Block"})]})]})})}function jx(e,t){var o,s,a,l;const n=e.upstream??((o=e.singleValueConfig)==null?void 0:o.upstream)??((s=e.filterConfig)==null?void 0:s.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(E=>E.name===n&&(E.type==="sql"||E.type==="dql"));return!r||!r.content.trim()?null:{name:r.name,sql:r.content.trim()}}function Wx(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}`),`
475
+ visualization {
476
+ ${t.join(`
477
+ `)}
478
+ }`}function Vx(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,'\\"')}"`),`
479
+ visualization {
480
+ ${t.join(`
481
+ `)}
482
+ }`}function $x(e,t){return` query = """
483
+ ${e.replace(/^/gm," ")}
484
+ """${t}`}function Xx(e,t){var a,l,E,c;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=jx(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,s;switch(e.type){case"chart":r=Wx(e.chartConfig),o=e.name??(n.name?`${n.name}_chart`:"chart_block"),s=((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=Vx(e.singleValueConfig),o=e.name??((E=e.singleValueConfig)!=null&&E.label?e.singleValueConfig.label:`${n.name??"metric"}_kpi`),s=(c=e.singleValueConfig)==null?void 0:c.label;break;case"filter":case"pivot":case"table":o=e.name??(n.name?`${n.name}_${e.type}`:`${e.type}_block`);break}return{content:$x(n.sql,r),suggestedName:o,suggestedDescription:s,derivedFromUpstream:!0}}function Kx(e){let t=e;try{const c=JSON.parse(e);c&&typeof c.error=="string"&&(t=c.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 s;const a=t.match(/at or near "([^"]+)"/i);a?s=a[1]:/at end of input/i.test(t)&&(s="end of input");let l;n==="Syntax Error"?s==='"""'||t.includes('"""')?l="Triple-quoted strings are DQL block syntax. Use a DQL cell for block syntax, or plain SQL in a SQL cell.":s==="end of input"||/at end of input/i.test(t)?l="Query is incomplete — check for unclosed parentheses, missing keywords, or a dangling comma.":(s===")"||s==="(")&&(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 E=t.replace(/^(Parser Error|Binder Error|Conversion Error|Invalid Input Error|IO Error|Constraint Error):\s*/i,"").trim();return{type:n,message:E,line:r,near:s,hint:l}}function zx(e,t){const n=e.length,r=t.length,o=Array.from({length:n+1},(s,a)=>Array.from({length:r+1},(l,E)=>a===0?E:E===0?a:0));for(let s=1;s<=n;s++)for(let a=1;a<=r;a++)o[s][a]=e[s-1]===t[a-1]?o[s-1][a-1]:1+Math.min(o[s-1][a],o[s][a-1],o[s-1][a-1]);return o[n][r]}function Ad(e,t){const n=e.toLowerCase();let r=null,o=4;for(const s of t){const a=zx(n,s.toLowerCase());a<o&&(o=a,r=s)}return r}function Jx({message:e,themeMode:t,onFix:n,schemaTables:r}){const o=re[t],s=Kx(e);let a=null;if(r&&r.length>0&&s.type==="Reference Error"){const E=/column.*not found|Referenced column/i.test(s.message),c=/table.*not found|Table.*does not exist/i.test(s.message);if(E&&s.near){const d=r.flatMap(T=>T.columns.map(S=>S.name)),u=Ad(s.near,d);u&&(a=`Did you mean column "${u}"?`)}else if(c&&s.near){const d=Ad(s.near,r.map(u=>u.name));d&&(a=`Did you mean table "${d}"?`)}}const l=n&&(s.type==="Syntax Error"||s.near===")"||s.near==="("||s.near==="end of input");return i.jsxs("div",{style:{padding:"12px 14px",background:`${o.error}10`,borderLeft:`3px solid ${o.error}`,display:"flex",flexDirection:"column",gap:8},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[i.jsx("div",{style:{flexShrink:0,color:o.error,display:"flex",alignItems:"center"},children:i.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})})}),i.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:s.type}),s.line!==void 0&&i.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 ",s.line]}),s.near&&i.jsxs("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textSecondary,flexShrink:0},children:["near ",i.jsxs("span",{style:{color:o.error},children:["“",s.near,"”"]})]})]}),i.jsx("pre",{style:{margin:0,fontFamily:o.fontMono,fontSize:12,color:o.error,lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:s.message}),a&&i.jsxs("div",{style:{fontSize:12,fontFamily:o.font,color:o.textSecondary,display:"flex",alignItems:"center",gap:6},children:[i.jsx("span",{style:{color:o.accent},children:"→"}),a]}),s.hint&&i.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:[i.jsx("span",{style:{flexShrink:0,fontSize:13,lineHeight:1.5},children:"💡"}),i.jsx("span",{style:{fontSize:12,fontFamily:o.font,color:o.warning,lineHeight:1.6},children:s.hint})]}),l&&i.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:E=>{E.currentTarget.style.background=`${o.accent}25`},onMouseLeave:E=>{E.currentTarget.style.background=`${o.accent}15`},children:[i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 vl({path:e,onNodeClick:t,focalNodeId:n,t:r}){return e.nodes.length===0?null:i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,alignItems:"center"},children:e.nodes.map((o,s)=>i.jsxs(me.Fragment,{children:[i.jsx(qx,{node:o,isFocal:o.id===n,onClick:t?()=>t(o.id):void 0,t:r}),s<e.nodes.length-1&&i.jsx("span",{style:{color:r.textMuted,fontSize:10,lineHeight:1},children:"→"})]},o.id))})}function pd({title:e,paths:t,onNodeClick:n,focalNodeId:r,maxVisible:o=4,t:s}){const[a,l]=me.useState(!1),E=a?t:t.slice(0,o),c=t.length>o;return t.length===0?null:i.jsxs("div",{style:{border:`1px solid ${s.cellBorder}`,borderRadius:10,overflow:"hidden",background:s.inputBg},children:[i.jsxs("div",{style:{padding:"8px 12px",borderBottom:`1px solid ${s.cellBorder}`,fontSize:11,fontWeight:700,color:s.textMuted,fontFamily:s.font,textTransform:"uppercase",letterSpacing:"0.04em",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i.jsx("span",{children:e}),i.jsxs("span",{style:{fontWeight:400,fontSize:10},children:[t.length," path",t.length!==1?"s":""]})]}),i.jsxs("div",{style:{display:"grid",gap:8,padding:10},children:[E.map((d,u)=>i.jsx(vl,{path:d,onNodeClick:n,focalNodeId:r,t:s},`path-${u}`)),c&&!a&&i.jsxs("button",{onClick:()=>l(!0),style:{background:"none",border:"none",color:s.accent,cursor:"pointer",fontSize:11,fontFamily:s.font,padding:"2px 0",textAlign:"left"},children:["Show ",t.length-o," more path",t.length-o!==1?"s":"","..."]})]})]})}function qx({node:e,isFocal:t,onClick:n,t:r}){const o=we[e.type]??"#8b949e",s=_c[e.type]??e.type.slice(0,3).toUpperCase();return i.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:[i.jsx("span",{style:{fontSize:8,fontWeight:700,color:"#0d1117",background:o,borderRadius:3,padding:"1px 3px",flexShrink:0},children:s}),i.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]})}function Qx({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"},s={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"};return i.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:i.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3},children:[i.jsx("span",{style:{width:8,height:8,borderRadius:2,background:o[a],display:"inline-block"}}),s[a],": ",l]},a)})})}function Le(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=Le(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var Zx={value:()=>{}};function Di(){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 Ns(n)}function Ns(e){this._=e}function ey(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}})}Ns.prototype=Di.prototype={constructor:Ns,on:function(e,t){var n=this._,r=ey(e+"",n),o,s=-1,a=r.length;if(arguments.length<2){for(;++s<a;)if((o=(e=r[s]).type)&&(o=ty(n[o],e.name)))return o;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++s<a;)if(o=(e=r[s]).type)n[o]=Id(n[o],e.name,t);else if(t==null)for(o in n)n[o]=Id(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 Ns(e)},call:function(e,t){if((o=arguments.length-2)>0)for(var n=new Array(o),r=0,o,s;r<o;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(s=this._[e],r=0,o=s.length;r<o;++r)s[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,s=r.length;o<s;++o)r[o].value.apply(t,n)}};function ty(e,t){for(var n=0,r=e.length,o;n<r;++n)if((o=e[n]).name===t)return o.value}function Id(e,t,n){for(var r=0,o=e.length;r<o;++r)if(e[r].name===t){e[r]=Zx,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Ul="http://www.w3.org/1999/xhtml";const Od={svg:"http://www.w3.org/2000/svg",xhtml:Ul,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Mi(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),Od.hasOwnProperty(t)?{space:Od[t],local:e}:e}function ny(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Ul&&t.documentElement.namespaceURI===Ul?t.createElement(e):t.createElementNS(n,e)}}function ry(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function of(e){var t=Mi(e);return(t.local?ry:ny)(t)}function oy(){}function Bc(e){return e==null?oy:function(){return this.querySelector(e)}}function sy(e){typeof e!="function"&&(e=Bc(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],a=s.length,l=r[o]=new Array(a),E,c,d=0;d<a;++d)(E=s[d])&&(c=e.call(E,E.__data__,d,s))&&("__data__"in E&&(c.__data__=E.__data__),l[d]=c);return new Ke(r,this._parents)}function iy(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function ay(){return[]}function sf(e){return e==null?ay:function(){return this.querySelectorAll(e)}}function ly(e){return function(){return iy(e.apply(this,arguments))}}function cy(e){typeof e=="function"?e=ly(e):e=sf(e);for(var t=this._groups,n=t.length,r=[],o=[],s=0;s<n;++s)for(var a=t[s],l=a.length,E,c=0;c<l;++c)(E=a[c])&&(r.push(e.call(E,E.__data__,c,a)),o.push(E));return new Ke(r,o)}function af(e){return function(){return this.matches(e)}}function lf(e){return function(t){return t.matches(e)}}var Ey=Array.prototype.find;function dy(e){return function(){return Ey.call(this.children,e)}}function uy(){return this.firstElementChild}function Ty(e){return this.select(e==null?uy:dy(typeof e=="function"?e:lf(e)))}var Sy=Array.prototype.filter;function Ry(){return Array.from(this.children)}function fy(e){return function(){return Sy.call(this.children,e)}}function Ay(e){return this.selectAll(e==null?Ry:fy(typeof e=="function"?e:lf(e)))}function py(e){typeof e!="function"&&(e=af(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],a=s.length,l=r[o]=[],E,c=0;c<a;++c)(E=s[c])&&e.call(E,E.__data__,c,s)&&l.push(E);return new Ke(r,this._parents)}function cf(e){return new Array(e.length)}function Iy(){return new Ke(this._enter||this._groups.map(cf),this._parents)}function Vs(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}Vs.prototype={constructor:Vs,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 Oy(e){return function(){return e}}function Ny(e,t,n,r,o,s){for(var a=0,l,E=t.length,c=s.length;a<c;++a)(l=t[a])?(l.__data__=s[a],r[a]=l):n[a]=new Vs(e,s[a]);for(;a<E;++a)(l=t[a])&&(o[a]=l)}function hy(e,t,n,r,o,s,a){var l,E,c=new Map,d=t.length,u=s.length,T=new Array(d),S;for(l=0;l<d;++l)(E=t[l])&&(T[l]=S=a.call(E,E.__data__,l,t)+"",c.has(S)?o[l]=E:c.set(S,E));for(l=0;l<u;++l)S=a.call(e,s[l],l,s)+"",(E=c.get(S))?(r[l]=E,E.__data__=s[l],c.delete(S)):n[l]=new Vs(e,s[l]);for(l=0;l<d;++l)(E=t[l])&&c.get(T[l])===E&&(o[l]=E)}function my(e){return e.__data__}function Cy(e,t){if(!arguments.length)return Array.from(this,my);var n=t?hy:Ny,r=this._parents,o=this._groups;typeof e!="function"&&(e=Oy(e));for(var s=o.length,a=new Array(s),l=new Array(s),E=new Array(s),c=0;c<s;++c){var d=r[c],u=o[c],T=u.length,S=gy(e.call(d,d&&d.__data__,c,r)),A=S.length,f=l[c]=new Array(A),I=a[c]=new Array(A),p=E[c]=new Array(T);n(d,u,f,I,p,S,t);for(var O=0,N=0,h,C;O<A;++O)if(h=f[O]){for(O>=N&&(N=O+1);!(C=I[N])&&++N<A;);h._next=C||null}}return a=new Ke(a,r),a._enter=l,a._exit=E,a}function gy(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function Ly(){return new Ke(this._exit||this._groups.map(cf),this._parents)}function _y(e,t,n){var r=this.enter(),o=this,s=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?s.remove():n(s),r&&o?r.merge(o).order():o}function xy(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,o=n.length,s=r.length,a=Math.min(o,s),l=new Array(o),E=0;E<a;++E)for(var c=n[E],d=r[E],u=c.length,T=l[E]=new Array(u),S,A=0;A<u;++A)(S=c[A]||d[A])&&(T[A]=S);for(;E<o;++E)l[E]=n[E];return new Ke(l,this._parents)}function yy(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],o=r.length-1,s=r[o],a;--o>=0;)(a=r[o])&&(s&&a.compareDocumentPosition(s)^4&&s.parentNode.insertBefore(a,s),s=a);return this}function Dy(e){e||(e=My);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),s=0;s<r;++s){for(var a=n[s],l=a.length,E=o[s]=new Array(l),c,d=0;d<l;++d)(c=a[d])&&(E[d]=c);E.sort(t)}return new Ke(o,this._parents).order()}function My(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function Py(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function by(){return Array.from(this)}function vy(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,s=r.length;o<s;++o){var a=r[o];if(a)return a}return null}function Uy(){let e=0;for(const t of this)++e;return e}function wy(){return!this.node()}function By(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var o=t[n],s=0,a=o.length,l;s<a;++s)(l=o[s])&&e.call(l,l.__data__,s,o);return this}function Fy(e){return function(){this.removeAttribute(e)}}function Gy(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Hy(e,t){return function(){this.setAttribute(e,t)}}function ky(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function Yy(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function jy(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 Wy(e,t){var n=Mi(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?Gy:Fy:typeof t=="function"?n.local?jy:Yy:n.local?ky:Hy)(n,t))}function Ef(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function Vy(e){return function(){this.style.removeProperty(e)}}function $y(e,t,n){return function(){this.style.setProperty(e,t,n)}}function Xy(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function Ky(e,t,n){return arguments.length>1?this.each((t==null?Vy:typeof t=="function"?Xy:$y)(e,t,n??"")):or(this.node(),e)}function or(e,t){return e.style.getPropertyValue(t)||Ef(e).getComputedStyle(e,null).getPropertyValue(t)}function zy(e){return function(){delete this[e]}}function Jy(e,t){return function(){this[e]=t}}function qy(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function Qy(e,t){return arguments.length>1?this.each((t==null?zy:typeof t=="function"?qy:Jy)(e,t)):this.node()[e]}function df(e){return e.trim().split(/^|\s+/)}function Fc(e){return e.classList||new uf(e)}function uf(e){this._node=e,this._names=df(e.getAttribute("class")||"")}uf.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 Tf(e,t){for(var n=Fc(e),r=-1,o=t.length;++r<o;)n.add(t[r])}function Sf(e,t){for(var n=Fc(e),r=-1,o=t.length;++r<o;)n.remove(t[r])}function Zy(e){return function(){Tf(this,e)}}function e0(e){return function(){Sf(this,e)}}function t0(e,t){return function(){(t.apply(this,arguments)?Tf:Sf)(this,e)}}function n0(e,t){var n=df(e+"");if(arguments.length<2){for(var r=Fc(this.node()),o=-1,s=n.length;++o<s;)if(!r.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?t0:t?Zy:e0)(n,t))}function r0(){this.textContent=""}function o0(e){return function(){this.textContent=e}}function s0(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function i0(e){return arguments.length?this.each(e==null?r0:(typeof e=="function"?s0:o0)(e)):this.node().textContent}function a0(){this.innerHTML=""}function l0(e){return function(){this.innerHTML=e}}function c0(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function E0(e){return arguments.length?this.each(e==null?a0:(typeof e=="function"?c0:l0)(e)):this.node().innerHTML}function d0(){this.nextSibling&&this.parentNode.appendChild(this)}function u0(){return this.each(d0)}function T0(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function S0(){return this.each(T0)}function R0(e){var t=typeof e=="function"?e:of(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function f0(){return null}function A0(e,t){var n=typeof e=="function"?e:of(e),r=t==null?f0:typeof t=="function"?t:Bc(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function p0(){var e=this.parentNode;e&&e.removeChild(this)}function I0(){return this.each(p0)}function O0(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function N0(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function h0(e){return this.select(e?N0:O0)}function m0(e){return arguments.length?this.property("__data__",e):this.node().__data__}function C0(e){return function(t){e.call(this,t,this.__data__)}}function g0(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 L0(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,o=t.length,s;n<o;++n)s=t[n],(!e.type||s.type===e.type)&&s.name===e.name?this.removeEventListener(s.type,s.listener,s.options):t[++r]=s;++r?t.length=r:delete this.__on}}}function _0(e,t,n){return function(){var r=this.__on,o,s=C0(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=s,o.options=n),o.value=t;return}}this.addEventListener(e.type,s,n),o={type:e.type,name:e.name,value:t,listener:s,options:n},r?r.push(o):this.__on=[o]}}function x0(e,t,n){var r=g0(e+""),o,s=r.length,a;if(arguments.length<2){var l=this.node().__on;if(l){for(var E=0,c=l.length,d;E<c;++E)for(o=0,d=l[E];o<s;++o)if((a=r[o]).type===d.type&&a.name===d.name)return d.value}return}for(l=t?_0:L0,o=0;o<s;++o)this.each(l(r[o],t,n));return this}function Rf(e,t,n){var r=Ef(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 y0(e,t){return function(){return Rf(this,e,t)}}function D0(e,t){return function(){return Rf(this,e,t.apply(this,arguments))}}function M0(e,t){return this.each((typeof t=="function"?D0:y0)(e,t))}function*P0(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,s=r.length,a;o<s;++o)(a=r[o])&&(yield a)}var ff=[null];function Ke(e,t){this._groups=e,this._parents=t}function So(){return new Ke([[document.documentElement]],ff)}function b0(){return this}Ke.prototype=So.prototype={constructor:Ke,select:sy,selectAll:cy,selectChild:Ty,selectChildren:Ay,filter:py,data:Cy,enter:Iy,exit:Ly,join:_y,merge:xy,selection:b0,order:yy,sort:Dy,call:Py,nodes:by,node:vy,size:Uy,empty:wy,each:By,attr:Wy,style:Ky,property:Qy,classed:n0,text:i0,html:E0,raise:u0,lower:S0,append:R0,insert:A0,remove:I0,clone:h0,datum:m0,on:x0,dispatch:M0,[Symbol.iterator]:P0};function $e(e){return typeof e=="string"?new Ke([[document.querySelector(e)]],[document.documentElement]):new Ke([[e]],ff)}function v0(e){let t;for(;t=e.sourceEvent;)e=t;return e}function tt(e,t){if(e=v0(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 U0={passive:!1},Jr={capture:!0,passive:!1};function Ca(e){e.stopImmediatePropagation()}function qn(e){e.preventDefault(),e.stopImmediatePropagation()}function Af(e){var t=e.document.documentElement,n=$e(e).on("dragstart.drag",qn,Jr);"onselectstart"in t?n.on("selectstart.drag",qn,Jr):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function pf(e,t){var n=e.document.documentElement,r=$e(e).on("dragstart.drag",null);t&&(r.on("click.drag",qn,Jr),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 rs=e=>()=>e;function wl(e,{sourceEvent:t,subject:n,target:r,identifier:o,active:s,x:a,y:l,dx:E,dy:c,dispatch:d}){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:s,enumerable:!0,configurable:!0},x:{value:a,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:E,enumerable:!0,configurable:!0},dy:{value:c,enumerable:!0,configurable:!0},_:{value:d}})}wl.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function w0(e){return!e.ctrlKey&&!e.button}function B0(){return this.parentNode}function F0(e,t){return t??{x:e.x,y:e.y}}function G0(){return navigator.maxTouchPoints||"ontouchstart"in this}function If(){var e=w0,t=B0,n=F0,r=G0,o={},s=Di("start","drag","end"),a=0,l,E,c,d,u=0;function T(h){h.on("mousedown.drag",S).filter(r).on("touchstart.drag",I).on("touchmove.drag",p,U0).on("touchend.drag touchcancel.drag",O).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function S(h,C){if(!(d||!e.call(this,h,C))){var m=N(this,t.call(this,h,C),h,C,"mouse");m&&($e(h.view).on("mousemove.drag",A,Jr).on("mouseup.drag",f,Jr),Af(h.view),Ca(h),c=!1,l=h.clientX,E=h.clientY,m("start",h))}}function A(h){if(qn(h),!c){var C=h.clientX-l,m=h.clientY-E;c=C*C+m*m>u}o.mouse("drag",h)}function f(h){$e(h.view).on("mousemove.drag mouseup.drag",null),pf(h.view,c),qn(h),o.mouse("end",h)}function I(h,C){if(e.call(this,h,C)){var m=h.changedTouches,g=t.call(this,h,C),y=m.length,_,U;for(_=0;_<y;++_)(U=N(this,g,h,C,m[_].identifier,m[_]))&&(Ca(h),U("start",h,m[_]))}}function p(h){var C=h.changedTouches,m=C.length,g,y;for(g=0;g<m;++g)(y=o[C[g].identifier])&&(qn(h),y("drag",h,C[g]))}function O(h){var C=h.changedTouches,m=C.length,g,y;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),g=0;g<m;++g)(y=o[C[g].identifier])&&(Ca(h),y("end",h,C[g]))}function N(h,C,m,g,y,_){var U=s.copy(),D=tt(_||m,C),b,F,L;if((L=n.call(h,new wl("beforestart",{sourceEvent:m,target:T,identifier:y,active:a,x:D[0],y:D[1],dx:0,dy:0,dispatch:U}),g))!=null)return b=L.x-D[0]||0,F=L.y-D[1]||0,function P(M,w,v){var x=D,B;switch(M){case"start":o[y]=P,B=a++;break;case"end":delete o[y],--a;case"drag":D=tt(v||w,C),B=a;break}U.call(M,h,new wl(M,{sourceEvent:w,subject:L,target:T,identifier:y,active:B,x:D[0]+b,y:D[1]+F,dx:D[0]-x[0],dy:D[1]-x[1],dispatch:U}),g)}}return T.filter=function(h){return arguments.length?(e=typeof h=="function"?h:rs(!!h),T):e},T.container=function(h){return arguments.length?(t=typeof h=="function"?h:rs(h),T):t},T.subject=function(h){return arguments.length?(n=typeof h=="function"?h:rs(h),T):n},T.touchable=function(h){return arguments.length?(r=typeof h=="function"?h:rs(!!h),T):r},T.on=function(){var h=s.on.apply(s,arguments);return h===s?T:h},T.clickDistance=function(h){return arguments.length?(u=(h=+h)*h,T):Math.sqrt(u)},T}function Gc(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function Of(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Ro(){}var qr=.7,$s=1/qr,Qn="\\s*([+-]?\\d+)\\s*",Qr="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",It="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",H0=/^#([0-9a-f]{3,8})$/,k0=new RegExp(`^rgb\\(${Qn},${Qn},${Qn}\\)$`),Y0=new RegExp(`^rgb\\(${It},${It},${It}\\)$`),j0=new RegExp(`^rgba\\(${Qn},${Qn},${Qn},${Qr}\\)$`),W0=new RegExp(`^rgba\\(${It},${It},${It},${Qr}\\)$`),V0=new RegExp(`^hsl\\(${Qr},${It},${It}\\)$`),$0=new RegExp(`^hsla\\(${Qr},${It},${It},${Qr}\\)$`),Nd={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};Gc(Ro,In,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:hd,formatHex:hd,formatHex8:X0,formatHsl:K0,formatRgb:md,toString:md});function hd(){return this.rgb().formatHex()}function X0(){return this.rgb().formatHex8()}function K0(){return Nf(this).formatHsl()}function md(){return this.rgb().formatRgb()}function In(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=H0.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Cd(t):n===3?new Fe(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?os(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?os(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=k0.exec(e))?new Fe(t[1],t[2],t[3],1):(t=Y0.exec(e))?new Fe(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=j0.exec(e))?os(t[1],t[2],t[3],t[4]):(t=W0.exec(e))?os(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=V0.exec(e))?_d(t[1],t[2]/100,t[3]/100,1):(t=$0.exec(e))?_d(t[1],t[2]/100,t[3]/100,t[4]):Nd.hasOwnProperty(e)?Cd(Nd[e]):e==="transparent"?new Fe(NaN,NaN,NaN,0):null}function Cd(e){return new Fe(e>>16&255,e>>8&255,e&255,1)}function os(e,t,n,r){return r<=0&&(e=t=n=NaN),new Fe(e,t,n,r)}function z0(e){return e instanceof Ro||(e=In(e)),e?(e=e.rgb(),new Fe(e.r,e.g,e.b,e.opacity)):new Fe}function Bl(e,t,n,r){return arguments.length===1?z0(e):new Fe(e,t,n,r??1)}function Fe(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Gc(Fe,Bl,Of(Ro,{brighter(e){return e=e==null?$s:Math.pow($s,e),new Fe(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?qr:Math.pow(qr,e),new Fe(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Fe(Sn(this.r),Sn(this.g),Sn(this.b),Xs(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:gd,formatHex:gd,formatHex8:J0,formatRgb:Ld,toString:Ld}));function gd(){return`#${Tn(this.r)}${Tn(this.g)}${Tn(this.b)}`}function J0(){return`#${Tn(this.r)}${Tn(this.g)}${Tn(this.b)}${Tn((isNaN(this.opacity)?1:this.opacity)*255)}`}function Ld(){const e=Xs(this.opacity);return`${e===1?"rgb(":"rgba("}${Sn(this.r)}, ${Sn(this.g)}, ${Sn(this.b)}${e===1?")":`, ${e})`}`}function Xs(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Sn(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Tn(e){return e=Sn(e),(e<16?"0":"")+e.toString(16)}function _d(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new nt(e,t,n,r)}function Nf(e){if(e instanceof nt)return new nt(e.h,e.s,e.l,e.opacity);if(e instanceof Ro||(e=In(e)),!e)return new nt;if(e instanceof nt)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,o=Math.min(t,n,r),s=Math.max(t,n,r),a=NaN,l=s-o,E=(s+o)/2;return l?(t===s?a=(n-r)/l+(n<r)*6:n===s?a=(r-t)/l+2:a=(t-n)/l+4,l/=E<.5?s+o:2-s-o,a*=60):l=E>0&&E<1?0:a,new nt(a,l,E,e.opacity)}function q0(e,t,n,r){return arguments.length===1?Nf(e):new nt(e,t,n,r??1)}function nt(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Gc(nt,q0,Of(Ro,{brighter(e){return e=e==null?$s:Math.pow($s,e),new nt(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?qr:Math.pow(qr,e),new nt(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 Fe(ga(e>=240?e-240:e+120,o,r),ga(e,o,r),ga(e<120?e+240:e-120,o,r),this.opacity)},clamp(){return new nt(xd(this.h),ss(this.s),ss(this.l),Xs(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=Xs(this.opacity);return`${e===1?"hsl(":"hsla("}${xd(this.h)}, ${ss(this.s)*100}%, ${ss(this.l)*100}%${e===1?")":`, ${e})`}`}}));function xd(e){return e=(e||0)%360,e<0?e+360:e}function ss(e){return Math.max(0,Math.min(1,e||0))}function ga(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 Hc=e=>()=>e;function Q0(e,t){return function(n){return e+n*t}}function Z0(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 eD(e){return(e=+e)==1?hf:function(t,n){return n-t?Z0(t,n,e):Hc(isNaN(t)?n:t)}}function hf(e,t){var n=t-e;return n?Q0(e,n):Hc(isNaN(e)?t:e)}const Ks=(function e(t){var n=eD(t);function r(o,s){var a=n((o=Bl(o)).r,(s=Bl(s)).r),l=n(o.g,s.g),E=n(o.b,s.b),c=hf(o.opacity,s.opacity);return function(d){return o.r=a(d),o.g=l(d),o.b=E(d),o.opacity=c(d),o+""}}return r.gamma=e,r})(1);function tD(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),o;return function(s){for(o=0;o<n;++o)r[o]=e[o]*(1-s)+t[o]*s;return r}}function nD(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function rD(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,o=new Array(r),s=new Array(n),a;for(a=0;a<r;++a)o[a]=Fr(e[a],t[a]);for(;a<n;++a)s[a]=t[a];return function(l){for(a=0;a<r;++a)s[a]=o[a](l);return s}}function oD(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function St(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function sD(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]=Fr(e[o],t[o]):r[o]=t[o];return function(s){for(o in n)r[o]=n[o](s);return r}}var Fl=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,La=new RegExp(Fl.source,"g");function iD(e){return function(){return e}}function aD(e){return function(t){return e(t)+""}}function mf(e,t){var n=Fl.lastIndex=La.lastIndex=0,r,o,s,a=-1,l=[],E=[];for(e=e+"",t=t+"";(r=Fl.exec(e))&&(o=La.exec(t));)(s=o.index)>n&&(s=t.slice(n,s),l[a]?l[a]+=s:l[++a]=s),(r=r[0])===(o=o[0])?l[a]?l[a]+=o:l[++a]=o:(l[++a]=null,E.push({i:a,x:St(r,o)})),n=La.lastIndex;return n<t.length&&(s=t.slice(n),l[a]?l[a]+=s:l[++a]=s),l.length<2?E[0]?aD(E[0].x):iD(t):(t=E.length,function(c){for(var d=0,u;d<t;++d)l[(u=E[d]).i]=u.x(c);return l.join("")})}function Fr(e,t){var n=typeof t,r;return t==null||n==="boolean"?Hc(t):(n==="number"?St:n==="string"?(r=In(t))?(t=r,Ks):mf:t instanceof In?Ks:t instanceof Date?oD:nD(t)?tD:Array.isArray(t)?rD:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?sD:St)(e,t)}var yd=180/Math.PI,Gl={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Cf(e,t,n,r,o,s){var a,l,E;return(a=Math.sqrt(e*e+t*t))&&(e/=a,t/=a),(E=e*n+t*r)&&(n-=e*E,r-=t*E),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,E/=l),e*r<t*n&&(e=-e,t=-t,E=-E,a=-a),{translateX:o,translateY:s,rotate:Math.atan2(t,e)*yd,skewX:Math.atan(E)*yd,scaleX:a,scaleY:l}}var is;function lD(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Gl:Cf(t.a,t.b,t.c,t.d,t.e,t.f)}function cD(e){return e==null||(is||(is=document.createElementNS("http://www.w3.org/2000/svg","g")),is.setAttribute("transform",e),!(e=is.transform.baseVal.consolidate()))?Gl:(e=e.matrix,Cf(e.a,e.b,e.c,e.d,e.e,e.f))}function gf(e,t,n,r){function o(c){return c.length?c.pop()+" ":""}function s(c,d,u,T,S,A){if(c!==u||d!==T){var f=S.push("translate(",null,t,null,n);A.push({i:f-4,x:St(c,u)},{i:f-2,x:St(d,T)})}else(u||T)&&S.push("translate("+u+t+T+n)}function a(c,d,u,T){c!==d?(c-d>180?d+=360:d-c>180&&(c+=360),T.push({i:u.push(o(u)+"rotate(",null,r)-2,x:St(c,d)})):d&&u.push(o(u)+"rotate("+d+r)}function l(c,d,u,T){c!==d?T.push({i:u.push(o(u)+"skewX(",null,r)-2,x:St(c,d)}):d&&u.push(o(u)+"skewX("+d+r)}function E(c,d,u,T,S,A){if(c!==u||d!==T){var f=S.push(o(S)+"scale(",null,",",null,")");A.push({i:f-4,x:St(c,u)},{i:f-2,x:St(d,T)})}else(u!==1||T!==1)&&S.push(o(S)+"scale("+u+","+T+")")}return function(c,d){var u=[],T=[];return c=e(c),d=e(d),s(c.translateX,c.translateY,d.translateX,d.translateY,u,T),a(c.rotate,d.rotate,u,T),l(c.skewX,d.skewX,u,T),E(c.scaleX,c.scaleY,d.scaleX,d.scaleY,u,T),c=d=null,function(S){for(var A=-1,f=T.length,I;++A<f;)u[(I=T[A]).i]=I.x(S);return u.join("")}}}var ED=gf(lD,"px, ","px)","deg)"),dD=gf(cD,", ",")",")"),uD=1e-12;function Dd(e){return((e=Math.exp(e))+1/e)/2}function TD(e){return((e=Math.exp(e))-1/e)/2}function SD(e){return((e=Math.exp(2*e))-1)/(e+1)}const hs=(function e(t,n,r){function o(s,a){var l=s[0],E=s[1],c=s[2],d=a[0],u=a[1],T=a[2],S=d-l,A=u-E,f=S*S+A*A,I,p;if(f<uD)p=Math.log(T/c)/t,I=function(g){return[l+g*S,E+g*A,c*Math.exp(t*g*p)]};else{var O=Math.sqrt(f),N=(T*T-c*c+r*f)/(2*c*n*O),h=(T*T-c*c-r*f)/(2*T*n*O),C=Math.log(Math.sqrt(N*N+1)-N),m=Math.log(Math.sqrt(h*h+1)-h);p=(m-C)/t,I=function(g){var y=g*p,_=Dd(C),U=c/(n*O)*(_*SD(t*y+C)-TD(C));return[l+U*S,E+U*A,c*_/Dd(t*y+C)]}}return I.duration=p*1e3*t/Math.SQRT2,I}return o.rho=function(s){var a=Math.max(.001,+s),l=a*a,E=l*l;return e(a,l,E)},o})(Math.SQRT2,2,4);var sr=0,br=0,yr=0,Lf=1e3,zs,vr,Js=0,On=0,Pi=0,Zr=typeof performance=="object"&&performance.now?performance:Date,_f=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function kc(){return On||(_f(RD),On=Zr.now()+Pi)}function RD(){On=0}function qs(){this._call=this._time=this._next=null}qs.prototype=xf.prototype={constructor:qs,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?kc():+n)+(t==null?0:+t),!this._next&&vr!==this&&(vr?vr._next=this:zs=this,vr=this),this._call=e,this._time=n,Hl()},stop:function(){this._call&&(this._call=null,this._time=1/0,Hl())}};function xf(e,t,n){var r=new qs;return r.restart(e,t,n),r}function fD(){kc(),++sr;for(var e=zs,t;e;)(t=On-e._time)>=0&&e._call.call(void 0,t),e=e._next;--sr}function Md(){On=(Js=Zr.now())+Pi,sr=br=0;try{fD()}finally{sr=0,pD(),On=0}}function AD(){var e=Zr.now(),t=e-Js;t>Lf&&(Pi-=t,Js=e)}function pD(){for(var e,t=zs,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:zs=n);vr=e,Hl(r)}function Hl(e){if(!sr){br&&(br=clearTimeout(br));var t=e-On;t>24?(e<1/0&&(br=setTimeout(Md,e-Zr.now()-Pi)),yr&&(yr=clearInterval(yr))):(yr||(Js=Zr.now(),yr=setInterval(AD,Lf)),sr=1,_f(Md))}}function Pd(e,t,n){var r=new qs;return t=t==null?0:+t,r.restart(o=>{r.stop(),e(o+t)},t,n),r}var ID=Di("start","end","cancel","interrupt"),OD=[],yf=0,bd=1,kl=2,ms=3,vd=4,Yl=5,Cs=6;function bi(e,t,n,r,o,s){var a=e.__transition;if(!a)e.__transition={};else if(n in a)return;ND(e,n,{name:t,index:r,group:o,on:ID,tween:OD,time:s.time,delay:s.delay,duration:s.duration,ease:s.ease,timer:null,state:yf})}function Yc(e,t){var n=Et(e,t);if(n.state>yf)throw new Error("too late; already scheduled");return n}function ht(e,t){var n=Et(e,t);if(n.state>ms)throw new Error("too late; already running");return n}function Et(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function ND(e,t,n){var r=e.__transition,o;r[t]=n,n.timer=xf(s,0,n.time);function s(c){n.state=bd,n.timer.restart(a,n.delay,n.time),n.delay<=c&&a(c-n.delay)}function a(c){var d,u,T,S;if(n.state!==bd)return E();for(d in r)if(S=r[d],S.name===n.name){if(S.state===ms)return Pd(a);S.state===vd?(S.state=Cs,S.timer.stop(),S.on.call("interrupt",e,e.__data__,S.index,S.group),delete r[d]):+d<t&&(S.state=Cs,S.timer.stop(),S.on.call("cancel",e,e.__data__,S.index,S.group),delete r[d])}if(Pd(function(){n.state===ms&&(n.state=vd,n.timer.restart(l,n.delay,n.time),l(c))}),n.state=kl,n.on.call("start",e,e.__data__,n.index,n.group),n.state===kl){for(n.state=ms,o=new Array(T=n.tween.length),d=0,u=-1;d<T;++d)(S=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(o[++u]=S);o.length=u+1}}function l(c){for(var d=c<n.duration?n.ease.call(null,c/n.duration):(n.timer.restart(E),n.state=Yl,1),u=-1,T=o.length;++u<T;)o[u].call(e,d);n.state===Yl&&(n.on.call("end",e,e.__data__,n.index,n.group),E())}function E(){n.state=Cs,n.timer.stop(),delete r[t];for(var c in r)return;delete e.__transition}}function gs(e,t){var n=e.__transition,r,o,s=!0,a;if(n){t=t==null?null:t+"";for(a in n){if((r=n[a]).name!==t){s=!1;continue}o=r.state>kl&&r.state<Yl,r.state=Cs,r.timer.stop(),r.on.call(o?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[a]}s&&delete e.__transition}}function hD(e){return this.each(function(){gs(this,e)})}function mD(e,t){var n,r;return function(){var o=ht(this,e),s=o.tween;if(s!==n){r=n=s;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 CD(e,t,n){var r,o;if(typeof n!="function")throw new Error;return function(){var s=ht(this,e),a=s.tween;if(a!==r){o=(r=a).slice();for(var l={name:t,value:n},E=0,c=o.length;E<c;++E)if(o[E].name===t){o[E]=l;break}E===c&&o.push(l)}s.tween=o}}function gD(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Et(this.node(),n).tween,o=0,s=r.length,a;o<s;++o)if((a=r[o]).name===e)return a.value;return null}return this.each((t==null?mD:CD)(n,e,t))}function jc(e,t,n){var r=e._id;return e.each(function(){var o=ht(this,r);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return Et(o,r).value[t]}}function Df(e,t){var n;return(typeof t=="number"?St:t instanceof In?Ks:(n=In(t))?(t=n,Ks):mf)(e,t)}function LD(e){return function(){this.removeAttribute(e)}}function _D(e){return function(){this.removeAttributeNS(e.space,e.local)}}function xD(e,t,n){var r,o=n+"",s;return function(){var a=this.getAttribute(e);return a===o?null:a===r?s:s=t(r=a,n)}}function yD(e,t,n){var r,o=n+"",s;return function(){var a=this.getAttributeNS(e.space,e.local);return a===o?null:a===r?s:s=t(r=a,n)}}function DD(e,t,n){var r,o,s;return function(){var a,l=n(this),E;return l==null?void this.removeAttribute(e):(a=this.getAttribute(e),E=l+"",a===E?null:a===r&&E===o?s:(o=E,s=t(r=a,l)))}}function MD(e,t,n){var r,o,s;return function(){var a,l=n(this),E;return l==null?void this.removeAttributeNS(e.space,e.local):(a=this.getAttributeNS(e.space,e.local),E=l+"",a===E?null:a===r&&E===o?s:(o=E,s=t(r=a,l)))}}function PD(e,t){var n=Mi(e),r=n==="transform"?dD:Df;return this.attrTween(e,typeof t=="function"?(n.local?MD:DD)(n,r,jc(this,"attr."+e,t)):t==null?(n.local?_D:LD)(n):(n.local?yD:xD)(n,r,t))}function bD(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function vD(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function UD(e,t){var n,r;function o(){var s=t.apply(this,arguments);return s!==r&&(n=(r=s)&&vD(e,s)),n}return o._value=t,o}function wD(e,t){var n,r;function o(){var s=t.apply(this,arguments);return s!==r&&(n=(r=s)&&bD(e,s)),n}return o._value=t,o}function BD(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=Mi(e);return this.tween(n,(r.local?UD:wD)(r,t))}function FD(e,t){return function(){Yc(this,e).delay=+t.apply(this,arguments)}}function GD(e,t){return t=+t,function(){Yc(this,e).delay=t}}function HD(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?FD:GD)(t,e)):Et(this.node(),t).delay}function kD(e,t){return function(){ht(this,e).duration=+t.apply(this,arguments)}}function YD(e,t){return t=+t,function(){ht(this,e).duration=t}}function jD(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?kD:YD)(t,e)):Et(this.node(),t).duration}function WD(e,t){if(typeof t!="function")throw new Error;return function(){ht(this,e).ease=t}}function VD(e){var t=this._id;return arguments.length?this.each(WD(t,e)):Et(this.node(),t).ease}function $D(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;ht(this,e).ease=n}}function XD(e){if(typeof e!="function")throw new Error;return this.each($D(this._id,e))}function KD(e){typeof e!="function"&&(e=af(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],a=s.length,l=r[o]=[],E,c=0;c<a;++c)(E=s[c])&&e.call(E,E.__data__,c,s)&&l.push(E);return new vt(r,this._parents,this._name,this._id)}function zD(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,o=n.length,s=Math.min(r,o),a=new Array(r),l=0;l<s;++l)for(var E=t[l],c=n[l],d=E.length,u=a[l]=new Array(d),T,S=0;S<d;++S)(T=E[S]||c[S])&&(u[S]=T);for(;l<r;++l)a[l]=t[l];return new vt(a,this._parents,this._name,this._id)}function JD(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 qD(e,t,n){var r,o,s=JD(t)?Yc:ht;return function(){var a=s(this,e),l=a.on;l!==r&&(o=(r=l).copy()).on(t,n),a.on=o}}function QD(e,t){var n=this._id;return arguments.length<2?Et(this.node(),n).on.on(e):this.each(qD(n,e,t))}function ZD(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function eM(){return this.on("end.remove",ZD(this._id))}function tM(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Bc(e));for(var r=this._groups,o=r.length,s=new Array(o),a=0;a<o;++a)for(var l=r[a],E=l.length,c=s[a]=new Array(E),d,u,T=0;T<E;++T)(d=l[T])&&(u=e.call(d,d.__data__,T,l))&&("__data__"in d&&(u.__data__=d.__data__),c[T]=u,bi(c[T],t,n,T,c,Et(d,n)));return new vt(s,this._parents,t,n)}function nM(e){var t=this._name,n=this._id;typeof e!="function"&&(e=sf(e));for(var r=this._groups,o=r.length,s=[],a=[],l=0;l<o;++l)for(var E=r[l],c=E.length,d,u=0;u<c;++u)if(d=E[u]){for(var T=e.call(d,d.__data__,u,E),S,A=Et(d,n),f=0,I=T.length;f<I;++f)(S=T[f])&&bi(S,t,n,f,T,A);s.push(T),a.push(d)}return new vt(s,a,t,n)}var rM=So.prototype.constructor;function oM(){return new rM(this._groups,this._parents)}function sM(e,t){var n,r,o;return function(){var s=or(this,e),a=(this.style.removeProperty(e),or(this,e));return s===a?null:s===n&&a===r?o:o=t(n=s,r=a)}}function Mf(e){return function(){this.style.removeProperty(e)}}function iM(e,t,n){var r,o=n+"",s;return function(){var a=or(this,e);return a===o?null:a===r?s:s=t(r=a,n)}}function aM(e,t,n){var r,o,s;return function(){var a=or(this,e),l=n(this),E=l+"";return l==null&&(E=l=(this.style.removeProperty(e),or(this,e))),a===E?null:a===r&&E===o?s:(o=E,s=t(r=a,l))}}function lM(e,t){var n,r,o,s="style."+t,a="end."+s,l;return function(){var E=ht(this,e),c=E.on,d=E.value[s]==null?l||(l=Mf(t)):void 0;(c!==n||o!==d)&&(r=(n=c).copy()).on(a,o=d),E.on=r}}function cM(e,t,n){var r=(e+="")=="transform"?ED:Df;return t==null?this.styleTween(e,sM(e,r)).on("end.style."+e,Mf(e)):typeof t=="function"?this.styleTween(e,aM(e,r,jc(this,"style."+e,t))).each(lM(this._id,e)):this.styleTween(e,iM(e,r,t),n).on("end.style."+e,null)}function EM(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function dM(e,t,n){var r,o;function s(){var a=t.apply(this,arguments);return a!==o&&(r=(o=a)&&EM(e,a,n)),r}return s._value=t,s}function uM(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,dM(e,t,n??""))}function TM(e){return function(){this.textContent=e}}function SM(e){return function(){var t=e(this);this.textContent=t??""}}function RM(e){return this.tween("text",typeof e=="function"?SM(jc(this,"text",e)):TM(e==null?"":e+""))}function fM(e){return function(t){this.textContent=e.call(this,t)}}function AM(e){var t,n;function r(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&fM(o)),t}return r._value=e,r}function pM(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,AM(e))}function IM(){for(var e=this._name,t=this._id,n=Pf(),r=this._groups,o=r.length,s=0;s<o;++s)for(var a=r[s],l=a.length,E,c=0;c<l;++c)if(E=a[c]){var d=Et(E,t);bi(E,e,n,c,a,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new vt(r,this._parents,e,n)}function OM(){var e,t,n=this,r=n._id,o=n.size();return new Promise(function(s,a){var l={value:a},E={value:function(){--o===0&&s()}};n.each(function(){var c=ht(this,r),d=c.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(E)),c.on=t}),o===0&&s()})}var NM=0;function vt(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Pf(){return++NM}var _t=So.prototype;vt.prototype={constructor:vt,select:tM,selectAll:nM,selectChild:_t.selectChild,selectChildren:_t.selectChildren,filter:KD,merge:zD,selection:oM,transition:IM,call:_t.call,nodes:_t.nodes,node:_t.node,size:_t.size,empty:_t.empty,each:_t.each,on:QD,attr:PD,attrTween:BD,style:cM,styleTween:uM,text:RM,textTween:pM,remove:eM,tween:gD,delay:HD,duration:jD,ease:VD,easeVarying:XD,end:OM,[Symbol.iterator]:_t[Symbol.iterator]};function hM(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var mM={time:null,delay:0,duration:250,ease:hM};function CM(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 gM(e){var t,n;e instanceof vt?(t=e._id,e=e._name):(t=Pf(),(n=mM).time=kc(),e=e==null?null:e+"");for(var r=this._groups,o=r.length,s=0;s<o;++s)for(var a=r[s],l=a.length,E,c=0;c<l;++c)(E=a[c])&&bi(E,e,t,c,a,n||CM(E,t));return new vt(r,this._parents,e,t)}So.prototype.interrupt=hD;So.prototype.transition=gM;const as=e=>()=>e;function LM(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 Dt(e,t,n){this.k=e,this.x=t,this.y=n}Dt.prototype={constructor:Dt,scale:function(e){return e===1?this:new Dt(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Dt(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 vi=new Dt(1,0,0);bf.prototype=Dt.prototype;function bf(e){for(;!e.__zoom;)if(!(e=e.parentNode))return vi;return e.__zoom}function _a(e){e.stopImmediatePropagation()}function Dr(e){e.preventDefault(),e.stopImmediatePropagation()}function _M(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function xM(){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 Ud(){return this.__zoom||vi}function yM(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function DM(){return navigator.maxTouchPoints||"ontouchstart"in this}function MM(e,t,n){var r=e.invertX(t[0][0])-n[0][0],o=e.invertX(t[1][0])-n[1][0],s=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>s?(s+a)/2:Math.min(0,s)||Math.max(0,a))}function vf(){var e=_M,t=xM,n=MM,r=yM,o=DM,s=[0,1/0],a=[[-1/0,-1/0],[1/0,1/0]],l=250,E=hs,c=Di("start","zoom","end"),d,u,T,S=500,A=150,f=0,I=10;function p(L){L.property("__zoom",Ud).on("wheel.zoom",y,{passive:!1}).on("mousedown.zoom",_).on("dblclick.zoom",U).filter(o).on("touchstart.zoom",D).on("touchmove.zoom",b).on("touchend.zoom touchcancel.zoom",F).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}p.transform=function(L,P,M,w){var v=L.selection?L.selection():L;v.property("__zoom",Ud),L!==v?C(L,P,M,w):v.interrupt().each(function(){m(this,arguments).event(w).start().zoom(null,typeof P=="function"?P.apply(this,arguments):P).end()})},p.scaleBy=function(L,P,M,w){p.scaleTo(L,function(){var v=this.__zoom.k,x=typeof P=="function"?P.apply(this,arguments):P;return v*x},M,w)},p.scaleTo=function(L,P,M,w){p.transform(L,function(){var v=t.apply(this,arguments),x=this.__zoom,B=M==null?h(v):typeof M=="function"?M.apply(this,arguments):M,H=x.invert(B),Y=typeof P=="function"?P.apply(this,arguments):P;return n(N(O(x,Y),B,H),v,a)},M,w)},p.translateBy=function(L,P,M,w){p.transform(L,function(){return n(this.__zoom.translate(typeof P=="function"?P.apply(this,arguments):P,typeof M=="function"?M.apply(this,arguments):M),t.apply(this,arguments),a)},null,w)},p.translateTo=function(L,P,M,w,v){p.transform(L,function(){var x=t.apply(this,arguments),B=this.__zoom,H=w==null?h(x):typeof w=="function"?w.apply(this,arguments):w;return n(vi.translate(H[0],H[1]).scale(B.k).translate(typeof P=="function"?-P.apply(this,arguments):-P,typeof M=="function"?-M.apply(this,arguments):-M),x,a)},w,v)};function O(L,P){return P=Math.max(s[0],Math.min(s[1],P)),P===L.k?L:new Dt(P,L.x,L.y)}function N(L,P,M){var w=P[0]-M[0]*L.k,v=P[1]-M[1]*L.k;return w===L.x&&v===L.y?L:new Dt(L.k,w,v)}function h(L){return[(+L[0][0]+ +L[1][0])/2,(+L[0][1]+ +L[1][1])/2]}function C(L,P,M,w){L.on("start.zoom",function(){m(this,arguments).event(w).start()}).on("interrupt.zoom end.zoom",function(){m(this,arguments).event(w).end()}).tween("zoom",function(){var v=this,x=arguments,B=m(v,x).event(w),H=t.apply(v,x),Y=M==null?h(H):typeof M=="function"?M.apply(v,x):M,K=Math.max(H[1][0]-H[0][0],H[1][1]-H[0][1]),X=v.__zoom,q=typeof P=="function"?P.apply(v,x):P,ee=E(X.invert(Y).concat(K/X.k),q.invert(Y).concat(K/q.k));return function(Z){if(Z===1)Z=q;else{var $=ee(Z),z=K/$[2];Z=new Dt(z,Y[0]-$[0]*z,Y[1]-$[1]*z)}B.zoom(null,Z)}})}function m(L,P,M){return!M&&L.__zooming||new g(L,P)}function g(L,P){this.that=L,this.args=P,this.active=0,this.sourceEvent=null,this.extent=t.apply(L,P),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,P){return this.mouse&&L!=="mouse"&&(this.mouse[1]=P.invert(this.mouse[0])),this.touch0&&L!=="touch"&&(this.touch0[1]=P.invert(this.touch0[0])),this.touch1&&L!=="touch"&&(this.touch1[1]=P.invert(this.touch1[0])),this.that.__zoom=P,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(L){var P=$e(this.that).datum();c.call(L,this.that,new LM(L,{sourceEvent:this.sourceEvent,target:p,transform:this.that.__zoom,dispatch:c}),P)}};function y(L,...P){if(!e.apply(this,arguments))return;var M=m(this,P).event(L),w=this.__zoom,v=Math.max(s[0],Math.min(s[1],w.k*Math.pow(2,r.apply(this,arguments)))),x=tt(L);if(M.wheel)(M.mouse[0][0]!==x[0]||M.mouse[0][1]!==x[1])&&(M.mouse[1]=w.invert(M.mouse[0]=x)),clearTimeout(M.wheel);else{if(w.k===v)return;M.mouse=[x,w.invert(x)],gs(this),M.start()}Dr(L),M.wheel=setTimeout(B,A),M.zoom("mouse",n(N(O(w,v),M.mouse[0],M.mouse[1]),M.extent,a));function B(){M.wheel=null,M.end()}}function _(L,...P){if(T||!e.apply(this,arguments))return;var M=L.currentTarget,w=m(this,P,!0).event(L),v=$e(L.view).on("mousemove.zoom",Y,!0).on("mouseup.zoom",K,!0),x=tt(L,M),B=L.clientX,H=L.clientY;Af(L.view),_a(L),w.mouse=[x,this.__zoom.invert(x)],gs(this),w.start();function Y(X){if(Dr(X),!w.moved){var q=X.clientX-B,ee=X.clientY-H;w.moved=q*q+ee*ee>f}w.event(X).zoom("mouse",n(N(w.that.__zoom,w.mouse[0]=tt(X,M),w.mouse[1]),w.extent,a))}function K(X){v.on("mousemove.zoom mouseup.zoom",null),pf(X.view,w.moved),Dr(X),w.event(X).end()}}function U(L,...P){if(e.apply(this,arguments)){var M=this.__zoom,w=tt(L.changedTouches?L.changedTouches[0]:L,this),v=M.invert(w),x=M.k*(L.shiftKey?.5:2),B=n(N(O(M,x),w,v),t.apply(this,P),a);Dr(L),l>0?$e(this).transition().duration(l).call(C,B,w,L):$e(this).call(p.transform,B,w,L)}}function D(L,...P){if(e.apply(this,arguments)){var M=L.touches,w=M.length,v=m(this,P,L.changedTouches.length===w).event(L),x,B,H,Y;for(_a(L),B=0;B<w;++B)H=M[B],Y=tt(H,this),Y=[Y,this.__zoom.invert(Y),H.identifier],v.touch0?!v.touch1&&v.touch0[2]!==Y[2]&&(v.touch1=Y,v.taps=0):(v.touch0=Y,x=!0,v.taps=1+!!d);d&&(d=clearTimeout(d)),x&&(v.taps<2&&(u=Y[0],d=setTimeout(function(){d=null},S)),gs(this),v.start())}}function b(L,...P){if(this.__zooming){var M=m(this,P).event(L),w=L.changedTouches,v=w.length,x,B,H,Y;for(Dr(L),x=0;x<v;++x)B=w[x],H=tt(B,this),M.touch0&&M.touch0[2]===B.identifier?M.touch0[0]=H:M.touch1&&M.touch1[2]===B.identifier&&(M.touch1[0]=H);if(B=M.that.__zoom,M.touch1){var K=M.touch0[0],X=M.touch0[1],q=M.touch1[0],ee=M.touch1[1],Z=(Z=q[0]-K[0])*Z+(Z=q[1]-K[1])*Z,$=($=ee[0]-X[0])*$+($=ee[1]-X[1])*$;B=O(B,Math.sqrt(Z/$)),H=[(K[0]+q[0])/2,(K[1]+q[1])/2],Y=[(X[0]+ee[0])/2,(X[1]+ee[1])/2]}else if(M.touch0)H=M.touch0[0],Y=M.touch0[1];else return;M.zoom("touch",n(N(B,H,Y),M.extent,a))}}function F(L,...P){if(this.__zooming){var M=m(this,P).event(L),w=L.changedTouches,v=w.length,x,B;for(_a(L),T&&clearTimeout(T),T=setTimeout(function(){T=null},S),x=0;x<v;++x)B=w[x],M.touch0&&M.touch0[2]===B.identifier?delete M.touch0:M.touch1&&M.touch1[2]===B.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&&(B=tt(B,this),Math.hypot(u[0]-B[0],u[1]-B[1])<I)){var H=$e(this).on("dblclick.zoom");H&&H.apply(this,arguments)}}}return p.wheelDelta=function(L){return arguments.length?(r=typeof L=="function"?L:as(+L),p):r},p.filter=function(L){return arguments.length?(e=typeof L=="function"?L:as(!!L),p):e},p.touchable=function(L){return arguments.length?(o=typeof L=="function"?L:as(!!L),p):o},p.extent=function(L){return arguments.length?(t=typeof L=="function"?L:as([[+L[0][0],+L[0][1]],[+L[1][0],+L[1][1]]]),p):t},p.scaleExtent=function(L){return arguments.length?(s[0]=+L[0],s[1]=+L[1],p):[s[0],s[1]]},p.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],p):[[a[0][0],a[0][1]],[a[1][0],a[1][1]]]},p.constrain=function(L){return arguments.length?(n=L,p):n},p.duration=function(L){return arguments.length?(l=+L,p):l},p.interpolate=function(L){return arguments.length?(E=L,p):E},p.on=function(){var L=c.on.apply(c,arguments);return L===c?p:L},p.clickDistance=function(L){return arguments.length?(f=(L=+L)*L,p):Math.sqrt(f)},p.tapDistance=function(L){return arguments.length?(I=+L,p):I},p}const Ot={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."},eo=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],Uf=["Enter"," ","Escape"],wf={"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 ir;(function(e){e.Strict="strict",e.Loose="loose"})(ir||(ir={}));var Rn;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Rn||(Rn={}));var to;(function(e){e.Partial="partial",e.Full="full"})(to||(to={}));const Bf={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var $t;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})($t||($t={}));var ar;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(ar||(ar={}));var ne;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(ne||(ne={}));const wd={[ne.Left]:ne.Right,[ne.Right]:ne.Left,[ne.Top]:ne.Bottom,[ne.Bottom]:ne.Top};function Ff(e){return e===null?null:e?"valid":"invalid"}const Gf=e=>"id"in e&&"source"in e&&"target"in e,PM=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),Wc=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),fo=(e,t=[0,0])=>{const{width:n,height:r}=wt(e),o=e.origin??t,s=n*o[0],a=r*o[1];return{x:e.position.x-s,y:e.position.y-a}},bM=(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 s=typeof o=="string";let a=!t.nodeLookup&&!s?o:void 0;t.nodeLookup&&(a=s?t.nodeLookup.get(o):Wc(o)?o:t.nodeLookup.get(o.id));const l=a?Qs(a,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return Ui(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return wi(n)},Ao=(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=Ui(n,Qs(o)),r=!0)}),r?wi(n):{x:0,y:0,width:0,height:0}},Vc=(e,t,[n,r,o]=[0,0,1],s=!1,a=!1)=>{const l={...Io(t,[n,r,o]),width:t.width/o,height:t.height/o},E=[];for(const c of e.values()){const{measured:d,selectable:u=!0,hidden:T=!1}=c;if(a&&!u||T)continue;const S=d.width??c.width??c.initialWidth??null,A=d.height??c.height??c.initialHeight??null,f=no(l,cr(c)),I=(S??0)*(A??0),p=s&&f>0;(!c.internals.handleBounds||p||f>=I||c.dragging)&&E.push(c)}return E},vM=(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 UM(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 wM({nodes:e,width:t,height:n,panZoom:r,minZoom:o,maxZoom:s},a){if(e.size===0)return Promise.resolve(!0);const l=UM(e,a),E=Ao(l),c=$c(E,t,n,(a==null?void 0:a.minZoom)??o,(a==null?void 0:a.maxZoom)??s,(a==null?void 0:a.padding)??.1);return await r.setViewport(c,{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 Hf({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:o,onError:s}){const a=n.get(e),l=a.parentId?n.get(a.parentId):void 0,{x:E,y:c}=l?l.internals.positionAbsolute:{x:0,y:0},d=a.origin??r;let u=a.extent||o;if(a.extent==="parent"&&!a.expandParent)if(!l)s==null||s("005",Ot.error005());else{const S=l.measured.width,A=l.measured.height;S&&A&&(u=[[E,c],[E+S,c+A]])}else l&&Er(a.extent)&&(u=[[a.extent[0][0]+E,a.extent[0][1]+c],[a.extent[1][0]+E,a.extent[1][1]+c]]);const T=Er(u)?Nn(t,u,a.measured):t;return(a.measured.width===void 0||a.measured.height===void 0)&&(s==null||s("015",Ot.error015())),{position:{x:T.x-E+(a.measured.width??0)*d[0],y:T.y-c+(a.measured.height??0)*d[1]},positionAbsolute:T}}async function BM({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:o}){const s=new Set(e.map(T=>T.id)),a=[];for(const T of n){if(T.deletable===!1)continue;const S=s.has(T.id),A=!S&&T.parentId&&a.find(f=>f.id===T.parentId);(S||A)&&a.push(T)}const l=new Set(t.map(T=>T.id)),E=r.filter(T=>T.deletable!==!1),d=vM(a,E);for(const T of E)l.has(T.id)&&!d.find(A=>A.id===T.id)&&d.push(T);if(!o)return{edges:d,nodes:a};const u=await o({nodes:a,edges:d});return typeof u=="boolean"?u?{edges:d,nodes:a}:{edges:[],nodes:[]}:u}const lr=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Nn=(e={x:0,y:0},t,n)=>({x:lr(e.x,t[0][0],t[1][0]-((n==null?void 0:n.width)??0)),y:lr(e.y,t[0][1],t[1][1]-((n==null?void 0:n.height)??0))});function kf(e,t,n){const{width:r,height:o}=wt(n),{x:s,y:a}=n.internals.positionAbsolute;return Nn(e,[[s,a],[s+r,a+o]],t)}const Bd=(e,t,n)=>e<t?lr(Math.abs(e-t),1,t)/t:e>n?-lr(Math.abs(e-n),1,t)/t:0,Yf=(e,t,n=15,r=40)=>{const o=Bd(e.x,r,t.width-r)*n,s=Bd(e.y,r,t.height-r)*n;return[o,s]},Ui=(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)}),jl=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),wi=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),cr=(e,t=[0,0])=>{var o,s;const{x:n,y:r}=Wc(e)?e.internals.positionAbsolute:fo(e,t);return{x:n,y:r,width:((o=e.measured)==null?void 0:o.width)??e.width??e.initialWidth??0,height:((s=e.measured)==null?void 0:s.height)??e.height??e.initialHeight??0}},Qs=(e,t=[0,0])=>{var o,s;const{x:n,y:r}=Wc(e)?e.internals.positionAbsolute:fo(e,t);return{x:n,y:r,x2:n+(((o=e.measured)==null?void 0:o.width)??e.width??e.initialWidth??0),y2:r+(((s=e.measured)==null?void 0:s.height)??e.height??e.initialHeight??0)}},jf=(e,t)=>wi(Ui(jl(e),jl(t))),no=(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)},Fd=e=>rt(e.width)&&rt(e.height)&&rt(e.x)&&rt(e.y),rt=e=>!isNaN(e)&&isFinite(e),FM=(e,t)=>{},po=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),Io=({x:e,y:t},[n,r,o],s=!1,a=[1,1])=>{const l={x:(e-n)/o,y:(t-r)/o};return s?po(l,a):l},Zs=({x:e,y:t},[n,r,o])=>({x:e*o+n,y:t*o+r});function Fn(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 GM(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=Fn(e,n),o=Fn(e,t);return{top:r,right:o,bottom:r,left:o,x:o*2,y:r*2}}if(typeof e=="object"){const r=Fn(e.top??e.y??0,n),o=Fn(e.bottom??e.y??0,n),s=Fn(e.left??e.x??0,t),a=Fn(e.right??e.x??0,t);return{top:r,right:a,bottom:o,left:s,x:s+a,y:r+o}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function HM(e,t,n,r,o,s){const{x:a,y:l}=Zs(e,[t,n,r]),{x:E,y:c}=Zs({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=o-E,u=s-c;return{left:Math.floor(a),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(u)}}const $c=(e,t,n,r,o,s)=>{const a=GM(s,t,n),l=(t-a.x)/e.width,E=(n-a.y)/e.height,c=Math.min(l,E),d=lr(c,r,o),u=e.x+e.width/2,T=e.y+e.height/2,S=t/2-u*d,A=n/2-T*d,f=HM(e,S,A,d,t,n),I={left:Math.min(f.left-a.left,0),top:Math.min(f.top-a.top,0),right:Math.min(f.right-a.right,0),bottom:Math.min(f.bottom-a.bottom,0)};return{x:S-I.left+I.right,y:A-I.top+I.bottom,zoom:d}},ro=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0};function Er(e){return e!=null&&e!=="parent"}function wt(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 Wf(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 Vf(e,t={width:0,height:0},n,r,o){const s={...e},a=r.get(n);if(a){const l=a.origin||o;s.x+=a.internals.positionAbsolute.x-(t.width??0)*l[0],s.y+=a.internals.positionAbsolute.y-(t.height??0)*l[1]}return s}function Gd(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function kM(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function YM(e){return{...wf,...e||{}}}function Gr(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:o}){const{x:s,y:a}=ot(e),l=Io({x:s-((o==null?void 0:o.left)??0),y:a-((o==null?void 0:o.top)??0)},r),{x:E,y:c}=n?po(l,t):l;return{xSnapped:E,ySnapped:c,...l}}const Xc=e=>({width:e.offsetWidth,height:e.offsetHeight}),$f=e=>{var t;return((t=e==null?void 0:e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},jM=["INPUT","SELECT","TEXTAREA"];function Xf(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:jM.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const Kf=e=>"clientX"in e,ot=(e,t)=>{var s,a;const n=Kf(e),r=n?e.clientX:(s=e.touches)==null?void 0:s[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)}},Hd=(e,t,n,r,o)=>{const s=t.querySelectorAll(`.${e}`);return!s||!s.length?null:Array.from(s).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,...Xc(a)}})};function zf({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:o,sourceControlY:s,targetControlX:a,targetControlY:l}){const E=e*.125+o*.375+a*.375+n*.125,c=t*.125+s*.375+l*.375+r*.125,d=Math.abs(E-e),u=Math.abs(c-t);return[E,c,d,u]}function ls(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function kd({pos:e,x1:t,y1:n,x2:r,y2:o,c:s}){switch(e){case ne.Left:return[t-ls(t-r,s),n];case ne.Right:return[t+ls(r-t,s),n];case ne.Top:return[t,n-ls(n-o,s)];case ne.Bottom:return[t,n+ls(o-n,s)]}}function Jf({sourceX:e,sourceY:t,sourcePosition:n=ne.Bottom,targetX:r,targetY:o,targetPosition:s=ne.Top,curvature:a=.25}){const[l,E]=kd({pos:n,x1:e,y1:t,x2:r,y2:o,c:a}),[c,d]=kd({pos:s,x1:r,y1:o,x2:e,y2:t,c:a}),[u,T,S,A]=zf({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:l,sourceControlY:E,targetControlX:c,targetControlY:d});return[`M${e},${t} C${l},${E} ${c},${d} ${r},${o}`,u,T,S,A]}function qf({sourceX:e,sourceY:t,targetX:n,targetY:r}){const o=Math.abs(n-e)/2,s=n<e?n+o:n-o,a=Math.abs(r-t)/2,l=r<t?r+a:r-a;return[s,l,o,a]}function WM({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:o=!1,zIndexMode:s="basic"}){if(s==="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 VM({sourceNode:e,targetNode:t,width:n,height:r,transform:o}){const s=Ui(Qs(e),Qs(t));s.x===s.x2&&(s.x2+=1),s.y===s.y2&&(s.y2+=1);const a={x:-o[0]/o[2],y:-o[1]/o[2],width:n/o[2],height:r/o[2]};return no(a,wi(s))>0}const $M=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,XM=(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)),KM=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||$M;let o;return Gf(e)?o={...e}:o={...e,id:r(e)},XM(o,t)?t:(o.sourceHandle===null&&delete o.sourceHandle,o.targetHandle===null&&delete o.targetHandle,t.concat(o))};function Qf({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[o,s,a,l]=qf({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,o,s,a,l]}const Yd={[ne.Left]:{x:-1,y:0},[ne.Right]:{x:1,y:0},[ne.Top]:{x:0,y:-1},[ne.Bottom]:{x:0,y:1}},zM=({source:e,sourcePosition:t=ne.Bottom,target:n})=>t===ne.Left||t===ne.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},jd=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function JM({source:e,sourcePosition:t=ne.Bottom,target:n,targetPosition:r=ne.Top,center:o,offset:s,stepPosition:a}){const l=Yd[t],E=Yd[r],c={x:e.x+l.x*s,y:e.y+l.y*s},d={x:n.x+E.x*s,y:n.y+E.y*s},u=zM({source:c,sourcePosition:t,target:d}),T=u.x!==0?"x":"y",S=u[T];let A=[],f,I;const p={x:0,y:0},O={x:0,y:0},[,,N,h]=qf({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[T]*E[T]===-1){T==="x"?(f=o.x??c.x+(d.x-c.x)*a,I=o.y??(c.y+d.y)/2):(f=o.x??(c.x+d.x)/2,I=o.y??c.y+(d.y-c.y)*a);const m=[{x:f,y:c.y},{x:f,y:d.y}],g=[{x:c.x,y:I},{x:d.x,y:I}];l[T]===S?A=T==="x"?m:g:A=T==="x"?g:m}else{const m=[{x:c.x,y:d.y}],g=[{x:d.x,y:c.y}];if(T==="x"?A=l.x===S?g:m:A=l.y===S?m:g,t===r){const b=Math.abs(e[T]-n[T]);if(b<=s){const F=Math.min(s-1,s-b);l[T]===S?p[T]=(c[T]>e[T]?-1:1)*F:O[T]=(d[T]>n[T]?-1:1)*F}}if(t!==r){const b=T==="x"?"y":"x",F=l[T]===E[b],L=c[b]>d[b],P=c[b]<d[b];(l[T]===1&&(!F&&L||F&&P)||l[T]!==1&&(!F&&P||F&&L))&&(A=T==="x"?m:g)}const y={x:c.x+p.x,y:c.y+p.y},_={x:d.x+O.x,y:d.y+O.y},U=Math.max(Math.abs(y.x-A[0].x),Math.abs(_.x-A[0].x)),D=Math.max(Math.abs(y.y-A[0].y),Math.abs(_.y-A[0].y));U>=D?(f=(y.x+_.x)/2,I=A[0].y):(f=A[0].x,I=(y.y+_.y)/2)}return[[e,{x:c.x+p.x,y:c.y+p.y},...A,{x:d.x+O.x,y:d.y+O.y},n],f,I,N,h]}function qM(e,t,n,r){const o=Math.min(jd(e,t)/2,jd(t,n)/2,r),{x:s,y:a}=t;if(e.x===s&&s===n.x||e.y===a&&a===n.y)return`L${s} ${a}`;if(e.y===a){const c=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${s+o*c},${a}Q ${s},${a} ${s},${a+o*d}`}const l=e.x<n.x?1:-1,E=e.y<n.y?-1:1;return`L ${s},${a+o*E}Q ${s},${a} ${s+o*l},${a}`}function Wl({sourceX:e,sourceY:t,sourcePosition:n=ne.Bottom,targetX:r,targetY:o,targetPosition:s=ne.Top,borderRadius:a=5,centerX:l,centerY:E,offset:c=20,stepPosition:d=.5}){const[u,T,S,A,f]=JM({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:o},targetPosition:s,center:{x:l,y:E},offset:c,stepPosition:d});return[u.reduce((p,O,N)=>{let h="";return N>0&&N<u.length-1?h=qM(u[N-1],O,u[N+1],a):h=`${N===0?"M":"L"}${O.x} ${O.y}`,p+=h,p},""),T,S,A,f]}function Wd(e){var t;return e&&!!(e.internals.handleBounds||(t=e.handles)!=null&&t.length)&&!!(e.measured.width||e.width||e.initialWidth)}function QM(e){var u;const{sourceNode:t,targetNode:n}=e;if(!Wd(t)||!Wd(n))return null;const r=t.internals.handleBounds||Vd(t.handles),o=n.internals.handleBounds||Vd(n.handles),s=$d((r==null?void 0:r.source)??[],e.sourceHandle),a=$d(e.connectionMode===ir.Strict?(o==null?void 0:o.target)??[]:((o==null?void 0:o.target)??[]).concat((o==null?void 0:o.source)??[]),e.targetHandle);if(!s||!a)return(u=e.onError)==null||u.call(e,"008",Ot.error008(s?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=(s==null?void 0:s.position)||ne.Bottom,E=(a==null?void 0:a.position)||ne.Top,c=hn(t,s,l),d=hn(n,a,E);return{sourceX:c.x,sourceY:c.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:E}}function Vd(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 hn(e,t,n=ne.Left,r=!1){const o=((t==null?void 0:t.x)??0)+e.internals.positionAbsolute.x,s=((t==null?void 0:t.y)??0)+e.internals.positionAbsolute.y,{width:a,height:l}=t??wt(e);if(r)return{x:o+a/2,y:s+l/2};switch((t==null?void 0:t.position)??n){case ne.Top:return{x:o+a/2,y:s};case ne.Right:return{x:o+a,y:s+l/2};case ne.Bottom:return{x:o+a/2,y:s+l};case ne.Left:return{x:o,y:s+l/2}}}function $d(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Vl(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function ZM(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:o}){const s=new Set;return e.reduce((a,l)=>([l.markerStart||r,l.markerEnd||o].forEach(E=>{if(E&&typeof E=="object"){const c=Vl(E,t);s.has(c)||(a.push({id:c,color:E.color||n,...E}),s.add(c))}}),a),[]).sort((a,l)=>a.id.localeCompare(l.id))}const Zf=1e3,eP=10,Kc={nodeOrigin:[0,0],nodeExtent:eo,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},tP={...Kc,checkEquality:!0};function zc(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function nP(e,t,n){const r=zc(Kc,n);for(const o of e.values())if(o.parentId)qc(o,e,t,r);else{const s=fo(o,r.nodeOrigin),a=Er(o.extent)?o.extent:r.nodeExtent,l=Nn(s,a,wt(o));o.internals.positionAbsolute=l}}function rP(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 s={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(s):o.type==="target"&&r.push(s)}return{source:n,target:r}}function Jc(e){return e==="manual"}function $l(e,t,n,r={}){var c,d;const o=zc(tP,r),s={i:0},a=new Map(t),l=o!=null&&o.elevateNodesOnSelect&&!Jc(o.zIndexMode)?Zf:0;let E=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 S=fo(u,o.nodeOrigin),A=Er(u.extent)?u.extent:o.nodeExtent,f=Nn(S,A,wt(u));T={...o.defaults,...u,measured:{width:(c=u.measured)==null?void 0:c.width,height:(d=u.measured)==null?void 0:d.height},internals:{positionAbsolute:f,handleBounds:rP(u,T),z:eA(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&&(E=!1),u.parentId&&qc(T,t,n,r,s)}return E}function oP(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 qc(e,t,n,r,o){const{elevateNodesOnSelect:s,nodeOrigin:a,nodeExtent:l,zIndexMode:E}=zc(Kc,r),c=e.parentId,d=t.get(c);if(!d){console.warn(`Parent node ${c} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}oP(e,n),o&&!d.parentId&&d.internals.rootParentIndex===void 0&&E==="auto"&&(d.internals.rootParentIndex=++o.i,d.internals.z=d.internals.z+o.i*eP),o&&d.internals.rootParentIndex!==void 0&&(o.i=d.internals.rootParentIndex);const u=s&&!Jc(E)?Zf:0,{x:T,y:S,z:A}=sP(e,d,a,l,u,E),{positionAbsolute:f}=e.internals,I=T!==f.x||S!==f.y;(I||A!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:I?{x:T,y:S}:f,z:A}})}function eA(e,t,n){const r=rt(e.zIndex)?e.zIndex:0;return Jc(n)?r:r+(e.selected?t:0)}function sP(e,t,n,r,o,s){const{x:a,y:l}=t.internals.positionAbsolute,E=wt(e),c=fo(e,n),d=Er(e.extent)?Nn(c,e.extent,E):c;let u=Nn({x:a+d.x,y:l+d.y},r,E);e.extent==="parent"&&(u=kf(u,E,t));const T=eA(e,o,s),S=t.internals.z??0;return{x:u.x,y:u.y,z:S>=T?S+1:T}}function Qc(e,t,n,r=[0,0]){var a;const o=[],s=new Map;for(const l of e){const E=t.get(l.parentId);if(!E)continue;const c=((a=s.get(l.parentId))==null?void 0:a.expandedRect)??cr(E),d=jf(c,l.rect);s.set(l.parentId,{expandedRect:d,parent:E})}return s.size>0&&s.forEach(({expandedRect:l,parent:E},c)=>{var N;const d=E.internals.positionAbsolute,u=wt(E),T=E.origin??r,S=l.x<d.x?Math.round(Math.abs(d.x-l.x)):0,A=l.y<d.y?Math.round(Math.abs(d.y-l.y)):0,f=Math.max(u.width,Math.round(l.width)),I=Math.max(u.height,Math.round(l.height)),p=(f-u.width)*T[0],O=(I-u.height)*T[1];(S>0||A>0||p||O)&&(o.push({id:c,type:"position",position:{x:E.position.x-S+p,y:E.position.y-A+O}}),(N=n.get(c))==null||N.forEach(h=>{e.some(C=>C.id===h.id)||o.push({id:h.id,type:"position",position:{x:h.position.x+S,y:h.position.y+A}})})),(u.width<l.width||u.height<l.height||S||A)&&o.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:f+(S?T[0]*S-p:0),height:I+(A?T[1]*A-O:0)}})}),o}function iP(e,t,n,r,o,s,a){const l=r==null?void 0:r.querySelector(".xyflow__viewport");let E=!1;if(!l)return{changes:[],updatedInternals:E};const c=[],d=window.getComputedStyle(l),{m22:u}=new window.DOMMatrixReadOnly(d.transform),T=[];for(const S of e.values()){const A=t.get(S.id);if(!A)continue;if(A.hidden){t.set(A.id,{...A,internals:{...A.internals,handleBounds:void 0}}),E=!0;continue}const f=Xc(S.nodeElement),I=A.measured.width!==f.width||A.measured.height!==f.height;if(!!(f.width&&f.height&&(I||!A.internals.handleBounds||S.force))){const O=S.nodeElement.getBoundingClientRect(),N=Er(A.extent)?A.extent:s;let{positionAbsolute:h}=A.internals;A.parentId&&A.extent==="parent"?h=kf(h,f,t.get(A.parentId)):N&&(h=Nn(h,N,f));const C={...A,measured:f,internals:{...A.internals,positionAbsolute:h,handleBounds:{source:Hd("source",S.nodeElement,O,u,A.id),target:Hd("target",S.nodeElement,O,u,A.id)}}};t.set(A.id,C),A.parentId&&qc(C,t,n,{nodeOrigin:o,zIndexMode:a}),E=!0,I&&(c.push({id:A.id,type:"dimensions",dimensions:f}),A.expandParent&&A.parentId&&T.push({id:A.id,parentId:A.parentId,rect:cr(C,o)}))}}if(T.length>0){const S=Qc(T,t,n,o);c.push(...S)}return{changes:c,updatedInternals:E}}async function aP({delta:e,panZoom:t,transform:n,translateExtent:r,width:o,height:s}){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,s]],r),l=!!a&&(a.x!==n[0]||a.y!==n[1]||a.k!==n[2]);return Promise.resolve(l)}function Xd(e,t,n,r,o,s){let a=o;const l=r.get(a)||new Map;r.set(a,l.set(n,t)),a=`${o}-${e}`;const E=r.get(a)||new Map;if(r.set(a,E.set(n,t)),s){a=`${o}-${e}-${s}`;const c=r.get(a)||new Map;r.set(a,c.set(n,t))}}function tA(e,t,n){e.clear(),t.clear();for(const r of n){const{source:o,target:s,sourceHandle:a=null,targetHandle:l=null}=r,E={edgeId:r.id,source:o,target:s,sourceHandle:a,targetHandle:l},c=`${o}-${a}--${s}-${l}`,d=`${s}-${l}--${o}-${a}`;Xd("source",E,d,e,o,a),Xd("target",E,c,e,s,l),t.set(r.id,r)}}function nA(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:nA(n,t):!1}function Kd(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 lP(e,t,n,r){const o=new Map;for(const[s,a]of e)if((a.selected||a.id===r)&&(!a.parentId||!nA(a,e))&&(a.draggable||t&&typeof a.draggable>"u")){const l=e.get(s);l&&o.set(s,{id:s,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 xa({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){var a,l,E;const o=[];for(const[c,d]of t){const u=(a=n.get(c))==null?void 0:a.internals.userNode;u&&o.push({...u,position:d.position,dragging:r})}if(!e)return[o[0],o];const s=(l=n.get(e))==null?void 0:l.internals.userNode;return[s?{...s,position:((E=t.get(e))==null?void 0:E.position)||s.position,dragging:r}:o[0],o]}function cP({dragItems:e,snapGrid:t,x:n,y:r}){const o=e.values().next().value;if(!o)return null;const s={x:n-o.distance.x,y:r-o.distance.y},a=po(s,t);return{x:a.x-s.x,y:a.y-s.y}}function EP({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:o}){let s={x:null,y:null},a=0,l=new Map,E=!1,c={x:0,y:0},d=null,u=!1,T=null,S=!1,A=!1,f=null;function I({noDragClassName:O,handleSelector:N,domNode:h,isSelectable:C,nodeId:m,nodeClickDistance:g=0}){T=$e(h);function y({x:b,y:F}){const{nodeLookup:L,nodeExtent:P,snapGrid:M,snapToGrid:w,nodeOrigin:v,onNodeDrag:x,onSelectionDrag:B,onError:H,updateNodePositions:Y}=t();s={x:b,y:F};let K=!1;const X=l.size>1,q=X&&P?jl(Ao(l)):null,ee=X&&w?cP({dragItems:l,snapGrid:M,x:b,y:F}):null;for(const[Z,$]of l){if(!L.has(Z))continue;let z={x:b-$.distance.x,y:F-$.distance.y};w&&(z=ee?{x:Math.round(z.x+ee.x),y:Math.round(z.y+ee.y)}:po(z,M));let ce=null;if(X&&P&&!$.extent&&q){const{positionAbsolute:J}=$.internals,Ee=J.x-q.x+P[0][0],Ae=J.x+$.measured.width-q.x2+P[1][0],ue=J.y-q.y+P[0][1],Re=J.y+$.measured.height-q.y2+P[1][1];ce=[[Ee,ue],[Ae,Re]]}const{position:se,positionAbsolute:V}=Hf({nodeId:Z,nextPosition:z,nodeLookup:L,nodeExtent:ce||P,nodeOrigin:v,onError:H});K=K||$.position.x!==se.x||$.position.y!==se.y,$.position=se,$.internals.positionAbsolute=V}if(A=A||K,!!K&&(Y(l,!0),f&&(r||x||!m&&B))){const[Z,$]=xa({nodeId:m,dragItems:l,nodeLookup:L});r==null||r(f,l,Z,$),x==null||x(f,Z,$),m||B==null||B(f,$)}}async function _(){if(!d)return;const{transform:b,panBy:F,autoPanSpeed:L,autoPanOnNodeDrag:P}=t();if(!P){E=!1,cancelAnimationFrame(a);return}const[M,w]=Yf(c,d,L);(M!==0||w!==0)&&(s.x=(s.x??0)-M/b[2],s.y=(s.y??0)-w/b[2],await F({x:M,y:w})&&y(s)),a=requestAnimationFrame(_)}function U(b){var X;const{nodeLookup:F,multiSelectionActive:L,nodesDraggable:P,transform:M,snapGrid:w,snapToGrid:v,selectNodesOnDrag:x,onNodeDragStart:B,onSelectionDragStart:H,unselectNodesAndEdges:Y}=t();u=!0,(!x||!C)&&!L&&m&&((X=F.get(m))!=null&&X.selected||Y()),C&&x&&m&&(e==null||e(m));const K=Gr(b.sourceEvent,{transform:M,snapGrid:w,snapToGrid:v,containerBounds:d});if(s=K,l=lP(F,P,K,m),l.size>0&&(n||B||!m&&H)){const[q,ee]=xa({nodeId:m,dragItems:l,nodeLookup:F});n==null||n(b.sourceEvent,l,q,ee),B==null||B(b.sourceEvent,q,ee),m||H==null||H(b.sourceEvent,ee)}}const D=If().clickDistance(g).on("start",b=>{const{domNode:F,nodeDragThreshold:L,transform:P,snapGrid:M,snapToGrid:w}=t();d=(F==null?void 0:F.getBoundingClientRect())||null,S=!1,A=!1,f=b.sourceEvent,L===0&&U(b),s=Gr(b.sourceEvent,{transform:P,snapGrid:M,snapToGrid:w,containerBounds:d}),c=ot(b.sourceEvent,d)}).on("drag",b=>{const{autoPanOnNodeDrag:F,transform:L,snapGrid:P,snapToGrid:M,nodeDragThreshold:w,nodeLookup:v}=t(),x=Gr(b.sourceEvent,{transform:L,snapGrid:P,snapToGrid:M,containerBounds:d});if(f=b.sourceEvent,(b.sourceEvent.type==="touchmove"&&b.sourceEvent.touches.length>1||m&&!v.has(m))&&(S=!0),!S){if(!E&&F&&u&&(E=!0,_()),!u){const B=ot(b.sourceEvent,d),H=B.x-c.x,Y=B.y-c.y;Math.sqrt(H*H+Y*Y)>w&&U(b)}(s.x!==x.xSnapped||s.y!==x.ySnapped)&&l&&u&&(c=ot(b.sourceEvent,d),y(x))}}).on("end",b=>{if(!(!u||S)&&(E=!1,u=!1,cancelAnimationFrame(a),l.size>0)){const{nodeLookup:F,updateNodePositions:L,onNodeDragStop:P,onSelectionDragStop:M}=t();if(A&&(L(l,!1),A=!1),o||P||!m&&M){const[w,v]=xa({nodeId:m,dragItems:l,nodeLookup:F,dragging:!1});o==null||o(b.sourceEvent,l,w,v),P==null||P(b.sourceEvent,w,v),m||M==null||M(b.sourceEvent,v)}}}).filter(b=>{const F=b.target;return!b.button&&(!O||!Kd(F,`.${O}`,h))&&(!N||Kd(F,N,h))});T.call(D)}function p(){T==null||T.on(".drag",null)}return{update:I,destroy:p}}function dP(e,t,n){const r=[],o={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const s of t.values())no(o,cr(s))>0&&r.push(s);return r}const uP=250;function TP(e,t,n,r){var l,E;let o=[],s=1/0;const a=dP(e,n,t+uP);for(const c of a){const d=[...((l=c.internals.handleBounds)==null?void 0:l.source)??[],...((E=c.internals.handleBounds)==null?void 0:E.target)??[]];for(const u of d){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:T,y:S}=hn(c,u,u.position,!0),A=Math.sqrt(Math.pow(T-e.x,2)+Math.pow(S-e.y,2));A>t||(A<s?(o=[{...u,x:T,y:S}],s=A):A===s&&o.push({...u,x:T,y:S}))}}if(!o.length)return null;if(o.length>1){const c=r.type==="source"?"target":"source";return o.find(d=>d.type===c)??o[0]}return o[0]}function rA(e,t,n,r,o,s=!1){var c,d,u;const a=r.get(e);if(!a)return null;const l=o==="strict"?(c=a.internals.handleBounds)==null?void 0:c[t]:[...((d=a.internals.handleBounds)==null?void 0:d.source)??[],...((u=a.internals.handleBounds)==null?void 0:u.target)??[]],E=(n?l==null?void 0:l.find(T=>T.id===n):l==null?void 0:l[0])??null;return E&&s?{...E,...hn(a,E,E.position,!0)}:E}function oA(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function SP(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const sA=()=>!0;function RP(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:o,edgeUpdaterType:s,isTarget:a,domNode:l,nodeLookup:E,lib:c,autoPanOnConnect:d,flowId:u,panBy:T,cancelConnection:S,onConnectStart:A,onConnect:f,onConnectEnd:I,isValidConnection:p=sA,onReconnectEnd:O,updateConnection:N,getTransform:h,getFromHandle:C,autoPanSpeed:m,dragThreshold:g=1,handleDomNode:y}){const _=$f(e.target);let U=0,D;const{x:b,y:F}=ot(e),L=oA(s,y),P=l==null?void 0:l.getBoundingClientRect();let M=!1;if(!P||!L)return;const w=rA(o,L,r,E,t);if(!w)return;let v=ot(e,P),x=!1,B=null,H=!1,Y=null;function K(){if(!d||!P)return;const[se,V]=Yf(v,P,m);T({x:se,y:V}),U=requestAnimationFrame(K)}const X={...w,nodeId:o,type:L,position:w.position},q=E.get(o);let Z={inProgress:!0,isValid:null,from:hn(q,X,ne.Left,!0),fromHandle:X,fromPosition:X.position,fromNode:q,to:v,toHandle:null,toPosition:wd[X.position],toNode:null,pointer:v};function $(){M=!0,N(Z),A==null||A(e,{nodeId:o,handleId:r,handleType:L})}g===0&&$();function z(se){if(!M){const{x:Re,y:He}=ot(se),Pe=Re-b,dt=He-F;if(!(Pe*Pe+dt*dt>g*g))return;$()}if(!C()||!X){ce(se);return}const V=h();v=ot(se,P),D=TP(Io(v,V,!1,[1,1]),n,E,X),x||(K(),x=!0);const J=iA(se,{handle:D,connectionMode:t,fromNodeId:o,fromHandleId:r,fromType:a?"target":"source",isValidConnection:p,doc:_,lib:c,flowId:u,nodeLookup:E});Y=J.handleDomNode,B=J.connection,H=SP(!!D,J.isValid);const Ee=E.get(o),Ae=Ee?hn(Ee,X,ne.Left,!0):Z.from,ue={...Z,from:Ae,isValid:H,to:J.toHandle&&H?Zs({x:J.toHandle.x,y:J.toHandle.y},V):v,toHandle:J.toHandle,toPosition:H&&J.toHandle?J.toHandle.position:wd[X.position],toNode:J.toHandle?E.get(J.toHandle.nodeId):null,pointer:v};N(ue),Z=ue}function ce(se){if(!("touches"in se&&se.touches.length>0)){if(M){(D||Y)&&B&&H&&(f==null||f(B));const{inProgress:V,...J}=Z,Ee={...J,toPosition:Z.toHandle?Z.toPosition:null};I==null||I(se,Ee),s&&(O==null||O(se,Ee))}S(),cancelAnimationFrame(U),x=!1,H=!1,B=null,Y=null,_.removeEventListener("mousemove",z),_.removeEventListener("mouseup",ce),_.removeEventListener("touchmove",z),_.removeEventListener("touchend",ce)}}_.addEventListener("mousemove",z),_.addEventListener("mouseup",ce),_.addEventListener("touchmove",z),_.addEventListener("touchend",ce)}function iA(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:o,fromType:s,doc:a,lib:l,flowId:E,isValidConnection:c=sA,nodeLookup:d}){const u=s==="target",T=t?a.querySelector(`.${l}-flow__handle[data-id="${E}-${t==null?void 0:t.nodeId}-${t==null?void 0:t.id}-${t==null?void 0:t.type}"]`):null,{x:S,y:A}=ot(e),f=a.elementFromPoint(S,A),I=f!=null&&f.classList.contains(`${l}-flow__handle`)?f:T,p={handleDomNode:I,isValid:!1,connection:null,toHandle:null};if(I){const O=oA(void 0,I),N=I.getAttribute("data-nodeid"),h=I.getAttribute("data-handleid"),C=I.classList.contains("connectable"),m=I.classList.contains("connectableend");if(!N||!O)return p;const g={source:u?N:r,sourceHandle:u?h:o,target:u?r:N,targetHandle:u?o:h};p.connection=g;const _=C&&m&&(n===ir.Strict?u&&O==="source"||!u&&O==="target":N!==r||h!==o);p.isValid=_&&c(g),p.toHandle=rA(N,O,h,d,n,!0)}return p}const Xl={onPointerDown:RP,isValid:iA};function fP({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const o=$e(e);function s({translateExtent:l,width:E,height:c,zoomStep:d=1,pannable:u=!0,zoomable:T=!0,inversePan:S=!1}){const A=N=>{if(N.sourceEvent.type!=="wheel"||!t)return;const h=n(),C=N.sourceEvent.ctrlKey&&ro()?10:1,m=-N.sourceEvent.deltaY*(N.sourceEvent.deltaMode===1?.05:N.sourceEvent.deltaMode?1:.002)*d,g=h[2]*Math.pow(2,m*C);t.scaleTo(g)};let f=[0,0];const I=N=>{(N.sourceEvent.type==="mousedown"||N.sourceEvent.type==="touchstart")&&(f=[N.sourceEvent.clientX??N.sourceEvent.touches[0].clientX,N.sourceEvent.clientY??N.sourceEvent.touches[0].clientY])},p=N=>{const h=n();if(N.sourceEvent.type!=="mousemove"&&N.sourceEvent.type!=="touchmove"||!t)return;const C=[N.sourceEvent.clientX??N.sourceEvent.touches[0].clientX,N.sourceEvent.clientY??N.sourceEvent.touches[0].clientY],m=[C[0]-f[0],C[1]-f[1]];f=C;const g=r()*Math.max(h[2],Math.log(h[2]))*(S?-1:1),y={x:h[0]-m[0]*g,y:h[1]-m[1]*g},_=[[0,0],[E,c]];t.setViewportConstrained({x:y.x,y:y.y,zoom:h[2]},_,l)},O=vf().on("start",I).on("zoom",u?p:null).on("zoom.wheel",T?A:null);o.call(O,{})}function a(){o.on("zoom",null)}return{update:s,destroy:a,pointer:tt}}const Bi=e=>({x:e.x,y:e.y,zoom:e.k}),ya=({x:e,y:t,zoom:n})=>vi.translate(e,t).scale(n),$n=(e,t)=>e.target.closest(`.${t}`),aA=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),AP=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Da=(e,t=0,n=AP,r=()=>{})=>{const o=typeof t=="number"&&t>0;return o||r(),o?e.transition().duration(t).ease(n).on("end",r):e},lA=e=>{const t=e.ctrlKey&&ro()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function pP({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:o,panOnScrollSpeed:s,zoomOnPinch:a,onPanZoomStart:l,onPanZoom:E,onPanZoomEnd:c}){return d=>{if($n(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const u=n.property("__zoom").k||1;if(d.ctrlKey&&a){const I=tt(d),p=lA(d),O=u*Math.pow(2,p);r.scaleTo(n,O,I,d);return}const T=d.deltaMode===1?20:1;let S=o===Rn.Vertical?0:d.deltaX*T,A=o===Rn.Horizontal?0:d.deltaY*T;!ro()&&d.shiftKey&&o!==Rn.Vertical&&(S=d.deltaY*T,A=0),r.translateBy(n,-(S/u)*s,-(A/u)*s,{internal:!0});const f=Bi(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(E==null||E(d,f),e.panScrollTimeout=setTimeout(()=>{c==null||c(d,f),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l==null||l(d,f))}}function IP({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,o){const s=r.type==="wheel",a=!t&&s&&!r.ctrlKey,l=$n(r,e);if(r.ctrlKey&&s&&l&&r.preventDefault(),a||l)return null;r.preventDefault(),n.call(this,r,o)}}function OP({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{var s,a,l;if((s=r.sourceEvent)!=null&&s.internal)return;const o=Bi(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 NP({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:o}){return s=>{var a,l;e.usedRightMouseButton=!!(n&&aA(t,e.mouseButton??0)),(a=s.sourceEvent)!=null&&a.sync||r([s.transform.x,s.transform.y,s.transform.k]),o&&!((l=s.sourceEvent)!=null&&l.internal)&&(o==null||o(s.sourceEvent,Bi(s.transform)))}}function hP({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:o,onPaneContextMenu:s}){return a=>{var l;if(!((l=a.sourceEvent)!=null&&l.internal)&&(e.isZoomingOrPanning=!1,s&&aA(t,e.mouseButton??0)&&!e.usedRightMouseButton&&a.sourceEvent&&s(a.sourceEvent),e.usedRightMouseButton=!1,r(!1),o)){const E=Bi(a.transform);e.prevViewport=E,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{o==null||o(a.sourceEvent,E)},n?150:0)}}}function mP({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:o,zoomOnDoubleClick:s,userSelectionActive:a,noWheelClassName:l,noPanClassName:E,lib:c,connectionInProgress:d}){return u=>{var I;const T=e||t,S=n&&u.ctrlKey,A=u.type==="wheel";if(u.button===1&&u.type==="mousedown"&&($n(u,`${c}-flow__node`)||$n(u,`${c}-flow__edge`)))return!0;if(!r&&!T&&!o&&!s&&!n||a||d&&!A||$n(u,l)&&A||$n(u,E)&&(!A||o&&A&&!e)||!n&&u.ctrlKey&&A)return!1;if(!n&&u.type==="touchstart"&&((I=u.touches)==null?void 0:I.length)>1)return u.preventDefault(),!1;if(!T&&!o&&!S&&A||!r&&(u.type==="mousedown"||u.type==="touchstart")||Array.isArray(r)&&!r.includes(u.button)&&u.type==="mousedown")return!1;const f=Array.isArray(r)&&r.includes(u.button)||!u.button||u.button<=1;return(!u.ctrlKey||A)&&f}}function CP({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:o,onPanZoom:s,onPanZoomStart:a,onPanZoomEnd:l,onDraggingChange:E}){const c={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),u=vf().scaleExtent([t,n]).translateExtent(r),T=$e(e).call(u);O({x:o.x,y:o.y,zoom:lr(o.zoom,t,n)},[[0,0],[d.width,d.height]],r);const S=T.on("wheel.zoom"),A=T.on("dblclick.zoom");u.wheelDelta(lA);function f(D,b){return T?new Promise(F=>{u==null||u.interpolate((b==null?void 0:b.interpolate)==="linear"?Fr:hs).transform(Da(T,b==null?void 0:b.duration,b==null?void 0:b.ease,()=>F(!0)),D)}):Promise.resolve(!1)}function I({noWheelClassName:D,noPanClassName:b,onPaneContextMenu:F,userSelectionActive:L,panOnScroll:P,panOnDrag:M,panOnScrollMode:w,panOnScrollSpeed:v,preventScrolling:x,zoomOnPinch:B,zoomOnScroll:H,zoomOnDoubleClick:Y,zoomActivationKeyPressed:K,lib:X,onTransformChange:q,connectionInProgress:ee,paneClickDistance:Z,selectionOnDrag:$}){L&&!c.isZoomingOrPanning&&p();const z=P&&!K&&!L;u.clickDistance($?1/0:!rt(Z)||Z<0?0:Z);const ce=z?pP({zoomPanValues:c,noWheelClassName:D,d3Selection:T,d3Zoom:u,panOnScrollMode:w,panOnScrollSpeed:v,zoomOnPinch:B,onPanZoomStart:a,onPanZoom:s,onPanZoomEnd:l}):IP({noWheelClassName:D,preventScrolling:x,d3ZoomHandler:S});if(T.on("wheel.zoom",ce,{passive:!1}),!L){const V=OP({zoomPanValues:c,onDraggingChange:E,onPanZoomStart:a});u.on("start",V);const J=NP({zoomPanValues:c,panOnDrag:M,onPaneContextMenu:!!F,onPanZoom:s,onTransformChange:q});u.on("zoom",J);const Ee=hP({zoomPanValues:c,panOnDrag:M,panOnScroll:P,onPaneContextMenu:F,onPanZoomEnd:l,onDraggingChange:E});u.on("end",Ee)}const se=mP({zoomActivationKeyPressed:K,panOnDrag:M,zoomOnScroll:H,panOnScroll:P,zoomOnDoubleClick:Y,zoomOnPinch:B,userSelectionActive:L,noPanClassName:b,noWheelClassName:D,lib:X,connectionInProgress:ee});u.filter(se),Y?T.on("dblclick.zoom",A):T.on("dblclick.zoom",null)}function p(){u.on("zoom",null)}async function O(D,b,F){const L=ya(D),P=u==null?void 0:u.constrain()(L,b,F);return P&&await f(P),new Promise(M=>M(P))}async function N(D,b){const F=ya(D);return await f(F,b),new Promise(L=>L(F))}function h(D){if(T){const b=ya(D),F=T.property("__zoom");(F.k!==D.zoom||F.x!==D.x||F.y!==D.y)&&(u==null||u.transform(T,b,null,{sync:!0}))}}function C(){const D=T?bf(T.node()):{x:0,y:0,k:1};return{x:D.x,y:D.y,zoom:D.k}}function m(D,b){return T?new Promise(F=>{u==null||u.interpolate((b==null?void 0:b.interpolate)==="linear"?Fr:hs).scaleTo(Da(T,b==null?void 0:b.duration,b==null?void 0:b.ease,()=>F(!0)),D)}):Promise.resolve(!1)}function g(D,b){return T?new Promise(F=>{u==null||u.interpolate((b==null?void 0:b.interpolate)==="linear"?Fr:hs).scaleBy(Da(T,b==null?void 0:b.duration,b==null?void 0:b.ease,()=>F(!0)),D)}):Promise.resolve(!1)}function y(D){u==null||u.scaleExtent(D)}function _(D){u==null||u.translateExtent(D)}function U(D){const b=!rt(D)||D<0?0:D;u==null||u.clickDistance(b)}return{update:I,destroy:p,setViewport:N,setViewportConstrained:O,getViewport:C,scaleTo:m,scaleBy:g,setScaleExtent:y,setTranslateExtent:_,syncViewport:h,setClickDistance:U}}var dr;(function(e){e.Line="line",e.Handle="handle"})(dr||(dr={}));function gP({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:o,affectsY:s}){const a=e-t,l=n-r,E=[a>0?1:a<0?-1:0,l>0?1:l<0?-1:0];return a&&o&&(E[0]=E[0]*-1),l&&s&&(E[1]=E[1]*-1),E}function zd(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 jt(e,t){return Math.max(0,t-e)}function Wt(e,t){return Math.max(0,e-t)}function cs(e,t,n){return Math.max(0,t-e,e-n)}function Jd(e,t){return e?!t:t}function LP(e,t,n,r,o,s,a,l){let{affectsX:E,affectsY:c}=t;const{isHorizontal:d,isVertical:u}=t,T=d&&u,{xSnapped:S,ySnapped:A}=n,{minWidth:f,maxWidth:I,minHeight:p,maxHeight:O}=r,{x:N,y:h,width:C,height:m,aspectRatio:g}=e;let y=Math.floor(d?S-e.pointerX:0),_=Math.floor(u?A-e.pointerY:0);const U=C+(E?-y:y),D=m+(c?-_:_),b=-s[0]*C,F=-s[1]*m;let L=cs(U,f,I),P=cs(D,p,O);if(a){let v=0,x=0;E&&y<0?v=jt(N+y+b,a[0][0]):!E&&y>0&&(v=Wt(N+U+b,a[1][0])),c&&_<0?x=jt(h+_+F,a[0][1]):!c&&_>0&&(x=Wt(h+D+F,a[1][1])),L=Math.max(L,v),P=Math.max(P,x)}if(l){let v=0,x=0;E&&y>0?v=Wt(N+y,l[0][0]):!E&&y<0&&(v=jt(N+U,l[1][0])),c&&_>0?x=Wt(h+_,l[0][1]):!c&&_<0&&(x=jt(h+D,l[1][1])),L=Math.max(L,v),P=Math.max(P,x)}if(o){if(d){const v=cs(U/g,p,O)*g;if(L=Math.max(L,v),a){let x=0;!E&&!c||E&&!c&&T?x=Wt(h+F+U/g,a[1][1])*g:x=jt(h+F+(E?y:-y)/g,a[0][1])*g,L=Math.max(L,x)}if(l){let x=0;!E&&!c||E&&!c&&T?x=jt(h+U/g,l[1][1])*g:x=Wt(h+(E?y:-y)/g,l[0][1])*g,L=Math.max(L,x)}}if(u){const v=cs(D*g,f,I)/g;if(P=Math.max(P,v),a){let x=0;!E&&!c||c&&!E&&T?x=Wt(N+D*g+b,a[1][0])/g:x=jt(N+(c?_:-_)*g+b,a[0][0])/g,P=Math.max(P,x)}if(l){let x=0;!E&&!c||c&&!E&&T?x=jt(N+D*g,l[1][0])/g:x=Wt(N+(c?_:-_)*g,l[0][0])/g,P=Math.max(P,x)}}}_=_+(_<0?P:-P),y=y+(y<0?L:-L),o&&(T?U>D*g?_=(Jd(E,c)?-y:y)/g:y=(Jd(E,c)?-_:_)*g:d?(_=y/g,c=E):(y=_*g,E=c));const M=E?N+y:N,w=c?h+_:h;return{width:C+(E?-y:y),height:m+(c?-_:_),x:s[0]*y*(E?-1:1)+M,y:s[1]*_*(c?-1:1)+w}}const cA={width:0,height:0,x:0,y:0},_P={...cA,pointerX:0,pointerY:0,aspectRatio:1};function xP(e){return[[0,0],[e.measured.width,e.measured.height]]}function yP(e,t,n){const r=t.position.x+e.position.x,o=t.position.y+e.position.y,s=e.measured.width??0,a=e.measured.height??0,l=n[0]*s,E=n[1]*a;return[[r-l,o-E],[r+s-l,o+a-E]]}function DP({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:o}){const s=$e(e);let a={controlDirection:zd("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:c,boundaries:d,keepAspectRatio:u,resizeDirection:T,onResizeStart:S,onResize:A,onResizeEnd:f,shouldResize:I}){let p={...cA},O={..._P};a={boundaries:d,resizeDirection:T,keepAspectRatio:u,controlDirection:zd(c)};let N,h=null,C=[],m,g,y,_=!1;const U=If().on("start",D=>{const{nodeLookup:b,transform:F,snapGrid:L,snapToGrid:P,nodeOrigin:M,paneDomNode:w}=n();if(N=b.get(t),!N)return;h=(w==null?void 0:w.getBoundingClientRect())??null;const{xSnapped:v,ySnapped:x}=Gr(D.sourceEvent,{transform:F,snapGrid:L,snapToGrid:P,containerBounds:h});p={width:N.measured.width??0,height:N.measured.height??0,x:N.position.x??0,y:N.position.y??0},O={...p,pointerX:v,pointerY:x,aspectRatio:p.width/p.height},m=void 0,N.parentId&&(N.extent==="parent"||N.expandParent)&&(m=b.get(N.parentId),g=m&&N.extent==="parent"?xP(m):void 0),C=[],y=void 0;for(const[B,H]of b)if(H.parentId===t&&(C.push({id:B,position:{...H.position},extent:H.extent}),H.extent==="parent"||H.expandParent)){const Y=yP(H,N,H.origin??M);y?y=[[Math.min(Y[0][0],y[0][0]),Math.min(Y[0][1],y[0][1])],[Math.max(Y[1][0],y[1][0]),Math.max(Y[1][1],y[1][1])]]:y=Y}S==null||S(D,{...p})}).on("drag",D=>{const{transform:b,snapGrid:F,snapToGrid:L,nodeOrigin:P}=n(),M=Gr(D.sourceEvent,{transform:b,snapGrid:F,snapToGrid:L,containerBounds:h}),w=[];if(!N)return;const{x:v,y:x,width:B,height:H}=p,Y={},K=N.origin??P,{width:X,height:q,x:ee,y:Z}=LP(O,a.controlDirection,M,a.boundaries,a.keepAspectRatio,K,g,y),$=X!==B,z=q!==H,ce=ee!==v&&$,se=Z!==x&&z;if(!ce&&!se&&!$&&!z)return;if((ce||se||K[0]===1||K[1]===1)&&(Y.x=ce?ee:p.x,Y.y=se?Z:p.y,p.x=Y.x,p.y=Y.y,C.length>0)){const Ae=ee-v,ue=Z-x;for(const Re of C)Re.position={x:Re.position.x-Ae+K[0]*(X-B),y:Re.position.y-ue+K[1]*(q-H)},w.push(Re)}if(($||z)&&(Y.width=$&&(!a.resizeDirection||a.resizeDirection==="horizontal")?X:p.width,Y.height=z&&(!a.resizeDirection||a.resizeDirection==="vertical")?q:p.height,p.width=Y.width,p.height=Y.height),m&&N.expandParent){const Ae=K[0]*(Y.width??0);Y.x&&Y.x<Ae&&(p.x=Ae,O.x=O.x-(Y.x-Ae));const ue=K[1]*(Y.height??0);Y.y&&Y.y<ue&&(p.y=ue,O.y=O.y-(Y.y-ue))}const V=gP({width:p.width,prevWidth:B,height:p.height,prevHeight:H,affectsX:a.controlDirection.affectsX,affectsY:a.controlDirection.affectsY}),J={...p,direction:V};(I==null?void 0:I(D,J))!==!1&&(_=!0,A==null||A(D,J),r(Y,w))}).on("end",D=>{_&&(f==null||f(D,{...p}),o==null||o({...p}),_=!1)});s.call(U)}function E(){s.on(".drag",null)}return{update:l,destroy:E}}var Ma={exports:{}},Pa={},ba={exports:{}},va={};/**
485
+ * @license React
486
+ * use-sync-external-store-shim.production.js
487
+ *
488
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
489
+ *
490
+ * This source code is licensed under the MIT license found in the
491
+ * LICENSE file in the root directory of this source tree.
492
+ */var qd;function MP(){if(qd)return va;qd=1;var e=ii();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,s=e.useLayoutEffect,a=e.useDebugValue;function l(u,T){var S=T(),A=r({inst:{value:S,getSnapshot:T}}),f=A[0].inst,I=A[1];return s(function(){f.value=S,f.getSnapshot=T,E(f)&&I({inst:f})},[u,S,T]),o(function(){return E(f)&&I({inst:f}),u(function(){E(f)&&I({inst:f})})},[u]),a(S),S}function E(u){var T=u.getSnapshot;u=u.value;try{var S=T();return!n(u,S)}catch{return!0}}function c(u,T){return T()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?c:l;return va.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:d,va}var Qd;function PP(){return Qd||(Qd=1,ba.exports=MP()),ba.exports}/**
493
+ * @license React
494
+ * use-sync-external-store-shim/with-selector.production.js
495
+ *
496
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
497
+ *
498
+ * This source code is licensed under the MIT license found in the
499
+ * LICENSE file in the root directory of this source tree.
500
+ */var Zd;function bP(){if(Zd)return Pa;Zd=1;var e=ii(),t=PP();function n(c,d){return c===d&&(c!==0||1/c===1/d)||c!==c&&d!==d}var r=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,s=e.useRef,a=e.useEffect,l=e.useMemo,E=e.useDebugValue;return Pa.useSyncExternalStoreWithSelector=function(c,d,u,T,S){var A=s(null);if(A.current===null){var f={hasValue:!1,value:null};A.current=f}else f=A.current;A=l(function(){function p(m){if(!O){if(O=!0,N=m,m=T(m),S!==void 0&&f.hasValue){var g=f.value;if(S(g,m))return h=g}return h=m}if(g=h,r(N,m))return g;var y=T(m);return S!==void 0&&S(g,y)?(N=m,g):(N=m,h=y)}var O=!1,N,h,C=u===void 0?null:u;return[function(){return p(d())},C===null?void 0:function(){return p(C())}]},[d,u,T,S]);var I=o(c,A[0],A[1]);return a(function(){f.hasValue=!0,f.value=I},[I]),E(I),I},Pa}var eu;function vP(){return eu||(eu=1,Ma.exports=bP()),Ma.exports}var UP=vP();const wP=ai(UP),BP={},tu=e=>{let t;const n=new Set,r=(d,u)=>{const T=typeof d=="function"?d(t):d;if(!Object.is(T,t)){const S=t;t=u??(typeof T!="object"||T===null)?T:Object.assign({},t,T),n.forEach(A=>A(t,S))}},o=()=>t,E={setState:r,getState:o,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(BP?"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()}},c=t=e(r,o,E);return E},FP=e=>e?tu(e):tu,{useDebugValue:GP}=me,{useSyncExternalStoreWithSelector:HP}=wP,kP=e=>e;function EA(e,t=kP,n){const r=HP(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return GP(r),r}const nu=(e,t)=>{const n=FP(e),r=(o,s=t)=>EA(n,o,s);return Object.assign(r,n),r},YP=(e,t)=>e?nu(e,t):nu;function Ie(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 Fi=R.createContext(null),jP=Fi.Provider,dA=Ot.error001();function Se(e,t){const n=R.useContext(Fi);if(n===null)throw new Error(dA);return EA(n,e,t)}function Ne(){const e=R.useContext(Fi);if(e===null)throw new Error(dA);return R.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const ru={display:"none"},WP={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},uA="react-flow__node-desc",TA="react-flow__edge-desc",VP="react-flow__aria-live",$P=e=>e.ariaLiveMessage,XP=e=>e.ariaLabelConfig;function KP({rfId:e}){const t=Se($P);return i.jsx("div",{id:`${VP}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:WP,children:t})}function zP({rfId:e,disableKeyboardA11y:t}){const n=Se(XP);return i.jsxs(i.Fragment,{children:[i.jsx("div",{id:`${uA}-${e}`,style:ru,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),i.jsx("div",{id:`${TA}-${e}`,style:ru,children:n["edge.a11yDescription.default"]}),!t&&i.jsx(KP,{rfId:e})]})}const ur=R.forwardRef(({position:e="top-left",children:t,className:n,style:r,...o},s)=>{const a=`${e}`.split("-");return i.jsx("div",{className:Le(["react-flow__panel",n,...a]),style:r,ref:s,...o,children:t})});ur.displayName="Panel";function JP({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:i.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:i.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const qP=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}},Es=e=>e.id;function QP(e,t){return Ie(e.selectedNodes.map(Es),t.selectedNodes.map(Es))&&Ie(e.selectedEdges.map(Es),t.selectedEdges.map(Es))}function ZP({onSelectionChange:e}){const t=Ne(),{selectedNodes:n,selectedEdges:r}=Se(qP,QP);return R.useEffect(()=>{const o={nodes:n,edges:r};e==null||e(o),t.getState().onSelectionChangeHandlers.forEach(s=>s(o))},[n,r,e]),null}const e1=e=>!!e.onSelectionChangeHandlers;function t1({onSelectionChange:e}){const t=Se(e1);return e||t?i.jsx(ZP,{onSelectionChange:e}):null}const SA=[0,0],n1={x:0,y:0,zoom:1},r1=["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"],ou=[...r1,"rfId"],o1=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}),su={translateExtent:eo,nodeOrigin:SA,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function s1(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:o,setTranslateExtent:s,setNodeExtent:a,reset:l,setDefaultNodesAndEdges:E}=Se(o1,Ie),c=Ne();R.useEffect(()=>(E(e.defaultNodes,e.defaultEdges),()=>{d.current=su,l()}),[]);const d=R.useRef(su);return R.useEffect(()=>{for(const u of ou){const T=e[u],S=d.current[u];T!==S&&(typeof e[u]>"u"||(u==="nodes"?t(T):u==="edges"?n(T):u==="minZoom"?r(T):u==="maxZoom"?o(T):u==="translateExtent"?s(T):u==="nodeExtent"?a(T):u==="ariaLabelConfig"?c.setState({ariaLabelConfig:YM(T)}):u==="fitView"?c.setState({fitViewQueued:T}):u==="fitViewOptions"?c.setState({fitViewOptions:T}):c.setState({[u]:T})))}d.current=e},ou.map(u=>e[u])),null}function iu(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function i1(e){var r;const[t,n]=R.useState(e==="system"?null:e);return R.useEffect(()=>{if(e!=="system"){n(e);return}const o=iu(),s=()=>n(o!=null&&o.matches?"dark":"light");return s(),o==null||o.addEventListener("change",s),()=>{o==null||o.removeEventListener("change",s)}},[e]),t!==null?t:(r=iu())!=null&&r.matches?"dark":"light"}const au=typeof document<"u"?document:null;function oo(e=null,t={target:au,actInsideInputWithModifier:!0}){const[n,r]=R.useState(!1),o=R.useRef(!1),s=R.useRef(new Set([])),[a,l]=R.useMemo(()=>{if(e!==null){const c=(Array.isArray(e)?e:[e]).filter(u=>typeof u=="string").map(u=>u.replace("+",`
501
+ `).replace(`
502
+
503
+ `,`
504
+ +`).split(`
505
+ `)),d=c.reduce((u,T)=>u.concat(...T),[]);return[c,d]}return[[],[]]},[e]);return R.useEffect(()=>{const E=(t==null?void 0:t.target)??au,c=(t==null?void 0:t.actInsideInputWithModifier)??!0;if(e!==null){const d=S=>{var I,p;if(o.current=S.ctrlKey||S.metaKey||S.shiftKey||S.altKey,(!o.current||o.current&&!c)&&Xf(S))return!1;const f=cu(S.code,l);if(s.current.add(S[f]),lu(a,s.current,!1)){const O=((p=(I=S.composedPath)==null?void 0:I.call(S))==null?void 0:p[0])||S.target,N=(O==null?void 0:O.nodeName)==="BUTTON"||(O==null?void 0:O.nodeName)==="A";t.preventDefault!==!1&&(o.current||!N)&&S.preventDefault(),r(!0)}},u=S=>{const A=cu(S.code,l);lu(a,s.current,!0)?(r(!1),s.current.clear()):s.current.delete(S[A]),S.key==="Meta"&&s.current.clear(),o.current=!1},T=()=>{s.current.clear(),r(!1)};return E==null||E.addEventListener("keydown",d),E==null||E.addEventListener("keyup",u),window.addEventListener("blur",T),window.addEventListener("contextmenu",T),()=>{E==null||E.removeEventListener("keydown",d),E==null||E.removeEventListener("keyup",u),window.removeEventListener("blur",T),window.removeEventListener("contextmenu",T)}}},[e,r]),n}function lu(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(o=>t.has(o)))}function cu(e,t){return t.includes(e)?"code":"key"}const a1=()=>{const e=Ne();return R.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,s],panZoom:a}=e.getState();return a?(await a.setViewport({x:t.x??r,y:t.y??o,zoom:t.zoom??s},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:s,maxZoom:a,panZoom:l}=e.getState(),E=$c(t,r,o,s,a,(n==null?void 0:n.padding)??.1);return l?(await l.setViewport(E,{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:s,domNode:a}=e.getState();if(!a)return t;const{x:l,y:E}=a.getBoundingClientRect(),c={x:t.x-l,y:t.y-E},d=n.snapGrid??o,u=n.snapToGrid??s;return Io(c,r,u,d)},flowToScreenPosition:t=>{const{transform:n,domNode:r}=e.getState();if(!r)return t;const{x:o,y:s}=r.getBoundingClientRect(),a=Zs(t,n);return{x:a.x+o,y:a.y+s}}}),[])};function RA(e,t){const n=[],r=new Map,o=[];for(const s of e)if(s.type==="add"){o.push(s);continue}else if(s.type==="remove"||s.type==="replace")r.set(s.id,[s]);else{const a=r.get(s.id);a?a.push(s):r.set(s.id,[s])}for(const s of t){const a=r.get(s.id);if(!a){n.push(s);continue}if(a[0].type==="remove")continue;if(a[0].type==="replace"){n.push({...a[0].item});continue}const l={...s};for(const E of a)l1(E,l);n.push(l)}return o.length&&o.forEach(s=>{s.index!==void 0?n.splice(s.index,0,{...s.item}):n.push({...s.item})}),n}function l1(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 fA(e,t){return RA(e,t)}function AA(e,t){return RA(e,t)}function dn(e,t){return{id:e,type:"select",selected:t}}function Xn(e,t=new Set,n=!1){const r=[];for(const[o,s]of e){const a=t.has(o);!(s.selected===void 0&&!a)&&s.selected!==a&&(n&&(s.selected=a),r.push(dn(s.id,a)))}return r}function Eu({items:e=[],lookup:t}){var o;const n=[],r=new Map(e.map(s=>[s.id,s]));for(const[s,a]of e.entries()){const l=t.get(a.id),E=((o=l==null?void 0:l.internals)==null?void 0:o.userNode)??l;E!==void 0&&E!==a&&n.push({id:a.id,item:a,type:"replace"}),E===void 0&&n.push({item:a,type:"add",index:s})}for(const[s]of t)r.get(s)===void 0&&n.push({id:s,type:"remove"});return n}function du(e){return{id:e.id,type:"remove"}}const uu=e=>PM(e),c1=e=>Gf(e);function pA(e){return R.forwardRef(e)}const E1=typeof window<"u"?R.useLayoutEffect:R.useEffect;function Tu(e){const[t,n]=R.useState(BigInt(0)),[r]=R.useState(()=>d1(()=>n(o=>o+BigInt(1))));return E1(()=>{const o=r.get();o.length&&(e(o),r.reset())},[t]),r}function d1(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}const IA=R.createContext(null);function u1({children:e}){const t=Ne(),n=R.useCallback(l=>{const{nodes:E=[],setNodes:c,hasDefaultNodes:d,onNodesChange:u,nodeLookup:T,fitViewQueued:S,onNodesChangeMiddlewareMap:A}=t.getState();let f=E;for(const p of l)f=typeof p=="function"?p(f):p;let I=Eu({items:f,lookup:T});for(const p of A.values())I=p(I);d&&c(f),I.length>0?u==null||u(I):S&&window.requestAnimationFrame(()=>{const{fitViewQueued:p,nodes:O,setNodes:N}=t.getState();p&&N(O)})},[]),r=Tu(n),o=R.useCallback(l=>{const{edges:E=[],setEdges:c,hasDefaultEdges:d,onEdgesChange:u,edgeLookup:T}=t.getState();let S=E;for(const A of l)S=typeof A=="function"?A(S):A;d?c(S):u&&u(Eu({items:S,lookup:T}))},[]),s=Tu(o),a=R.useMemo(()=>({nodeQueue:r,edgeQueue:s}),[]);return i.jsx(IA.Provider,{value:a,children:e})}function T1(){const e=R.useContext(IA);if(!e)throw new Error("useBatchContext must be used within a BatchProvider");return e}const S1=e=>!!e.panZoom;function Zc(){const e=a1(),t=Ne(),n=T1(),r=Se(S1),o=R.useMemo(()=>{const s=u=>t.getState().nodeLookup.get(u),a=u=>{n.nodeQueue.push(u)},l=u=>{n.edgeQueue.push(u)},E=u=>{var p,O;const{nodeLookup:T,nodeOrigin:S}=t.getState(),A=uu(u)?u:T.get(u.id),f=A.parentId?Vf(A.position,A.measured,A.parentId,T,S):A.position,I={...A,position:f,width:((p=A.measured)==null?void 0:p.width)??A.width,height:((O=A.measured)==null?void 0:O.height)??A.height};return cr(I)},c=(u,T,S={replace:!1})=>{a(A=>A.map(f=>{if(f.id===u){const I=typeof T=="function"?T(f):T;return S.replace&&uu(I)?I:{...f,...I}}return f}))},d=(u,T,S={replace:!1})=>{l(A=>A.map(f=>{if(f.id===u){const I=typeof T=="function"?T(f):T;return S.replace&&c1(I)?I:{...f,...I}}return f}))};return{getNodes:()=>t.getState().nodes.map(u=>({...u})),getNode:u=>{var T;return(T=s(u))==null?void 0:T.internals.userNode},getInternalNode:s,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(S=>[...S,...T])},addEdges:u=>{const T=Array.isArray(u)?u:[u];n.edgeQueue.push(S=>[...S,...T])},toObject:()=>{const{nodes:u=[],edges:T=[],transform:S}=t.getState(),[A,f,I]=S;return{nodes:u.map(p=>({...p})),edges:T.map(p=>({...p})),viewport:{x:A,y:f,zoom:I}}},deleteElements:async({nodes:u=[],edges:T=[]})=>{const{nodes:S,edges:A,onNodesDelete:f,onEdgesDelete:I,triggerNodeChanges:p,triggerEdgeChanges:O,onDelete:N,onBeforeDelete:h}=t.getState(),{nodes:C,edges:m}=await BM({nodesToRemove:u,edgesToRemove:T,nodes:S,edges:A,onBeforeDelete:h}),g=m.length>0,y=C.length>0;if(g){const _=m.map(du);I==null||I(m),O(_)}if(y){const _=C.map(du);f==null||f(C),p(_)}return(y||g)&&(N==null||N({nodes:C,edges:m})),{deletedNodes:C,deletedEdges:m}},getIntersectingNodes:(u,T=!0,S)=>{const A=Fd(u),f=A?u:E(u),I=S!==void 0;return f?(S||t.getState().nodes).filter(p=>{const O=t.getState().nodeLookup.get(p.id);if(O&&!A&&(p.id===u.id||!O.internals.positionAbsolute))return!1;const N=cr(I?p:O),h=no(N,f);return T&&h>0||h>=N.width*N.height||h>=f.width*f.height}):[]},isNodeIntersecting:(u,T,S=!0)=>{const f=Fd(u)?u:E(u);if(!f)return!1;const I=no(f,T);return S&&I>0||I>=T.width*T.height||I>=f.width*f.height},updateNode:c,updateNodeData:(u,T,S={replace:!1})=>{c(u,A=>{const f=typeof T=="function"?T(A):T;return S.replace?{...A,data:f}:{...A,data:{...A.data,...f}}},S)},updateEdge:d,updateEdgeData:(u,T,S={replace:!1})=>{d(u,A=>{const f=typeof T=="function"?T(A):T;return S.replace?{...A,data:f}:{...A,data:{...A.data,...f}}},S)},getNodesBounds:u=>{const{nodeLookup:T,nodeOrigin:S}=t.getState();return bM(u,{nodeLookup:T,nodeOrigin:S})},getHandleConnections:({type:u,id:T,nodeId:S})=>{var A;return Array.from(((A=t.getState().connectionLookup.get(`${S}-${u}${T?`-${T}`:""}`))==null?void 0:A.values())??[])},getNodeConnections:({type:u,handleId:T,nodeId:S})=>{var A;return Array.from(((A=t.getState().connectionLookup.get(`${S}${u?T?`-${u}-${T}`:`-${u}`:""}`))==null?void 0:A.values())??[])},fitView:async u=>{const T=t.getState().fitViewResolver??kM();return t.setState({fitViewQueued:!0,fitViewOptions:u,fitViewResolver:T}),n.nodeQueue.push(S=>[...S]),T.promise}}},[]);return R.useMemo(()=>({...o,...e,viewportInitialized:r}),[r])}const Su=e=>e.selected,R1=typeof window<"u"?window:void 0;function f1({deleteKeyCode:e,multiSelectionKeyCode:t}){const n=Ne(),{deleteElements:r}=Zc(),o=oo(e,{actInsideInputWithModifier:!1}),s=oo(t,{target:R1});R.useEffect(()=>{if(o){const{edges:a,nodes:l}=n.getState();r({nodes:l.filter(Su),edges:a.filter(Su)}),n.setState({nodesSelectionActive:!1})}},[o]),R.useEffect(()=>{n.setState({multiSelectionActive:s})},[s])}function A1(e){const t=Ne();R.useEffect(()=>{const n=()=>{var o,s,a,l;if(!e.current||!(((s=(o=e.current).checkVisibility)==null?void 0:s.call(o))??!0))return!1;const r=Xc(e.current);(r.height===0||r.width===0)&&((l=(a=t.getState()).onError)==null||l.call(a,"004",Ot.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 Gi={position:"absolute",width:"100%",height:"100%",top:0,left:0},p1=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function I1({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panOnScrollSpeed:o=.5,panOnScrollMode:s=Rn.Free,zoomOnDoubleClick:a=!0,panOnDrag:l=!0,defaultViewport:E,translateExtent:c,minZoom:d,maxZoom:u,zoomActivationKeyCode:T,preventScrolling:S=!0,children:A,noWheelClassName:f,noPanClassName:I,onViewportChange:p,isControlledViewport:O,paneClickDistance:N,selectionOnDrag:h}){const C=Ne(),m=R.useRef(null),{userSelectionActive:g,lib:y,connectionInProgress:_}=Se(p1,Ie),U=oo(T),D=R.useRef();A1(m);const b=R.useCallback(F=>{p==null||p({x:F[0],y:F[1],zoom:F[2]}),O||C.setState({transform:F})},[p,O]);return R.useEffect(()=>{if(m.current){D.current=CP({domNode:m.current,minZoom:d,maxZoom:u,translateExtent:c,viewport:E,onDraggingChange:M=>C.setState(w=>w.paneDragging===M?w:{paneDragging:M}),onPanZoomStart:(M,w)=>{const{onViewportChangeStart:v,onMoveStart:x}=C.getState();x==null||x(M,w),v==null||v(w)},onPanZoom:(M,w)=>{const{onViewportChange:v,onMove:x}=C.getState();x==null||x(M,w),v==null||v(w)},onPanZoomEnd:(M,w)=>{const{onViewportChangeEnd:v,onMoveEnd:x}=C.getState();x==null||x(M,w),v==null||v(w)}});const{x:F,y:L,zoom:P}=D.current.getViewport();return C.setState({panZoom:D.current,transform:[F,L,P],domNode:m.current.closest(".react-flow")}),()=>{var M;(M=D.current)==null||M.destroy()}}},[]),R.useEffect(()=>{var F;(F=D.current)==null||F.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panOnScrollSpeed:o,panOnScrollMode:s,zoomOnDoubleClick:a,panOnDrag:l,zoomActivationKeyPressed:U,preventScrolling:S,noPanClassName:I,userSelectionActive:g,noWheelClassName:f,lib:y,onTransformChange:b,connectionInProgress:_,selectionOnDrag:h,paneClickDistance:N})},[e,t,n,r,o,s,a,l,U,S,I,g,f,y,b,_,h,N]),i.jsx("div",{className:"react-flow__renderer",ref:m,style:Gi,children:A})}const O1=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function N1(){const{userSelectionActive:e,userSelectionRect:t}=Se(O1,Ie);return e&&t?i.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 Ua=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},h1=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function m1({isSelecting:e,selectionKeyPressed:t,selectionMode:n=to.Full,panOnDrag:r,paneClickDistance:o,selectionOnDrag:s,onSelectionStart:a,onSelectionEnd:l,onPaneClick:E,onPaneContextMenu:c,onPaneScroll:d,onPaneMouseEnter:u,onPaneMouseMove:T,onPaneMouseLeave:S,children:A}){const f=Ne(),{userSelectionActive:I,elementsSelectable:p,dragging:O,connectionInProgress:N}=Se(h1,Ie),h=p&&(e||I),C=R.useRef(null),m=R.useRef(),g=R.useRef(new Set),y=R.useRef(new Set),_=R.useRef(!1),U=v=>{if(_.current||N){_.current=!1;return}E==null||E(v),f.getState().resetSelectedElements(),f.setState({nodesSelectionActive:!1})},D=v=>{if(Array.isArray(r)&&(r!=null&&r.includes(2))){v.preventDefault();return}c==null||c(v)},b=d?v=>d(v):void 0,F=v=>{_.current&&(v.stopPropagation(),_.current=!1)},L=v=>{var q,ee;const{domNode:x}=f.getState();if(m.current=x==null?void 0:x.getBoundingClientRect(),!m.current)return;const B=v.target===C.current;if(!B&&!!v.target.closest(".nokey")||!e||!(s&&B||t)||v.button!==0||!v.isPrimary)return;(ee=(q=v.target)==null?void 0:q.setPointerCapture)==null||ee.call(q,v.pointerId),_.current=!1;const{x:K,y:X}=ot(v.nativeEvent,m.current);f.setState({userSelectionRect:{width:0,height:0,startX:K,startY:X,x:K,y:X}}),B||(v.stopPropagation(),v.preventDefault())},P=v=>{const{userSelectionRect:x,transform:B,nodeLookup:H,edgeLookup:Y,connectionLookup:K,triggerNodeChanges:X,triggerEdgeChanges:q,defaultEdgeOptions:ee,resetSelectedElements:Z}=f.getState();if(!m.current||!x)return;const{x:$,y:z}=ot(v.nativeEvent,m.current),{startX:ce,startY:se}=x;if(!_.current){const ue=t?0:o;if(Math.hypot($-ce,z-se)<=ue)return;Z(),a==null||a(v)}_.current=!0;const V={startX:ce,startY:se,x:$<ce?$:ce,y:z<se?z:se,width:Math.abs($-ce),height:Math.abs(z-se)},J=g.current,Ee=y.current;g.current=new Set(Vc(H,V,B,n===to.Partial,!0).map(ue=>ue.id)),y.current=new Set;const Ae=(ee==null?void 0:ee.selectable)??!0;for(const ue of g.current){const Re=K.get(ue);if(Re)for(const{edgeId:He}of Re.values()){const Pe=Y.get(He);Pe&&(Pe.selectable??Ae)&&y.current.add(He)}}if(!Gd(J,g.current)){const ue=Xn(H,g.current,!0);X(ue)}if(!Gd(Ee,y.current)){const ue=Xn(Y,y.current);q(ue)}f.setState({userSelectionRect:V,userSelectionActive:!0,nodesSelectionActive:!1})},M=v=>{var x,B;v.button===0&&((B=(x=v.target)==null?void 0:x.releasePointerCapture)==null||B.call(x,v.pointerId),!I&&v.target===C.current&&f.getState().userSelectionRect&&(U==null||U(v)),f.setState({userSelectionActive:!1,userSelectionRect:null}),_.current&&(l==null||l(v),f.setState({nodesSelectionActive:g.current.size>0})))},w=r===!0||Array.isArray(r)&&r.includes(0);return i.jsxs("div",{className:Le(["react-flow__pane",{draggable:w,dragging:O,selection:e}]),onClick:h?void 0:Ua(U,C),onContextMenu:Ua(D,C),onWheel:Ua(b,C),onPointerEnter:h?void 0:u,onPointerMove:h?P:T,onPointerUp:h?M:void 0,onPointerDownCapture:h?L:void 0,onClickCapture:h?F:void 0,onPointerLeave:S,ref:C,style:Gi,children:[A,i.jsx(N1,{})]})}function Kl({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:o,unselectNodesAndEdges:s,multiSelectionActive:a,nodeLookup:l,onError:E}=t.getState(),c=l.get(e);if(!c){E==null||E("012",Ot.error012(e));return}t.setState({nodesSelectionActive:!1}),c.selected?(n||c.selected&&a)&&(s({nodes:[c],edges:[]}),requestAnimationFrame(()=>{var d;return(d=r==null?void 0:r.current)==null?void 0:d.blur()})):o([e])}function OA({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:o,isSelectable:s,nodeClickDistance:a}){const l=Ne(),[E,c]=R.useState(!1),d=R.useRef();return R.useEffect(()=>{d.current=EP({getStoreItems:()=>l.getState(),onNodeMouseDown:u=>{Kl({id:u,store:l,nodeRef:e})},onDragStart:()=>{c(!0)},onDragStop:()=>{c(!1)}})},[]),R.useEffect(()=>{if(!(t||!e.current||!d.current))return d.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:s,nodeId:o,nodeClickDistance:a}),()=>{var u;(u=d.current)==null||u.destroy()}},[n,r,t,s,e,o,a]),E}const C1=e=>t=>t.selected&&(t.draggable||e&&typeof t.draggable>"u");function NA(){const e=Ne();return R.useCallback(n=>{const{nodeExtent:r,snapToGrid:o,snapGrid:s,nodesDraggable:a,onError:l,updateNodePositions:E,nodeLookup:c,nodeOrigin:d}=e.getState(),u=new Map,T=C1(a),S=o?s[0]:5,A=o?s[1]:5,f=n.direction.x*S*n.factor,I=n.direction.y*A*n.factor;for(const[,p]of c){if(!T(p))continue;let O={x:p.internals.positionAbsolute.x+f,y:p.internals.positionAbsolute.y+I};o&&(O=po(O,s));const{position:N,positionAbsolute:h}=Hf({nodeId:p.id,nextPosition:O,nodeLookup:c,nodeExtent:r,nodeOrigin:d,onError:l});p.position=N,p.internals.positionAbsolute=h,u.set(p.id,p)}E(u)},[])}const eE=R.createContext(null),g1=eE.Provider;eE.Consumer;const hA=()=>R.useContext(eE),L1=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),_1=(e,t,n)=>r=>{const{connectionClickStartHandle:o,connectionMode:s,connection:a}=r,{fromHandle:l,toHandle:E,isValid:c}=a,d=(E==null?void 0:E.nodeId)===e&&(E==null?void 0:E.id)===t&&(E==null?void 0:E.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:d,clickConnecting:(o==null?void 0:o.nodeId)===e&&(o==null?void 0:o.id)===t&&(o==null?void 0:o.type)===n,isPossibleEndHandle:s===ir.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:d&&c}};function x1({type:e="source",position:t=ne.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:o=!0,isConnectableEnd:s=!0,id:a,onConnect:l,children:E,className:c,onMouseDown:d,onTouchStart:u,...T},S){var P,M;const A=a||null,f=e==="target",I=Ne(),p=hA(),{connectOnClick:O,noPanClassName:N,rfId:h}=Se(L1,Ie),{connectingFrom:C,connectingTo:m,clickConnecting:g,isPossibleEndHandle:y,connectionInProcess:_,clickConnectionInProcess:U,valid:D}=Se(_1(p,A,e),Ie);p||(M=(P=I.getState()).onError)==null||M.call(P,"010",Ot.error010());const b=w=>{const{defaultEdgeOptions:v,onConnect:x,hasDefaultEdges:B}=I.getState(),H={...v,...w};if(B){const{edges:Y,setEdges:K}=I.getState();K(KM(H,Y))}x==null||x(H),l==null||l(H)},F=w=>{if(!p)return;const v=Kf(w.nativeEvent);if(o&&(v&&w.button===0||!v)){const x=I.getState();Xl.onPointerDown(w.nativeEvent,{handleDomNode:w.currentTarget,autoPanOnConnect:x.autoPanOnConnect,connectionMode:x.connectionMode,connectionRadius:x.connectionRadius,domNode:x.domNode,nodeLookup:x.nodeLookup,lib:x.lib,isTarget:f,handleId:A,nodeId:p,flowId:x.rfId,panBy:x.panBy,cancelConnection:x.cancelConnection,onConnectStart:x.onConnectStart,onConnectEnd:(...B)=>{var H,Y;return(Y=(H=I.getState()).onConnectEnd)==null?void 0:Y.call(H,...B)},updateConnection:x.updateConnection,onConnect:b,isValidConnection:n||((...B)=>{var H,Y;return((Y=(H=I.getState()).isValidConnection)==null?void 0:Y.call(H,...B))??!0}),getTransform:()=>I.getState().transform,getFromHandle:()=>I.getState().connection.fromHandle,autoPanSpeed:x.autoPanSpeed,dragThreshold:x.connectionDragThreshold})}v?d==null||d(w):u==null||u(w)},L=w=>{const{onClickConnectStart:v,onClickConnectEnd:x,connectionClickStartHandle:B,connectionMode:H,isValidConnection:Y,lib:K,rfId:X,nodeLookup:q,connection:ee}=I.getState();if(!p||!B&&!o)return;if(!B){v==null||v(w.nativeEvent,{nodeId:p,handleId:A,handleType:e}),I.setState({connectionClickStartHandle:{nodeId:p,type:e,id:A}});return}const Z=$f(w.target),$=n||Y,{connection:z,isValid:ce}=Xl.isValid(w.nativeEvent,{handle:{nodeId:p,id:A,type:e},connectionMode:H,fromNodeId:B.nodeId,fromHandleId:B.id||null,fromType:B.type,isValidConnection:$,flowId:X,doc:Z,lib:K,nodeLookup:q});ce&&z&&b(z);const se=structuredClone(ee);delete se.inProgress,se.toPosition=se.toHandle?se.toHandle.position:null,x==null||x(w,se),I.setState({connectionClickStartHandle:null})};return i.jsx("div",{"data-handleid":A,"data-nodeid":p,"data-handlepos":t,"data-id":`${h}-${p}-${A}-${e}`,className:Le(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",N,c,{source:!f,target:f,connectable:r,connectablestart:o,connectableend:s,clickconnecting:g,connectingfrom:C,connectingto:m,valid:D,connectionindicator:r&&(!_||y)&&(_||U?s:o)}]),onMouseDown:F,onTouchStart:F,onClick:O?L:void 0,ref:S,...T,children:E})}const tn=R.memo(pA(x1));function y1({data:e,isConnectable:t,sourcePosition:n=ne.Bottom}){return i.jsxs(i.Fragment,{children:[e==null?void 0:e.label,i.jsx(tn,{type:"source",position:n,isConnectable:t})]})}function D1({data:e,isConnectable:t,targetPosition:n=ne.Top,sourcePosition:r=ne.Bottom}){return i.jsxs(i.Fragment,{children:[i.jsx(tn,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,i.jsx(tn,{type:"source",position:r,isConnectable:t})]})}function M1(){return null}function P1({data:e,isConnectable:t,targetPosition:n=ne.Top}){return i.jsxs(i.Fragment,{children:[i.jsx(tn,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label]})}const ei={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},Ru={input:y1,default:D1,output:P1,group:M1};function b1(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 v1=e=>{const{width:t,height:n,x:r,y:o}=Ao(e.nodeLookup,{filter:s=>!!s.selected});return{width:rt(t)?t:null,height:rt(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 U1({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=Ne(),{width:o,height:s,transformString:a,userSelectionActive:l}=Se(v1,Ie),E=NA(),c=R.useRef(null);R.useEffect(()=>{var S;n||(S=c.current)==null||S.focus({preventScroll:!0})},[n]);const d=!l&&o!==null&&s!==null;if(OA({nodeRef:c,disabled:!d}),!d)return null;const u=e?S=>{const A=r.getState().nodes.filter(f=>f.selected);e(S,A)}:void 0,T=S=>{Object.prototype.hasOwnProperty.call(ei,S.key)&&(S.preventDefault(),E({direction:ei[S.key],factor:S.shiftKey?4:1}))};return i.jsx("div",{className:Le(["react-flow__nodesselection","react-flow__container",t]),style:{transform:a},children:i.jsx("div",{ref:c,className:"react-flow__nodesselection-rect",onContextMenu:u,tabIndex:n?void 0:-1,onKeyDown:n?void 0:T,style:{width:o,height:s}})})}const fu=typeof window<"u"?window:void 0,w1=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function mA({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:s,onPaneScroll:a,paneClickDistance:l,deleteKeyCode:E,selectionKeyCode:c,selectionOnDrag:d,selectionMode:u,onSelectionStart:T,onSelectionEnd:S,multiSelectionKeyCode:A,panActivationKeyCode:f,zoomActivationKeyCode:I,elementsSelectable:p,zoomOnScroll:O,zoomOnPinch:N,panOnScroll:h,panOnScrollSpeed:C,panOnScrollMode:m,zoomOnDoubleClick:g,panOnDrag:y,defaultViewport:_,translateExtent:U,minZoom:D,maxZoom:b,preventScrolling:F,onSelectionContextMenu:L,noWheelClassName:P,noPanClassName:M,disableKeyboardA11y:w,onViewportChange:v,isControlledViewport:x}){const{nodesSelectionActive:B,userSelectionActive:H}=Se(w1,Ie),Y=oo(c,{target:fu}),K=oo(f,{target:fu}),X=K||y,q=K||h,ee=d&&X!==!0,Z=Y||H||ee;return f1({deleteKeyCode:E,multiSelectionKeyCode:A}),i.jsx(I1,{onPaneContextMenu:s,elementsSelectable:p,zoomOnScroll:O,zoomOnPinch:N,panOnScroll:q,panOnScrollSpeed:C,panOnScrollMode:m,zoomOnDoubleClick:g,panOnDrag:!Y&&X,defaultViewport:_,translateExtent:U,minZoom:D,maxZoom:b,zoomActivationKeyCode:I,preventScrolling:F,noWheelClassName:P,noPanClassName:M,onViewportChange:v,isControlledViewport:x,paneClickDistance:l,selectionOnDrag:ee,children:i.jsxs(m1,{onSelectionStart:T,onSelectionEnd:S,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:s,onPaneScroll:a,panOnDrag:X,isSelecting:!!Z,selectionMode:u,selectionKeyPressed:Y,paneClickDistance:l,selectionOnDrag:ee,children:[e,B&&i.jsx(U1,{onSelectionContextMenu:L,noPanClassName:M,disableKeyboardA11y:w})]})})}mA.displayName="FlowRenderer";const B1=R.memo(mA),F1=e=>t=>e?Vc(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 G1(e){return Se(R.useCallback(F1(e),[e]),Ie)}const H1=e=>e.updateNodeInternals;function k1(){const e=Se(H1),[t]=R.useState(()=>typeof ResizeObserver>"u"?null:new ResizeObserver(n=>{const r=new Map;n.forEach(o=>{const s=o.target.getAttribute("data-id");r.set(s,{id:s,nodeElement:o.target,force:!0})}),e(r)}));return R.useEffect(()=>()=>{t==null||t.disconnect()},[t]),t}function Y1({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){const o=Ne(),s=R.useRef(null),a=R.useRef(null),l=R.useRef(e.sourcePosition),E=R.useRef(e.targetPosition),c=R.useRef(t),d=n&&!!e.internals.handleBounds;return R.useEffect(()=>{s.current&&!e.hidden&&(!d||a.current!==s.current)&&(a.current&&(r==null||r.unobserve(a.current)),r==null||r.observe(s.current),a.current=s.current)},[d,e.hidden]),R.useEffect(()=>()=>{a.current&&(r==null||r.unobserve(a.current),a.current=null)},[]),R.useEffect(()=>{if(s.current){const u=c.current!==t,T=l.current!==e.sourcePosition,S=E.current!==e.targetPosition;(u||T||S)&&(c.current=t,l.current=e.sourcePosition,E.current=e.targetPosition,o.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:s.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),s}function j1({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:o,onContextMenu:s,onDoubleClick:a,nodesDraggable:l,elementsSelectable:E,nodesConnectable:c,nodesFocusable:d,resizeObserver:u,noDragClassName:T,noPanClassName:S,disableKeyboardA11y:A,rfId:f,nodeTypes:I,nodeClickDistance:p,onError:O}){const{node:N,internals:h,isParent:C}=Se($=>{const z=$.nodeLookup.get(e),ce=$.parentLookup.has(e);return{node:z,internals:z.internals,isParent:ce}},Ie);let m=N.type||"default",g=(I==null?void 0:I[m])||Ru[m];g===void 0&&(O==null||O("003",Ot.error003(m)),m="default",g=(I==null?void 0:I.default)||Ru.default);const y=!!(N.draggable||l&&typeof N.draggable>"u"),_=!!(N.selectable||E&&typeof N.selectable>"u"),U=!!(N.connectable||c&&typeof N.connectable>"u"),D=!!(N.focusable||d&&typeof N.focusable>"u"),b=Ne(),F=Wf(N),L=Y1({node:N,nodeType:m,hasDimensions:F,resizeObserver:u}),P=OA({nodeRef:L,disabled:N.hidden||!y,noDragClassName:T,handleSelector:N.dragHandle,nodeId:e,isSelectable:_,nodeClickDistance:p}),M=NA();if(N.hidden)return null;const w=wt(N),v=b1(N),x=_||y||t||n||r||o,B=n?$=>n($,{...h.userNode}):void 0,H=r?$=>r($,{...h.userNode}):void 0,Y=o?$=>o($,{...h.userNode}):void 0,K=s?$=>s($,{...h.userNode}):void 0,X=a?$=>a($,{...h.userNode}):void 0,q=$=>{const{selectNodesOnDrag:z,nodeDragThreshold:ce}=b.getState();_&&(!z||!y||ce>0)&&Kl({id:e,store:b,nodeRef:L}),t&&t($,{...h.userNode})},ee=$=>{if(!(Xf($.nativeEvent)||A)){if(Uf.includes($.key)&&_){const z=$.key==="Escape";Kl({id:e,store:b,unselect:z,nodeRef:L})}else if(y&&N.selected&&Object.prototype.hasOwnProperty.call(ei,$.key)){$.preventDefault();const{ariaLabelConfig:z}=b.getState();b.setState({ariaLiveMessage:z["node.a11yDescription.ariaLiveMessage"]({direction:$.key.replace("Arrow","").toLowerCase(),x:~~h.positionAbsolute.x,y:~~h.positionAbsolute.y})}),M({direction:ei[$.key],factor:$.shiftKey?4:1})}}},Z=()=>{var Ee;if(A||!((Ee=L.current)!=null&&Ee.matches(":focus-visible")))return;const{transform:$,width:z,height:ce,autoPanOnNodeFocus:se,setCenter:V}=b.getState();if(!se)return;Vc(new Map([[e,N]]),{x:0,y:0,width:z,height:ce},$,!0).length>0||V(N.position.x+w.width/2,N.position.y+w.height/2,{zoom:$[2]})};return i.jsx("div",{className:Le(["react-flow__node",`react-flow__node-${m}`,{[S]:y},N.className,{selected:N.selected,selectable:_,parent:C,draggable:y,dragging:P}]),ref:L,style:{zIndex:h.z,transform:`translate(${h.positionAbsolute.x}px,${h.positionAbsolute.y}px)`,pointerEvents:x?"all":"none",visibility:F?"visible":"hidden",...N.style,...v},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:B,onMouseMove:H,onMouseLeave:Y,onContextMenu:K,onClick:q,onDoubleClick:X,onKeyDown:D?ee:void 0,tabIndex:D?0:void 0,onFocus:D?Z:void 0,role:N.ariaRole??(D?"group":void 0),"aria-roledescription":"node","aria-describedby":A?void 0:`${uA}-${f}`,"aria-label":N.ariaLabel,...N.domAttributes,children:i.jsx(g1,{value:e,children:i.jsx(g,{id:e,data:N.data,type:m,positionAbsoluteX:h.positionAbsolute.x,positionAbsoluteY:h.positionAbsolute.y,selected:N.selected??!1,selectable:_,draggable:y,deletable:N.deletable??!0,isConnectable:U,sourcePosition:N.sourcePosition,targetPosition:N.targetPosition,dragging:P,dragHandle:N.dragHandle,zIndex:h.z,parentId:N.parentId,...w})})})}var W1=R.memo(j1);const V1=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function CA(e){const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,onError:s}=Se(V1,Ie),a=G1(e.onlyRenderVisibleElements),l=k1();return i.jsx("div",{className:"react-flow__nodes",style:Gi,children:a.map(E=>i.jsx(W1,{id:E,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:s},E))})}CA.displayName="NodeRenderer";const $1=R.memo(CA);function X1(e){return Se(R.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 s=n.nodeLookup.get(o.source),a=n.nodeLookup.get(o.target);s&&a&&VM({sourceNode:s,targetNode:a,width:n.width,height:n.height,transform:n.transform})&&r.push(o.id)}return r},[e]),Ie)}const K1=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e}};return i.jsx("polyline",{className:"arrow",style:n,strokeLinecap:"round",fill:"none",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4"})},z1=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e,fill:e}};return i.jsx("polyline",{className:"arrowclosed",style:n,strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},Au={[ar.Arrow]:K1,[ar.ArrowClosed]:z1};function J1(e){const t=Ne();return R.useMemo(()=>{var o,s;return Object.prototype.hasOwnProperty.call(Au,e)?Au[e]:((s=(o=t.getState()).onError)==null||s.call(o,"009",Ot.error009(e)),null)},[e])}const q1=({id:e,type:t,color:n,width:r=12.5,height:o=12.5,markerUnits:s="strokeWidth",strokeWidth:a,orient:l="auto-start-reverse"})=>{const E=J1(t);return E?i.jsx("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${o}`,viewBox:"-10 -10 20 20",markerUnits:s,orient:l,refX:"0",refY:"0",children:i.jsx(E,{color:n,strokeWidth:a})}):null},gA=({defaultColor:e,rfId:t})=>{const n=Se(s=>s.edges),r=Se(s=>s.defaultEdgeOptions),o=R.useMemo(()=>ZM(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?i.jsx("svg",{className:"react-flow__marker","aria-hidden":"true",children:i.jsx("defs",{children:o.map(s=>i.jsx(q1,{id:s.id,type:s.type,color:s.color,width:s.width,height:s.height,markerUnits:s.markerUnits,strokeWidth:s.strokeWidth,orient:s.orient},s.id))})}):null};gA.displayName="MarkerDefinitions";var Q1=R.memo(gA);function LA({x:e,y:t,label:n,labelStyle:r,labelShowBg:o=!0,labelBgStyle:s,labelBgPadding:a=[2,4],labelBgBorderRadius:l=2,children:E,className:c,...d}){const[u,T]=R.useState({x:1,y:0,width:0,height:0}),S=Le(["react-flow__edge-textwrapper",c]),A=R.useRef(null);return R.useEffect(()=>{if(A.current){const f=A.current.getBBox();T({x:f.x,y:f.y,width:f.width,height:f.height})}},[n]),n?i.jsxs("g",{transform:`translate(${e-u.width/2} ${t-u.height/2})`,className:S,visibility:u.width?"visible":"hidden",...d,children:[o&&i.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:s,rx:l,ry:l}),i.jsx("text",{className:"react-flow__edge-text",y:u.height/2,dy:"0.3em",ref:A,style:r,children:n}),E]}):null}LA.displayName="EdgeText";const Z1=R.memo(LA);function Hi({path:e,labelX:t,labelY:n,label:r,labelStyle:o,labelShowBg:s,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:E,interactionWidth:c=20,...d}){return i.jsxs(i.Fragment,{children:[i.jsx("path",{...d,d:e,fill:"none",className:Le(["react-flow__edge-path",d.className])}),c?i.jsx("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:c,className:"react-flow__edge-interaction"}):null,r&&rt(t)&&rt(n)?i.jsx(Z1,{x:t,y:n,label:r,labelStyle:o,labelShowBg:s,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:E}):null]})}function pu({pos:e,x1:t,y1:n,x2:r,y2:o}){return e===ne.Left||e===ne.Right?[.5*(t+r),n]:[t,.5*(n+o)]}function _A({sourceX:e,sourceY:t,sourcePosition:n=ne.Bottom,targetX:r,targetY:o,targetPosition:s=ne.Top}){const[a,l]=pu({pos:n,x1:e,y1:t,x2:r,y2:o}),[E,c]=pu({pos:s,x1:r,y1:o,x2:e,y2:t}),[d,u,T,S]=zf({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:a,sourceControlY:l,targetControlX:E,targetControlY:c});return[`M${e},${t} C${a},${l} ${E},${c} ${r},${o}`,d,u,T,S]}function xA(e){return R.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,sourcePosition:a,targetPosition:l,label:E,labelStyle:c,labelShowBg:d,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:S,style:A,markerEnd:f,markerStart:I,interactionWidth:p})=>{const[O,N,h]=_A({sourceX:n,sourceY:r,sourcePosition:a,targetX:o,targetY:s,targetPosition:l}),C=e.isInternal?void 0:t;return i.jsx(Hi,{id:C,path:O,labelX:N,labelY:h,label:E,labelStyle:c,labelShowBg:d,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:S,style:A,markerEnd:f,markerStart:I,interactionWidth:p})})}const eb=xA({isInternal:!1}),yA=xA({isInternal:!0});eb.displayName="SimpleBezierEdge";yA.displayName="SimpleBezierEdgeInternal";function DA(e){return R.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,label:a,labelStyle:l,labelShowBg:E,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:u,style:T,sourcePosition:S=ne.Bottom,targetPosition:A=ne.Top,markerEnd:f,markerStart:I,pathOptions:p,interactionWidth:O})=>{const[N,h,C]=Wl({sourceX:n,sourceY:r,sourcePosition:S,targetX:o,targetY:s,targetPosition:A,borderRadius:p==null?void 0:p.borderRadius,offset:p==null?void 0:p.offset,stepPosition:p==null?void 0:p.stepPosition}),m=e.isInternal?void 0:t;return i.jsx(Hi,{id:m,path:N,labelX:h,labelY:C,label:a,labelStyle:l,labelShowBg:E,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:u,style:T,markerEnd:f,markerStart:I,interactionWidth:O})})}const MA=DA({isInternal:!1}),PA=DA({isInternal:!0});MA.displayName="SmoothStepEdge";PA.displayName="SmoothStepEdgeInternal";function bA(e){return R.memo(({id:t,...n})=>{var o;const r=e.isInternal?void 0:t;return i.jsx(MA,{...n,id:r,pathOptions:R.useMemo(()=>{var s;return{borderRadius:0,offset:(s=n.pathOptions)==null?void 0:s.offset}},[(o=n.pathOptions)==null?void 0:o.offset])})})}const tb=bA({isInternal:!1}),vA=bA({isInternal:!0});tb.displayName="StepEdge";vA.displayName="StepEdgeInternal";function UA(e){return R.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,label:a,labelStyle:l,labelShowBg:E,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:u,style:T,markerEnd:S,markerStart:A,interactionWidth:f})=>{const[I,p,O]=Qf({sourceX:n,sourceY:r,targetX:o,targetY:s}),N=e.isInternal?void 0:t;return i.jsx(Hi,{id:N,path:I,labelX:p,labelY:O,label:a,labelStyle:l,labelShowBg:E,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:u,style:T,markerEnd:S,markerStart:A,interactionWidth:f})})}const nb=UA({isInternal:!1}),wA=UA({isInternal:!0});nb.displayName="StraightEdge";wA.displayName="StraightEdgeInternal";function BA(e){return R.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,sourcePosition:a=ne.Bottom,targetPosition:l=ne.Top,label:E,labelStyle:c,labelShowBg:d,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:S,style:A,markerEnd:f,markerStart:I,pathOptions:p,interactionWidth:O})=>{const[N,h,C]=Jf({sourceX:n,sourceY:r,sourcePosition:a,targetX:o,targetY:s,targetPosition:l,curvature:p==null?void 0:p.curvature}),m=e.isInternal?void 0:t;return i.jsx(Hi,{id:m,path:N,labelX:h,labelY:C,label:E,labelStyle:c,labelShowBg:d,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:S,style:A,markerEnd:f,markerStart:I,interactionWidth:O})})}const rb=BA({isInternal:!1}),FA=BA({isInternal:!0});rb.displayName="BezierEdge";FA.displayName="BezierEdgeInternal";const Iu={default:FA,straight:wA,step:vA,smoothstep:PA,simplebezier:yA},Ou={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},ob=(e,t,n)=>n===ne.Left?e-t:n===ne.Right?e+t:e,sb=(e,t,n)=>n===ne.Top?e-t:n===ne.Bottom?e+t:e,Nu="react-flow__edgeupdater";function hu({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:o,onMouseEnter:s,onMouseOut:a,type:l}){return i.jsx("circle",{onMouseDown:o,onMouseEnter:s,onMouseOut:a,className:Le([Nu,`${Nu}-${l}`]),cx:ob(t,r,e),cy:sb(n,r,e),r,stroke:"transparent",fill:"transparent"})}function ib({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:o,targetX:s,targetY:a,sourcePosition:l,targetPosition:E,onReconnect:c,onReconnectStart:d,onReconnectEnd:u,setReconnecting:T,setUpdateHover:S}){const A=Ne(),f=(h,C)=>{if(h.button!==0)return;const{autoPanOnConnect:m,domNode:g,connectionMode:y,connectionRadius:_,lib:U,onConnectStart:D,cancelConnection:b,nodeLookup:F,rfId:L,panBy:P,updateConnection:M}=A.getState(),w=C.type==="target",v=(H,Y)=>{T(!1),u==null||u(H,n,C.type,Y)},x=H=>c==null?void 0:c(n,H),B=(H,Y)=>{T(!0),d==null||d(h,n,C.type),D==null||D(H,Y)};Xl.onPointerDown(h.nativeEvent,{autoPanOnConnect:m,connectionMode:y,connectionRadius:_,domNode:g,handleId:C.id,nodeId:C.nodeId,nodeLookup:F,isTarget:w,edgeUpdaterType:C.type,lib:U,flowId:L,cancelConnection:b,panBy:P,isValidConnection:(...H)=>{var Y,K;return((K=(Y=A.getState()).isValidConnection)==null?void 0:K.call(Y,...H))??!0},onConnect:x,onConnectStart:B,onConnectEnd:(...H)=>{var Y,K;return(K=(Y=A.getState()).onConnectEnd)==null?void 0:K.call(Y,...H)},onReconnectEnd:v,updateConnection:M,getTransform:()=>A.getState().transform,getFromHandle:()=>A.getState().connection.fromHandle,dragThreshold:A.getState().connectionDragThreshold,handleDomNode:h.currentTarget})},I=h=>f(h,{nodeId:n.target,id:n.targetHandle??null,type:"target"}),p=h=>f(h,{nodeId:n.source,id:n.sourceHandle??null,type:"source"}),O=()=>S(!0),N=()=>S(!1);return i.jsxs(i.Fragment,{children:[(e===!0||e==="source")&&i.jsx(hu,{position:l,centerX:r,centerY:o,radius:t,onMouseDown:I,onMouseEnter:O,onMouseOut:N,type:"source"}),(e===!0||e==="target")&&i.jsx(hu,{position:E,centerX:s,centerY:a,radius:t,onMouseDown:p,onMouseEnter:O,onMouseOut:N,type:"target"})]})}function ab({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:o,onDoubleClick:s,onContextMenu:a,onMouseEnter:l,onMouseMove:E,onMouseLeave:c,reconnectRadius:d,onReconnect:u,onReconnectStart:T,onReconnectEnd:S,rfId:A,edgeTypes:f,noPanClassName:I,onError:p,disableKeyboardA11y:O}){let N=Se(V=>V.edgeLookup.get(e));const h=Se(V=>V.defaultEdgeOptions);N=h?{...h,...N}:N;let C=N.type||"default",m=(f==null?void 0:f[C])||Iu[C];m===void 0&&(p==null||p("011",Ot.error011(C)),C="default",m=(f==null?void 0:f.default)||Iu.default);const g=!!(N.focusable||t&&typeof N.focusable>"u"),y=typeof u<"u"&&(N.reconnectable||n&&typeof N.reconnectable>"u"),_=!!(N.selectable||r&&typeof N.selectable>"u"),U=R.useRef(null),[D,b]=R.useState(!1),[F,L]=R.useState(!1),P=Ne(),{zIndex:M,sourceX:w,sourceY:v,targetX:x,targetY:B,sourcePosition:H,targetPosition:Y}=Se(R.useCallback(V=>{const J=V.nodeLookup.get(N.source),Ee=V.nodeLookup.get(N.target);if(!J||!Ee)return{zIndex:N.zIndex,...Ou};const Ae=QM({id:e,sourceNode:J,targetNode:Ee,sourceHandle:N.sourceHandle||null,targetHandle:N.targetHandle||null,connectionMode:V.connectionMode,onError:p});return{zIndex:WM({selected:N.selected,zIndex:N.zIndex,sourceNode:J,targetNode:Ee,elevateOnSelect:V.elevateEdgesOnSelect,zIndexMode:V.zIndexMode}),...Ae||Ou}},[N.source,N.target,N.sourceHandle,N.targetHandle,N.selected,N.zIndex]),Ie),K=R.useMemo(()=>N.markerStart?`url('#${Vl(N.markerStart,A)}')`:void 0,[N.markerStart,A]),X=R.useMemo(()=>N.markerEnd?`url('#${Vl(N.markerEnd,A)}')`:void 0,[N.markerEnd,A]);if(N.hidden||w===null||v===null||x===null||B===null)return null;const q=V=>{var ue;const{addSelectedEdges:J,unselectNodesAndEdges:Ee,multiSelectionActive:Ae}=P.getState();_&&(P.setState({nodesSelectionActive:!1}),N.selected&&Ae?(Ee({nodes:[],edges:[N]}),(ue=U.current)==null||ue.blur()):J([e])),o&&o(V,N)},ee=s?V=>{s(V,{...N})}:void 0,Z=a?V=>{a(V,{...N})}:void 0,$=l?V=>{l(V,{...N})}:void 0,z=E?V=>{E(V,{...N})}:void 0,ce=c?V=>{c(V,{...N})}:void 0,se=V=>{var J;if(!O&&Uf.includes(V.key)&&_){const{unselectNodesAndEdges:Ee,addSelectedEdges:Ae}=P.getState();V.key==="Escape"?((J=U.current)==null||J.blur(),Ee({edges:[N]})):Ae([e])}};return i.jsx("svg",{style:{zIndex:M},children:i.jsxs("g",{className:Le(["react-flow__edge",`react-flow__edge-${C}`,N.className,I,{selected:N.selected,animated:N.animated,inactive:!_&&!o,updating:D,selectable:_}]),onClick:q,onDoubleClick:ee,onContextMenu:Z,onMouseEnter:$,onMouseMove:z,onMouseLeave:ce,onKeyDown:g?se:void 0,tabIndex:g?0:void 0,role:N.ariaRole??(g?"group":"img"),"aria-roledescription":"edge","data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":N.ariaLabel===null?void 0:N.ariaLabel||`Edge from ${N.source} to ${N.target}`,"aria-describedby":g?`${TA}-${A}`:void 0,ref:U,...N.domAttributes,children:[!F&&i.jsx(m,{id:e,source:N.source,target:N.target,type:N.type,selected:N.selected,animated:N.animated,selectable:_,deletable:N.deletable??!0,label:N.label,labelStyle:N.labelStyle,labelShowBg:N.labelShowBg,labelBgStyle:N.labelBgStyle,labelBgPadding:N.labelBgPadding,labelBgBorderRadius:N.labelBgBorderRadius,sourceX:w,sourceY:v,targetX:x,targetY:B,sourcePosition:H,targetPosition:Y,data:N.data,style:N.style,sourceHandleId:N.sourceHandle,targetHandleId:N.targetHandle,markerStart:K,markerEnd:X,pathOptions:"pathOptions"in N?N.pathOptions:void 0,interactionWidth:N.interactionWidth}),y&&i.jsx(ib,{edge:N,isReconnectable:y,reconnectRadius:d,onReconnect:u,onReconnectStart:T,onReconnectEnd:S,sourceX:w,sourceY:v,targetX:x,targetY:B,sourcePosition:H,targetPosition:Y,setUpdateHover:b,setReconnecting:L})]})})}var lb=R.memo(ab);const cb=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function GA({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:o,onReconnect:s,onEdgeContextMenu:a,onEdgeMouseEnter:l,onEdgeMouseMove:E,onEdgeMouseLeave:c,onEdgeClick:d,reconnectRadius:u,onEdgeDoubleClick:T,onReconnectStart:S,onReconnectEnd:A,disableKeyboardA11y:f}){const{edgesFocusable:I,edgesReconnectable:p,elementsSelectable:O,onError:N}=Se(cb,Ie),h=X1(t);return i.jsxs("div",{className:"react-flow__edges",children:[i.jsx(Q1,{defaultColor:e,rfId:n}),h.map(C=>i.jsx(lb,{id:C,edgesFocusable:I,edgesReconnectable:p,elementsSelectable:O,noPanClassName:o,onReconnect:s,onContextMenu:a,onMouseEnter:l,onMouseMove:E,onMouseLeave:c,onClick:d,reconnectRadius:u,onDoubleClick:T,onReconnectStart:S,onReconnectEnd:A,rfId:n,onError:N,edgeTypes:r,disableKeyboardA11y:f},C))]})}GA.displayName="EdgeRenderer";const Eb=R.memo(GA),db=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function ub({children:e}){const t=Se(db);return i.jsx("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:t},children:e})}function Tb(e){const t=Zc(),n=R.useRef(!1);R.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const Sb=e=>{var t;return(t=e.panZoom)==null?void 0:t.syncViewport};function Rb(e){const t=Se(Sb),n=Ne();return R.useEffect(()=>{e&&(t==null||t(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function fb(e){return e.connection.inProgress?{...e.connection,to:Io(e.connection.to,e.transform)}:{...e.connection}}function Ab(e){return fb}function pb(e){const t=Ab();return Se(t,Ie)}const Ib=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function Ob({containerStyle:e,style:t,type:n,component:r}){const{nodesConnectable:o,width:s,height:a,isValid:l,inProgress:E}=Se(Ib,Ie);return!(s&&o&&E)?null:i.jsx("svg",{style:e,width:s,height:a,className:"react-flow__connectionline react-flow__container",children:i.jsx("g",{className:Le(["react-flow__connection",Ff(l)]),children:i.jsx(HA,{style:t,type:n,CustomComponent:r,isValid:l})})})}const HA=({style:e,type:t=$t.Bezier,CustomComponent:n,isValid:r})=>{const{inProgress:o,from:s,fromNode:a,fromHandle:l,fromPosition:E,to:c,toNode:d,toHandle:u,toPosition:T,pointer:S}=pb();if(!o)return;if(n)return i.jsx(n,{connectionLineType:t,connectionLineStyle:e,fromNode:a,fromHandle:l,fromX:s.x,fromY:s.y,toX:c.x,toY:c.y,fromPosition:E,toPosition:T,connectionStatus:Ff(r),toNode:d,toHandle:u,pointer:S});let A="";const f={sourceX:s.x,sourceY:s.y,sourcePosition:E,targetX:c.x,targetY:c.y,targetPosition:T};switch(t){case $t.Bezier:[A]=Jf(f);break;case $t.SimpleBezier:[A]=_A(f);break;case $t.Step:[A]=Wl({...f,borderRadius:0});break;case $t.SmoothStep:[A]=Wl(f);break;default:[A]=Qf(f)}return i.jsx("path",{d:A,fill:"none",className:"react-flow__connection-path",style:e})};HA.displayName="ConnectionLine";const Nb={};function mu(e=Nb){R.useRef(e),Ne(),R.useEffect(()=>{},[e])}function hb(){Ne(),R.useRef(!1),R.useEffect(()=>{},[])}function kA({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:o,onNodeDoubleClick:s,onEdgeDoubleClick:a,onNodeMouseEnter:l,onNodeMouseMove:E,onNodeMouseLeave:c,onNodeContextMenu:d,onSelectionContextMenu:u,onSelectionStart:T,onSelectionEnd:S,connectionLineType:A,connectionLineStyle:f,connectionLineComponent:I,connectionLineContainerStyle:p,selectionKeyCode:O,selectionOnDrag:N,selectionMode:h,multiSelectionKeyCode:C,panActivationKeyCode:m,zoomActivationKeyCode:g,deleteKeyCode:y,onlyRenderVisibleElements:_,elementsSelectable:U,defaultViewport:D,translateExtent:b,minZoom:F,maxZoom:L,preventScrolling:P,defaultMarkerColor:M,zoomOnScroll:w,zoomOnPinch:v,panOnScroll:x,panOnScrollSpeed:B,panOnScrollMode:H,zoomOnDoubleClick:Y,panOnDrag:K,onPaneClick:X,onPaneMouseEnter:q,onPaneMouseMove:ee,onPaneMouseLeave:Z,onPaneScroll:$,onPaneContextMenu:z,paneClickDistance:ce,nodeClickDistance:se,onEdgeContextMenu:V,onEdgeMouseEnter:J,onEdgeMouseMove:Ee,onEdgeMouseLeave:Ae,reconnectRadius:ue,onReconnect:Re,onReconnectStart:He,onReconnectEnd:Pe,noDragClassName:dt,noWheelClassName:an,noPanClassName:Bt,disableKeyboardA11y:Dn,nodeExtent:No,rfId:Ft,viewport:mt,onViewportChange:Gt}){return mu(e),mu(t),hb(),Tb(n),Rb(mt),i.jsx(B1,{onPaneClick:X,onPaneMouseEnter:q,onPaneMouseMove:ee,onPaneMouseLeave:Z,onPaneContextMenu:z,onPaneScroll:$,paneClickDistance:ce,deleteKeyCode:y,selectionKeyCode:O,selectionOnDrag:N,selectionMode:h,onSelectionStart:T,onSelectionEnd:S,multiSelectionKeyCode:C,panActivationKeyCode:m,zoomActivationKeyCode:g,elementsSelectable:U,zoomOnScroll:w,zoomOnPinch:v,zoomOnDoubleClick:Y,panOnScroll:x,panOnScrollSpeed:B,panOnScrollMode:H,panOnDrag:K,defaultViewport:D,translateExtent:b,minZoom:F,maxZoom:L,onSelectionContextMenu:u,preventScrolling:P,noDragClassName:dt,noWheelClassName:an,noPanClassName:Bt,disableKeyboardA11y:Dn,onViewportChange:Gt,isControlledViewport:!!mt,children:i.jsxs(ub,{children:[i.jsx(Eb,{edgeTypes:t,onEdgeClick:o,onEdgeDoubleClick:a,onReconnect:Re,onReconnectStart:He,onReconnectEnd:Pe,onlyRenderVisibleElements:_,onEdgeContextMenu:V,onEdgeMouseEnter:J,onEdgeMouseMove:Ee,onEdgeMouseLeave:Ae,reconnectRadius:ue,defaultMarkerColor:M,noPanClassName:Bt,disableKeyboardA11y:Dn,rfId:Ft}),i.jsx(Ob,{style:f,type:A,component:I,containerStyle:p}),i.jsx("div",{className:"react-flow__edgelabel-renderer"}),i.jsx($1,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:s,onNodeMouseEnter:l,onNodeMouseMove:E,onNodeMouseLeave:c,onNodeContextMenu:d,nodeClickDistance:se,onlyRenderVisibleElements:_,noPanClassName:Bt,noDragClassName:dt,disableKeyboardA11y:Dn,nodeExtent:No,rfId:Ft}),i.jsx("div",{className:"react-flow__viewport-portal"})]})})}kA.displayName="GraphView";const mb=R.memo(kA),Cu=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:a,fitViewOptions:l,minZoom:E=.5,maxZoom:c=2,nodeOrigin:d,nodeExtent:u,zIndexMode:T="basic"}={})=>{const S=new Map,A=new Map,f=new Map,I=new Map,p=r??t??[],O=n??e??[],N=d??[0,0],h=u??eo;tA(f,I,p);const C=$l(O,S,A,{nodeOrigin:N,nodeExtent:h,zIndexMode:T});let m=[0,0,1];if(a&&o&&s){const g=Ao(S,{filter:D=>!!((D.width||D.initialWidth)&&(D.height||D.initialHeight))}),{x:y,y:_,zoom:U}=$c(g,o,s,E,c,(l==null?void 0:l.padding)??.1);m=[y,_,U]}return{rfId:"1",width:o??0,height:s??0,transform:m,nodes:O,nodesInitialized:C,nodeLookup:S,parentLookup:A,edges:p,edgeLookup:I,connectionLookup:f,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:E,maxZoom:c,translateExtent:eo,nodeExtent:h,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:ir.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:N,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:{...Bf},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:FM,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:wf,zIndexMode:T,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},Cb=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:a,fitViewOptions:l,minZoom:E,maxZoom:c,nodeOrigin:d,nodeExtent:u,zIndexMode:T})=>YP((S,A)=>{async function f(){const{nodeLookup:I,panZoom:p,fitViewOptions:O,fitViewResolver:N,width:h,height:C,minZoom:m,maxZoom:g}=A();p&&(await wM({nodes:I,width:h,height:C,panZoom:p,minZoom:m,maxZoom:g},O),N==null||N.resolve(!0),S({fitViewResolver:null}))}return{...Cu({nodes:e,edges:t,width:o,height:s,fitView:a,fitViewOptions:l,minZoom:E,maxZoom:c,nodeOrigin:d,nodeExtent:u,defaultNodes:n,defaultEdges:r,zIndexMode:T}),setNodes:I=>{const{nodeLookup:p,parentLookup:O,nodeOrigin:N,elevateNodesOnSelect:h,fitViewQueued:C,zIndexMode:m}=A(),g=$l(I,p,O,{nodeOrigin:N,nodeExtent:u,elevateNodesOnSelect:h,checkEquality:!0,zIndexMode:m});C&&g?(f(),S({nodes:I,nodesInitialized:g,fitViewQueued:!1,fitViewOptions:void 0})):S({nodes:I,nodesInitialized:g})},setEdges:I=>{const{connectionLookup:p,edgeLookup:O}=A();tA(p,O,I),S({edges:I})},setDefaultNodesAndEdges:(I,p)=>{if(I){const{setNodes:O}=A();O(I),S({hasDefaultNodes:!0})}if(p){const{setEdges:O}=A();O(p),S({hasDefaultEdges:!0})}},updateNodeInternals:I=>{const{triggerNodeChanges:p,nodeLookup:O,parentLookup:N,domNode:h,nodeOrigin:C,nodeExtent:m,debug:g,fitViewQueued:y,zIndexMode:_}=A(),{changes:U,updatedInternals:D}=iP(I,O,N,h,C,m,_);D&&(nP(O,N,{nodeOrigin:C,nodeExtent:m,zIndexMode:_}),y?(f(),S({fitViewQueued:!1,fitViewOptions:void 0})):S({}),(U==null?void 0:U.length)>0&&(g&&console.log("React Flow: trigger node changes",U),p==null||p(U)))},updateNodePositions:(I,p=!1)=>{const O=[];let N=[];const{nodeLookup:h,triggerNodeChanges:C,connection:m,updateConnection:g,onNodesChangeMiddlewareMap:y}=A();for(const[_,U]of I){const D=h.get(_),b=!!(D!=null&&D.expandParent&&(D!=null&&D.parentId)&&(U!=null&&U.position)),F={id:_,type:"position",position:b?{x:Math.max(0,U.position.x),y:Math.max(0,U.position.y)}:U.position,dragging:p};if(D&&m.inProgress&&m.fromNode.id===D.id){const L=hn(D,m.fromHandle,ne.Left,!0);g({...m,from:L})}b&&D.parentId&&O.push({id:_,parentId:D.parentId,rect:{...U.internals.positionAbsolute,width:U.measured.width??0,height:U.measured.height??0}}),N.push(F)}if(O.length>0){const{parentLookup:_,nodeOrigin:U}=A(),D=Qc(O,h,_,U);N.push(...D)}for(const _ of y.values())N=_(N);C(N)},triggerNodeChanges:I=>{const{onNodesChange:p,setNodes:O,nodes:N,hasDefaultNodes:h,debug:C}=A();if(I!=null&&I.length){if(h){const m=fA(I,N);O(m)}C&&console.log("React Flow: trigger node changes",I),p==null||p(I)}},triggerEdgeChanges:I=>{const{onEdgesChange:p,setEdges:O,edges:N,hasDefaultEdges:h,debug:C}=A();if(I!=null&&I.length){if(h){const m=AA(I,N);O(m)}C&&console.log("React Flow: trigger edge changes",I),p==null||p(I)}},addSelectedNodes:I=>{const{multiSelectionActive:p,edgeLookup:O,nodeLookup:N,triggerNodeChanges:h,triggerEdgeChanges:C}=A();if(p){const m=I.map(g=>dn(g,!0));h(m);return}h(Xn(N,new Set([...I]),!0)),C(Xn(O))},addSelectedEdges:I=>{const{multiSelectionActive:p,edgeLookup:O,nodeLookup:N,triggerNodeChanges:h,triggerEdgeChanges:C}=A();if(p){const m=I.map(g=>dn(g,!0));C(m);return}C(Xn(O,new Set([...I]))),h(Xn(N,new Set,!0))},unselectNodesAndEdges:({nodes:I,edges:p}={})=>{const{edges:O,nodes:N,nodeLookup:h,triggerNodeChanges:C,triggerEdgeChanges:m}=A(),g=I||N,y=p||O,_=[];for(const D of g){if(!D.selected)continue;const b=h.get(D.id);b&&(b.selected=!1),_.push(dn(D.id,!1))}const U=[];for(const D of y)D.selected&&U.push(dn(D.id,!1));C(_),m(U)},setMinZoom:I=>{const{panZoom:p,maxZoom:O}=A();p==null||p.setScaleExtent([I,O]),S({minZoom:I})},setMaxZoom:I=>{const{panZoom:p,minZoom:O}=A();p==null||p.setScaleExtent([O,I]),S({maxZoom:I})},setTranslateExtent:I=>{var p;(p=A().panZoom)==null||p.setTranslateExtent(I),S({translateExtent:I})},resetSelectedElements:()=>{const{edges:I,nodes:p,triggerNodeChanges:O,triggerEdgeChanges:N,elementsSelectable:h}=A();if(!h)return;const C=p.reduce((g,y)=>y.selected?[...g,dn(y.id,!1)]:g,[]),m=I.reduce((g,y)=>y.selected?[...g,dn(y.id,!1)]:g,[]);O(C),N(m)},setNodeExtent:I=>{const{nodes:p,nodeLookup:O,parentLookup:N,nodeOrigin:h,elevateNodesOnSelect:C,nodeExtent:m,zIndexMode:g}=A();I[0][0]===m[0][0]&&I[0][1]===m[0][1]&&I[1][0]===m[1][0]&&I[1][1]===m[1][1]||($l(p,O,N,{nodeOrigin:h,nodeExtent:I,elevateNodesOnSelect:C,checkEquality:!1,zIndexMode:g}),S({nodeExtent:I}))},panBy:I=>{const{transform:p,width:O,height:N,panZoom:h,translateExtent:C}=A();return aP({delta:I,panZoom:h,transform:p,translateExtent:C,width:O,height:N})},setCenter:async(I,p,O)=>{const{width:N,height:h,maxZoom:C,panZoom:m}=A();if(!m)return Promise.resolve(!1);const g=typeof(O==null?void 0:O.zoom)<"u"?O.zoom:C;return await m.setViewport({x:N/2-I*g,y:h/2-p*g,zoom:g},{duration:O==null?void 0:O.duration,ease:O==null?void 0:O.ease,interpolate:O==null?void 0:O.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{S({connection:{...Bf}})},updateConnection:I=>{S({connection:I})},reset:()=>S({...Cu()})}},Object.is);function gb({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:o,initialHeight:s,initialMinZoom:a,initialMaxZoom:l,initialFitViewOptions:E,fitView:c,nodeOrigin:d,nodeExtent:u,zIndexMode:T,children:S}){const[A]=R.useState(()=>Cb({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:c,minZoom:a,maxZoom:l,fitViewOptions:E,nodeOrigin:d,nodeExtent:u,zIndexMode:T}));return i.jsx(jP,{value:A,children:i.jsx(u1,{children:S})})}function Lb({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:o,width:s,height:a,fitView:l,fitViewOptions:E,minZoom:c,maxZoom:d,nodeOrigin:u,nodeExtent:T,zIndexMode:S}){return R.useContext(Fi)?i.jsx(i.Fragment,{children:e}):i.jsx(gb,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:o,initialWidth:s,initialHeight:a,fitView:l,initialFitViewOptions:E,initialMinZoom:c,initialMaxZoom:d,nodeOrigin:u,nodeExtent:T,zIndexMode:S,children:e})}const _b={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};function xb({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:o,nodeTypes:s,edgeTypes:a,onNodeClick:l,onEdgeClick:E,onInit:c,onMove:d,onMoveStart:u,onMoveEnd:T,onConnect:S,onConnectStart:A,onConnectEnd:f,onClickConnectStart:I,onClickConnectEnd:p,onNodeMouseEnter:O,onNodeMouseMove:N,onNodeMouseLeave:h,onNodeContextMenu:C,onNodeDoubleClick:m,onNodeDragStart:g,onNodeDrag:y,onNodeDragStop:_,onNodesDelete:U,onEdgesDelete:D,onDelete:b,onSelectionChange:F,onSelectionDragStart:L,onSelectionDrag:P,onSelectionDragStop:M,onSelectionContextMenu:w,onSelectionStart:v,onSelectionEnd:x,onBeforeDelete:B,connectionMode:H,connectionLineType:Y=$t.Bezier,connectionLineStyle:K,connectionLineComponent:X,connectionLineContainerStyle:q,deleteKeyCode:ee="Backspace",selectionKeyCode:Z="Shift",selectionOnDrag:$=!1,selectionMode:z=to.Full,panActivationKeyCode:ce="Space",multiSelectionKeyCode:se=ro()?"Meta":"Control",zoomActivationKeyCode:V=ro()?"Meta":"Control",snapToGrid:J,snapGrid:Ee,onlyRenderVisibleElements:Ae=!1,selectNodesOnDrag:ue,nodesDraggable:Re,autoPanOnNodeFocus:He,nodesConnectable:Pe,nodesFocusable:dt,nodeOrigin:an=SA,edgesFocusable:Bt,edgesReconnectable:Dn,elementsSelectable:No=!0,defaultViewport:Ft=n1,minZoom:mt=.5,maxZoom:Gt=2,translateExtent:ho=eo,preventScrolling:mo=!0,nodeExtent:Or,defaultMarkerColor:Co="#b1b1b7",zoomOnScroll:Wi=!0,zoomOnPinch:Ht=!0,panOnScroll:go=!1,panOnScrollSpeed:kt=.5,panOnScrollMode:Lo=Rn.Free,zoomOnDoubleClick:Mn=!0,panOnDrag:Nr=!0,onPaneClick:Ze,onPaneMouseEnter:Vi,onPaneMouseMove:$i,onPaneMouseLeave:Xi,onPaneScroll:Pn,onPaneContextMenu:ln,paneClickDistance:Ki=1,nodeClickDistance:zi=0,children:hr,onReconnect:Ji,onReconnectStart:_o,onReconnectEnd:bn,onEdgeContextMenu:ut,onEdgeDoubleClick:ke,onEdgeMouseEnter:xo,onEdgeMouseMove:yo,onEdgeMouseLeave:Do,reconnectRadius:qi=10,onNodesChange:Qi,onEdgesChange:Mo,noDragClassName:Zi="nodrag",noWheelClassName:ea="nowheel",noPanClassName:Po="nopan",fitView:bo,fitViewOptions:vo,connectOnClick:ta,attributionPosition:Uo,proOptions:wo,defaultEdgeOptions:Bo,elevateNodesOnSelect:Fo=!0,elevateEdgesOnSelect:Go=!1,disableKeyboardA11y:mr=!1,autoPanOnConnect:Ho,autoPanOnNodeDrag:ko,autoPanSpeed:Yo,connectionRadius:k,isValidConnection:le,onError:he,style:ge,id:Yt,nodeDragThreshold:Cr,connectionDragThreshold:gr,viewport:kp,onViewportChange:Yp,width:jp,height:Wp,colorMode:Vp="light",debug:$p,onScroll:jo,ariaLabelConfig:Xp,zIndexMode:aE="basic",...Kp},zp){const na=Yt||"1",Jp=i1(Vp),qp=R.useCallback(lE=>{lE.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),jo==null||jo(lE)},[jo]);return i.jsx("div",{"data-testid":"rf__wrapper",...Kp,onScroll:qp,style:{...ge,..._b},ref:zp,className:Le(["react-flow",o,Jp]),id:Yt,role:"application",children:i.jsxs(Lb,{nodes:e,edges:t,width:jp,height:Wp,fitView:bo,fitViewOptions:vo,minZoom:mt,maxZoom:Gt,nodeOrigin:an,nodeExtent:Or,zIndexMode:aE,children:[i.jsx(mb,{onInit:c,onNodeClick:l,onEdgeClick:E,onNodeMouseEnter:O,onNodeMouseMove:N,onNodeMouseLeave:h,onNodeContextMenu:C,onNodeDoubleClick:m,nodeTypes:s,edgeTypes:a,connectionLineType:Y,connectionLineStyle:K,connectionLineComponent:X,connectionLineContainerStyle:q,selectionKeyCode:Z,selectionOnDrag:$,selectionMode:z,deleteKeyCode:ee,multiSelectionKeyCode:se,panActivationKeyCode:ce,zoomActivationKeyCode:V,onlyRenderVisibleElements:Ae,defaultViewport:Ft,translateExtent:ho,minZoom:mt,maxZoom:Gt,preventScrolling:mo,zoomOnScroll:Wi,zoomOnPinch:Ht,zoomOnDoubleClick:Mn,panOnScroll:go,panOnScrollSpeed:kt,panOnScrollMode:Lo,panOnDrag:Nr,onPaneClick:Ze,onPaneMouseEnter:Vi,onPaneMouseMove:$i,onPaneMouseLeave:Xi,onPaneScroll:Pn,onPaneContextMenu:ln,paneClickDistance:Ki,nodeClickDistance:zi,onSelectionContextMenu:w,onSelectionStart:v,onSelectionEnd:x,onReconnect:Ji,onReconnectStart:_o,onReconnectEnd:bn,onEdgeContextMenu:ut,onEdgeDoubleClick:ke,onEdgeMouseEnter:xo,onEdgeMouseMove:yo,onEdgeMouseLeave:Do,reconnectRadius:qi,defaultMarkerColor:Co,noDragClassName:Zi,noWheelClassName:ea,noPanClassName:Po,rfId:na,disableKeyboardA11y:mr,nodeExtent:Or,viewport:kp,onViewportChange:Yp}),i.jsx(s1,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:S,onConnectStart:A,onConnectEnd:f,onClickConnectStart:I,onClickConnectEnd:p,nodesDraggable:Re,autoPanOnNodeFocus:He,nodesConnectable:Pe,nodesFocusable:dt,edgesFocusable:Bt,edgesReconnectable:Dn,elementsSelectable:No,elevateNodesOnSelect:Fo,elevateEdgesOnSelect:Go,minZoom:mt,maxZoom:Gt,nodeExtent:Or,onNodesChange:Qi,onEdgesChange:Mo,snapToGrid:J,snapGrid:Ee,connectionMode:H,translateExtent:ho,connectOnClick:ta,defaultEdgeOptions:Bo,fitView:bo,fitViewOptions:vo,onNodesDelete:U,onEdgesDelete:D,onDelete:b,onNodeDragStart:g,onNodeDrag:y,onNodeDragStop:_,onSelectionDrag:P,onSelectionDragStart:L,onSelectionDragStop:M,onMove:d,onMoveStart:u,onMoveEnd:T,noPanClassName:Po,nodeOrigin:an,rfId:na,autoPanOnConnect:Ho,autoPanOnNodeDrag:ko,autoPanSpeed:Yo,onError:he,connectionRadius:k,isValidConnection:le,selectNodesOnDrag:ue,nodeDragThreshold:Cr,connectionDragThreshold:gr,onBeforeDelete:B,debug:$p,ariaLabelConfig:Xp,zIndexMode:aE}),i.jsx(t1,{onSelectionChange:F}),hr,i.jsx(JP,{proOptions:wo,position:Uo}),i.jsx(zP,{rfId:na,disableKeyboardA11y:mr})]})})}var YA=pA(xb);function jA(e){const[t,n]=R.useState(e),r=R.useCallback(o=>n(s=>fA(o,s)),[]);return[t,n,r]}function WA(e){const[t,n]=R.useState(e),r=R.useCallback(o=>n(s=>AA(o,s)),[]);return[t,n,r]}function yb({dimensions:e,lineWidth:t,variant:n,className:r}){return i.jsx("path",{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:Le(["react-flow__background-pattern",n,r])})}function Db({radius:e,className:t}){return i.jsx("circle",{cx:e,cy:e,r:e,className:Le(["react-flow__background-pattern","dots",t])})}var Jt;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(Jt||(Jt={}));const Mb={[Jt.Dots]:1,[Jt.Lines]:1,[Jt.Cross]:6},Pb=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function VA({id:e,variant:t=Jt.Dots,gap:n=20,size:r,lineWidth:o=1,offset:s=0,color:a,bgColor:l,style:E,className:c,patternClassName:d}){const u=R.useRef(null),{transform:T,patternId:S}=Se(Pb,Ie),A=r||Mb[t],f=t===Jt.Dots,I=t===Jt.Cross,p=Array.isArray(n)?n:[n,n],O=[p[0]*T[2]||1,p[1]*T[2]||1],N=A*T[2],h=Array.isArray(s)?s:[s,s],C=I?[N,N]:O,m=[h[0]*T[2]||1+C[0]/2,h[1]*T[2]||1+C[1]/2],g=`${S}${e||""}`;return i.jsxs("svg",{className:Le(["react-flow__background",c]),style:{...E,...Gi,"--xy-background-color-props":l,"--xy-background-pattern-color-props":a},ref:u,"data-testid":"rf__background",children:[i.jsx("pattern",{id:g,x:T[0]%O[0],y:T[1]%O[1],width:O[0],height:O[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${m[0]},-${m[1]})`,children:f?i.jsx(Db,{radius:N/2,className:d}):i.jsx(yb,{dimensions:C,lineWidth:o,variant:t,className:d})}),i.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${g})`})]})}VA.displayName="Background";const $A=R.memo(VA);function bb(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:i.jsx("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function vb(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:i.jsx("path",{d:"M0 0h32v4.2H0z"})})}function Ub(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:i.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 wb(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:i.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 Bb(){return i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:i.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 ds({children:e,className:t,...n}){return i.jsx("button",{type:"button",className:Le(["react-flow__controls-button",t]),...n,children:e})}const Fb=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function XA({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:o,onZoomIn:s,onZoomOut:a,onFitView:l,onInteractiveChange:E,className:c,children:d,position:u="bottom-left",orientation:T="vertical","aria-label":S}){const A=Ne(),{isInteractive:f,minZoomReached:I,maxZoomReached:p,ariaLabelConfig:O}=Se(Fb,Ie),{zoomIn:N,zoomOut:h,fitView:C}=Zc(),m=()=>{N(),s==null||s()},g=()=>{h(),a==null||a()},y=()=>{C(o),l==null||l()},_=()=>{A.setState({nodesDraggable:!f,nodesConnectable:!f,elementsSelectable:!f}),E==null||E(!f)},U=T==="horizontal"?"horizontal":"vertical";return i.jsxs(ur,{className:Le(["react-flow__controls",U,c]),position:u,style:e,"data-testid":"rf__controls","aria-label":S??O["controls.ariaLabel"],children:[t&&i.jsxs(i.Fragment,{children:[i.jsx(ds,{onClick:m,className:"react-flow__controls-zoomin",title:O["controls.zoomIn.ariaLabel"],"aria-label":O["controls.zoomIn.ariaLabel"],disabled:p,children:i.jsx(bb,{})}),i.jsx(ds,{onClick:g,className:"react-flow__controls-zoomout",title:O["controls.zoomOut.ariaLabel"],"aria-label":O["controls.zoomOut.ariaLabel"],disabled:I,children:i.jsx(vb,{})})]}),n&&i.jsx(ds,{className:"react-flow__controls-fitview",onClick:y,title:O["controls.fitView.ariaLabel"],"aria-label":O["controls.fitView.ariaLabel"],children:i.jsx(Ub,{})}),r&&i.jsx(ds,{className:"react-flow__controls-interactive",onClick:_,title:O["controls.interactive.ariaLabel"],"aria-label":O["controls.interactive.ariaLabel"],children:f?i.jsx(Bb,{}):i.jsx(wb,{})}),d]})}XA.displayName="Controls";const Gb=R.memo(XA);function Hb({id:e,x:t,y:n,width:r,height:o,style:s,color:a,strokeColor:l,strokeWidth:E,className:c,borderRadius:d,shapeRendering:u,selected:T,onClick:S}){const{background:A,backgroundColor:f}=s||{},I=a||A||f;return i.jsx("rect",{className:Le(["react-flow__minimap-node",{selected:T},c]),x:t,y:n,rx:d,ry:d,width:r,height:o,style:{fill:I,stroke:l,strokeWidth:E},shapeRendering:u,onClick:S?p=>S(p,e):void 0})}const kb=R.memo(Hb),Yb=e=>e.nodes.map(t=>t.id),wa=e=>e instanceof Function?e:()=>e;function jb({nodeStrokeColor:e,nodeColor:t,nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:o,nodeComponent:s=kb,onClick:a}){const l=Se(Yb,Ie),E=wa(t),c=wa(e),d=wa(n),u=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return i.jsx(i.Fragment,{children:l.map(T=>i.jsx(Vb,{id:T,nodeColorFunc:E,nodeStrokeColorFunc:c,nodeClassNameFunc:d,nodeBorderRadius:r,nodeStrokeWidth:o,NodeComponent:s,onClick:a,shapeRendering:u},T))})}function Wb({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:o,nodeStrokeWidth:s,shapeRendering:a,NodeComponent:l,onClick:E}){const{node:c,x:d,y:u,width:T,height:S}=Se(A=>{const f=A.nodeLookup.get(e);if(!f)return{node:void 0,x:0,y:0,width:0,height:0};const I=f.internals.userNode,{x:p,y:O}=f.internals.positionAbsolute,{width:N,height:h}=wt(I);return{node:I,x:p,y:O,width:N,height:h}},Ie);return!c||c.hidden||!Wf(c)?null:i.jsx(l,{x:d,y:u,width:T,height:S,style:c.style,selected:!!c.selected,className:r(c),color:t(c),borderRadius:o,strokeColor:n(c),strokeWidth:s,shapeRendering:a,onClick:E,id:c.id})}const Vb=R.memo(Wb);var $b=R.memo(jb);const Xb=200,Kb=150,zb=e=>!e.hidden,Jb=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?jf(Ao(e.nodeLookup,{filter:zb}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},qb="react-flow__minimap-desc";function KA({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:o="",nodeBorderRadius:s=5,nodeStrokeWidth:a,nodeComponent:l,bgColor:E,maskColor:c,maskStrokeColor:d,maskStrokeWidth:u,position:T="bottom-right",onClick:S,onNodeClick:A,pannable:f=!1,zoomable:I=!1,ariaLabel:p,inversePan:O,zoomStep:N=1,offsetScale:h=5}){const C=Ne(),m=R.useRef(null),{boundingRect:g,viewBB:y,rfId:_,panZoom:U,translateExtent:D,flowWidth:b,flowHeight:F,ariaLabelConfig:L}=Se(Jb,Ie),P=(e==null?void 0:e.width)??Xb,M=(e==null?void 0:e.height)??Kb,w=g.width/P,v=g.height/M,x=Math.max(w,v),B=x*P,H=x*M,Y=h*x,K=g.x-(B-g.width)/2-Y,X=g.y-(H-g.height)/2-Y,q=B+Y*2,ee=H+Y*2,Z=`${qb}-${_}`,$=R.useRef(0),z=R.useRef();$.current=x,R.useEffect(()=>{if(m.current&&U)return z.current=fP({domNode:m.current,panZoom:U,getTransform:()=>C.getState().transform,getViewScale:()=>$.current}),()=>{var J;(J=z.current)==null||J.destroy()}},[U]),R.useEffect(()=>{var J;(J=z.current)==null||J.update({translateExtent:D,width:b,height:F,inversePan:O,pannable:f,zoomStep:N,zoomable:I})},[f,I,O,N,D,b,F]);const ce=S?J=>{var ue;const[Ee,Ae]=((ue=z.current)==null?void 0:ue.pointer(J))||[0,0];S(J,{x:Ee,y:Ae})}:void 0,se=A?R.useCallback((J,Ee)=>{const Ae=C.getState().nodeLookup.get(Ee).internals.userNode;A(J,Ae)},[]):void 0,V=p??L["minimap.ariaLabel"];return i.jsx(ur,{position:T,style:{...e,"--xy-minimap-background-color-props":typeof E=="string"?E:void 0,"--xy-minimap-mask-background-color-props":typeof c=="string"?c:void 0,"--xy-minimap-mask-stroke-color-props":typeof d=="string"?d:void 0,"--xy-minimap-mask-stroke-width-props":typeof u=="number"?u*x: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:Le(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:i.jsxs("svg",{width:P,height:M,viewBox:`${K} ${X} ${q} ${ee}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":Z,ref:m,onClick:ce,children:[V&&i.jsx("title",{id:Z,children:V}),i.jsx($b,{onClick:se,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:s,nodeClassName:o,nodeStrokeWidth:a,nodeComponent:l}),i.jsx("path",{className:"react-flow__minimap-mask",d:`M${K-Y},${X-Y}h${q+Y*2}v${ee+Y*2}h${-q-Y*2}z
506
+ M${y.x},${y.y}h${y.width}v${y.height}h${-y.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}KA.displayName="MiniMap";const Qb=R.memo(KA),Zb=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,ev={[dr.Line]:"right",[dr.Handle]:"bottom-right"};function tv({nodeId:e,position:t,variant:n=dr.Handle,className:r,style:o=void 0,children:s,color:a,minWidth:l=10,minHeight:E=10,maxWidth:c=Number.MAX_VALUE,maxHeight:d=Number.MAX_VALUE,keepAspectRatio:u=!1,resizeDirection:T,autoScale:S=!0,shouldResize:A,onResizeStart:f,onResize:I,onResizeEnd:p}){const O=hA(),N=typeof e=="string"?e:O,h=Ne(),C=R.useRef(null),m=n===dr.Handle,g=Se(R.useCallback(Zb(m&&S),[m,S]),Ie),y=R.useRef(null),_=t??ev[n];R.useEffect(()=>{if(!(!C.current||!N))return y.current||(y.current=DP({domNode:C.current,nodeId:N,getStoreItems:()=>{const{nodeLookup:D,transform:b,snapGrid:F,snapToGrid:L,nodeOrigin:P,domNode:M}=h.getState();return{nodeLookup:D,transform:b,snapGrid:F,snapToGrid:L,nodeOrigin:P,paneDomNode:M}},onChange:(D,b)=>{const{triggerNodeChanges:F,nodeLookup:L,parentLookup:P,nodeOrigin:M}=h.getState(),w=[],v={x:D.x,y:D.y},x=L.get(N);if(x&&x.expandParent&&x.parentId){const B=x.origin??M,H=D.width??x.measured.width??0,Y=D.height??x.measured.height??0,K={id:x.id,parentId:x.parentId,rect:{width:H,height:Y,...Vf({x:D.x??x.position.x,y:D.y??x.position.y},{width:H,height:Y},x.parentId,L,B)}},X=Qc([K],L,P,M);w.push(...X),v.x=D.x?Math.max(B[0]*H,D.x):void 0,v.y=D.y?Math.max(B[1]*Y,D.y):void 0}if(v.x!==void 0&&v.y!==void 0){const B={id:N,type:"position",position:{...v}};w.push(B)}if(D.width!==void 0&&D.height!==void 0){const H={id:N,type:"dimensions",resizing:!0,setAttributes:T?T==="horizontal"?"width":"height":!0,dimensions:{width:D.width,height:D.height}};w.push(H)}for(const B of b){const H={...B,type:"position"};w.push(H)}F(w)},onEnd:({width:D,height:b})=>{const F={id:N,type:"dimensions",resizing:!1,dimensions:{width:D,height:b}};h.getState().triggerNodeChanges([F])}})),y.current.update({controlPosition:_,boundaries:{minWidth:l,minHeight:E,maxWidth:c,maxHeight:d},keepAspectRatio:u,resizeDirection:T,onResizeStart:f,onResize:I,onResizeEnd:p,shouldResize:A}),()=>{var D;(D=y.current)==null||D.destroy()}},[_,l,E,c,d,u,f,I,p,A]);const U=_.split("-");return i.jsx("div",{className:Le(["react-flow__resize-control","nodrag",...U,n,r]),ref:C,style:{...o,scale:g,...a&&{[m?"backgroundColor":"borderColor"]:a}},children:s})}R.memo(tv);var zA=Object.defineProperty,nv=(e,t,n)=>t in e?zA(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,rv=(e,t)=>{for(var n in t)zA(e,n,{get:t[n],enumerable:!0})},ov=(e,t,n)=>nv(e,t+"",n),JA={};rv(JA,{Graph:()=>Qe,alg:()=>tE,json:()=>QA,version:()=>av});var sv=Object.defineProperty,qA=(e,t)=>{for(var n in t)sv(e,n,{get:t[n],enumerable:!0})},Qe=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,s])=>{e(o)&&t.setNode(o,s)}),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 s=this.parent(o);return!s||t.hasNode(s)?(n[o]=s??void 0,s??void 0):s in n?n[s]:r(s)};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,s,a,l,E=!1;typeof e=="object"&&e!==null&&"v"in e?(o=e.v,s=e.w,a=e.name,arguments.length===2&&(l=t,E=!0)):(o=e,s=t,a=r,arguments.length>2&&(l=n,E=!0)),o=""+o,s=""+s,a!==void 0&&(a=""+a);let c=Ur(this._isDirected,o,s,a);if(c in this._edgeLabels)return E&&(this._edgeLabels[c]=l),this;if(a!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(o),this.setNode(s),this._edgeLabels[c]=E?l:this._defaultEdgeLabelFn(o,s,a);let d=iv(this._isDirected,o,s,a);return o=d.v,s=d.w,Object.freeze(d),this._edgeObjs[c]=d,gu(this._preds[s],o),gu(this._sucs[o],s),this._in[s][c]=d,this._out[o][c]=d,this._edgeCount++,this}edge(e,t,n){let r=arguments.length===1?Ba(this._isDirected,e):Ur(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?Ba(this._isDirected,e):Ur(this._isDirected,e,t,n))in this._edgeLabels}removeEdge(e,t,n){let r=arguments.length===1?Ba(this._isDirected,e):Ur(this._isDirected,e,t,n),o=this._edgeObjs[r];if(o){let s=o.v,a=o.w;delete this._edgeLabels[r],delete this._edgeObjs[r],Lu(this._preds[a],s),Lu(this._sucs[s],a),delete this._in[a][r],delete this._out[s][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 gu(e,t){e[t]?e[t]++:e[t]=1}function Lu(e,t){e[t]!==void 0&&!--e[t]&&delete e[t]}function Ur(e,t,n,r){let o=""+t,s=""+n;if(!e&&o>s){let a=o;o=s,s=a}return o+""+s+""+(r===void 0?"\0":r)}function iv(e,t,n,r){let o=""+t,s=""+n;if(!e&&o>s){let l=o;o=s,s=l}let a={v:o,w:s};return r&&(a.name=r),a}function Ba(e,t){return Ur(e,t.v,t.w,t.name)}var av="4.0.1",QA={};qA(QA,{read:()=>dv,write:()=>lv});function lv(e){let t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:cv(e),edges:Ev(e)},n=e.graph();return n!==void 0&&(t.value=structuredClone(n)),t}function cv(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 Ev(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 dv(e){let t=new Qe(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 tE={};qA(tE,{CycleException:()=>ni,bellmanFord:()=>ZA,components:()=>Sv,dijkstra:()=>ti,dijkstraAll:()=>Av,findCycles:()=>pv,floydWarshall:()=>Ov,isAcyclic:()=>hv,postorder:()=>Cv,preorder:()=>gv,prim:()=>Lv,shortestPaths:()=>_v,tarjan:()=>tp,topsort:()=>np});var uv=()=>1;function ZA(e,t,n,r){return Tv(e,String(t),n||uv,r||function(o){return e.outEdges(o)})}function Tv(e,t,n,r){let o={},s,a=0,l=e.nodes(),E=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},s=!0)},c=function(){l.forEach(function(u){r(u).forEach(function(T){let S=T.v===u?T.v:T.w,A=S===T.v?T.w:T.v;E({v:S,w:A})})})};l.forEach(function(u){let T=u===t?0:Number.POSITIVE_INFINITY;o[u]={distance:T,predecessor:""}});let d=l.length;for(let u=1;u<d&&(s=!1,a++,c(),!!s);u++);if(a===d-1&&(s=!1,c(),s))throw new Error("The graph contains a negative weight cycle");return o}function Sv(e){let t={},n=[],r;function o(s){s in t||(t[s]=!0,r.push(s),e.successors(s).forEach(o),e.predecessors(s).forEach(o))}return e.nodes().forEach(function(s){r=[],o(s),r.length&&n.push(r)}),n}var ep=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,s=o.length;return n[r]=s,o.push({key:r,priority:t}),this._decrease(s),!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],s=n[t];n[e]=s,n[t]=o,r[s.key]=e,r[o.key]=t}},Rv=()=>1;function ti(e,t,n,r){let o=function(s){return e.outEdges(s)};return fv(e,String(t),n||Rv,r||o)}function fv(e,t,n,r){let o={},s=new ep,a,l,E=function(c){let d=c.v!==a?c.v:c.w,u=o[d],T=n(c),S=l.distance+T;if(T<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+c+" Weight: "+T);S<u.distance&&(u.distance=S,u.predecessor=a,s.decrease(d,S))};for(e.nodes().forEach(function(c){let d=c===t?0:Number.POSITIVE_INFINITY;o[c]={distance:d,predecessor:""},s.add(c,d)});s.size()>0&&(a=s.removeMin(),l=o[a],l.distance!==Number.POSITIVE_INFINITY);)r(a).forEach(E);return o}function Av(e,t,n){return e.nodes().reduce(function(r,o){return r[o]=ti(e,o,t,n),r},{})}function tp(e){let t=0,n=[],r={},o=[];function s(a){let l=r[a]={onStack:!0,lowlink:t,index:t++};if(n.push(a),e.successors(a).forEach(function(E){E in r?r[E].onStack&&(l.lowlink=Math.min(l.lowlink,r[E].index)):(s(E),l.lowlink=Math.min(l.lowlink,r[E].lowlink))}),l.lowlink===l.index){let E=[],c;do c=n.pop(),r[c].onStack=!1,E.push(c);while(a!==c);o.push(E)}}return e.nodes().forEach(function(a){a in r||s(a)}),o}function pv(e){return tp(e).filter(function(t){return t.length>1||t.length===1&&e.hasEdge(t[0],t[0])})}var Iv=()=>1;function Ov(e,t,n){return Nv(e,t||Iv,n||function(r){return e.outEdges(r)})}function Nv(e,t,n){let r={},o=e.nodes();return o.forEach(function(s){r[s]={},r[s][s]={distance:0,predecessor:""},o.forEach(function(a){s!==a&&(r[s][a]={distance:Number.POSITIVE_INFINITY,predecessor:""})}),n(s).forEach(function(a){let l=a.v===s?a.w:a.v,E=t(a);r[s][l]={distance:E,predecessor:s}})}),o.forEach(function(s){let a=r[s];o.forEach(function(l){let E=r[l];o.forEach(function(c){let d=E[s],u=a[c],T=E[c],S=d.distance+u.distance;S<T.distance&&(T.distance=S,T.predecessor=u.predecessor)})})}),r}var ni=class extends Error{constructor(...e){super(...e)}};function np(e){let t={},n={},r=[];function o(s){if(s in n)throw new ni;s in t||(n[s]=!0,t[s]=!0,e.predecessors(s).forEach(o),delete n[s],r.push(s))}if(e.sinks().forEach(o),Object.keys(t).length!==e.nodeCount())throw new ni;return r}function hv(e){try{np(e)}catch(t){if(t instanceof ni)return!1;throw t}return!0}function mv(e,t,n,r,o){Array.isArray(t)||(t=[t]);let s=(l=>{var E;return(E=e.isDirected()?e.successors(l):e.neighbors(l))!=null?E:[]}),a={};return t.forEach(function(l){if(!e.hasNode(l))throw new Error("Graph does not have node: "+l);o=rp(e,l,n==="post",a,s,r,o)}),o}function rp(e,t,n,r,o,s,a){return t in r||(r[t]=!0,n||(a=s(a,t)),o(t).forEach(function(l){a=rp(e,l,n,r,o,s,a)}),n&&(a=s(a,t))),a}function op(e,t,n){return mv(e,t,n,function(r,o){return r.push(o),r},[])}function Cv(e,t){return op(e,t,"post")}function gv(e,t){return op(e,t,"pre")}function Lv(e,t){let n=new Qe,r={},o=new ep,s;function a(E){let c=E.v===s?E.w:E.v,d=o.priority(c);if(d!==void 0){let u=t(E);u<d&&(r[c]=s,o.decrease(c,u))}}if(e.nodeCount()===0)return n;e.nodes().forEach(function(E){o.add(E,Number.POSITIVE_INFINITY),n.setNode(E)}),o.decrease(e.nodes()[0],0);let l=!1;for(;o.size()>0;){if(s=o.removeMin(),s in r)n.setEdge(s,r[s]);else{if(l)throw new Error("Input graph is not connected: "+e);l=!0}e.nodeEdges(s).forEach(a)}return n}function _v(e,t,n,r){return xv(e,t,n,r??(o=>{let s=e.outEdges(o);return s??[]}))}function xv(e,t,n,r){if(n===void 0)return ti(e,t,n,r);let o=!1,s=e.nodes();for(let a=0;a<s.length;a++){let l=r(s[a]);for(let E=0;E<l.length;E++){let c=l[E],d=c.v===s[a]?c.v:c.w,u=d===c.v?c.w:c.v;n({v:d,w:u})<0&&(o=!0)}if(o)return ZA(e,t,n,r)}return ti(e,t,n,r)}function pr(e,t,n,r){let o=r;for(;e.hasNode(o);)o=nE(r);return n.dummy=t,e.setNode(o,n),o}function yv(e){let t=new Qe().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 sp(e){let t=new Qe({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 _u(e,t){let n=e.x,r=e.y,o=t.x-n,s=t.y-r,a=e.width/2,l=e.height/2;if(!o&&!s)throw new Error("Not possible to find intersection inside of the rectangle");let E,c;return Math.abs(s)*a>Math.abs(o)*l?(s<0&&(l=-l),E=l*o/s,c=l):(o<0&&(a=-a),E=a,c=a*s/o),{x:n+E,y:r+c}}function Oo(e){let t=so(ap(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 Dv(e){let t=e.nodes().map(r=>{let o=e.node(r).rank;return o===void 0?Number.MAX_VALUE:o}),n=At(Math.min,t);e.nodes().forEach(r=>{let o=e.node(r);Object.hasOwn(o,"rank")&&(o.rank-=n)})}function Mv(e){let t=e.nodes().map(a=>e.node(a).rank).filter(a=>a!==void 0),n=At(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,s=e.graph().nodeRankFactor;Array.from(r).forEach((a,l)=>{a===void 0&&l%s!==0?--o:a!==void 0&&o&&a.forEach(E=>e.node(E).rank+=o)})}function xu(e,t,n,r){let o={width:0,height:0};return arguments.length>=4&&(o.rank=n,o.order=r),pr(e,"border",o,t)}function Pv(e,t=ip){let n=[];for(let r=0;r<e.length;r+=t){let o=e.slice(r,r+t);n.push(o)}return n}var ip=65535;function At(e,t){if(t.length>ip){let n=Pv(t);return e(...n.map(r=>e(...r)))}else return e(...t)}function ap(e){let t=e.nodes().map(n=>{let r=e.node(n).rank;return r===void 0?Number.MIN_VALUE:r});return At(Math.max,t)}function bv(e,t){let n={lhs:[],rhs:[]};return e.forEach(r=>{t(r)?n.lhs.push(r):n.rhs.push(r)}),n}function lp(e,t){let n=Date.now();try{return t()}finally{console.log(e+" time: "+(Date.now()-n)+"ms")}}function cp(e,t){return t()}var vv=0;function nE(e){let t=++vv;return e+(""+t)}function so(e,t,n=1){t==null&&(t=e,e=0);let r=s=>s<t;n<0&&(r=s=>t<s);let o=[];for(let s=e;r(s);s+=n)o.push(s);return o}function ri(e,t){let n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return n}function ki(e,t){let n;return typeof t=="string"?n=r=>r[t]:n=t,Object.entries(e).reduce((r,[o,s])=>(r[o]=n(s,o),r),{})}function Uv(e,t){return e.reduce((n,r,o)=>(n[r]=t[o],n),{})}var Yi="\0",wv="3.0.0",Bv=class{constructor(){ov(this,"_sentinel");let e={};e._next=e._prev=e,this._sentinel=e}dequeue(){let e=this._sentinel,t=e._prev;if(t!==e)return yu(t),t}enqueue(e){let t=this._sentinel;e._prev&&e._next&&yu(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,Fv)),n=n._prev;return"["+e.join(", ")+"]"}};function yu(e){e._prev._next=e._next,e._next._prev=e._prev,delete e._next,delete e._prev}function Fv(e,t){if(e!=="_next"&&e!=="_prev")return t}var Gv=Bv,Hv=()=>1;function kv(e,t){if(e.nodeCount()<=1)return[];let n=jv(e,t||Hv);return Yv(n.graph,n.buckets,n.zeroIdx).flatMap(r=>e.outEdges(r.v,r.w)||[])}function Yv(e,t,n){var r;let o=[],s=t[t.length-1],a=t[0],l;for(;e.nodeCount();){for(;l=a.dequeue();)Fa(e,t,n,l);for(;l=s.dequeue();)Fa(e,t,n,l);if(e.nodeCount()){for(let E=t.length-2;E>0;--E)if(l=(r=t[E])==null?void 0:r.dequeue(),l){o=o.concat(Fa(e,t,n,l,!0)||[]);break}}}return o}function Fa(e,t,n,r,o){let s=[],a=o?s:void 0;return(e.inEdges(r.v)||[]).forEach(l=>{let E=e.edge(l),c=e.node(l.v);o&&s.push({v:l.v,w:l.w}),c.out-=E,zl(t,n,c)}),(e.outEdges(r.v)||[]).forEach(l=>{let E=e.edge(l),c=l.w,d=e.node(c);d.in-=E,zl(t,n,d)}),e.removeNode(r.v),a}function jv(e,t){let n=new Qe,r=0,o=0;e.nodes().forEach(l=>{n.setNode(l,{v:l,in:0,out:0})}),e.edges().forEach(l=>{let E=n.edge(l.v,l.w)||0,c=t(l),d=E+c;n.setEdge(l.v,l.w,d);let u=n.node(l.v),T=n.node(l.w);o=Math.max(o,u.out+=c),r=Math.max(r,T.in+=c)});let s=Wv(o+r+3).map(()=>new Gv),a=r+1;return n.nodes().forEach(l=>{zl(s,a,n.node(l))}),{graph:n,buckets:s,zeroIdx:a}}function zl(e,t,n){var r,o,s;n.out?n.in?(s=e[n.out-n.in+t])==null||s.enqueue(n):(o=e[e.length-1])==null||o.enqueue(n):(r=e[0])==null||r.enqueue(n)}function Wv(e){let t=[];for(let n=0;n<e;n++)t.push(n);return t}function Vv(e){(e.graph().acyclicer==="greedy"?kv(e,t(e)):$v(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,nE("rev"))});function t(n){return r=>n.edge(r).weight}}function $v(e){let t=[],n={},r={};function o(s){Object.hasOwn(r,s)||(r[s]=!0,n[s]=!0,e.outEdges(s).forEach(a=>{Object.hasOwn(n,a.w)?t.push(a):o(a.w)}),delete n[s])}return e.nodes().forEach(o),t}function Xv(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 Kv(e){e.graph().dummyChains=[],e.edges().forEach(t=>zv(e,t))}function zv(e,t){let n=t.v,r=e.node(n).rank,o=t.w,s=e.node(o).rank,a=t.name,l=e.edge(t),E=l.labelRank;if(s===r+1)return;e.removeEdge(t);let c,d,u;for(u=0,++r;r<s;++u,++r)l.points=[],d={width:0,height:0,edgeLabel:l,edgeObj:t,rank:r},c=pr(e,"edge",d,"_d"),r===E&&(d.width=l.width,d.height=l.height,d.dummy="edge-label",d.labelpos=l.labelpos),e.setEdge(n,c,{weight:l.weight},a),u===0&&e.graph().dummyChains.push(c),n=c;e.setEdge(n,o,{weight:l.weight},a)}function Jv(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 rE(e){let t={};function n(r){let o=e.node(r);if(Object.hasOwn(t,r))return o.rank;t[r]=!0;let s=e.outEdges(r),a=s?s.map(E=>E==null?Number.POSITIVE_INFINITY:n(E.w)-e.edge(E).minlen):[],l=At(Math.min,a);return l===Number.POSITIVE_INFINITY&&(l=0),o.rank=l}e.sources().forEach(n)}function Tr(e,t){return e.node(t.w).rank-e.node(t.v).rank-e.edge(t).minlen}var Ep=qv;function qv(e){let t=new Qe({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 s,a;for(;Qv(t,e)<o&&(s=Zv(t,e),!!s);)a=t.hasNode(s.v)?Tr(e,s):-Tr(e,s),eU(t,e,a);return t}function Qv(e,t){function n(r){let o=t.nodeEdges(r);o&&o.forEach(s=>{let a=s.v,l=r===a?s.w:a;!e.hasNode(l)&&!Tr(t,s)&&(e.setNode(l,{}),e.setEdge(r,l,{}),n(l))})}return e.nodes().forEach(n),e.nodeCount()}function Zv(e,t){return t.edges().reduce((n,r)=>{let o=Number.POSITIVE_INFINITY;return e.hasNode(r.v)!==e.hasNode(r.w)&&(o=Tr(t,r)),o<n[0]?[o,r]:n},[Number.POSITIVE_INFINITY,null])[1]}function eU(e,t,n){e.nodes().forEach(r=>t.node(r).rank+=n)}var{preorder:tU,postorder:nU}=tE,rU=xn;xn.initLowLimValues=sE;xn.initCutValues=oE;xn.calcCutValue=dp;xn.leaveEdge=Tp;xn.enterEdge=Sp;xn.exchangeEdges=Rp;function xn(e){e=yv(e),rE(e);let t=Ep(e);sE(t),oE(t,e);let n,r;for(;n=Tp(t);)r=Sp(t,e,n),Rp(t,e,n,r)}function oE(e,t){let n=nU(e,e.nodes());n=n.slice(0,n.length-1),n.forEach(r=>oU(e,t,r))}function oU(e,t,n){let r=e.node(n).parent,o=e.edge(n,r);o.cutvalue=dp(e,t,n)}function dp(e,t,n){let r=e.node(n).parent,o=!0,s=t.edge(n,r),a=0;s||(o=!1,s=t.edge(r,n)),a=s.weight;let l=t.nodeEdges(n);return l&&l.forEach(E=>{let c=E.v===n,d=c?E.w:E.v;if(d!==r){let u=c===o,T=t.edge(E).weight;if(a+=u?T:-T,iU(e,n,d)){let S=e.edge(n,d).cutvalue;a+=u?-S:S}}}),a}function sE(e,t){arguments.length<2&&(t=e.nodes()[0]),up(e,{},1,t)}function up(e,t,n,r,o){let s=n,a=e.node(r);t[r]=!0;let l=e.neighbors(r);return l&&l.forEach(E=>{Object.hasOwn(t,E)||(n=up(e,t,n,E,r))}),a.low=s,a.lim=n++,o?a.parent=o:delete a.parent,n}function Tp(e){return e.edges().find(t=>e.edge(t).cutvalue<0)}function Sp(e,t,n){let r=n.v,o=n.w;t.hasEdge(r,o)||(r=n.w,o=n.v);let s=e.node(r),a=e.node(o),l=s,E=!1;return s.lim>a.lim&&(l=a,E=!0),t.edges().filter(c=>E===Du(e,e.node(c.v),l)&&E!==Du(e,e.node(c.w),l)).reduce((c,d)=>Tr(t,d)<Tr(t,c)?d:c)}function Rp(e,t,n,r){let o=n.v,s=n.w;e.removeEdge(o,s),e.setEdge(r.v,r.w,{}),sE(e),oE(e,t),sU(e,t)}function sU(e,t){let n=e.nodes().find(o=>!e.node(o).parent);if(!n)return;let r=tU(e,[n]);r=r.slice(1),r.forEach(o=>{let s=e.node(o).parent,a=t.edge(o,s),l=!1;a||(a=t.edge(s,o),l=!0),t.node(o).rank=t.node(s).rank+(l?a.minlen:-a.minlen)})}function iU(e,t,n){return e.hasEdge(t,n)}function Du(e,t,n){return n.low<=t.lim&&t.lim<=n.lim}var aU=lU;function lU(e){let t=e.graph().ranker;if(typeof t=="function")return t(e);switch(t){case"network-simplex":Mu(e);break;case"tight-tree":EU(e);break;case"longest-path":cU(e);break;case"none":break;default:Mu(e)}}var cU=rE;function EU(e){rE(e),Ep(e)}function Mu(e){rU(e)}var dU=uU;function uU(e){let t=SU(e);e.graph().dummyChains.forEach(n=>{let r=e.node(n),o=r.edgeObj,s=TU(e,t,o.v,o.w),a=s.path,l=s.lca,E=0,c=a[E],d=!0;for(;n!==o.w;){if(r=e.node(n),d){for(;(c=a[E])!==l&&e.node(c).maxRank<r.rank;)E++;c===l&&(d=!1)}if(!d){for(;E<a.length-1&&e.node(a[E+1]).minRank<=r.rank;)E++;c=a[E]}c!==void 0&&e.setParent(n,c),n=e.successors(n)[0]}})}function TU(e,t,n,r){let o=[],s=[],a=Math.min(t[n].low,t[r].low),l=Math.max(t[n].lim,t[r].lim),E;E=n;do E=e.parent(E),o.push(E);while(E&&(t[E].low>a||l>t[E].lim));let c=E,d=r;for(;(d=e.parent(d))!==c;)s.push(d);return{path:o.concat(s.reverse()),lca:c}}function SU(e){let t={},n=0;function r(o){let s=n;e.children(o).forEach(r),t[o]={low:s,lim:n++}}return e.children(Yi).forEach(r),t}function RU(e){let t=pr(e,"root",{},"_root"),n=fU(e),r=Object.values(n),o=At(Math.max,r)-1,s=2*o+1;e.graph().nestingRoot=t,e.edges().forEach(l=>e.edge(l).minlen*=s);let a=AU(e)+1;e.children(Yi).forEach(l=>fp(e,t,s,a,o,n,l)),e.graph().nodeRankFactor=s}function fp(e,t,n,r,o,s,a){var l;let E=e.children(a);if(!E.length){a!==t&&e.setEdge(t,a,{weight:0,minlen:n});return}let c=xu(e,"_bt"),d=xu(e,"_bb"),u=e.node(a);e.setParent(c,a),u.borderTop=c,e.setParent(d,a),u.borderBottom=d,E.forEach(T=>{var S;fp(e,t,n,r,o,s,T);let A=e.node(T),f=A.borderTop?A.borderTop:T,I=A.borderBottom?A.borderBottom:T,p=A.borderTop?r:2*r,O=f!==I?1:o-((S=s[a])!=null?S:0)+1;e.setEdge(c,f,{weight:p,minlen:O,nestingEdge:!0}),e.setEdge(I,d,{weight:p,minlen:O,nestingEdge:!0})}),e.parent(a)||e.setEdge(t,c,{weight:0,minlen:o+((l=s[a])!=null?l:0)})}function fU(e){let t={};function n(r,o){let s=e.children(r);s&&s.length&&s.forEach(a=>n(a,o+1)),t[r]=o}return e.children(Yi).forEach(r=>n(r,1)),t}function AU(e){return e.edges().reduce((t,n)=>t+e.edge(n).weight,0)}function pU(e){let t=e.graph();e.removeNode(t.nestingRoot),delete t.nestingRoot,e.edges().forEach(n=>{e.edge(n).nestingEdge&&e.removeEdge(n)})}var IU=OU;function OU(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 s=o.minRank,a=o.maxRank+1;s<a;++s)Pu(e,"borderLeft","_bl",n,o,s),Pu(e,"borderRight","_br",n,o,s)}}e.children(Yi).forEach(t)}function Pu(e,t,n,r,o,s){let a={width:0,height:0,rank:s,borderType:t},l=o[t][s-1],E=pr(e,"border",a,n);o[t][s]=E,e.setParent(E,r),l&&e.setEdge(l,E,{weight:1})}function NU(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="lr"||n==="rl")&&Ap(e)}function hU(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="bt"||n==="rl")&&mU(e),(n==="lr"||n==="rl")&&(CU(e),Ap(e))}function Ap(e){e.nodes().forEach(t=>bu(e.node(t))),e.edges().forEach(t=>bu(e.edge(t)))}function bu(e){let t=e.width;e.width=e.height,e.height=t}function mU(e){e.nodes().forEach(t=>Ga(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(Ga),Object.hasOwn(r,"y")&&Ga(r)})}function Ga(e){e.y=-e.y}function CU(e){e.nodes().forEach(t=>Ha(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(Ha),Object.hasOwn(r,"x")&&Ha(r)})}function Ha(e){let t=e.x;e.x=e.y,e.y=t}function gU(e){let t={},n=e.nodes().filter(l=>!e.children(l).length),r=n.map(l=>e.node(l).rank),o=At(Math.max,r),s=so(o+1).map(()=>[]);function a(l){if(t[l])return;t[l]=!0;let E=e.node(l);s[E.rank].push(l);let c=e.successors(l);c&&c.forEach(a)}return n.sort((l,E)=>e.node(l).rank-e.node(E).rank).forEach(a),s}function LU(e,t){let n=0;for(let r=1;r<t.length;++r)n+=_U(e,t[r-1],t[r]);return n}function _U(e,t,n){let r=Uv(n,n.map((c,d)=>d)),o=t.flatMap(c=>{let d=e.outEdges(c);return d?d.map(u=>({pos:r[u.w],weight:e.edge(u).weight})).sort((u,T)=>u.pos-T.pos):[]}),s=1;for(;s<n.length;)s<<=1;let a=2*s-1;s-=1;let l=new Array(a).fill(0),E=0;return o.forEach(c=>{let d=c.pos+s;l[d]+=c.weight;let u=0;for(;d>0;)d%2&&(u+=l[d+1]),d=d-1>>1,l[d]+=c.weight;E+=c.weight*u}),E}function xU(e,t=[]){return t.map(n=>{let r=e.inEdges(n);if(!r||!r.length)return{v:n};{let o=r.reduce((s,a)=>{let l=e.edge(a),E=e.node(a.v);return{sum:s.sum+l.weight*E.order,weight:s.weight+l.weight}},{sum:0,weight:0});return{v:n,barycenter:o.sum/o.weight,weight:o.weight}}})}function yU(e,t){let n={};e.forEach((o,s)=>{let a={indegree:0,in:[],out:[],vs:[o.v],i:s};o.barycenter!==void 0&&(a.barycenter=o.barycenter,a.weight=o.weight),n[o.v]=a}),t.edges().forEach(o=>{let s=n[o.v],a=n[o.w];s!==void 0&&a!==void 0&&(a.indegree++,s.out.push(a))});let r=Object.values(n).filter(o=>!o.indegree);return DU(r)}function DU(e){let t=[];function n(o){return s=>{s.merged||(s.barycenter===void 0||o.barycenter===void 0||s.barycenter>=o.barycenter)&&MU(o,s)}}function r(o){return s=>{s.in.push(o),--s.indegree===0&&e.push(s)}}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=>ri(o,["vs","i","barycenter","weight"]))}function MU(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 PU(e,t){let n=bv(e,d=>Object.hasOwn(d,"barycenter")),r=n.lhs,o=n.rhs.sort((d,u)=>u.i-d.i),s=[],a=0,l=0,E=0;r.sort(bU(!!t)),E=vu(s,o,E),r.forEach(d=>{E+=d.vs.length,s.push(d.vs),a+=d.barycenter*d.weight,l+=d.weight,E=vu(s,o,E)});let c={vs:s.flat(1)};return l&&(c.barycenter=a/l,c.weight=l),c}function vu(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 bU(e){return(t,n)=>t.barycenter<n.barycenter?-1:t.barycenter>n.barycenter?1:e?n.i-t.i:t.i-n.i}function pp(e,t,n,r){let o=e.children(t),s=e.node(t),a=s?s.borderLeft:void 0,l=s?s.borderRight:void 0,E={};a&&(o=o.filter(T=>T!==a&&T!==l));let c=xU(e,o);c.forEach(T=>{if(e.children(T.v).length){let S=pp(e,T.v,n,r);E[T.v]=S,Object.hasOwn(S,"barycenter")&&UU(T,S)}});let d=yU(c,n);vU(d,E);let u=PU(d,r);if(a&&l){u.vs=[a,u.vs,l].flat(1);let T=e.predecessors(a);if(T&&T.length){let S=e.node(T[0]),A=e.predecessors(l),f=e.node(A[0]);Object.hasOwn(u,"barycenter")||(u.barycenter=0,u.weight=0),u.barycenter=(u.barycenter*u.weight+S.order+f.order)/(u.weight+2),u.weight+=2}}return u}function vU(e,t){e.forEach(n=>{n.vs=n.vs.flatMap(r=>t[r]?t[r].vs:r)})}function UU(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 wU(e,t,n,r){r||(r=e.nodes());let o=BU(e),s=new Qe({compound:!0}).setGraph({root:o}).setDefaultNodeLabel(a=>e.node(a));return r.forEach(a=>{let l=e.node(a),E=e.parent(a);if(l.rank===t||l.minRank<=t&&t<=l.maxRank){s.setNode(a),s.setParent(a,E||o);let c=e[n](a);c&&c.forEach(d=>{let u=d.v===a?d.w:d.v,T=s.edge(u,a),S=T!==void 0?T.weight:0;s.setEdge(u,a,{weight:e.edge(d).weight+S})}),Object.hasOwn(l,"minRank")&&s.setNode(a,{borderLeft:l.borderLeft[t],borderRight:l.borderRight[t]})}}),s}function BU(e){let t;for(;e.hasNode(t=nE("_root")););return t}function FU(e,t,n){let r={},o;n.forEach(s=>{let a=e.parent(s),l,E;for(;a;){if(l=e.parent(a),l?(E=r[l],r[l]=a):(E=o,o=a),E&&E!==a){t.setEdge(E,a);return}a=l}})}function Ip(e,t={}){if(typeof t.customOrder=="function"){t.customOrder(e,Ip);return}let n=ap(e),r=Uu(e,so(1,n+1),"inEdges"),o=Uu(e,so(n-1,-1,-1),"outEdges"),s=gU(e);if(wu(e,s),t.disableOptimalOrderHeuristic)return;let a=Number.POSITIVE_INFINITY,l,E=t.constraints||[];for(let c=0,d=0;d<4;++c,++d){GU(c%2?r:o,c%4>=2,E),s=Oo(e);let u=LU(e,s);u<a?(d=0,l=Object.assign({},s),a=u):u===a&&(l=structuredClone(s))}wu(e,l)}function Uu(e,t,n){let r=new Map,o=(s,a)=>{r.has(s)||r.set(s,[]),r.get(s).push(a)};for(let s of e.nodes()){let a=e.node(s);if(typeof a.rank=="number"&&o(a.rank,s),typeof a.minRank=="number"&&typeof a.maxRank=="number")for(let l=a.minRank;l<=a.maxRank;l++)l!==a.rank&&o(l,s)}return t.map(function(s){return wU(e,s,n,r.get(s)||[])})}function GU(e,t,n){let r=new Qe;e.forEach(function(o){n.forEach(l=>r.setEdge(l.left,l.right));let s=o.graph().root,a=pp(o,s,r,t);a.vs.forEach((l,E)=>o.node(l).order=E),FU(o,r,a.vs)})}function wu(e,t){Object.values(t).forEach(n=>n.forEach((r,o)=>e.node(r).order=o))}function HU(e,t){let n={};function r(o,s){let a=0,l=0,E=o.length,c=s[s.length-1];return s.forEach((d,u)=>{let T=YU(e,d),S=T?e.node(T).order:E;(T||d===c)&&(s.slice(l,u+1).forEach(A=>{let f=e.predecessors(A);f&&f.forEach(I=>{let p=e.node(I),O=p.order;(O<a||S<O)&&!(p.dummy&&e.node(A).dummy)&&Op(n,I,A)})}),l=u+1,a=S)}),s}return t.length&&t.reduce(r),n}function kU(e,t){let n={};function r(s,a,l,E,c){so(a,l).forEach(d=>{let u=s[d];if(u!==void 0&&e.node(u).dummy){let T=e.predecessors(u);T&&T.forEach(S=>{if(S===void 0)return;let A=e.node(S);A.dummy&&(A.order<E||A.order>c)&&Op(n,S,u)})}})}function o(s,a){let l=-1,E=-1,c=0;return a.forEach((d,u)=>{if(e.node(d).dummy==="border"){let T=e.predecessors(d);if(T&&T.length){let S=T[0];if(S===void 0)return;E=e.node(S).order,r(a,c,u,l,E),c=u,l=E}}r(a,c,a.length,E,s.length)}),a}return t.length&&t.reduce(o),n}function YU(e,t){if(e.node(t).dummy){let n=e.predecessors(t);if(n)return n.find(r=>e.node(r).dummy)}}function Op(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 jU(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 WU(e,t,n,r){let o={},s={},a={};return t.forEach(l=>{l.forEach((E,c)=>{o[E]=E,s[E]=E,a[E]=c})}),t.forEach(l=>{let E=-1;l.forEach(c=>{let d=r(c);if(d&&d.length){let u=d.sort((S,A)=>{let f=a[S],I=a[A];return(f!==void 0?f:0)-(I!==void 0?I:0)}),T=(u.length-1)/2;for(let S=Math.floor(T),A=Math.ceil(T);S<=A;++S){let f=u[S];if(f===void 0)continue;let I=a[f];if(I!==void 0&&s[c]===c&&E<I&&!jU(n,c,f)){let p=o[f];p!==void 0&&(s[f]=c,s[c]=o[c]=p,E=I)}}}})}),{root:o,align:s}}function VU(e,t,n,r,o=!1){let s={},a=$U(e,t,n,o),l=o?"borderLeft":"borderRight";function E(S,A){let f=a.nodes().slice(),I={},p=f.pop();for(;p;){if(I[p])S(p);else{I[p]=!0,f.push(p);for(let O of A(p))f.push(O)}p=f.pop()}}function c(S){let A=a.inEdges(S);A?s[S]=A.reduce((f,I)=>{var p;let O=(p=s[I.v])!=null?p:0,N=a.edge(I);return Math.max(f,O+(N!==void 0?N:0))},0):s[S]=0}function d(S){let A=a.outEdges(S),f=Number.POSITIVE_INFINITY;A&&(f=A.reduce((p,O)=>{let N=s[O.w],h=a.edge(O);return Math.min(p,(N!==void 0?N:0)-(h!==void 0?h:0))},Number.POSITIVE_INFINITY));let I=e.node(S);f!==Number.POSITIVE_INFINITY&&I.borderType!==l&&(s[S]=Math.max(s[S]!==void 0?s[S]:0,f))}function u(S){return a.predecessors(S)||[]}function T(S){return a.successors(S)||[]}return E(c,u),E(d,T),Object.keys(r).forEach(S=>{var A;let f=n[S];f!==void 0&&(s[S]=(A=s[f])!=null?A:0)}),s}function $U(e,t,n,r){let o=new Qe,s=e.graph(),a=qU(s.nodesep,s.edgesep,r);return t.forEach(l=>{let E;l.forEach(c=>{let d=n[c];if(d!==void 0){if(o.setNode(d),E!==void 0){let u=n[E];if(u!==void 0){let T=o.edge(u,d);o.setEdge(u,d,Math.max(a(e,c,E),T||0))}}E=c}})}),o}function XU(e,t){return Object.values(t).reduce((n,r)=>{let o=Number.NEGATIVE_INFINITY,s=Number.POSITIVE_INFINITY;Object.entries(r).forEach(([l,E])=>{let c=QU(e,l)/2;o=Math.max(E+c,o),s=Math.min(E-c,s)});let a=o-s;return a<n[0]&&(n=[a,r]),n},[Number.POSITIVE_INFINITY,null])[1]}function KU(e,t){let n=Object.values(t),r=At(Math.min,n),o=At(Math.max,n);["u","d"].forEach(s=>{["l","r"].forEach(a=>{let l=s+a,E=e[l];if(!E||E===t)return;let c=Object.values(E),d=r-At(Math.min,c);a!=="l"&&(d=o-At(Math.max,c)),d&&(e[l]=ki(E,u=>u+d))})})}function zU(e,t=void 0){let n=e.ul;return n?ki(n,(r,o)=>{var s,a;if(t){let E=t.toLowerCase(),c=e[E];if(c&&c[o]!==void 0)return c[o]}let l=Object.values(e).map(E=>{let c=E[o];return c!==void 0?c:0}).sort((E,c)=>E-c);return(((s=l[1])!=null?s:0)+((a=l[2])!=null?a:0))/2}):{}}function JU(e){let t=Oo(e),n=Object.assign(HU(e,t),kU(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(d=>Object.values(d).reverse()));let E=WU(e,o,n,d=>(a==="u"?e.predecessors(d):e.successors(d))||[]),c=VU(e,o,E.root,E.align,l==="r");l==="r"&&(c=ki(c,d=>-d)),r[a+l]=c})});let s=XU(e,r);return KU(r,s),zU(r,e.graph().align)}function qU(e,t,n){return(r,o,s)=>{let a=r.node(o),l=r.node(s),E=0,c;if(E+=a.width/2,Object.hasOwn(a,"labelpos"))switch(a.labelpos.toLowerCase()){case"l":c=-a.width/2;break;case"r":c=a.width/2;break}if(c&&(E+=n?c:-c),c=void 0,E+=(a.dummy?t:e)/2,E+=(l.dummy?t:e)/2,E+=l.width/2,Object.hasOwn(l,"labelpos"))switch(l.labelpos.toLowerCase()){case"l":c=l.width/2;break;case"r":c=-l.width/2;break}return c&&(E+=n?c:-c),E}}function QU(e,t){return e.node(t).width}function ZU(e){e=sp(e),ew(e),Object.entries(JU(e)).forEach(([t,n])=>e.node(t).x=n)}function ew(e){let t=Oo(e),n=e.graph(),r=n.ranksep,o=n.rankalign,s=0;t.forEach(a=>{let l=a.reduce((E,c)=>{var d;let u=(d=e.node(c).height)!=null?d:0;return E>u?E:u},0);a.forEach(E=>{let c=e.node(E);o==="top"?c.y=s+c.height/2:o==="bottom"?c.y=s+l-c.height/2:c.y=s+l/2}),s+=l+r})}function tw(e,t={}){let n=t.debugTiming?lp:cp;return n("layout",()=>{let r=n(" buildLayoutGraph",()=>dw(e));return n(" runLayout",()=>nw(r,n,t)),n(" updateInputGraph",()=>rw(e,r)),r})}function nw(e,t,n){t(" makeSpaceForEdgeLabels",()=>uw(e)),t(" removeSelfEdges",()=>Nw(e)),t(" acyclic",()=>Vv(e)),t(" nestingGraph.run",()=>RU(e)),t(" rank",()=>aU(sp(e))),t(" injectEdgeLabelProxies",()=>Tw(e)),t(" removeEmptyRanks",()=>Mv(e)),t(" nestingGraph.cleanup",()=>pU(e)),t(" normalizeRanks",()=>Dv(e)),t(" assignRankMinMax",()=>Sw(e)),t(" removeEdgeLabelProxies",()=>Rw(e)),t(" normalize.run",()=>Kv(e)),t(" parentDummyChains",()=>dU(e)),t(" addBorderSegments",()=>IU(e)),t(" order",()=>Ip(e,n)),t(" insertSelfEdges",()=>hw(e)),t(" adjustCoordinateSystem",()=>NU(e)),t(" position",()=>ZU(e)),t(" positionSelfEdges",()=>mw(e)),t(" removeBorderNodes",()=>Ow(e)),t(" normalize.undo",()=>Jv(e)),t(" fixupEdgeLabelCoords",()=>pw(e)),t(" undoCoordinateSystem",()=>hU(e)),t(" translateGraph",()=>fw(e)),t(" assignNodeIntersects",()=>Aw(e)),t(" reversePoints",()=>Iw(e)),t(" acyclic.undo",()=>Xv(e))}function rw(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 ow=["nodesep","edgesep","ranksep","marginx","marginy"],sw={ranksep:50,edgesep:20,nodesep:50,rankdir:"TB",rankalign:"center"},iw=["acyclicer","ranker","rankdir","align","rankalign"],aw=["width","height","rank"],Bu={width:0,height:0},lw=["minlen","weight","width","height","labeloffset"],cw={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},Ew=["labelpos"];function dw(e){let t=new Qe({multigraph:!0,compound:!0}),n=Ya(e.graph());return t.setGraph(Object.assign({},sw,ka(n,ow),ri(n,iw))),e.nodes().forEach(r=>{let o=Ya(e.node(r)),s=ka(o,aw);Object.keys(Bu).forEach(l=>{s[l]===void 0&&(s[l]=Bu[l])}),t.setNode(r,s);let a=e.parent(r);a!==void 0&&t.setParent(r,a)}),e.edges().forEach(r=>{let o=Ya(e.edge(r));t.setEdge(r,Object.assign({},cw,ka(o,lw),ri(o,Ew)))}),t}function uw(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 Tw(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};pr(e,"edge-proxy",o,"_ep")}})}function Sw(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 Rw(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 fw(e){let t=Number.POSITIVE_INFINITY,n=0,r=Number.POSITIVE_INFINITY,o=0,s=e.graph(),a=s.marginx||0,l=s.marginy||0;function E(c){let d=c.x,u=c.y,T=c.width,S=c.height;t=Math.min(t,d-T/2),n=Math.max(n,d+T/2),r=Math.min(r,u-S/2),o=Math.max(o,u+S/2)}e.nodes().forEach(c=>E(e.node(c))),e.edges().forEach(c=>{let d=e.edge(c);Object.hasOwn(d,"x")&&E(d)}),t-=a,r-=l,e.nodes().forEach(c=>{let d=e.node(c);d.x-=t,d.y-=r}),e.edges().forEach(c=>{let d=e.edge(c);d.points.forEach(u=>{u.x-=t,u.y-=r}),Object.hasOwn(d,"x")&&(d.x-=t),Object.hasOwn(d,"y")&&(d.y-=r)}),s.width=n-t+a,s.height=o-r+l}function Aw(e){e.edges().forEach(t=>{let n=e.edge(t),r=e.node(t.v),o=e.node(t.w),s,a;n.points?(s=n.points[0],a=n.points[n.points.length-1]):(n.points=[],s=o,a=r),n.points.unshift(_u(r,s)),n.points.push(_u(o,a))})}function pw(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 Iw(e){e.edges().forEach(t=>{let n=e.edge(t);n.reversed&&n.points.reverse()})}function Ow(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),s=e.node(n.borderLeft[n.borderLeft.length-1]),a=e.node(n.borderRight[n.borderRight.length-1]);n.width=Math.abs(a.x-s.x),n.height=Math.abs(o.y-r.y),n.x=s.x+n.width/2,n.y=r.y+n.height/2}}),e.nodes().forEach(t=>{e.node(t).dummy==="border"&&e.removeNode(t)})}function Nw(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 hw(e){Oo(e).forEach(t=>{let n=0;t.forEach((r,o)=>{let s=e.node(r);s.order=o+n,(s.selfEdges||[]).forEach(a=>{pr(e,"selfedge",{width:a.label.width,height:a.label.height,rank:s.rank,order:o+ ++n,e:a.e,label:a.label},"_se")}),delete s.selfEdges})})}function mw(e){e.nodes().forEach(t=>{let n=e.node(t);if(n.dummy==="selfedge"){let r=n,o=e.node(r.e.v),s=o.x+o.width/2,a=o.y,l=n.x-s,E=o.height/2;e.setEdge(r.e,r.label),e.removeNode(t),r.label.points=[{x:s+2*l/3,y:a-E},{x:s+5*l/6,y:a-E},{x:s+l,y:a},{x:s+5*l/6,y:a+E},{x:s+2*l/3,y:a+E}],r.label.x=n.x,r.label.y=n.y}})}function ka(e,t){return ki(ri(e,t),Number)}function Ya(e){let t={};return e&&Object.entries(e).forEach(([n,r])=>{typeof n=="string"&&(n=n.toLowerCase()),t[n]=r}),t}function Cw(e){let t=Oo(e),n=new Qe({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 s="layer"+o;n.setNode(s,{rank:"same"}),r.reduce((a,l)=>(n.setEdge(a,l,{style:"invis"}),l))}),n}var gw={graphlib:JA,version:wv,layout:tw,debug:Cw,util:{time:lp,notime:cp}},oi=gw;/*! For license information please see dagre.esm.js.LEGAL.txt */function Lw(e,t,n={}){var o;if(e.length===0)return e;const r=new oi.graphlib.Graph().setDefaultEdgeLabel(()=>({}));r.setGraph({rankdir:"LR",ranksep:60,nodesep:30,marginx:20,marginy:20});for(const s of e){const a={width:170,height:52};if(n.mode==="layered"&&((o=s.data)!=null&&o.layer)){const l=Fs.indexOf(s.data.layer);l>=0&&(a.rank=l)}r.setNode(s.id,a)}for(const s of t)r.setEdge(s.source,s.target);return oi.layout(r),e.map(s=>{const a=r.node(s.id);return{...s,position:{x:a.x-85,y:a.y-26}}})}function _w({data:e,selected:t}){const n=e.nodeType,r=e.isFocal,o=we[n]??"#8b949e",s=_c[n]??n.toUpperCase();return i.jsxs("div",{style:{minWidth:140,maxWidth:190,background:"#161b22",border:`2px solid ${r||t?"#58a6ff":o}`,borderRadius:8,padding:"6px 8px",boxShadow:r?"0 0 0 2px rgba(88, 166, 255, 0.25)":"none"},children:[i.jsx(tn,{type:"target",position:ne.Left,style:{width:6,height:6,background:o,border:"none"}}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginBottom:2},children:[i.jsx("span",{style:{fontSize:8,fontWeight:700,letterSpacing:"0.04em",color:"#0d1117",background:o,borderRadius:3,padding:"1px 4px"},children:s}),e.domain&&i.jsx("span",{style:{color:"#8b949e",fontSize:9},children:e.domain})]}),i.jsx("div",{style:{color:"#e6edf3",fontSize:10,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.label,children:e.label}),i.jsx(tn,{type:"source",position:ne.Right,style:{width:6,height:6,background:o,border:"none"}})]})}const xw={miniDagNode:_w};function Np({nodes:e,edges:t,focalNodeId:n,height:r=250,onNodeClick:o,interactive:s=!0,layoutMode:a="flow"}){const[l,E,c]=jA([]),[d,u,T]=WA([]);return R.useEffect(()=>{const S=e.map(f=>({id:f.id,type:"miniDagNode",position:{x:0,y:0},data:{label:f.name,nodeType:f.type,domain:f.domain,layer:xc(f),isFocal:f.id===n}})),A=t.map((f,I)=>({id:`mini-edge-${I}-${f.source}-${f.target}`,source:f.source,target:f.target,style:{stroke:Br[f.type]??"#8b949e",strokeWidth:1.4},markerEnd:{type:ar.ArrowClosed,color:Br[f.type]??"#8b949e",width:10,height:10}}));E(Lw(S,A,{mode:a})),u(A)},[e,t,n,a,E,u]),e.length===0?i.jsx("div",{style:{height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#8b949e",fontSize:11},children:"No lineage nodes to display"}):i.jsx("div",{style:{height:r,width:"100%",borderRadius:8,overflow:"hidden",border:"1px solid #30363d"},children:i.jsx(YA,{nodes:l,edges:d,onNodesChange:s?c:void 0,onEdgesChange:s?T:void 0,onNodeClick:o?(S,A)=>o(A.id):void 0,nodeTypes:xw,fitView:!0,fitViewOptions:{padding:.15},proOptions:{hideAttribution:!0},nodesDraggable:s,nodesConnectable:!1,zoomOnScroll:s,panOnDrag:s,style:{background:"#0d1117"},children:i.jsx($A,{color:"#21262d",gap:20,size:1})})})}function yw(e){const t=e.match(/^\s*block\s+"([^"]+)"/i);return t?t[1]:null}function Dw(e){const t=[],n=/\b(?:FROM|JOIN)\s+([a-zA-Z_][\w.]*)/gi;for(const o of e.matchAll(n)){const s=o[1].toLowerCase();["select","where","group","order","having","limit","union","lateral"].includes(s)||t.push(s)}const r=/\bref\s*\(\s*"([^"]+)"\s*\)/gi;for(const o of e.matchAll(r))t.push(o[1]);return[...new Set(t)]}function Mw(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 Pw({cellContent:e,cellType:t,cellName:n,themeMode:r,t:o,onFocusNode:s}){const[a,l]=R.useState(!1),[E,c]=R.useState(!1),[d,u]=R.useState([]),[T,S]=R.useState([]),[A,f]=R.useState(),[I,p]=R.useState([]),[O,N]=R.useState({metrics:[],dimensions:[]}),[h,C]=R.useState(null),[m,g]=R.useState(null),_=(t==="dql"?yw(e):null)||n,U=R.useCallback(async()=>{if(!(!_&&t!=="sql")){c(!0),g(null);try{const b=Dw(e);if(p(b),N(Mw(e)),_){const F=`block:${_}`;f(F);const[L,P]=await Promise.all([Q.queryLineage({focus:F}),Q.fetchLineagePaths(F)]);L!=null&&L.graph&&(u(L.graph.nodes??[]),S(L.graph.edges??[])),P&&C(P)}else{f(void 0);const L=((await Q.fetchLineage()).nodes??[]).filter(P=>b.some(M=>P.name===M||P.id===`table:${M}`));u(L),S([])}}catch{g("Failed to load lineage")}finally{c(!1)}}},[_,e,t]);R.useEffect(()=>{a&&U()},[a,U]);const D=I.length>0||O.metrics.length>0||O.dimensions.length>0;return e.trim()?i.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[i.jsxs("button",{onClick:()=>l(b=>!b),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:[i.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",style:{flexShrink:0},children:[i.jsx("circle",{cx:"4",cy:"4",r:"2"}),i.jsx("circle",{cx:"12",cy:"8",r:"2"}),i.jsx("circle",{cx:"4",cy:"12",r:"2"}),i.jsx("line",{x1:"6",y1:"4",x2:"10",y2:"8"}),i.jsx("line",{x1:"6",y1:"12",x2:"10",y2:"8"})]}),i.jsx("span",{children:"Lineage"}),i.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:i.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})}),a&&_&&s&&i.jsx("span",{onClick:b=>{b.stopPropagation(),s(`block:${_}`)},style:{marginLeft:"auto",fontSize:9,color:o.accent,cursor:"pointer",textDecoration:"underline"},children:"View in DAG"})]}),a&&i.jsx("div",{style:{fontSize:11},children:E?i.jsx("div",{style:{color:o.textMuted,padding:"8px 12px"},children:"Loading lineage..."}):m?i.jsx("div",{style:{color:o.error,padding:"8px 12px"},children:m}):i.jsxs(i.Fragment,{children:[d.length>0&&A&&i.jsx("div",{style:{borderBottom:`1px solid ${o.cellBorder}`},children:i.jsx(Np,{nodes:d,edges:T,focalNodeId:A,height:200,onNodeClick:s,interactive:!0,layoutMode:"flow"})}),i.jsxs("div",{style:{padding:"6px 12px 8px"},children:[h&&(h.upstreamPaths.length>0||h.downstreamPaths.length>0)&&i.jsxs("div",{style:{marginBottom:8},children:[i.jsx("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:4},children:"Complete Paths"}),i.jsxs("div",{style:{display:"grid",gap:6},children:[h.upstreamPaths.slice(0,3).map((b,F)=>i.jsx(vl,{path:b,onNodeClick:s,focalNodeId:A,t:o},`up-${F}`)),h.downstreamPaths.slice(0,2).map((b,F)=>i.jsx(vl,{path:b,onNodeClick:s,focalNodeId:A,t:o},`down-${F}`))]})]}),I.length>0&&i.jsxs("div",{style:{marginBottom:6},children:[i.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Reads From (",I.length,")"]}),I.map(b=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[i.jsx("span",{style:{color:we.source_table,fontSize:9,fontWeight:700,width:26},children:"TBL"}),i.jsx("span",{children:b})]},b))]}),O.metrics.length>0&&i.jsxs("div",{style:{marginBottom:6},children:[i.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Metrics (",O.metrics.length,")"]}),O.metrics.map(b=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[i.jsx("span",{style:{color:we.metric,fontSize:9,fontWeight:700,width:26},children:"MET"}),i.jsx("span",{children:b})]},b))]}),O.dimensions.length>0&&i.jsxs("div",{style:{marginBottom:6},children:[i.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Dimensions (",O.dimensions.length,")"]}),O.dimensions.map(b=>i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[i.jsx("span",{style:{color:we.dimension,fontSize:9,fontWeight:700,width:26},children:"DIM"}),i.jsx("span",{children:b})]},b))]}),!D&&d.length===0&&!h&&i.jsx("div",{style:{color:o.textMuted,padding:"2px 0"},children:"No lineage dependencies detected for this cell."})]})]})})]}):null}const G=e=>e.flatMap(bw),bw=e=>Ls(Uw(e)).map(vw),vw=e=>e.replace(/ +/g," ").trim(),Uw=e=>({type:"mandatory_block",items:iE(e,0)[0]}),iE=(e,t,n)=>{const r=[];for(;e[t];){const[o,s]=ww(e,t);if(r.push(o),t=s,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]},ww=(e,t)=>{const n=[];for(;;){const[r,o]=Bw(e,t);if(r)n.push(r),t=o;else break}return n.length===1?[n[0],t]:[{type:"concatenation",items:n},t]},Bw=(e,t)=>{if(e[t]==="{")return Fw(e,t+1);if(e[t]==="[")return Gw(e,t+1);{let n="";for(;e[t]&&/[A-Za-z0-9_ ]/.test(e[t]);)n+=e[t],t++;return[n,t]}},Fw=(e,t)=>{const[n,r]=iE(e,t,"}");return[{type:"mandatory_block",items:n},r]},Gw=(e,t)=>{const[n,r]=iE(e,t,"]");return[{type:"optional_block",items:n},r]},Ls=e=>{if(typeof e=="string")return[e];if(e.type==="concatenation")return e.items.map(Ls).reduce(Hw,[""]);if(e.type==="mandatory_block")return e.items.flatMap(Ls);if(e.type==="optional_block")return["",...e.items.flatMap(Ls)];throw new Error(`Unknown node type: ${e}`)},Hw=(e,t)=>{const n=[];for(const r of e)for(const o of t)n.push(r+o);return n};var W;(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"})(W=W||(W={}));const hp=e=>({type:W.EOF,raw:"«EOF»",text:"«EOF»",start:e}),nn=hp(1/0),Gn=e=>t=>t.type===e.type&&t.text===e.text,rn={ARRAY:Gn({text:"ARRAY",type:W.RESERVED_DATA_TYPE}),BY:Gn({text:"BY",type:W.RESERVED_KEYWORD}),SET:Gn({text:"SET",type:W.RESERVED_CLAUSE}),STRUCT:Gn({text:"STRUCT",type:W.RESERVED_DATA_TYPE}),WINDOW:Gn({text:"WINDOW",type:W.RESERVED_CLAUSE}),VALUES:Gn({text:"VALUES",type:W.RESERVED_CLAUSE})},mp=e=>e===W.RESERVED_DATA_TYPE||e===W.RESERVED_KEYWORD||e===W.RESERVED_FUNCTION_NAME||e===W.RESERVED_KEYWORD_PHRASE||e===W.RESERVED_DATA_TYPE_PHRASE||e===W.RESERVED_CLAUSE||e===W.RESERVED_SELECT||e===W.RESERVED_SET_OPERATION||e===W.RESERVED_JOIN||e===W.ARRAY_KEYWORD||e===W.CASE||e===W.END||e===W.WHEN||e===W.ELSE||e===W.THEN||e===W.LIMIT||e===W.BETWEEN||e===W.AND||e===W.OR||e===W.XOR,kw=e=>e===W.AND||e===W.OR||e===W.XOR,Yw=["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"],jw=["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"],Ww=["ARRAY","BOOL","BYTES","DATE","DATETIME","GEOGRAPHY","INTERVAL","INT64","INT","SMALLINT","INTEGER","BIGINT","TINYINT","BYTEINT","NUMERIC","DECIMAL","BIGNUMERIC","BIGDECIMAL","FLOAT64","STRING","STRUCT","TIME","TIMEZONE"],Vw=G(["SELECT [ALL | DISTINCT] [AS STRUCT | AS VALUE]"]),$w=G(["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"]),Fu=G(["CREATE [OR REPLACE] [TEMP|TEMPORARY|SNAPSHOT|EXTERNAL] TABLE [IF NOT EXISTS]"]),ja=G(["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"]),Xw=G(["UNION {ALL | DISTINCT}","EXCEPT DISTINCT","INTERSECT DISTINCT"]),Kw=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),zw=G(["TABLESAMPLE SYSTEM","ANY TYPE","ALL COLUMNS","NOT DETERMINISTIC","{ROWS | RANGE} BETWEEN","IS [NOT] DISTINCT FROM"]),Jw=G([]),qw={name:"bigquery",tokenizerOptions:{reservedSelect:Vw,reservedClauses:[...$w,...ja,...Fu],reservedSetOperations:Xw,reservedJoins:Kw,reservedKeywordPhrases:zw,reservedDataTypePhrases:Jw,reservedKeywords:jw,reservedDataTypes:Ww,reservedFunctionNames:Yw,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:Qw},formatOptions:{onelineClauses:[...Fu,...ja],tabularOnelineClauses:ja}};function Qw(e){return Zw(eB(e))}function Zw(e){let t=nn;return e.map(n=>n.text==="OFFSET"&&t.text==="["?(t=n,Object.assign(Object.assign({},n),{type:W.RESERVED_FUNCTION_NAME})):(t=n,n))}function eB(e){var t;const n=[];for(let r=0;r<e.length;r++){const o=e[r];if((rn.ARRAY(o)||rn.STRUCT(o))&&((t=e[r+1])===null||t===void 0?void 0:t.text)==="<"){const s=tB(e,r+1),a=e.slice(r,s+1);n.push({type:W.IDENTIFIER,raw:a.map(Gu("raw")).join(""),text:a.map(Gu("text")).join(""),start:o.start}),r=s}else n.push(o)}return n}const Gu=e=>t=>t.type===W.IDENTIFIER||t.type===W.COMMA?t[e]+" ":t[e];function tB(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 nB=["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"],rB=["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"],oB=["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"],sB=G(["SELECT [DISTINCT]","MODIFY QUERY SELECT [DISTINCT]"]),iB=G(["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]"]),Hu=G(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),Wa=G(["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"]),aB=G(["UNION [ALL | DISTINCT]","PARALLEL WITH"]),lB=G(["[GLOBAL] [INNER|LEFT|RIGHT|FULL|CROSS] [OUTER|SEMI|ANTI|ANY|ALL|ASOF] JOIN","[LEFT] ARRAY JOIN"]),cB=G(["{ROWS | RANGE} BETWEEN","ALTER MATERIALIZE STATISTICS"]),EB={name:"clickhouse",tokenizerOptions:{reservedSelect:sB,reservedClauses:[...iB,...Hu,...Wa],reservedSetOperations:aB,reservedJoins:lB,reservedKeywordPhrases:cB,reservedKeywords:rB,reservedDataTypes:oB,reservedFunctionNames:nB,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:dB},formatOptions:{onelineClauses:[...Hu,...Wa],tabularOnelineClauses:Wa}};function dB(e){return e.map((t,n)=>{const r=e[n+1]||nn,o=e[n-1]||nn;return t.type===W.RESERVED_SELECT&&(r.type===W.COMMA||o.type===W.RESERVED_CLAUSE||o.type===W.COMMA)?Object.assign(Object.assign({},t),{type:W.RESERVED_KEYWORD}):rn.SET(t)&&r.type===W.OPEN_PAREN?Object.assign(Object.assign({},t),{type:W.RESERVED_FUNCTION_NAME}):t})}const uB=["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"],TB=["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"],SB=["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"],RB=G(["SELECT [ALL | DISTINCT]"]),fB=G(["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"]),ku=G(["CREATE [GLOBAL TEMPORARY | EXTERNAL] TABLE [IF NOT EXISTS]"]),Va=G(["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"]),AB=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),pB=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),IB=G(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),OB=G([]),NB={name:"db2",tokenizerOptions:{reservedSelect:RB,reservedClauses:[...fB,...ku,...Va],reservedSetOperations:AB,reservedJoins:pB,reservedKeywordPhrases:IB,reservedDataTypePhrases:OB,reservedKeywords:TB,reservedDataTypes:SB,reservedFunctionNames:uB,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:[...ku,...Va],tabularOnelineClauses:Va}},hB=["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"],mB=["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"],CB=["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"],gB=G(["SELECT [ALL | DISTINCT]"]),LB=G(["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"]),Yu=G(["CREATE [OR REPLACE] TABLE"]),$a=G(["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}"]),_B=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),xB=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","[LEFT | RIGHT] EXCEPTION JOIN","{INNER | CROSS} JOIN"]),yB=G(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),DB=G([]),MB={name:"db2i",tokenizerOptions:{reservedSelect:gB,reservedClauses:[...LB,...Yu,...$a],reservedSetOperations:_B,reservedJoins:xB,reservedKeywordPhrases:yB,reservedDataTypePhrases:DB,reservedKeywords:mB,reservedDataTypes:CB,reservedFunctionNames:hB,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:[...Yu,...$a],tabularOnelineClauses:$a}},PB=["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"],bB=["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"],vB=["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"],UB=G(["SELECT [ALL | DISTINCT]"]),wB=G(["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"]),ju=G(["CREATE [OR REPLACE] [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),Xa=G(["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]"]),BB=G(["UNION [ALL | BY NAME]","EXCEPT [ALL]","INTERSECT [ALL]"]),FB=G(["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"]),GB=G(["{ROWS | RANGE | GROUPS} BETWEEN","SIMILAR TO","IS [NOT] DISTINCT FROM"]),HB=G(["TIMESTAMP WITH TIME ZONE"]),kB={name:"duckdb",tokenizerOptions:{reservedSelect:UB,reservedClauses:[...wB,...ju,...Xa],reservedSetOperations:BB,reservedJoins:FB,reservedKeywordPhrases:GB,reservedDataTypePhrases:HB,supportsXor:!0,reservedKeywords:bB,reservedDataTypes:vB,reservedFunctionNames:PB,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:[...ju,...Xa],tabularOnelineClauses:Xa}},YB=["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"],jB=["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"],WB=["ARRAY","BIGINT","BINARY","BOOLEAN","CHAR","DATE","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","INTERVAL","MAP","NUMERIC","PRECISION","SMALLINT","STRUCT","TIMESTAMP","VARCHAR"],VB=G(["SELECT [ALL | DISTINCT]"]),$B=G(["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"]),Wu=G(["CREATE [TEMPORARY] [EXTERNAL] TABLE [IF NOT EXISTS]"]),Ka=G(["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"]),XB=G(["UNION [ALL | DISTINCT]"]),KB=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","LEFT SEMI JOIN"]),zB=G(["{ROWS | RANGE} BETWEEN"]),JB=G([]),qB={name:"hive",tokenizerOptions:{reservedSelect:VB,reservedClauses:[...$B,...Wu,...Ka],reservedSetOperations:XB,reservedJoins:KB,reservedKeywordPhrases:zB,reservedDataTypePhrases:JB,reservedKeywords:jB,reservedDataTypes:WB,reservedFunctionNames:YB,extraParens:["[]"],stringTypes:['""-bs',"''-bs"],identTypes:["``"],variableTypes:[{quote:"{}",prefixes:["$"],requirePrefix:!0}],operators:["%","~","^","|","&","<=>","==","!","||"]},formatOptions:{onelineClauses:[...Wu,...Ka],tabularOnelineClauses:Ka}};function ji(e){return e.map((t,n)=>{const r=e[n+1]||nn;if(rn.SET(t)&&r.text==="(")return Object.assign(Object.assign({},t),{type:W.RESERVED_FUNCTION_NAME});const o=e[n-1]||nn;return rn.VALUES(t)&&o.text==="="?Object.assign(Object.assign({},t),{type:W.RESERVED_FUNCTION_NAME}):t})}const QB=["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"],ZB=["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"],eF=["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"],tF=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),nF=G(["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"]),Vu=G(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),za=G(["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"]),rF=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]","MINUS [ALL | DISTINCT]"]),oF=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),sF=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),iF=G([]),aF={name:"mariadb",tokenizerOptions:{reservedSelect:tF,reservedClauses:[...nF,...Vu,...za],reservedSetOperations:rF,reservedJoins:oF,reservedKeywordPhrases:sF,reservedDataTypePhrases:iF,supportsXor:!0,reservedKeywords:QB,reservedDataTypes:ZB,reservedFunctionNames:eF,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:ji},formatOptions:{onelineClauses:[...Vu,...za],tabularOnelineClauses:za}},lF=["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"],cF=["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"],EF=["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"],dF=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),uF=G(["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"]),$u=G(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),Ja=G(["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"]),TF=G(["UNION [ALL | DISTINCT]"]),SF=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),RF=G(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),fF=G([]),AF={name:"mysql",tokenizerOptions:{reservedSelect:dF,reservedClauses:[...uF,...$u,...Ja],reservedSetOperations:TF,reservedJoins:SF,reservedKeywordPhrases:RF,reservedDataTypePhrases:fF,supportsXor:!0,reservedKeywords:lF,reservedDataTypes:cF,reservedFunctionNames:EF,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:ji},formatOptions:{onelineClauses:[...$u,...Ja],tabularOnelineClauses:Ja}},pF=["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"],IF=["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"],OF=["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"],NF=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),hF=G(["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"]),Xu=G(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),qa=G(["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"]),mF=G(["UNION [ALL | DISTINCT]"]),CF=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),gF=G(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),LF=G([]),_F={name:"tidb",tokenizerOptions:{reservedSelect:NF,reservedClauses:[...hF,...Xu,...qa],reservedSetOperations:mF,reservedJoins:CF,reservedKeywordPhrases:gF,reservedDataTypePhrases:LF,supportsXor:!0,reservedKeywords:pF,reservedDataTypes:IF,reservedFunctionNames:OF,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:ji},formatOptions:{onelineClauses:[...Xu,...qa],tabularOnelineClauses:qa}},xF=["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"],yF=["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"],DF=[],MF=G(["SELECT [ALL | DISTINCT]"]),PF=G(["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"]),Ku=G(["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"]),bF=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),vF=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","INNER JOIN"]),UF=G(["{ROWS | RANGE | GROUPS} BETWEEN"]),wF=G([]),BF={name:"n1ql",tokenizerOptions:{reservedSelect:MF,reservedClauses:[...PF,...Ku],reservedSetOperations:bF,reservedJoins:vF,reservedKeywordPhrases:UF,reservedDataTypePhrases:wF,supportsXor:!0,reservedKeywords:yF,reservedDataTypes:DF,reservedFunctionNames:xF,stringTypes:['""-bs',"''-bs"],identTypes:["``"],extraParens:["[]","{}"],paramTypes:{positional:!0,numbered:["$"],named:["$"]},lineCommentTypes:["#","--"],operators:["%","==",":","||"]},formatOptions:{onelineClauses:Ku}},FF=["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"],GF=["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"],HF=["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"],kF=G(["SELECT [ALL | DISTINCT | UNIQUE]"]),YF=G(["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"]),zu=G(["CREATE [GLOBAL TEMPORARY | PRIVATE TEMPORARY | SHARDED | DUPLICATED | IMMUTABLE BLOCKCHAIN | BLOCKCHAIN | IMMUTABLE] TABLE"]),Qa=G(["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"]),jF=G(["UNION [ALL]","MINUS","INTERSECT"]),WF=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | OUTER} APPLY"]),VF=G(["ON {UPDATE | DELETE} [SET NULL]","ON COMMIT","{ROWS | RANGE} BETWEEN"]),$F=G([]),XF={name:"plsql",tokenizerOptions:{reservedSelect:kF,reservedClauses:[...YF,...zu,...Qa],reservedSetOperations:jF,reservedJoins:WF,reservedKeywordPhrases:VF,reservedDataTypePhrases:$F,supportsXor:!0,reservedKeywords:FF,reservedDataTypes:GF,reservedFunctionNames:HF,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:KF},formatOptions:{alwaysDenseOperators:["@"],onelineClauses:[...zu,...Qa],tabularOnelineClauses:Qa}};function KF(e){let t=nn;return e.map(n=>rn.SET(n)&&rn.BY(t)?Object.assign(Object.assign({},n),{type:W.RESERVED_KEYWORD}):(mp(n.type)&&(t=n),n))}const zF=["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"],JF=["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"],qF=["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"],QF=G(["SELECT [ALL | DISTINCT]"]),ZF=G(["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"]),Ju=G(["CREATE [GLOBAL | LOCAL] [TEMPORARY | TEMP | UNLOGGED] TABLE [IF NOT EXISTS]"]),Za=G(["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"]),eG=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),tG=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),nG=G(["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"]),rG=G(["[TIMESTAMP | TIME] {WITH | WITHOUT} TIME ZONE"]),oG={name:"postgresql",tokenizerOptions:{reservedSelect:QF,reservedClauses:[...ZF,...Ju,...Za],reservedSetOperations:eG,reservedJoins:tG,reservedKeywordPhrases:nG,reservedDataTypePhrases:rG,reservedKeywords:JF,reservedDataTypes:qF,reservedFunctionNames:zF,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:[...Ju,...Za],tabularOnelineClauses:Za}},sG=["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"],iG=["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"],aG=["ARRAY","BIGINT","BPCHAR","CHAR","CHARACTER VARYING","CHARACTER","DECIMAL","INT","INT2","INT4","INT8","INTEGER","NCHAR","NUMERIC","NVARCHAR","SMALLINT","TEXT","VARBYTE","VARCHAR"],lG=G(["SELECT [ALL | DISTINCT]"]),cG=G(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","QUALIFY","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT INTO","VALUES","SET"]),qu=G(["CREATE [TEMPORARY | TEMP | LOCAL TEMPORARY | LOCAL TEMP] TABLE [IF NOT EXISTS]"]),el=G(["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"]),EG=G(["UNION [ALL]","EXCEPT","INTERSECT","MINUS"]),dG=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),uG=G(["NULL AS","DATA CATALOG","HIVE METASTORE","{ROWS | RANGE} BETWEEN"]),TG=G([]),SG={name:"redshift",tokenizerOptions:{reservedSelect:lG,reservedClauses:[...cG,...qu,...el],reservedSetOperations:EG,reservedJoins:dG,reservedKeywordPhrases:uG,reservedDataTypePhrases:TG,reservedKeywords:iG,reservedDataTypes:aG,reservedFunctionNames:sG,extraParens:["[]"],stringTypes:["''-qq"],identTypes:['""-qq'],identChars:{first:"#"},paramTypes:{numbered:["$"]},operators:["^","%","@","|/","||/","&","|","~","<<",">>","||","::"]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...qu,...el],tabularOnelineClauses:el}},RG=["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"],fG=["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"],AG=["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"],pG=G(["SELECT [ALL | DISTINCT]"]),IG=G(["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"]),Qu=G(["CREATE [EXTERNAL] TABLE [IF NOT EXISTS]"]),tl=G(["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"]),OG=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),NG=G(["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"]),hG=G(["ON DELETE","ON UPDATE","CURRENT ROW","{ROWS | RANGE} BETWEEN"]),mG=G([]),CG={name:"spark",tokenizerOptions:{reservedSelect:pG,reservedClauses:[...IG,...Qu,...tl],reservedSetOperations:OG,reservedJoins:NG,reservedKeywordPhrases:hG,reservedDataTypePhrases:mG,supportsXor:!0,reservedKeywords:RG,reservedDataTypes:fG,reservedFunctionNames:AG,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:gG},formatOptions:{onelineClauses:[...Qu,...tl],tabularOnelineClauses:tl}};function gG(e){return e.map((t,n)=>{const r=e[n-1]||nn,o=e[n+1]||nn;return rn.WINDOW(t)&&o.type===W.OPEN_PAREN?Object.assign(Object.assign({},t),{type:W.RESERVED_FUNCTION_NAME}):t.text==="ITEMS"&&t.type===W.RESERVED_KEYWORD&&!(r.text==="COLLECTION"&&o.text==="TERMINATED")?Object.assign(Object.assign({},t),{type:W.IDENTIFIER,text:t.raw}):t})}const LG=["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"],_G=["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"],xG=["ANY","ARRAY","BLOB","CHARACTER","DECIMAL","INT","INTEGER","NATIVE CHARACTER","NCHAR","NUMERIC","NVARCHAR","REAL","TEXT","VARCHAR","VARYING CHARACTER"],yG=G(["SELECT [ALL | DISTINCT]"]),DG=G(["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"]),Zu=G(["CREATE [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),nl=G(["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"]),MG=G(["UNION [ALL]","EXCEPT","INTERSECT"]),PG=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),bG=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE | GROUPS} BETWEEN","DO UPDATE"]),vG=G([]),UG={name:"sqlite",tokenizerOptions:{reservedSelect:yG,reservedClauses:[...DG,...Zu,...nl],reservedSetOperations:MG,reservedJoins:PG,reservedKeywordPhrases:bG,reservedDataTypePhrases:vG,reservedKeywords:_G,reservedDataTypes:xG,reservedFunctionNames:LG,stringTypes:["''-qq",{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``","[]"],paramTypes:{positional:!0,numbered:["?"],named:[":","@","$"]},operators:["%","~","&","|","<<",">>","==","->","->>","||"]},formatOptions:{onelineClauses:[...Zu,...nl],tabularOnelineClauses:nl}},wG=["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"],BG=["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"],FG=["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"],GG=G(["SELECT [ALL | DISTINCT]"]),HG=G(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY [ALL | DISTINCT]","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","FETCH {FIRST | NEXT}","INSERT INTO","VALUES","SET"]),eT=G(["CREATE [GLOBAL TEMPORARY | LOCAL TEMPORARY] TABLE"]),rl=G(["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"]),kG=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),YG=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),jG=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),WG=G([]),VG={name:"sql",tokenizerOptions:{reservedSelect:GG,reservedClauses:[...HG,...eT,...rl],reservedSetOperations:kG,reservedJoins:YG,reservedKeywordPhrases:jG,reservedDataTypePhrases:WG,reservedKeywords:BG,reservedDataTypes:FG,reservedFunctionNames:wG,stringTypes:[{quote:"''-qq-bs",prefixes:["N","U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``"],paramTypes:{positional:!0},operators:["||"]},formatOptions:{onelineClauses:[...eT,...rl],tabularOnelineClauses:rl}},$G=["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"],XG=["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"],KG=["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"],zG=G(["SELECT [ALL | DISTINCT]"]),JG=G(["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"]),tT=G(["CREATE TABLE [IF NOT EXISTS]"]),ol=G(["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"]),qG=G(["UNION [ALL | DISTINCT] [CORRESPONDING]","EXCEPT [ALL | DISTINCT] [CORRESPONDING]","INTERSECT [ALL | DISTINCT] [CORRESPONDING]"]),QG=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),ZG=G(["{ROWS | RANGE | GROUPS} BETWEEN","IS [NOT] DISTINCT FROM"]),eH=G([]),tH={name:"trino",tokenizerOptions:{reservedSelect:zG,reservedClauses:[...JG,...tT,...ol],reservedSetOperations:qG,reservedJoins:QG,reservedKeywordPhrases:ZG,reservedDataTypePhrases:eH,reservedKeywords:XG,reservedDataTypes:KG,reservedFunctionNames:$G,extraParens:["[]","{}"],stringTypes:[{quote:"''-qq",prefixes:["U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq'],paramTypes:{positional:!0},operators:["%","->","=>",":","||","|","^","$"]},formatOptions:{onelineClauses:[...tT,...ol],tabularOnelineClauses:ol}},nH=["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"],rH=["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"],oH=["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"],sH=G(["SELECT [ALL | DISTINCT]"]),iH=G(["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"]),nT=G(["CREATE TABLE"]),sl=G(["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"]),aH=G(["UNION [ALL]","EXCEPT","INTERSECT"]),lH=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","{CROSS | OUTER} APPLY"]),cH=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),EH=G([]),dH={name:"transactsql",tokenizerOptions:{reservedSelect:sH,reservedClauses:[...iH,...nT,...sl],reservedSetOperations:aH,reservedJoins:lH,reservedKeywordPhrases:cH,reservedDataTypePhrases:EH,reservedKeywords:rH,reservedDataTypes:oH,reservedFunctionNames:nH,nestedBlockComments:!0,stringTypes:[{quote:"''-qq",prefixes:["N"]},"{}"],identTypes:['""-qq',"[]"],identChars:{first:"#@",rest:"#@$"},paramTypes:{named:["@"],quoted:["@"]},operators:["%","&","|","^","~","!<","!>","+=","-=","*=","/=","%=","|=","&=","^=","::",":"],propertyAccessOperators:[".."]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...nT,...sl],tabularOnelineClauses:sl}},uH=["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"],TH=["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"],SH=["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"],RH=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),fH=G(["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"]),rT=G(["CREATE [ROWSTORE] [REFERENCE | TEMPORARY | GLOBAL TEMPORARY] TABLE [IF NOT EXISTS]"]),il=G(["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"]),AH=G(["UNION [ALL | DISTINCT]","EXCEPT","INTERSECT","MINUS"]),pH=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),IH=G(["ON DELETE","ON UPDATE","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),OH=G([]),NH={name:"singlestoredb",tokenizerOptions:{reservedSelect:RH,reservedClauses:[...fH,...rT,...il],reservedSetOperations:AH,reservedJoins:pH,reservedKeywordPhrases:IH,reservedDataTypePhrases:OH,reservedKeywords:uH,reservedDataTypes:TH,reservedFunctionNames:SH,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:ji},formatOptions:{alwaysDenseOperators:["::","::$","::%"],onelineClauses:[...rT,...il],tabularOnelineClauses:il}},hH=["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"],mH=["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"],CH=["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"],gH=G(["SELECT [ALL | DISTINCT]"]),LH=G(["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"]),oT=G(["CREATE [OR REPLACE] [VOLATILE] TABLE [IF NOT EXISTS]","CREATE [OR REPLACE] [LOCAL | GLOBAL] {TEMP|TEMPORARY} TABLE [IF NOT EXISTS]"]),al=G(["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"]),_H=G(["UNION [ALL]","MINUS","EXCEPT","INTERSECT"]),xH=G(["[INNER] JOIN","[NATURAL] {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | NATURAL} JOIN"]),yH=G(["{ROWS | RANGE} BETWEEN","ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]"]),DH=G([]),MH={name:"snowflake",tokenizerOptions:{reservedSelect:gH,reservedClauses:[...LH,...oT,...al],reservedSetOperations:_H,reservedJoins:xH,reservedKeywordPhrases:yH,reservedDataTypePhrases:DH,reservedKeywords:mH,reservedDataTypes:CH,reservedFunctionNames:hH,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:[...oT,...al],tabularOnelineClauses:al}},PH=Object.freeze(Object.defineProperty({__proto__:null,bigquery:qw,clickhouse:EB,db2:NB,db2i:MB,duckdb:kB,hive:qB,mariadb:aF,mysql:AF,n1ql:BF,plsql:XF,postgresql:oG,redshift:SG,singlestoredb:NH,snowflake:MH,spark:CG,sql:VG,sqlite:UG,tidb:_F,transactsql:dH,trino:tH},Symbol.toStringTag,{value:"Module"})),Hr=e=>e[e.length-1],Cp=e=>e.sort((t,n)=>n.length-t.length||t.localeCompare(n)),_s=e=>e.replace(/\s+/gu," "),ll=e=>/\n/.test(e),st=e=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),sT=/\s+/uy,yn=e=>new RegExp(`(?:${e})`,"uy"),bH=e=>e.split("").map(t=>/ /gu.test(t)?"\\s+":`[${t.toUpperCase()}${t.toLowerCase()}]`).join(""),vH=e=>e+"(?:-"+e+")*",UH=({prefixes:e,requirePrefix:t})=>`(?:${e.map(bH).join("|")}${t?"":"|"})`,wH=e=>new RegExp(`(?:${e.map(st).join("|")}).*?(?=\r
507
+ |\r|
508
+ |$)`,"uy"),iT=(e,t=[])=>{const n=e==="open"?0:1,r=["()",...t].map(o=>o[n]);return yn(r.map(st).join("|"))},aT=e=>yn(`${Cp(e).map(st).join("|")}`),BH=({rest:e,dashes:t})=>e||t?`(?![${e||""}${t?"-":""}])`:"",xt=(e,t={})=>{if(e.length===0)return/^\b$/u;const n=BH(t),r=Cp(e).map(st).join("|").replace(/ /gu,"\\s+");return new RegExp(`(?:${r})${n}\\b`,"iuy")},cl=(e,t)=>{if(!e.length)return;const n=e.map(st).join("|");return yn(`(?:${n})(?:${t})`)},FH=()=>{const e={"<":">","[":"]","(":")","{":"}"},t="{left}(?:(?!{right}').)*?{right}",n=Object.entries(e).map(([a,l])=>t.replace(/{left}/g,st(a)).replace(/{right}/g,st(l))),r=st(Object.keys(e).join(""));return`[Qq]'(?:${String.raw`(?<tag>[^\s${r}])(?:(?!\k<tag>').)*?\k<tag>`}|${n.join("|")})'`},lT={"``":"(?:`[^`]*`)+","[]":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''":FH()},gp=e=>typeof e=="string"?lT[e]:"regex"in e?e.regex:UH(e)+lT[e.quote],GH=e=>yn(e.map(t=>"regex"in t?t.regex:gp(t)).join("|")),Lp=e=>e.map(gp).join("|"),cT=e=>yn(Lp(e)),HH=(e={})=>yn(_p(e)),_p=({first:e,rest:t,dashes:n,allowFirstCharNumber:r}={})=>{const o="\\p{Alphabetic}\\p{Mark}_",s="\\p{Decimal_Number}",a=st(e??""),l=st(t??""),E=r?`[${o}${s}${a}][${o}${s}${l}]*`:`[${o}${a}][${o}${s}${l}]*`;return n?vH(E):E};function xp(e,t){const n=e.slice(0,t).split(/\n/);return{line:n.length,col:n[n.length-1].length+1}}class kH{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}=xp(this.input,this.index);return new Error(`Parse error: Unexpected "${t}" at line ${n} column ${r}.
509
+ ${this.dialectInfo()}`)}dialectInfo(){return this.dialectName==="sql"?`This likely happens because you're using the default "sql" dialect.
510
+ If possible, please select a more specific dialect (like sqlite, postgresql, etc).`:`SQL dialect used: "${this.dialectName}".`}getWhitespace(){sT.lastIndex=this.index;const t=sT.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 ET=/\/\*/uy,YH=/[\s\S]/uy,jH=/\*\//uy;class WH{constructor(){this.lastIndex=0}exec(t){let n="",r,o=0;if(r=this.matchSection(ET,t))n+=r,o++;else return null;for(;o>0;)if(r=this.matchSection(ET,t))n+=r,o++;else if(r=this.matchSection(jH,t))n+=r,o--;else if(r=this.matchSection(YH,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 VH{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 kH(r,this.dialectName).tokenize(t);return this.cfg.postProcess?this.cfg.postProcess(o):o}buildRulesBeforeParams(t){var n,r,o;return this.validRules([{type:W.DISABLE_COMMENT,regex:/(\/\* *sql-formatter-disable *\*\/[\s\S]*?(?:\/\* *sql-formatter-enable *\*\/|$))/uy},{type:W.BLOCK_COMMENT,regex:t.nestedBlockComments?new WH:/(\/\*[^]*?\*\/)/uy},{type:W.LINE_COMMENT,regex:wH((n=t.lineCommentTypes)!==null&&n!==void 0?n:["--"])},{type:W.QUOTED_IDENTIFIER,regex:cT(t.identTypes)},{type:W.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:W.RESERVED_KEYWORD_PHRASE,regex:xt((r=t.reservedKeywordPhrases)!==null&&r!==void 0?r:[],t.identChars),text:_e},{type:W.RESERVED_DATA_TYPE_PHRASE,regex:xt((o=t.reservedDataTypePhrases)!==null&&o!==void 0?o:[],t.identChars),text:_e},{type:W.CASE,regex:/CASE\b/iuy,text:_e},{type:W.END,regex:/END\b/iuy,text:_e},{type:W.BETWEEN,regex:/BETWEEN\b/iuy,text:_e},{type:W.LIMIT,regex:t.reservedClauses.includes("LIMIT")?/LIMIT\b/iuy:void 0,text:_e},{type:W.RESERVED_CLAUSE,regex:xt(t.reservedClauses,t.identChars),text:_e},{type:W.RESERVED_SELECT,regex:xt(t.reservedSelect,t.identChars),text:_e},{type:W.RESERVED_SET_OPERATION,regex:xt(t.reservedSetOperations,t.identChars),text:_e},{type:W.WHEN,regex:/WHEN\b/iuy,text:_e},{type:W.ELSE,regex:/ELSE\b/iuy,text:_e},{type:W.THEN,regex:/THEN\b/iuy,text:_e},{type:W.RESERVED_JOIN,regex:xt(t.reservedJoins,t.identChars),text:_e},{type:W.AND,regex:/AND\b/iuy,text:_e},{type:W.OR,regex:/OR\b/iuy,text:_e},{type:W.XOR,regex:t.supportsXor?/XOR\b/iuy:void 0,text:_e},...t.operatorKeyword?[{type:W.OPERATOR,regex:/OPERATOR *\([^)]+\)/iuy}]:[],{type:W.RESERVED_FUNCTION_NAME,regex:xt(t.reservedFunctionNames,t.identChars),text:_e},{type:W.RESERVED_DATA_TYPE,regex:xt(t.reservedDataTypes,t.identChars),text:_e},{type:W.RESERVED_KEYWORD,regex:xt(t.reservedKeywords,t.identChars),text:_e}])}buildRulesAfterParams(t){var n,r;return this.validRules([{type:W.VARIABLE,regex:t.variableTypes?GH(t.variableTypes):void 0},{type:W.STRING,regex:cT(t.stringTypes)},{type:W.IDENTIFIER,regex:HH(t.identChars)},{type:W.DELIMITER,regex:/[;]/uy},{type:W.COMMA,regex:/[,]/y},{type:W.OPEN_PAREN,regex:iT("open",t.extraParens)},{type:W.CLOSE_PAREN,regex:iT("close",t.extraParens)},{type:W.OPERATOR,regex:aT(["+","-","/",">","<","=","<>","<=",">=","!=",...(n=t.operators)!==null&&n!==void 0?n:[]])},{type:W.ASTERISK,regex:/[*]/uy},{type:W.PROPERTY_ACCESS_OPERATOR,regex:aT([".",...(r=t.propertyAccessOperators)!==null&&r!==void 0?r:[]])}])}buildParamRules(t,n){var r,o,s,a,l;const E={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)||((s=t.paramTypes)===null||s===void 0?void 0:s.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:W.NAMED_PARAMETER,regex:cl(E.named,_p(t.paramChars||t.identChars)),key:c=>c.slice(1)},{type:W.QUOTED_PARAMETER,regex:cl(E.quoted,Lp(t.identTypes)),key:c=>(({tokenKey:d,quoteChar:u})=>d.replace(new RegExp(st("\\"+u),"gu"),u))({tokenKey:c.slice(2,-1),quoteChar:c.slice(-1)})},{type:W.NUMBERED_PARAMETER,regex:cl(E.numbered,"[0-9]+"),key:c=>c.slice(1)},{type:W.POSITIONAL_PARAMETER,regex:E.positional?/[?]/y:void 0},...E.custom.map(c=>{var d;return{type:W.CUSTOM_PARAMETER,regex:yn(c.regex),key:(d=c.key)!==null&&d!==void 0?d:(u=>u)}})])}validRules(t){return t.filter(n=>!!n.regex)}}const _e=e=>_s(e.toUpperCase()),dT=new Map,$H=e=>{let t=dT.get(e);return t||(t=XH(e),dT.set(e,t)),t},XH=e=>({tokenizer:new VH(e.tokenizerOptions,e.name),formatOptions:KH(e.formatOptions)}),KH=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 zH(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"?" ".repeat(10):e.useTabs?" ":" ".repeat(e.tabWidth)}function Hn(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"}class JH{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 xs={exports:{}},qH=xs.exports,uT;function QH(){return uT||(uT=1,(function(e){(function(t,n){e.exports?e.exports=n():t.nearley=n()})(qH,function(){function t(c,d,u){return this.id=++t.highestId,this.name=c,this.symbols=d,this.postprocess=u,this}t.highestId=0,t.prototype.toString=function(c){var d=typeof c>"u"?this.symbols.map(E).join(" "):this.symbols.slice(0,c).map(E).join(" ")+" ● "+this.symbols.slice(c).map(E).join(" ");return this.name+" → "+d};function n(c,d,u,T){this.rule=c,this.dot=d,this.reference=u,this.data=[],this.wantedBy=T,this.isComplete=this.dot===c.symbols.length}n.prototype.toString=function(){return"{"+this.rule.toString(this.dot)+"}, from: "+(this.reference||0)},n.prototype.nextState=function(c){var d=new n(this.rule,this.dot+1,this.reference,this.wantedBy);return d.left=this,d.right=c,d.isComplete&&(d.data=d.build(),d.right=void 0),d},n.prototype.build=function(){var c=[],d=this;do c.push(d.right.data),d=d.left;while(d.left);return c.reverse(),c},n.prototype.finish=function(){this.rule.postprocess&&(this.data=this.rule.postprocess(this.data,this.reference,a.fail))};function r(c,d){this.grammar=c,this.index=d,this.states=[],this.wants={},this.scannable=[],this.completed={}}r.prototype.process=function(c){for(var d=this.states,u=this.wants,T=this.completed,S=0;S<d.length;S++){var A=d[S];if(A.isComplete){if(A.finish(),A.data!==a.fail){for(var f=A.wantedBy,I=f.length;I--;){var p=f[I];this.complete(p,A)}if(A.reference===this.index){var O=A.rule.name;(this.completed[O]=this.completed[O]||[]).push(A)}}}else{var O=A.rule.symbols[A.dot];if(typeof O!="string"){this.scannable.push(A);continue}if(u[O]){if(u[O].push(A),T.hasOwnProperty(O))for(var N=T[O],I=0;I<N.length;I++){var h=N[I];this.complete(A,h)}}else u[O]=[A],this.predict(O)}}},r.prototype.predict=function(c){for(var d=this.grammar.byName[c]||[],u=0;u<d.length;u++){var T=d[u],S=this.wants[c],A=new n(T,0,this.index,S);this.states.push(A)}},r.prototype.complete=function(c,d){var u=c.nextState(d);this.states.push(u)};function o(c,d){this.rules=c,this.start=d||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,d){var u=T.Lexer;T.ParserStart&&(d=T.ParserStart,T=T.ParserRules);var T=T.map(function(A){return new t(A.name,A.symbols,A.postprocess)}),S=new o(T,d);return S.lexer=u,S};function s(){this.reset("")}s.prototype.reset=function(c,d){this.buffer=c,this.index=0,this.line=d?d.line:1,this.lastLineBreak=d?-d.col:0},s.prototype.next=function(){if(this.index<this.buffer.length){var c=this.buffer[this.index++];return c===`
511
+ `&&(this.line+=1,this.lastLineBreak=this.index),{value:c}}},s.prototype.save=function(){return{line:this.line,col:this.index-this.lastLineBreak}},s.prototype.formatError=function(c,d){var u=this.buffer;if(typeof u=="string"){var T=u.split(`
512
+ `).slice(Math.max(0,this.line-5),this.line),S=u.indexOf(`
513
+ `,this.index);S===-1&&(S=u.length);var A=this.index-this.lastLineBreak,f=String(this.line).length;return d+=" at line "+this.line+" col "+A+`:
514
+
515
+ `,d+=T.map(function(p,O){return I(this.line-T.length+O+1,f)+" "+p},this).join(`
516
+ `),d+=`
517
+ `+I("",f+A)+`^
518
+ `,d}else return d+" at index "+(this.index-1);function I(p,O){var N=String(p);return Array(O-N.length+1).join(" ")+N}};function a(c,d,u){if(c instanceof o)var T=c,u=d;else var T=o.fromCompiled(c,d);this.grammar=T,this.options={keepHistory:!1,lexer:T.lexer||new s};for(var S in u||{})this.options[S]=u[S];this.lexer=this.options.lexer,this.lexerState=void 0;var A=new r(T,0);this.table=[A],A.wants[T.start]=[],A.predict(T.start),A.process(),this.current=0}a.fail={},a.prototype.feed=function(c){var d=this.lexer;d.reset(c,this.lexerState);for(var u;;){try{if(u=d.next(),!u)break}catch(g){var f=new r(this.grammar,this.current+1);this.table.push(f);var T=new Error(this.reportLexerError(g));throw T.offset=this.current,T.token=g.token,T}var S=this.table[this.current];this.options.keepHistory||delete this.table[this.current-1];var A=this.current+1,f=new r(this.grammar,A);this.table.push(f);for(var I=u.text!==void 0?u.text:u.value,p=d.constructor===s?u.value:u,O=S.scannable,N=O.length;N--;){var h=O[N],C=h.rule.symbols[h.dot];if(C.test?C.test(p):C.type?C.type===u.type:C.literal===I){var m=h.nextState({data:p,token:u,isToken:!0,reference:A-1});f.states.push(m)}}if(f.process(),f.states.length===0){var T=new Error(this.reportError(u));throw T.offset=this.current,T.token=u,T}this.options.keepHistory&&(S.lexerState=d.save()),this.current++}return S&&(this.lexerState=d.save()),this.results=this.finish(),this},a.prototype.reportLexerError=function(c){var d,u,T=c.token;return T?(d="input "+JSON.stringify(T.text[0])+" (lexer error)",u=this.lexer.formatError(T,"Syntax error")):(d="input (lexer error)",u=c.message),this.reportErrorCommon(u,d)},a.prototype.reportError=function(c){var d=(c.type?c.type+" token: ":"")+JSON.stringify(c.value!==void 0?c.value:c),u=this.lexer.formatError(c,"Syntax error");return this.reportErrorCommon(u,d)},a.prototype.reportErrorCommon=function(c,d){var u=[];u.push(c);var T=this.table.length-2,S=this.table[T],A=S.states.filter(function(I){var p=I.rule.symbols[I.dot];return p&&typeof p!="string"});if(A.length===0)u.push("Unexpected "+d+`. I did not expect any more input. Here is the state of my parse table:
519
+ `),this.displayStateStack(S.states,u);else{u.push("Unexpected "+d+`. Instead, I was expecting to see one of the following:
520
+ `);var f=A.map(function(I){return this.buildFirstStateStack(I,[])||[I]},this);f.forEach(function(I){var p=I[0],O=p.rule.symbols[p.dot],N=this.getSymbolDisplay(O);u.push("A "+N+" based on:"),this.displayStateStack(I,u)},this)}return u.push(""),u.join(`
521
+ `)},a.prototype.displayStateStack=function(c,d){for(var u,T=0,S=0;S<c.length;S++){var A=c[S],f=A.rule.toString(A.dot);f===u?T++:(T>0&&d.push(" ^ "+T+" more lines identical to this"),T=0,d.push(" "+f)),u=f}},a.prototype.getSymbolDisplay=function(c){return l(c)},a.prototype.buildFirstStateStack=function(c,d){if(d.indexOf(c)!==-1)return null;if(c.wantedBy.length===0)return[c];var u=c.wantedBy[0],T=[c].concat(d),S=this.buildFirstStateStack(u,T);return S===null?null:[c].concat(S)},a.prototype.save=function(){var c=this.table[this.current];return c.lexerState=this.lexerState,c},a.prototype.restore=function(c){var d=c.index;this.current=d,this.table[d]=c,this.table.splice(d+1),this.lexerState=c.lexerState,this.results=this.finish()},a.prototype.rewind=function(c){if(!this.options.keepHistory)throw new Error("set option `keepHistory` to enable rewinding");this.restore(this.table[c])},a.prototype.finish=function(){var c=[],d=this.grammar.start,u=this.table[this.table.length-1];return u.states.forEach(function(T){T.rule.name===d&&T.dot===T.rule.symbols.length&&T.reference===0&&T.data!==a.fail&&c.push(T)}),c.map(function(T){return T.data})};function l(c){var d=typeof c;if(d==="string")return c;if(d==="object"){if(c.literal)return JSON.stringify(c.literal);if(c instanceof RegExp)return"character matching "+c;if(c.type)return c.type+" token";if(c.test)return"token matching "+String(c.test);throw new Error("Unknown symbol type: "+c)}}function E(c){var d=typeof c;if(d==="string")return c;if(d==="object"){if(c.literal)return JSON.stringify(c.literal);if(c instanceof RegExp)return c.toString();if(c.type)return"%"+c.type;if(c.test)return"<"+String(c.test)+">";throw new Error("Unknown symbol type: "+c)}}return{Parser:a,Grammar:o,Rule:t}})})(xs)),xs.exports}var ZH=QH();const e2=ai(ZH);function t2(e){return e.map(n2).map(r2).map(o2).map(s2).map(i2)}const n2=(e,t,n)=>{if(mp(e.type)){const r=a2(n,t);if(r&&r.type===W.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:W.IDENTIFIER,text:e.raw});const o=Ir(n,t);if(o&&o.type===W.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:W.IDENTIFIER,text:e.raw})}return e},r2=(e,t,n)=>{if(e.type===W.RESERVED_FUNCTION_NAME){const r=Ir(n,t);if(!r||!yp(r))return Object.assign(Object.assign({},e),{type:W.IDENTIFIER,text:e.raw})}return e},o2=(e,t,n)=>{if(e.type===W.RESERVED_DATA_TYPE){const r=Ir(n,t);if(r&&yp(r))return Object.assign(Object.assign({},e),{type:W.RESERVED_PARAMETERIZED_DATA_TYPE})}return e},s2=(e,t,n)=>{if(e.type===W.IDENTIFIER){const r=Ir(n,t);if(r&&Dp(r))return Object.assign(Object.assign({},e),{type:W.ARRAY_IDENTIFIER})}return e},i2=(e,t,n)=>{if(e.type===W.RESERVED_DATA_TYPE){const r=Ir(n,t);if(r&&Dp(r))return Object.assign(Object.assign({},e),{type:W.ARRAY_KEYWORD})}return e},a2=(e,t)=>Ir(e,t,-1),Ir=(e,t,n=1)=>{let r=1;for(;e[t+r*n]&&l2(e[t+r*n]);)r++;return e[t+r*n]},yp=e=>e.type===W.OPEN_PAREN&&e.text==="(",Dp=e=>e.type===W.OPEN_PAREN&&e.text==="[",l2=e=>e.type===W.BLOCK_COMMENT||e.type===W.LINE_COMMENT;class Mp{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}=xp(this.input,t.start);return`Parse error at token: ${t.text} at line ${n} column ${r}`}has(t){return t in W}}var te;(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"})(te=te||(te={}));function El(e){return e[0]}const ie=new Mp(e=>[]),En=([[e]])=>e,xe=e=>({type:te.keyword,tokenType:e.type,text:e.text,raw:e.raw}),TT=e=>({type:te.data_type,text:e.text,raw:e.raw}),ye=(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),c2=(e,{leading:t,trailing:n})=>{if(t!=null&&t.length){const[r,...o]=e;e=[ye(r,{leading:t}),...o]}if(n!=null&&n.length){const r=e.slice(0,-1),o=e[e.length-1];e=[...r,ye(o,{trailing:n})]}return e},E2={Lexer:ie,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:[ie.has("DELIMITER")?{type:"DELIMITER"}:DELIMITER]},{name:"statement$subexpression$1",symbols:[ie.has("EOF")?{type:"EOF"}:EOF]},{name:"statement",symbols:["expressions_or_clauses","statement$subexpression$1"],postprocess:([e,[t]])=>({type:te.statement,children:e,hasSemicolon:t.type===W.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:En},{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:[ie.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:El},{name:"limit_clause$ebnf$1",symbols:[],postprocess:()=>null},{name:"limit_clause",symbols:[ie.has("LIMIT")?{type:"LIMIT"}:LIMIT,"_","expression_chain_","limit_clause$ebnf$1"],postprocess:([e,t,n,r])=>{if(r){const[o,s]=r;return{type:te.limit_clause,limitKw:ye(xe(e),{trailing:t}),offset:n,count:s}}else return{type:te.limit_clause,limitKw:ye(xe(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:[ie.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT,"select_clause$subexpression$1"],postprocess:([e,[t,n]])=>({type:te.clause,nameKw:xe(e),children:[t,...n]})},{name:"select_clause",symbols:[ie.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT],postprocess:([e])=>({type:te.clause,nameKw:xe(e),children:[]})},{name:"all_columns_asterisk",symbols:[ie.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK],postprocess:()=>({type:te.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:[ie.has("RESERVED_CLAUSE")?{type:"RESERVED_CLAUSE"}:RESERVED_CLAUSE,"other_clause$ebnf$1"],postprocess:([e,t])=>({type:te.clause,nameKw:xe(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:[ie.has("RESERVED_SET_OPERATION")?{type:"RESERVED_SET_OPERATION"}:RESERVED_SET_OPERATION,"set_operation$ebnf$1"],postprocess:([e,t])=>({type:te.set_operation,nameKw:xe(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:El},{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])=>ye(e,{trailing:t})},{name:"_expression_with_comments",symbols:["_","expression"],postprocess:([e,t])=>ye(t,{leading:e})},{name:"_andless_expression_with_comments",symbols:["_","andless_expression"],postprocess:([e,t])=>ye(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:En},{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:En},{name:"expression$subexpression$1",symbols:["andless_expression"]},{name:"expression$subexpression$1",symbols:["logic_operator"]},{name:"expression",symbols:["expression$subexpression$1"],postprocess:En},{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:En},{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:En},{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:En},{name:"array_subscript",symbols:[ie.has("ARRAY_IDENTIFIER")?{type:"ARRAY_IDENTIFIER"}:ARRAY_IDENTIFIER,"_","square_brackets"],postprocess:([e,t,n])=>({type:te.array_subscript,array:ye({type:te.identifier,quoted:!1,text:e.text},{trailing:t}),parenthesis:n})},{name:"array_subscript",symbols:[ie.has("ARRAY_KEYWORD")?{type:"ARRAY_KEYWORD"}:ARRAY_KEYWORD,"_","square_brackets"],postprocess:([e,t,n])=>({type:te.array_subscript,array:ye(xe(e),{trailing:t}),parenthesis:n})},{name:"function_call",symbols:[ie.has("RESERVED_FUNCTION_NAME")?{type:"RESERVED_FUNCTION_NAME"}:RESERVED_FUNCTION_NAME,"_","parenthesis"],postprocess:([e,t,n])=>({type:te.function_call,nameKw:ye(xe(e),{trailing:t}),parenthesis:n})},{name:"parenthesis",symbols:[{literal:"("},"expressions_or_clauses",{literal:")"}],postprocess:([e,t,n])=>({type:te.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:te.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:te.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","_",ie.has("PROPERTY_ACCESS_OPERATOR")?{type:"PROPERTY_ACCESS_OPERATOR"}:PROPERTY_ACCESS_OPERATOR,"_","property_access$subexpression$1"],postprocess:([e,t,n,r,[o]])=>({type:te.property_access,object:ye(e,{trailing:t}),operator:n.text,property:ye(o,{leading:r})})},{name:"between_predicate",symbols:[ie.has("BETWEEN")?{type:"BETWEEN"}:BETWEEN,"_","andless_expression_chain","_",ie.has("AND")?{type:"AND"}:AND,"_","andless_expression"],postprocess:([e,t,n,r,o,s,a])=>({type:te.between_predicate,betweenKw:xe(e),expr1:c2(n,{leading:t,trailing:r}),andKw:xe(o),expr2:[ye(a,{leading:s})]})},{name:"case_expression$ebnf$1",symbols:["expression_chain_"],postprocess:El},{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:[ie.has("CASE")?{type:"CASE"}:CASE,"_","case_expression$ebnf$1","case_expression$ebnf$2",ie.has("END")?{type:"END"}:END],postprocess:([e,t,n,r,o])=>({type:te.case_expression,caseKw:ye(xe(e),{trailing:t}),endKw:xe(o),expr:n||[],clauses:r})},{name:"case_clause",symbols:[ie.has("WHEN")?{type:"WHEN"}:WHEN,"_","expression_chain_",ie.has("THEN")?{type:"THEN"}:THEN,"_","expression_chain_"],postprocess:([e,t,n,r,o,s])=>({type:te.case_when,whenKw:ye(xe(e),{trailing:t}),thenKw:ye(xe(r),{trailing:o}),condition:n,result:s})},{name:"case_clause",symbols:[ie.has("ELSE")?{type:"ELSE"}:ELSE,"_","expression_chain_"],postprocess:([e,t,n])=>({type:te.case_else,elseKw:ye(xe(e),{trailing:t}),result:n})},{name:"comma$subexpression$1",symbols:[ie.has("COMMA")?{type:"COMMA"}:COMMA]},{name:"comma",symbols:["comma$subexpression$1"],postprocess:([[e]])=>({type:te.comma})},{name:"asterisk$subexpression$1",symbols:[ie.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK]},{name:"asterisk",symbols:["asterisk$subexpression$1"],postprocess:([[e]])=>({type:te.operator,text:e.text})},{name:"operator$subexpression$1",symbols:[ie.has("OPERATOR")?{type:"OPERATOR"}:OPERATOR]},{name:"operator",symbols:["operator$subexpression$1"],postprocess:([[e]])=>({type:te.operator,text:e.text})},{name:"identifier$subexpression$1",symbols:[ie.has("IDENTIFIER")?{type:"IDENTIFIER"}:IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[ie.has("QUOTED_IDENTIFIER")?{type:"QUOTED_IDENTIFIER"}:QUOTED_IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[ie.has("VARIABLE")?{type:"VARIABLE"}:VARIABLE]},{name:"identifier",symbols:["identifier$subexpression$1"],postprocess:([[e]])=>({type:te.identifier,quoted:e.type!=="IDENTIFIER",text:e.text})},{name:"parameter$subexpression$1",symbols:[ie.has("NAMED_PARAMETER")?{type:"NAMED_PARAMETER"}:NAMED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ie.has("QUOTED_PARAMETER")?{type:"QUOTED_PARAMETER"}:QUOTED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ie.has("NUMBERED_PARAMETER")?{type:"NUMBERED_PARAMETER"}:NUMBERED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ie.has("POSITIONAL_PARAMETER")?{type:"POSITIONAL_PARAMETER"}:POSITIONAL_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ie.has("CUSTOM_PARAMETER")?{type:"CUSTOM_PARAMETER"}:CUSTOM_PARAMETER]},{name:"parameter",symbols:["parameter$subexpression$1"],postprocess:([[e]])=>({type:te.parameter,key:e.key,text:e.text})},{name:"literal$subexpression$1",symbols:[ie.has("NUMBER")?{type:"NUMBER"}:NUMBER]},{name:"literal$subexpression$1",symbols:[ie.has("STRING")?{type:"STRING"}:STRING]},{name:"literal",symbols:["literal$subexpression$1"],postprocess:([[e]])=>({type:te.literal,text:e.text})},{name:"keyword$subexpression$1",symbols:[ie.has("RESERVED_KEYWORD")?{type:"RESERVED_KEYWORD"}:RESERVED_KEYWORD]},{name:"keyword$subexpression$1",symbols:[ie.has("RESERVED_KEYWORD_PHRASE")?{type:"RESERVED_KEYWORD_PHRASE"}:RESERVED_KEYWORD_PHRASE]},{name:"keyword$subexpression$1",symbols:[ie.has("RESERVED_JOIN")?{type:"RESERVED_JOIN"}:RESERVED_JOIN]},{name:"keyword",symbols:["keyword$subexpression$1"],postprocess:([[e]])=>xe(e)},{name:"data_type$subexpression$1",symbols:[ie.has("RESERVED_DATA_TYPE")?{type:"RESERVED_DATA_TYPE"}:RESERVED_DATA_TYPE]},{name:"data_type$subexpression$1",symbols:[ie.has("RESERVED_DATA_TYPE_PHRASE")?{type:"RESERVED_DATA_TYPE_PHRASE"}:RESERVED_DATA_TYPE_PHRASE]},{name:"data_type",symbols:["data_type$subexpression$1"],postprocess:([[e]])=>TT(e)},{name:"data_type",symbols:[ie.has("RESERVED_PARAMETERIZED_DATA_TYPE")?{type:"RESERVED_PARAMETERIZED_DATA_TYPE"}:RESERVED_PARAMETERIZED_DATA_TYPE,"_","parenthesis"],postprocess:([e,t,n])=>({type:te.parameterized_data_type,dataType:ye(TT(e),{trailing:t}),parenthesis:n})},{name:"logic_operator$subexpression$1",symbols:[ie.has("AND")?{type:"AND"}:AND]},{name:"logic_operator$subexpression$1",symbols:[ie.has("OR")?{type:"OR"}:OR]},{name:"logic_operator$subexpression$1",symbols:[ie.has("XOR")?{type:"XOR"}:XOR]},{name:"logic_operator",symbols:["logic_operator$subexpression$1"],postprocess:([[e]])=>xe(e)},{name:"other_keyword$subexpression$1",symbols:[ie.has("WHEN")?{type:"WHEN"}:WHEN]},{name:"other_keyword$subexpression$1",symbols:[ie.has("THEN")?{type:"THEN"}:THEN]},{name:"other_keyword$subexpression$1",symbols:[ie.has("ELSE")?{type:"ELSE"}:ELSE]},{name:"other_keyword$subexpression$1",symbols:[ie.has("END")?{type:"END"}:END]},{name:"other_keyword",symbols:["other_keyword$subexpression$1"],postprocess:([[e]])=>xe(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:[ie.has("LINE_COMMENT")?{type:"LINE_COMMENT"}:LINE_COMMENT],postprocess:([e])=>({type:te.line_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[ie.has("BLOCK_COMMENT")?{type:"BLOCK_COMMENT"}:BLOCK_COMMENT],postprocess:([e])=>({type:te.block_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[ie.has("DISABLE_COMMENT")?{type:"DISABLE_COMMENT"}:DISABLE_COMMENT],postprocess:([e])=>({type:te.disable_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})}],ParserStart:"main"},{Parser:d2,Grammar:u2}=e2;function T2(e){let t={};const n=new Mp(o=>[...t2(e.tokenize(o,t)),hp(o.length)]),r=new d2(u2.fromCompiled(E2),{lexer:n});return{parse:(o,s)=>{t=s;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
522
+ ${JSON.stringify(a,void 0,2)}`)}}}var j;(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"})(j=j||(j={}));class Pp{constructor(t){this.indentation=t,this.items=[]}add(...t){for(const n of t)switch(n){case j.SPACE:this.items.push(j.SPACE);break;case j.NO_SPACE:this.trimHorizontalWhitespace();break;case j.NO_NEWLINE:this.trimWhitespace();break;case j.NEWLINE:this.trimHorizontalWhitespace(),this.addNewline(j.NEWLINE);break;case j.MANDATORY_NEWLINE:this.trimHorizontalWhitespace(),this.addNewline(j.MANDATORY_NEWLINE);break;case j.INDENT:this.addIndentation();break;case j.SINGLE_INDENT:this.items.push(j.SINGLE_INDENT);break;default:this.items.push(n)}}trimHorizontalWhitespace(){for(;S2(Hr(this.items));)this.items.pop()}trimWhitespace(){for(;R2(Hr(this.items));)this.items.pop()}addNewline(t){if(this.items.length>0)switch(Hr(this.items)){case j.NEWLINE:this.items.pop(),this.items.push(t);break;case j.MANDATORY_NEWLINE:break;default:this.items.push(t);break}}addIndentation(){for(let t=0;t<this.indentation.getLevel();t++)this.items.push(j.SINGLE_INDENT)}toString(){return this.items.map(t=>this.itemToString(t)).join("")}getLayoutItems(){return this.items}itemToString(t){switch(t){case j.SPACE:return" ";case j.NEWLINE:case j.MANDATORY_NEWLINE:return`
523
+ `;case j.SINGLE_INDENT:return this.indentation.getSingleIndent();default:return t}}}const S2=e=>e===j.SPACE||e===j.SINGLE_INDENT,R2=e=>e===j.SPACE||e===j.SINGLE_INDENT||e===j.NEWLINE;function ST(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 RT(e){return kw(e)||e===W.RESERVED_CLAUSE||e===W.RESERVED_SELECT||e===W.RESERVED_SET_OPERATION||e===W.RESERVED_JOIN||e===W.LIMIT}const dl="top-level",f2="block-level";class bp{constructor(t){this.indent=t,this.indentTypes=[]}getSingleIndent(){return this.indent}getLevel(){return this.indentTypes.length}increaseTopLevel(){this.indentTypes.push(dl)}increaseBlockLevel(){this.indentTypes.push(f2)}decreaseTopLevel(){this.indentTypes.length>0&&Hr(this.indentTypes)===dl&&this.indentTypes.pop()}decreaseBlockLevel(){for(;this.indentTypes.length>0&&this.indentTypes.pop()===dl;);}}class A2 extends Pp{constructor(t){super(new bp("")),this.expressionWidth=t,this.length=0,this.trailingSpace=!1}add(...t){if(t.forEach(n=>this.addToLength(n)),this.length>this.expressionWidth)throw new Jl;super.add(...t)}addToLength(t){if(typeof t=="string")this.length+=t.length,this.trailingSpace=!1;else{if(t===j.MANDATORY_NEWLINE||t===j.NEWLINE)throw new Jl;t===j.INDENT||t===j.SINGLE_INDENT||t===j.SPACE?this.trailingSpace||(this.length++,this.trailingSpace=!0):(t===j.NO_NEWLINE||t===j.NO_SPACE)&&this.trailingSpace&&(this.trailingSpace=!1,this.length--)}}}class Jl extends Error{}class si{constructor({cfg:t,dialectCfg:n,params:r,layout:o,inline:s=!1}){this.inline=!1,this.nodes=[],this.index=-1,this.cfg=t,this.dialectCfg=n,this.inline=s,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 te.function_call:return this.formatFunctionCall(t);case te.parameterized_data_type:return this.formatParameterizedDataType(t);case te.array_subscript:return this.formatArraySubscript(t);case te.property_access:return this.formatPropertyAccess(t);case te.parenthesis:return this.formatParenthesis(t);case te.between_predicate:return this.formatBetweenPredicate(t);case te.case_expression:return this.formatCaseExpression(t);case te.case_when:return this.formatCaseWhen(t);case te.case_else:return this.formatCaseElse(t);case te.clause:return this.formatClause(t);case te.set_operation:return this.formatSetOperation(t);case te.limit_clause:return this.formatLimitClause(t);case te.all_columns_asterisk:return this.formatAllColumnsAsterisk(t);case te.literal:return this.formatLiteral(t);case te.identifier:return this.formatIdentifier(t);case te.parameter:return this.formatParameter(t);case te.operator:return this.formatOperator(t);case te.comma:return this.formatComma(t);case te.line_comment:return this.formatLineComment(t);case te.block_comment:return this.formatBlockComment(t);case te.disable_comment:return this.formatBlockComment(t);case te.data_type:return this.formatDataType(t);case te.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 te.data_type:n=this.showDataType(t.array);break;case te.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(j.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(j.NO_SPACE,t.closeParen,j.SPACE)):(this.layout.add(t.openParen,j.NEWLINE),Hn(this.cfg)?(this.layout.add(j.INDENT),this.layout=this.formatSubExpression(t.children)):(this.layout.indentation.increaseBlockLevel(),this.layout.add(j.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseBlockLevel()),this.layout.add(j.NEWLINE,j.INDENT,t.closeParen,j.SPACE))}formatBetweenPredicate(t){this.layout.add(this.showKw(t.betweenKw),j.SPACE),this.layout=this.formatSubExpression(t.expr1),this.layout.add(j.NO_SPACE,j.SPACE,this.showNonTabularKw(t.andKw),j.SPACE),this.layout=this.formatSubExpression(t.expr2),this.layout.add(j.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(j.NEWLINE,j.INDENT),this.formatNode(t.endKw)}formatCaseWhen(t){this.layout.add(j.NEWLINE,j.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(j.NEWLINE,j.INDENT),this.formatNode(t.elseKw),this.layout=this.formatSubExpression(t.result)}formatClause(t){this.isOnelineClause(t)?this.formatClauseInOnelineStyle(t):Hn(this.cfg)?this.formatClauseInTabularStyle(t):this.formatClauseInIndentedStyle(t)}isOnelineClause(t){return Hn(this.cfg)?this.dialectCfg.tabularOnelineClauses[t.nameKw.text]:this.dialectCfg.onelineClauses[t.nameKw.text]}formatClauseInIndentedStyle(t){this.layout.add(j.NEWLINE,j.INDENT,this.showKw(t.nameKw),j.NEWLINE),this.layout.indentation.increaseTopLevel(),this.layout.add(j.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatClauseInOnelineStyle(t){this.layout.add(j.NEWLINE,j.INDENT,this.showKw(t.nameKw),j.SPACE),this.layout=this.formatSubExpression(t.children)}formatClauseInTabularStyle(t){this.layout.add(j.NEWLINE,j.INDENT,this.showKw(t.nameKw),j.SPACE),this.layout.indentation.increaseTopLevel(),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatSetOperation(t){this.layout.add(j.NEWLINE,j.INDENT,this.showKw(t.nameKw),j.NEWLINE),this.layout.add(j.INDENT),this.layout=this.formatSubExpression(t.children)}formatLimitClause(t){this.withComments(t.limitKw,()=>{this.layout.add(j.NEWLINE,j.INDENT,this.showKw(t.limitKw))}),this.layout.indentation.increaseTopLevel(),Hn(this.cfg)?this.layout.add(j.SPACE):this.layout.add(j.NEWLINE,j.INDENT),t.offset?(this.layout=this.formatSubExpression(t.offset),this.layout.add(j.NO_SPACE,",",j.SPACE),this.layout=this.formatSubExpression(t.count)):this.layout=this.formatSubExpression(t.count),this.layout.indentation.decreaseTopLevel()}formatAllColumnsAsterisk(t){this.layout.add("*",j.SPACE)}formatLiteral(t){this.layout.add(t.text,j.SPACE)}formatIdentifier(t){this.layout.add(this.showIdentifier(t),j.SPACE)}formatParameter(t){this.layout.add(this.params.get(t),j.SPACE)}formatOperator({text:t}){this.cfg.denseOperators||this.dialectCfg.alwaysDenseOperators.includes(t)?this.layout.add(j.NO_SPACE,t):t===":"?this.layout.add(j.NO_SPACE,t,j.SPACE):this.layout.add(t,j.SPACE)}formatComma(t){this.inline?this.layout.add(j.NO_SPACE,",",j.SPACE):this.layout.add(j.NO_SPACE,",",j.NEWLINE,j.INDENT)}withComments(t,n){this.formatComments(t.leadingComments),n(),this.formatComments(t.trailingComments)}formatComments(t){t&&t.forEach(n=>{n.type===te.line_comment?this.formatLineComment(n):this.formatBlockComment(n)})}formatLineComment(t){ll(t.precedingWhitespace||"")?this.layout.add(j.NEWLINE,j.INDENT,t.text,j.MANDATORY_NEWLINE,j.INDENT):this.layout.getLayoutItems().length>0?this.layout.add(j.NO_NEWLINE,j.SPACE,t.text,j.MANDATORY_NEWLINE,j.INDENT):this.layout.add(t.text,j.MANDATORY_NEWLINE,j.INDENT)}formatBlockComment(t){t.type===te.block_comment&&this.isMultilineBlockComment(t)?(this.splitBlockComment(t.text).forEach(n=>{this.layout.add(j.NEWLINE,j.INDENT,n)}),this.layout.add(j.NEWLINE,j.INDENT)):this.layout.add(t.text,j.SPACE)}isMultilineBlockComment(t){return ll(t.text)||ll(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(Hr(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 si({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 si({cfg:this.cfg,dialectCfg:this.dialectCfg,params:this.params,layout:new A2(this.cfg.expressionWidth),inline:!0}).format(t)}catch(r){if(r instanceof Jl){this.params.setPositionalParameterIndex(n);return}else throw r}}formatKeywordNode(t){switch(t.tokenType){case W.RESERVED_JOIN:return this.formatJoin(t);case W.AND:case W.OR:case W.XOR:return this.formatLogicalOperator(t);default:return this.formatKeyword(t)}}formatJoin(t){Hn(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add(j.NEWLINE,j.INDENT,this.showKw(t),j.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add(j.NEWLINE,j.INDENT,this.showKw(t),j.SPACE)}formatKeyword(t){this.layout.add(this.showKw(t),j.SPACE)}formatLogicalOperator(t){this.cfg.logicalOperatorNewline==="before"?Hn(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add(j.NEWLINE,j.INDENT,this.showKw(t),j.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add(j.NEWLINE,j.INDENT,this.showKw(t),j.SPACE):this.layout.add(this.showKw(t),j.NEWLINE,j.INDENT)}formatDataType(t){this.layout.add(this.showDataType(t),j.SPACE)}showKw(t){return RT(t.tokenType)?ST(this.showNonTabularKw(t),this.cfg.indentStyle):this.showNonTabularKw(t)}showNonTabularKw(t){switch(this.cfg.keywordCase){case"preserve":return _s(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}showFunctionKw(t){return RT(t.tokenType)?ST(this.showNonTabularFunctionKw(t),this.cfg.indentStyle):this.showNonTabularFunctionKw(t)}showNonTabularFunctionKw(t){switch(this.cfg.functionCase){case"preserve":return _s(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 _s(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}}class p2{constructor(t,n){this.dialect=t,this.cfg=n,this.params=new JH(this.cfg.params)}format(t){const n=this.parse(t);return this.formatAst(n).trimEnd()}parse(t){return T2(this.dialect.tokenizer).parse(t,this.cfg.paramTypes||{})}formatAst(t){return t.map(n=>this.formatStatement(n)).join(`
524
+ `.repeat(this.cfg.linesBetweenQueries+1))}formatStatement(t){const n=new si({cfg:this.cfg,dialectCfg:this.dialect.formatOptions,params:this.params,layout:new Pp(new bp(zH(this.cfg)))}).format(t.children);return t.hasSemicolon&&(this.cfg.newlineBeforeSemicolon?n.add(j.NEWLINE,";"):n.add(j.NO_NEWLINE,";")),n.toString()}}class ys extends Error{}function I2(e){const t=["multilineLists","newlineBeforeOpenParen","newlineBeforeCloseParen","aliasAs","commaPosition","tabulateAlias"];for(const n of t)if(n in e)throw new ys(`${n} config is no more supported.`);if(e.expressionWidth<=0)throw new ys(`expressionWidth config must be positive number. Received ${e.expressionWidth} instead.`);if(e.params&&!O2(e.params)&&console.warn('WARNING: All "params" option values should be strings.'),e.paramTypes&&!N2(e.paramTypes))throw new ys("Empty regex given in custom paramTypes. That would result in matching infinite amount of parameters.");return e}function O2(e){return(e instanceof Array?e:Object.values(e)).every(n=>typeof n=="string")}function N2(e){return e.custom&&Array.isArray(e.custom)?e.custom.every(t=>t.regex!==""):!0}var h2=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 vp={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"},m2=Object.keys(vp),C2={tabWidth:2,useTabs:!1,keywordCase:"preserve",identifierCase:"preserve",dataTypeCase:"preserve",functionCase:"preserve",indentStyle:"standard",logicalOperatorNewline:"before",expressionWidth:50,linesBetweenQueries:1,denseOperators:!1,newlineBeforeSemicolon:!1},g2=(e,t={})=>{if(typeof t.language=="string"&&!m2.includes(t.language))throw new ys(`Unsupported SQL dialect: ${t.language}`);const n=vp[t.language||"sql"];return L2(e,Object.assign(Object.assign({},t),{dialect:PH[n]}))},L2=(e,t)=>{var{dialect:n}=t,r=h2(t,["dialect"]);if(typeof e!="string")throw new Error("Invalid query argument. Expected string, instead got "+typeof e);const o=I2(Object.assign(Object.assign({},C2),r));return new p2($H(n),o).format(e)};function kn({children:e}){return i.jsxs("div",{style:{display:"flex",gap:0,marginBottom:2},children:[i.jsx("div",{style:{width:40,flexShrink:0}}),i.jsx("div",{style:{flex:1,minWidth:0},children:e})]})}const _2={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"},ul={sql:"#388bfd",markdown:"#56d364",dql:"#e3b341",param:"#e3b341",chart:"#a371f7",pivot:"#a371f7",single_value:"#a371f7",filter:"#ff7b72",table:"#79c0ff",map:"#7ce38b",writeback:"#d2a8ff",python:"#3572a5"},x2={table:{title:"Table",subtitle:"Render an upstream dataframe as a table with typed columns.",color:"#79c0ff"},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 y2(e,t){switch(e.status){case"running":return t.cellBorderRunning;case"success":return t.success;case"error":return t.error;default:return t.cellBorder}}function D2({cell:e,t}){var s;let n="",r=t.textMuted,o="";if(e.status==="running")n="[*]",r=t.cellBorderRunning;else if(e.status==="error")n="[!]",r=t.error;else if(e.executionCount!==void 0){if(n=`[${e.executionCount}]`,r=t.textMuted,((s=e.result)==null?void 0:s.executionTime)!==void 0){const a=e.result.executionTime;o=a<1e3?`${a}ms`:`${(a/1e3).toFixed(1)}s`}}else n="[ ]",r=t.textMuted;return i.jsxs("div",{style:{width:40,display:"flex",flexDirection:"column",alignItems:"center",paddingTop:12,flexShrink:0,gap:2},children:[i.jsx("span",{style:{fontFamily:t.fontMono,fontSize:11,color:r,lineHeight:1.4,userSelect:"none",transition:"color 0.2s"},children:e.status==="running"?i.jsxs("span",{style:{display:"inline-block",animation:"spin 0.8s linear infinite"},children:[i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:i.jsx("circle",{cx:"6",cy:"6",r:"4.5",stroke:r,strokeWidth:"1.5",strokeDasharray:"14 7"})}),i.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}):n}),o&&i.jsx("span",{style:{fontFamily:t.fontMono,fontSize:8,color:t.textMuted,lineHeight:1,userSelect:"none"},children:o})]})}function M2(e){if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=o=>{var s;return((s=e.match(new RegExp(`\\b${o}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:s[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 Tl(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 P2(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 b2({content:e,onChange:t,t:n}){const r=M2(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"},s={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 i.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px",padding:"5px 10px",borderBottom:`1px solid ${n.cellBorder}`,background:`${n.tableHeaderBg}40`},children:[i.jsxs("div",{style:a,children:[i.jsx("span",{style:s,children:"domain"}),i.jsx("input",{style:{...o,width:80},value:r.domain,placeholder:"e.g. finance",onChange:l=>t(Tl(e,"domain",l.target.value))})]}),i.jsxs("div",{style:a,children:[i.jsx("span",{style:s,children:"owner"}),i.jsx("input",{style:{...o,width:90},value:r.owner,placeholder:"e.g. data-team",onChange:l=>t(Tl(e,"owner",l.target.value))})]}),i.jsxs("div",{style:a,children:[i.jsx("span",{style:s,children:"tags"}),i.jsx("input",{style:{...o,width:110},value:r.tags.join(", "),placeholder:"revenue, kpi",onChange:l=>{const E=l.target.value.split(",").map(c=>c.trim()).filter(Boolean);t(P2(e,E))}})]}),i.jsxs("div",{style:{...a,flex:1},children:[i.jsx("span",{style:s,children:"description"}),i.jsx("input",{style:{...o,flex:1,minWidth:120},value:r.description,placeholder:"What this block measures",onChange:l=>t(Tl(e,"description",l.target.value))})]})]})}function v2({cell:e,index:t}){var se;const{state:n,dispatch:r}=de(),o=re[n.themeMode],{executeCell:s,executeDependents:a,cancelCell:l}=gi(),[E,c]=R.useState(!1),[d,u]=R.useState(!1),[T,S]=R.useState(e.name??""),[A,f]=R.useState(!0),[I,p]=R.useState("table"),[O,N]=R.useState(null),[h,C]=R.useState(!1),[m,g]=R.useState(!1),[y,_]=R.useState(!1),U=R.useMemo(()=>y?Xx(e,n.cells):null,[y,e,n.cells]),D=e.type==="sql"||e.type==="dql"||e.type==="chart"||e.type==="pivot"||e.type==="single_value"||e.type==="filter"||e.type==="table",b=y2(e,o),F=e.type!=="markdown"&&e.type!=="param",L=R.useRef(null),P=R.useRef(e.content),[M,w]=R.useState(!1),v=R.useMemo(()=>n.schemaTables.length>0?Object.fromEntries(n.schemaTables.map(V=>[V.name,V.columns.map(J=>J.name)])):void 0,[n.schemaTables]);R.useEffect(()=>{if(e.status==="success"&&e.result){const V=zr(e.result,e.chartConfig);N(V!=="table"?V:null),p(V!=="table"?"chart":"table")}},[e.status,e.result,e.chartConfig]);const x=R.useCallback(()=>{F&&s(e.id)},[e.id,s,F]),B=R.useCallback(V=>{r({type:"UPDATE_CELL",id:e.id,updates:{content:V}}),w(V!==P.current)},[e.id,r]),H=R.useCallback(()=>{var J;const V=P.current;r({type:"UPDATE_CELL",id:e.id,updates:{content:V}}),(J=L.current)==null||J.resetTo(V),w(!1)},[e.id,r]),Y=R.useCallback(()=>{if(e.content.trim())try{const V=g2(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]),K=R.useCallback(()=>{Y(),setTimeout(()=>s(e.id),80)},[Y,s,e.id]),X=R.useCallback(V=>r({type:"UPDATE_CELL",id:e.id,updates:V}),[r,e.id]);if(e.type==="param")return i.jsx(kn,{children:i.jsx(W_,{cell:e,themeMode:n.themeMode,onApplyParam:a})});if(e.type==="pivot")return i.jsx(kn,{children:i.jsx(Bx,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:X})});if(e.type==="single_value")return i.jsx(kn,{children:i.jsx(vx,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:X})});if(e.type==="filter")return i.jsx(kn,{children:i.jsx(xx,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:X})});if(e.type==="chart")return i.jsx(kn,{children:i.jsx(Cx,{cell:e,cells:n.cells,index:t,themeMode:n.themeMode,onUpdate:X})});const q=x2[e.type];if(q)return i.jsx(kn,{children:i.jsx(V_,{cell:e,themeMode:n.themeMode,title:q.title,subtitle:q.subtitle,color:q.color,badge:q.badge})});const ee=()=>{r({type:"DELETE_CELL",id:e.id})},Z=()=>{r({type:"MOVE_CELL",id:e.id,direction:"up"})},$=()=>{r({type:"MOVE_CELL",id:e.id,direction:"down"})},z=()=>{u(!1),r({type:"UPDATE_CELL",id:e.id,updates:{name:T.trim()||void 0}})},ce=(e.result||e.error)&&e.type!=="markdown";return e.result&&zr(e.result,e.chartConfig),i.jsxs("div",{onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{display:"flex",gap:0,marginBottom:2},children:[y&&U&&i.jsx(Yx,{cell:e,initialContent:U.derivedFromUpstream?U.content:void 0,initialName:U.suggestedName,initialDescription:U.suggestedDescription,onClose:()=>_(!1),onSaved:({path:V,name:J})=>{r({type:"FILE_ADDED",file:{name:J,path:V,type:"block",folder:"blocks"}})}}),i.jsx(D2,{cell:e,t:o}),i.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${E||e.status!=="idle"?b:o.cellBorder}`,borderLeft:`2px solid ${b}`,background:o.cellBg,overflow:"hidden",transition:"border-color 0.2s"},children:[i.jsxs("div",{style:{height:32,display:"flex",alignItems:"center",padding:"0 8px 0 10px",gap:8,borderBottom:`1px solid ${o.cellBorder}`,background:`${o.tableHeaderBg}80`},children:[i.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:10,fontWeight:700,fontFamily:o.fontMono,letterSpacing:"0.08em",color:ul[e.type]??o.accent,background:`${ul[e.type]??o.accent}18`,border:`1px solid ${ul[e.type]??o.accent}40`,borderRadius:4,padding:"1px 6px",flexShrink:0,textTransform:"uppercase"},children:_2[e.type]}),E&&(e.type==="sql"||e.type==="dql")&&i.jsx(Hx,{themeMode:n.themeMode,cellType:e.type,onInsert:V=>B(V)}),E&&(e.type==="sql"||e.type==="dql")&&i.jsx("button",{title:"Format SQL (clean up whitespace & keywords)",onClick:Y,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")&&i.jsx("button",{title:"Reset to last saved version (discard changes)",onClick:H,style:{background:"transparent",border:`1px solid ${o.btnBorder}`,borderRadius:4,color:"#f85149",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="#f85149"},onMouseLeave:V=>{V.currentTarget.style.borderColor=o.btnBorder},children:"↺ Reset"}),E&&D&&i.jsx("button",{title:"Save this cell as a reusable block",onClick:()=>_(!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")&&i.jsx(X_,{cells:n.cells,index:t,content:e.content,themeMode:n.themeMode,onInsertHandle:V=>{const J=`{{${V}}}`,Ee=e.content??"";if(Ee.includes(J))return;const Ae=Ee.trim().length===0?`SELECT * FROM ${J}`:`${Ee.replace(/\s*$/,"")} ${J}`;B(Ae)}}),d?i.jsx("input",{autoFocus:!0,value:T,onChange:V=>S(V.target.value),onBlur:z,onKeyDown:V=>{V.key==="Enter"&&z(),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&&i.jsx("span",{onClick:()=>{S(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}),i.jsx("div",{style:{flex:1}}),E&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[!e.name&&!d&&i.jsx(Yn,{title:"Name this cell",onClick:()=>{S(""),u(!0)},t:o,children:i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})})}),F&&e.status==="running"?i.jsx(Yn,{title:"Cancel execution",onClick:()=>l(e.id),t:o,danger:!0,children:i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:i.jsx("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1"})})}):F?i.jsx(Yn,{title:"Run cell (Shift+Enter)",onClick:x,t:o,accent:!0,children:i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:i.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})})}):null,i.jsx(Yn,{title:"Move up",onClick:Z,t:o,children:i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})})}),i.jsx(Yn,{title:"Move down",onClick:$,t:o,children:i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})})}),i.jsx(Yn,{title:"Delete cell",onClick:ee,t:o,danger:!0,children:i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"&&i.jsx(b2,{content:e.content,onChange:B,t:o}),e.type==="markdown"?i.jsx(j_,{value:e.content,onChange:B,themeMode:n.themeMode}):i.jsx(vc,{value:e.content,onChange:B,onRun:x,themeMode:n.themeMode,schema:v,errorMessage:e.status==="error"?e.error:void 0,editorRef:L}),ce&&i.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[i.jsxs("div",{style:{height:28,display:"flex",alignItems:"center",padding:"0 12px",gap:10,borderBottom:e.result&&A?`1px solid ${o.cellBorder}`:"none",background:`${o.tableHeaderBg}60`},children:[e.result&&i.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&&i.jsxs(i.Fragment,{children:[" · ",e.result.executionTime<1e3?`${e.result.executionTime}ms`:`${(e.result.executionTime/1e3).toFixed(2)}s`]})]}),e.error&&i.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.error},children:"Error"}),i.jsx("div",{style:{flex:1}}),e.result&&A&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:3,position:"relative"},children:[i.jsx("button",{onClick:()=>{p("table"),C(!1)},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${I==="table"?o.accent:o.btnBorder}`,background:I==="table"?`${o.accent}20`:"transparent",color:I==="table"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s"},children:"Table"}),i.jsxs("div",{style:{position:"relative"},children:[i.jsxs("button",{onClick:()=>{I==="chart"&&h?C(!1):(p("chart"),C(V=>!V))},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${I==="chart"?o.accent:o.btnBorder}`,background:I==="chart"?`${o.accent}20`:"transparent",color:I==="chart"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s",display:"flex",alignItems:"center",gap:3},children:[O?((se=_i.find(V=>V.value===O))==null?void 0:se.label)??"Chart":"Chart",i.jsx("svg",{width:"6",height:"6",viewBox:"0 0 8 8",fill:"currentColor",children:i.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),h&&i.jsx(U2,{selected:O,onSelect:V=>{N(V),p("chart"),C(!1)},onClose:()=>C(!1),t:o})]}),I==="chart"&&i.jsx("button",{onClick:()=>g(V=>!V),title:"Chart configuration",style:{padding:"1px 5px",fontSize:11,borderRadius:3,cursor:"pointer",border:`1px solid ${m?o.accent:o.btnBorder}`,background:m?`${o.accent}20`:"transparent",color:m?o.accent:o.textMuted,transition:"all 0.15s",display:"flex",alignItems:"center"},children:i.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:i.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"})})})]}),i.jsxs("button",{onClick:()=>f(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:[i.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:A?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.15s"},children:i.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})}),A?"Hide":"Show"]})]}),A&&i.jsxs(i.Fragment,{children:[e.error&&i.jsx(Jx,{message:e.error,themeMode:n.themeMode,onFix:F?K:void 0,schemaTables:n.schemaTables}),e.result&&!e.error&&(I==="chart"&&O?i.jsxs(i.Fragment,{children:[yi(O,e.result,n.themeMode,e.chartConfig),m&&i.jsx(w2,{columns:e.result.columns,chartConfig:e.chartConfig,onChange:V=>r({type:"UPDATE_CELL",id:e.id,updates:{chartConfig:{...e.chartConfig,...V}}}),t:o})]}):i.jsx(Li,{result:e.result,themeMode:n.themeMode}))]})]}),F&&i.jsx(Pw,{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 Yn({title:e,onClick:t,children:n,t:r,accent:o,danger:s}){const[a,l]=R.useState(!1);return i.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?s?`${r.error}18`:o?`${r.accent}18`:r.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:a?s?r.error:o?r.accent:r.textSecondary:r.textMuted,transition:"all 0.15s",padding:0},children:n})}function U2({selected:e,onSelect:t,onClose:n,t:r}){const[o,s]=R.useState(null);return me.useEffect(()=>{const a=l=>{setTimeout(()=>n(),0)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[n]),i.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:_i.map(({value:a,label:l})=>i.jsx("button",{onClick:()=>t(a),onMouseEnter:()=>s(a),onMouseLeave:()=>s(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 w2({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},s={fontSize:9,fontWeight:700,color:r.textMuted,fontFamily:r.font,letterSpacing:"0.05em",textTransform:"uppercase",minWidth:40,flexShrink:0};return i.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px 16px",padding:"8px 12px",borderTop:`1px solid ${r.cellBorder}`,background:`${r.tableHeaderBg}40`},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx("span",{style:s,children:"X axis"}),i.jsxs("select",{style:o,value:(t==null?void 0:t.x)??"",onChange:a=>n({x:a.target.value||void 0}),children:[i.jsx("option",{value:"",children:"Auto"}),e.map(a=>i.jsx("option",{value:a,children:a},a))]})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx("span",{style:s,children:"Y axis"}),i.jsxs("select",{style:o,value:(t==null?void 0:t.y)??"",onChange:a=>n({y:a.target.value||void 0}),children:[i.jsx("option",{value:"",children:"Auto"}),e.map(a=>i.jsx("option",{value:a,children:a},a))]})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx("span",{style:s,children:"Color"}),i.jsxs("select",{style:o,value:(t==null?void 0:t.color)??"",onChange:a=>n({color:a.target.value||void 0}),children:[i.jsx("option",{value:"",children:"None"}),e.map(a=>i.jsx("option",{value:a,children:a},a))]})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:150},children:[i.jsx("span",{style:s,children:"Title"}),i.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 B2=[{type:"sql",label:"SQL",icon:"SQL",color:"#388bfd",available:!0,group:"compute"},{type:"python",label:"Python",icon:"Py",color:"#3572a5",available:!1,group:"compute"},{type:"markdown",label:"Text",icon:"Tt",color:"#56d364",available:!0,group:"compute"},{type:"chart",label:"Chart",icon:"📊",color:"#a371f7",available:!0,group:"viz"},{type:"pivot",label:"Pivot",icon:"▦",color:"#a371f7",available:!0,group:"viz"},{type:"single_value",label:"Single value",icon:"123",color:"#a371f7",available:!0,group:"viz"},{type:"table",label:"Table",icon:"⊞",color:"#79c0ff",available:!0,group:"viz"},{type:"param",label:"Inputs",icon:"⌸",color:"#e3b341",available:!0,group:"io"},{type:"filter",label:"Filter",icon:"⟲",color:"#ff7b72",available:!0,group:"transform"},{type:"map",label:"Map",icon:"◉",color:"#7ce38b",available:!1,group:"viz"},{type:"writeback",label:"Writeback",icon:"⇧",color:"#d2a8ff",available:!1,group:"io"}],F2=[{type:"dql",label:"DQL block",icon:"◇",color:"#e3b341",available:!0,group:"compute"}];function Sl({afterId:e}){const{state:t,dispatch:n}=de(),r=re[t.themeMode],[o,s]=R.useState(!1),[a,l]=R.useState(!1),[E,c]=R.useState(!1),[d,u]=R.useState(!1),[T,S]=R.useState(""),[A,f]=R.useState(!1),I=R.useRef(null),p=R.useRef(null);R.useEffect(()=>{if(!a)return;function m(g){I.current&&!I.current.contains(g.target)&&(l(!1),c(!1),u(!1))}return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[a]);const O=m=>{const g=We(m);n({type:"ADD_CELL",cell:g,afterId:e}),l(!1),c(!1),u(!1)},N=t.files.filter(m=>m.type==="block"),h=T?N.filter(m=>m.name.toLowerCase().includes(T.toLowerCase())):N,C=m=>{const g=We("sql",`-- Block: ${m.path}
525
+ @include('${m.path}')`);n({type:"ADD_CELL",cell:g,afterId:e}),l(!1),c(!1),u(!1),S("")};return i.jsxs("div",{ref:I,onDragOver:m=>{m.dataTransfer.types.includes(Ws)&&(m.preventDefault(),f(!0))},onDragLeave:()=>f(!1),onDrop:m=>{const g=KR(m.dataTransfer.getData(Ws));if(!g)return;m.preventDefault(),f(!1);const y=We("sql",g.reference);n({type:"ADD_CELL",cell:y,afterId:e}),Q.trackUsage(g.name),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:g.name}}))},onMouseEnter:()=>s(!0),onMouseLeave:()=>{s(!1),f(!1)},style:{position:"relative",height:28,display:"flex",alignItems:"center",justifyContent:"center",cursor:"default"},children:[i.jsx("div",{style:{position:"absolute",left:0,right:0,height:1,background:A?r.accent:o||a?r.cellBorderActive:"transparent",transition:"background 0.15s"}}),(o||a||A)&&i.jsxs("button",{onClick:()=>l(m=>!m),style:{position:"relative",zIndex:2,height:22,padding:"0 10px",borderRadius:11,border:`1px solid ${A?r.accent:r.cellBorderActive}`,background:A?`${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:[i.jsx("span",{style:{fontSize:14,lineHeight:1,marginTop:-1},children:"+"}),"Add cell"]}),a&&i.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:720},children:[i.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"flex-start"},children:[B2.map(m=>i.jsx(fT,{entry:m,onClick:()=>{m.available&&O(m.type)},t:r},m.type)),i.jsx(G2,{open:E,onClick:()=>c(m=>!m),t:r})]}),E&&i.jsxs("div",{style:{display:"flex",gap:6,padding:"6px 2px 2px",borderTop:`1px solid ${r.cellBorder}`,alignItems:"center"},children:[F2.map(m=>i.jsx(fT,{entry:m,onClick:()=>O(m.type),t:r},m.type)),i.jsx("button",{onClick:()=>{u(m=>!m),setTimeout(()=>{var m;return(m=p.current)==null?void 0:m.focus()},50)},style:{background:d?`${r.accent}18`:"transparent",border:`1px solid ${r.cellBorder}`,borderRadius:6,color:r.textSecondary,cursor:"pointer",fontFamily:r.font,fontSize:11,fontWeight:500,padding:"6px 10px"},children:"Reference block…"})]}),d&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"4px 2px"},children:[i.jsx("input",{ref:p,value:T,onChange:m=>S(m.target.value),placeholder:"Search blocks...",style:{background:r.inputBg,border:`1px solid ${r.inputBorder}`,borderRadius:4,color:r.textPrimary,fontSize:11,fontFamily:r.font,padding:"6px 10px",outline:"none"}}),i.jsx("div",{style:{maxHeight:180,overflow:"auto",display:"flex",flexDirection:"column",gap:2},children:h.length===0?i.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,padding:"4px 8px",fontStyle:"italic"},children:N.length===0?"No blocks yet":"No matches"}):h.map(m=>i.jsx(H2,{file:m,onClick:()=>C(m),t:r},m.path))})]})]})]})}function fT({entry:e,onClick:t,t:n}){const[r,o]=R.useState(!1),s=!e.available;return i.jsxs("button",{onClick:t,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),disabled:s,title:s?`${e.label} — coming soon`:e.label,style:{background:s?"transparent":r?`${e.color}18`:"transparent",border:`1px solid ${s?n.cellBorder:r?e.color:n.cellBorder}`,borderRadius:8,cursor:s?"not-allowed":"pointer",color:s?n.textMuted:r?e.color:n.textSecondary,fontSize:11,fontFamily:n.font,fontWeight:500,padding:"8px 10px",minWidth:84,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:4,transition:"all 0.12s",opacity:s?.5:1,position:"relative"},children:[i.jsx("span",{style:{fontSize:14,fontFamily:n.fontMono,fontWeight:700,color:s?n.textMuted:e.color,letterSpacing:"0.02em"},children:e.icon}),i.jsx("span",{style:{letterSpacing:"0.02em"},children:e.label}),s&&i.jsx("span",{style:{position:"absolute",top:3,right:4,fontSize:8,color:n.textMuted,textTransform:"uppercase",letterSpacing:"0.08em"},children:"soon"})]})}function G2({open:e,onClick:t,t:n}){const[r,o]=R.useState(!1);return i.jsxs("button",{onClick:t,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),style:{background:e||r?`${n.accent}12`:"transparent",border:`1px solid ${e?n.accent:n.cellBorder}`,borderRadius:8,cursor:"pointer",color:r||e?n.accent:n.textSecondary,fontSize:11,fontFamily:n.font,fontWeight:500,padding:"8px 10px",minWidth:84,display:"flex",flexDirection:"column",alignItems:"center",gap:4,transition:"all 0.12s"},children:[i.jsx("span",{style:{fontSize:16,fontWeight:700,lineHeight:1},children:"⋯"}),i.jsx("span",{children:"More"})]})}function H2({file:e,onClick:t,t:n}){const[r,o]=R.useState(!1);return i.jsxs("button",{onClick:t,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),style:{background:r?n.sidebarItemHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:n.textPrimary,fontSize:11,fontFamily:n.font,padding:"6px 8px",textAlign:"left",display:"flex",flexDirection:"column",gap:1,transition:"background 0.1s"},children:[i.jsx("span",{style:{fontWeight:500},children:e.name.replace(/\.dql$/,"")}),i.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.fontMono},children:e.path})]})}function k2({registerCellRef:e}){const{state:t,dispatch:n}=de(),{executeCell:r}=gi(),o=re[t.themeMode],[s,a]=R.useState(null),l=R.useRef(0),[E,c]=R.useState(null),[d,u]=R.useState(null);R.useCallback(I=>{a(I)},[]),R.useEffect(()=>{s&&t.inspectorOpen&&n({type:"SET_INSPECTOR_CONTEXT",context:{kind:"cell",cellId:s}})},[s,t.inspectorOpen,n]),R.useEffect(()=>{function I(p){var C;if(!s)return;const O=p.target;if(O.tagName==="TEXTAREA"||O.tagName==="INPUT"||O.isContentEditable||O.closest(".cm-editor")){a(null);return}const N=t.cells,h=N.findIndex(m=>m.id===s);if(h!==-1)switch(p.key){case"a":{p.preventDefault();const m=We("sql");if(h===0)n({type:"ADD_CELL",cell:m,afterId:N[0].id}),n({type:"MOVE_CELL",id:m.id,direction:"up"});else{const g=N[h-1].id;n({type:"ADD_CELL",cell:m,afterId:g})}a(m.id);break}case"b":{p.preventDefault();const m=We("sql");n({type:"ADD_CELL",cell:m,afterId:s}),a(m.id);break}case"d":{p.preventDefault();const m=Date.now();if(m-l.current<=500){if(n({type:"DELETE_CELL",id:s}),N.length>1){const g=h>0?h-1:1;a(((C=N[g])==null?void 0:C.id)??null)}else a(null);l.current=0}else l.current=m;break}case"Enter":{if(p.shiftKey){p.preventDefault();const m=N[h];m&&m.type!=="markdown"&&r(m.id)}break}}}return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[s,t.cells,n,r]),R.useEffect(()=>{function I(p){p.target.closest("[data-cell-id]")||a(null)}return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[]);const T=R.useCallback((I,p)=>{c(p),I.dataTransfer.effectAllowed="move",I.dataTransfer.setData("text/plain",String(p));const O=I.currentTarget;setTimeout(()=>{O.style.opacity="0.4"},0)},[]),S=R.useCallback(I=>{I.currentTarget.style.opacity="1",c(null),u(null)},[]),A=R.useCallback((I,p)=>{I.preventDefault(),I.dataTransfer.dropEffect="move",u(p)},[]),f=R.useCallback((I,p)=>{I.preventDefault(),E!==null&&E!==p&&n({type:"REORDER_CELL",fromIndex:E,toIndex:p}),c(null),u(null)},[E,n]);return t.cells.length===0?i.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[i.jsx(Sl,{}),i.jsx(Y2,{t:o})]}):i.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[i.jsx(Sl,{afterId:void 0}),t.cells.map((I,p)=>i.jsxs(me.Fragment,{children:[i.jsxs("div",{ref:O=>e(I.id,O),"data-cell-id":I.id,draggable:!0,onDragStart:O=>T(O,p),onDragEnd:S,onDragOver:O=>A(O,p),onDrop:O=>f(O,p),onClick:O=>{const N=O.target;!N.closest(".cm-editor")&&!N.closest("textarea")&&!N.closest("input")&&a(I.id)},style:{outline:s===I.id?`2px solid ${o.accent}40`:"none",outlineOffset:2,borderRadius:10,transition:"outline 0.1s, transform 0.15s",position:"relative",...d===p&&E!==null&&E!==p?{borderTop:`2px solid ${o.accent}`}:{}},children:[i.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:i.jsxs("svg",{width:"8",height:"14",viewBox:"0 0 8 14",fill:"currentColor",children:[i.jsx("circle",{cx:"2",cy:"2",r:"1.2"}),i.jsx("circle",{cx:"6",cy:"2",r:"1.2"}),i.jsx("circle",{cx:"2",cy:"7",r:"1.2"}),i.jsx("circle",{cx:"6",cy:"7",r:"1.2"}),i.jsx("circle",{cx:"2",cy:"12",r:"1.2"}),i.jsx("circle",{cx:"6",cy:"12",r:"1.2"})]})}),i.jsx(v2,{cell:I,index:p})]}),i.jsx(Sl,{afterId:I.id})]},I.id)),i.jsx("style",{children:`
526
+ [data-cell-id]:hover .drag-handle { opacity: 0.5 !important; }
527
+ [data-cell-id]:hover .drag-handle:hover { opacity: 1 !important; }
528
+ `})]})}function Y2({t:e}){return i.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"48px 0",gap:12,color:e.textMuted},children:[i.jsx("svg",{width:"40",height:"40",viewBox:"0 0 16 16",fill:"currentColor",style:{opacity:.3},children:i.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"})}),i.jsx("span",{style:{fontSize:13,fontFamily:e.font},children:"Empty notebook. Click + to add your first cell."})]})}function j2(){const{state:e}=de(),t=re[e.themeMode],n=e.cells.filter(r=>r.type==="markdown"||r.result&&r.status!=="running"||r.error);return i.jsx("div",{style:{flex:1,overflow:"auto",background:t.appBg,padding:"32px 24px 48px"},children:i.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",display:"flex",flexDirection:"column",gap:24},children:[i.jsxs("div",{style:{textAlign:"center",marginBottom:8},children:[i.jsx("h1",{style:{fontSize:28,fontWeight:700,color:t.textPrimary,fontFamily:t.font,letterSpacing:"-0.3px",margin:0},children:e.notebookTitle||"Untitled"}),i.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?i.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=>i.jsx(W2,{cell:r},r.id))]})})}function W2({cell:e}){const{state:t}=de(),n=re[t.themeMode];if(e.type==="markdown")return i.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:$2(e.content,n)}});if(e.error)return i.jsxs("div",{style:{background:n.cellBg,borderRadius:10,border:`1px solid ${n.error}40`,padding:"16px 24px"},children:[e.name&&i.jsx(V2,{name:e.name,t:n}),i.jsx("div",{style:{color:n.error,fontSize:12,fontFamily:n.fontMono,whiteSpace:"pre-wrap"},children:e.error})]});if(!e.result)return null;const r=zr(e.result,e.chartConfig),o=r!=="table";return i.jsxs("div",{style:{background:n.cellBg,borderRadius:10,border:`1px solid ${n.cellBorder}`,overflow:"hidden"},children:[i.jsxs("div",{style:{padding:"10px 20px",borderBottom:`1px solid ${n.cellBorder}`,display:"flex",alignItems:"center",gap:8},children:[e.name?i.jsx("span",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,fontFamily:n.font,flex:1},children:e.name}):i.jsx("span",{style:{flex:1}}),i.jsxs("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.fontMono},children:[e.result.rowCount??e.result.rows.length," rows",e.result.executionTime!=null&&i.jsxs(i.Fragment,{children:[" · ",e.result.executionTime<1e3?`${e.result.executionTime}ms`:`${(e.result.executionTime/1e3).toFixed(1)}s`]})]})]}),i.jsx("div",{style:{padding:o?"16px 20px":0},children:o?yi(r,e.result,t.themeMode,e.chartConfig):i.jsx(Li,{result:e.result,themeMode:t.themeMode})})]})}function V2({name:e,t}){return i.jsx("div",{style:{fontSize:13,fontWeight:600,color:t.textPrimary,fontFamily:t.font,marginBottom:8},children:e})}function $2(e,t){const n=r=>r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return e.split(`
529
+ `).map(r=>{const o=r.trim(),s=o.match(/^(#{1,6})\s+(.+)$/);if(s){const l=s[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(s[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 Up=[{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 X2(e){return e?Up.find(t=>t.value===e)??{value:e,label:e,dot:"#888"}:null}function K2(){const{state:e,dispatch:t}=de(),n=re[e.themeMode],[r,o]=R.useState(null),s=R.useRef(null);if(R.useEffect(()=>{if(!r)return;const S=f=>{s.current&&!s.current.contains(f.target)&&o(null)},A=f=>{f.key==="Escape"&&o(null)};return document.addEventListener("mousedown",S),document.addEventListener("keydown",A),()=>{document.removeEventListener("mousedown",S),document.removeEventListener("keydown",A)}},[r]),!e.activeFile)return null;const a=e.activeFile.name.replace(/\.dqlnb$/,""),l=e.notebookMetadata,E=S=>{t({type:"UPDATE_NOTEBOOK_METADATA",updates:S})},c=X2(l.status),d=(l.categories??[]).length>0,u=!!l.description,T=!!l.projectFilter;return i.jsxs("div",{ref:s,style:{maxWidth:1080,margin:"0 auto",padding:"32px 48px 8px",display:"flex",flexDirection:"column",gap:12},children:[i.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,alignItems:"center",position:"relative"},children:[i.jsx(us,{t:n,active:r==="status",filled:!!c,icon:i.jsx("span",{style:{color:(c==null?void 0:c.dot)??n.textMuted,fontSize:12},children:"●"}),label:(c==null?void 0:c.label)??"Add status",onClick:()=>o(r==="status"?null:"status"),children:r==="status"&&i.jsxs(Ts,{t:n,children:[Up.map(S=>i.jsxs("button",{onClick:()=>{E({status:S.value}),o(null)},style:IT(n,l.status===S.value),children:[i.jsx("span",{style:{color:S.dot,fontSize:12},children:"●"}),i.jsx("span",{children:S.label})]},S.value)),l.status&&i.jsx("button",{onClick:()=>{E({status:void 0}),o(null)},style:{...IT(n,!1),color:n.textMuted},children:i.jsx("span",{children:"Clear"})})]})}),i.jsx(us,{t:n,active:r==="categories",filled:d,icon:i.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10},children:"#"}),label:d?(l.categories??[]).slice(0,3).join(", ")+((l.categories??[]).length>3?"…":""):"Add categories",onClick:()=>o(r==="categories"?null:"categories"),children:r==="categories"&&i.jsx(Ts,{t:n,width:260,children:i.jsx(J2,{t:n,value:l.categories??[],onChange:S=>E({categories:S.length?S:void 0})})})}),i.jsx(us,{t:n,active:r==="description",filled:u,icon:i.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10},children:"✎"}),label:u?AT(l.description,48):"Add description",onClick:()=>o(r==="description"?null:"description"),children:r==="description"&&i.jsx(Ts,{t:n,width:320,children:i.jsx(pT,{multiline:!0,initial:l.description??"",onCommit:S=>E({description:S||void 0}),placeholder:"What does this notebook answer?",style:z2(n)})})}),i.jsx(us,{t:n,active:r==="projectFilter",filled:T,icon:i.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10},children:"⌕"}),label:T?AT(l.projectFilter,32):"Add project filter",onClick:()=>o(r==="projectFilter"?null:"projectFilter"),children:r==="projectFilter"&&i.jsx(Ts,{t:n,width:280,children:i.jsx(pT,{initial:l.projectFilter??"",onCommit:S=>E({projectFilter:S||void 0}),placeholder:"e.g. team:analytics",style:wp(n)})})})]}),i.jsx("div",{style:{fontSize:22,fontWeight:600,color:n.textPrimary,fontFamily:n.font,letterSpacing:"-0.01em"},children:a})]})}function AT(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e}function pT({initial:e,onCommit:t,multiline:n,placeholder:r,style:o}){const[s,a]=R.useState(e),l=R.useRef(s);l.current=s;const E=()=>{const c=l.current.trim();c!==e.trim()&&t(c)};return R.useEffect(()=>()=>E(),[]),n?i.jsx("textarea",{autoFocus:!0,value:s,onChange:c=>a(c.target.value),onBlur:E,placeholder:r,rows:4,style:o}):i.jsx("input",{autoFocus:!0,value:s,onChange:c=>a(c.target.value),onBlur:E,onKeyDown:c=>{c.key==="Enter"&&(c.preventDefault(),c.target.blur())},placeholder:r,style:o})}function us({t:e,active:t,filled:n,icon:r,label:o,onClick:s,children:a}){return i.jsxs("div",{style:{position:"relative"},children:[i.jsxs("button",{className:"dql-meta-pill",onClick:s,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,i.jsx("span",{children:o})]}),a]})}function Ts({t:e,width:t=200,children:n}){return i.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 IT(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 z2(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 wp(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 J2({t:e,value:t,onChange:n}){const[r,o]=R.useState(""),s=()=>{const a=r.trim();if(a){if(t.includes(a)){o("");return}n([...t,a]),o("")}};return i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.length>0&&i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:t.map(a=>i.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,i.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))}),i.jsx("input",{autoFocus:!0,value:r,onChange:a=>o(a.target.value),onKeyDown:a=>{a.key==="Enter"||a.key===","?(a.preventDefault(),s()):a.key==="Backspace"&&!r&&t.length>0&&n(t.slice(0,-1))},placeholder:"Add category, press Enter",style:wp(e)})]})}function q2({onOpenFile:e,registerCellRef:t}){const{state:n}=de(),r=re[n.themeMode];return n.activeFile?n.dashboardMode?i.jsx(j2,{}):i.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",background:r.appBg},children:[i.jsx(Q2,{t:r}),i.jsxs("div",{style:{flex:1,overflow:"auto",padding:"0 0 40px"},children:[i.jsx(K2,{}),i.jsx(k2,{registerCellRef:t})]})]}):i.jsx(n_,{onOpenFile:e})}function Q2({t:e}){const{state:t}=de(),n=t.cells.length;return i.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:[i.jsx(Z2,{t:e}),i.jsx("div",{style:{flex:1}}),i.jsxs("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.font,display:"flex",alignItems:"center",gap:12},children:[i.jsxs("span",{children:[n," ",n===1?"cell":"cells"]}),t.notebookDirty&&i.jsx("span",{style:{color:e.warning},children:"● unsaved"})]})]})}function Z2({t:e}){const{state:t}=de();if(!t.activeFile)return null;const n=t.activeFile.path.split("/").filter(Boolean);return i.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,fontSize:12,fontFamily:e.fontMono,color:e.textMuted,overflow:"hidden"},children:n.map((r,o)=>i.jsxs(me.Fragment,{children:[o>0&&i.jsx("span",{style:{color:e.textMuted,opacity:.5},children:"/"}),i.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 OT={blank:"Blank",revenue:"Revenue Analysis",pipeline:"Pipeline Health"},ek={blank:"Start with an empty notebook.",revenue:"Pre-built queries for revenue metrics and trends.",pipeline:"Templates for data pipeline health monitoring."};function NT(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function tk(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function nk(e){switch(e){case"revenue":return[We("markdown",`# Revenue Analysis
530
+
531
+ This notebook analyzes revenue metrics and trends over time.`),{...We("sql",`SELECT
532
+ DATE_TRUNC('month', order_date) AS month,
533
+ SUM(amount) AS revenue
534
+ FROM orders
535
+ GROUP BY 1
536
+ ORDER BY 1`),name:"monthly_revenue"},{...We("sql",`SELECT
537
+ product_category,
538
+ SUM(amount) AS total_revenue,
539
+ COUNT(*) AS orders
540
+ FROM orders
541
+ GROUP BY 1
542
+ ORDER BY 2 DESC`),name:"revenue_by_category"}];case"pipeline":return[We("markdown",`# Pipeline Health
543
+
544
+ Monitor data pipeline performance, SLA compliance, and error rates.`),{...We("sql",`SELECT
545
+ pipeline_name,
546
+ COUNT(*) AS runs,
547
+ AVG(duration_seconds) AS avg_duration,
548
+ SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failures
549
+ FROM pipeline_runs
550
+ GROUP BY 1
551
+ ORDER BY 4 DESC`),name:"pipeline_summary"},{...We("sql",`SELECT
552
+ *
553
+ FROM pipeline_runs
554
+ WHERE status = 'failed'
555
+ AND run_date >= CURRENT_DATE - INTERVAL '7 days'
556
+ ORDER BY run_date DESC`),name:"recent_failures"}];default:return[We("sql")]}}function rk({onFileOpened:e}){const{state:t,dispatch:n}=de(),r=re[t.themeMode],[o,s]=R.useState(""),[a,l]=R.useState("blank"),[E,c]=R.useState(null),[d,u]=R.useState(!1),T=R.useRef(null);R.useEffect(()=>{var f;(f=T.current)==null||f.focus()},[]),R.useEffect(()=>{const f=I=>{I.key==="Escape"&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[n]);const S=async()=>{const f=tk(o);if(f){c(f);return}u(!0),c(null);const I=NT(o),p=nk(a);try{const O=await Q.createNotebook(I,a),N={name:`${I}.dqlnb`,path:O.path,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:N}),n({type:"OPEN_FILE",file:N,cells:p,title:o.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(N)}catch{const O=`notebooks/${I}.dqlnb`,N={name:`${I}.dqlnb`,path:O,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:N}),n({type:"OPEN_FILE",file:N,cells:p,title:o.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(N)}finally{u(!1)}},A=f=>{f.target===f.currentTarget&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return i.jsx("div",{onClick:A,style:{position:"fixed",inset:0,background:r.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:i.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:[i.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[i.jsx("h2",{style:{fontSize:16,fontWeight:600,color:r.textPrimary,fontFamily:r.font,margin:0},children:"New Notebook"}),i.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:"×"})]}),i.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:20},children:[i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Name"}),i.jsx("input",{ref:T,value:o,onChange:f=>{s(f.target.value),c(null)},onKeyDown:f=>{f.key==="Enter"&&S()},placeholder:"my-analysis",style:{background:r.inputBg,border:`1px solid ${E?r.error:r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:13,fontFamily:r.font,padding:"8px 12px",outline:"none",transition:"border-color 0.15s"}}),E&&i.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:E}),o&&!E&&i.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["File: ",NT(o),".dqlnb"]})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Template"}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:Object.keys(OT).map(f=>i.jsx(ok,{value:f,selected:a===f,onSelect:()=>l(f),label:OT[f],description:ek[f],t:r},f))})]})]}),i.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${r.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[i.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"}),i.jsx("button",{onClick:S,disabled:d||!o.trim(),style:{background:r.accent,border:`1px solid ${r.accent}`,borderRadius:6,color:"#ffffff",cursor:d||!o.trim()?"not-allowed":"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 20px",opacity:d||!o.trim()?.6:1,display:"flex",alignItems:"center",gap:6},children:d?"Creating…":"Create Notebook"})]})]})})}function ok({value:e,selected:t,onSelect:n,label:r,description:o,t:s}){const[a,l]=R.useState(!1);return i.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?s.cellBorderActive:a?s.textMuted:s.inputBorder}`,background:t?`${s.cellBorderActive}10`:a?s.sidebarItemHover:"transparent",cursor:"pointer",transition:"all 0.15s"},children:[i.jsx("div",{style:{width:16,height:16,borderRadius:8,border:`2px solid ${t?s.accent:s.textMuted}`,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:1,transition:"border-color 0.15s"},children:t&&i.jsx("div",{style:{width:8,height:8,borderRadius:4,background:s.accent}})}),i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:13,fontWeight:500,color:s.textPrimary,fontFamily:s.font,marginBottom:2},children:r}),i.jsx("div",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:o})]})]})}function hT(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function sk(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function ik({onFileOpened:e}){const{state:t,dispatch:n}=de(),r=re[t.themeMode],[o,s]=R.useState(""),[a,l]=R.useState(null),[E,c]=R.useState(!1),d=R.useRef(null);R.useEffect(()=>{var S;(S=d.current)==null||S.focus()},[]),R.useEffect(()=>{const S=A=>{A.key==="Escape"&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[n]);const u=async()=>{var f;const S=sk(o);if(S){l(S);return}c(!0),l(null);const A=hT(o);try{const I=await Q.createBlock(o.trim()),p={name:`${A}.dql`,path:I.path,type:"block",folder:"blocks",isNew:!0};n({type:"FILE_ADDED",file:p}),n({type:"CLOSE_NEW_BLOCK_MODAL"}),e(p)}catch(I){(f=I.message)!=null&&f.includes("already exists")?l("A block with this name already exists."):l(I.message??"Failed to create block.")}finally{c(!1)}},T=S=>{S.target===S.currentTarget&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return i.jsx("div",{onClick:T,style:{position:"fixed",inset:0,background:r.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:i.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:[i.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[i.jsx("h2",{style:{fontSize:16,fontWeight:600,color:r.textPrimary,fontFamily:r.font,margin:0},children:"New Block"}),i.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:"×"})]}),i.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},children:[i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Block Name"}),i.jsx("input",{ref:d,value:o,onChange:S=>{s(S.target.value),l(null)},onKeyDown:S=>{S.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&&i.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:a}),o&&!a&&i.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["blocks/",hT(o),".dql"]})]}),i.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 ",i.jsx("code",{style:{fontFamily:r.fontMono,fontSize:11},children:"blocks/"})," folder. They can be referenced from notebooks and other blocks."]})]}),i.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${r.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[i.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"}),i.jsx("button",{onClick:u,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 Block"})]})]})})}function ak({item:e,favorite:t,onInsert:n,onPreview:r,onCopySql:o,onToggleFavorite:s,t:a}){if(!e)return null;const l=e.kind==="metric"||e.kind==="dimension",E=!!e.sql,c=e.source?`${e.source.provider} · ${e.source.objectType}`:null;return i.jsxs("div",{style:{borderTop:`1px solid ${a.headerBorder}`,padding:"12px 10px",display:"flex",flexDirection:"column",gap:10,background:`${a.cellBg}cc`},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsxs("div",{style:{flex:1,minWidth:0},children:[i.jsx("div",{style:{fontSize:12,fontWeight:600,color:a.textPrimary,fontFamily:a.font},children:e.label||e.name}),i.jsxs("div",{style:{fontSize:10,color:a.textMuted,fontFamily:a.fontMono},children:[e.kind," · ",e.name]})]}),i.jsx("button",{onClick:s,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&&i.jsx("div",{style:{fontSize:12,color:a.textSecondary,fontFamily:a.font,lineHeight:1.5},children:e.description}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,fontSize:11,fontFamily:a.fontMono,color:a.textMuted},children:[i.jsxs("div",{children:["domain: ",e.domain||"uncategorized"]}),i.jsxs("div",{children:["owner: ",e.owner??"unassigned"]}),e.table?i.jsxs("div",{children:["table: ",e.table]}):i.jsx("div",{}),e.cube?i.jsxs("div",{children:["cube: ",e.cube]}):i.jsx("div",{}),e.type?i.jsxs("div",{children:["type: ",e.type]}):i.jsx("div",{}),c?i.jsxs("div",{children:["source: ",c]}):i.jsx("div",{})]}),e.tags.length>0&&i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:e.tags.map(d=>i.jsx("span",{style:{fontSize:10,color:a.textMuted,background:a.pillBg,borderRadius:999,padding:"2px 8px",fontFamily:a.font},children:d},d))}),e.sql&&i.jsxs("div",{style:{position:"relative"},children:[i.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}),i.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&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("div",{style:{fontSize:11,fontWeight:600,color:a.textSecondary,fontFamily:a.font},children:"Joins"}),e.joins.map(d=>i.jsxs("div",{style:{fontSize:10,color:a.textMuted,fontFamily:a.fontMono},children:[d.left," ",d.type," ",d.right]},d.name))]}),e.levels&&e.levels.length>0&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("div",{style:{fontSize:11,fontWeight:600,color:a.textSecondary,fontFamily:a.font},children:"Levels"}),e.levels.map(d=>i.jsxs("div",{style:{fontSize:10,color:a.textMuted,fontFamily:a.fontMono},children:[d.order,". ",d.label," → ",d.dimension]},d.name))]}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx("button",{onClick:r,disabled:!E,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"}),i.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"}),i.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 lk({query:e,provider:t,cube:n,owner:r,domain:o,tag:s,type:a,providers:l,cubes:E,owners:c,domains:d,tags:u,onQueryChange:T,onProviderChange:S,onCubeChange:A,onOwnerChange:f,onDomainChange:I,onTagChange:p,onTypeChange:O,t:N}){const h={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"};return i.jsxs("div",{style:{padding:"10px",display:"flex",flexDirection:"column",gap:8,borderBottom:`1px solid ${N.headerBorder}`},children:[i.jsx("input",{value:e,onChange:C=>T(C.target.value),placeholder:"Search labels, cubes, owners, tags...",style:h}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:6},children:[i.jsxs("select",{value:t,onChange:C=>S(C.target.value),style:h,children:[i.jsx("option",{value:"",children:"All providers"}),l.map(C=>i.jsx("option",{value:C,children:C},C))]}),i.jsxs("select",{value:o,onChange:C=>I(C.target.value),style:h,children:[i.jsx("option",{value:"",children:"All domains"}),d.map(C=>i.jsx("option",{value:C,children:C},C))]}),i.jsxs("select",{value:n,onChange:C=>A(C.target.value),style:h,children:[i.jsx("option",{value:"",children:"All cubes"}),E.map(C=>i.jsx("option",{value:C,children:C},C))]}),i.jsxs("select",{value:r,onChange:C=>f(C.target.value),style:h,children:[i.jsx("option",{value:"",children:"All owners"}),c.map(C=>i.jsx("option",{value:C,children:C},C))]}),i.jsxs("select",{value:s,onChange:C=>p(C.target.value),style:h,children:[i.jsx("option",{value:"",children:"All tags"}),u.map(C=>i.jsx("option",{value:C,children:C},C))]}),i.jsxs("select",{value:a,onChange:C=>O(C.target.value),style:h,children:[i.jsx("option",{value:"",children:"All types"}),i.jsx("option",{value:"cube",children:"Cubes"}),i.jsx("option",{value:"metric",children:"Metrics"}),i.jsx("option",{value:"dimension",children:"Dimensions"}),i.jsx("option",{value:"hierarchy",children:"Hierarchies"}),i.jsx("option",{value:"segment",children:"Segments"}),i.jsx("option",{value:"pre_aggregation",children:"Pre-aggregations"})]})]})]})}function ql({label:e,depth:t=0,badge:n,badgeColor:r,count:o,expanded:s,favorite:a,selected:l,onClick:E,onDoubleClick:c,onToggle:d,onFavoriteToggle:u,onDragStart:T,title:S,muted:A,t:f}){const[I,p]=R.useState(!1);return i.jsxs("button",{draggable:!!T,onDragStart:T,onClick:E,onDoubleClick:c,onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),title:S,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:`5px 8px 5px ${10+t*14}px`,background:l?`${f.accent}18`:I?f.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:A?f.textMuted:f.textPrimary,fontSize:12,fontFamily:f.font,textAlign:"left"},children:[d?i.jsx("span",{onClick:O=>{O.stopPropagation(),d()},style:{display:"inline-flex",transform:s?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s",color:f.textMuted},children:i.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:i.jsx("path",{d:"M3 2l4 3-4 3V2Z"})})}):i.jsx("span",{style:{width:10,flexShrink:0}}),i.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),n&&i.jsx("span",{style:{fontSize:9,fontFamily:f.fontMono,color:r??f.accent,background:`${r??f.accent}18`,borderRadius:4,padding:"1px 4px",flexShrink:0},children:n}),typeof o=="number"&&i.jsx("span",{style:{fontSize:10,color:f.textMuted,background:f.pillBg,borderRadius:999,padding:"1px 6px",flexShrink:0},children:o}),typeof a=="boolean"&&i.jsx("span",{onClick:O=>{O.stopPropagation(),u==null||u()},style:{color:a?"#e3b341":f.textMuted,display:"inline-flex",flexShrink:0},children:i.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:i.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 Ss=31,mT=10;function ck(){var Uo,wo,Bo,Fo,Go,mr,Ho,ko,Yo;const{state:e,dispatch:t}=de(),n=re[e.themeMode],[r,o]=R.useState("semantic"),[s,a]=R.useState("validate"),[l,E]=R.useState(""),[c,d]=R.useState(""),[u,T]=R.useState(""),[S,A]=R.useState(""),[f,I]=R.useState(""),[p,O]=R.useState(""),[N,h]=R.useState(""),[C,m]=R.useState({}),[g,y]=R.useState(null),[_,U]=R.useState(null),[D,b]=R.useState([]),[F,L]=R.useState({}),[P,M]=R.useState(""),[w,v]=R.useState(new Set),[x,B]=R.useState(!1),[H,Y]=R.useState(!1),[K,X]=R.useState(null),[q,ee]=R.useState(null),[Z,$]=R.useState([]),[z,ce]=R.useState(!1),[se,V]=R.useState(null),[J,Ee]=R.useState(!1),[Ae,ue]=R.useState(!1),[Re,He]=R.useState(null),[Pe,dt]=R.useState(null),[an,Bt]=R.useState(null),[Dn,No]=R.useState(!1),[Ft,mt]=R.useState(0),[Gt,ho]=R.useState(400),[mo,Or]=R.useState(360),[Co,Wi]=R.useState(280),[Ht,go]=R.useState(!1),[kt,Lo]=R.useState(!1),Mn=R.useRef(null);R.useEffect(()=>{t({type:"SET_BLOCK_STUDIO_CATALOG_LOADING",loading:!0}),ee(null),Q.getBlockStudioCatalog().then(k=>{t({type:"SET_BLOCK_STUDIO_CATALOG",catalog:k}),b(k.databaseTree)}).catch(()=>{ee("Failed to load schema. Check your connection and try refreshing.")}).finally(()=>t({type:"SET_BLOCK_STUDIO_CATALOG_LOADING",loading:!1}))},[t]),R.useEffect(()=>{if(!g||g.startsWith("provider:")||g.startsWith("domain:")||g.startsWith("group:")){U(null);return}Q.getSemanticObject(g).then(U).catch(()=>U(null))},[g]),R.useEffect(()=>{const k=window.setTimeout(()=>{e.blockStudioDraft.trim()&&Q.validateBlockStudio(e.blockStudioDraft,e.activeBlockPath).then(le=>t({type:"SET_BLOCK_STUDIO_VALIDATION",validation:le})).catch(()=>{})},250);return()=>window.clearTimeout(k)},[e.blockStudioDraft,e.activeBlockPath,t]);const Nr=((Uo=e.blockStudioCatalog)==null?void 0:Uo.semanticTree)??null,Ze=R.useMemo(()=>Ck(Nr)?Nr:gk(e.semanticLayer),[Nr,e.semanticLayer]),Vi=R.useMemo(()=>Rl(Ze,"provider"),[Ze]),$i=R.useMemo(()=>Rl(Ze,"cube"),[Ze]),Xi=R.useMemo(()=>Rl(Ze,"owner"),[Ze]),Pn=R.useMemo(()=>Ze?Bp(Ze,{query:l,provider:c,domain:u,cube:S,owner:f,tag:p,type:N}):null,[Ze,l,c,u,S,f,p,N]),ln=R.useMemo(()=>Fp((Pn==null?void 0:Pn.children)??[],C),[Pn,C]),Ki=R.useMemo(()=>hk(D,P),[D,P]),zi=R.useMemo(()=>mk(D),[D]),hr={metrics:e.semanticLayer.metrics.length,dimensions:e.semanticLayer.dimensions.length,hierarchies:e.semanticLayer.hierarchies.length},Ji=ln.length*Ss,_o=R.useMemo(()=>{const k=Math.max(0,Math.floor(Ft/Ss)-mT),le=Math.min(ln.length,Math.ceil((Ft+Gt)/Ss)+mT);return{offsetTop:k*Ss,rows:ln.slice(k,le)}},[ln,Ft,Gt]);R.useEffect(()=>{const k=Mn.current;if(!k)return;const le=()=>ho(k.clientHeight||400);if(le(),typeof ResizeObserver>"u")return window.addEventListener("resize",le),()=>window.removeEventListener("resize",le);const he=new ResizeObserver(()=>le());return he.observe(k),()=>he.disconnect()},[]),R.useEffect(()=>{mt(0),Mn.current&&(Mn.current.scrollTop=0)},[l,c,u,S,f,p,N]);const bn=R.useMemo(()=>{var le;const k=zE(e.blockStudioDraft);return e.blockStudioMetadata?{...k,name:(k==null?void 0:k.name)||e.blockStudioMetadata.name,domain:(k==null?void 0:k.domain)||e.blockStudioMetadata.domain,description:(k==null?void 0:k.description)||e.blockStudioMetadata.description,owner:(k==null?void 0:k.owner)||e.blockStudioMetadata.owner,tags:(le=k==null?void 0:k.tags)!=null&&le.length?k.tags:e.blockStudioMetadata.tags,blockType:(k==null?void 0:k.blockType)||"custom"}:k},[e.blockStudioDraft,e.blockStudioMetadata]),ut=(bn==null?void 0:bn.name)??((wo=e.blockStudioMetadata)==null?void 0:wo.name)??null;R.useEffect(()=>{if(!ut)return;const k=`block:${ut}`;t({type:"SET_LINEAGE_FOCUS",nodeId:k}),ue(!0),Promise.all([Q.fetchLineageNode(k),Q.queryLineage({focus:k}),Q.fetchLineagePaths(k)]).then(([le,he,ge])=>{He(le),dt(he.graph??null),Bt(ge)}).catch(()=>{He(null),dt(null),Bt(null)}).finally(()=>ue(!1))},[ut,t]);const ke=k=>{t({type:"SET_BLOCK_STUDIO_DRAFT",draft:k})},xo=async()=>{var k,le,he;B(!0);try{const ge=await Q.runBlockStudio(e.blockStudioDraft,e.activeBlockPath);t({type:"SET_BLOCK_STUDIO_PREVIEW",preview:ge}),a("results")}catch(ge){t({type:"SET_BLOCK_STUDIO_VALIDATION",validation:{valid:!1,chartConfig:(k=e.blockStudioValidation)==null?void 0:k.chartConfig,executableSql:((le=e.blockStudioValidation)==null?void 0:le.executableSql)??null,semanticRefs:((he=e.blockStudioValidation)==null?void 0:he.semanticRefs)??{metrics:[],dimensions:[],segments:[]},diagnostics:[{severity:"error",code:"block_run_failed",message:ge instanceof Error?ge.message:String(ge)}]}}),a("validate")}finally{B(!1)}},yo=async()=>{if(!e.blockStudioMetadata){t({type:"OPEN_NEW_BLOCK_MODAL"});return}Y(!0),X(null);try{const k=await Q.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:`${k.metadata.name}.dql`,path:k.path,type:"block",folder:"blocks"},payload:k}),e.files.some(he=>he.path===k.path)||t({type:"FILE_ADDED",file:{name:`${k.metadata.name}.dql`,path:k.path,type:"block",folder:"blocks"}}),a("save")}catch(k){const le=(k==null?void 0:k.message)??"Save failed";X(le.includes("409")||le.includes("BLOCK_EXISTS")?"A block with this name already exists. Rename and try again.":le),setTimeout(()=>X(null),5e3)}finally{Y(!1)}},Do=k=>{var le;if(k.kind==="metric"||k.kind==="dimension"){const he=vL(k.kind==="metric"?"metric":"dimension",k.name);(((le=zE(e.blockStudioDraft))==null?void 0:le.blockType)??"custom")==="semantic"?ke(UL(e.blockStudioDraft,{kind:k.kind==="metric"?"metric":"dimension",name:k.name})):b_(he)||ke(wL(e.blockStudioDraft,he)),t({type:"ADD_SEMANTIC_RECENT",name:k.name});return}if(k.kind==="segment"&&k.sql){ke(Rs(e.blockStudioDraft,`/* segment:${k.name} */ (${k.sql})`));return}k.kind==="pre_aggregation"&&ke(Rs(e.blockStudioDraft,`/* pre_aggregation:${k.name} */`))},qi=k=>{ke(Rs(e.blockStudioDraft,k))},Qi=async k=>{if(!(!k.path||k.kind!=="table"||k.children&&k.children.length>0)){v(le=>new Set(le).add(k.id));try{const le=await Q.describeTable(k.path);b(he=>Gp(he,k.id,{...k,children:le.map(ge=>({id:`db-column:${k.path}:${ge.name}`,label:ge.name,kind:"column",path:k.path,type:ge.type}))}))}finally{v(le=>{const he=new Set(le);return he.delete(k.id),he})}}},Mo=R.useCallback(async()=>{try{const k=await Q.getBlockStudioCatalog();k!=null&&k.databaseTree&&b(k.databaseTree),t({type:"SET_BLOCK_STUDIO_CATALOG",catalog:k})}catch{}},[t]),Zi=((Bo=e.blockStudioValidation)==null?void 0:Bo.chartConfig)??((Fo=e.blockStudioPreview)==null?void 0:Fo.chartConfig)??{chart:"table"},ea=e.blockStudioPreview?zr(e.blockStudioPreview.result,e.blockStudioPreview.chartConfig):"table",Po=R.useMemo(()=>((Re==null?void 0:Re.incoming)??[]).filter(k=>k.node),[Re]),bo=R.useMemo(()=>((Re==null?void 0:Re.outgoing)??[]).filter(k=>k.node),[Re]),vo=k=>{k.preventDefault();const le=k.clientX,he=mo,ge=Cr=>{const gr=Math.min(520,Math.max(280,he+Cr.clientX-le));Or(gr)},Yt=()=>{window.removeEventListener("mousemove",ge),window.removeEventListener("mouseup",Yt)};window.addEventListener("mousemove",ge),window.addEventListener("mouseup",Yt)},ta=k=>{k.preventDefault();const le=k.clientY,he=Co,ge=Cr=>{const gr=Math.min(520,Math.max(180,he-(Cr.clientY-le)));Wi(gr)},Yt=()=>{window.removeEventListener("mousemove",ge),window.removeEventListener("mouseup",Yt)};window.addEventListener("mousemove",ge),window.addEventListener("mouseup",Yt)};return i.jsxs("div",{style:{flex:1,position:"relative",display:"grid",gridTemplateColumns:Ht?"0 0 minmax(0, 1fr)":`${mo}px 6px minmax(0, 1fr)`,gridTemplateRows:kt?"minmax(0, 1fr) 0 0":`minmax(0, 1fr) 6px ${Co}px`,overflow:"hidden",background:n.appBg},children:[i.jsxs("div",{style:{borderRight:Ht?"none":`1px solid ${n.headerBorder}`,display:Ht?"none":"flex",flexDirection:"column",overflow:"hidden",background:n.sidebarBg,minWidth:0},children:[i.jsxs("div",{style:{padding:14,display:"grid",gap:12,borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:700,color:n.textPrimary,fontFamily:n.font},children:"Block Studio"}),i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:"Build DQL with semantic models and live database structure in one workspace."})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.semanticLayer.provider&&i.jsx("span",{style:{fontSize:10,fontWeight:700,color:n.accent,background:`${n.accent}18`,borderRadius:999,padding:"5px 9px",textTransform:"uppercase",letterSpacing:"0.04em"},children:e.semanticLayer.provider}),i.jsx("button",{onClick:()=>go(!0),style:{background:n.btnBg,border:`1px solid ${n.btnBorder}`,borderRadius:6,color:n.textSecondary,cursor:"pointer",fontSize:12,fontFamily:n.font,padding:"4px 8px"},title:"Collapse explorer",children:"‹"})]})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8},children:[i.jsx(Zn,{label:"Metrics",value:hr.metrics,t:n}),i.jsx(Zn,{label:"Dimensions",value:hr.dimensions,t:n}),i.jsx(Zn,{label:"Hierarchies",value:hr.hierarchies,t:n})]})]}),i.jsxs("div",{style:{display:"flex",padding:"10px 12px",gap:8,borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsx(Tt,{active:r==="semantic",onClick:()=>o("semantic"),label:"Semantic Layer"}),i.jsx(Tt,{active:r==="database",onClick:()=>o("database"),label:"Database"})]}),r==="semantic"?i.jsxs(i.Fragment,{children:[i.jsx("div",{style:{padding:12,borderBottom:`1px solid ${n.headerBorder}`,background:`${n.cellBg}66`},children:i.jsx(lk,{query:l,provider:c,cube:S,owner:f,domain:u,tag:p,type:N,providers:Vi,cubes:$i,owners:Xi,domains:e.semanticLayer.domains,tags:e.semanticLayer.tags,onQueryChange:E,onProviderChange:d,onCubeChange:A,onOwnerChange:I,onDomainChange:T,onTagChange:O,onTypeChange:h,t:n})}),i.jsx("div",{ref:Mn,onScroll:k=>mt(k.currentTarget.scrollTop),style:{flex:1,overflowY:"auto",borderBottom:`1px solid ${n.headerBorder}`,background:n.cellBg},children:q?i.jsxs("div",{style:{padding:16,display:"grid",gap:8,textAlign:"center"},children:[i.jsx("div",{style:{fontSize:12,color:"#f85149",fontFamily:n.font},children:q}),i.jsx("button",{onClick:()=>{ee(null),Mo()},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?i.jsx(Mt,{message:"Loading semantic catalog…"}):ln.length===0?i.jsx(Mt,{message:"No semantic objects match the current filters."}):i.jsx("div",{style:{height:Ji,position:"relative"},children:i.jsx("div",{style:{position:"absolute",top:_o.offsetTop,left:0,right:0},children:_o.rows.map(k=>i.jsx(Ik,{row:k,selectedId:g,setSelectedId:y,expanded:C,setExpanded:m,onInsert:Do,favorites:new Set(e.semanticLayer.favorites),dispatch:t,t:n},k.node.id))})})}),i.jsx(ak,{item:_,favorite:!!(_&&e.semanticLayer.favorites.includes(_.name)),onInsert:()=>_&&Do(_),onPreview:()=>{_!=null&&_.sql&&ke(Rs(e.blockStudioDraft,_.sql))},onCopySql:()=>{_!=null&&_.sql&&navigator.clipboard.writeText(_.sql)},onToggleFavorite:()=>{!_||_.kind!=="metric"&&_.kind!=="dimension"||Q.toggleFavorite(_.name).then(k=>t({type:"SET_SEMANTIC_FAVORITES",favorites:k}))},t:n})]}):i.jsx(pk,{tree:Ki,totalTree:D,expanded:F,setExpanded:L,onEnsureColumns:Qi,onInsert:qi,query:P,onQueryChange:M,stats:zi,connectionName:((Go=e.blockStudioCatalog)==null?void 0:Go.connection.current)??"default",loadingNodes:w,onRefresh:Mo,t:n})]}),i.jsx("div",{onMouseDown:Ht?void 0:vo,style:{display:Ht?"none":"block",cursor:"col-resize",background:n.headerBorder}}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden",gridColumn:"3",gridRow:"1"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"12px 14px",borderBottom:`1px solid ${n.headerBorder}`,background:n.cellBg},children:[Ht&&i.jsx("button",{onClick:()=>go(!1),style:{background:n.btnBg,border:`1px solid ${n.btnBorder}`,borderRadius:6,color:n.textSecondary,cursor:"pointer",fontSize:12,fontFamily:n.font,padding:"6px 10px"},title:"Open explorer",children:"Explorer"}),i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:700,color:n.textPrimary,fontFamily:n.font},children:"DQL Source"}),i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:"Use templates, insert semantic refs, run, validate, and save from one editor."})]}),i.jsx("div",{style:{flex:1}}),i.jsx(Mr,{label:"Semantic Skeleton",onClick:()=>{var k;return ke(Ok(((k=e.blockStudioMetadata)==null?void 0:k.name)??"New Block"))}}),i.jsx(Mr,{label:"Custom Skeleton",onClick:()=>{var k;return ke(Nk(((k=e.blockStudioMetadata)==null?void 0:k.name)??"New Block"))}}),i.jsx(Mr,{label:"Lineage",onClick:()=>a("lineage")}),i.jsx(Mr,{label:"Run",onClick:()=>void xo(),busy:x}),i.jsx(Mr,{label:"Save",onClick:()=>void yo(),busy:H}),K&&i.jsx("span",{style:{fontSize:11,color:"#f85149",fontFamily:n.font,padding:"4px 8px",background:"#f8514918",borderRadius:6},children:K})]}),i.jsxs("div",{style:{padding:"10px 14px",display:"flex",gap:10,alignItems:"center",borderBottom:`1px solid ${n.headerBorder}`,background:`${n.pillBg}66`,flexWrap:"wrap"},children:[i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Active lineage"}),i.jsx(CT,{label:"Upstream",count:Po.length,t:n}),i.jsx(CT,{label:"Downstream",count:bo.length,t:n}),((mr=Re==null?void 0:Re.node)==null?void 0:mr.domain)&&i.jsxs("span",{style:{fontSize:11,color:n.textSecondary,fontFamily:n.font},children:["Domain: ",Re.node.domain]}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{onClick:()=>{ut&&(t({type:"SET_LINEAGE_FOCUS",nodeId:`block:${ut}`}),e.lineageFullscreen||t({type:"TOGGLE_LINEAGE_FULLSCREEN"}))},style:{background:n.btnBg,border:`1px solid ${n.btnBorder}`,borderRadius:6,color:n.textPrimary,cursor:"pointer",fontSize:11,fontFamily:n.font,padding:"6px 10px"},children:"Open Full Lineage"})]}),i.jsx("div",{style:{flex:1,overflow:"hidden"},children:i.jsx(vc,{value:e.blockStudioDraft,onChange:ke,onRun:()=>void xo(),themeMode:e.themeMode,autoFocus:!0,errorMessage:(ko=(Ho=e.blockStudioValidation)==null?void 0:Ho.diagnostics.find(k=>k.severity==="error"))==null?void 0:ko.message})})]}),i.jsx("div",{onMouseDown:kt?void 0:ta,style:{gridColumn:"1 / -1",gridRow:"2",display:kt?"none":"block",cursor:"row-resize",background:n.headerBorder}}),i.jsxs("div",{style:{gridColumn:"1 / -1",gridRow:"3",borderTop:kt?"none":`1px solid ${n.headerBorder}`,display:kt?"none":"flex",flexDirection:"column",overflow:"hidden",background:n.cellBg},children:[i.jsxs("div",{style:{padding:"12px 14px",display:"grid",gap:10,borderBottom:`1px solid ${n.headerBorder}`},children:[i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:700,color:n.textPrimary,fontFamily:n.font},children:"Preview & Governance"}),i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:"Validate references, inspect results, tune visualization, and save companion metadata."})]}),i.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[i.jsx(Tt,{active:s==="results",onClick:()=>a("results"),label:"Results"}),i.jsx(Tt,{active:s==="visualization",onClick:()=>a("visualization"),label:"Visualization"}),i.jsx(Tt,{active:s==="lineage",onClick:()=>a("lineage"),label:"Lineage"}),i.jsx(Tt,{active:s==="validate",onClick:()=>a("validate"),label:"Validate"}),i.jsx(Tt,{active:s==="tests",onClick:()=>a("tests"),label:"Tests"}),i.jsx(Tt,{active:s==="history",onClick:()=>{a("history"),!z&&e.activeBlockPath&&Q.getBlockHistory(e.activeBlockPath).then(k=>{$(k.entries),ce(!0)})},label:"History"}),i.jsx(Tt,{active:s==="save",onClick:()=>a("save"),label:"Save"}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{onClick:()=>Lo(!0),style:{background:n.btnBg,border:`1px solid ${n.btnBorder}`,borderRadius:6,color:n.textSecondary,cursor:"pointer",fontSize:12,fontFamily:n.font,padding:"6px 10px"},children:"Hide Pane"})]})]}),i.jsxs("div",{style:{flex:1,overflow:"auto"},children:[s==="results"&&(e.blockStudioPreview?i.jsxs("div",{style:{display:"grid",gap:12,padding:12},children:[i.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.fontMono},children:e.blockStudioPreview.sql}),ea==="table"?i.jsx(Li,{result:e.blockStudioPreview.result,themeMode:e.themeMode}):i.jsx(Ix,{result:e.blockStudioPreview.result,chartConfig:e.blockStudioPreview.chartConfig,themeMode:e.themeMode})]}):i.jsx(Mt,{message:"Run the block to preview results and visualization."})),s==="visualization"&&i.jsx(dk,{chartConfig:Zi,onChange:k=>ke(bL(e.blockStudioDraft,k)),t:n}),s==="lineage"&&i.jsx(uk,{blockName:ut,loading:Ae,detail:Re,graph:Pe,paths:an,onSelectNode:k=>{t({type:"SET_LINEAGE_FOCUS",nodeId:k}),e.lineageFullscreen||t({type:"TOGGLE_LINEAGE_FULLSCREEN"})},onOpenFull:()=>{ut&&(t({type:"SET_LINEAGE_FOCUS",nodeId:`block:${ut}`}),e.lineageFullscreen||t({type:"TOGGLE_LINEAGE_FULLSCREEN"}))},t:n}),s==="tests"&&i.jsx(fk,{source:e.blockStudioDraft,blockPath:e.activeBlockPath,testResults:se,running:J,onRunTests:async()=>{if(e.activeBlockPath){Ee(!0);try{const k=await Q.runBlockTests(e.blockStudioDraft,e.activeBlockPath);V(k.assertions??[])}catch{V([])}finally{Ee(!1)}}},t:n}),s==="validate"&&i.jsx(Ek,{diagnostics:((Yo=e.blockStudioValidation)==null?void 0:Yo.diagnostics)??[],t:n}),s==="history"&&i.jsx(Ak,{entries:Z,t:n}),s==="save"&&i.jsxs("div",{style:{display:"grid",gap:12},children:[e.activeBlockPath&&e.blockStudioMetadata&&i.jsx("div",{style:{padding:"12px 12px 0"},children:i.jsx(Rk,{currentStatus:e.blockStudioMetadata.reviewStatus??"draft",blockPath:e.activeBlockPath,onStatusChanged:k=>{e.blockStudioMetadata&&t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,reviewStatus:k}})},t:n})}),i.jsx(Tk,{metadata:e.blockStudioMetadata,draftMetadata:bn,onChange:k=>{if(!e.blockStudioMetadata)return;t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,...k}});let le=e.blockStudioDraft;typeof k.name=="string"&&(le=BR(le,k.name)),typeof k.domain=="string"&&(le=Oa(le,"domain",k.domain)),typeof k.owner=="string"&&(le=Oa(le,"owner",k.owner)),typeof k.description=="string"&&(le=Oa(le,"description",k.description)),k.tags&&(le=PL(le,k.tags)),ke(le)},onSave:()=>void yo(),saving:H,t:n})]})]})]}),kt&&i.jsx("div",{style:{position:"absolute",right:16,bottom:16},children:i.jsx("button",{onClick:()=>Lo(!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 Tt({active:e,onClick:t,label:n,busy:r}){const{state:o}=de(),s=re[o.themeMode];return i.jsx("button",{onClick:t,style:{background:e?`${s.accent}18`:s.btnBg,border:`1px solid ${e?s.accent:s.btnBorder}`,borderRadius:6,color:e?s.accent:s.textSecondary,cursor:"pointer",fontSize:11,fontFamily:s.font,padding:"6px 10px",opacity:r?.7:1},children:r?`${n}…`:n})}function Mr(e){return i.jsx(Tt,{active:!1,...e})}function Zn({label:e,value:t,t:n}){return i.jsxs("div",{style:{background:n.cellBg,border:`1px solid ${n.headerBorder}`,borderRadius:10,padding:"10px 12px"},children:[i.jsx("div",{style:{fontSize:10,fontWeight:700,color:n.textMuted,fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em"},children:e}),i.jsx("div",{style:{fontSize:20,fontWeight:700,color:n.textPrimary,fontFamily:n.font,marginTop:4},children:t})]})}function Ek({diagnostics:e,t}){return e.length===0?i.jsx(Mt,{message:"No validation messages."}):i.jsx("div",{style:{display:"grid",gap:8,padding:12},children:e.map((n,r)=>i.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:[i.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}),i.jsx("div",{style:{fontSize:12,color:t.textPrimary,marginTop:4},children:n.message})]},`${n.code??n.message}-${r}`))})}function dk({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 i.jsxs("div",{style:{display:"grid",gap:10,padding:12},children:[i.jsxs("select",{value:e.chart??"table",onChange:o=>t({...e,chart:o.target.value}),style:r,children:[i.jsx("option",{value:"table",children:"Table"}),_i.map(o=>i.jsx("option",{value:o.value,children:o.label},o.value))]}),i.jsx("input",{value:e.x??"",onChange:o=>t({...e,x:o.target.value}),placeholder:"x binding",style:r}),i.jsx("input",{value:e.y??"",onChange:o=>t({...e,y:o.target.value}),placeholder:"y binding",style:r}),i.jsx("input",{value:e.color??"",onChange:o=>t({...e,color:o.target.value}),placeholder:"color binding",style:r}),i.jsx("input",{value:e.title??"",onChange:o=>t({...e,title:o.target.value}),placeholder:"title",style:r})]})}function CT({label:e,count:t,t:n}){return i.jsxs("span",{style:{fontSize:11,fontWeight:600,color:n.textPrimary,background:n.pillBg,border:`1px solid ${n.cellBorder}`,borderRadius:999,padding:"4px 10px",fontFamily:n.font},children:[e,": ",t]})}function uk({blockName:e,loading:t,detail:n,graph:r,paths:o,onSelectNode:s,onOpenFull:a,t:l}){const[E,c]=R.useState(!1);if(!e)return i.jsx(Mt,{message:"Lineage will appear once the block has a name."});if(t)return i.jsx(Mt,{message:"Loading block lineage…"});if(!(n!=null&&n.node))return i.jsxs("div",{style:{padding:12,display:"grid",gap:12},children:[i.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."}),i.jsx("div",{children:i.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 d=`block:${e}`;return i.jsxs("div",{style:{padding:12,display:"grid",gap:12,overflowY:"auto"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:700,color:l.textPrimary,fontFamily:l.font},children:n.node.name}),i.jsx("div",{style:{fontSize:11,color:l.textMuted,fontFamily:l.font},children:n.node.domain?`Domain: ${n.node.domain}`:"Block lineage focus"})]}),i.jsx("div",{style:{flex:1}}),i.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)&&i.jsx(Qx,{layerSummary:o.layerSummary,t:l}),r&&r.nodes.length>0&&i.jsx(Np,{nodes:r.nodes,edges:r.edges,focalNodeId:d,height:220,onNodeClick:s,layoutMode:"flow"}),o&&(o.upstreamPaths.length>0||o.downstreamPaths.length>0)&&i.jsxs("div",{style:{display:"grid",gap:10},children:[i.jsx("div",{style:{fontSize:12,color:l.textMuted,fontFamily:l.font,lineHeight:1.5},children:"Source tables and dbt models flow into this block. Downstream paths show notebooks and charts that consume it."}),o.upstreamPaths.length>0&&i.jsx(pd,{title:"Source to Block",paths:o.upstreamPaths,onNodeClick:s,focalNodeId:d,t:l}),o.downstreamPaths.length>0&&i.jsx(pd,{title:"Block to Consumption",paths:o.downstreamPaths,onNodeClick:s,focalNodeId:d,t:l})]}),i.jsxs("button",{onClick:()=>c(u=>!u),style:{background:"none",border:`1px solid ${l.cellBorder}`,borderRadius:6,padding:"6px 10px",color:l.textMuted,cursor:"pointer",fontSize:11,fontFamily:l.font,textAlign:"left"},children:[E?"▾":"▸"," Upstream / Downstream Details"]}),E&&i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, minmax(0, 1fr))",gap:12},children:[i.jsx(gT,{title:"Upstream",entries:n.incoming,emptyMessage:"No upstream dependencies yet.",onSelectNode:s,t:l}),i.jsx(gT,{title:"Downstream",entries:n.outgoing,emptyMessage:"No downstream dependencies yet.",onSelectNode:s,t:l})]})]})}function gT({title:e,entries:t,emptyMessage:n,onSelectNode:r,t:o}){const s=t.filter(a=>a.node);return i.jsxs("div",{style:{border:`1px solid ${o.cellBorder}`,borderRadius:10,overflow:"hidden",background:o.inputBg},children:[i.jsxs("div",{style:{padding:"10px 12px",borderBottom:`1px solid ${o.cellBorder}`,fontSize:11,fontWeight:700,color:o.textMuted,fontFamily:o.font,textTransform:"uppercase",letterSpacing:"0.04em"},children:[e," (",s.length,")"]}),s.length===0?i.jsx("div",{style:{padding:12,fontSize:12,color:o.textMuted,fontFamily:o.font},children:n}):i.jsx("div",{style:{display:"grid"},children:s.map(a=>i.jsxs("button",{onClick:()=>r(a.node.id),style:{background:"transparent",border:"none",borderTop:`1px solid ${o.cellBorder}`,padding:"10px 12px",textAlign:"left",cursor:"pointer"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{fontSize:10,fontWeight:700,color:o.accent,fontFamily:o.font,textTransform:"uppercase"},children:a.node.type.replace("_"," ")}),i.jsx("span",{style:{fontSize:12,color:o.textPrimary,fontFamily:o.font,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.node.name})]}),i.jsxs("div",{style:{marginTop:3,fontSize:11,color:o.textMuted,fontFamily:o.font},children:["via ",a.edge.type,a.node.domain?` · ${a.node.domain}`:""]})]},`${a.node.id}-${a.edge.type}`))})]})}function Tk({metadata:e,draftMetadata:t,onChange:n,onSave:r,saving:o,t:s}){const a={width:"100%",background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:6,color:s.textPrimary,fontSize:12,fontFamily:s.font,padding:"8px 10px",outline:"none"},l={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 i.jsxs("div",{style:{display:"grid",gap:10,padding:12},children:[i.jsx("input",{value:l.name,onChange:E=>n({name:E.target.value}),placeholder:"Block name",style:a}),i.jsx("input",{value:l.domain,onChange:E=>n({domain:E.target.value}),placeholder:"Domain",style:a}),i.jsx("input",{value:l.owner,onChange:E=>n({owner:E.target.value}),placeholder:"Owner",style:a}),i.jsx("input",{value:l.description,onChange:E=>n({description:E.target.value}),placeholder:"Description",style:a}),i.jsx("input",{value:l.tags.join(", "),onChange:E=>n({tags:E.target.value.split(",").map(c=>c.trim()).filter(Boolean)}),placeholder:"Tags",style:a}),i.jsx("button",{onClick:r,style:{background:s.accent,border:`1px solid ${s.accent}`,borderRadius:6,color:"#fff",cursor:"pointer",fontSize:12,fontFamily:s.font,padding:"8px 12px"},children:o?"Saving…":"Save Block"})]})}function Mt({message:e}){const{state:t}=de(),n=re[t.themeMode];return i.jsx("div",{style:{padding:16,fontSize:12,color:n.textMuted},children:e})}const LT={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149"},Sk={draft:["review"],review:["certified","draft"],certified:["deprecated"],deprecated:["draft"]};function Rk({currentStatus:e,blockPath:t,onStatusChanged:n,t:r}){const[o,s]=R.useState(!1),a=Sk[e]??[],l=async E=>{if(t){s(!0);try{const c=await Q.updateBlockStatus(t,E);c.ok&&c.status&&n(c.status)}finally{s(!1)}}};return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 12px",background:r.pillBg,borderRadius:8},children:[i.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:"Status:"}),i.jsx("span",{style:{fontSize:11,fontWeight:600,color:LT[e]??r.textMuted,background:`${LT[e]??r.textMuted}18`,padding:"2px 8px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em",fontFamily:r.font},children:e}),i.jsx("span",{style:{flex:1}}),a.map(E=>i.jsx("button",{onClick:()=>void l(E),disabled:o,style:{background:E==="certified"?"#3fb950":E==="deprecated"?"#f85149":r.btnBg,border:`1px solid ${E==="certified"?"#3fb950":E==="deprecated"?"#f85149":r.btnBorder}`,borderRadius:4,color:E==="certified"||E==="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?"...":E==="certified"?"Certify":E==="deprecated"?"Deprecate":`Move to ${E}`},E))]})}function fk({source:e,blockPath:t,testResults:n,running:r,onRunTests:o,t:s}){const l=[...e.matchAll(/assert\s+(\w+)\s*(>=?|<=?|==|!=|IN)\s*(\S+)/g)].map(E=>({field:E[1],operator:E[2],expected:E[3]}));return i.jsxs("div",{style:{padding:12,display:"grid",gap:10},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{style:{fontSize:12,fontWeight:600,color:s.textPrimary,fontFamily:s.font},children:"Test Assertions"}),i.jsx("span",{style:{flex:1}}),i.jsx("button",{onClick:o,disabled:r||!t,style:{background:s.accent,border:"none",borderRadius:6,color:"#fff",cursor:r||!t?"not-allowed":"pointer",fontSize:11,fontWeight:600,fontFamily:s.font,padding:"5px 14px",opacity:r||!t?.5:1},children:r?"Running...":"Run Tests"})]}),l.length===0&&i.jsxs("div",{style:{fontSize:12,color:s.textMuted,fontFamily:s.font,lineHeight:1.5},children:["No test assertions found. Add assertions in your block:",i.jsx("pre",{style:{margin:"8px 0 0",padding:"8px 10px",background:s.editorBg,border:`1px solid ${s.cellBorder}`,borderRadius:6,fontSize:10,fontFamily:s.fontMono,color:s.textSecondary},children:`tests {
557
+ assert row_count > 0
558
+ assert max_value <= 1000000
559
+ }`})]}),l.map((E,c)=>{const d=n==null?void 0:n[c],u=d==null?void 0:d.passed;return i.jsxs("div",{style:{padding:"8px 12px",borderRadius:8,border:`1px solid ${d?u?"#3fb95040":"#f8514940":s.cellBorder}`,background:d?u?"#3fb95008":"#f8514908":"transparent",display:"flex",alignItems:"center",gap:8},children:[d&&i.jsx("span",{style:{fontSize:14,color:u?"#3fb950":"#f85149",fontWeight:700},children:u?"✓":"✗"}),i.jsxs("div",{style:{flex:1},children:[i.jsxs("div",{style:{fontSize:12,color:s.textPrimary,fontFamily:s.fontMono},children:[E.field," ",E.operator," ",E.expected]}),d&&!u&&d.actual&&i.jsxs("div",{style:{fontSize:11,color:"#f85149",fontFamily:s.font,marginTop:2},children:["Actual: ",d.actual]})]})]},c)}),n&&n.length>0&&i.jsxs("div",{style:{padding:"8px 12px",background:s.pillBg,borderRadius:8,fontSize:12,fontFamily:s.font,color:s.textSecondary},children:[n.filter(E=>E.passed).length,"/",n.length," passed"]})]})}function Ak({entries:e,t}){return e.length===0?i.jsx(Mt,{message:"No version history available. Commit changes to build history."}):i.jsxs("div",{style:{padding:12,display:"grid",gap:8},children:[i.jsx("div",{style:{fontSize:12,fontWeight:600,color:t.textPrimary,fontFamily:t.font},children:"Version History"}),e.map(n=>i.jsxs("div",{style:{padding:"8px 12px",border:`1px solid ${t.cellBorder}`,borderRadius:8,background:t.inputBg},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[i.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)}),i.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font},children:new Date(n.date).toLocaleDateString()}),i.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font,marginLeft:"auto"},children:n.author})]}),i.jsx("div",{style:{fontSize:12,color:t.textPrimary,fontFamily:t.font},children:n.message})]},n.hash))]})}function pk({tree:e,totalTree:t,expanded:n,setExpanded:r,onEnsureColumns:o,onInsert:s,query:a,onQueryChange:l,stats:E,connectionName:c,loadingNodes:d,onRefresh:u,t:T}){const S={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"},A=(f,I=0)=>{var g,y,_;const p=f.kind!=="column",O=n[f.id]??I<1,N=d.has(f.id),h=f.kind==="schema"?(g=f.children)==null?void 0:g.length:f.kind==="table"?(y=f.children)==null?void 0:y.length:void 0,C=f.kind==="column"?f.type:f.kind,m=f.kind==="column"&&f.type?gl(f.type,T.accent):void 0;return i.jsxs("div",{children:[i.jsx(ql,{label:N?`${f.label} …`:f.label,depth:I,count:h,expanded:p?O:void 0,onToggle:p?()=>{r(U=>({...U,[f.id]:!O})),O||o(f)}:void 0,badge:C,badgeColor:m,onClick:()=>{if(f.kind==="table"&&f.path&&s(f.path),f.kind==="column"){const U=f.path?f.path.split(".").pop():"";s(U?`${U}.${f.label}`:f.label)}},onDoubleClick:()=>{f.kind==="table"&&f.path&&s(`SELECT *
560
+ FROM ${f.path}
561
+ LIMIT 100`)},t:T}),p&&O&&((_=f.children)==null?void 0:_.map(U=>A(U,I+1)))]},f.id)};return i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:{padding:12,display:"grid",gap:12,borderBottom:`1px solid ${T.headerBorder}`,background:`${T.cellBg}66`},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[i.jsxs("div",{children:[i.jsx("div",{style:{fontSize:12,fontWeight:700,color:T.textPrimary,fontFamily:T.font},children:"Database Browser"}),i.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."})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.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:"↻"}),i.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:c})]})]}),i.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8},children:[i.jsx(Zn,{label:"Schemas",value:E.schemas,t:T}),i.jsx(Zn,{label:"Tables",value:E.tables,t:T}),i.jsx(Zn,{label:"Columns",value:E.columns,t:T})]}),i.jsx("input",{value:a,onChange:f=>l(f.target.value),placeholder:"Search schemas, tables, columns...",style:S})]}),i.jsx("div",{style:{flex:1,overflowY:"auto",padding:e.length>0?"6px 0 0":0},children:t.length===0?i.jsx(Mt,{message:"No schemas were found for the active connection yet."}):e.length===0?i.jsx(Mt,{message:"No database objects match the current search."}):e.map(f=>A(f))})]})}function Ik({row:e,selectedId:t,setSelectedId:n,expanded:r,setExpanded:o,onInsert:s,favorites:a,dispatch:l,t:E}){var A;const{node:c,depth:d,hasChildren:u,isExpanded:T}=e,S=c.id.split(":").slice(1).join(":");return u?i.jsx(ql,{label:c.label,depth:d,count:(A=c.children)==null?void 0:A.length,expanded:T,onToggle:()=>o(f=>({...f,[c.id]:!T})),onClick:()=>n(c.id),selected:t===c.id,t:E}):i.jsx(ql,{label:c.label,depth:d,badge:c.kind,selected:t===c.id,onClick:()=>n(c.id),onDoubleClick:()=>{Q.getSemanticObject(c.id).then(s).catch(()=>{})},onFavoriteToggle:c.kind==="metric"||c.kind==="dimension"?()=>void Q.toggleFavorite(S).then(f=>l({type:"SET_SEMANTIC_FAVORITES",favorites:f})):void 0,favorite:c.kind==="metric"||c.kind==="dimension"?a.has(S):void 0,t:E})}function Rs(e,t){const n=e.match(/query\s*=\s*"""([\s\S]*?)"""/i);return n?e.replace(n[0],`query = """${n[1].trimEnd()}
562
+ ${t}
563
+ """`):/^\s*block\s+"/i.test(e.trim())?e.replace(/\n\}\s*$/,`
564
+
565
+ query = """
566
+ ${t}
567
+ """
568
+ }
569
+ `):`${e.trimEnd()}
570
+ ${t}
571
+ `}function Ok(e){return`block "${e}" {
572
+ domain = "uncategorized"
573
+ type = "semantic"
574
+ description = ""
575
+ owner = ""
576
+ tags = []
577
+ metric = "total_revenue"
578
+
579
+ visualization {
580
+ chart = "table"
581
+ }
582
+ }
583
+ `}function Nk(e){return`block "${e}" {
584
+ domain = "uncategorized"
585
+ type = "custom"
586
+ description = ""
587
+ owner = ""
588
+ tags = []
589
+
590
+ query = """
591
+ SELECT 1 AS value
592
+ """
593
+
594
+ visualization {
595
+ chart = "table"
596
+ }
597
+ }
598
+ `}function Rl(e,t){if(!e)return[];const n=new Set,r=o=>{var a;const s=(a=o.meta)==null?void 0:a[t];typeof s=="string"&&s.trim()&&n.add(s.trim());for(const l of o.children??[])r(l)};return r(e),Array.from(n).sort((o,s)=>o.localeCompare(s))}function Bp(e,t){var T,S,A,f,I;const n=t.query.trim().toLowerCase(),r=Object.values(e.meta??{}).filter(p=>p!=null).map(p=>String(p).toLowerCase()),o=!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||r.some(p=>p.includes(n)),s=!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||((S=e.meta)==null?void 0:S.provider)===t.provider||e.id===`provider:${t.provider}`,E=!t.cube||((A=e.meta)==null?void 0:A.cube)===t.cube,c=!t.owner||((f=e.meta)==null?void 0:f.owner)===t.owner,d=!t.tag||String(((I=e.meta)==null?void 0:I.tags)??"").split(",").filter(Boolean).includes(t.tag),u=(e.children??[]).map(p=>Bp(p,t)).filter(p=>!!p);return u.length>0?{...e,children:u,count:e.kind==="provider"||e.kind==="domain"||e.kind==="group"?u.length:e.count}:o&&s&&a&&l&&E&&c&&d?{...e,children:[]}:null}function Fp(e,t,n=0){const r=[];for(const o of e){const s=!!(o.children&&o.children.length>0),a=t[o.id]??n<3;r.push({node:o,depth:n,hasChildren:s,isExpanded:a}),s&&a&&r.push(...Fp(o.children??[],t,n+1))}return r}function Gp(e,t,n){return e.map(r=>r.id===t?n:r.children?{...r,children:Gp(r.children,t,n)}:r)}function hk(e,t){const n=t.trim().toLowerCase();if(!n)return e;const r=o=>{const s=[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 s||a.length>0?{...o,children:a}:null};return e.map(o=>r(o)).filter(o=>!!o)}function mk(e){let t=0,n=0,r=0;const o=s=>{s.kind==="schema"&&(t+=1),s.kind==="table"&&(n+=1),s.kind==="column"&&(r+=1);for(const a of s.children??[])o(a)};for(const s of e)o(s);return{schemas:t,tables:n,columns:r}}function Ck(e){return!!(e&&e.children&&e.children.length>0)}function gk(e){if(e.metrics.length===0&&e.dimensions.length===0&&e.hierarchies.length===0)return null;const t=e.provider??"dql",n=new Map,r=(s,a)=>{const l=n.get(s)??[];l.push(a),n.set(s,l)};for(const s of e.metrics){const a=s.domain||"uncategorized";r(a,{id:`metric:${s.name}`,label:s.label||s.name,kind:"metric",meta:{provider:t,domain:a,cube:s.table,owner:s.owner??"",tags:s.tags.join(",")}})}for(const s of e.dimensions){const a=s.domain||"uncategorized";r(a,{id:`dimension:${s.name}`,label:s.label||s.name,kind:"dimension",meta:{provider:t,domain:a,cube:s.table,owner:s.owner??"",tags:s.tags.join(",")}})}for(const s of e.hierarchies){const a=s.domain||"uncategorized";r(a,{id:`hierarchy:${s.name}`,label:s.label||s.name,kind:"hierarchy",meta:{provider:t,domain:a}})}const o=Array.from(n.entries()).sort((s,a)=>s[0].localeCompare(a[0])).map(([s,a])=>{const l=a.filter(u=>u.kind==="metric"),E=a.filter(u=>u.kind==="dimension"),c=a.filter(u=>u.kind==="hierarchy"),d=[];return l.length>0&&d.push({id:`group:${s}:metrics`,label:"Metrics",kind:"group",count:l.length,meta:{provider:t,domain:s},children:l.sort((u,T)=>u.label.localeCompare(T.label))}),E.length>0&&d.push({id:`group:${s}:dimensions`,label:"Dimensions",kind:"group",count:E.length,meta:{provider:t,domain:s},children:E.sort((u,T)=>u.label.localeCompare(T.label))}),c.length>0&&d.push({id:`group:${s}:hierarchies`,label:"Hierarchies",kind:"group",count:c.length,meta:{provider:t,domain:s},children:c.sort((u,T)=>u.label.localeCompare(T.label))}),{id:`domain:${t}:${s}`,label:s,kind:"domain",count:d.length,meta:{provider:t,domain:s},children:d}});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 Hp={source_table:"TABLE",dbt_model:"DBT",dbt_source:"SOURCE",block:"BLOCK",metric:"METRIC",dimension:"DIM",domain:"DOMAIN",chart:"CHART",dashboard:"NOTEBOOK"};function Lk(e,t,n="flow",r="LR"){var a;const o=new oi.graphlib.Graph().setDefaultEdgeLabel(()=>({})),s=r==="LR";o.setGraph({rankdir:r,ranksep:n==="layered"?120:s?80:60,nodesep:s?40:50,marginx:32,marginy:32});for(const l of e){const E={width:190,height:58};if(n==="layered"&&((a=l.data)!=null&&a.layer)){const c=Fs.indexOf(l.data.layer);c>=0&&(E.rank=c)}o.setNode(l.id,E)}for(const l of t)o.setEdge(l.source,l.target);return oi.layout(o),e.map(l=>{const E=o.node(l.id);return{...l,position:{x:E.x-95,y:E.y-29},data:{...l.data,direction:r}}})}function _k({data:e,selected:t}){const n=e.nodeType,r=we[n]??"#8b949e",o=Hp[n]??n.toUpperCase(),s=e.direction??"LR",a=s==="LR"?ne.Left:ne.Top,l=s==="LR"?ne.Right:ne.Bottom;return i.jsxs("div",{style:{minWidth:156,maxWidth:220,background:"#161b22",border:`2px solid ${t?"#58a6ff":r}`,borderRadius:10,padding:"8px 10px",boxShadow:t?"0 0 0 1px rgba(88, 166, 255, 0.2)":"none"},children:[i.jsx(tn,{type:"target",position:a,style:{width:7,height:7,background:r,border:"none"}}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[i.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.04em",color:"#0d1117",background:r,borderRadius:4,padding:"2px 6px"},children:o}),e.domain&&i.jsx("span",{style:{color:"#8b949e",fontSize:10},children:e.domain})]}),i.jsx("div",{style:{color:"#e6edf3",fontSize:11,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.label,children:e.label}),i.jsx("div",{style:{color:"#8b949e",fontSize:10,marginTop:3},children:Ci[n]??n}),i.jsx(tn,{type:"source",position:l,style:{width:7,height:7,background:r,border:"none"}})]})}const xk={dagNode:_k};function jn({label:e,active:t,color:n,onClick:r}){return i.jsx("button",{onClick:r,style:{borderRadius:999,border:`1px solid ${t?n:"#30363d"}`,background:t?`${n}22`:"transparent",color:t?n:"#8b949e",fontSize:10,fontWeight:700,padding:"4px 8px",cursor:"pointer"},children:e})}function yk(){const{state:e,dispatch:t}=de(),n=re[e.themeMode],[r,o]=R.useState(!0),[s,a]=R.useState({nodes:[],edges:[]}),[l,E]=R.useState({nodes:[],edges:[]}),[c,d]=R.useState(null),[u,T]=R.useState(null),[S,A]=R.useState(""),[f,I]=R.useState([]),[p,O]=R.useState({source_table:!0,dbt_model:!0,dbt_source:!0,block:!0,dashboard:!0,domain:!0}),[N,h]=R.useState("flow"),[C,m]=R.useState("LR"),[g,y,_]=jA([]),[U,D,b]=WA([]),F=R.useCallback(async()=>{o(!0);const x=await Q.fetchLineage(),B={nodes:x.nodes??[],edges:x.edges??[]};a(B),E(B),o(!1)},[]);R.useEffect(()=>{F()},[F]),R.useEffect(()=>{let x=!1;if(S.trim().length<2){I([]);return}return Q.searchLineage(S.trim()).then(B=>{x||I(B.matches??[])}),()=>{x=!0}},[S]);const L=R.useMemo(()=>{const x=new Set(l.nodes.filter(B=>p[B.type]??!1).map(B=>B.id));return{nodes:l.nodes.filter(B=>x.has(B.id)),edges:l.edges.filter(B=>x.has(B.source)&&x.has(B.target))}},[l,p]);R.useEffect(()=>{const x=L.nodes.map(H=>({id:H.id,type:"dagNode",position:{x:0,y:0},data:{label:H.name,nodeType:H.type,domain:H.domain,layer:xc(H)}})),B=L.edges.map((H,Y)=>({id:`edge-${Y}-${H.source}-${H.target}-${H.type}`,source:H.source,target:H.target,style:{stroke:Br[H.type]??"#8b949e",strokeWidth:1.6},markerEnd:{type:ar.ArrowClosed,color:Br[H.type]??"#8b949e",width:12,height:12}}));y(Lk(x,B,N,C)),D(B)},[L,N,C,D,y]);const P=R.useCallback(async x=>{const B=await Q.queryLineage({focus:x});E(B.graph??{nodes:[],edges:[]}),d(B.focalNode??null),T(B.focalNode??null),t({type:"SET_LINEAGE_FOCUS",nodeId:x}),A(""),I([])},[t]);R.useEffect(()=>{e.lineageFocusNodeId&&P(e.lineageFocusNodeId)},[P,e.lineageFocusNodeId]);const M=R.useCallback(()=>{E(s),d(null),T(null),t({type:"SET_LINEAGE_FOCUS",nodeId:null})},[t,s]),w=R.useCallback(async(x,B)=>{await P(B.id)},[P]),v=R.useMemo(()=>{if(!u)return null;const x=l.edges.filter(H=>H.target===u.id).length,B=l.edges.filter(H=>H.source===u.id).length;return{incoming:x,outgoing:B}},[l.edges,u]);return r?i.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"Loading lineage graph..."}):s.nodes.length===0?i.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"No lineage graph available yet."}):i.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",background:"#0d1117"},children:[i.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`,background:n.sidebarBg},children:[i.jsxs("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap",alignItems:"center"},children:[i.jsxs("div",{style:{display:"flex",borderRadius:6,border:`1px solid ${n.headerBorder}`,overflow:"hidden"},children:[i.jsx("button",{onClick:()=>h("flow"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",cursor:"pointer",background:N==="flow"?"#30363d":"transparent",color:N==="flow"?"#e6edf3":"#8b949e"},children:"Flow"}),i.jsx("button",{onClick:()=>h("layered"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",borderLeft:`1px solid ${n.headerBorder}`,cursor:"pointer",background:N==="layered"?"#30363d":"transparent",color:N==="layered"?"#e6edf3":"#8b949e"},children:"Layered"})]}),i.jsxs("div",{style:{display:"flex",borderRadius:6,border:`1px solid ${n.headerBorder}`,overflow:"hidden",marginRight:4},children:[i.jsxs("button",{title:"Horizontal layout (left → right)",onClick:()=>m("LR"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",cursor:"pointer",background:C==="LR"?"#30363d":"transparent",color:C==="LR"?"#e6edf3":"#8b949e",display:"flex",alignItems:"center",gap:3},children:[i.jsxs("svg",{width:"14",height:"10",viewBox:"0 0 14 10",fill:"none",children:[i.jsx("rect",{x:"0",y:"2",width:"4",height:"6",rx:"1",fill:"currentColor",opacity:"0.7"}),i.jsx("line",{x1:"4",y1:"5",x2:"10",y2:"5",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M9 3l2 2-2 2",stroke:"currentColor",strokeWidth:"1.2",fill:"none"}),i.jsx("rect",{x:"10",y:"2",width:"4",height:"6",rx:"1",fill:"currentColor"})]}),"LR"]}),i.jsxs("button",{title:"Vertical layout (top → bottom)",onClick:()=>m("TB"),style:{padding:"4px 8px",fontSize:10,fontWeight:700,border:"none",borderLeft:`1px solid ${n.headerBorder}`,cursor:"pointer",background:C==="TB"?"#30363d":"transparent",color:C==="TB"?"#e6edf3":"#8b949e",display:"flex",alignItems:"center",gap:3},children:[i.jsxs("svg",{width:"10",height:"14",viewBox:"0 0 10 14",fill:"none",children:[i.jsx("rect",{x:"2",y:"0",width:"6",height:"4",rx:"1",fill:"currentColor",opacity:"0.7"}),i.jsx("line",{x1:"5",y1:"4",x2:"5",y2:"10",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M3 9l2 2 2-2",stroke:"currentColor",strokeWidth:"1.2",fill:"none"}),i.jsx("rect",{x:"2",y:"10",width:"6",height:"4",rx:"1",fill:"currentColor"})]}),"TB"]})]}),i.jsx(jn,{label:"Tables",active:p.source_table,color:we.source_table,onClick:()=>O(x=>({...x,source_table:!x.source_table}))}),i.jsx(jn,{label:"dbt Models",active:p.dbt_model,color:we.dbt_model,onClick:()=>O(x=>({...x,dbt_model:!x.dbt_model}))}),i.jsx(jn,{label:"dbt Sources",active:p.dbt_source,color:we.dbt_source,onClick:()=>O(x=>({...x,dbt_source:!x.dbt_source}))}),i.jsx(jn,{label:"DQL Blocks",active:p.block,color:we.block,onClick:()=>O(x=>({...x,block:!x.block}))}),i.jsx(jn,{label:"Notebooks",active:p.dashboard,color:we.dashboard,onClick:()=>O(x=>({...x,dashboard:!x.dashboard}))}),i.jsx(jn,{label:"Domains",active:p.domain,color:we.domain,onClick:()=>O(x=>({...x,domain:!x.domain}))})]}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx("input",{value:S,onChange:x=>A(x.target.value),placeholder:"Search lineage and focus the graph...",style:{flex:1,padding:"8px 10px",borderRadius:6,border:`1px solid ${n.headerBorder}`,background:"#0d1117",color:n.textPrimary,fontSize:12,outline:"none"}}),c&&i.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"})]}),i.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."}),f.length>0&&i.jsx("div",{style:{marginTop:8,border:`1px solid ${n.headerBorder}`,borderRadius:8,overflow:"hidden"},children:f.slice(0,8).map(x=>i.jsxs("button",{onClick:()=>void P(x.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:[i.jsx("span",{style:{color:we[x.node.type]??"#8b949e",fontSize:10,fontWeight:700,marginRight:8},children:Hp[x.node.type]??x.node.type.toUpperCase()}),x.node.name]},x.node.id))})]}),i.jsx("div",{style:{flex:1,position:"relative"},children:i.jsxs(YA,{nodes:g,edges:U,onNodesChange:_,onEdgesChange:b,onNodeClick:w,nodeTypes:xk,fitView:!0,fitViewOptions:{padding:.18},proOptions:{hideAttribution:!0},style:{background:"#0d1117"},children:[i.jsx($A,{color:"#21262d",gap:24,size:1}),i.jsx(Gb,{showInteractive:!1}),i.jsx(Qb,{nodeColor:x=>{var B;return we[((B=x.data)==null?void 0:B.nodeType)??"source_table"]??"#8b949e"},maskColor:"rgba(0,0,0,0.55)",style:{background:"#0d1117",border:"1px solid #30363d"}}),i.jsx(ur,{position:"top-left",children:i.jsxs("div",{style:{background:"rgba(13, 17, 23, 0.9)",border:"1px solid #30363d",borderRadius:8,padding:"8px 10px",minWidth:220,color:"#e6edf3",fontSize:12},children:[i.jsx("div",{style:{fontWeight:700,marginBottom:4},children:c?c.name:"Full Lineage View"}),i.jsxs("div",{style:{color:"#8b949e",fontSize:11},children:[l.nodes.length," node(s), ",l.edges.length," edge(s)"]}),i.jsx("div",{style:{color:"#8b949e",fontSize:11,marginTop:6,lineHeight:1.5},children:c?`Focused on ${Ci[c.type]??c.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&&v&&i.jsxs("div",{style:{marginTop:8,color:"#8b949e",fontSize:11},children:[v.incoming," upstream, ",v.outgoing," downstream"]})]})}),i.jsx(ur,{position:"bottom-left",children:i.jsx("div",{style:{display:"flex",gap:10,background:"rgba(13, 17, 23, 0.9)",border:"1px solid #30363d",borderRadius:8,padding:"6px 10px",color:"#8b949e",fontSize:10},children:Object.entries(Br).map(([x,B])=>i.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[i.jsx("span",{style:{width:10,height:2,background:B,display:"inline-block"}}),aL[x]??x]},x))})})]})})]})}function Dk(){const{state:e,dispatch:t}=de(),{executeAll:n}=gi();R.useEffect(()=>{const r=o=>{const s=o.metaKey||o.ctrlKey;if(s&&o.key==="b"&&!o.shiftKey){o.preventDefault(),t({type:"TOGGLE_SIDEBAR"});return}if(s&&o.shiftKey&&o.key==="Enter"){o.preventDefault(),e.activeFile&&n();return}if(s&&o.key==="j"&&!o.shiftKey){o.preventDefault(),t({type:"TOGGLE_DEV_PANEL"});return}if(s&&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 Mk=600;function Pk(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 _T(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 bk(){var o;const{state:e}=de(),t=R.useRef(null),n=R.useRef(""),r=R.useRef(null);R.useEffect(()=>{var l;const s=((l=e.activeFile)==null?void 0:l.path)??null;if(!s)return;if(s!==r.current){r.current=s,n.current=_T(e.cells);return}const a=_T(e.cells);if(a!==n.current)return n.current=a,t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{const E=Pk(s,e.cells);Q.saveRunSnapshot(s,E).catch(()=>{})},Mk),()=>{t.current&&clearTimeout(t.current)}},[e.cells,(o=e.activeFile)==null?void 0:o.path])}function vk(){const{state:e,dispatch:t}=de(),n=re[e.themeMode],r=R.useRef({}),[o,s]=R.useState(!1);Dk(),bk(),R.useEffect(()=>{const E=c=>{(c.metaKey||c.ctrlKey)&&c.key.toLowerCase()==="k"&&!c.shiftKey&&(c.preventDefault(),s(d=>!d)),(c.metaKey||c.ctrlKey)&&c.shiftKey&&c.key.toLowerCase()==="i"&&(c.preventDefault(),t({type:"TOGGLE_INSPECTOR"}))};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[t]);const a=R.useCallback(async E=>{try{if(E.type==="block"){const f=await Q.openBlockStudio(E.path);t({type:"OPEN_BLOCK_STUDIO",file:E,payload:f});return}const{content:c}=await Q.readNotebook(E.path),{title:d,cells:u,metadata:T}=CL(E.path,c),S=await Q.fetchRunSnapshot(E.path),A=S.found&&S.snapshot?u.map(f=>{const I=S.snapshot.cells.find(p=>p.cellId===f.id);return I?{...f,status:I.status??f.status,result:I.result??f.result,error:I.error??f.error,executionCount:I.executionCount??f.executionCount}:f}):u;t({type:"OPEN_FILE",file:E,cells:A,title:d,metadata:T}),e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"})}catch(c){if(console.error("Failed to open file:",c),E.type==="block")try{const{content:d}=await Q.readNotebook(E.path);t({type:"OPEN_BLOCK_STUDIO",file:E,payload:{path:E.path,source:d,companionPath:null,metadata:{name:E.name.replace(/\.dql$/i,""),path:E.path,domain:E.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(d){console.error("Failed to open block fallback:",d)}else t({type:"OPEN_FILE",file:E,cells:[We("sql")],title:E.name})}},[t,e.sidebarPanel]);R.useCallback(E=>{const c=r.current[E];c&&c.scrollIntoView({behavior:"smooth",block:"start"})},[]);const l=R.useCallback((E,c)=>{c?r.current[E]=c:delete r.current[E]},[]);return i.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100vh",width:"100vw",background:n.appBg,fontFamily:n.font,color:n.textPrimary,overflow:"hidden"},children:[i.jsx(JL,{}),i.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[i.jsx(Dg,{}),e.sidebarOpen&&i.jsx(OL,{onOpenFile:a}),i.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:e.lineageFullscreen?i.jsx(yk,{}):e.mainView==="connection"?i.jsx(xT,{title:"Connections",description:"Manage database connections, edit driver settings, and test connectivity in a full-page workspace.",children:i.jsx(PR,{})}):e.mainView==="reference"?i.jsx(xT,{title:"Quick Reference",description:"Browse the complete DQL guide, semantic workflows, and authoring patterns in a documentation-style view.",children:i.jsx(bR,{themeMode:e.themeMode})}):i.jsx(i.Fragment,{children:e.mainView==="block_studio"?i.jsx(ck,{}):i.jsxs(i.Fragment,{children:[i.jsx(q2,{onOpenFile:a,registerCellRef:l}),i.jsx(e_,{})]})})}),e.inspectorOpen&&!e.lineageFullscreen&&!e.dashboardMode&&i.jsx(Tg,{})]}),e.newNotebookModalOpen&&i.jsx(rk,{onFileOpened:a}),e.newBlockModalOpen&&i.jsx(ik,{onFileOpened:a}),i.jsx(dg,{open:o,onClose:()=>s(!1)})]})}function xT({title:e,description:t,children:n}){return i.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden"},children:[i.jsxs("div",{style:{padding:"18px 24px 12px",borderBottom:"1px solid rgba(127, 127, 127, 0.16)"},children:[i.jsx("div",{style:{fontSize:22,fontWeight:700},children:e}),i.jsx("div",{style:{fontSize:13,opacity:.72,marginTop:6,maxWidth:760,lineHeight:1.5},children:t})]}),i.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:n})]})}function Uk(){const{state:e,dispatch:t}=de(),n=R.useRef(null),r=R.useRef(null);R.useEffect(()=>{var o;n.current=((o=e.activeFile)==null?void 0:o.path)??null},[e.activeFile]),R.useEffect(()=>{if(typeof EventSource>"u")return;const o=()=>{const s=new EventSource(`${window.location.origin}/api/watch`);r.current=s,s.addEventListener("change",a=>{try{const l=JSON.parse(a.data);(l.type==="file-added"||l.type==="file-deleted")&&Q.listNotebooks().then(E=>{t({type:"SET_FILES",files:E})}),l.type==="file-changed"&&Q.listNotebooks().then(E=>{t({type:"SET_FILES",files:E})}),l.type==="semantic-reload"&&(t({type:"SET_SEMANTIC_LOADING",loading:!0}),Q.getSemanticLayer().then(E=>{t({type:"SET_SEMANTIC_LAYER",layer:E})}))}catch{}}),s.addEventListener("error",()=>{s.close(),setTimeout(o,5e3)})};return o(),()=>{var s;(s=r.current)==null||s.close(),r.current=null}},[t])}function wk(){const{state:e,dispatch:t}=de(),n=re[e.themeMode];return R.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=`
599
+ * { margin: 0; padding: 0; box-sizing: border-box; }
600
+ body {
601
+ font-family: ${n.font};
602
+ overflow: hidden;
603
+ background: ${n.appBg};
604
+ color: ${n.textPrimary};
605
+ }
606
+ ::-webkit-scrollbar { width: 6px; height: 6px; }
607
+ ::-webkit-scrollbar-track { background: transparent; }
608
+ ::-webkit-scrollbar-thumb {
609
+ background: ${n.scrollbarThumb};
610
+ border-radius: 3px;
611
+ }
612
+ ::-webkit-scrollbar-thumb:hover {
613
+ background: ${n.textMuted};
614
+ }
615
+ ::selection {
616
+ background: ${n.accent}40;
617
+ color: ${n.textPrimary};
618
+ }
619
+ .dql-meta-pill:hover {
620
+ background: var(--dql-pill-hover-bg) !important;
621
+ border-color: var(--dql-pill-hover-border) !important;
622
+ }
623
+ `},[n]),R.useEffect(()=>{t({type:"SET_FILES_LOADING",loading:!0}),Q.listNotebooks().then(r=>{t({type:"SET_FILES",files:r}),t({type:"SET_FILES_LOADING",loading:!1})})},[t]),R.useEffect(()=>{t({type:"SET_SCHEMA_LOADING",loading:!0}),Q.getSchema().then(r=>{t({type:"SET_SCHEMA",tables:r}),t({type:"SET_SCHEMA_LOADING",loading:!1})})},[t]),Uk(),i.jsx(kI,{theme:e.themeMode,applyGlobal:!0,children:i.jsx(ZN,{delayDuration:200,skipDelayDuration:400,children:i.jsx(vk,{})})})}function Bk(){return i.jsx(cg,{children:i.jsx(wk,{})})}wI.createRoot(document.getElementById("root")).render(i.jsx(Bk,{}));