@duckcodeailabs/dql-cli 0.10.0 → 0.10.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,608 @@
|
|
|
1
|
+
import{r as ei,a as aT,g as ti}from"./react-CRB3T2We.js";import{S as ni,g as lT,E as it,s as mI,a as be,b as cT,c as LI,P as _I,d as gI,e as xI,F as yI,f as DI,h as ET,V as PI,D as un,R as MI,i as bI,C as Xt,j as dT,k as ze,r as vI,l as UI,m as wI,u as BI,n as FI,t as GI,o as HI,p as YI,q as kI,v as WI,w as VI,x as jI,y as ko,z as $I,A as XI,B as KI,G as zI,H as JI,I as qI,J as QI,K as ZI,L as eO,M as tO,N as nO,O as rO}from"./codemirror-BqWuFwtC.js";function oO(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 i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).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 zi={exports:{}},mr={};/**
|
|
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 qc;function sO(){if(qc)return mr;qc=1;var e=ei(),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 i(l,c,E){var d,u={},T=null,S=null;E!==void 0&&(T=""+E),c.key!==void 0&&(T=""+c.key),c.ref!==void 0&&(S=c.ref);for(d in c)r.call(c,d)&&!s.hasOwnProperty(d)&&(u[d]=c[d]);if(l&&l.defaultProps)for(d in c=l.defaultProps,c)u[d]===void 0&&(u[d]=c[d]);return{$$typeof:t,type:l,key:T,ref:S,props:u,_owner:o.current}}return mr.Fragment=n,mr.jsx=i,mr.jsxs=i,mr}var Qc;function iO(){return Qc||(Qc=1,zi.exports=sO()),zi.exports}var a=iO(),Wo={},Zc;function aO(){if(Zc)return Wo;Zc=1;var e=aT();return Wo.createRoot=e.createRoot,Wo.hydrateRoot=e.hydrateRoot,Wo}var lO=aO(),R=ei();const Ce=ti(R),uT=oO({__proto__:null,default:Ce},[R]),Ae={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"},Ie={1:"4px",2:"8px",3:"12px",4:"16px"},Cn={sm:"4px",md:"6px",lg:"8px"},ve={xs:"11px",sm:"12px",md:"14px"},Gl={medium:"500",semibold:"600"},Gr={overlay:1e3,modal:1100,popover:1200,tooltip:1300},cO={surfaceBase:Ae.gray1000,surfaceRaised:Ae.gray975,surfaceElevated:Ae.gray950,surfaceOverlay:"rgba(0,0,0,0.7)",surfaceHover:Ae.gray900,surfaceActive:"#1f2d3d",surfaceSunken:Ae.gray1000,borderSubtle:"#21262d",borderDefault:"#30363d",borderStrong:"#484f58",borderFocus:Ae.blue500,textPrimary:"#e6edf3",textSecondary:"#8b949e",textMuted:"#484f58",textDisabled:"#32383f",textInverse:Ae.gray1000,accent:Ae.blue500,accentHover:Ae.blue400,accentMuted:"rgba(56,139,253,0.15)",accentContrast:"#ffffff",success:Ae.green500,warning:Ae.yellow500,danger:Ae.red500,info:Ae.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)"},EO={surfaceBase:Ae.gray0,surfaceRaised:Ae.gray50,surfaceElevated:Ae.gray0,surfaceOverlay:"rgba(0,0,0,0.4)",surfaceHover:Ae.gray100,surfaceActive:"#dbeafe",surfaceSunken:Ae.gray50,borderSubtle:Ae.gray100,borderDefault:Ae.gray200,borderStrong:Ae.gray300,borderFocus:Ae.blue600,textPrimary:"#1f2328",textSecondary:Ae.gray600,textMuted:Ae.gray400,textDisabled:Ae.gray300,textInverse:Ae.gray0,accent:Ae.blue600,accentHover:Ae.blue700,accentMuted:"rgba(9,105,218,0.12)",accentContrast:"#ffffff",success:Ae.green600,warning:Ae.yellow600,danger:Ae.red600,info:Ae.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)"},dO={dark:cO,light:EO};function TT(e){return`--dql-${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function eE(e){const t={};for(const[n,r]of Object.entries(e))t[TT(n)]=r;return t}function ue(e){return`var(${TT(e)})`}const uO=R.createContext(null);function TO({theme:e,defaultTheme:t="dark",onThemeChange:n,applyGlobal:r=!1,children:o}){const[s,i]=R.useState(t),l=e??s,c=dO[l],E=R.useCallback(T=>{e===void 0&&i(T),n==null||n(T)},[e,n]);R.useEffect(()=>{if(!r)return;const T=eE(c),S=document.documentElement;for(const[f,A]of Object.entries(T))S.style.setProperty(f,A);return S.setAttribute("data-theme",l),()=>{for(const f of Object.keys(T))S.style.removeProperty(f);S.removeAttribute("data-theme")}},[r,l,c]);const d=R.useMemo(()=>({theme:l,tokens:c,setTheme:E}),[l,c,E]),u=r?void 0:eE(c);return a.jsx(uO.Provider,{value:d,children:a.jsx("div",{"data-theme":l,style:u,children:o})})}function oe(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 ri(...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 me(...e){return R.useCallback(ri(...e),e)}function SO(e,t){const n=R.createContext(t),r=s=>{const{children:i,...l}=s,c=R.useMemo(()=>l,Object.values(l));return a.jsx(n.Provider,{value:c,children:i})};r.displayName=e+"Provider";function o(s){const i=R.useContext(n);if(i)return i;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,i){const l=R.createContext(i),c=n.length;n=[...n,i];const E=u=>{var I;const{scope:T,children:S,...f}=u,A=((I=T==null?void 0:T[e])==null?void 0:I[c])||l,O=R.useMemo(()=>f,Object.values(f));return a.jsx(A.Provider,{value:O,children:S})};E.displayName=s+"Provider";function d(u,T){var A;const S=((A=T==null?void 0:T[e])==null?void 0:A[c])||l,f=R.useContext(S);if(f)return f;if(i!==void 0)return i;throw new Error(`\`${u}\` must be used within \`${s}\``)}return[E,d]}const o=()=>{const s=n.map(i=>R.createContext(i));return function(l){const c=(l==null?void 0:l[e])||s;return R.useMemo(()=>({[`__scope${e}`]:{...l,[e]:c}}),[l,c])}};return o.scopeName=e,[r,RO(o,...t)]}function RO(...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 i=r.reduce((l,{useScope:c,scopeName:E})=>{const u=c(s)[`__scope${E}`];return{...l,...u}},{});return R.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Hl=aT();const AO=ti(Hl);function Qn(e){const t=fO(e),n=R.forwardRef((r,o)=>{const{children:s,...i}=r,l=R.Children.toArray(s),c=l.find(OO);if(c){const E=c.props.children,d=l.map(u=>u===c?R.Children.count(E)>1?R.Children.only(null):R.isValidElement(E)?E.props.children:null:u);return a.jsx(t,{...i,ref:o,children:R.isValidElement(E)?R.cloneElement(E,void 0,d):null})}return a.jsx(t,{...i,ref:o,children:s})});return n.displayName=`${e}.Slot`,n}function fO(e){const t=R.forwardRef((n,r)=>{const{children:o,...s}=n;if(R.isValidElement(o)){const i=pO(o),l=NO(s,o.props);return o.type!==R.Fragment&&(l.ref=r?ri(r,i):i),R.cloneElement(o,l)}return R.Children.count(o)>1?R.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var ST=Symbol("radix.slottable");function IO(e){const t=({children:n})=>a.jsx(a.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=ST,t}function OO(e){return R.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===ST}function NO(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 c=s(...l);return o(...l),c}:o&&(n[r]=o):r==="style"?n[r]={...o,...s}:r==="className"&&(n[r]=[o,s].filter(Boolean).join(" "))}return{...e,...n}}function pO(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 hO=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ne=hO.reduce((e,t)=>{const n=Qn(`Primitive.${t}`),r=R.forwardRef((o,s)=>{const{asChild:i,...l}=o,c=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),a.jsx(c,{...l,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function RT(e,t){e&&Hl.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 CO(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 mO="DismissableLayer",al="dismissableLayer.update",LO="dismissableLayer.pointerDownOutside",_O="dismissableLayer.focusOutside",nE,AT=R.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),oo=R.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:l,...c}=e,E=R.useContext(AT),[d,u]=R.useState(null),T=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,S]=R.useState({}),f=me(t,_=>u(_)),A=Array.from(E.layers),[O]=[...E.layersWithOutsidePointerEventsDisabled].slice(-1),I=A.indexOf(O),p=d?A.indexOf(d):-1,N=E.layersWithOutsidePointerEventsDisabled.size>0,h=p>=I,C=yO(_=>{const D=_.target,g=[...E.branches].some(b=>b.contains(D));!h||g||(o==null||o(_),i==null||i(_),_.defaultPrevented||l==null||l())},T),m=DO(_=>{const D=_.target;[...E.branches].some(b=>b.contains(D))||(s==null||s(_),i==null||i(_),_.defaultPrevented||l==null||l())},T);return CO(_=>{p===E.layers.size-1&&(r==null||r(_),!_.defaultPrevented&&l&&(_.preventDefault(),l()))},T),R.useEffect(()=>{if(d)return n&&(E.layersWithOutsidePointerEventsDisabled.size===0&&(nE=T.body.style.pointerEvents,T.body.style.pointerEvents="none"),E.layersWithOutsidePointerEventsDisabled.add(d)),E.layers.add(d),rE(),()=>{n&&E.layersWithOutsidePointerEventsDisabled.size===1&&(T.body.style.pointerEvents=nE)}},[d,T,n,E]),R.useEffect(()=>()=>{d&&(E.layers.delete(d),E.layersWithOutsidePointerEventsDisabled.delete(d),rE())},[d,E]),R.useEffect(()=>{const _=()=>S({});return document.addEventListener(al,_),()=>document.removeEventListener(al,_)},[]),a.jsx(Ne.div,{...c,ref:f,style:{pointerEvents:N?h?"auto":"none":void 0,...e.style},onFocusCapture:oe(e.onFocusCapture,m.onFocusCapture),onBlurCapture:oe(e.onBlurCapture,m.onBlurCapture),onPointerDownCapture:oe(e.onPointerDownCapture,C.onPointerDownCapture)})});oo.displayName=mO;var gO="DismissableLayerBranch",xO=R.forwardRef((e,t)=>{const n=R.useContext(AT),r=R.useRef(null),o=me(t,r);return R.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),a.jsx(Ne.div,{...e,ref:o})});xO.displayName=gO;function yO(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 c=function(){fT(LO,n,E,{discrete:!0})};const E={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=c,t.addEventListener("click",o.current,{once:!0})):c()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function DO(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&&fT(_O,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(al);document.dispatchEvent(e)}function fT(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?RT(o,s):o.dispatchEvent(s)}var Qt=globalThis!=null&&globalThis.document?R.useLayoutEffect:()=>{},PO=uT[" useId ".trim().toString()]||(()=>{}),MO=0;function vr(e){const[t,n]=R.useState(PO());return Qt(()=>{n(r=>r??String(MO++))},[e]),t?`radix-${t}`:""}const bO=["top","right","bottom","left"],Zt=Math.min,je=Math.max,ms=Math.round,Vo=Math.floor,It=e=>({x:e,y:e}),vO={left:"right",right:"left",bottom:"top",top:"bottom"};function ll(e,t,n){return je(e,Zt(t,n))}function Pt(e,t){return typeof e=="function"?e(t):e}function Mt(e){return e.split("-")[0]}function ur(e){return e.split("-")[1]}function Yl(e){return e==="x"?"y":"x"}function kl(e){return e==="y"?"height":"width"}function At(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function Wl(e){return Yl(At(e))}function UO(e,t,n){n===void 0&&(n=!1);const r=ur(e),o=Wl(e),s=kl(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=Ls(i)),[i,Ls(i)]}function wO(e){const t=Ls(e);return[cl(e),t,cl(t)]}function cl(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const oE=["left","right"],sE=["right","left"],BO=["top","bottom"],FO=["bottom","top"];function GO(e,t,n){switch(e){case"top":case"bottom":return n?t?sE:oE:t?oE:sE;case"left":case"right":return t?BO:FO;default:return[]}}function HO(e,t,n,r){const o=ur(e);let s=GO(Mt(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(cl)))),s}function Ls(e){const t=Mt(e);return vO[t]+e.slice(t.length)}function YO(e){return{top:0,right:0,bottom:0,left:0,...e}}function IT(e){return typeof e!="number"?YO(e):{top:e,right:e,bottom:e,left:e}}function _s(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 iE(e,t,n){let{reference:r,floating:o}=e;const s=At(t),i=Wl(t),l=kl(i),c=Mt(t),E=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(c){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(ur(t)){case"start":S[i]-=T*(n&&E?-1:1);break;case"end":S[i]+=T*(n&&E?-1:1);break}return S}async function kO(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:l,strategy:c}=e,{boundary:E="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:T=!1,padding:S=0}=Pt(t,e),f=IT(S),O=l[T?u==="floating"?"reference":"floating":u],I=_s(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(O)))==null||n?O:O.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(l.floating)),boundary:E,rootBoundary:d,strategy:c})),p=u==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.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=_s(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:p,offsetParent:N,strategy:c}):p);return{top:(I.top-C.top+f.top)/h.y,bottom:(C.bottom-I.bottom+f.bottom)/h.y,left:(I.left-C.left+f.left)/h.x,right:(C.right-I.right+f.right)/h.x}}const WO=50,VO=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,l=i.detectOverflow?i:{...i,detectOverflow:kO},c=await(i.isRTL==null?void 0:i.isRTL(t));let E=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:u}=iE(E,r,c),T=r,S=0;const f={};for(let A=0;A<s.length;A++){const O=s[A];if(!O)continue;const{name:I,fn:p}=O,{x:N,y:h,data:C,reset:m}=await p({x:d,y:u,initialPlacement:r,placement:T,strategy:o,middlewareData:f,rects:E,platform:l,elements:{reference:e,floating:t}});d=N??d,u=h??u,f[I]={...f[I],...C},m&&S<WO&&(S++,typeof m=="object"&&(m.placement&&(T=m.placement),m.rects&&(E=m.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):m.rects),{x:d,y:u}=iE(E,T,c)),A=-1)}return{x:d,y:u,placement:T,strategy:o,middlewareData:f}},jO=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:l,middlewareData:c}=t,{element:E,padding:d=0}=Pt(e,t)||{};if(E==null)return{};const u=IT(d),T={x:n,y:r},S=Wl(o),f=kl(S),A=await i.getDimensions(E),O=S==="y",I=O?"top":"left",p=O?"bottom":"right",N=O?"clientHeight":"clientWidth",h=s.reference[f]+s.reference[S]-T[S]-s.floating[f],C=T[S]-s.reference[S],m=await(i.getOffsetParent==null?void 0:i.getOffsetParent(E));let _=m?m[N]:0;(!_||!await(i.isElement==null?void 0:i.isElement(m)))&&(_=l.floating[N]||s.floating[f]);const D=h/2-C/2,g=_/2-A[f]/2-1,b=Zt(u[I],g),y=Zt(u[p],g),M=b,F=_-A[f]-y,L=_/2-A[f]/2+D,v=ll(M,L,F),P=!c.arrow&&ur(o)!=null&&L!==v&&s.reference[f]/2-(L<M?b:y)-A[f]/2<0,w=P?L<M?L-M:L-F:0;return{[S]:T[S]+w,data:{[S]:v,centerOffset:L-v-w,...P&&{alignmentOffset:w}},reset:P}}}),$O=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:l,platform:c,elements:E}=t,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:T,fallbackStrategy:S="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:A=!0,...O}=Pt(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const I=Mt(o),p=At(l),N=Mt(l)===l,h=await(c.isRTL==null?void 0:c.isRTL(E.floating)),C=T||(N||!A?[Ls(l)]:wO(l)),m=f!=="none";!T&&m&&C.push(...HO(l,A,f,h));const _=[l,...C],D=await c.detectOverflow(t,O),g=[];let b=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&g.push(D[I]),u){const L=UO(o,i,h);g.push(D[L[0]],D[L[1]])}if(b=[...b,{placement:o,overflows:g}],!g.every(L=>L<=0)){var y,M;const L=(((y=s.flip)==null?void 0:y.index)||0)+1,v=_[L];if(v&&(!(u==="alignment"?p!==At(v):!1)||b.every(U=>At(U.placement)===p?U.overflows[0]>0:!0)))return{data:{index:L,overflows:b},reset:{placement:v}};let P=(M=b.filter(w=>w.overflows[0]<=0).sort((w,U)=>w.overflows[1]-U.overflows[1])[0])==null?void 0:M.placement;if(!P)switch(S){case"bestFit":{var F;const w=(F=b.filter(U=>{if(m){const x=At(U.placement);return x===p||x==="y"}return!0}).map(U=>[U.placement,U.overflows.filter(x=>x>0).reduce((x,B)=>x+B,0)]).sort((U,x)=>U[1]-x[1])[0])==null?void 0:F[0];w&&(P=w);break}case"initialPlacement":P=l;break}if(o!==P)return{reset:{placement:P}}}return{}}}};function aE(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function lE(e){return bO.some(t=>e[t]>=0)}const XO=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 i=await r.detectOverflow(t,{...s,elementContext:"reference"}),l=aE(i,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:lE(l)}}}case"escaped":{const i=await r.detectOverflow(t,{...s,altBoundary:!0}),l=aE(i,n.floating);return{data:{escapedOffsets:l,escaped:lE(l)}}}default:return{}}}}},OT=new Set(["left","top"]);async function KO(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Mt(n),l=ur(n),c=At(n)==="y",E=OT.has(i)?-1:1,d=s&&c?-1:1,u=Pt(t,e);let{mainAxis:T,crossAxis:S,alignmentAxis:f}=typeof u=="number"?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return l&&typeof f=="number"&&(S=l==="end"?f*-1:f),c?{x:S*d,y:T*E}:{x:T*E,y:S*d}}const zO=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:l}=t,c=await KO(t,e);return i===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:o+c.x,y:s+c.y,data:{...c,placement:i}}}}},JO=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:i=!0,crossAxis:l=!1,limiter:c={fn:I=>{let{x:p,y:N}=I;return{x:p,y:N}}},...E}=Pt(e,t),d={x:n,y:r},u=await s.detectOverflow(t,E),T=At(Mt(o)),S=Yl(T);let f=d[S],A=d[T];if(i){const I=S==="y"?"top":"left",p=S==="y"?"bottom":"right",N=f+u[I],h=f-u[p];f=ll(N,f,h)}if(l){const I=T==="y"?"top":"left",p=T==="y"?"bottom":"right",N=A+u[I],h=A-u[p];A=ll(N,A,h)}const O=c.fn({...t,[S]:f,[T]:A});return{...O,data:{x:O.x-n,y:O.y-r,enabled:{[S]:i,[T]:l}}}}}},qO=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:l=0,mainAxis:c=!0,crossAxis:E=!0}=Pt(e,t),d={x:n,y:r},u=At(o),T=Yl(u);let S=d[T],f=d[u];const A=Pt(l,t),O=typeof A=="number"?{mainAxis:A,crossAxis:0}:{mainAxis:0,crossAxis:0,...A};if(c){const N=T==="y"?"height":"width",h=s.reference[T]-s.floating[N]+O.mainAxis,C=s.reference[T]+s.reference[N]-O.mainAxis;S<h?S=h:S>C&&(S=C)}if(E){var I,p;const N=T==="y"?"width":"height",h=OT.has(Mt(o)),C=s.reference[u]-s.floating[N]+(h&&((I=i.offset)==null?void 0:I[u])||0)+(h?0:O.crossAxis),m=s.reference[u]+s.reference[N]+(h?0:((p=i.offset)==null?void 0:p[u])||0)-(h?O.crossAxis:0);f<C?f=C:f>m&&(f=m)}return{[T]:S,[u]:f}}}},QO=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:l}=t,{apply:c=()=>{},...E}=Pt(e,t),d=await i.detectOverflow(t,E),u=Mt(o),T=ur(o),S=At(o)==="y",{width:f,height:A}=s.floating;let O,I;u==="top"||u==="bottom"?(O=u,I=T===(await(i.isRTL==null?void 0:i.isRTL(l.floating))?"start":"end")?"left":"right"):(I=u,O=T==="end"?"top":"bottom");const p=A-d.top-d.bottom,N=f-d.left-d.right,h=Zt(A-d[O],p),C=Zt(f-d[I],N),m=!t.middlewareData.shift;let _=h,D=C;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(D=N),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(_=p),m&&!T){const b=je(d.left,0),y=je(d.right,0),M=je(d.top,0),F=je(d.bottom,0);S?D=f-2*(b!==0||y!==0?b+y:je(d.left,d.right)):_=A-2*(M!==0||F!==0?M+F:je(d.top,d.bottom))}await c({...t,availableWidth:D,availableHeight:_});const g=await i.getDimensions(l.floating);return f!==g.width||A!==g.height?{reset:{rects:!0}}:{}}}};function oi(){return typeof window<"u"}function Tr(e){return NT(e)?(e.nodeName||"").toLowerCase():"#document"}function Xe(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function pt(e){var t;return(t=(NT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function NT(e){return oi()?e instanceof Node||e instanceof Xe(e).Node:!1}function at(e){return oi()?e instanceof Element||e instanceof Xe(e).Element:!1}function vt(e){return oi()?e instanceof HTMLElement||e instanceof Xe(e).HTMLElement:!1}function cE(e){return!oi()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Xe(e).ShadowRoot}function so(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 ZO(e){return/^(table|td|th)$/.test(Tr(e))}function si(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const eN=/transform|translate|scale|rotate|perspective|filter/,tN=/paint|layout|strict|content/,cn=e=>!!e&&e!=="none";let Ji;function Vl(e){const t=at(e)?lt(e):e;return cn(t.transform)||cn(t.translate)||cn(t.scale)||cn(t.rotate)||cn(t.perspective)||!jl()&&(cn(t.backdropFilter)||cn(t.filter))||eN.test(t.willChange||"")||tN.test(t.contain||"")}function nN(e){let t=en(e);for(;vt(t)&&!Zn(t);){if(Vl(t))return t;if(si(t))return null;t=en(t)}return null}function jl(){return Ji==null&&(Ji=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ji}function Zn(e){return/^(html|body|#document)$/.test(Tr(e))}function lt(e){return Xe(e).getComputedStyle(e)}function ii(e){return at(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function en(e){if(Tr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||cE(e)&&e.host||pt(e);return cE(t)?t.host:t}function pT(e){const t=en(e);return Zn(t)?e.ownerDocument?e.ownerDocument.body:e.body:vt(t)&&so(t)?t:pT(t)}function Hr(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=pT(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=Xe(o);if(s){const l=El(i);return t.concat(i,i.visualViewport||[],so(o)?o:[],l&&n?Hr(l):[])}else return t.concat(o,Hr(o,[],n))}function El(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function hT(e){const t=lt(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=vt(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,l=ms(n)!==s||ms(r)!==i;return l&&(n=s,r=i),{width:n,height:r,$:l}}function $l(e){return at(e)?e:e.contextElement}function $n(e){const t=$l(e);if(!vt(t))return It(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=hT(t);let i=(s?ms(n.width):n.width)/r,l=(s?ms(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!l||!Number.isFinite(l))&&(l=1),{x:i,y:l}}const rN=It(0);function CT(e){const t=Xe(e);return!jl()||!t.visualViewport?rN:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function oN(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Xe(e)?!1:t}function An(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=$l(e);let i=It(1);t&&(r?at(r)&&(i=$n(r)):i=$n(e));const l=oN(s,n,r)?CT(s):It(0);let c=(o.left+l.x)/i.x,E=(o.top+l.y)/i.y,d=o.width/i.x,u=o.height/i.y;if(s){const T=Xe(s),S=r&&at(r)?Xe(r):r;let f=T,A=El(f);for(;A&&r&&S!==f;){const O=$n(A),I=A.getBoundingClientRect(),p=lt(A),N=I.left+(A.clientLeft+parseFloat(p.paddingLeft))*O.x,h=I.top+(A.clientTop+parseFloat(p.paddingTop))*O.y;c*=O.x,E*=O.y,d*=O.x,u*=O.y,c+=N,E+=h,f=Xe(A),A=El(f)}}return _s({width:d,height:u,x:c,y:E})}function ai(e,t){const n=ii(e).scrollLeft;return t?t.left+n:An(pt(e)).left+n}function mT(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ai(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function sN(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=pt(r),l=t?si(t.floating):!1;if(r===i||l&&s)return n;let c={scrollLeft:0,scrollTop:0},E=It(1);const d=It(0),u=vt(r);if((u||!u&&!s)&&((Tr(r)!=="body"||so(i))&&(c=ii(r)),u)){const S=An(r);E=$n(r),d.x=S.x+r.clientLeft,d.y=S.y+r.clientTop}const T=i&&!u&&!s?mT(i,c):It(0);return{width:n.width*E.x,height:n.height*E.y,x:n.x*E.x-c.scrollLeft*E.x+d.x+T.x,y:n.y*E.y-c.scrollTop*E.y+d.y+T.y}}function iN(e){return Array.from(e.getClientRects())}function aN(e){const t=pt(e),n=ii(e),r=e.ownerDocument.body,o=je(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=je(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+ai(e);const l=-n.scrollTop;return lt(r).direction==="rtl"&&(i+=je(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:l}}const EE=25;function lN(e,t){const n=Xe(e),r=pt(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,l=0,c=0;if(o){s=o.width,i=o.height;const d=jl();(!d||d&&t==="fixed")&&(l=o.offsetLeft,c=o.offsetTop)}const E=ai(r);if(E<=0){const d=r.ownerDocument,u=d.body,T=getComputedStyle(u),S=d.compatMode==="CSS1Compat"&&parseFloat(T.marginLeft)+parseFloat(T.marginRight)||0,f=Math.abs(r.clientWidth-u.clientWidth-S);f<=EE&&(s-=f)}else E<=EE&&(s+=E);return{width:s,height:i,x:l,y:c}}function cN(e,t){const n=An(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=vt(e)?$n(e):It(1),i=e.clientWidth*s.x,l=e.clientHeight*s.y,c=o*s.x,E=r*s.y;return{width:i,height:l,x:c,y:E}}function dE(e,t,n){let r;if(t==="viewport")r=lN(e,n);else if(t==="document")r=aN(pt(e));else if(at(t))r=cN(t,n);else{const o=CT(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return _s(r)}function LT(e,t){const n=en(e);return n===t||!at(n)||Zn(n)?!1:lt(n).position==="fixed"||LT(n,t)}function EN(e,t){const n=t.get(e);if(n)return n;let r=Hr(e,[],!1).filter(l=>at(l)&&Tr(l)!=="body"),o=null;const s=lt(e).position==="fixed";let i=s?en(e):e;for(;at(i)&&!Zn(i);){const l=lt(i),c=Vl(i);!c&&l.position==="fixed"&&(o=null),(s?!c&&!o:!c&&l.position==="static"&&!!o&&(o.position==="absolute"||o.position==="fixed")||so(i)&&!c&<(e,i))?r=r.filter(d=>d!==i):o=l,i=en(i)}return t.set(e,r),r}function dN(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?si(t)?[]:EN(t,this._c):[].concat(n),r],l=dE(t,i[0],o);let c=l.top,E=l.right,d=l.bottom,u=l.left;for(let T=1;T<i.length;T++){const S=dE(t,i[T],o);c=je(S.top,c),E=Zt(S.right,E),d=Zt(S.bottom,d),u=je(S.left,u)}return{width:E-u,height:d-c,x:u,y:c}}function uN(e){const{width:t,height:n}=hT(e);return{width:t,height:n}}function TN(e,t,n){const r=vt(t),o=pt(t),s=n==="fixed",i=An(e,!0,s,t);let l={scrollLeft:0,scrollTop:0};const c=It(0);function E(){c.x=ai(o)}if(r||!r&&!s)if((Tr(t)!=="body"||so(o))&&(l=ii(t)),r){const S=An(t,!0,s,t);c.x=S.x+t.clientLeft,c.y=S.y+t.clientTop}else o&&E();s&&!r&&o&&E();const d=o&&!r&&!s?mT(o,l):It(0),u=i.left+l.scrollLeft-c.x-d.x,T=i.top+l.scrollTop-c.y-d.y;return{x:u,y:T,width:i.width,height:i.height}}function qi(e){return lt(e).position==="static"}function uE(e,t){if(!vt(e)||lt(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return pt(e)===n&&(n=n.ownerDocument.body),n}function _T(e,t){const n=Xe(e);if(si(e))return n;if(!vt(e)){let o=en(e);for(;o&&!Zn(o);){if(at(o)&&!qi(o))return o;o=en(o)}return n}let r=uE(e,t);for(;r&&ZO(r)&&qi(r);)r=uE(r,t);return r&&Zn(r)&&qi(r)&&!Vl(r)?n:r||nN(e)||n}const SN=async function(e){const t=this.getOffsetParent||_T,n=this.getDimensions,r=await n(e.floating);return{reference:TN(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function RN(e){return lt(e).direction==="rtl"}const AN={convertOffsetParentRelativeRectToViewportRelativeRect:sN,getDocumentElement:pt,getClippingRect:dN,getOffsetParent:_T,getElementRects:SN,getClientRects:iN,getDimensions:uN,getScale:$n,isElement:at,isRTL:RN};function gT(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function fN(e,t){let n=null,r;const o=pt(e);function s(){var l;clearTimeout(r),(l=n)==null||l.disconnect(),n=null}function i(l,c){l===void 0&&(l=!1),c===void 0&&(c=1),s();const E=e.getBoundingClientRect(),{left:d,top:u,width:T,height:S}=E;if(l||t(),!T||!S)return;const f=Vo(u),A=Vo(o.clientWidth-(d+T)),O=Vo(o.clientHeight-(u+S)),I=Vo(d),N={rootMargin:-f+"px "+-A+"px "+-O+"px "+-I+"px",threshold:je(0,Zt(1,c))||1};let h=!0;function C(m){const _=m[0].intersectionRatio;if(_!==c){if(!h)return i();_?i(!1,_):r=setTimeout(()=>{i(!1,1e-7)},1e3)}_===1&&!gT(E,e.getBoundingClientRect())&&i(),h=!1}try{n=new IntersectionObserver(C,{...N,root:o.ownerDocument})}catch{n=new IntersectionObserver(C,N)}n.observe(e)}return i(!0),s}function IN(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,E=$l(e),d=o||s?[...E?Hr(E):[],...t?Hr(t):[]]:[];d.forEach(I=>{o&&I.addEventListener("scroll",n,{passive:!0}),s&&I.addEventListener("resize",n)});const u=E&&l?fN(E,n):null;let T=-1,S=null;i&&(S=new ResizeObserver(I=>{let[p]=I;p&&p.target===E&&S&&t&&(S.unobserve(t),cancelAnimationFrame(T),T=requestAnimationFrame(()=>{var N;(N=S)==null||N.observe(t)})),n()}),E&&!c&&S.observe(E),t&&S.observe(t));let f,A=c?An(e):null;c&&O();function O(){const I=An(e);A&&!gT(A,I)&&n(),A=I,f=requestAnimationFrame(O)}return n(),()=>{var I;d.forEach(p=>{o&&p.removeEventListener("scroll",n),s&&p.removeEventListener("resize",n)}),u==null||u(),(I=S)==null||I.disconnect(),S=null,c&&cancelAnimationFrame(f)}}const ON=zO,NN=JO,pN=$O,hN=QO,CN=XO,TE=jO,mN=qO,LN=(e,t,n)=>{const r=new Map,o={platform:AN,...n},s={...o.platform,_c:r};return VO(e,t,{...o,platform:s})};var _N=typeof document<"u",gN=function(){},ds=_N?R.useLayoutEffect:gN;function gs(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(!gs(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)&&!gs(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function xT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function SE(e,t){const n=xT(e);return Math.round(t*n)/n}function Qi(e){const t=R.useRef(e);return ds(()=>{t.current=e}),t}function xN(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:l=!0,whileElementsMounted:c,open:E}=e,[d,u]=R.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[T,S]=R.useState(r);gs(T,r)||S(r);const[f,A]=R.useState(null),[O,I]=R.useState(null),p=R.useCallback(U=>{U!==m.current&&(m.current=U,A(U))},[]),N=R.useCallback(U=>{U!==_.current&&(_.current=U,I(U))},[]),h=s||f,C=i||O,m=R.useRef(null),_=R.useRef(null),D=R.useRef(d),g=c!=null,b=Qi(c),y=Qi(o),M=Qi(E),F=R.useCallback(()=>{if(!m.current||!_.current)return;const U={placement:t,strategy:n,middleware:T};y.current&&(U.platform=y.current),LN(m.current,_.current,U).then(x=>{const B={...x,isPositioned:M.current!==!1};L.current&&!gs(D.current,B)&&(D.current=B,Hl.flushSync(()=>{u(B)}))})},[T,t,n,y,M]);ds(()=>{E===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,u(U=>({...U,isPositioned:!1})))},[E]);const L=R.useRef(!1);ds(()=>(L.current=!0,()=>{L.current=!1}),[]),ds(()=>{if(h&&(m.current=h),C&&(_.current=C),h&&C){if(b.current)return b.current(h,C,F);F()}},[h,C,F,b,g]);const v=R.useMemo(()=>({reference:m,floating:_,setReference:p,setFloating:N}),[p,N]),P=R.useMemo(()=>({reference:h,floating:C}),[h,C]),w=R.useMemo(()=>{const U={position:n,left:0,top:0};if(!P.floating)return U;const x=SE(P.floating,d.x),B=SE(P.floating,d.y);return l?{...U,transform:"translate("+x+"px, "+B+"px)",...xT(P.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:x,top:B}},[n,l,P.floating,d.x,d.y]);return R.useMemo(()=>({...d,update:F,refs:v,elements:P,floatingStyles:w}),[d,F,v,P,w])}const yN=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?TE({element:r.current,padding:o}).fn(n):{}:r?TE({element:r,padding:o}).fn(n):{}}}},DN=(e,t)=>{const n=ON(e);return{name:n.name,fn:n.fn,options:[e,t]}},PN=(e,t)=>{const n=NN(e);return{name:n.name,fn:n.fn,options:[e,t]}},MN=(e,t)=>({fn:mN(e).fn,options:[e,t]}),bN=(e,t)=>{const n=pN(e);return{name:n.name,fn:n.fn,options:[e,t]}},vN=(e,t)=>{const n=hN(e);return{name:n.name,fn:n.fn,options:[e,t]}},UN=(e,t)=>{const n=CN(e);return{name:n.name,fn:n.fn,options:[e,t]}},wN=(e,t)=>{const n=yN(e);return{name:n.name,fn:n.fn,options:[e,t]}};var BN="Arrow",yT=R.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return a.jsx(Ne.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:a.jsx("polygon",{points:"0,0 30,0 15,10"})})});yT.displayName=BN;var FN=yT;function GN(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 i,l;if("borderBoxSize"in s){const c=s.borderBoxSize,E=Array.isArray(c)?c[0]:c;i=E.inlineSize,l=E.blockSize}else i=e.offsetWidth,l=e.offsetHeight;n({width:i,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Xl="Popper",[DT,Sr]=on(Xl),[HN,PT]=DT(Xl),MT=e=>{const{__scopePopper:t,children:n}=e,[r,o]=R.useState(null);return a.jsx(HN,{scope:t,anchor:r,onAnchorChange:o,children:n})};MT.displayName=Xl;var bT="PopperAnchor",vT=R.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=PT(bT,n),i=R.useRef(null),l=me(t,i),c=R.useRef(null);return R.useEffect(()=>{const E=c.current;c.current=(r==null?void 0:r.current)||i.current,E!==c.current&&s.onAnchorChange(c.current)}),r?null:a.jsx(Ne.div,{...o,ref:l})});vT.displayName=bT;var Kl="PopperContent",[YN,kN]=DT(Kl),UT=R.forwardRef((e,t)=>{var z,Y,K,le,se,ne;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:l=0,avoidCollisions:c=!0,collisionBoundary:E=[],collisionPadding:d=0,sticky:u="partial",hideWhenDetached:T=!1,updatePositionStrategy:S="optimized",onPlaced:f,...A}=e,O=PT(Kl,n),[I,p]=R.useState(null),N=me(t,te=>p(te)),[h,C]=R.useState(null),m=GN(h),_=(m==null?void 0:m.width)??0,D=(m==null?void 0:m.height)??0,g=r+(s!=="center"?"-"+s:""),b=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},y=Array.isArray(E)?E:[E],M=y.length>0,F={padding:b,boundary:y.filter(VN),altBoundary:M},{refs:L,floatingStyles:v,placement:P,isPositioned:w,middlewareData:U}=xN({strategy:"fixed",placement:g,whileElementsMounted:(...te)=>IN(...te,{animationFrame:S==="always"}),elements:{reference:O.anchor},middleware:[DN({mainAxis:o+D,alignmentAxis:i}),c&&PN({mainAxis:!0,crossAxis:!1,limiter:u==="partial"?MN():void 0,...F}),c&&bN({...F}),vN({...F,apply:({elements:te,rects:Ee,availableWidth:fe,availableHeight:de})=>{const{width:Re,height:He}=Ee.reference,Me=te.floating.style;Me.setProperty("--radix-popper-available-width",`${fe}px`),Me.setProperty("--radix-popper-available-height",`${de}px`),Me.setProperty("--radix-popper-anchor-width",`${Re}px`),Me.setProperty("--radix-popper-anchor-height",`${He}px`)}}),h&&wN({element:h,padding:l}),jN({arrowWidth:_,arrowHeight:D}),T&&UN({strategy:"referenceHidden",...F})]}),[x,B]=FT(P),H=qt(f);Qt(()=>{w&&(H==null||H())},[w,H]);const W=(z=U.arrow)==null?void 0:z.x,$=(Y=U.arrow)==null?void 0:Y.y,X=((K=U.arrow)==null?void 0:K.centerOffset)!==0,[J,q]=R.useState();return Qt(()=>{I&&q(window.getComputedStyle(I).zIndex)},[I]),a.jsx("div",{ref:L.setFloating,"data-radix-popper-content-wrapper":"",style:{...v,transform:w?v.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:J,"--radix-popper-transform-origin":[(le=U.transformOrigin)==null?void 0:le.x,(se=U.transformOrigin)==null?void 0:se.y].join(" "),...((ne=U.hide)==null?void 0:ne.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:a.jsx(YN,{scope:n,placedSide:x,onArrowChange:C,arrowX:W,arrowY:$,shouldHideArrow:X,children:a.jsx(Ne.div,{"data-side":x,"data-align":B,...A,ref:N,style:{...A.style,animation:w?void 0:"none"}})})})});UT.displayName=Kl;var wT="PopperArrow",WN={top:"bottom",right:"left",bottom:"top",left:"right"},BT=R.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=kN(wT,r),i=WN[s.placedSide];return a.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]: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:a.jsx(FN,{...o,ref:n,style:{...o.style,display:"block"}})})});BT.displayName=wT;function VN(e){return e!==null}var jN=e=>({name:"transformOrigin",options:e,fn(t){var O,I,p;const{placement:n,rects:r,middlewareData:o}=t,i=((O=o.arrow)==null?void 0:O.centerOffset)!==0,l=i?0:e.arrowWidth,c=i?0:e.arrowHeight,[E,d]=FT(n),u={start:"0%",center:"50%",end:"100%"}[d],T=(((I=o.arrow)==null?void 0:I.x)??0)+l/2,S=(((p=o.arrow)==null?void 0:p.y)??0)+c/2;let f="",A="";return E==="bottom"?(f=i?u:`${T}px`,A=`${-c}px`):E==="top"?(f=i?u:`${T}px`,A=`${r.floating.height+c}px`):E==="right"?(f=`${-c}px`,A=i?u:`${S}px`):E==="left"&&(f=`${r.floating.width+c}px`,A=i?u:`${S}px`),{data:{x:f,y:A}}}});function FT(e){const[t,n="center"]=e.split("-");return[t,n]}var $N=MT,li=vT,zl=UT,Jl=BT,XN="Portal",io=R.forwardRef((e,t)=>{var l;const{container:n,...r}=e,[o,s]=R.useState(!1);Qt(()=>s(!0),[]);const i=n||o&&((l=globalThis==null?void 0:globalThis.document)==null?void 0:l.body);return i?AO.createPortal(a.jsx(Ne.div,{...r,ref:t}),i):null});io.displayName=XN;function KN(e,t){return R.useReducer((n,r)=>t[n][r]??n,e)}var qe=e=>{const{present:t,children:n}=e,r=zN(t),o=typeof n=="function"?n({present:r.isPresent}):R.Children.only(n),s=me(r.ref,JN(o));return typeof n=="function"||r.isPresent?R.cloneElement(o,{ref:s}):null};qe.displayName="Presence";function zN(e){const[t,n]=R.useState(),r=R.useRef(null),o=R.useRef(e),s=R.useRef("none"),i=e?"mounted":"unmounted",[l,c]=KN(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return R.useEffect(()=>{const E=jo(r.current);s.current=l==="mounted"?E:"none"},[l]),Qt(()=>{const E=r.current,d=o.current;if(d!==e){const T=s.current,S=jo(E);e?c("MOUNT"):S==="none"||(E==null?void 0:E.display)==="none"?c("UNMOUNT"):c(d&&T!==S?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),Qt(()=>{if(t){let E;const d=t.ownerDocument.defaultView??window,u=S=>{const A=jo(r.current).includes(CSS.escape(S.animationName));if(S.target===t&&A&&(c("ANIMATION_END"),!o.current)){const O=t.style.animationFillMode;t.style.animationFillMode="forwards",E=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=O)})}},T=S=>{S.target===t&&(s.current=jo(r.current))};return t.addEventListener("animationstart",T),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{d.clearTimeout(E),t.removeEventListener("animationstart",T),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:R.useCallback(E=>{r.current=E?getComputedStyle(E):null,n(E)},[])}}function jo(e){return(e==null?void 0:e.animationName)||"none"}function JN(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 qN=uT[" useInsertionEffect ".trim().toString()]||Qt;function ql({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=QN({defaultProp:t,onChange:n}),l=e!==void 0,c=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 E=R.useCallback(d=>{var u;if(l){const T=ZN(d)?d(e):d;T!==e&&((u=i.current)==null||u.call(i,T))}else s(d)},[l,e,s,i]);return[c,E]}function QN({defaultProp:e,onChange:t}){const[n,r]=R.useState(e),o=R.useRef(n),s=R.useRef(t);return qN(()=>{s.current=t},[t]),R.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function ZN(e){return typeof e=="function"}var ep=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"}),tp="VisuallyHidden",GT=R.forwardRef((e,t)=>a.jsx(Ne.span,{...e,ref:t,style:{...ep,...e.style}}));GT.displayName=tp;var np=GT,[ci]=on("Tooltip",[Sr]),Ei=Sr(),HT="TooltipProvider",rp=700,dl="tooltip.open",[op,Ql]=ci(HT),YT=e=>{const{__scopeTooltip:t,delayDuration:n=rp,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:s}=e,i=R.useRef(!0),l=R.useRef(!1),c=R.useRef(0);return R.useEffect(()=>{const E=c.current;return()=>window.clearTimeout(E)},[]),a.jsx(op,{scope:t,isOpenDelayedRef:i,delayDuration:n,onOpen:R.useCallback(()=>{window.clearTimeout(c.current),i.current=!1},[]),onClose:R.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>i.current=!0,r)},[r]),isPointerInTransitRef:l,onPointerInTransitChange:R.useCallback(E=>{l.current=E},[]),disableHoverableContent:o,children:s})};YT.displayName=HT;var Yr="Tooltip",[sp,ao]=ci(Yr),kT=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o,onOpenChange:s,disableHoverableContent:i,delayDuration:l}=e,c=Ql(Yr,e.__scopeTooltip),E=Ei(t),[d,u]=R.useState(null),T=vr(),S=R.useRef(0),f=i??c.disableHoverableContent,A=l??c.delayDuration,O=R.useRef(!1),[I,p]=ql({prop:r,defaultProp:o??!1,onChange:_=>{_?(c.onOpen(),document.dispatchEvent(new CustomEvent(dl))):c.onClose(),s==null||s(_)},caller:Yr}),N=R.useMemo(()=>I?O.current?"delayed-open":"instant-open":"closed",[I]),h=R.useCallback(()=>{window.clearTimeout(S.current),S.current=0,O.current=!1,p(!0)},[p]),C=R.useCallback(()=>{window.clearTimeout(S.current),S.current=0,p(!1)},[p]),m=R.useCallback(()=>{window.clearTimeout(S.current),S.current=window.setTimeout(()=>{O.current=!0,p(!0),S.current=0},A)},[A,p]);return R.useEffect(()=>()=>{S.current&&(window.clearTimeout(S.current),S.current=0)},[]),a.jsx($N,{...E,children:a.jsx(sp,{scope:t,contentId:T,open:I,stateAttribute:N,trigger:d,onTriggerChange:u,onTriggerEnter:R.useCallback(()=>{c.isOpenDelayedRef.current?m():h()},[c.isOpenDelayedRef,m,h]),onTriggerLeave:R.useCallback(()=>{f?C():(window.clearTimeout(S.current),S.current=0)},[C,f]),onOpen:h,onClose:C,disableHoverableContent:f,children:n})})};kT.displayName=Yr;var ul="TooltipTrigger",WT=R.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=ao(ul,n),s=Ql(ul,n),i=Ei(n),l=R.useRef(null),c=me(t,l,o.onTriggerChange),E=R.useRef(!1),d=R.useRef(!1),u=R.useCallback(()=>E.current=!1,[]);return R.useEffect(()=>()=>document.removeEventListener("pointerup",u),[u]),a.jsx(li,{asChild:!0,...i,children:a.jsx(Ne.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...r,ref:c,onPointerMove:oe(e.onPointerMove,T=>{T.pointerType!=="touch"&&!d.current&&!s.isPointerInTransitRef.current&&(o.onTriggerEnter(),d.current=!0)}),onPointerLeave:oe(e.onPointerLeave,()=>{o.onTriggerLeave(),d.current=!1}),onPointerDown:oe(e.onPointerDown,()=>{o.open&&o.onClose(),E.current=!0,document.addEventListener("pointerup",u,{once:!0})}),onFocus:oe(e.onFocus,()=>{E.current||o.onOpen()}),onBlur:oe(e.onBlur,o.onClose),onClick:oe(e.onClick,o.onClose)})})});WT.displayName=ul;var Zl="TooltipPortal",[ip,ap]=ci(Zl,{forceMount:void 0}),VT=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:o}=e,s=ao(Zl,t);return a.jsx(ip,{scope:t,forceMount:n,children:a.jsx(qe,{present:n||s.open,children:a.jsx(io,{asChild:!0,container:o,children:r})})})};VT.displayName=Zl;var er="TooltipContent",jT=R.forwardRef((e,t)=>{const n=ap(er,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...s}=e,i=ao(er,e.__scopeTooltip);return a.jsx(qe,{present:r||i.open,children:i.disableHoverableContent?a.jsx($T,{side:o,...s,ref:t}):a.jsx(lp,{side:o,...s,ref:t})})}),lp=R.forwardRef((e,t)=>{const n=ao(er,e.__scopeTooltip),r=Ql(er,e.__scopeTooltip),o=R.useRef(null),s=me(t,o),[i,l]=R.useState(null),{trigger:c,onClose:E}=n,d=o.current,{onPointerInTransitChange:u}=r,T=R.useCallback(()=>{l(null),u(!1)},[u]),S=R.useCallback((f,A)=>{const O=f.currentTarget,I={x:f.clientX,y:f.clientY},p=Tp(I,O.getBoundingClientRect()),N=Sp(I,p),h=Rp(A.getBoundingClientRect()),C=fp([...N,...h]);l(C),u(!0)},[u]);return R.useEffect(()=>()=>T(),[T]),R.useEffect(()=>{if(c&&d){const f=O=>S(O,d),A=O=>S(O,c);return c.addEventListener("pointerleave",f),d.addEventListener("pointerleave",A),()=>{c.removeEventListener("pointerleave",f),d.removeEventListener("pointerleave",A)}}},[c,d,S,T]),R.useEffect(()=>{if(i){const f=A=>{const O=A.target,I={x:A.clientX,y:A.clientY},p=(c==null?void 0:c.contains(O))||(d==null?void 0:d.contains(O)),N=!Ap(I,i);p?T():N&&(T(),E())};return document.addEventListener("pointermove",f),()=>document.removeEventListener("pointermove",f)}},[c,d,i,E,T]),a.jsx($T,{...e,ref:s})}),[cp,Ep]=ci(Yr,{isInside:!1}),dp=IO("TooltipContent"),$T=R.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:s,onPointerDownOutside:i,...l}=e,c=ao(er,n),E=Ei(n),{onClose:d}=c;return R.useEffect(()=>(document.addEventListener(dl,d),()=>document.removeEventListener(dl,d)),[d]),R.useEffect(()=>{if(c.trigger){const u=T=>{const S=T.target;S!=null&&S.contains(c.trigger)&&d()};return window.addEventListener("scroll",u,{capture:!0}),()=>window.removeEventListener("scroll",u,{capture:!0})}},[c.trigger,d]),a.jsx(oo,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:u=>u.preventDefault(),onDismiss:d,children:a.jsxs(zl,{"data-state":c.stateAttribute,...E,...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:[a.jsx(dp,{children:r}),a.jsx(cp,{scope:n,isInside:!0,children:a.jsx(np,{id:c.contentId,role:"tooltip",children:o||r})})]})})});jT.displayName=er;var XT="TooltipArrow",up=R.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Ei(n);return Ep(XT,n).isInside?null:a.jsx(Jl,{...o,...r,ref:t})});up.displayName=XT;function Tp(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 Sp(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 Rp(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 Ap(e,t){const{x:n,y:r}=e;let o=!1;for(let s=0,i=t.length-1;s<t.length;i=s++){const l=t[s],c=t[i],E=l.x,d=l.y,u=c.x,T=c.y;d>r!=T>r&&n<(u-E)*(r-d)/(T-d)+E&&(o=!o)}return o}function fp(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),Ip(t)}function Ip(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],i=t[t.length-2];if((s.x-i.x)*(o.y-i.y)>=(s.y-i.y)*(o.x-i.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],i=n[n.length-2];if((s.x-i.x)*(o.y-i.y)>=(s.y-i.y)*(o.x-i.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 Op=YT,Np=kT,pp=WT,hp=VT,Cp=jT;function mp({content:e,children:t,side:n="right",align:r="center",sideOffset:o=6,delayMs:s=200,container:i}){return a.jsxs(Np,{delayDuration:s,children:[a.jsx(pp,{asChild:!0,children:t}),a.jsx(hp,{container:i,children:a.jsx(Cp,{side:n,align:r,sideOffset:o,style:{background:ue("surfaceElevated"),color:ue("textPrimary"),border:`1px solid ${ue("borderDefault")}`,borderRadius:Cn.sm,padding:`${Ie[1]} ${Ie[2]}`,fontSize:ve.sm,boxShadow:ue("shadowMd"),zIndex:Gr.tooltip,userSelect:"none"},children:e})})]})}const Lp=Op;var Zi="focusScope.autoFocusOnMount",ea="focusScope.autoFocusOnUnmount",RE={bubbles:!1,cancelable:!0},_p="FocusScope",di=R.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[l,c]=R.useState(null),E=qt(o),d=qt(s),u=R.useRef(null),T=me(t,A=>c(A)),S=R.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;R.useEffect(()=>{if(r){let A=function(N){if(S.paused||!l)return;const h=N.target;l.contains(h)?u.current=h:jt(u.current,{select:!0})},O=function(N){if(S.paused||!l)return;const h=N.relatedTarget;h!==null&&(l.contains(h)||jt(u.current,{select:!0}))},I=function(N){if(document.activeElement===document.body)for(const C of N)C.removedNodes.length>0&&jt(l)};document.addEventListener("focusin",A),document.addEventListener("focusout",O);const p=new MutationObserver(I);return l&&p.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",A),document.removeEventListener("focusout",O),p.disconnect()}}},[r,l,S.paused]),R.useEffect(()=>{if(l){fE.add(S);const A=document.activeElement;if(!l.contains(A)){const I=new CustomEvent(Zi,RE);l.addEventListener(Zi,E),l.dispatchEvent(I),I.defaultPrevented||(gp(Mp(KT(l)),{select:!0}),document.activeElement===A&&jt(l))}return()=>{l.removeEventListener(Zi,E),setTimeout(()=>{const I=new CustomEvent(ea,RE);l.addEventListener(ea,d),l.dispatchEvent(I),I.defaultPrevented||jt(A??document.body,{select:!0}),l.removeEventListener(ea,d),fE.remove(S)},0)}}},[l,E,d,S]);const f=R.useCallback(A=>{if(!n&&!r||S.paused)return;const O=A.key==="Tab"&&!A.altKey&&!A.ctrlKey&&!A.metaKey,I=document.activeElement;if(O&&I){const p=A.currentTarget,[N,h]=xp(p);N&&h?!A.shiftKey&&I===h?(A.preventDefault(),n&&jt(N,{select:!0})):A.shiftKey&&I===N&&(A.preventDefault(),n&&jt(h,{select:!0})):I===p&&A.preventDefault()}},[n,r,S.paused]);return a.jsx(Ne.div,{tabIndex:-1,...i,ref:T,onKeyDown:f})});di.displayName=_p;function gp(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(jt(r,{select:t}),document.activeElement!==n)return}function xp(e){const t=KT(e),n=AE(t,e),r=AE(t.reverse(),e);return[n,r]}function KT(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 AE(e,t){for(const n of e)if(!yp(n,{upTo:t}))return n}function yp(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 Dp(e){return e instanceof HTMLInputElement&&"select"in e}function jt(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Dp(e)&&t&&e.select()}}var fE=Pp();function Pp(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=IE(e,t),e.unshift(t)},remove(t){var n;e=IE(e,t),(n=e[0])==null||n.resume()}}}function IE(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Mp(e){return e.filter(t=>t.tagName!=="A")}var ta=0;function ec(){R.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??OE()),document.body.insertAdjacentElement("beforeend",e[1]??OE()),ta++,()=>{ta===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),ta--}},[])}function OE(){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 zT(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 bp(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 us="right-scroll-bar-position",Ts="width-before-scroll-bar",vp="with-scroll-bars-hidden",Up="--removed-body-scroll-bar-size";function na(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function wp(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 Bp=typeof window<"u"?R.useLayoutEffect:R.useEffect,NE=new WeakMap;function Fp(e,t){var n=wp(null,function(r){return e.forEach(function(o){return na(o,r)})});return Bp(function(){var r=NE.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(l){s.has(l)||na(l,null)}),s.forEach(function(l){o.has(l)||na(l,i)})}NE.set(n,e)},[e]),n}function Gp(e){return e}function Hp(e,t){t===void 0&&(t=Gp);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 i=t(s,r);return n.push(i),function(){n=n.filter(function(l){return l!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(l){return s(l)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var l=n;n=[],l.forEach(s),i=n}var c=function(){var d=i;i=[],d.forEach(s)},E=function(){return Promise.resolve().then(c)};E(),n={push:function(d){i.push(d),E()},filter:function(d){return i=i.filter(d),n}}}};return o}function Yp(e){e===void 0&&(e={});var t=Hp(null);return t.options=Rt({async:!0,ssr:!1},e),t}var JT=function(e){var t=e.sideCar,n=zT(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))};JT.isSideCarExport=!0;function kp(e,t){return e.useMedium(t),JT}var qT=Yp(),ra=function(){},ui=R.forwardRef(function(e,t){var n=R.useRef(null),r=R.useState({onScrollCapture:ra,onWheelCapture:ra,onTouchMoveCapture:ra}),o=r[0],s=r[1],i=e.forwardProps,l=e.children,c=e.className,E=e.removeScrollBar,d=e.enabled,u=e.shards,T=e.sideCar,S=e.noRelative,f=e.noIsolation,A=e.inert,O=e.allowPinchZoom,I=e.as,p=I===void 0?"div":I,N=e.gapMode,h=zT(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=T,m=Fp([n,t]),_=Rt(Rt({},h),o);return R.createElement(R.Fragment,null,d&&R.createElement(C,{sideCar:qT,removeScrollBar:E,shards:u,noRelative:S,noIsolation:f,inert:A,setCallbacks:s,allowPinchZoom:!!O,lockRef:n,gapMode:N}),i?R.cloneElement(R.Children.only(l),Rt(Rt({},_),{ref:m})):R.createElement(p,Rt({},_,{className:c,ref:m}),l))});ui.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};ui.classNames={fullWidth:Ts,zeroRight:us};var Wp=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Vp(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Wp();return t&&e.setAttribute("nonce",t),e}function jp(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function $p(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Xp=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Vp())&&(jp(t,n),$p(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Kp=function(){var e=Xp();return function(t,n){R.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},QT=function(){var e=Kp(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},zp={left:0,top:0,right:0,gap:0},oa=function(e){return parseInt(e||"",10)||0},Jp=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[oa(n),oa(r),oa(o)]},qp=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return zp;var t=Jp(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])}},Qp=QT(),Xn="data-scroll-locked",Zp=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,l=e.gap;return n===void 0&&(n="margin"),`
|
|
10
|
+
.`.concat(vp,` {
|
|
11
|
+
overflow: hidden `).concat(r,`;
|
|
12
|
+
padding-right: `).concat(l,"px ").concat(r,`;
|
|
13
|
+
}
|
|
14
|
+
body[`).concat(Xn,`] {
|
|
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(i,`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(us,` {
|
|
28
|
+
right: `).concat(l,"px ").concat(r,`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
.`).concat(Ts,` {
|
|
32
|
+
margin-right: `).concat(l,"px ").concat(r,`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
.`).concat(us," .").concat(us,` {
|
|
36
|
+
right: 0 `).concat(r,`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
.`).concat(Ts," .").concat(Ts,` {
|
|
40
|
+
margin-right: 0 `).concat(r,`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
body[`).concat(Xn,`] {
|
|
44
|
+
`).concat(Up,": ").concat(l,`px;
|
|
45
|
+
}
|
|
46
|
+
`)},pE=function(){var e=parseInt(document.body.getAttribute(Xn)||"0",10);return isFinite(e)?e:0},eh=function(){R.useEffect(function(){return document.body.setAttribute(Xn,(pE()+1).toString()),function(){var e=pE()-1;e<=0?document.body.removeAttribute(Xn):document.body.setAttribute(Xn,e.toString())}},[])},th=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;eh();var s=R.useMemo(function(){return qp(o)},[o]);return R.createElement(Qp,{styles:Zp(s,!t,o,n?"":"!important")})},Tl=!1;if(typeof window<"u")try{var $o=Object.defineProperty({},"passive",{get:function(){return Tl=!0,!0}});window.addEventListener("test",$o,$o),window.removeEventListener("test",$o,$o)}catch{Tl=!1}var vn=Tl?{passive:!1}:!1,nh=function(e){return e.tagName==="TEXTAREA"},ZT=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!nh(e)&&n[t]==="visible")},rh=function(e){return ZT(e,"overflowY")},oh=function(e){return ZT(e,"overflowX")},hE=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=eS(e,r);if(o){var s=tS(e,r),i=s[1],l=s[2];if(i>l)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},sh=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},ih=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},eS=function(e,t){return e==="v"?rh(t):oh(t)},tS=function(e,t){return e==="v"?sh(t):ih(t)},ah=function(e,t){return e==="h"&&t==="rtl"?-1:1},lh=function(e,t,n,r,o){var s=ah(e,window.getComputedStyle(t).direction),i=s*r,l=n.target,c=t.contains(l),E=!1,d=i>0,u=0,T=0;do{if(!l)break;var S=tS(e,l),f=S[0],A=S[1],O=S[2],I=A-O-s*f;(f||I)&&eS(e,l)&&(u+=I,T+=f);var p=l.parentNode;l=p&&p.nodeType===Node.DOCUMENT_FRAGMENT_NODE?p.host:p}while(!c&&l!==document.body||c&&(t.contains(l)||t===l));return(d&&Math.abs(u)<1||!d&&Math.abs(T)<1)&&(E=!0),E},Xo=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},CE=function(e){return[e.deltaX,e.deltaY]},mE=function(e){return e&&"current"in e?e.current:e},ch=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Eh=function(e){return`
|
|
47
|
+
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
48
|
+
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
49
|
+
`)},dh=0,Un=[];function uh(e){var t=R.useRef([]),n=R.useRef([0,0]),r=R.useRef(),o=R.useState(dh++)[0],s=R.useState(QT)[0],i=R.useRef(e);R.useEffect(function(){i.current=e},[e]),R.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var A=bp([e.lockRef.current],(e.shards||[]).map(mE),!0).filter(Boolean);return A.forEach(function(O){return O.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),A.forEach(function(O){return O.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=R.useCallback(function(A,O){if("touches"in A&&A.touches.length===2||A.type==="wheel"&&A.ctrlKey)return!i.current.allowPinchZoom;var I=Xo(A),p=n.current,N="deltaX"in A?A.deltaX:p[0]-I[0],h="deltaY"in A?A.deltaY:p[1]-I[1],C,m=A.target,_=Math.abs(N)>Math.abs(h)?"h":"v";if("touches"in A&&_==="h"&&m.type==="range")return!1;var D=window.getSelection(),g=D&&D.anchorNode,b=g?g===m||g.contains(m):!1;if(b)return!1;var y=hE(_,m);if(!y)return!0;if(y?C=_:(C=_==="v"?"h":"v",y=hE(_,m)),!y)return!1;if(!r.current&&"changedTouches"in A&&(N||h)&&(r.current=C),!C)return!0;var M=r.current||C;return lh(M,O,A,M==="h"?N:h)},[]),c=R.useCallback(function(A){var O=A;if(!(!Un.length||Un[Un.length-1]!==s)){var I="deltaY"in O?CE(O):Xo(O),p=t.current.filter(function(C){return C.name===O.type&&(C.target===O.target||O.target===C.shadowParent)&&ch(C.delta,I)})[0];if(p&&p.should){O.cancelable&&O.preventDefault();return}if(!p){var N=(i.current.shards||[]).map(mE).filter(Boolean).filter(function(C){return C.contains(O.target)}),h=N.length>0?l(O,N[0]):!i.current.noIsolation;h&&O.cancelable&&O.preventDefault()}}},[]),E=R.useCallback(function(A,O,I,p){var N={name:A,delta:O,target:I,should:p,shadowParent:Th(I)};t.current.push(N),setTimeout(function(){t.current=t.current.filter(function(h){return h!==N})},1)},[]),d=R.useCallback(function(A){n.current=Xo(A),r.current=void 0},[]),u=R.useCallback(function(A){E(A.type,CE(A),A.target,l(A,e.lockRef.current))},[]),T=R.useCallback(function(A){E(A.type,Xo(A),A.target,l(A,e.lockRef.current))},[]);R.useEffect(function(){return Un.push(s),e.setCallbacks({onScrollCapture:u,onWheelCapture:u,onTouchMoveCapture:T}),document.addEventListener("wheel",c,vn),document.addEventListener("touchmove",c,vn),document.addEventListener("touchstart",d,vn),function(){Un=Un.filter(function(A){return A!==s}),document.removeEventListener("wheel",c,vn),document.removeEventListener("touchmove",c,vn),document.removeEventListener("touchstart",d,vn)}},[]);var S=e.removeScrollBar,f=e.inert;return R.createElement(R.Fragment,null,f?R.createElement(s,{styles:Eh(o)}):null,S?R.createElement(th,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Th(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Sh=kp(qT,uh);var Ti=R.forwardRef(function(e,t){return R.createElement(ui,Rt({},e,{ref:t,sideCar:Sh}))});Ti.classNames=ui.classNames;var Rh=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},wn=new WeakMap,Ko=new WeakMap,zo={},sa=0,nS=function(e){return e&&(e.host||nS(e.parentNode))},Ah=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=nS(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})},fh=function(e,t,n,r){var o=Ah(t,Array.isArray(e)?e:[e]);zo[n]||(zo[n]=new WeakMap);var s=zo[n],i=[],l=new Set,c=new Set(o),E=function(u){!u||l.has(u)||(l.add(u),E(u.parentNode))};o.forEach(E);var d=function(u){!u||c.has(u)||Array.prototype.forEach.call(u.children,function(T){if(l.has(T))d(T);else try{var S=T.getAttribute(r),f=S!==null&&S!=="false",A=(wn.get(T)||0)+1,O=(s.get(T)||0)+1;wn.set(T,A),s.set(T,O),i.push(T),A===1&&f&&Ko.set(T,!0),O===1&&T.setAttribute(n,"true"),f||T.setAttribute(r,"true")}catch(I){console.error("aria-hidden: cannot operate on ",T,I)}})};return d(t),l.clear(),sa++,function(){i.forEach(function(u){var T=wn.get(u)-1,S=s.get(u)-1;wn.set(u,T),s.set(u,S),T||(Ko.has(u)||u.removeAttribute(r),Ko.delete(u)),S||u.removeAttribute(n)}),sa--,sa||(wn=new WeakMap,wn=new WeakMap,Ko=new WeakMap,zo={})}},tc=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=Rh(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),fh(r,o,n,"aria-hidden")):function(){return null}},Si="Dialog",[rS]=on(Si),[Ih,ct]=rS(Si),oS=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:s,modal:i=!0}=e,l=R.useRef(null),c=R.useRef(null),[E,d]=ql({prop:r,defaultProp:o??!1,onChange:s,caller:Si});return a.jsx(Ih,{scope:t,triggerRef:l,contentRef:c,contentId:vr(),titleId:vr(),descriptionId:vr(),open:E,onOpenChange:d,onOpenToggle:R.useCallback(()=>d(u=>!u),[d]),modal:i,children:n})};oS.displayName=Si;var sS="DialogTrigger",Oh=R.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ct(sS,n),s=me(t,o.triggerRef);return a.jsx(Ne.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":oc(o.open),...r,ref:s,onClick:oe(e.onClick,o.onOpenToggle)})});Oh.displayName=sS;var nc="DialogPortal",[Nh,iS]=rS(nc,{forceMount:void 0}),aS=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,s=ct(nc,t);return a.jsx(Nh,{scope:t,forceMount:n,children:R.Children.map(r,i=>a.jsx(qe,{present:n||s.open,children:a.jsx(io,{asChild:!0,container:o,children:i})}))})};aS.displayName=nc;var xs="DialogOverlay",lS=R.forwardRef((e,t)=>{const n=iS(xs,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=ct(xs,e.__scopeDialog);return s.modal?a.jsx(qe,{present:r||s.open,children:a.jsx(hh,{...o,ref:t})}):null});lS.displayName=xs;var ph=Qn("DialogOverlay.RemoveScroll"),hh=R.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ct(xs,n);return a.jsx(Ti,{as:ph,allowPinchZoom:!0,shards:[o.contentRef],children:a.jsx(Ne.div,{"data-state":oc(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),fn="DialogContent",cS=R.forwardRef((e,t)=>{const n=iS(fn,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,s=ct(fn,e.__scopeDialog);return a.jsx(qe,{present:r||s.open,children:s.modal?a.jsx(Ch,{...o,ref:t}):a.jsx(mh,{...o,ref:t})})});cS.displayName=fn;var Ch=R.forwardRef((e,t)=>{const n=ct(fn,e.__scopeDialog),r=R.useRef(null),o=me(t,n.contentRef,r);return R.useEffect(()=>{const s=r.current;if(s)return tc(s)},[]),a.jsx(ES,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:oe(e.onCloseAutoFocus,s=>{var i;s.preventDefault(),(i=n.triggerRef.current)==null||i.focus()}),onPointerDownOutside:oe(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,l=i.button===0&&i.ctrlKey===!0;(i.button===2||l)&&s.preventDefault()}),onFocusOutside:oe(e.onFocusOutside,s=>s.preventDefault())})}),mh=R.forwardRef((e,t)=>{const n=ct(fn,e.__scopeDialog),r=R.useRef(!1),o=R.useRef(!1);return a.jsx(ES,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var i,l;(i=e.onCloseAutoFocus)==null||i.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 c,E;(c=e.onInteractOutside)==null||c.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;((E=n.triggerRef.current)==null?void 0:E.contains(i))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),ES=R.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,...i}=e,l=ct(fn,n),c=R.useRef(null),E=me(t,c);return ec(),a.jsxs(a.Fragment,{children:[a.jsx(di,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:a.jsx(oo,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":oc(l.open),...i,ref:E,onDismiss:()=>l.onOpenChange(!1)})}),a.jsxs(a.Fragment,{children:[a.jsx(gh,{titleId:l.titleId}),a.jsx(yh,{contentRef:c,descriptionId:l.descriptionId})]})]})}),rc="DialogTitle",dS=R.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ct(rc,n);return a.jsx(Ne.h2,{id:o.titleId,...r,ref:t})});dS.displayName=rc;var uS="DialogDescription",Lh=R.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ct(uS,n);return a.jsx(Ne.p,{id:o.descriptionId,...r,ref:t})});Lh.displayName=uS;var TS="DialogClose",_h=R.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ct(TS,n);return a.jsx(Ne.button,{type:"button",...r,ref:t,onClick:oe(e.onClick,()=>o.onOpenChange(!1))})});_h.displayName=TS;function oc(e){return e?"open":"closed"}var SS="DialogTitleWarning",[f2,RS]=SO(SS,{contentName:fn,titleName:rc,docsSlug:"dialog"}),gh=({titleId:e})=>{const t=RS(SS),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},xh="DialogDescriptionWarning",yh=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${RS(xh).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},Dh=oS,Ph=aS,Mh=lS,bh=cS,vh=dS;function AS(e){const t=e+"CollectionProvider",[n,r]=on(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=A=>{const{scope:O,children:I}=A,p=Ce.useRef(null),N=Ce.useRef(new Map).current;return a.jsx(o,{scope:O,itemMap:N,collectionRef:p,children:I})};i.displayName=t;const l=e+"CollectionSlot",c=Qn(l),E=Ce.forwardRef((A,O)=>{const{scope:I,children:p}=A,N=s(l,I),h=me(O,N.collectionRef);return a.jsx(c,{ref:h,children:p})});E.displayName=l;const d=e+"CollectionItemSlot",u="data-radix-collection-item",T=Qn(d),S=Ce.forwardRef((A,O)=>{const{scope:I,children:p,...N}=A,h=Ce.useRef(null),C=me(O,h),m=s(d,I);return Ce.useEffect(()=>(m.itemMap.set(h,{ref:h,...N}),()=>void m.itemMap.delete(h))),a.jsx(T,{[u]:"",ref:C,children:p})});S.displayName=d;function f(A){const O=s(e+"CollectionConsumer",A);return Ce.useCallback(()=>{const p=O.collectionRef.current;if(!p)return[];const N=Array.from(p.querySelectorAll(`[${u}]`));return Array.from(O.itemMap.values()).sort((m,_)=>N.indexOf(m.ref.current)-N.indexOf(_.ref.current))},[O.collectionRef,O.itemMap])}return[{Provider:i,Slot:E,ItemSlot:S},f,r]}var Uh=R.createContext(void 0);function wh(e){const t=R.useContext(Uh);return e||t||"ltr"}var ia="rovingFocusGroup.onEntryFocus",Bh={bubbles:!1,cancelable:!0},lo="RovingFocusGroup",[Sl,fS,Fh]=AS(lo),[Gh,IS]=on(lo,[Fh]),[Hh,Yh]=Gh(lo),OS=R.forwardRef((e,t)=>a.jsx(Sl.Provider,{scope:e.__scopeRovingFocusGroup,children:a.jsx(Sl.Slot,{scope:e.__scopeRovingFocusGroup,children:a.jsx(kh,{...e,ref:t})})}));OS.displayName=lo;var kh=R.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:c,onEntryFocus:E,preventScrollOnEntryFocus:d=!1,...u}=e,T=R.useRef(null),S=me(t,T),f=wh(s),[A,O]=ql({prop:i,defaultProp:l??null,onChange:c,caller:lo}),[I,p]=R.useState(!1),N=qt(E),h=fS(n),C=R.useRef(!1),[m,_]=R.useState(0);return R.useEffect(()=>{const D=T.current;if(D)return D.addEventListener(ia,N),()=>D.removeEventListener(ia,N)},[N]),a.jsx(Hh,{scope:n,orientation:r,dir:f,loop:o,currentTabStopId:A,onItemFocus:R.useCallback(D=>O(D),[O]),onItemShiftTab:R.useCallback(()=>p(!0),[]),onFocusableItemAdd:R.useCallback(()=>_(D=>D+1),[]),onFocusableItemRemove:R.useCallback(()=>_(D=>D-1),[]),children:a.jsx(Ne.div,{tabIndex:I||m===0?-1:0,"data-orientation":r,...u,ref:S,style:{outline:"none",...e.style},onMouseDown:oe(e.onMouseDown,()=>{C.current=!0}),onFocus:oe(e.onFocus,D=>{const g=!C.current;if(D.target===D.currentTarget&&g&&!I){const b=new CustomEvent(ia,Bh);if(D.currentTarget.dispatchEvent(b),!b.defaultPrevented){const y=h().filter(P=>P.focusable),M=y.find(P=>P.active),F=y.find(P=>P.id===A),v=[M,F,...y].filter(Boolean).map(P=>P.ref.current);hS(v,d)}}C.current=!1}),onBlur:oe(e.onBlur,()=>p(!1))})})}),NS="RovingFocusGroupItem",pS=R.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...l}=e,c=vr(),E=s||c,d=Yh(NS,n),u=d.currentTabStopId===E,T=fS(n),{onFocusableItemAdd:S,onFocusableItemRemove:f,currentTabStopId:A}=d;return R.useEffect(()=>{if(r)return S(),()=>f()},[r,S,f]),a.jsx(Sl.ItemSlot,{scope:n,id:E,focusable:r,active:o,children:a.jsx(Ne.span,{tabIndex:u?0:-1,"data-orientation":d.orientation,...l,ref:t,onMouseDown:oe(e.onMouseDown,O=>{r?d.onItemFocus(E):O.preventDefault()}),onFocus:oe(e.onFocus,()=>d.onItemFocus(E)),onKeyDown:oe(e.onKeyDown,O=>{if(O.key==="Tab"&&O.shiftKey){d.onItemShiftTab();return}if(O.target!==O.currentTarget)return;const I=jh(O,d.orientation,d.dir);if(I!==void 0){if(O.metaKey||O.ctrlKey||O.altKey||O.shiftKey)return;O.preventDefault();let N=T().filter(h=>h.focusable).map(h=>h.ref.current);if(I==="last")N.reverse();else if(I==="prev"||I==="next"){I==="prev"&&N.reverse();const h=N.indexOf(O.currentTarget);N=d.loop?$h(N,h+1):N.slice(h+1)}setTimeout(()=>hS(N))}}),children:typeof i=="function"?i({isCurrentTabStop:u,hasTabStop:A!=null}):i})})});pS.displayName=NS;var Wh={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Vh(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function jh(e,t,n){const r=Vh(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Wh[r]}function hS(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function $h(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Xh=OS,Kh=pS,Rl=["Enter"," "],zh=["ArrowDown","PageUp","Home"],CS=["ArrowUp","PageDown","End"],Jh=[...zh,...CS],qh={ltr:[...Rl,"ArrowRight"],rtl:[...Rl,"ArrowLeft"]},Qh={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Ri="Menu",[kr,Zh,eC]=AS(Ri),[mn,mS]=on(Ri,[eC,Sr,IS]),sc=Sr(),LS=IS(),[I2,Ln]=mn(Ri),[O2,co]=mn(Ri),tC="MenuAnchor",ic=R.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=sc(n);return a.jsx(li,{...o,...r,ref:t})});ic.displayName=tC;var ac="MenuPortal",[nC,_S]=mn(ac,{forceMount:void 0}),gS=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,s=Ln(ac,t);return a.jsx(nC,{scope:t,forceMount:n,children:a.jsx(qe,{present:n||s.open,children:a.jsx(io,{asChild:!0,container:o,children:r})})})};gS.displayName=ac;var Je="MenuContent",[rC,lc]=mn(Je),xS=R.forwardRef((e,t)=>{const n=_S(Je,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Ln(Je,e.__scopeMenu),i=co(Je,e.__scopeMenu);return a.jsx(kr.Provider,{scope:e.__scopeMenu,children:a.jsx(qe,{present:r||s.open,children:a.jsx(kr.Slot,{scope:e.__scopeMenu,children:i.modal?a.jsx(oC,{...o,ref:t}):a.jsx(sC,{...o,ref:t})})})})}),oC=R.forwardRef((e,t)=>{const n=Ln(Je,e.__scopeMenu),r=R.useRef(null),o=me(t,r);return R.useEffect(()=>{const s=r.current;if(s)return tc(s)},[]),a.jsx(cc,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:oe(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),sC=R.forwardRef((e,t)=>{const n=Ln(Je,e.__scopeMenu);return a.jsx(cc,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),iC=Qn("MenuContent.ScrollLock"),cc=R.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEntryFocus:c,onEscapeKeyDown:E,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:T,onDismiss:S,disableOutsideScroll:f,...A}=e,O=Ln(Je,n),I=co(Je,n),p=sc(n),N=LS(n),h=Zh(n),[C,m]=R.useState(null),_=R.useRef(null),D=me(t,_,O.onContentChange),g=R.useRef(0),b=R.useRef(""),y=R.useRef(0),M=R.useRef(null),F=R.useRef("right"),L=R.useRef(0),v=f?Ti:R.Fragment,P=f?{as:iC,allowPinchZoom:!0}:void 0,w=x=>{var z,Y;const B=b.current+x,H=h().filter(K=>!K.disabled),W=document.activeElement,$=(z=H.find(K=>K.ref.current===W))==null?void 0:z.textValue,X=H.map(K=>K.textValue),J=IC(X,B,$),q=(Y=H.find(K=>K.textValue===J))==null?void 0:Y.ref.current;(function K(le){b.current=le,window.clearTimeout(g.current),le!==""&&(g.current=window.setTimeout(()=>K(""),1e3))})(B),q&&setTimeout(()=>q.focus())};R.useEffect(()=>()=>window.clearTimeout(g.current),[]),ec();const U=R.useCallback(x=>{var H,W;return F.current===((H=M.current)==null?void 0:H.side)&&NC(x,(W=M.current)==null?void 0:W.area)},[]);return a.jsx(rC,{scope:n,searchRef:b,onItemEnter:R.useCallback(x=>{U(x)&&x.preventDefault()},[U]),onItemLeave:R.useCallback(x=>{var B;U(x)||((B=_.current)==null||B.focus(),m(null))},[U]),onTriggerLeave:R.useCallback(x=>{U(x)&&x.preventDefault()},[U]),pointerGraceTimerRef:y,onPointerGraceIntentChange:R.useCallback(x=>{M.current=x},[]),children:a.jsx(v,{...P,children:a.jsx(di,{asChild:!0,trapped:o,onMountAutoFocus:oe(s,x=>{var B;x.preventDefault(),(B=_.current)==null||B.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:a.jsx(oo,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:E,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:T,onDismiss:S,children:a.jsx(Xh,{asChild:!0,...N,dir:I.dir,orientation:"vertical",loop:r,currentTabStopId:C,onCurrentTabStopIdChange:m,onEntryFocus:oe(c,x=>{I.isUsingKeyboardRef.current||x.preventDefault()}),preventScrollOnEntryFocus:!0,children:a.jsx(zl,{role:"menu","aria-orientation":"vertical","data-state":VS(O.open),"data-radix-menu-content":"",dir:I.dir,...p,...A,ref:D,style:{outline:"none",...A.style},onKeyDown:oe(A.onKeyDown,x=>{const H=x.target.closest("[data-radix-menu-content]")===x.currentTarget,W=x.ctrlKey||x.altKey||x.metaKey,$=x.key.length===1;H&&(x.key==="Tab"&&x.preventDefault(),!W&&$&&w(x.key));const X=_.current;if(x.target!==X||!Jh.includes(x.key))return;x.preventDefault();const q=h().filter(z=>!z.disabled).map(z=>z.ref.current);CS.includes(x.key)&&q.reverse(),AC(q)}),onBlur:oe(e.onBlur,x=>{x.currentTarget.contains(x.target)||(window.clearTimeout(g.current),b.current="")}),onPointerMove:oe(e.onPointerMove,Wr(x=>{const B=x.target,H=L.current!==x.clientX;if(x.currentTarget.contains(B)&&H){const W=x.clientX>L.current?"right":"left";F.current=W,L.current=x.clientX}}))})})})})})})});xS.displayName=Je;var aC="MenuGroup",Ec=R.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return a.jsx(Ne.div,{role:"group",...r,ref:t})});Ec.displayName=aC;var lC="MenuLabel",yS=R.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return a.jsx(Ne.div,{...r,ref:t})});yS.displayName=lC;var ys="MenuItem",LE="menu.itemSelect",Ai=R.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,s=R.useRef(null),i=co(ys,e.__scopeMenu),l=lc(ys,e.__scopeMenu),c=me(t,s),E=R.useRef(!1),d=()=>{const u=s.current;if(!n&&u){const T=new CustomEvent(LE,{bubbles:!0,cancelable:!0});u.addEventListener(LE,S=>r==null?void 0:r(S),{once:!0}),RT(u,T),T.defaultPrevented?E.current=!1:i.onClose()}};return a.jsx(DS,{...o,ref:c,disabled:n,onClick:oe(e.onClick,d),onPointerDown:u=>{var T;(T=e.onPointerDown)==null||T.call(e,u),E.current=!0},onPointerUp:oe(e.onPointerUp,u=>{var T;E.current||(T=u.currentTarget)==null||T.click()}),onKeyDown:oe(e.onKeyDown,u=>{const T=l.searchRef.current!=="";n||T&&u.key===" "||Rl.includes(u.key)&&(u.currentTarget.click(),u.preventDefault())})})});Ai.displayName=ys;var DS=R.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...s}=e,i=lc(ys,n),l=LS(n),c=R.useRef(null),E=me(t,c),[d,u]=R.useState(!1),[T,S]=R.useState("");return R.useEffect(()=>{const f=c.current;f&&S((f.textContent??"").trim())},[s.children]),a.jsx(kr.ItemSlot,{scope:n,disabled:r,textValue:o??T,children:a.jsx(Kh,{asChild:!0,...l,focusable:!r,children:a.jsx(Ne.div,{role:"menuitem","data-highlighted":d?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:E,onPointerMove:oe(e.onPointerMove,Wr(f=>{r?i.onItemLeave(f):(i.onItemEnter(f),f.defaultPrevented||f.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:oe(e.onPointerLeave,Wr(f=>i.onItemLeave(f))),onFocus:oe(e.onFocus,()=>u(!0)),onBlur:oe(e.onBlur,()=>u(!1))})})})}),cC="MenuCheckboxItem",PS=R.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return a.jsx(wS,{scope:e.__scopeMenu,checked:n,children:a.jsx(Ai,{role:"menuitemcheckbox","aria-checked":Ds(n)?"mixed":n,...o,ref:t,"data-state":uc(n),onSelect:oe(o.onSelect,()=>r==null?void 0:r(Ds(n)?!0:!n),{checkForDefaultPrevented:!1})})})});PS.displayName=cC;var MS="MenuRadioGroup",[EC,dC]=mn(MS,{value:void 0,onValueChange:()=>{}}),bS=R.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,s=qt(r);return a.jsx(EC,{scope:e.__scopeMenu,value:n,onValueChange:s,children:a.jsx(Ec,{...o,ref:t})})});bS.displayName=MS;var vS="MenuRadioItem",US=R.forwardRef((e,t)=>{const{value:n,...r}=e,o=dC(vS,e.__scopeMenu),s=n===o.value;return a.jsx(wS,{scope:e.__scopeMenu,checked:s,children:a.jsx(Ai,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":uc(s),onSelect:oe(r.onSelect,()=>{var i;return(i=o.onValueChange)==null?void 0:i.call(o,n)},{checkForDefaultPrevented:!1})})})});US.displayName=vS;var dc="MenuItemIndicator",[wS,uC]=mn(dc,{checked:!1}),BS=R.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,s=uC(dc,n);return a.jsx(qe,{present:r||Ds(s.checked)||s.checked===!0,children:a.jsx(Ne.span,{...o,ref:t,"data-state":uc(s.checked)})})});BS.displayName=dc;var TC="MenuSeparator",FS=R.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return a.jsx(Ne.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});FS.displayName=TC;var SC="MenuArrow",GS=R.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=sc(n);return a.jsx(Jl,{...o,...r,ref:t})});GS.displayName=SC;var RC="MenuSub",[N2,HS]=mn(RC),Dr="MenuSubTrigger",YS=R.forwardRef((e,t)=>{const n=Ln(Dr,e.__scopeMenu),r=co(Dr,e.__scopeMenu),o=HS(Dr,e.__scopeMenu),s=lc(Dr,e.__scopeMenu),i=R.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:c}=s,E={__scopeMenu:e.__scopeMenu},d=R.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return R.useEffect(()=>d,[d]),R.useEffect(()=>{const u=l.current;return()=>{window.clearTimeout(u),c(null)}},[l,c]),a.jsx(ic,{asChild:!0,...E,children:a.jsx(DS,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":VS(n.open),...e,ref:ri(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:oe(e.onPointerMove,Wr(u=>{s.onItemEnter(u),!u.defaultPrevented&&!e.disabled&&!n.open&&!i.current&&(s.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{n.onOpenChange(!0),d()},100))})),onPointerLeave:oe(e.onPointerLeave,Wr(u=>{var S,f;d();const T=(S=n.content)==null?void 0:S.getBoundingClientRect();if(T){const A=(f=n.content)==null?void 0:f.dataset.side,O=A==="right",I=O?-5:5,p=T[O?"left":"right"],N=T[O?"right":"left"];s.onPointerGraceIntentChange({area:[{x:u.clientX+I,y:u.clientY},{x:p,y:T.top},{x:N,y:T.top},{x:N,y:T.bottom},{x:p,y:T.bottom}],side:A}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(u),u.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:oe(e.onKeyDown,u=>{var S;const T=s.searchRef.current!=="";e.disabled||T&&u.key===" "||qh[r.dir].includes(u.key)&&(n.onOpenChange(!0),(S=n.content)==null||S.focus(),u.preventDefault())})})})});YS.displayName=Dr;var kS="MenuSubContent",WS=R.forwardRef((e,t)=>{const n=_S(Je,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,s=Ln(Je,e.__scopeMenu),i=co(Je,e.__scopeMenu),l=HS(kS,e.__scopeMenu),c=R.useRef(null),E=me(t,c);return a.jsx(kr.Provider,{scope:e.__scopeMenu,children:a.jsx(qe,{present:r||s.open,children:a.jsx(kr.Slot,{scope:e.__scopeMenu,children:a.jsx(cc,{id:l.contentId,"aria-labelledby":l.triggerId,...o,ref:E,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:d=>{var u;i.isUsingKeyboardRef.current&&((u=c.current)==null||u.focus()),d.preventDefault()},onCloseAutoFocus:d=>d.preventDefault(),onFocusOutside:oe(e.onFocusOutside,d=>{d.target!==l.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:oe(e.onEscapeKeyDown,d=>{i.onClose(),d.preventDefault()}),onKeyDown:oe(e.onKeyDown,d=>{var S;const u=d.currentTarget.contains(d.target),T=Qh[i.dir].includes(d.key);u&&T&&(s.onOpenChange(!1),(S=l.trigger)==null||S.focus(),d.preventDefault())})})})})})});WS.displayName=kS;function VS(e){return e?"open":"closed"}function Ds(e){return e==="indeterminate"}function uc(e){return Ds(e)?"indeterminate":e?"checked":"unchecked"}function AC(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function fC(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function IC(e,t,n){const o=t.length>1&&Array.from(t).every(E=>E===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=fC(e,Math.max(s,0));o.length===1&&(i=i.filter(E=>E!==n));const c=i.find(E=>E.toLowerCase().startsWith(o.toLowerCase()));return c!==n?c:void 0}function OC(e,t){const{x:n,y:r}=e;let o=!1;for(let s=0,i=t.length-1;s<t.length;i=s++){const l=t[s],c=t[i],E=l.x,d=l.y,u=c.x,T=c.y;d>r!=T>r&&n<(u-E)*(r-d)/(T-d)+E&&(o=!o)}return o}function NC(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return OC(n,t)}function Wr(e){return t=>t.pointerType==="mouse"?e(t):void 0}var pC=ic,hC=gS,CC=xS,mC=Ec,LC=yS,_C=Ai,gC=PS,xC=bS,yC=US,DC=BS,PC=FS,MC=GS,bC=YS,vC=WS,jS="DropdownMenu",[UC]=on(jS,[mS]),Ge=mS(),[p2,$S]=UC(jS),XS="DropdownMenuTrigger",wC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,s=$S(XS,n),i=Ge(n);return a.jsx(pC,{asChild:!0,...i,children:a.jsx(Ne.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:ri(t,s.triggerRef),onPointerDown:oe(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(s.onOpenToggle(),s.open||l.preventDefault())}),onKeyDown:oe(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&s.onOpenToggle(),l.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});wC.displayName=XS;var BC="DropdownMenuPortal",KS=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Ge(t);return a.jsx(hC,{...r,...n})};KS.displayName=BC;var zS="DropdownMenuContent",JS=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=$S(zS,n),s=Ge(n),i=R.useRef(!1);return a.jsx(CC,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...r,ref:t,onCloseAutoFocus:oe(e.onCloseAutoFocus,l=>{var c;i.current||(c=o.triggerRef.current)==null||c.focus(),i.current=!1,l.preventDefault()}),onInteractOutside:oe(e.onInteractOutside,l=>{const c=l.detail.originalEvent,E=c.button===0&&c.ctrlKey===!0,d=c.button===2||E;(!o.modal||d)&&(i.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)"}})});JS.displayName=zS;var FC="DropdownMenuGroup",GC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return a.jsx(mC,{...o,...r,ref:t})});GC.displayName=FC;var HC="DropdownMenuLabel",qS=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return a.jsx(LC,{...o,...r,ref:t})});qS.displayName=HC;var YC="DropdownMenuItem",QS=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return a.jsx(_C,{...o,...r,ref:t})});QS.displayName=YC;var kC="DropdownMenuCheckboxItem",WC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return a.jsx(gC,{...o,...r,ref:t})});WC.displayName=kC;var VC="DropdownMenuRadioGroup",jC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return a.jsx(xC,{...o,...r,ref:t})});jC.displayName=VC;var $C="DropdownMenuRadioItem",XC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return a.jsx(yC,{...o,...r,ref:t})});XC.displayName=$C;var KC="DropdownMenuItemIndicator",zC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return a.jsx(DC,{...o,...r,ref:t})});zC.displayName=KC;var JC="DropdownMenuSeparator",ZS=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return a.jsx(PC,{...o,...r,ref:t})});ZS.displayName=JC;var qC="DropdownMenuArrow",QC=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return a.jsx(MC,{...o,...r,ref:t})});QC.displayName=qC;var ZC="DropdownMenuSubTrigger",em=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return a.jsx(bC,{...o,...r,ref:t})});em.displayName=ZC;var tm="DropdownMenuSubContent",nm=R.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Ge(n);return a.jsx(vC,{...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)"}})});nm.displayName=tm;var rm=KS,om=JS,sm=qS,im=QS,am=ZS;const lm=R.forwardRef(({container:e,style:t,sideOffset:n=4,...r},o)=>a.jsx(rm,{container:e,children:a.jsx(om,{ref:o,sideOffset:n,style:{minWidth:180,background:ue("surfaceElevated"),color:ue("textPrimary"),border:`1px solid ${ue("borderDefault")}`,borderRadius:Cn.md,boxShadow:ue("shadowMd"),padding:Ie[1],zIndex:Gr.popover,...t},...r})}));lm.displayName="DropdownMenuContent";const cm=R.forwardRef(({style:e,...t},n)=>a.jsx(im,{ref:n,style:{display:"flex",alignItems:"center",gap:Ie[2],padding:`${Ie[1]} ${Ie[2]}`,fontSize:ve.sm,borderRadius:Cn.sm,cursor:"default",outline:"none",userSelect:"none",...e},...t}));cm.displayName="DropdownMenuItem";const Em=R.forwardRef(({style:e,...t},n)=>a.jsx(am,{ref:n,style:{height:1,background:ue("borderSubtle"),margin:`${Ie[1]} 0`,...e},...t}));Em.displayName="DropdownMenuSeparator";const dm=R.forwardRef(({style:e,...t},n)=>a.jsx(sm,{ref:n,style:{padding:`${Ie[1]} ${Ie[2]}`,fontSize:ve.xs,color:ue("textMuted"),textTransform:"uppercase",letterSpacing:"0.04em",...e},...t}));dm.displayName="DropdownMenuLabel";var eR="Popover",[tR]=on(eR,[Sr]),fi=Sr(),[h2,sn]=tR(eR),nR="PopoverAnchor",um=R.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=sn(nR,n),s=fi(n),{onCustomAnchorAdd:i,onCustomAnchorRemove:l}=o;return R.useEffect(()=>(i(),()=>l()),[i,l]),a.jsx(li,{...s,...r,ref:t})});um.displayName=nR;var rR="PopoverTrigger",Tm=R.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=sn(rR,n),s=fi(n),i=me(t,o.triggerRef),l=a.jsx(Ne.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":lR(o.open),...r,ref:i,onClick:oe(e.onClick,o.onOpenToggle)});return o.hasCustomAnchor?l:a.jsx(li,{asChild:!0,...s,children:l})});Tm.displayName=rR;var Tc="PopoverPortal",[Sm,Rm]=tR(Tc,{forceMount:void 0}),oR=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,s=sn(Tc,t);return a.jsx(Sm,{scope:t,forceMount:n,children:a.jsx(qe,{present:n||s.open,children:a.jsx(io,{asChild:!0,container:o,children:r})})})};oR.displayName=Tc;var tr="PopoverContent",sR=R.forwardRef((e,t)=>{const n=Rm(tr,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,s=sn(tr,e.__scopePopover);return a.jsx(qe,{present:r||s.open,children:s.modal?a.jsx(fm,{...o,ref:t}):a.jsx(Im,{...o,ref:t})})});sR.displayName=tr;var Am=Qn("PopoverContent.RemoveScroll"),fm=R.forwardRef((e,t)=>{const n=sn(tr,e.__scopePopover),r=R.useRef(null),o=me(t,r),s=R.useRef(!1);return R.useEffect(()=>{const i=r.current;if(i)return tc(i)},[]),a.jsx(Ti,{as:Am,allowPinchZoom:!0,children:a.jsx(iR,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:oe(e.onCloseAutoFocus,i=>{var l;i.preventDefault(),s.current||(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:oe(e.onPointerDownOutside,i=>{const l=i.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,E=l.button===2||c;s.current=E},{checkForDefaultPrevented:!1}),onFocusOutside:oe(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1})})})}),Im=R.forwardRef((e,t)=>{const n=sn(tr,e.__scopePopover),r=R.useRef(!1),o=R.useRef(!1);return a.jsx(iR,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var i,l;(i=e.onCloseAutoFocus)==null||i.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 c,E;(c=e.onInteractOutside)==null||c.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const i=s.target;((E=n.triggerRef.current)==null?void 0:E.contains(i))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})}),iR=R.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:s,disableOutsidePointerEvents:i,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:E,onInteractOutside:d,...u}=e,T=sn(tr,n),S=fi(n);return ec(),a.jsx(di,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:s,children:a.jsx(oo,{asChild:!0,disableOutsidePointerEvents:i,onInteractOutside:d,onEscapeKeyDown:l,onPointerDownOutside:c,onFocusOutside:E,onDismiss:()=>T.onOpenChange(!1),children:a.jsx(zl,{"data-state":lR(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)"}})})})}),aR="PopoverClose",Om=R.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=sn(aR,n);return a.jsx(Ne.button,{type:"button",...r,ref:t,onClick:oe(e.onClick,()=>o.onOpenChange(!1))})});Om.displayName=aR;var Nm="PopoverArrow",pm=R.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=fi(n);return a.jsx(Jl,{...o,...r,ref:t})});pm.displayName=Nm;function lR(e){return e?"open":"closed"}var hm=oR,Cm=sR;const mm=R.forwardRef(({container:e,style:t,sideOffset:n=6,...r},o)=>a.jsx(hm,{container:e,children:a.jsx(Cm,{ref:o,sideOffset:n,style:{background:ue("surfaceElevated"),color:ue("textPrimary"),border:`1px solid ${ue("borderDefault")}`,borderRadius:Cn.md,boxShadow:ue("shadowMd"),padding:Ie[3],zIndex:Gr.popover,minWidth:220,...t},...r})}));mm.displayName="PopoverContent";const _E=e=>{let t;const n=new Set,r=(E,d)=>{const u=typeof E=="function"?E(t):E;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:()=>c,subscribe:E=>(n.add(E),()=>n.delete(E))},c=t=e(r,o,l);return l},Lm=(e=>e?_E(e):_E),_m=e=>e;function gm(e,t=_m){const n=Ce.useSyncExternalStore(e.subscribe,Ce.useCallback(()=>t(e.getState()),[e,t]),Ce.useCallback(()=>t(e.getInitialState()),[e,t]));return Ce.useDebugValue(n),n}const gE=e=>{const t=Lm(e),n=r=>gm(t,r);return Object.assign(n,t),n},xm=(e=>e?gE(e):gE),xE=e=>Symbol.iterator in e,yE=e=>"entries"in e,DE=(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},ym=(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 Dm(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:xE(e)&&xE(t)?yE(e)&&yE(t)?DE(e,t):ym(e,t):DE({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Pm(e){const t=Ce.useRef(void 0);return n=>{const r=e(n);return Dm(t.current,r)?t.current:t.current=r}}const Mm={mainView:"notebook",themeMode:"dark",sidebarPanel:"files",sidebarOpen:!0,files:[],filesLoading:!1,activeFile:null,cells:[],notebookTitle:"",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 bm(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,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"ADD_CELL":{if(!t.afterId)return{...e,cells:[...e.cells,t.cell],notebookDirty:!0};const o=e.cells.findIndex(i=>i.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(i=>i.id===t.id?{...i,...t.updates}:i),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(i=>i.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 i=[...e.cells],[l]=i.splice(o,1);return i.splice(s,0,l),{...e,cells:i,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 PE=xm((e,t)=>({...Mm,dispatch:n=>{const r=bm(t(),n);e(r)}})),vm=R.createContext(null);function Um({children:e}){return a.jsx(a.Fragment,{children:e})}function Te(){const e=PE(Pm(r=>{const{dispatch:o,...s}=r;return s})),t=PE(r=>r.dispatch);return R.useContext(vm)??{state:e,dispatch:t}}function xt(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Ve(e,t=""){const n={id:xt(),type:e,content:t,status:"idle"};return e==="param"&&(n.content="",n.paramConfig={paramType:"text",label:"Parameter",defaultValue:"",options:[]}),n}function wm(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 Bm({open:e,onClose:t}){const{state:n,dispatch:r}=Te(),[o,s]=R.useState(""),[i,l]=R.useState(0),c=R.useRef(null);R.useEffect(()=>{e&&(s(""),l(0))},[e]);const E=R.useMemo(()=>{const S=p=>r(p),f=()=>t(),A=p=>()=>{p(),f()},O=[["Files","files"],["Schema","schema"],["Lineage","lineage"],["Block Library","block_library"],["Connections","connection"],["Reference","reference"]];return[{id:"sidebar.toggle",label:n.sidebarOpen?"Hide sidebar":"Show sidebar",group:"View",shortcut:"⌘B",run:A(()=>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:A(()=>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:A(()=>S({type:"TOGGLE_INSPECTOR"}))},{id:"dashboard.toggle",label:n.dashboardMode?"Exit dashboard mode":"Enter dashboard mode",group:"View",shortcut:"⌘D",run:A(()=>S({type:"TOGGLE_DASHBOARD_MODE"}))},{id:"dev.toggle",label:"Toggle dev panel",group:"View",shortcut:"⌘J",run:A(()=>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:A(()=>S({type:"TOGGLE_LINEAGE_FULLSCREEN"}))},...O.map(([p,N])=>({id:`panel.${N}`,label:`Go to ${p}`,group:"Navigate",run:A(()=>{S({type:"SET_SIDEBAR_PANEL",panel:N}),n.sidebarOpen||S({type:"TOGGLE_SIDEBAR"})})})),{id:"notebook.new",label:"New notebook…",group:"Create",run:A(()=>S({type:"OPEN_NEW_NOTEBOOK_MODAL"}))},{id:"block.new",label:"New block…",group:"Create",run:A(()=>S({type:"OPEN_NEW_BLOCK_MODAL"}))}]},[n.sidebarOpen,n.themeMode,n.dashboardMode,n.lineageFullscreen,n.inspectorOpen,r,t]),d=R.useMemo(()=>{const S=E.map(f=>({a:f,s:wm(f,o)})).filter(f=>f.s>0);return S.sort((f,A)=>A.s-f.s),S.map(f=>f.a)},[E,o]);R.useEffect(()=>{l(0)},[o]),R.useEffect(()=>{var f;const S=(f=c.current)==null?void 0:f.querySelector(`[data-palette-idx="${i}"]`);S==null||S.scrollIntoView({block:"nearest"})},[i]);const u=S=>{var f;S.key==="ArrowDown"?(S.preventDefault(),l(A=>Math.min(d.length-1,A+1))):S.key==="ArrowUp"?(S.preventDefault(),l(A=>Math.max(0,A-1))):S.key==="Enter"&&(S.preventDefault(),(f=d[i])==null||f.run())};let T="";return a.jsx(Dh,{open:e,onOpenChange:S=>!S&&t(),children:a.jsxs(Ph,{children:[a.jsx(Mh,{style:{position:"fixed",inset:0,background:ue("surfaceOverlay"),zIndex:Gr.overlay}}),a.jsxs(bh,{"aria-label":"Command palette",style:{position:"fixed",top:"18vh",left:"50%",transform:"translateX(-50%)",width:"92vw",maxWidth:620,background:ue("surfaceRaised"),color:ue("textPrimary"),border:`1px solid ${ue("borderDefault")}`,borderRadius:Cn.lg,boxShadow:ue("shadowLg"),zIndex:Gr.modal,display:"flex",flexDirection:"column",overflow:"hidden"},onKeyDown:u,children:[a.jsx(vh,{style:{position:"absolute",left:-9999},children:"Command palette"}),a.jsx("input",{autoFocus:!0,value:o,onChange:S=>s(S.target.value),placeholder:"Type a command…",style:{padding:`${Ie[3]}px ${Ie[4]}px`,border:"none",outline:"none",background:"transparent",color:ue("textPrimary"),fontSize:ve.md,borderBottom:`1px solid ${ue("borderSubtle")}`}}),a.jsxs("div",{ref:c,style:{maxHeight:360,overflowY:"auto",padding:`${Ie[1]}px 0`},children:[d.length===0&&a.jsx("div",{style:{padding:Ie[4],fontSize:ve.sm,color:ue("textMuted"),textAlign:"center"},children:"No matching commands"}),d.map((S,f)=>{const A=S.group!==T;T=S.group;const O=f===i;return a.jsxs(Ce.Fragment,{children:[A&&a.jsx("div",{style:{padding:`${Ie[2]}px ${Ie[4]}px ${Ie[1]}px`,fontSize:ve.xs,fontWeight:Gl.medium,textTransform:"uppercase",letterSpacing:.5,color:ue("textMuted")},children:S.group}),a.jsxs("div",{"data-palette-idx":f,role:"option","aria-selected":O,onMouseEnter:()=>l(f),onMouseDown:I=>{I.preventDefault(),S.run()},style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:`${Ie[2]}px ${Ie[4]}px`,fontSize:ve.sm,cursor:"pointer",background:O?ue("surfaceHover"):"transparent",color:ue("textPrimary")},children:[a.jsx("span",{children:S.label}),S.shortcut&&a.jsx("span",{style:{fontSize:ve.xs,color:ue("textMuted"),fontFamily:"var(--dql-font-mono, monospace)"},children:S.shortcut})]})]},S.id)})]})]})]})})}const Fm=window.location.origin;async function ae(e,t){const n=await fetch(`${Fm}${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 Z={async listNotebooks(){try{return await ae("/api/notebooks")}catch{return[]}},async readNotebook(e){return ae(`/api/notebook-content?path=${encodeURIComponent(e)}`)},async createNotebook(e,t){return ae("/api/notebooks",{method:"POST",body:JSON.stringify({name:e,template:t})})},async createBlock(e){return ae("/api/blocks",{method:"POST",body:JSON.stringify({name:e})})},async getBlockLibrary(){try{return await ae("/api/blocks/library")}catch{return{blocks:[]}}},async updateBlockStatus(e,t){return ae("/api/blocks/status",{method:"POST",body:JSON.stringify({path:e,newStatus:t})})},async getBlockHistory(e){try{return await ae(`/api/blocks/history?path=${encodeURIComponent(e)}`)}catch{return{entries:[]}}},async runBlockTests(e,t){return ae("/api/blocks/run-tests",{method:"POST",body:JSON.stringify({source:e,path:t})})},async getBlockStudioCatalog(){return ae("/api/block-studio/catalog")},async openBlockStudio(e){return ae(`/api/block-studio/open?path=${encodeURIComponent(e)}`)},async validateBlockStudio(e,t){return ae("/api/block-studio/validate",{method:"POST",body:JSON.stringify({source:e,path:t})})},async runBlockStudio(e,t){return ae("/api/block-studio/run",{method:"POST",body:JSON.stringify({source:e,path:t})})},async saveBlockStudio(e){return ae("/api/block-studio/save",{method:"POST",body:JSON.stringify(e)})},async saveAsBlock(e){return ae("/api/blocks/save-from-cell",{method:"POST",body:JSON.stringify(e)})},async getBlockTemplates(){try{return(await ae("/api/blocks/templates")).templates}catch{return[]}},async listBlocks(e){try{return(await ae("/api/notebooks")).filter(n=>n.type==="block"&&(!e||n.path.startsWith(`blocks/${e}/`)))}catch{return[]}},async saveNotebook(e,t){return ae("/api/notebook-content",{method:"PUT",body:JSON.stringify({path:e,content:t})})},async executeQuery(e,t){var o;const n=await ae("/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 ae("/api/schema")}catch{return[]}},async getConnections(){try{return await ae("/api/connections")}catch{return{default:"unknown",connections:{}}}},async saveConnections(e){return ae("/api/connections",{method:"PUT",body:JSON.stringify({connections:e})})},async testConnection(){try{return await ae("/api/test-connection",{method:"POST",body:JSON.stringify({})})}catch(e){return{ok:!1,message:e.message??"Connection failed"}}},async getSemanticLayer(){try{return await ae("/api/semantic-layer")}catch{return{available:!1,provider:null,metrics:[],dimensions:[],hierarchies:[],domains:[],tags:[],favorites:[],recentlyUsed:[],lastSyncTime:null}}},async getSemanticTree(){return(await ae("/api/semantic-layer/tree")).tree},async getSemanticObject(e){return ae(`/api/semantic-layer/object/${encodeURIComponent(e)}`)},async importSemanticLayer(e){return ae("/api/semantic-layer/import",{method:"POST",body:JSON.stringify(e)})},async syncSemanticLayer(){return ae("/api/semantic-layer/sync",{method:"POST",body:JSON.stringify({})})},async previewSemanticImport(e){return ae("/api/semantic-layer/import-preview",{method:"POST",body:JSON.stringify(e)})},async previewSyncDiff(){return ae("/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 ae(`/api/semantic-layer/search?${t.toString()}`)}catch{return{metrics:[],dimensions:[],hierarchies:[]}}},async getFavorites(){try{return(await ae("/api/user-prefs/favorites")).favorites}catch{return[]}},async toggleFavorite(e){return(await ae("/api/user-prefs/favorites",{method:"POST",body:JSON.stringify({name:e})})).favorites},async getRecentlyUsed(){try{return(await ae("/api/user-prefs/recent")).recentlyUsed}catch{return[]}},async trackUsage(e){try{return(await ae("/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 ae(`/api/semantic-layer/compatible-dims?${t.toString()}`)).dimensions}catch{return[]}},async composeQuery(e,t,n){try{return await ae("/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 ae("/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 ae("/api/semantic-builder/save",{method:"POST",body:JSON.stringify(e)})},async createMetric(e){try{return await ae("/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 ae(`/api/describe-table?${o.toString()}`)}catch{return[]}},async fetchLineage(){try{return await ae("/api/lineage")}catch{return{nodes:[],edges:[]}}},async searchLineage(e){try{return await ae(`/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 ae(`/api/lineage/query?${t.toString()}`)}catch{return{graph:{nodes:[],edges:[]},matches:[]}}},async fetchLineageNode(e){try{return await ae(`/api/lineage/node/${encodeURIComponent(e)}`)}catch{return null}},async fetchBlockLineage(e){try{return await ae(`/api/lineage/block/${encodeURIComponent(e)}`)}catch{return null}},async fetchImpactAnalysis(e){try{return await ae(`/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 ae(o)}catch{return null}}};function Gm(){const{state:e,dispatch:t}=Te(),n=e.inspectorContext;return a.jsxs("aside",{"aria-label":"Inspector",style:{width:320,borderLeft:`1px solid ${ue("borderSubtle")}`,background:ue("surfaceBase"),color:ue("textPrimary"),display:"flex",flexDirection:"column",overflow:"hidden",flexShrink:0},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:`${Ie[3]}px ${Ie[4]}px`,borderBottom:`1px solid ${ue("borderSubtle")}`},children:[a.jsx("div",{style:{fontSize:ve.sm,fontWeight:Gl.semibold},children:n?Hm(n):"Inspector"}),a.jsx("button",{onClick:()=>t({type:"SET_INSPECTOR",open:!1}),"aria-label":"Close inspector",style:{background:"transparent",border:"none",color:ue("textMuted"),cursor:"pointer",fontSize:ve.md,padding:2,borderRadius:Cn.sm},children:"×"})]}),a.jsx("div",{style:{flex:1,overflow:"auto",padding:Ie[4]},children:n?a.jsx(Ym,{context:n}):a.jsx(jm,{})})]})}function Hm(e){switch(e.kind){case"cell":return"Cell";case"lineage-node":return"Lineage node";case"metric":return"Metric"}}function Ym({context:e}){return e.kind==="cell"?a.jsx(km,{cellId:e.cellId}):e.kind==="lineage-node"?a.jsx(Wm,{nodeId:e.nodeId}):a.jsx(Vm,{name:e.name})}function km({cellId:e}){const{state:t}=Te(),n=t.cells.find(r=>r.id===e);return n?a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:Ie[3],fontSize:ve.sm},children:[a.jsx(We,{label:"Type",children:n.type}),a.jsx(We,{label:"ID",children:a.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:n.id})}),a.jsxs(We,{label:"Length",children:[n.content.length," chars"]}),n.status&&a.jsx(We,{label:"Status",children:n.status})]}):a.jsx(Ps,{children:"No matching cell in the active notebook."})}function Wm({nodeId:e}){const[t,n]=R.useState(null),[r,o]=R.useState(!0);if(R.useEffect(()=>{let i=!1;return o(!0),Z.fetchLineageNode(e).then(l=>{i||(n(l),o(!1))}).catch(()=>{i||o(!1)}),()=>{i=!0}},[e]),r)return a.jsx(Ps,{children:"Loading node…"});if(!t||!t.node)return a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:Ie[3]},children:[a.jsx(We,{label:"Node ID",children:a.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:e})}),a.jsx(Ps,{children:"No metadata available for this node."})]});const s=t.node;return a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:Ie[3]},children:[a.jsx(We,{label:"Name",children:s.name??e}),a.jsx(We,{label:"Type",children:s.type}),s.domain&&a.jsx(We,{label:"Domain",children:s.domain}),s.layer&&a.jsx(We,{label:"Layer",children:s.layer}),a.jsx(We,{label:"Upstream",children:t.incoming.length}),a.jsx(We,{label:"Downstream",children:t.outgoing.length}),s.path&&a.jsx(We,{label:"Path",children:a.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)",fontSize:ve.xs},children:s.path})})]})}function Vm({name:e}){return a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:Ie[3]},children:[a.jsx(We,{label:"Metric",children:e}),a.jsx(Ps,{children:"Definition, dimensions, and governance surface will render here."})]})}function We({label:e,children:t}){return a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[a.jsx("div",{style:{fontSize:ve.xs,color:ue("textMuted"),textTransform:"uppercase",letterSpacing:.5,fontWeight:Gl.medium},children:e}),a.jsx("div",{style:{fontSize:ve.sm,color:ue("textPrimary")},children:t})]})}function Ps({children:e}){return a.jsx("div",{style:{fontSize:ve.sm,color:ue("textSecondary"),lineHeight:1.5,background:ue("surfaceSunken"),border:`1px solid ${ue("borderSubtle")}`,borderRadius:Cn.md,padding:Ie[3]},children:e})}function jm(){return a.jsx("div",{style:{fontSize:ve.sm,color:ue("textMuted"),lineHeight:1.5},children:"Select a cell, lineage node, or metric to inspect its details here."})}const $m={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"},Xm={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"},ce={dark:$m,light:Xm};function kt({title:e,active:t,onClick:n,children:r,t:o}){const[s,i]=R.useState(!1);return a.jsx(mp,{content:e,side:"right",children:a.jsx("button",{"aria-label":e,onClick:n,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!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 Km(){return a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 zm(){return a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 Jm(){return a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 qm(){return a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 Qm(){return a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 Zm(){return a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 eL(){return a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 tL(){const{state:e,dispatch:t}=Te(),n=ce[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 a.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:[a.jsx(kt,{title:"Files",active:e.sidebarPanel==="files"&&e.sidebarOpen,onClick:()=>r("files"),t:n,children:a.jsx(Km,{})}),a.jsx(kt,{title:"Schema",active:e.sidebarPanel==="schema"&&e.sidebarOpen,onClick:()=>r("schema"),t:n,children:a.jsx(zm,{})}),a.jsx(kt,{title:"Block Library",active:e.sidebarPanel==="block_library"&&e.sidebarOpen,onClick:()=>r("block_library"),t:n,children:a.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",children:[a.jsx("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",stroke:"currentColor",strokeWidth:"1.3"}),a.jsx("rect",{x:"10",y:"2",width:"6",height:"6",rx:"1",stroke:"currentColor",strokeWidth:"1.3"}),a.jsx("rect",{x:"2",y:"10",width:"6",height:"6",rx:"1",stroke:"currentColor",strokeWidth:"1.3"}),a.jsx("rect",{x:"10",y:"10",width:"6",height:"6",rx:"1",stroke:"currentColor",strokeWidth:"1.3"})]})}),a.jsx(kt,{title:"Lineage",active:e.sidebarPanel==="lineage"&&e.sidebarOpen,onClick:()=>r("lineage"),t:n,children:a.jsx(Jm,{})}),a.jsx(kt,{title:"Connection",active:e.mainView==="connection",onClick:()=>r("connection"),t:n,children:a.jsx(qm,{})}),a.jsx(kt,{title:"Reference",active:e.mainView==="reference",onClick:()=>r("reference"),t:n,children:a.jsx(Qm,{})}),a.jsx("div",{style:{flex:1}}),a.jsx(kt,{title:"Help & Reference",active:e.mainView==="reference",onClick:()=>r("reference"),t:n,children:a.jsx(Zm,{})}),a.jsx(kt,{title:"Settings",active:!1,onClick:()=>{},t:n,children:a.jsx(eL,{})})]})}const aa={notebooks:"Notebooks",workbooks:"Workbooks",blocks:"Blocks",dashboards:"Dashboards"};function nL({type:e}){switch(e){case"notebook":return a.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 a.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 a.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 a.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 rL({expanded:e}){return a.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:e?a.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"}):a.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 oL(e){return e.name.replace(/\.(dqlnb|dql)$/,"")}function sL({onOpenFile:e}){const{state:t,dispatch:n}=Te(),r=ce[t.themeMode],[o,s]=R.useState({notebooks:!0,workbooks:!0,blocks:!1,dashboards:!1}),[i,l]=R.useState(!1),c={notebooks:[],workbooks:[],blocks:[],dashboards:[]};for(const d of t.files){const u=d.folder.toLowerCase();u in c&&c[u].push(d)}const E=d=>{s(u=>({...u,[d]:!u[d]}))};return a.jsxs("div",{style:{flex:1,overflow:"auto",padding:"8px 0",display:"flex",flexDirection:"column",gap:0},children:[a.jsx("div",{style:{padding:"0 8px 8px"},children:a.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 ${i?r.accent:r.cellBorder}`,borderRadius:6,color:i?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:[a.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"New Notebook"]})}),t.filesLoading&&a.jsx("div",{style:{padding:"8px 14px",color:r.textMuted,fontSize:12,fontFamily:r.font},children:"Loading files…"}),Object.keys(aa).map(d=>{const u=c[d],T=o[d],S=d==="notebooks"?()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}):d==="blocks"?()=>n({type:"OPEN_NEW_BLOCK_MODAL"}):void 0;return a.jsxs("div",{children:[a.jsx(iL,{label:aa[d],count:u.length,expanded:T,onToggle:()=>E(d),onAdd:S,t:r}),T&&a.jsx("div",{children:u.length===0?a.jsxs("div",{style:{padding:"4px 14px 4px 32px",fontSize:12,color:r.textMuted,fontFamily:r.font,fontStyle:"italic"},children:["No ",aa[d].toLowerCase()]}):u.map(f=>{var A;return a.jsx(aL,{file:f,active:((A=t.activeFile)==null?void 0:A.path)===f.path,onClick:()=>e(f),t:r},f.path)})})]},d)})]})}function iL({label:e,count:t,expanded:n,onToggle:r,onAdd:o,t:s}){const[i,l]=R.useState(!1),[c,E]=R.useState(!1);return a.jsxs("div",{onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{display:"flex",alignItems:"center",background:i?s.sidebarItemHover:"transparent",transition:"background 0.1s"},children:[a.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:[a.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:a.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),a.jsx(rL,{expanded:n}),a.jsx("span",{style:{flex:1},children:e}),t>0&&a.jsx("span",{style:{background:s.pillBg,color:s.textMuted,borderRadius:10,padding:"0 5px",fontSize:10,fontWeight:500},children:t})]}),o&&i&&a.jsx("button",{onClick:d=>{d.stopPropagation(),o()},onMouseEnter:()=>E(!0),onMouseLeave:()=>E(!1),title:`New ${e.slice(0,-1)}`,style:{background:c?s.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:c?s.accent:s.textMuted,fontSize:14,lineHeight:1,padding:"2px 8px",marginRight:4,flexShrink:0,transition:"color 0.1s"},children:"+"})]})}function aL({file:e,active:t,onClick:n,t:r}){const[o,s]=R.useState(!1);return a.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:[a.jsx("span",{style:{flexShrink:0,color:t?r.accent:r.textMuted},children:a.jsx(nL,{type:e.type})}),a.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:oL(e)}),e.isNew&&a.jsx("span",{style:{fontSize:9,fontWeight:600,color:r.accent,background:r.sidebarItemActive,borderRadius:4,padding:"1px 4px",flexShrink:0},children:"NEW"})]})}const lL={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 Al(e,t){const n=e.toLowerCase().split("(")[0].trim();return lL[n]??t}function cL({t:e}){return a.jsxs("div",{style:{padding:"8px 12px",display:"flex",flexDirection:"column",gap:8},children:[[1,2,3].map(t=>a.jsx("div",{style:{height:28,borderRadius:4,background:e.pillBg,opacity:.6,animation:"pulse 1.5s ease-in-out infinite"}},t)),a.jsx("style",{children:"@keyframes pulse { 0%,100%{opacity:.6} 50%{opacity:.3} }"})]})}function EL(){const{state:e,dispatch:t}=Te(),n=ce[e.themeMode],[r,o]=R.useState(!1),[s,i]=R.useState(""),l=async()=>{t({type:"SET_SCHEMA_LOADING",loading:!0});try{const T=await Z.getSchema();t({type:"SET_SCHEMA",tables:T})}catch(T){console.error("Schema refresh failed:",T)}finally{t({type:"SET_SCHEMA_LOADING",loading:!1})}},c=R.useMemo(()=>{const T=s.trim().toLowerCase();return T?e.schemaTables.filter(S=>{const f=[S.name,S.path,S.objectType].filter(O=>!!O).some(O=>O.toLowerCase().includes(T)),A=S.columns.some(O=>O.name.toLowerCase().includes(T)||O.type.toLowerCase().includes(T));return f||A}):e.schemaTables},[s,e.schemaTables]),E=R.useMemo(()=>{const T=new Map;for(const S of c){const[f,...A]=S.name.split("."),O=A.length>0?f:S.source==="file"?"files":"default",I=T.get(O)??[];I.push(S),T.set(O,I)}return Array.from(T.entries()).sort((S,f)=>S[0].localeCompare(f[0]))},[c]),d={schemas:E.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 a.jsxs("div",{style:{flex:1,overflow:"auto",display:"flex",flexDirection:"column"},children:[a.jsxs("div",{style:{padding:"10px",display:"grid",gap:10,borderBottom:`1px solid ${n.headerBorder}`},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:12,fontWeight:700,color:n.textPrimary,fontFamily:n.font},children:"Database Catalog"}),a.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:"Browse schemas, tables, views, and loaded columns from the active connection."})]}),a.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:[a.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:a.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"]})]}),a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8},children:[a.jsx(la,{label:"Schemas",value:d.schemas,t:n}),a.jsx(la,{label:"Tables",value:d.tables,t:n}),a.jsx(la,{label:"Columns",value:d.columns,t:n})]}),a.jsx("input",{value:s,onChange:T=>i(T.target.value),placeholder:"Search schemas, tables, columns...",style:u})]}),e.schemaLoading?a.jsx(cL,{t:n}):e.schemaTables.length===0?a.jsxs("div",{style:{padding:"24px 14px",color:n.textMuted,fontSize:12,fontFamily:n.font,textAlign:"center",fontStyle:"italic"},children:["No tables found.",a.jsx("br",{}),"Connect a data source to explore schema."]}):c.length===0?a.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."}):a.jsx("div",{style:{overflow:"auto",flex:1},children:E.map(([T,S])=>a.jsxs("div",{children:[a.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(f=>a.jsx(dL,{table:f,t:n},f.name))]},T))})]})}function la({label:e,value:t,t:n}){return a.jsxs("div",{style:{background:n.cellBg,border:`1px solid ${n.headerBorder}`,borderRadius:8,padding:"8px 10px"},children:[a.jsx("div",{style:{fontSize:9,fontWeight:700,color:n.textMuted,fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em"},children:e}),a.jsx("div",{style:{fontSize:18,fontWeight:700,color:n.textPrimary,fontFamily:n.font,marginTop:2},children:t})]})}function dL({table:e,t}){var c;const{dispatch:n}=Te(),[r,o]=R.useState(!1),[s,i]=R.useState(!1),l=async()=>{if(n({type:"TOGGLE_SCHEMA_TABLE",tableName:e.name}),!e.expanded&&e.columns.length===0){i(!0);try{const E=await Z.describeTable(e.path);E.length>0&&n({type:"SET_TABLE_COLUMNS",tableName:e.name,columns:E})}catch(E){console.error("describeTable failed:",E)}finally{i(!1)}}};return a.jsxs("div",{children:[a.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:[a.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:a.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),e.source==="database"?a.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",style:{color:"#56d364",flexShrink:0},children:a.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"})}):a.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",style:{color:t.accent,flexShrink:0},children:a.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"})}),a.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),e.objectType&&a.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"}),((c=e.governance)==null?void 0:c.status)&&a.jsx(SL,{status:e.governance.status,t}),e.columns.length>0&&a.jsx("span",{style:{fontSize:10,color:t.textMuted,background:t.pillBg,borderRadius:8,padding:"1px 5px",flexShrink:0},children:e.columns.length})]}),e.expanded&&a.jsxs("div",{style:{paddingLeft:26},children:[e.governance&&(e.governance.owner||e.governance.domain)&&a.jsxs("div",{style:{padding:"3px 10px",display:"flex",gap:8,flexWrap:"wrap"},children:[e.governance.domain&&a.jsxs("span",{style:{fontSize:9,fontFamily:t.font,color:t.textMuted},children:[a.jsx("span",{style:{fontWeight:600},children:"domain:"})," ",e.governance.domain]}),e.governance.owner&&a.jsxs("span",{style:{fontSize:9,fontFamily:t.font,color:t.textMuted},children:[a.jsx("span",{style:{fontWeight:600},children:"owner:"})," ",e.governance.owner]})]}),s?a.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:"..."}):e.columns.length===0?a.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:"No columns"}):e.columns.map(E=>a.jsx(uL,{col:E,t},E.name))]})]})}function uL({col:e,t}){const[n,r]=R.useState(!1);return a.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:[a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",style:{color:t.textMuted,flexShrink:0},children:a.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"})}),a.jsx("span",{style:{flex:1,fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),a.jsx("span",{style:{fontSize:10,fontFamily:t.fontMono,color:Al(e.type,t.accent),background:`${Al(e.type,t.accent)}18`,borderRadius:4,padding:"1px 5px",flexShrink:0},children:e.type.toLowerCase()})]})}const TL={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 SL({status:e,t}){const n=TL[e];return n?a.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 fl={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"},ca={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"},RL={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"]},AL=[{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 cR(){const{state:e}=Te(),t=ce[e.themeMode],[n,r]=R.useState(null),[o,s]=R.useState(!1),[i,l]=R.useState(null),[c,E]=R.useState(null),[d,u]=R.useState(!1),[T,S]=R.useState(!1),[f,A]=R.useState(null),[O,I]=R.useState(""),[p,N]=R.useState("duckdb"),[h,C]=R.useState({});R.useEffect(()=>{Z.getConnections().then(P=>{r(P),Object.keys(P.connections).length>0&&Z.testConnection().then(l)})},[]);const m=async()=>{s(!0),l(null);const P=await Z.testConnection();l(P),s(!1)},_=(P,w)=>{E(P),u(!1),I(P),N((w==null?void 0:w.driver)??"duckdb");const U={};Object.entries(w??{}).forEach(([x,B])=>{x!=="driver"&&x!=="type"&&(U[x]=String(B??""))}),C(U)},D=()=>{u(!0),E(null),I(""),N("duckdb"),C({})},g=()=>{E(null),u(!1)},b=async()=>{if(!n)return;S(!0),A(null);const P=O.trim()||(c??"default"),w={driver:p};Object.entries(h).forEach(([x,B])=>{B.trim()&&(x==="port"&&!isNaN(Number(B))?w[x]=Number(B):w[x]=B)});const U={...n.connections};c&&c!==P&&delete U[c],U[P]=w;try{await Z.saveConnections(U);const x=await Z.getConnections();r(x),A("Saved"),setTimeout(()=>A(null),2e3),E(null),u(!1);try{s(!0);const B=await Z.testConnection();l(B)}catch{}finally{s(!1)}}catch(x){A(`Error: ${x.message}`)}finally{S(!1)}},y=async P=>{if(!n)return;const w={...n.connections};delete w[P],S(!0);try{await Z.saveConnections(w);const U=await Z.getConnections();r(U),E(null)}finally{S(!1)}},M={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)??{},v=(n==null?void 0:n.default)??"";return a.jsxs("div",{style:{flex:1,overflow:"auto",padding:"12px 12px 20px"},children:[i&&a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",marginBottom:10,borderRadius:6,background:i.ok?`${t.success}12`:`${t.error}12`,border:`1px solid ${i.ok?t.success:t.error}30`},children:[a.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:i.ok?t.success:t.error,flexShrink:0}}),a.jsx("span",{style:{fontSize:11,fontFamily:t.font,color:i.ok?t.success:t.error},children:i.ok?"Connected":"Disconnected"})]}),a.jsx("div",{style:M,children:"Connections"}),n===null?a.jsx("div",{style:{fontSize:12,color:t.textMuted,fontFamily:t.font},children:"Loading…"}):Object.entries(L).map(([P,w])=>{const U=(w==null?void 0:w.driver)??(w==null?void 0:w.type)??"unknown",x=P===v||Object.keys(L).length===1,B=ca[U]??t.accent;return c===P?a.jsx(ME,{t,editName:O,setEditName:I,editDriver:p,setEditDriver:N,editFields:h,setEditFields:C,onSave:b,onCancel:g,onDelete:()=>y(P),saving:T,isNew:!1},P):a.jsxs("div",{style:{...F,borderLeft:x?`3px solid ${B}`:`1px solid ${t.cellBorder}`},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[a.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:fl[U]??U}),a.jsx("span",{style:{fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,fontWeight:500},children:P}),x&&a.jsx("span",{style:{fontSize:9,color:t.accent,fontFamily:t.font,fontWeight:600},children:"DEFAULT"}),a.jsx("div",{style:{flex:1}}),a.jsx("button",{onClick:()=>_(P,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"})]}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:3},children:Object.entries(w??{}).filter(([H])=>H!=="driver"&&H!=="type").map(([H,W])=>a.jsxs("div",{style:{display:"flex",gap:6,alignItems:"baseline"},children:[a.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.fontMono,minWidth:70,flexShrink:0},children:H}),a.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(W)})]},H))})]},P)}),!d&&!c&&Object.keys(L).length===0&&a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{...M,marginTop:8},children:"Quick Connect"}),a.jsx("div",{style:{display:"grid",gap:6,marginBottom:12},children:AL.map(P=>a.jsxs("button",{onClick:async()=>{S(!0);try{const w={...L,[P.name]:P.config};await Z.saveConnections(w);const U=await Z.getConnections();r(U),s(!0);const x=await Z.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:[a.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:ca[P.config.driver]??t.accent,flexShrink:0}}),a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:12,fontWeight:600,color:t.textPrimary,fontFamily:t.font},children:P.label}),a.jsx("div",{style:{fontSize:10,color:t.textMuted,fontFamily:t.font},children:P.description})]})]},P.name))})]}),d?a.jsx(ME,{t,editName:O,setEditName:I,editDriver:p,setEditDriver:N,editFields:h,setEditFields:C,onSave:b,onCancel:g,saving:T,isNew:!0}):a.jsxs("button",{onClick:D,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:[a.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"Add Connection"]}),f&&a.jsx("div",{style:{fontSize:11,fontFamily:t.font,padding:"4px 10px",borderRadius:4,marginBottom:8,color:f.startsWith("Error")?t.error:t.success,background:f.startsWith("Error")?`${t.error}12`:`${t.success}12`},children:f}),a.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"}),i&&a.jsxs("div",{style:{fontSize:12,fontFamily:t.font,color:i.ok?t.success:t.error,background:i.ok?`${t.success}12`:`${t.error}12`,border:`1px solid ${i.ok?t.success:t.error}40`,borderRadius:6,padding:"7px 10px",marginBottom:12},children:[i.ok?"✓ ":"✗ ",i.message]}),a.jsx("div",{style:{...M,marginTop:4},children:"Supported Drivers"}),a.jsx("div",{style:{...F,display:"flex",flexDirection:"column",gap:4},children:Object.entries(fl).map(([P,w])=>a.jsxs("div",{style:{display:"flex",gap:8,alignItems:"baseline"},children:[a.jsx("code",{style:{fontSize:10,fontFamily:t.fontMono,color:ca[P]??t.textMuted,minWidth:80,flexShrink:0},children:P}),a.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font},children:w})]},P))})]})}function ME({t:e,editName:t,setEditName:n,editDriver:r,setEditDriver:o,editFields:s,setEditFields:i,onSave:l,onCancel:c,onDelete:E,saving:d,isNew:u}){const T=RL[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%"},f={fontSize:9,fontWeight:600,color:e.textMuted,fontFamily:e.font,letterSpacing:"0.05em",textTransform:"uppercase",marginBottom:2};return a.jsxs("div",{style:{background:e.cellBg,border:`1px solid ${e.accent}40`,borderRadius:7,padding:"10px 12px",marginBottom:10},children:[a.jsx("div",{style:{fontSize:11,fontWeight:600,color:e.accent,fontFamily:e.font,marginBottom:8},children:u?"New Connection":"Edit Connection"}),a.jsxs("div",{style:{marginBottom:6},children:[a.jsx("div",{style:f,children:"Name"}),a.jsx("input",{style:S,value:t,onChange:A=>n(A.target.value),placeholder:"e.g. production"})]}),a.jsxs("div",{style:{marginBottom:6},children:[a.jsx("div",{style:f,children:"Driver"}),a.jsx("select",{style:{...S,fontFamily:e.font},value:r,onChange:A=>{o(A.target.value),i({})},children:Object.entries(fl).map(([A,O])=>a.jsx("option",{value:A,children:O},A))})]}),T.map(A=>a.jsxs("div",{style:{marginBottom:6},children:[a.jsx("div",{style:f,children:A}),a.jsx("input",{style:S,type:A.toLowerCase().includes("password")||A.toLowerCase().includes("token")?"password":"text",value:s[A]??"",placeholder:A==="port"?"5432":A==="filepath"?":memory:":"",onChange:O=>i({...s,[A]:O.target.value})})]},A)),a.jsxs("div",{style:{display:"flex",gap:6,marginTop:8},children:[a.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"}),a.jsx("button",{onClick:c,style:{padding:"5px 12px",borderRadius:5,border:`1px solid ${e.btnBorder}`,background:"transparent",color:e.textSecondary,fontSize:11,fontFamily:e.font,cursor:"pointer"},children:"Cancel"}),E&&!u&&a.jsx("button",{onClick:E,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 mt({title:e,defaultOpen:t=!1,children:n,t:r}){const[o,s]=R.useState(t),[i,l]=R.useState(!1);return a.jsxs("div",{style:{borderBottom:`1px solid ${r.headerBorder}`},children:[a.jsxs("button",{onClick:()=>s(c=>!c),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{width:"100%",padding:"7px 12px",display:"flex",alignItems:"center",gap:6,background:i?r.sidebarItemHover:"transparent",border:"none",cursor:"pointer",textAlign:"left",transition:"background 0.1s"},children:[a.jsx("span",{style:{fontSize:9,color:r.textMuted,display:"inline-block",transition:"transform 0.15s",transform:o?"rotate(90deg)":"rotate(0deg)",lineHeight:1},children:"▶"}),a.jsx("span",{style:{fontSize:11,fontWeight:600,fontFamily:r.font,color:r.textSecondary,letterSpacing:"0.04em"},children:e})]}),o&&a.jsx("div",{style:{padding:"4px 12px 10px"},children:n})]})}function fL({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 a.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 a.jsxs("div",{style:{position:"relative",marginTop:6},children:[a.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}),a.jsx(fL,{code:e,t})]})}function bE({rows:e,t}){return a.jsx("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11,fontFamily:t.font,marginTop:6},children:a.jsx("tbody",{children:e.map(([n,r],o)=>a.jsxs("tr",{style:{borderBottom:`1px solid ${t.tableBorder}`},children:[a.jsx("td",{style:{padding:"5px 6px 5px 0",fontFamily:t.fontMono,fontSize:11,color:t.accent,whiteSpace:"nowrap",verticalAlign:"top",width:"45%"},children:n}),a.jsx("td",{style:{padding:"5px 0",color:t.textSecondary,verticalAlign:"top",lineHeight:1.5},children:r})]},o))})})}const IL=`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
|
+
}`,OL=`# 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`,NL=`# 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`,pL=`# 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`,hL=`# 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"`,CL=`{
|
|
139
|
+
"semanticLayer": {
|
|
140
|
+
"provider": "dql"
|
|
141
|
+
}
|
|
142
|
+
}`,mL=`{
|
|
143
|
+
"semanticLayer": {
|
|
144
|
+
"provider": "dbt",
|
|
145
|
+
"projectPath": "/path/to/your/dbt-project"
|
|
146
|
+
}
|
|
147
|
+
}`,LL=`{
|
|
148
|
+
"semanticLayer": {
|
|
149
|
+
"provider": "cubejs",
|
|
150
|
+
"projectPath": "/path/to/your/cube-project"
|
|
151
|
+
}
|
|
152
|
+
}`,_L=`{
|
|
153
|
+
"defaultConnection": {
|
|
154
|
+
"driver": "file",
|
|
155
|
+
"filepath": ":memory:"
|
|
156
|
+
}
|
|
157
|
+
}`,gL=`{
|
|
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
|
+
}`,xL=`{
|
|
169
|
+
"defaultConnection": {
|
|
170
|
+
"driver": "bigquery",
|
|
171
|
+
"project": "your-gcp-project-id",
|
|
172
|
+
"dataset": "analytics",
|
|
173
|
+
"keyFilename": "./service-account.json"
|
|
174
|
+
}
|
|
175
|
+
}`,yL=`{
|
|
176
|
+
"defaultConnection": {
|
|
177
|
+
"driver": "postgres",
|
|
178
|
+
"host": "localhost",
|
|
179
|
+
"port": 5432,
|
|
180
|
+
"database": "analytics",
|
|
181
|
+
"username": "your_user",
|
|
182
|
+
"password": "\${POSTGRES_PASSWORD}"
|
|
183
|
+
}
|
|
184
|
+
}`,DL=`-- 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`,PL=`{
|
|
197
|
+
"semanticLayer": {
|
|
198
|
+
"provider": "snowflake",
|
|
199
|
+
"projectPath": "MY_DATABASE"
|
|
200
|
+
}
|
|
201
|
+
}`;function ER({themeMode:e}){const t=ce[e];return a.jsxs("div",{style:{flex:1,overflowY:"auto",fontFamily:t.font},children:[a.jsx(mt,{title:"SQL Essentials",defaultOpen:!0,t,children:a.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`})}),a.jsx(mt,{title:"DuckDB Functions",defaultOpen:!1,t,children:a.jsx(bE,{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"]]})}),a.jsxs(mt,{title:"DQL Block Structure",defaultOpen:!0,t,children:[a.jsx(De,{t,code:IL}),a.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.6},children:["Run ",a.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql certify <file> --connection duckdb"})," to execute ",a.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"tests {}"})," assertions against live data. Use ",a.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"--skip-tests"})," to check governance fields only."]})]}),a.jsxs(mt,{title:"DQL Chart Types",defaultOpen:!1,t,children:[a.jsx(bE,{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)"]]}),a.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.6},children:["Set chart type inside the"," ",a.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:'visualization { chart = "pie"; x = label_col; y = value_col }'})," ","block."]})]}),a.jsxs(mt,{title:"Semantic Layer Usage",defaultOpen:!1,t,children:[a.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:6},children:["Primary workflow: open the ",a.jsx("strong",{children:"Semantic Layer"})," panel → Compose Query → pick metrics and dimensions → Compose SQL → + Insert as Cell. Advanced: use ",a.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"@metric(name)"})," and ",a.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"@dim(name)"})," refs directly in any SQL cell."]}),a.jsx(De,{t,code:DL})]}),a.jsxs(mt,{title:"Semantic Layer",defaultOpen:!1,t,children:[a.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"," ",a.jsx("strong",{style:{color:t.textPrimary},children:"Semantic Layer"})," sidebar panel."]}),a.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"10px 0 4px",letterSpacing:"0.03em"},children:"Directory Structure"}),a.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)`}),a.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:[a.jsx("strong",{style:{color:t.textPrimary},children:"Recommended:"})," For multi-table projects, use a ",a.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"cubes/"})," file — it keeps metrics, dimensions, and joins together. Use standalone ",a.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"metrics/"})," and ",a.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dimensions/"})," files only for simple single-table projects."]}),a.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Metric YAML"}),a.jsx(De,{t,code:OL}),a.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Dimension YAML"}),a.jsx(De,{t,code:NL}),a.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Hierarchy YAML"}),a.jsx(De,{t,code:pL}),a.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)"}),a.jsx(De,{t,code:hL})]}),a.jsxs(mt,{title:"Semantic Layer Providers",defaultOpen:!1,t,children:[a.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Add to your ",a.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"})," to connect a semantic layer provider."]}),a.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/)"}),a.jsx(De,{t,code:CL}),a.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)"}),a.jsx(De,{t,code:mL}),a.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 ",a.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dbt_project.yml"}),"). Reads ",a.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"semantic_models"})," and"," ",a.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"metrics"})," blocks (dbt 1.6+)."]}),a.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/)"}),a.jsx(De,{t,code:LL}),a.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"," ",a.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"cubes:"})," blocks from YAML schema files."]}),a.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)"}),a.jsx(De,{t,code:PL}),a.jsxs("div",{style:{marginTop:4,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Introspects Snowflake semantic views via"," ",a.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"SHOW SEMANTIC VIEWS"}),". Set ",a.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"projectPath"})," to your database name to scope discovery. Requires a Snowflake connection in ",a.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"defaultConnection"}),"."]})]}),a.jsxs(mt,{title:"Connection Setup",defaultOpen:!1,t,children:[a.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Configure ",a.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"defaultConnection"})," in"," ",a.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"}),"."]}),a.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)"}),a.jsx(De,{t,code:_L}),a.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Snowflake"}),a.jsx(De,{t,code:gL}),a.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"BigQuery"}),a.jsx(De,{t,code:xL}),a.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"PostgreSQL"}),a.jsx(De,{t,code:yL}),a.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Use ",a.jsxs("code",{style:{fontFamily:t.fontMono,fontSize:10},children:["$","${ENV_VAR}"]})," syntax for secrets. Run ",a.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dql doctor"})," to verify your connection."]})]}),a.jsxs(mt,{title:"Variable References",defaultOpen:!1,t,children:[a.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Use"," ",a.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"{{cell_name}}"})," ","to reference other cells:",a.jsxs("ul",{style:{margin:"6px 0 0",paddingLeft:18},children:[a.jsxs("li",{children:[a.jsx("strong",{children:"Param cell"})," → substituted as a SQL literal value"]}),a.jsxs("li",{children:[a.jsx("strong",{children:"SQL cell"})," → injected as a CTE"]})]})]}),a.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"},Sc={source_table:"TBL",dbt_model:"DBT",dbt_source:"SRC",block:"BLK",metric:"MET",dimension:"DIM",domain:"DOM",chart:"CHT",dashboard:"DASH"},Ii={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"},Ur={reads_from:"#8b949e",feeds_into:"#56d364",aggregates:"#388bfd",visualizes:"#f778ba",depends_on:"#ff7b72",contains:"#d2a8ff",crosses_domain:"#d2a8ff"},ML={reads_from:"reads from",feeds_into:"feeds into",aggregates:"aggregates into",visualizes:"visualizes",depends_on:"dbt depends on",contains:"contains",crosses_domain:"crosses domain"},bL={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},vE={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"},Ms=["source","transform","answer","consumption"];function Rc(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 dR({type:e}){const t=we[e]??"#8b949e";return a.jsx("span",{style:{color:t,fontSize:10,fontWeight:700,textTransform:"uppercase",minWidth:34},title:Ii[e]??e,children:Sc[e]??e.slice(0,4).toUpperCase()})}function vL({value:e,onChange:t,placeholder:n,t:r}){return a.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 a.jsxs("button",{onClick:n,style:{width:"100%",textAlign:"left",background:"transparent",border:"none",borderRadius:6,padding:"6px 8px",cursor:"pointer",color:t.textPrimary},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[a.jsx(dR,{type:e.type}),a.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},title:e.name,children:e.name})]}),(r||e.domain)&&a.jsx("div",{style:{marginLeft:40,marginTop:2,color:t.textMuted,fontSize:11},children:r??e.domain})]})}const UL=30,Ea=200;function Lt({title:e,nodes:t,t:n,onSelect:r}){const o=t.length>UL,[s,i]=R.useState(!o),[l,c]=R.useState(Ea);if(t.length===0)return null;const E=s?Math.min(l,t.length):0,d=Math.max(0,t.length-E);return a.jsxs("div",{style:{padding:"8px 0",borderTop:`1px solid ${n.headerBorder}`},children:[a.jsxs("button",{onClick:()=>i(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:[a.jsx("span",{style:{display:"inline-block",width:10},children:s?"▾":"▸"}),a.jsx("span",{children:e}),a.jsx("span",{style:{marginLeft:"auto",fontWeight:500},children:t.length})]}),s&&t.slice(0,E).map(u=>a.jsx(uR,{node:u,t:n,onClick:()=>r(u)},u.id)),s&&d>0&&a.jsxs("button",{onClick:()=>c(u=>u+Ea),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(Ea,d)," more (",d," hidden)"]})]})}function wL(){const{state:e,dispatch:t}=Te(),n=ce[e.themeMode],[r,o]=R.useState(!0),[s,i]=R.useState([]),[l,c]=R.useState([]),[E,d]=R.useState(""),[u,T]=R.useState([]),[S,f]=R.useState(null),[A,O]=R.useState(null),I=R.useCallback(async()=>{o(!0);const g=await Z.fetchLineage();i(g.nodes??[]),c(g.edges??[]),o(!1)},[]);R.useEffect(()=>{I()},[I]),R.useEffect(()=>{let g=!1;if(E.trim().length<2){T([]);return}return Z.searchLineage(E.trim()).then(b=>{g||T(b.matches??[])}),()=>{g=!0}},[E]);const p=R.useCallback(async g=>{const b=await Z.queryLineage({focus:g.id});f(b.focalNode??g),O(b.graph??{nodes:[],edges:[]}),t({type:"SET_LINEAGE_FOCUS",nodeId:g.id}),t({type:"SET_INSPECTOR_CONTEXT",context:{kind:"lineage-node",nodeId:g.id}}),e.lineageFullscreen||t({type:"TOGGLE_LINEAGE_FULLSCREEN"})},[t,e.lineageFullscreen]),N=R.useCallback(()=>{f(null),O(null),d(""),T([]),t({type:"SET_LINEAGE_FOCUS",nodeId:null})},[t]),[h,C]=R.useState("type"),m=R.useMemo(()=>({dashboards:s.filter(g=>g.type==="dashboard"),blocks:s.filter(g=>g.type==="block"),dbtModels:s.filter(g=>g.type==="dbt_model"),dbtSources:s.filter(g=>g.type==="dbt_source"),tables:s.filter(g=>g.type==="source_table"),domains:s.filter(g=>g.type==="domain")}),[s]),_=R.useMemo(()=>{const g={source:[],transform:[],answer:[],consumption:[]};for(const b of s){const y=Rc(b);g[y].push(b)}return g},[s]),D=R.useMemo(()=>{if(!S||!A)return{upstream:[],downstream:[]};const g=new Set(A.edges.filter(y=>y.target===S.id).map(y=>y.source)),b=new Set(A.edges.filter(y=>y.source===S.id).map(y=>y.target));return{upstream:A.nodes.filter(y=>g.has(y.id)),downstream:A.nodes.filter(y=>b.has(y.id))}},[A,S]);return r?a.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"Loading lineage..."}):s.length===0?a.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"No lineage data found yet. Run `dql compile` or add notebooks/blocks first."}):a.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[a.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[a.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"}),a.jsx(vL,{value:E,onChange:d,placeholder:"Search blocks, tables, dbt models, notebooks...",t:n}),a.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."})]}),a.jsxs("div",{style:{flex:1,overflow:"auto"},children:[E.trim().length>=2&&u.length>0&&a.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[a.jsx("div",{style:{color:n.textMuted,fontSize:11,fontWeight:700,textTransform:"uppercase",marginBottom:6},children:"Search Results"}),u.slice(0,8).map(g=>a.jsx(uR,{node:g.node,t:n,onClick:()=>p(g.node),secondary:g.node.domain},g.node.id))]}),S&&A&&a.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[a.jsx(dR,{type:S.type}),a.jsxs("div",{style:{flex:1,minWidth:0},children:[a.jsx("div",{style:{color:n.textPrimary,fontSize:13,fontWeight:700},children:S.name}),a.jsx("div",{style:{color:n.textMuted,fontSize:11},children:S.domain??Ii[S.type]??S.type})]}),a.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"})]}),a.jsxs("div",{style:{color:n.textMuted,fontSize:11,marginBottom:6},children:[A.nodes.length," node(s), ",A.edges.length," edge(s)"]}),a.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."}),a.jsx(Lt,{title:"Upstream",nodes:D.upstream,t:n,onSelect:p}),a.jsx(Lt,{title:"Downstream",nodes:D.downstream,t:n,onSelect:p})]}),!S&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{style:{padding:"6px 8px",display:"flex",gap:8,flexWrap:"wrap",borderBottom:`1px solid ${n.headerBorder}`},children:[Ms.map(g=>{const b=_[g].length;return b===0?null:a.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:10,color:n.textMuted},children:[a.jsx("span",{style:{width:8,height:8,borderRadius:2,background:bL[g],display:"inline-block"}}),vE[g],": ",b]},g)}),a.jsx("span",{style:{flex:1}}),a.jsxs("div",{style:{display:"flex",borderRadius:4,border:`1px solid ${n.headerBorder}`,overflow:"hidden"},children:[a.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"}),a.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"?a.jsxs(a.Fragment,{children:[a.jsx(Lt,{title:"Notebooks",nodes:m.dashboards,t:n,onSelect:p}),a.jsx(Lt,{title:"DQL Blocks",nodes:m.blocks,t:n,onSelect:p}),a.jsx(Lt,{title:"dbt Models",nodes:m.dbtModels,t:n,onSelect:p}),a.jsx(Lt,{title:"dbt Sources",nodes:m.dbtSources,t:n,onSelect:p}),a.jsx(Lt,{title:"Source Tables",nodes:m.tables,t:n,onSelect:p}),a.jsx(Lt,{title:"Business Domains",nodes:m.domains,t:n,onSelect:p})]}):a.jsx(a.Fragment,{children:Ms.map(g=>a.jsx(Lt,{title:vE[g],nodes:_[g],t:n,onSelect:p},g))})]})]})]})}const UE={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149",pending_recertification:"#db6d28"};function BL(){const{state:e,dispatch:t}=Te(),n=ce[e.themeMode],[r,o]=R.useState([]),[s,i]=R.useState(!0),[l,c]=R.useState(""),[E,d]=R.useState(""),[u,T]=R.useState("");R.useEffect(()=>{i(!0),Z.getBlockLibrary().then(p=>o(p.blocks)).finally(()=>i(!1))},[]);const S=[...new Set(r.map(p=>p.domain))].sort(),f=[...new Set(r.map(p=>p.status))].sort(),A=r.filter(p=>!(l&&!p.name.toLowerCase().includes(l.toLowerCase())&&!p.description.toLowerCase().includes(l.toLowerCase())||E&&p.domain!==E||u&&p.status!==u)),O=p=>{const N={name:p.path.split("/").pop()??p.name,path:p.path,type:"block",folder:"blocks"};e.files.some(h=>h.path===p.path)||t({type:"FILE_ADDED",file:N}),Z.openBlockStudio(p.path).then(h=>{t({type:"OPEN_BLOCK_STUDIO",file:N,payload:h})})},I={background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:4,color:n.textPrimary,fontSize:11,fontFamily:n.font,padding:"4px 6px",outline:"none"};return a.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[a.jsxs("div",{style:{padding:"10px 12px",borderBottom:`1px solid ${n.headerBorder}`,display:"flex",alignItems:"center",gap:8},children:[a.jsx("span",{style:{fontSize:12,fontWeight:600,color:n.textPrimary,fontFamily:n.font},children:"Blocks"}),a.jsx("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:A.length}),a.jsx("span",{style:{flex:1}}),a.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"}),a.jsx("button",{onClick:()=>{i(!0),Z.getBlockLibrary().then(p=>o(p.blocks)).finally(()=>i(!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"})]}),a.jsxs("div",{style:{padding:"8px 12px",borderBottom:`1px solid ${n.headerBorder}`,display:"flex",gap:6,flexWrap:"wrap"},children:[a.jsx("input",{value:l,onChange:p=>c(p.target.value),placeholder:"Search blocks...",style:{...I,flex:1,minWidth:100}}),a.jsxs("select",{value:E,onChange:p=>d(p.target.value),style:I,children:[a.jsx("option",{value:"",children:"All domains"}),S.map(p=>a.jsx("option",{value:p,children:p},p))]}),a.jsxs("select",{value:u,onChange:p=>T(p.target.value),style:I,children:[a.jsx("option",{value:"",children:"All statuses"}),f.map(p=>a.jsx("option",{value:p,children:p},p))]})]}),a.jsx("div",{style:{flex:1,overflowY:"auto"},children:s?a.jsx("div",{style:{padding:20,textAlign:"center",fontSize:12,color:n.textMuted,fontFamily:n.font},children:"Loading blocks..."}):A.length===0?a.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."}):A.map(p=>a.jsxs("button",{onClick:()=>O(p),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:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[a.jsx("span",{style:{fontSize:12,fontWeight:600,color:n.textPrimary,fontFamily:n.font},children:p.name}),a.jsx("span",{style:{fontSize:9,fontWeight:600,color:UE[p.status]??n.textMuted,background:`${UE[p.status]??n.textMuted}18`,padding:"1px 6px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em",fontFamily:n.font},children:p.status})]}),p.description&&a.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font,lineHeight:1.3,marginBottom:4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p.description}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:n.textMuted,fontFamily:n.font},children:[a.jsx("span",{style:{background:n.pillBg,padding:"1px 6px",borderRadius:4},children:p.domain}),p.owner&&a.jsxs("span",{children:["by ",p.owner]}),a.jsx("span",{style:{marginLeft:"auto"},children:new Date(p.lastModified).toLocaleDateString()})]})]},p.path))})]})}const FL={files:"Explorer",schema:"Schema",block_library:"Block Library",lineage:"Lineage",connection:"Connection",reference:"Quick Reference"};function GL({onOpenFile:e}){const{state:t,dispatch:n}=Te(),r=ce[t.themeMode],[o,s]=R.useState(!1),i=t.sidebarPanel;return a.jsxs("div",{style:{width:240,flexShrink:0,background:r.sidebarBg,borderRight:`1px solid ${r.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden"},children:[a.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:[a.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",color:r.textSecondary,fontFamily:r.font},children:FL[i??""]??""}),a.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:"‹"})]}),a.jsxs("div",{style:{flex:1,overflow:"hidden",display:"flex",flexDirection:"column"},children:[i==="files"&&a.jsx(sL,{onOpenFile:e}),i==="schema"&&a.jsx(EL,{}),i==="block_library"&&a.jsx(BL,{}),i==="lineage"&&a.jsx(wL,{}),i==="connection"&&a.jsx(cR,{}),i==="reference"&&a.jsx(ER,{themeMode:t.themeMode})]})]})}function HL(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 i=s[1],l=s[2].trim();r.push({id:xt(),type:"markdown",content:`# ${i}`,status:"idle"}),l&&r.push({id:xt(),type:"dql",name:i.toLowerCase().replace(/\s+/g,"_"),content:l,status:"idle"})}return r.length===0&&r.push({id:xt(),type:"dql",content:e.trim(),status:"idle"}),{title:n,cells:r}}catch{return{title:"Untitled Workbook",cells:[{id:xt(),type:"dql",content:e.trim(),status:"idle"}]}}}function YL(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(s=>({id:s.id||xt(),type:s.type||"sql",content:s.content??s.source??"",name:s.name||s.title,status:"idle",...s.paramConfig?{paramConfig:s.paramConfig}:{},...s.paramValue!==void 0?{paramValue:s.paramValue}:{},...s.chartConfig?{chartConfig:s.chartConfig}:{}}));return{title:r,cells:o}}catch{return{title:"Untitled",cells:[{id:xt(),type:"sql",content:e,status:"idle"}]}}}function kL(e,t,n){const r={version:1,title:e,metadata:{...n,modifiedAt:new Date().toISOString(),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}:{}}))};return JSON.stringify(r,null,2)}function WL(e,t){return e.endsWith(".dql")?HL(t):YL(t)}function VL(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(i=>`(${n.map(c=>{const E=i[c];return E==null?"NULL":typeof E=="number"?String(E):typeof E=="boolean"?E?"TRUE":"FALSE":`'${String(E).replace(/'/g,"''")}'`}).join(", ")})`).join(`,
|
|
245
|
+
`),s=n.map(i=>`"${i.replace(/"/g,'""')}"`).join(", ");return`${e} AS (
|
|
246
|
+
SELECT * FROM (VALUES
|
|
247
|
+
${o}
|
|
248
|
+
) AS _t(${s})
|
|
249
|
+
)`}function jL(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function $L(){const{state:e}=Te();return{substituteVariables:R.useCallback(n=>{var d;const r=/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g,o=[...n.matchAll(r)];if(o.length===0)return{sql:n,substituted:[]};const s=[],i=[];let l=n;const c=new Map,E=new Map;for(const u of e.cells){const T=(d=u.name)==null?void 0:d.trim();T&&(u.type==="param"?c.set(T,u):u.status==="success"&&u.result&&E.set(T,u.result))}for(const u of o){const T=u[1];if(c.has(T)){const S=c.get(T),f=S.paramConfig,A=S.paramValue??(f==null?void 0:f.defaultValue)??"",O=(f==null?void 0:f.paramType)??"text",I=jL(A,O);l=l.replace(u[0],I),s.push(T)}else E.has(T)&&(i.push(VL(T,E.get(T))),l=l.replace(u[0],`"${T}"`),s.push(T))}if(i.length===0&&s.length===0)return{sql:n,substituted:[]};if(i.length>0){const u=l.trimStart();/^WITH\s+/i.test(u)?l=l.replace(/^(\s*WITH\s+)/i,`$1${i.join(`,
|
|
250
|
+
`)},
|
|
251
|
+
`):l=`WITH ${i.join(`,
|
|
252
|
+
`)}
|
|
253
|
+
${l}`}return{sql:l,substituted:s}},[e.cells])}}function XL(e){var s;const t=e.match(/visualization\s*\{([^}]+)\}/is);if(!t)return;const n=t[1],r=i=>{var l;return(l=n.match(new RegExp(`\\b${i}\\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 KL(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 i=s.search(/\b(visualization|tests|block)\s*\{/i);return i>0&&(s=s.slice(0,i)),s=zL(s),s.trim()||null}return null}function zL(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 wE(e){const t=_n(e);return t?{name:t.name,domain:t.domain,owner:t.owner,description:t.description,blockType:t.blockType,tags:t.tags}:null}function da(e,t,n){const r=_n(e);if(!r){const s=n.replace(/"/g,'\\"'),i=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return i.test(e)?e.replace(i,`$1"${s}"`):Ac(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),Rr(o)}function TR(e,t){const n=_n(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 Rr({...n,name:t})}function JL(e,t){const n=_n(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}]`):Ac(e,` tags = [${r}]`)}return Rr({...n,tags:t})}function qL(e,t){const n=_n(e),r=t_(t);return n?Rr({...n,visualization:r}):/visualization\s*\{[\s\S]*?\n\s*\}/i.test(e)?e.replace(/visualization\s*\{[\s\S]*?\n\s*\}/i,r):Ac(e,` ${r.replace(/\n/g,`
|
|
254
|
+
`)}`,!0)}function QL(e,t){return e==="metric"?`@metric(${t})`:`@dim(${t})`}function ZL(e,t){const n=_n(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 i of r.metrics)o.add(i);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 Rr(r)}function e_(e,t){const n=_n(e);if(!n||n.blockType!=="custom")return`${e.trimEnd()}
|
|
255
|
+
${t}
|
|
256
|
+
`;const r=n.query.trimEnd(),o=r?`${r}
|
|
257
|
+
${t}`:t;return Rr({...n,query:o})}function _n(e){var s,i;if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=l=>{var c;return((c=e.match(new RegExp(`\\b${l}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:c[1])??""},n=((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:BE(e,"metrics"),dimensions:BE(e,"dimensions"),timeDimension:t("time_dimension"),granularity:t("granularity"),query:((i=o==null?void 0:o[1])==null?void 0:i.trim())??"",visualization:FE(e,"visualization"),tests:FE(e,"tests")}}function BE(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 FE(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 i=e[s];if(i==="{")r===0&&(o=s),r++;else if(i==="}"&&(r--,r===0&&o>=0))return e.slice(n.index,s+1).trim()}return""}function Rr(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(...n_(e.query.trim(),4)),t.push(' """')),e.visualization&&(t.push(""),t.push(...GE(e.visualization,2))),e.tests&&(t.push(""),t.push(...GE(e.tests,2))),t.push("}"),t.join(`
|
|
258
|
+
`)+`
|
|
259
|
+
`}function t_(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(`
|
|
260
|
+
`)}function n_(e,t){const n=" ".repeat(t);return(e?e.split(`
|
|
261
|
+
`):[""]).map(o=>`${n}${o}`)}function GE(e,t){const n=" ".repeat(t);return e.split(`
|
|
262
|
+
`).map(r=>`${n}${r.trimEnd()}`)}function et(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ac(e,t,n=!1){const r=e.trimEnd();if(!/^\s*block\s+"/i.test(r))return`${r}
|
|
263
|
+
${t}
|
|
264
|
+
`;const o=n?`
|
|
265
|
+
|
|
266
|
+
${t}
|
|
267
|
+
`:`
|
|
268
|
+
${t}`;return r.replace(/\n\}\s*$/,`${o}
|
|
269
|
+
}`)}const Lr=new Map;function r_(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?KL(t):null}function Oi(){const{state:e,dispatch:t}=Te(),{substituteVariables:n}=$L(),r=R.useCallback(async l=>{const c=e.cells.find(f=>f.id===l);if(!c)return;const E=r_(c);if(!E)return;if(c.type==="dql"){const f=XL(c.content);f&&JSON.stringify(f)!==JSON.stringify(c.chartConfig)&&t({type:"UPDATE_CELL",id:l,updates:{chartConfig:f}})}const{sql:d}=n(E),u=Date.now(),T=Lr.get(l);T&&T.abort();const S=new AbortController;Lr.set(l,S),t({type:"UPDATE_CELL",id:l,updates:{status:"running",error:void 0,result:void 0}});try{const f=await Z.executeQuery(d,S.signal),A=Date.now()-u,O=(c.executionCount??0)+1;t({type:"UPDATE_CELL",id:l,updates:{status:"success",result:{...f,executionTime:f.executionTime??A,rowCount:f.rowCount??f.rows.length},executionCount:O}}),t({type:"APPEND_QUERY_LOG",entry:{id:xt(),cellName:c.name??c.id,rows:f.rowCount??f.rows.length,time:f.executionTime??A,ts:new Date}}),setTimeout(()=>{t({type:"UPDATE_CELL",id:l,updates:{status:"idle"}})},2e3)}catch(f){if(S.signal.aborted){t({type:"UPDATE_CELL",id:l,updates:{status:"idle",error:void 0}});return}const A=Date.now()-u,O=f instanceof Error?f.message:String(f);t({type:"UPDATE_CELL",id:l,updates:{status:"error",error:O,executionCount:(c.executionCount??0)+1}}),t({type:"APPEND_QUERY_LOG",entry:{id:xt(),cellName:c.name??c.id,rows:0,time:A,ts:new Date,error:O}})}finally{Lr.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 c=`{{${l}}}`;for(const E of e.cells)E.type==="markdown"||E.type==="param"||E.content.includes(c)&&await r(E.id)},[e.cells,r]),i=R.useCallback(l=>{const c=Lr.get(l);c&&(c.abort(),Lr.delete(l)),t({type:"UPDATE_CELL",id:l,updates:{status:"idle"}})},[t]);return{executeCell:r,executeAll:o,executeDependents:s,cancelCell:i}}function Be(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function o_(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 s_(e){const t=e.split(`
|
|
270
|
+
`),n=[];let r=!1,o=!1;for(const s of t){const i=s;if(i.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(i));continue}if(i.startsWith("### ")){o&&(n.push("</ul>"),o=!1),n.push(`<h3>${Be(i.slice(4))}</h3>`);continue}if(i.startsWith("## ")){o&&(n.push("</ul>"),o=!1),n.push(`<h2>${Be(i.slice(3))}</h2>`);continue}if(i.startsWith("# ")){o&&(n.push("</ul>"),o=!1),n.push(`<h1>${Be(i.slice(2))}</h1>`);continue}if(i.startsWith("> ")){o&&(n.push("</ul>"),o=!1),n.push(`<blockquote><p>${Be(i.slice(2))}</p></blockquote>`);continue}if(i.startsWith("- ")||i.startsWith("* ")){o||(n.push("<ul>"),o=!0),n.push(`<li>${HE(i.slice(2))}</li>`);continue}if(o&&(n.push("</ul>"),o=!1),i.trim()===""){n.push("<br>");continue}n.push(`<p>${HE(i)}</p>`)}return o&&n.push("</ul>"),r&&n.push("</code></pre>"),n.join(`
|
|
271
|
+
`)}function HE(e){return Be(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>")}function i_(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(""),i=r.map(l=>`<tr>${t.map(E=>{const d=l[E],u=typeof d=="number",T=d==null?"—":String(d);return`<td${u?' class="num"':""}>${Be(T)}</td>`}).join("")}</tr>`).join("");return`
|
|
272
|
+
<div class="table-wrap">
|
|
273
|
+
<table>
|
|
274
|
+
<thead><tr>${s}</tr></thead>
|
|
275
|
+
<tbody>${i}</tbody>
|
|
276
|
+
</table>
|
|
277
|
+
${o?`<p class="truncated">Showing first 200 of ${n.length.toLocaleString()} rows</p>`:""}
|
|
278
|
+
</div>`}function a_(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 l_(e){const t=a_(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,i=140,l=440,c=n.length*(o+s)+40,E=n.map((d,u)=>{const T=u*(o+s)+20,S=Math.max(d.value/r*l,2);return`
|
|
279
|
+
<text x="${i-6}" y="${T+o/2+4}" text-anchor="end" font-size="11" fill="#8b949e">${Be(d.label.slice(0,20))}</text>
|
|
280
|
+
<rect x="${i}" y="${T}" width="${S}" height="${o}" rx="3" fill="#388bfd" />
|
|
281
|
+
<text x="${i+S+5}" y="${T+o/2+4}" font-size="11" fill="#e6edf3">${o_(d.value)}</text>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" width="${i+l+80}" height="${c}" style="max-width:100%">${E}</svg>`}function c_(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${s_(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 i="";if(r.result&&r.result.rows.length>0){const l=l_(r.result),c=i_(r.result);i=`<div class="cell-output">${`<div class="output-meta">${r.result.rows.length.toLocaleString()} rows${r.result.executionTime?` · ${r.result.executionTime}ms`:""}</div>`}${l??""}${l?"":c}</div>`}else r.error&&(i=`<div class="cell-error">⚠ ${Be(r.error)}</div>`);return`<section class="cell sql-cell">${o}${s}${i}</section>`}).join(`
|
|
282
|
+
`);return`<!DOCTYPE html>
|
|
283
|
+
<html lang="en">
|
|
284
|
+
<head>
|
|
285
|
+
<meta charset="UTF-8">
|
|
286
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
287
|
+
<title>${Be(e)}</title>
|
|
288
|
+
<style>
|
|
289
|
+
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
|
290
|
+
body {
|
|
291
|
+
font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
292
|
+
background: #0d1117; color: #e6edf3;
|
|
293
|
+
line-height: 1.6; padding: 0;
|
|
294
|
+
}
|
|
295
|
+
.page-header {
|
|
296
|
+
background: #161b22; border-bottom: 1px solid #21262d;
|
|
297
|
+
padding: 16px 32px; display: flex; align-items: center; gap: 12px;
|
|
298
|
+
}
|
|
299
|
+
.logo {
|
|
300
|
+
width: 28px; height: 28px; border-radius: 6px;
|
|
301
|
+
background: linear-gradient(135deg, #388bfd, #1f6feb);
|
|
302
|
+
display: flex; align-items: center; justify-content: center;
|
|
303
|
+
font-size: 10px; font-weight: 700; color: #fff;
|
|
304
|
+
font-family: monospace; letter-spacing: -0.5px; flex-shrink: 0;
|
|
305
|
+
}
|
|
306
|
+
.page-title { font-size: 18px; font-weight: 600; color: #e6edf3; }
|
|
307
|
+
.page-meta { font-size: 12px; color: #8b949e; margin-left: auto; }
|
|
308
|
+
.content { max-width: 900px; margin: 0 auto; padding: 32px 24px; display: flex; flex-direction: column; gap: 24px; }
|
|
309
|
+
.cell { border-radius: 8px; overflow: hidden; }
|
|
310
|
+
.md-cell { padding: 4px 0; }
|
|
311
|
+
.md-cell h1 { font-size: 26px; font-weight: 700; color: #e6edf3; margin: 0 0 12px; }
|
|
312
|
+
.md-cell h2 { font-size: 20px; font-weight: 600; color: #e6edf3; margin: 20px 0 10px; }
|
|
313
|
+
.md-cell h3 { font-size: 16px; font-weight: 600; color: #e6edf3; margin: 16px 0 8px; }
|
|
314
|
+
.md-cell p { color: #c9d1d9; margin-bottom: 8px; }
|
|
315
|
+
.md-cell ul { padding-left: 20px; color: #c9d1d9; margin-bottom: 8px; }
|
|
316
|
+
.md-cell code { background: #21262d; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 13px; }
|
|
317
|
+
.md-cell pre { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 14px; overflow-x: auto; margin-bottom: 8px; }
|
|
318
|
+
.md-cell pre code { background: none; padding: 0; }
|
|
319
|
+
.md-cell blockquote { border-left: 3px solid #388bfd; padding-left: 14px; color: #8b949e; }
|
|
320
|
+
.sql-cell { background: #161b22; border: 1px solid #30363d; }
|
|
321
|
+
.cell-header { display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-bottom: 1px solid #21262d; background: #1c2128; }
|
|
322
|
+
.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; }
|
|
323
|
+
.cell-name { font-size: 12px; color: #388bfd; font-family: monospace; }
|
|
324
|
+
.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; }
|
|
325
|
+
.cell-output { padding: 14px; }
|
|
326
|
+
.output-meta { font-size: 11px; color: #8b949e; margin-bottom: 10px; }
|
|
327
|
+
.table-wrap { overflow-x: auto; }
|
|
328
|
+
table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
|
329
|
+
th { background: #1c2128; color: #8b949e; font-weight: 600; text-align: left; padding: 7px 12px; border-bottom: 1px solid #30363d; white-space: nowrap; }
|
|
330
|
+
td { padding: 6px 12px; border-bottom: 1px solid #21262d; color: #e6edf3; }
|
|
331
|
+
td.num { text-align: right; font-family: monospace; }
|
|
332
|
+
tr:last-child td { border-bottom: none; }
|
|
333
|
+
.truncated { font-size: 11px; color: #8b949e; margin-top: 8px; }
|
|
334
|
+
.cell-error { padding: 12px 14px; background: #3d1a1a; border-top: 1px solid #f85149; color: #f85149; font-size: 13px; }
|
|
335
|
+
.exported-by { text-align: center; color: #484f58; font-size: 11px; padding: 40px 0 24px; }
|
|
336
|
+
</style>
|
|
337
|
+
</head>
|
|
338
|
+
<body>
|
|
339
|
+
<div class="page-header">
|
|
340
|
+
<div class="logo">DQL</div>
|
|
341
|
+
<span class="page-title">${Be(e)}</span>
|
|
342
|
+
<span class="page-meta">Exported ${new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}</span>
|
|
343
|
+
</div>
|
|
344
|
+
<div class="content">
|
|
345
|
+
${n}
|
|
346
|
+
</div>
|
|
347
|
+
<p class="exported-by">Built with DQL Notebook</p>
|
|
348
|
+
</body>
|
|
349
|
+
</html>`}function E_(e,t){const n=c_(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 d_(e,t){var s,i;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 c=`Markdown ${o}`;n.push(""),n.push(` page "${c}" {`);const E=l.content.split(`
|
|
350
|
+
`);for(const d of E)n.push(` // ${d}`);n.push(" }")}else if(l.type==="sql"){r++;const c=((s=l.name)==null?void 0:s.trim())||`Query ${r}`;n.push(""),n.push(` page "${c}" {`);const d=l.content.trim().split(`
|
|
351
|
+
`).map(u=>` ${u}`).join(`
|
|
352
|
+
`);n.push(" chart.table("),n.push(d+","),n.push(` title = "${c}"`),n.push(" )"),n.push(" }")}else if(l.type==="dql"){r++;const c=((i=l.name)==null?void 0:i.trim())||`Query ${r}`;n.push(""),n.push(` page "${c}" {`);const E=l.content.trim().split(`
|
|
353
|
+
`);for(const d of E)n.push(` ${d}`);n.push(" }")}}return n.push("}"),n.join(`
|
|
354
|
+
`)}function u_(e,t){const n=d_(e,t),r=new Blob([n],{type:"text/plain;charset=utf-8"}),o=URL.createObjectURL(r),s=document.createElement("a"),i=e.replace(/[^a-zA-Z0-9_-]/g,"_")+".dql";s.href=o,s.download=i,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(o)}function T_({t:e}){return a.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:a.jsx("span",{style:{color:"#ffffff",fontSize:10,fontWeight:700,fontFamily:e.fontMono,letterSpacing:"-0.5px"},children:"DQL"})})}function S_(){const{state:e,dispatch:t}=Te(),n=ce[e.themeMode],{executeAll:r}=Oi(),[o,s]=R.useState(!1),[i,l]=R.useState(""),[c,E]=R.useState(!1),[d,u]=R.useState(!1),[T,S]=R.useState(!1),[f,A]=R.useState(!1),[O,I]=R.useState(!1),[p,N]=R.useState(!1),h=R.useRef(null),C=R.useRef(null),m=e.mainView==="block_studio"?e.blockStudioDirty:e.notebookDirty,_=e.mainView==="notebook",D=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(!p)return;function L(v){h.current&&!h.current.contains(v.target)&&N(!1)}return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},[p]);const g=()=>{l(e.notebookTitle),s(!0)},b=()=>{s(!1),i.trim()&&i!==e.notebookTitle&&(e.mainView==="block_studio"&&e.blockStudioMetadata?(t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,name:i.trim()}}),t({type:"SET_BLOCK_STUDIO_DRAFT",draft:TR(e.blockStudioDraft,i.trim())})):t({type:"SET_NOTEBOOK_DIRTY",dirty:!0}))},y=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 v=await Z.saveBlockStudio({path:e.activeBlockPath,source:e.blockStudioDraft,metadata:{name:e.blockStudioMetadata.name,domain:e.blockStudioMetadata.domain,description:e.blockStudioMetadata.description,owner:e.blockStudioMetadata.owner,tags:e.blockStudioMetadata.tags}});t({type:"OPEN_BLOCK_STUDIO",file:{name:`${v.metadata.name}.dql`,path:v.path,type:"block",folder:"blocks"},payload:v}),e.files.some(P=>P.path===v.path)||t({type:"FILE_ADDED",file:{name:`${v.metadata.name}.dql`,path:v.path,type:"block",folder:"blocks"}})}else{const v=e.activeFile.type==="block"?((L=e.cells[0])==null?void 0:L.content)??"":kL(e.notebookTitle,e.cells);await Z.saveNotebook(e.activeFile.path,v),t({type:"SET_NOTEBOOK_DIRTY",dirty:!1})}E(!0),setTimeout(()=>E(!1),2e3)}catch(v){console.error("Save failed:",v)}finally{t({type:"SET_SAVING",saving:!1})}}},[e.activeFile,e.activeBlockPath,e.blockStudioDraft,e.blockStudioMetadata,e.files,e.mainView,e.notebookTitle,e.cells,t]);R.useEffect(()=>{const L=v=>{(v.metaKey||v.ctrlKey)&&v.key==="s"&&(v.preventDefault(),y())};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[y]),R.useEffect(()=>{if(!e.autoSave||!m||!e.activeFile)return;const L=setTimeout(()=>{y()},2e3);return()=>clearTimeout(L)},[e.autoSave,m,e.activeFile,e.cells,e.blockStudioDraft,y]);const M=()=>{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 a.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:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[a.jsx(T_,{t:n}),a.jsx("div",{style:{width:1,height:20,background:n.headerBorder,flexShrink:0}}),e.activeFile&&a.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?a.jsx("input",{ref:C,value:i,onChange:L=>l(L.target.value),onBlur:b,onKeyDown:L=>{L.key==="Enter"&&b(),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}}):a.jsxs("span",{onClick:g,title:"Click to rename",style:{color:n.textPrimary,fontSize:13,fontWeight:500,fontFamily:n.font,cursor:"text",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",padding:"2px 4px",borderRadius:4,border:"1px solid transparent"},children:[D,m&&a.jsx("span",{style:{color:n.textMuted,marginLeft:4},children:"●"})]}):a.jsx("span",{style:{color:n.textSecondary,fontSize:13,fontFamily:n.font,padding:"2px 4px"},children:D})]}),a.jsx("div",{style:{flex:1}}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[a.jsxs("button",{onClick:_?r:void 0,disabled:!e.activeFile||!_,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...F,background:(d&&e.activeFile,n.accent),color:"#ffffff",border:`1px solid ${n.accent}`,opacity:!e.activeFile||!_?.4:d?.9:1},children:[a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:a.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})}),"Run All"]}),a.jsx("div",{style:{width:1,height:20,background:n.headerBorder}}),a.jsx("button",{onClick:M,onMouseEnter:()=>A(!0),onMouseLeave:()=>A(!1),title:e.themeMode==="dark"?"Switch to light mode":"Switch to dark mode",style:{...F,background:f?n.btnHover:n.btnBg,color:n.textSecondary,padding:"0 8px",fontSize:14},children:e.themeMode==="dark"?"☀":"☾"}),a.jsx("button",{onClick:y,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:c?n.success:n.textSecondary,opacity:e.activeFile?1:.4},children:e.savingFile?a.jsxs(a.Fragment,{children:[a.jsx(R_,{}),"Saving…"]}):c?a.jsx(a.Fragment,{children:"✓ Saved"}):a.jsx(a.Fragment,{children:"Save"})}),a.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"}),a.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:[a.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:e.dashboardMode?a.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"}):a.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"]}),a.jsx("div",{style:{width:1,height:20,background:n.headerBorder}}),a.jsxs("div",{ref:h,style:{position:"relative"},children:[a.jsxs("button",{onClick:()=>{e.activeFile&&N(L=>!L)},disabled:!e.activeFile,onMouseEnter:()=>I(!0),onMouseLeave:()=>I(!1),title:"Export options",style:{...F,background:(O||p)&&e.activeFile?n.btnHover:n.btnBg,color:n.textSecondary,opacity:e.activeFile?1:.4},children:[a.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:[a.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"}),a.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",a.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"currentColor",style:{marginLeft:1},children:a.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),p&&a.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:[a.jsx(YE,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{E_(e.notebookTitle||"dashboard",e.cells),N(!1)}}),a.jsx(YE,{label:"Export .dql",description:"DQL workbook file",t:n,onClick:()=>{u_(e.notebookTitle||"notebook",e.cells),N(!1)}})]})]})]})]})}function YE({label:e,description:t,t:n,onClick:r}){const[o,s]=R.useState(!1);return a.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:[a.jsx("span",{style:{fontSize:12,fontWeight:500,color:n.textPrimary,fontFamily:n.font},children:e}),a.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:t})]})}function R_(){return a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",style:{animation:"spin 0.8s linear infinite"},children:[a.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"}),a.jsx("circle",{cx:"6",cy:"6",r:"4.5",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"14 7"})]})}function A_(e){return e.toTimeString().slice(0,8)}function f_(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function I_(){const{state:e,dispatch:t}=Te(),n=ce[e.themeMode],[r,o]=R.useState(!1),s=e.queryLog.filter(l=>l.error),i=l=>t({type:"SET_DEV_PANEL_TAB",tab:l});return a.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&&a.jsxs(a.Fragment,{children:[a.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=>a.jsx(O_,{label:l==="errors"?`Errors${s.length>0?` (${s.length})`:""}`:`Logs (${e.queryLog.length})`,active:e.devPanelTab===l,onClick:()=>i(l),t:n},l)),a.jsx("div",{style:{flex:1}}),a.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"})]}),a.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[e.devPanelTab==="logs"&&(e.queryLog.length===0?a.jsx(kE,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(l=>a.jsx(WE,{entry:l,t:n},l.id))),e.devPanelTab==="errors"&&(s.length===0?a.jsx(kE,{t:n,message:"No errors."}):[...s].reverse().map(l=>a.jsx(WE,{entry:l,t:n},l.id)))]})]}),a.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:[a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:a.jsx("path",{d:e.devPanelOpen?"M1 7l4-4 4 4":"M1 3l4 4 4-4",strokeWidth:"1.5",stroke:"currentColor",fill:"none"})}),"Dev"]})]})}function O_({label:e,active:t,onClick:n,t:r}){const[o,s]=R.useState(!1);return a.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 kE({t:e,message:t}){return a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:e.textMuted,fontSize:12,fontFamily:e.font,fontStyle:"italic"},children:t})}function WE({entry:e,t}){return a.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:[a.jsx("span",{style:{color:t.textMuted,flexShrink:0},children:A_(e.ts)}),a.jsx("span",{style:{flexShrink:0,color:t.textPrimary,maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.cellName}),e.error?a.jsx("span",{style:{color:t.error,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.error}):a.jsxs(a.Fragment,{children:[a.jsxs("span",{style:{color:t.textMuted},children:[e.rows.toLocaleString()," rows"]}),a.jsx("span",{style:{color:t.textMuted},children:f_(e.time)})]})]})}function N_({onOpenFile:e}){const{state:t,dispatch:n}=Te(),r=ce[t.themeMode],o=t.files.slice(0,3);return a.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",background:r.appBg,padding:40,overflow:"auto"},children:a.jsxs("div",{style:{maxWidth:720,width:"100%",display:"flex",flexDirection:"column",alignItems:"center",gap:48},children:[a.jsxs("div",{style:{textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[a.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:a.jsx("span",{style:{color:"#fff",fontSize:26,fontWeight:800,fontFamily:r.fontMono,letterSpacing:"-1px"},children:"DQL"})}),a.jsxs("div",{children:[a.jsx("h1",{style:{fontSize:32,fontWeight:700,color:r.textPrimary,fontFamily:r.font,marginBottom:8,letterSpacing:"-0.5px"},children:"DQL Notebook"}),a.jsx("p",{style:{fontSize:15,color:r.textSecondary,fontFamily:r.font,letterSpacing:"0.02em"},children:"Analytics as Code"})]})]}),a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16,width:"100%"},children:[a.jsx(VE,{title:"New Notebook",description:"Start a fresh analysis with an empty notebook.",icon:a.jsx(C_,{}),accent:r.accent,onClick:()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}),t:r}),a.jsx(p_,{recentFiles:o,onOpenFile:e,t:r}),a.jsx(VE,{title:"New Block",description:"Create a reusable SQL block file.",icon:a.jsx(L_,{}),accent:"#e3b341",onClick:()=>n({type:"OPEN_NEW_BLOCK_MODAL"}),t:r})]}),a.jsxs("div",{style:{width:"100%",borderRadius:10,border:`1px solid ${r.cellBorder}`,padding:"16px 20px",background:r.cellBg},children:[a.jsx("div",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.08em",textTransform:"uppercase",color:r.textMuted,fontFamily:r.font,marginBottom:12},children:"Quick Tips"}),a.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,i])=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[a.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}),a.jsx("span",{style:{fontSize:12,color:r.textMuted,fontFamily:r.font},children:i})]},s))})]})]})})}function VE({title:e,description:t,icon:n,accent:r,onClick:o,t:s}){const[i,l]=R.useState(!1);return a.jsxs("button",{onClick:o,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{background:i?s.cellBg:"transparent",border:`1px solid ${i?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:i?`0 0 0 1px ${r}30, 0 4px 16px rgba(0,0,0,0.15)`:"none"},children:[a.jsx("div",{style:{width:36,height:36,borderRadius:8,background:`${r}18`,display:"flex",alignItems:"center",justifyContent:"center",color:r},children:n}),a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:13,fontWeight:600,color:s.textPrimary,fontFamily:s.font,marginBottom:4},children:e}),a.jsx("div",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font,lineHeight:1.5},children:t})]})]})}function p_({recentFiles:e,onOpenFile:t,t:n}){const[r,o]=R.useState(!1);return a.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:[a.jsx("div",{style:{width:36,height:36,borderRadius:8,background:`${n.warning}18`,display:"flex",alignItems:"center",justifyContent:"center",color:n.warning},children:a.jsx(m_,{})}),a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,fontFamily:n.font,marginBottom:8},children:"Open Recent"}),e.length===0?a.jsx("div",{style:{fontSize:12,color:n.textMuted,fontFamily:n.font,fontStyle:"italic"},children:"No recent files."}):a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:e.map(s=>a.jsx(h_,{file:s,onClick:()=>t(s),t:n},s.path))})]})]})}function h_({file:e,onClick:t,t:n}){const[r,o]=R.useState(!1);return a.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 C_(){return a.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 m_(){return a.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 L_(){return a.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 jE=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class Vr{constructor(t,n,r=0,o=t.length,s,i){this.test=i,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(jE(l)):jE,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 gI(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=bI(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=xI(t);let o=this.normalize(n);if(o.length)for(let s=0,i=r;;s++){let l=o.charCodeAt(s),c=this.match(l,i,this.bufferPos+this.bufferStart);if(s==o.length-1){if(c)return this.value=c,this;break}i==r&&s<n.length&&n.charCodeAt(s)==l&&i++}}}match(t,n,r){let o=null;for(let s=0;s<this.matches.length;s+=2){let i=this.matches[s],l=!1;this.query.charCodeAt(i)==t&&(i==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"&&(Vr.prototype[Symbol.iterator]=function(){return this});const SR={from:-1,to:-1,match:/.*/.exec("")},fc="gm"+(/x/.unicode==null?"":"u");class RR{constructor(t,n,r,o=0,s=t.length){if(this.text=t,this.to=s,this.curLine="",this.done=!1,this.value=SR,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new AR(t,n,r,o,s);this.re=new RegExp(n,fc+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.iter=t.iter();let i=t.lineAt(o);this.curLineStart=i.from,this.matchPos=bs(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=bs(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 ua=new WeakMap;class Kn{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let o=ua.get(t);if(!o||o.from>=r||o.to<=n){let l=new Kn(n,t.sliceString(n,r));return ua.set(t,l),l}if(o.from==n&&o.to==r)return o;let{text:s,from:i}=o;return i>n&&(s=t.sliceString(n,i)+s,i=n),o.to<r&&(s+=t.sliceString(o.to,r)),ua.set(t,new Kn(i,s)),new Kn(n,s.slice(n-i,r-i))}}class AR{constructor(t,n,r,o,s){this.text=t,this.to=s,this.done=!1,this.value=SR,this.matchPos=bs(t,o),this.re=new RegExp(n,fc+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=Kn.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=bs(this.text,o+(r==o?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Kn.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(RR.prototype[Symbol.iterator]=AR.prototype[Symbol.iterator]=function(){return this});function __(e){try{return new RegExp(e,fc),!0}catch{return!1}}function bs(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 g_=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:o}=mI(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 i=s&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(s.elements.line.value);if(!i){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,E,d,u]=i,T=d?+d.slice(1):0,S=E?+E:l.number;if(E&&u){let O=S/100;c&&(O=O*(c=="-"?-1:1)+l.number/t.doc.lines),S=Math.round(t.doc.lines*O)}else E&&c&&(S=S*(c=="-"?-1:1)+l.number);let f=t.doc.line(Math.max(1,Math.min(t.doc.lines,S))),A=it.cursor(f.from+Math.max(0,Math.min(T,f.length)));e.dispatch({effects:[r,be.scrollIntoView(A.from,{y:"center"})],selection:A})}),!0},x_=({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 y_(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 i=!1,l=new Vr(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new Vr(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),i=!0}else{if(i&&r.some(c=>c.from==l.value.from))continue;if(s){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const D_=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(s=>s.from===s.to))return x_({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=y_(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},gn=yI.define({combine(e){return DI(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new j_(t),scrollToMatch:t=>be.scrollIntoView(t)})}});function P_(e){return e?[gn.of(e),Ol]:Ol}class fR{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||__(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"?`
|
|
355
|
+
`: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 B_(this):new v_(this)}getCursor(t,n=0,r){let o=t.doc?t:ET.create({doc:t});return r==null&&(r=o.doc.length),this.regexp?Wn(this,o,n,r):kn(this,o,n,r)}}class IR{constructor(t){this.spec=t}}function M_(e,t,n){return(r,o,s,i)=>{if(n&&!n(r,o,s,i))return!1;let l=r>=i&&o<=i+s.length?s.slice(r-i,o-i):t.doc.sliceString(r,o);return e(l,t,r,o)}}function kn(e,t,n,r){let o;return e.wholeWord&&(o=b_(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(o=M_(e.test,t,o)),new Vr(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:s=>s.toLowerCase(),o)}function b_(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(vs(o,n-s))!=Xt.Word||t(Us(o,n-s))!=Xt.Word)&&(t(Us(o,r-s))!=Xt.Word||t(vs(o,r-s))!=Xt.Word))}class v_ extends IR{constructor(t){super(t)}nextMatch(t,n,r){let o=kn(this.spec,t,r,t.doc.length).nextOverlapping();if(o.done){let s=Math.min(t.doc.length,n+this.spec.unquoted.length);o=kn(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),i=kn(this.spec,t,s,o),l=null;for(;!i.nextOverlapping().done;)l=i.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=kn(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=kn(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 U_(e,t,n){return(r,o,s)=>(!n||n(r,o,s))&&e(s[0],t,r,o)}function Wn(e,t,n,r){let o;return e.wholeWord&&(o=w_(t.charCategorizer(t.selection.main.head))),e.test&&(o=U_(e.test,t,o)),new RR(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:o},n,r)}function vs(e,t){return e.slice(dT(e,t,!1),t)}function Us(e,t){return e.slice(t,dT(e,t))}function w_(e){return(t,n,r)=>!r[0].length||(e(vs(r.input,r.index))!=Xt.Word||e(Us(r.input,r.index))!=Xt.Word)&&(e(Us(r.input,r.index+r[0].length))!=Xt.Word||e(vs(r.input,r.index+r[0].length))!=Xt.Word)}class B_ extends IR{nextMatch(t,n,r){let o=Wn(this.spec,t,r,t.doc.length).next();return o.done&&(o=Wn(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),i=Wn(this.spec,t,s,r),l=null;for(;!i.next().done;)l=i.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=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-250),Math.min(r+250,t.doc.length));for(;!s.next().done;)o(s.value.from,s.value.to)}}const jr=ni.define(),Ic=ni.define(),Kt=cT.define({create(e){return new Ta(Il(e).create(),null)},update(e,t){for(let n of t.effects)n.is(jr)?e=new Ta(n.value.create(),e.panel):n.is(Ic)&&(e=new Ta(e.query,n.value?Oc:null));return e},provide:e=>LI.from(e,t=>t.panel)});class Ta{constructor(t,n){this.query=t,this.panel=n}}const F_=un.mark({class:"cm-searchMatch"}),G_=un.mark({class:"cm-searchMatch cm-searchMatch-selected"}),H_=PI.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 MI;for(let o=0,s=n.visibleRanges,i=s.length;o<i;o++){let{from:l,to:c}=s[o];for(;o<i-1&&c>s[o+1].from-500;)c=s[++o].to;e.highlight(n.state,l,c,(E,d)=>{let u=n.state.selection.ranges.some(T=>T.from==E&&T.to==d);r.add(E,d,u?G_:F_)})}return r.finish()}},{decorations:e=>e.decorations});function Eo(e){return t=>{let n=t.state.field(Kt,!1);return n&&n.query.spec.valid?e(t,n):hR(t)}}const ws=Eo((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(gn);return e.dispatch({selection:o,effects:[Nc(e,r),s.scrollToMatch(o.main,e)],userEvent:"select.search"}),pR(e),!0}),Bs=Eo((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),i=e.state.facet(gn);return e.dispatch({selection:s,effects:[Nc(e,o),i.scrollToMatch(s.main,e)],userEvent:"select.search"}),pR(e),!0}),Y_=Eo((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)}),k_=({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=[],i=0;for(let l=new Vr(e.doc,e.sliceDoc(r,o));!l.next().done;){if(s.length>1e3)return!1;l.value.from==r&&(i=s.length),s.push(it.range(l.value.from,l.value.to))}return t(e.update({selection:it.create(s,i),userEvent:"select.search.matches"})),!0},$E=Eo((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 i=s,l=[],c,E,d=[];i.from==r&&i.to==o&&(E=n.toText(t.getReplacement(i)),l.push({from:i.from,to:i.to,insert:E}),i=t.nextMatch(n,i.from,i.to),d.push(be.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+".")));let u=e.state.changes(l);return i&&(c=it.single(i.from,i.to).map(u),d.push(Nc(e,i)),d.push(n.facet(gn).scrollToMatch(c.main,e))),e.dispatch({changes:u,selection:c,effects:d,userEvent:"input.replace"}),!0}),W_=Eo((e,{query:t})=>{if(e.state.readOnly)return!1;let n=t.matchAll(e.state,1e9).map(o=>{let{from:s,to:i}=o;return{from:s,to:i,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 Oc(e){return e.state.facet(gn).createPanel(e)}function Il(e,t){var n,r,o,s,i;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let E=e.facet(gn);return new fR({search:((n=t==null?void 0:t.literal)!==null&&n!==void 0?n:E.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t==null?void 0:t.caseSensitive)!==null&&r!==void 0?r:E.caseSensitive,literal:(o=t==null?void 0:t.literal)!==null&&o!==void 0?o:E.literal,regexp:(s=t==null?void 0:t.regexp)!==null&&s!==void 0?s:E.regexp,wholeWord:(i=t==null?void 0:t.wholeWord)!==null&&i!==void 0?i:E.wholeWord})}function NR(e){let t=lT(e,Oc);return t&&t.dom.querySelector("[main-field]")}function pR(e){let t=NR(e);t&&t==e.root.activeElement&&t.select()}const hR=e=>{let t=e.state.field(Kt,!1);if(t&&t.panel){let n=NR(e);if(n&&n!=e.root.activeElement){let r=Il(e.state,t.query.spec);r.valid&&e.dispatch({effects:jr.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Ic.of(!0),t?jr.of(Il(e.state,t.query.spec)):ni.appendConfig.of(Ol)]});return!0},CR=e=>{let t=e.state.field(Kt,!1);if(!t||!t.panel)return!1;let n=lT(e,Oc);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Ic.of(!1)}),!0},V_=[{key:"Mod-f",run:hR,scope:"editor search-panel"},{key:"F3",run:ws,shift:Bs,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:ws,shift:Bs,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:CR,scope:"editor search-panel"},{key:"Mod-Shift-l",run:k_},{key:"Mod-Alt-g",run:g_},{key:"Mod-d",run:D_,preventDefault:!0}];class j_{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:ke(t,"Find"),"aria-label":ke(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:ke(t,"Replace"),"aria-label":ke(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,i){return ze("button",{class:"cm-button",name:o,onclick:s,type:"button"},i)}this.dom=ze("div",{onkeydown:o=>this.keydown(o),class:"cm-search"},[this.searchField,r("next",()=>ws(t),[ke(t,"next")]),r("prev",()=>Bs(t),[ke(t,"previous")]),r("select",()=>Y_(t),[ke(t,"all")]),ze("label",null,[this.caseField,ke(t,"match case")]),ze("label",null,[this.reField,ke(t,"regexp")]),ze("label",null,[this.wordField,ke(t,"by word")]),...t.state.readOnly?[]:[ze("br"),this.replaceField,r("replace",()=>$E(t),[ke(t,"replace")]),r("replaceAll",()=>W_(t),[ke(t,"replace all")])],ze("button",{name:"close",onclick:()=>CR(t),"aria-label":ke(t,"close"),type:"button"},["×"])])}commit(){let t=new fR({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:jr.of(t)}))}keydown(t){vI(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?Bs:ws)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),$E(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(jr)&&!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(gn).top}}function ke(e,t){return e.state.phrase(t)}const Jo=30,qo=/[\s\.,:;?!]/;function Nc(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-Jo),i=Math.min(o,n+Jo),l=e.state.sliceDoc(s,i);if(s!=r.from){for(let c=0;c<Jo;c++)if(!qo.test(l[c+1])&&qo.test(l[c])){l=l.slice(c);break}}if(i!=o){for(let c=l.length-1;c>l.length-Jo;c--)if(!qo.test(l[c-1])&&qo.test(l[c])){l=l.slice(0,c);break}}return be.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const $_=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"}}),Ol=[Kt,_I.low(H_),$_],X_=3e4,Fs="application/dql-semantic-ref";let Qo=[],XE=0,$r=null;function K_(e){Z.trackUsage(e),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:e}}))}async function KE(){if(Date.now()<XE&&Qo.length>0)return Qo;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 Qo=Array.isArray(t.completions)?t.completions:[],XE=Date.now()+X_,Qo}function mR(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 z_(e){$r=e}function J_(e){$r===e&&($r=null)}function q_(e){return $r?(mR($r,e),!0):!1}function Q_(e,t,n){const r=n?e.posAtCoords(n)??e.state.selection.main.from:e.state.selection.main.from;mR(e,t,r)}function zE(e,t,n){return{label:e.name,detail:e.type==="metric"?"@metric":"@dim",type:e.type==="metric"?"function":"variable",info:`${e.label}${e.description?`
|
|
356
|
+
${e.description}`:""}${e.sql?`
|
|
357
|
+
${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}}),K_(e.name)}}}function Z_(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 eg=async e=>{const{state:t,pos:n}=e,r=t.sliceDoc(Math.max(0,n-120),n),o=/@metric\(([^)]*)$/i.exec(r);if(o){const l=o[1].trim().toLowerCase(),c=n-o[1].length,E=(await KE()).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:c,options:E.map(d=>zE(d,c,n)),validFor:/^[\w-]*$/}}const s=/@dim\(([^)]*)$/i.exec(r);if(s){const l=s[1].trim().toLowerCase(),c=n-s[1].length,E=(await KE()).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:c,options:E.map(d=>zE(d,c,n)),validFor:/^[\w-]*$/}}const i=/@([md][a-z_]*)?$/i.exec(r);return i?Z_(n-i[0].length):(e.explicit,null)};function LR(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 tg(e){const t=e.match(/LINE\s+(\d+)/i);if(t){const o=parseInt(t[1],10),s=e.match(/\n(\s*)\^/),i=s?s[1].length+1:1;return{line:o,col:i}}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 Ss=ni.define(),ng=cT.define({create(){return un.none},update(e,t){for(const n of t.effects)if(n.is(Ss)){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)}),rg=be.baseTheme({".cm-sql-error":{textDecoration:"underline wavy #f85149",textUnderlineOffset:"3px",background:"rgba(248, 81, 73, 0.08)"}}),og=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}),sg=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 pc({value:e,onChange:t,onRun:n,themeMode:r,autoFocus:o,schema:s,errorMessage:i,editorRef:l}){const c=ce[r],E=R.useRef(null),d=R.useRef(null),[u,T]=R.useState(!1),S=R.useRef(n),f=R.useRef(t),A=R.useRef(new UI);return S.current=n,f.current=t,R.useEffect(()=>{l&&(l.current={undo:()=>{d.current&&BI(d.current)},redo:()=>{d.current&&wI(d.current)},resetTo:O=>{const I=d.current;I&&I.dispatch({changes:{from:0,to:I.state.doc.length,insert:O}})}})}),R.useEffect(()=>{if(!E.current)return;const O=FI.of([{key:"Shift-Enter",run:()=>(S.current(),!0)},{key:"Ctrl-Enter",mac:"Cmd-Enter",run:()=>(S.current(),!0)},{key:"Ctrl-/",mac:"Cmd-/",run:GI},HI,...YI,...kI,...WI,...V_,...VI,...jI]),I=be.updateListener.of(D=>{D.docChanged&&f.current(D.state.doc.toString())}),p=be.domEventHandlers({focus:(D,g)=>{z_(g)},blur:(D,g)=>{J_(g)}}),N=be.theme({"&":{background:c.editorBg,fontFamily:c.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?ko({schema:s,upperCaseKeywords:!1}):ko({upperCaseKeywords:!1}),C=[O,I,p,N,A.current.of(h),XI({closeOnBlur:!1,override:[eg]}),KI(),zI(),JI(),qI(),QI(),ZI(),eO(),tO(),be.lineWrapping,P_({top:!0}),ng,rg,...r==="dark"?[$I,sg]:[og,nO(rO)]],m=ET.create({doc:e,extensions:C}),_=new be({state:m,parent:E.current});return d.current=_,o&&_.focus(),()=>{_.destroy(),d.current=null}},[r]),R.useEffect(()=>{const O=d.current;if(!O)return;const I=s?ko({schema:s,upperCaseKeywords:!1}):ko({upperCaseKeywords:!1});O.dispatch({effects:A.current.reconfigure(I)})},[s]),R.useEffect(()=>{const O=d.current;if(!O)return;const I=O.state.doc.toString();I!==e&&O.dispatch({changes:{from:0,to:I.length,insert:e}})},[e]),R.useEffect(()=>{const O=d.current;if(!O)return;if(!i){O.dispatch({effects:Ss.of(null)});return}const I=tg(i),p=O.state.doc;if(I&&I.line>=1&&I.line<=p.lines){const N=p.line(I.line),h=N.from+Math.max(0,I.col-1),C=Math.max(h+1,N.to);O.dispatch({effects:Ss.of({from:Math.min(h,p.length),to:Math.min(C,p.length),message:i})})}else if(p.lines>=1){const N=p.line(1);O.dispatch({effects:Ss.of({from:N.from,to:Math.max(N.from+1,N.to),message:i})})}},[i]),a.jsx("div",{onDragOver:O=>{O.dataTransfer.types.includes(Fs)&&(O.preventDefault(),T(!0))},onDragLeave:()=>T(!1),onDrop:O=>{const I=d.current;if(!I)return;const p=LR(O.dataTransfer.getData(Fs));p&&(O.preventDefault(),T(!1),Q_(I,p.reference,{x:O.clientX,y:O.clientY}),Z.trackUsage(p.name),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:p.name}})))},style:{background:c.editorBg,minHeight:80,border:u?`1px solid ${c.accent}`:"1px solid transparent",borderRadius:6,transition:"border-color 0.15s"},children:a.jsx("div",{ref:E,style:{minHeight:80}})})}pc.displayName="SQLCellEditor";function ig(e,t){const n=e.split(`
|
|
358
|
+
`),r=[];let o=0;for(;o<n.length;){const s=n[o],i=s.match(/^(#{1,6})\s+(.+)$/);if(i){const l=i[1].length,c=i[2],d=[28,22,18,16,14,13][l-1];r.push(a.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:_r(c,t)},o)),o++;continue}if(/^[-*_]{3,}$/.test(s.trim())){r.push(a.jsx("hr",{style:{border:"none",borderTop:`1px solid ${t.cellBorder}`,margin:"12px 0"}},o)),o++;continue}if(s.startsWith("> ")){r.push(a.jsx("div",{style:{borderLeft:`3px solid ${t.textMuted}`,paddingLeft:12,marginLeft:4,color:t.textSecondary,fontStyle:"italic",fontFamily:t.fontSerif,fontSize:14},children:_r(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(a.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(`
|
|
359
|
+
`)},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(a.jsx("ul",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:l.map((c,E)=>a.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:_r(c,t)},E))},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(a.jsx("ol",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:l.map((c,E)=>a.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:_r(c,t)},E))},o));continue}if(!s.trim()){r.push(a.jsx("div",{style:{height:8}},o)),o++;continue}r.push(a.jsx("p",{style:{fontSize:14,lineHeight:1.7,fontFamily:t.fontSerif,color:t.textSecondary,marginBottom:6},children:_r(s,t)},o)),o++}return r}function _r(e,t){const n=[];let r=e,o=0;for(;r.length>0;){const s=r.match(/\*{3}(.+?)\*{3}/),i=r.match(/\*{2}(.+?)\*{2}/),l=r.match(/\*(.+?)\*/),c=r.match(/`(.+?)`/),E=r.match(/\[(.+?)\]\((.+?)\)/),d=[s?{match:s,type:"boldItalic"}:null,i?{match:i,type:"bold"}:null,l?{match:l,type:"italic"}:null,c?{match:c,type:"code"}:null,E?{match:E,type:"link"}:null].filter(Boolean);if(d.length===0){n.push(a.jsx(Ce.Fragment,{children:r},o++));break}const u=d.reduce((S,f)=>(S.match.index??0)<(f.match.index??0)?S:f),T=u.match.index??0;switch(T>0&&n.push(a.jsx(Ce.Fragment,{children:r.slice(0,T)},o++)),u.type){case"boldItalic":n.push(a.jsx("strong",{style:{fontStyle:"italic"},children:u.match[1]},o++));break;case"bold":n.push(a.jsx("strong",{children:u.match[1]},o++));break;case"italic":n.push(a.jsx("em",{children:u.match[1]},o++));break;case"code":n.push(a.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(a.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 a.jsx(a.Fragment,{children:n})}function ag({value:e,onChange:t,onRun:n,themeMode:r}){const o=ce[r],[s,i]=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 c=()=>{i(!1)},E=u=>{if(u.key==="Escape"&&i(!1),u.key==="Enter"&&u.shiftKey&&(u.preventDefault(),i(!1),n==null||n()),u.key==="Tab"){u.preventDefault();const T=u.currentTarget,S=T.selectionStart,f=T.selectionEnd,A=e.slice(0,S)+" "+e.slice(f);t(A),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?a.jsx("textarea",{ref:l,value:e,onChange:d,onBlur:c,onKeyDown:E,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()?a.jsx("div",{onDoubleClick:()=>i(!0),title:"Double-click to edit",style:{padding:"12px 16px",cursor:"text",minHeight:48},children:ig(e,o)}):a.jsx("div",{onDoubleClick:()=>i(!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 lg({cell:e,themeMode:t,onApplyParam:n}){const{dispatch:r}=Te(),o=ce[t],[s,i]=R.useState(!1),l=e.paramConfig??{paramType:"text",label:"Parameter",defaultValue:"",options:[]},c=e.paramValue??l.defaultValue,E=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 a.jsxs("div",{style:{background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderLeft:"3px solid #e3b341",borderRadius:8,overflow:"hidden"},children:[s&&a.jsxs("div",{style:{background:o.tableHeaderBg,borderBottom:`1px solid ${o.cellBorder}`,padding:"12px 14px",display:"flex",flexDirection:"column",gap:10},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:2},children:[a.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",color:"#e3b341",fontFamily:o.fontMono,textTransform:"uppercase"},children:"Configure Parameter"}),a.jsx("button",{onClick:()=>i(!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"})]}),a.jsxs("div",{style:{display:"flex",gap:10,flexWrap:"wrap"},children:[a.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[a.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Variable name"}),a.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"}})]}),a.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[a.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Display label"}),a.jsx("input",{value:l.label,onChange:S=>E({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"}})]}),a.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 100px"},children:[a.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Type"}),a.jsxs("select",{value:l.paramType,onChange:S=>E({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:[a.jsx("option",{value:"text",children:"Text"}),a.jsx("option",{value:"number",children:"Number"}),a.jsx("option",{value:"date",children:"Date"}),a.jsx("option",{value:"select",children:"Select"})]})]}),a.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[a.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Default value"}),a.jsx("input",{type:l.paramType==="number"?"number":l.paramType==="date"?"date":"text",value:l.defaultValue,onChange:S=>E({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"&&a.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3},children:[a.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Options (one per line)"}),a.jsx("textarea",{value:(l.options??[]).join(`
|
|
360
|
+
`),onChange:S=>E({options:S.target.value.split(`
|
|
361
|
+
`)}),rows:4,placeholder:`Option A
|
|
362
|
+
Option B
|
|
363
|
+
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"}})]})]}),a.jsxs("div",{style:{padding:"12px 14px",display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[a.jsx("button",{onClick:()=>i(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?a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:a.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"})}):a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:a.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"})})}),a.jsx("span",{style:{fontSize:13,fontWeight:500,fontFamily:o.font,color:o.textSecondary,flexShrink:0},children:l.label}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[l.paramType==="select"?a.jsx("select",{value:c,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?a.jsx("option",{value:"",children:"— no options configured —"}):u.map(S=>a.jsx("option",{value:S,children:S},S))}):a.jsx("input",{type:l.paramType,value:c,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&&a.jsx("span",{style:{fontSize:10,fontFamily:o.fontMono,color:"#e3b341",opacity:.8},children:T})]}),c&&a.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:c}),e.name&&n&&a.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"})]})]})}const cg=[{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
|
|
364
|
+
category,
|
|
365
|
+
COUNT(*) AS count,
|
|
366
|
+
SUM(amount) AS total
|
|
367
|
+
FROM read_csv_auto('data/filename.csv')
|
|
368
|
+
GROUP BY category
|
|
369
|
+
ORDER BY total DESC`},{id:"filter-date",label:"Filter by date range",description:"Filter rows between two dates",category:"SQL",code:`SELECT *
|
|
370
|
+
FROM read_csv_auto('data/filename.csv')
|
|
371
|
+
WHERE date_column >= '2024-01-01'
|
|
372
|
+
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
|
|
373
|
+
*,
|
|
374
|
+
ROW_NUMBER() OVER (PARTITION BY category ORDER BY amount DESC) AS rank
|
|
375
|
+
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 (
|
|
376
|
+
SELECT *
|
|
377
|
+
FROM read_csv_auto('data/filename.csv')
|
|
378
|
+
WHERE amount > 0
|
|
379
|
+
)
|
|
380
|
+
SELECT
|
|
381
|
+
category,
|
|
382
|
+
SUM(amount) AS total
|
|
383
|
+
FROM base
|
|
384
|
+
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
|
|
385
|
+
FROM read_csv_auto('data/table_a.csv') AS a
|
|
386
|
+
JOIN read_csv_auto('data/table_b.csv') AS b
|
|
387
|
+
ON a.id = b.id`},{id:"pivot",label:"Pivot / unpivot",description:"Pivot a column into multiple columns",category:"SQL",code:`SELECT *
|
|
388
|
+
FROM (
|
|
389
|
+
SELECT category, quarter, amount
|
|
390
|
+
FROM read_csv_auto('data/filename.csv')
|
|
391
|
+
) 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" {
|
|
392
|
+
domain = "analytics"
|
|
393
|
+
type = "custom"
|
|
394
|
+
description = "Describe what this block does"
|
|
395
|
+
owner = "data-team"
|
|
396
|
+
tags = ["analytics"]
|
|
397
|
+
|
|
398
|
+
query = """
|
|
399
|
+
SELECT *
|
|
400
|
+
FROM read_csv_auto('data/filename.csv')
|
|
401
|
+
LIMIT 100
|
|
402
|
+
"""
|
|
403
|
+
|
|
404
|
+
visualization {
|
|
405
|
+
chart = "table"
|
|
406
|
+
}
|
|
407
|
+
}`},{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" {
|
|
408
|
+
domain = "revenue"
|
|
409
|
+
type = "custom"
|
|
410
|
+
description = "Revenue grouped by segment"
|
|
411
|
+
owner = "data-team"
|
|
412
|
+
tags = ["revenue"]
|
|
413
|
+
|
|
414
|
+
params {
|
|
415
|
+
period = "current_quarter"
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
query = """
|
|
419
|
+
SELECT
|
|
420
|
+
segment_tier AS segment,
|
|
421
|
+
SUM(amount) AS revenue
|
|
422
|
+
FROM read_csv_auto('data/revenue.csv')
|
|
423
|
+
WHERE fiscal_period = \${period}
|
|
424
|
+
GROUP BY segment_tier
|
|
425
|
+
ORDER BY revenue DESC
|
|
426
|
+
"""
|
|
427
|
+
|
|
428
|
+
visualization {
|
|
429
|
+
chart = "bar"
|
|
430
|
+
x = segment
|
|
431
|
+
y = revenue
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
tests {
|
|
435
|
+
assert row_count > 0
|
|
436
|
+
}
|
|
437
|
+
}`},{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)
|
|
438
|
+
FROM fct_revenue
|
|
439
|
+
GROUP BY @dim(segment)
|
|
440
|
+
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" {
|
|
441
|
+
domain = "revenue"
|
|
442
|
+
type = "semantic"
|
|
443
|
+
owner = "data-team"
|
|
444
|
+
description = "Annual Recurring Revenue by subscription plan tier"
|
|
445
|
+
tags = ["arr", "revenue", "saas"]
|
|
446
|
+
|
|
447
|
+
metric = "arr"
|
|
448
|
+
dimensions = ["plan_tier"]
|
|
449
|
+
|
|
450
|
+
visualization {
|
|
451
|
+
chart = "bar"
|
|
452
|
+
x = plan_tier
|
|
453
|
+
y = arr
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
tests {
|
|
457
|
+
assert row_count > 0
|
|
458
|
+
}
|
|
459
|
+
}`},{id:"revenue-by-segment",label:"Revenue by segment",description:"Aggregate revenue totals, deal count, and average deal size per segment",category:"Analysis",code:`SELECT
|
|
460
|
+
segment_tier,
|
|
461
|
+
SUM(amount) AS total_revenue,
|
|
462
|
+
COUNT(*) AS deals,
|
|
463
|
+
ROUND(AVG(amount), 0) AS avg_deal
|
|
464
|
+
FROM read_csv_auto('data/revenue.csv')
|
|
465
|
+
GROUP BY segment_tier
|
|
466
|
+
ORDER BY total_revenue DESC`},{id:"quarterly-trend",label:"Quarterly trend",description:"Revenue totals grouped by fiscal year and quarter",category:"Analysis",code:`SELECT
|
|
467
|
+
fiscal_year || ' ' || fiscal_quarter AS period,
|
|
468
|
+
SUM(amount) AS revenue
|
|
469
|
+
FROM read_csv_auto('data/revenue.csv')
|
|
470
|
+
GROUP BY fiscal_year, fiscal_quarter
|
|
471
|
+
ORDER BY fiscal_year, fiscal_quarter`}];function Eg({onInsert:e,themeMode:t,cellType:n}){const r=ce[t],[o,s]=R.useState(!1),[i,l]=R.useState(null),c=R.useRef(null),E=cg.filter(T=>n==="dql"?T.category==="DQL":T.category==="SQL"||T.category==="Analysis"),d=Array.from(new Set(E.map(T=>T.category)));R.useEffect(()=>{if(!o)return;function T(S){c.current&&!c.current.contains(S.target)&&s(!1)}return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[o]);function u(T){e(T),s(!1)}return a.jsxs("div",{ref:c,style:{position:"relative",display:"inline-block"},children:[a.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:[a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:a.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&&a.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=>a.jsxs("div",{children:[a.jsx("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:700,fontFamily:r.font,letterSpacing:"0.08em",textTransform:"uppercase",color:r.textMuted},children:T}),E.filter(S=>S.category===T).map(S=>a.jsxs("button",{onMouseEnter:()=>l(S.id),onMouseLeave:()=>l(null),onClick:()=>u(S.code),style:{width:"100%",padding:"7px 12px",textAlign:"left",background:i===S.id?r.sidebarItemHover:"transparent",border:"none",cursor:"pointer",display:"flex",flexDirection:"column",gap:2,transition:"background 0.1s"},children:[a.jsx("span",{style:{fontSize:12,fontWeight:600,fontFamily:r.font,color:r.textPrimary,lineHeight:1.4},children:S.label}),a.jsx("span",{style:{fontSize:11,fontFamily:r.font,color:r.textMuted,lineHeight:1.4},children:S.description})]},S.id))]},T))})]})}function Sa(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function dg(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 ug({cell:e,onClose:t,onSaved:n}){const{state:r,dispatch:o}=Te(),s=ce[r.themeMode],i=R.useRef(null),[l,c]=R.useState(e.name||"new_block"),[E,d]=R.useState(""),[u,T]=R.useState(""),[S,f]=R.useState(""),[A,O]=R.useState(e.content),[I,p]=R.useState(!1),[N,h]=R.useState(null),C=R.useMemo(()=>dg(A),[A]);R.useEffect(()=>{var b;(b=i.current)==null||b.focus()},[]),R.useEffect(()=>{const b=y=>{y.key==="Escape"&&t()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[t]);const m=r.semanticLayer.domains,_=`${E.trim()?`blocks/${Sa(E)}/`:"blocks/"}${Sa(l)||"new-block"}.dql`,D=async()=>{var b;if(!l.trim()){h("Block name is required.");return}if(!A.trim()){h("Block content is required.");return}p(!0),h(null);try{const y=await Z.saveAsBlock({cellId:e.id,notebookPath:((b=r.activeFile)==null?void 0:b.path)??null,name:l.trim(),domain:E.trim()||void 0,content:A,description:u.trim()||void 0,tags:S.split(",").map(L=>L.trim()).filter(Boolean),metricRefs:C}),M={name:`${Sa(l)||"new-block"}.dql`,path:y.path,type:"block",folder:"blocks"};r.files.some(L=>L.path===y.path)||o({type:"FILE_ADDED",file:M});const F=await Z.openBlockStudio(y.path);o({type:"OPEN_BLOCK_STUDIO",file:M,payload:F}),n==null||n({...y,name:l.trim()}),t()}catch(y){h(y instanceof Error?y.message:String(y))}finally{p(!1)}},g={width:"100%",background:s.inputBg,border:`1px solid ${N?s.error:s.inputBorder}`,borderRadius:6,color:s.textPrimary,fontSize:13,fontFamily:s.font,padding:"8px 12px",outline:"none",boxSizing:"border-box"};return a.jsx("div",{onClick:b=>{b.target===b.currentTarget&&t()},style:{position:"fixed",inset:0,background:s.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1100,backdropFilter:"blur(4px)"},children:a.jsxs("div",{style:{width:760,maxWidth:"calc(100vw - 48px)",maxHeight:"calc(100vh - 48px)",overflow:"auto",background:s.modalBg,border:`1px solid ${s.cellBorder}`,borderRadius:12,boxShadow:"0 20px 60px rgba(0,0,0,0.5)"},children:[a.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[a.jsx("h2",{style:{margin:0,fontSize:16,fontWeight:600,color:s.textPrimary,fontFamily:s.font},children:"Save as Block"}),a.jsx("button",{onClick:t,style:{background:"transparent",border:"none",color:s.textMuted,cursor:"pointer",fontSize:18},children:"×"})]}),a.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},children:[a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[a.jsx("label",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:"Block Name"}),a.jsx("input",{ref:i,value:l,onChange:b=>c(b.target.value),style:g})]}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[a.jsx("label",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:"Domain"}),a.jsx("input",{value:E,onChange:b=>d(b.target.value),list:"semantic-domain-options",style:g,placeholder:"finance"}),a.jsx("datalist",{id:"semantic-domain-options",children:m.map(b=>a.jsx("option",{value:b},b))})]})]}),a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[a.jsx("label",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:"Description"}),a.jsx("input",{value:u,onChange:b=>T(b.target.value),style:g})]}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[a.jsx("label",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:"Tags"}),a.jsx("input",{value:S,onChange:b=>f(b.target.value),style:g,placeholder:"revenue, dashboard"})]})]}),a.jsx("div",{style:{fontSize:12,color:s.textMuted,fontFamily:s.fontMono,padding:"8px 12px",background:s.pillBg,borderRadius:6},children:_}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[a.jsx("label",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:"Content Preview"}),a.jsx("textarea",{value:A,onChange:b=>O(b.target.value),style:{...g,minHeight:220,resize:"vertical",fontFamily:s.fontMono,lineHeight:1.5}})]}),C.length>0&&a.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,padding:"10px 12px",background:s.pillBg,borderRadius:6},children:[a.jsx("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.font},children:"Detected semantic refs:"}),C.map(b=>a.jsx("span",{style:{fontSize:11,color:s.accent,fontFamily:s.fontMono,background:`${s.accent}18`,borderRadius:999,padding:"2px 8px"},children:b},b))]}),N&&a.jsx("div",{style:{fontSize:12,color:s.error,fontFamily:s.font},children:N})]}),a.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${s.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[a.jsx("button",{onClick:t,style:{background:s.btnBg,border:`1px solid ${s.btnBorder}`,borderRadius:6,color:s.textSecondary,cursor:"pointer",fontSize:13,fontFamily:s.font,padding:"7px 16px"},children:"Cancel"}),a.jsx("button",{onClick:D,disabled:I,style:{background:s.accent,border:`1px solid ${s.accent}`,borderRadius:6,color:"#fff",cursor:I?"not-allowed":"pointer",fontSize:13,fontFamily:s.font,padding:"7px 20px",opacity:I?.6:1},children:I?"Saving...":"Save Block"})]})]})})}const Tg=[25,50,100,500];function Nl(e){return typeof e=="number"?!0:typeof e=="string"?!isNaN(Number(e))&&e.trim()!=="":!1}function _R(e){return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function Sg(e,t){return e==null?1:t==null?-1:Nl(e)&&Nl(t)?Number(e)-Number(t):String(e).localeCompare(String(t))}function Rg(e,t){const n=i=>i.includes(",")||i.includes('"')||i.includes(`
|
|
472
|
+
`)?`"${i.replace(/"/g,'""')}"`:i,r=e.columns.map(n).join(","),o=e.rows.map(i=>e.columns.map(l=>n(_R(i[l]))).join(",")),s=[r,...o].join(`
|
|
473
|
+
`);gR(s,"export.csv","text/csv")}function Ag(e,t){const n=JSON.stringify(e.rows,null,2);gR(n,"export.json","application/json")}function gR(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 fg({dir:e,color:t}){return e?a.jsx("svg",{width:"8",height:"10",viewBox:"0 0 8 10",fill:t,style:{marginLeft:3,flexShrink:0},children:e==="asc"?a.jsx("path",{d:"M4 0L7 4H1L4 0Z"}):a.jsx("path",{d:"M4 10L1 6H7L4 10Z"})}):a.jsxs("svg",{width:"8",height:"10",viewBox:"0 0 8 10",fill:t,opacity:.3,style:{marginLeft:3,flexShrink:0},children:[a.jsx("path",{d:"M4 0L7 3.5H1L4 0Z"}),a.jsx("path",{d:"M4 10L1 6.5H7L4 10Z"})]})}function Ni({result:e,themeMode:t}){const n=ce[t],[r,o]=R.useState(null),[s,i]=R.useState(null),[l,c]=R.useState(null),[E,d]=R.useState(""),[u,T]=R.useState(50),[S,f]=R.useState(0),A=R.useCallback(C=>{s===C?l==="asc"?c("desc"):l==="desc"?(i(null),c(null)):c("asc"):(i(C),c("asc")),f(0)},[s,l]),O=R.useMemo(()=>{if(!E.trim())return e.rows;const C=E.toLowerCase();return e.rows.filter(m=>e.columns.some(_=>{const D=m[_];return D==null?!1:String(D).toLowerCase().includes(C)}))},[e.rows,e.columns,E]),I=R.useMemo(()=>{if(!s||!l)return O;const C=[...O];return C.sort((m,_)=>{const D=Sg(m[s],_[s]);return l==="desc"?-D:D}),C},[O,s,l]),p=Math.max(1,Math.ceil(I.length/u)),N=Math.min(S,p-1),h=I.slice(N*u,(N+1)*u);return e.columns.length===0?a.jsx("div",{style:{padding:"12px 16px",color:n.textMuted,fontSize:12,fontFamily:n.font,fontStyle:"italic"},children:"Query executed successfully. No columns to display."}):a.jsxs("div",{children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 8px",borderBottom:`1px solid ${n.tableBorder}`,background:`${n.tableHeaderBg}60`,flexWrap:"wrap"},children:[a.jsxs("div",{style:{position:"relative",flex:"0 1 200px",minWidth:120},children:[a.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:n.textMuted,style:{position:"absolute",left:6,top:6},children:a.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"})}),a.jsx("input",{value:E,onChange:C=>{d(C.target.value),f(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"}}),E&&a.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:"×"})]}),a.jsxs("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:[E?`${I.length} of ${e.rows.length}`:`${e.rows.length}`," rows"]}),a.jsx("div",{style:{flex:1}}),a.jsx(JE,{label:"CSV",onClick:()=>Rg(e),t:n}),a.jsx(JE,{label:"JSON",onClick:()=>Ag(e),t:n}),a.jsx("select",{value:u,onChange:C=>{T(Number(C.target.value)),f(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:Tg.map(C=>a.jsxs("option",{value:C,children:[C," / page"]},C))}),p>1&&a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[a.jsx(Zo,{disabled:N===0,onClick:()=>f(0),t:n,children:"«"}),a.jsx(Zo,{disabled:N===0,onClick:()=>f(N-1),t:n,children:"‹"}),a.jsxs("span",{style:{fontSize:10,color:n.textSecondary,fontFamily:n.font,padding:"0 4px"},children:[N+1,"/",p]}),a.jsx(Zo,{disabled:N>=p-1,onClick:()=>f(N+1),t:n,children:"›"}),a.jsx(Zo,{disabled:N>=p-1,onClick:()=>f(p-1),t:n,children:"»"})]})]}),a.jsx("div",{style:{maxHeight:400,overflow:"auto",position:"relative"},children:a.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",tableLayout:"auto",fontSize:12,fontFamily:n.fontMono},children:[a.jsx("thead",{children:a.jsx("tr",{children:e.columns.map(C=>a.jsx("th",{onClick:()=>A(C),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:a.jsxs("span",{style:{display:"flex",alignItems:"center"},children:[C,a.jsx(fg,{dir:s===C?l:null,color:s===C?n.accent:n.textMuted})]})},C))})}),a.jsx("tbody",{children:h.map((C,m)=>a.jsx("tr",{onMouseEnter:()=>o(m),onMouseLeave:()=>o(null),style:{background:r===m?n.tableRowHover:"transparent",transition:"background 0.1s"},children:e.columns.map(_=>{const D=C[_],g=D==null,b=Nl(D);return a.jsx("td",{style:{padding:"5px 12px",borderBottom:`1px solid ${n.tableBorder}`,borderRight:`1px solid ${n.tableBorder}`,color:g?n.textMuted:n.textPrimary,fontStyle:g?"italic":"normal",textAlign:b?"right":"left",whiteSpace:"nowrap",maxWidth:300,overflow:"hidden",textOverflow:"ellipsis"},children:g?"—":_R(D)},_)})},m))})]})}),(E||I.length>u)&&a.jsxs("div",{style:{padding:"4px 12px",color:n.textMuted,fontSize:10,fontFamily:n.font,borderTop:`1px solid ${n.tableBorder}`,background:`${n.tableHeaderBg}60`,display:"flex",justifyContent:"space-between"},children:[a.jsxs("span",{children:["Showing ",N*u+1,"–",Math.min((N+1)*u,I.length)," of ",I.length,E&&` (filtered from ${e.rows.length})`]}),s&&a.jsxs("span",{children:["Sorted by ",s," ",l]})]})]})}function JE({label:e,onClick:t,t:n}){const[r,o]=R.useState(!1);return a.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:[a.jsxs("svg",{width:"9",height:"9",viewBox:"0 0 16 16",fill:"currentColor",children:[a.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"}),a.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 Zo({disabled:e,onClick:t,children:n,t:r}){return a.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 hc=[{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"}],Ig=/date|time|at|day|month|year/i,xR=/^(label|name|category|status|type|group)$/i,yR=/^(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 Og(e){return typeof e=="string"||typeof e=="number"}const Ng=new Set(["bar","line","area","pie","donut","scatter","heatmap","funnel","waterfall","histogram","gauge","stacked-bar","grouped-bar","kpi","table"]);function Xr(e,t){if(t!=null&&t.chart){const n=t.chart.toLowerCase().replace(/_/g,"-");if(Ng.has(n))return n}return pg(e)}function pg(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),i=s.every(u=>zt(u[o])),l=s.every(u=>Og(u[r]));if(Ig.test(r)&&i&&l)return"line";const c=t.find(u=>xR.test(u)),E=t.find(u=>yR.test(u));return c&&E&&s.every(T=>zt(T[E]))?"bar":s.every(u=>zt(u[r]))&&i&&t.length>=2?"scatter":t.length===2&&l&&i?"bar":"table"}const DR={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=DR.default;function Pe(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 hg(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 pi(e,t){const n=(t!=null&&t.x&&e.columns.includes(t.x)?t.x:void 0)??e.columns.find(o=>xR.test(o))??e.columns[0],r=(t!=null&&t.y&&e.columns.includes(t.y)?t.y:void 0)??e.columns.find(o=>yR.test(o))??e.columns[1];return{labelCol:n,valueCol:r}}const In=20;function Cc({result:e,themeMode:t,chartConfig:n}){const r=ce[t],[o,s]=R.useState(null),{labelCol:i,valueCol:l}=pi(e,n),c=(n==null?void 0:n.maxItems)??In,E=e.rows.slice(0,c).map(I=>({label:String(I[i]??""),value:Number(I[l]??0)})),d=e.rows.length>c,u=Math.max(...E.map(I=>I.value),1),T=28,S=120,f=6,A=12,O=E.length*(T+f)+A*2;return a.jsxs("div",{style:{padding:"8px 0"},children:[a.jsx("svg",{width:"100%",height:O,viewBox:`0 0 600 ${O}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:E.map((I,p)=>{const N=A+p*(T+f),h=600-S-84,C=Math.max(I.value/u*h,2),m=o===p;return a.jsxs("g",{onMouseEnter:()=>s(p),onMouseLeave:()=>s(null),style:{cursor:"default"},children:[a.jsx("text",{x:S-8,y:N+T/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:I.label.length>16?I.label.slice(0,15)+"…":I.label}),a.jsx("rect",{x:S,y:N,width:C,height:T,rx:3,fill:m?r.accentHover:r.accent,style:{transition:"fill 0.15s"}}),a.jsx("text",{x:S+C+6,y:N+T/2+4,textAnchor:"start",fontSize:11,fontFamily:r.fontMono,fill:r.textMuted,children:Pe(I.value)})]},p)})}),d&&a.jsxs("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,fontStyle:"italic",padding:"4px 12px"},children:["Showing ",In," of ",e.rows.length," rows"]})]})}function Cg({result:e,themeMode:t,chartConfig:n}){const r=ce[t],[o,s]=R.useState(null),i=n!=null&&n.x&&e.columns.includes(n.x)?n.x:e.columns[0],l=e.rows.slice(0,5),c=e.columns.filter(I=>I!==i&&l.some(p=>zt(p[I])));if(c.length===0)return a.jsx(Cc,{result:e,themeMode:t,chartConfig:n});const E=e.rows.slice(0,In).map(I=>String(I[i]??"")),d=Math.max(...e.rows.slice(0,In).flatMap(I=>c.map(p=>Math.abs(Number(I[p]??0)))),1),u=24,T=u/c.length,S=120,f=12,A=8,O=E.length*(u+A)+f*2;return a.jsxs("div",{style:{padding:"8px 0"},children:[a.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:c.map((I,p)=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[a.jsx("div",{style:{width:10,height:10,borderRadius:2,background:Ue[p%Ue.length]}}),a.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:I})]},I))}),a.jsx("svg",{width:"100%",height:O,viewBox:`0 0 600 ${O}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:E.map((I,p)=>{const N=f+p*(u+A),h=e.rows[p];return a.jsxs("g",{children:[a.jsx("text",{x:S-8,y:N+u/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:I.length>16?I.slice(0,15)+"…":I}),c.map((C,m)=>{const _=Number(h[C]??0),D=600-S-60,g=Math.max(Math.abs(_)/d*D,1),b=N+m*T,y=`${p}-${m}`;return a.jsxs("g",{onMouseEnter:()=>s(y),onMouseLeave:()=>s(null),children:[a.jsx("rect",{x:S,y:b,width:g,height:T-1,rx:2,fill:Ue[m%Ue.length],opacity:o===y?1:.85,style:{transition:"opacity 0.15s"}}),o===y&&a.jsx("text",{x:S+g+4,y:b+T/2+3,fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Pe(_)})]},m)})]},p)})})]})}function mg({result:e,themeMode:t,chartConfig:n}){const r=ce[t],[o,s]=R.useState(null),i=n!=null&&n.x&&e.columns.includes(n.x)?n.x:e.columns[0],l=e.rows.slice(0,5),c=e.columns.filter(I=>I!==i&&l.some(p=>zt(p[I])));if(c.length===0)return a.jsx(Cc,{result:e,themeMode:t,chartConfig:n});const E=e.rows.slice(0,In),d=E.map(I=>String(I[i]??"")),u=Math.max(...E.map(I=>c.reduce((p,N)=>p+Math.abs(Number(I[N]??0)),0)),1),T=28,S=120,f=12,A=6,O=d.length*(T+A)+f*2;return a.jsxs("div",{style:{padding:"8px 0"},children:[a.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:c.map((I,p)=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[a.jsx("div",{style:{width:10,height:10,borderRadius:2,background:Ue[p%Ue.length]}}),a.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:I})]},I))}),a.jsx("svg",{width:"100%",height:O,viewBox:`0 0 600 ${O}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:d.map((I,p)=>{const N=f+p*(T+A),h=E[p],C=600-S-60;let m=S;return a.jsxs("g",{children:[a.jsx("text",{x:S-8,y:N+T/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:I.length>16?I.slice(0,15)+"…":I}),c.map((_,D)=>{const g=Math.abs(Number(h[_]??0)),b=Math.max(g/u*C,0),y=m;m+=b;const M=`${p}-${D}`;return a.jsxs("g",{onMouseEnter:()=>s(M),onMouseLeave:()=>s(null),children:[a.jsx("rect",{x:y,y:N,width:b,height:T,rx:D===0?3:0,fill:Ue[D%Ue.length],opacity:o===M?1:.85,style:{transition:"opacity 0.15s"}}),o===M&&b>30&&a.jsx("text",{x:y+b/2,y:N+T/2+4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:"#fff",fontWeight:600,children:Pe(g)})]},D)})]},p)})})]})}function qE({result:e,themeMode:t,showArea:n}){const r=ce[t],[o,s]=R.useState(null),i=e.columns[0],l=e.columns[1],c=e.rows.map(L=>({label:String(L[i]??""),value:Number(L[l]??0)}));if(c.length<2)return null;const E=560,d=200,u=52,T=16,S=16,f=36,A=E-u-T,O=d-S-f,I=Math.min(...c.map(L=>L.value)),N=Math.max(...c.map(L=>L.value))-I||1,h=A/(c.length-1),C=L=>u+L*h,m=L=>S+O-(L-I)/N*O,_=c.map((L,v)=>({x:C(v),y:m(L.value)})),D=_.reduce((L,v,P)=>{if(P===0)return`M ${v.x},${v.y}`;const w=_[P-1],U=w.x+(v.x-w.x)/2;return`${L} C ${U},${w.y} ${U},${v.y} ${v.x},${v.y}`},""),g=`${D} L ${_[_.length-1].x},${S+O} L ${u},${S+O} Z`,b=5,y=Array.from({length:b+1},(L,v)=>{const P=I+N*v/b;return{val:P,y:m(P)}}),M=Math.ceil(c.length/8),F=c.filter((L,v)=>v%M===0||v===c.length-1);return a.jsx("div",{style:{position:"relative",padding:"8px 0"},children:a.jsxs("svg",{width:"100%",height:d,viewBox:`0 0 ${E} ${d}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},onMouseLeave:()=>s(null),children:[y.map((L,v)=>a.jsxs("g",{children:[a.jsx("line",{x1:u,y1:L.y,x2:u+A,y2:L.y,stroke:r.tableBorder,strokeWidth:.5}),a.jsx("text",{x:u-6,y:L.y+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Pe(L.val)})]},v)),a.jsx("path",{d:g,fill:r.accent,opacity:n?.3:.15}),a.jsx("path",{d:D,fill:"none",stroke:r.accent,strokeWidth:2,strokeLinejoin:"round"}),_.map((L,v)=>a.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:c[v].label,value:c[v].value})},v)),F.map((L,v)=>{const P=c.indexOf(L);return a.jsx("text",{x:C(P),y:S+O+16,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:hg(L.label)},v)}),a.jsx("line",{x1:u,y1:S,x2:u,y2:S+O,stroke:r.tableBorder,strokeWidth:1}),a.jsx("line",{x1:u,y1:S+O,x2:u+A,y2:S+O,stroke:r.tableBorder,strokeWidth:1}),o&&a.jsxs("g",{children:[a.jsx("rect",{x:o.x+8,y:o.y-20,width:90,height:32,rx:4,fill:r.cellBg,stroke:r.cellBorder,strokeWidth:1}),a.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}),a.jsx("text",{x:o.x+13,y:o.y+6,fontSize:11,fontFamily:r.fontMono,fill:r.textPrimary,fontWeight:600,children:Pe(o.value)})]})]})})}function Lg({result:e,themeMode:t,chartConfig:n}){const r=ce[t],[o,s]=R.useState(null),i=n!=null&&n.x&&e.columns.includes(n.x)?n.x:e.columns[0],l=n!=null&&n.y&&e.columns.includes(n.y)?n.y:e.columns[1],c=n!=null&&n.color&&e.columns.includes(n.color)?n.color:void 0,E=e.rows.slice(0,200).map(y=>({x:Number(y[i]??0),y:Number(y[l]??0),color:c?String(y[c]??""):void 0})),d=560,u=300,T=52,S=16,f=16,A=36,O=d-T-S,I=u-f-A,p=Math.min(...E.map(y=>y.x)),N=Math.max(...E.map(y=>y.x)),h=Math.min(...E.map(y=>y.y)),C=Math.max(...E.map(y=>y.y)),m=N-p||1,_=C-h||1,D=y=>T+(y-p)/m*O,g=y=>f+I-(y-h)/_*I,b=c?[...new Set(E.map(y=>y.color))]:[];return a.jsxs("div",{style:{padding:"8px 0"},children:[c&&b.length>0&&a.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:b.slice(0,12).map((y,M)=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[a.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:Ue[M%Ue.length]}}),a.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:y})]},y))}),a.jsxs("svg",{width:"100%",height:u,viewBox:`0 0 ${d} ${u}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:6},(y,M)=>{const F=h+_*M/5,L=g(F);return a.jsxs("g",{children:[a.jsx("line",{x1:T,y1:L,x2:T+O,y2:L,stroke:r.tableBorder,strokeWidth:.5}),a.jsx("text",{x:T-6,y:L+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Pe(F)})]},M)}),Array.from({length:6},(y,M)=>{const F=p+m*M/5,L=D(F);return a.jsx("text",{x:L,y:f+I+16,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Pe(F)},M)}),a.jsx("line",{x1:T,y1:f,x2:T,y2:f+I,stroke:r.tableBorder,strokeWidth:1}),a.jsx("line",{x1:T,y1:f+I,x2:T+O,y2:f+I,stroke:r.tableBorder,strokeWidth:1}),a.jsx("text",{x:T+O/2,y:u-2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:i}),a.jsx("text",{x:10,y:f+I/2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,transform:`rotate(-90, 10, ${f+I/2})`,children:l}),E.map((y,M)=>{const F=c?b.indexOf(y.color):0;return a.jsx("circle",{cx:D(y.x),cy:g(y.y),r:o===M?5:3.5,fill:Ue[F%Ue.length],opacity:o===M?1:.7,style:{cursor:"crosshair",transition:"r 0.1s, opacity 0.1s"},onMouseEnter:()=>s(M),onMouseLeave:()=>s(null)},M)}),o!==null&&a.jsxs("g",{children:[a.jsx("rect",{x:D(E[o].x)+8,y:g(E[o].y)-24,width:100,height:28,rx:4,fill:r.cellBg,stroke:r.cellBorder,strokeWidth:1}),a.jsxs("text",{x:D(E[o].x)+13,y:g(E[o].y)-8,fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:["(",Pe(E[o].x),", ",Pe(E[o].y),")"]})]})]})]})}const _g=12;function QE({result:e,themeMode:t,chartConfig:n,isDonut:r}){const o=ce[t],[s,i]=R.useState(null),{labelCol:l,valueCol:c}=pi(e,n),E=e.rows.slice(0,_g).map(p=>({label:String(p[l]??""),value:Math.abs(Number(p[c]??0))})),d=E.reduce((p,N)=>p+N.value,0)||1,u=90,T=90,S=70,f=r?40:0,A=[];let O=-Math.PI/2;E.forEach((p,N)=>{const h=p.value/d*2*Math.PI,C=O,m=O+h,_=u+S*Math.cos(C),D=T+S*Math.sin(C),g=u+S*Math.cos(m),b=T+S*Math.sin(m),y=h>Math.PI?1:0;let M;if(f>0){const F=u+f*Math.cos(C),L=T+f*Math.sin(C),v=u+f*Math.cos(m),P=T+f*Math.sin(m);M=`M ${_} ${D} A ${S} ${S} 0 ${y} 1 ${g} ${b} L ${v} ${P} A ${f} ${f} 0 ${y} 0 ${F} ${L} Z`}else M=`M ${u} ${T} L ${_} ${D} A ${S} ${S} 0 ${y} 1 ${g} ${b} Z`;A.push({path:M,color:Ue[N%Ue.length],label:p.label,value:p.value,pct:p.value/d*100}),O=m});const I=s!==null?A[s]:null;return a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,padding:"8px 12px",flexWrap:"wrap"},children:[a.jsxs("svg",{width:180,height:180,style:{flexShrink:0},onMouseLeave:()=>i(null),children:[A.map((p,N)=>a.jsx("path",{d:p.path,fill:p.color,opacity:s===null||s===N?1:.55,style:{cursor:"pointer",transition:"opacity 0.15s"},onMouseEnter:()=>i(N)},N)),r&&a.jsxs(a.Fragment,{children:[a.jsx("text",{x:u,y:T-5,textAnchor:"middle",fontSize:11,fontFamily:o.fontMono,fill:o.textSecondary,children:Pe(I?I.value:d)}),a.jsx("text",{x:u,y:T+9,textAnchor:"middle",fontSize:9,fontFamily:o.font,fill:o.textMuted,children:I?`${I.pct.toFixed(1)}%`:"total"})]})]}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,maxHeight:180,overflowY:"auto",flex:1},children:A.map((p,N)=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,cursor:"default",opacity:s===null||s===N?1:.5},onMouseEnter:()=>i(N),onMouseLeave:()=>i(null),children:[a.jsx("div",{style:{width:10,height:10,borderRadius:2,background:p.color,flexShrink:0}}),a.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p.label}),a.jsxs("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textMuted,marginLeft:"auto",flexShrink:0},children:[p.pct.toFixed(1),"%"]})]},N))})]})}function gg({result:e,themeMode:t}){const n=ce[t],[r,o]=R.useState(null),s=e.columns[0],i=e.columns.slice(1),l=e.rows.slice(0,30),c=l.flatMap(O=>i.map(I=>Number(O[I]??0))),E=Math.min(...c),u=Math.max(...c)-E||1,T=Math.min(50,480/i.length),S=24,f=100;function A(O){const I=(O-E)/u,p=Math.round(56+I*192),N=Math.round(139+I*-58),h=Math.round(253+I*-180);return`rgb(${p},${N},${h})`}return a.jsx("div",{style:{padding:"8px 0",overflowX:"auto"},children:a.jsxs("svg",{width:f+i.length*T+20,height:l.length*S+S+16,style:{display:"block",overflow:"visible"},children:[i.map((O,I)=>a.jsx("text",{x:f+I*T+T/2,y:14,textAnchor:"middle",fontSize:9,fontFamily:n.font,fill:n.textMuted,transform:`rotate(-30, ${f+I*T+T/2}, 14)`,children:O.length>8?O.slice(0,7)+"…":O},I)),l.map((O,I)=>{const p=String(O[s]??""),N=S+I*S;return a.jsxs("g",{children:[a.jsx("text",{x:f-6,y:N+S/2+4,textAnchor:"end",fontSize:10,fontFamily:n.font,fill:n.textSecondary,children:p.length>14?p.slice(0,13)+"…":p}),i.map((h,C)=>{const m=Number(O[h]??0),_=(r==null?void 0:r.r)===I&&(r==null?void 0:r.c)===C;return a.jsxs("g",{onMouseEnter:()=>o({r:I,c:C}),onMouseLeave:()=>o(null),children:[a.jsx("rect",{x:f+C*T,y:N,width:T-1,height:S-1,rx:2,fill:A(m),opacity:_?1:.85,stroke:_?n.accent:"none",strokeWidth:_?1.5:0}),_&&a.jsx("text",{x:f+C*T+T/2,y:N+S/2+4,textAnchor:"middle",fontSize:10,fontFamily:n.fontMono,fill:"#fff",fontWeight:600,children:Pe(m)})]},C)})]},I)})]})})}function xg({result:e,themeMode:t,chartConfig:n}){const r=ce[t],[o,s]=R.useState(null),i=(n!=null&&n.x&&e.columns.includes(n.x)?n.x:void 0)??e.columns.find(D=>e.rows.slice(0,5).some(g=>zt(g[D])))??e.columns[0],l=e.rows.map(D=>Number(D[i]??0)).filter(D=>!isNaN(D));if(l.length===0)return null;const c=Math.min(20,Math.max(5,Math.ceil(Math.sqrt(l.length)))),E=Math.min(...l),T=(Math.max(...l)-E||1)/c,S=Array.from({length:c},(D,g)=>({low:E+g*T,high:E+(g+1)*T,count:0}));l.forEach(D=>{const g=Math.min(Math.floor((D-E)/T),c-1);S[g].count++});const f=Math.max(...S.map(D=>D.count),1),A=560,O=200,I=52,p=16,N=16,h=36,C=A-I-p,m=O-N-h,_=C/c;return a.jsx("div",{style:{padding:"8px 0"},children:a.jsxs("svg",{width:"100%",height:O,viewBox:`0 0 ${A} ${O}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:5},(D,g)=>{const b=f*(g+1)/5,y=N+m-b/f*m;return a.jsxs("g",{children:[a.jsx("line",{x1:I,y1:y,x2:I+C,y2:y,stroke:r.tableBorder,strokeWidth:.5}),a.jsx("text",{x:I-6,y:y+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Math.round(b)})]},g)}),S.map((D,g)=>{const b=D.count/f*m,y=I+g*_,M=N+m-b,F=o===g;return a.jsxs("g",{onMouseEnter:()=>s(g),onMouseLeave:()=>s(null),children:[a.jsx("rect",{x:y+1,y:M,width:_-2,height:b,rx:1,fill:F?r.accentHover:r.accent,opacity:F?1:.85,style:{transition:"fill 0.1s"}}),F&&a.jsx("text",{x:y+_/2,y:M-4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:D.count})]},g)}),S.filter((D,g)=>g%Math.ceil(c/6)===0).map((D,g)=>{const b=S.indexOf(D);return a.jsx("text",{x:I+b*_+_/2,y:N+m+16,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Pe(D.low)},g)}),a.jsx("line",{x1:I,y1:N,x2:I,y2:N+m,stroke:r.tableBorder,strokeWidth:1}),a.jsx("line",{x1:I,y1:N+m,x2:I+C,y2:N+m,stroke:r.tableBorder,strokeWidth:1}),a.jsx("text",{x:I+C/2,y:O-2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:i})]})})}function yg({result:e,themeMode:t,chartConfig:n}){const r=ce[t],[o,s]=R.useState(null),{labelCol:i,valueCol:l}=pi(e,n),c=e.rows.slice(0,10).map(O=>({label:String(O[i]??""),value:Math.abs(Number(O[l]??0))}));if(c.length===0)return null;const E=c[0].value||1,d=400,u=36,T=4,S=16,f=c.length*(u+T)+S*2,A=d/2;return a.jsx("div",{style:{padding:"8px 0",display:"flex",justifyContent:"center"},children:a.jsx("svg",{width:d,height:f,style:{display:"block"},children:c.map((O,I)=>{const p=S+I*(u+T),N=O.value/E,h=Math.max(N*(d-80),40),C=o===I,m=I<c.length-1?c[I+1].value/E:N*.8,_=Math.max(m*(d-80),40),D=A-h/2,g=A+h/2,b=A+_/2,y=A-_/2,M=`M ${D} ${p} L ${g} ${p} L ${b} ${p+u} L ${y} ${p+u} Z`;return a.jsxs("g",{onMouseEnter:()=>s(I),onMouseLeave:()=>s(null),style:{cursor:"default"},children:[a.jsx("path",{d:M,fill:Ue[I%Ue.length],opacity:C?1:.85,style:{transition:"opacity 0.15s"}}),a.jsx("text",{x:A,y:p+u/2+1,textAnchor:"middle",fontSize:11,fontFamily:r.font,fill:"#fff",fontWeight:500,children:O.label}),a.jsxs("text",{x:A,y:p+u/2+13,textAnchor:"middle",fontSize:9,fontFamily:r.fontMono,fill:"rgba(255,255,255,0.7)",children:[Pe(O.value)," (",(N*100).toFixed(0),"%)"]})]},I)})})})}function Dg({result:e,themeMode:t,chartConfig:n}){const r=ce[t],[o,s]=R.useState(null),{labelCol:i,valueCol:l}=pi(e,n),c=e.rows.slice(0,15).map(g=>({label:String(g[i]??""),value:Number(g[l]??0)}));if(c.length===0)return null;let E=0;const d=c.map(g=>{const b=E;return E+=g.value,{...g,start:b,end:E}}),u=d.flatMap(g=>[g.start,g.end]),T=Math.min(0,...u),f=Math.max(0,...u)-T||1,A=560,O=240,I=52,p=16,N=16,h=44,C=A-I-p,m=O-N-h,_=C/d.length,D=g=>N+m-(g-T)/f*m;return a.jsx("div",{style:{padding:"8px 0"},children:a.jsxs("svg",{width:"100%",height:O,viewBox:`0 0 ${A} ${O}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:6},(g,b)=>{const y=T+f*b/5,M=D(y);return a.jsxs("g",{children:[a.jsx("line",{x1:I,y1:M,x2:I+C,y2:M,stroke:r.tableBorder,strokeWidth:.5}),a.jsx("text",{x:I-6,y:M+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Pe(y)})]},b)}),a.jsx("line",{x1:I,y1:D(0),x2:I+C,y2:D(0),stroke:r.textMuted,strokeWidth:1,strokeDasharray:"3,3"}),d.map((g,b)=>{const y=I+b*_,M=D(Math.max(g.start,g.end)),L=D(Math.min(g.start,g.end))-M,v=g.value>=0,P=o===b;return a.jsxs("g",{onMouseEnter:()=>s(b),onMouseLeave:()=>s(null),children:[b<d.length-1&&a.jsx("line",{x1:y+_-2,y1:D(g.end),x2:y+_+2,y2:D(g.end),stroke:r.textMuted,strokeWidth:1,strokeDasharray:"2,2"}),a.jsx("rect",{x:y+4,y:M,width:_-8,height:Math.max(L,1),rx:2,fill:v?r.success:r.error,opacity:P?1:.8,style:{transition:"opacity 0.1s"}}),P&&a.jsxs("text",{x:y+_/2,y:M-4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:[g.value>=0?"+":"",Pe(g.value)]})]},b)}),d.map((g,b)=>a.jsx("text",{x:I+b*_+_/2,y:O-6,textAnchor:"middle",fontSize:9,fontFamily:r.font,fill:r.textMuted,transform:`rotate(-20, ${I+b*_+_/2}, ${O-6})`,children:g.label.length>8?g.label.slice(0,7)+"…":g.label},b)),a.jsx("line",{x1:I,y1:N,x2:I,y2:N+m,stroke:r.tableBorder,strokeWidth:1}),a.jsx("line",{x1:I,y1:N+m,x2:I+C,y2:N+m,stroke:r.tableBorder,strokeWidth:1})]})})}function Pg({result:e,themeMode:t,chartConfig:n}){const r=ce[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(D=>zt(o[D]))??e.columns[0],i=Number(o[s]??0),l=(n==null?void 0:n.title)??s,c=i>100?i*1.2:100,E=Math.min(Math.max(i/c,0),1),d=120,u=110,T=80,S=Math.PI,f=0,A=S-(S-f)*E,O=d+T*Math.cos(S),I=u+T*Math.sin(S),p=d+T*Math.cos(A),N=u+T*Math.sin(A),h=E>.5?1:0,C=d+T*Math.cos(f),m=u+T*Math.sin(f),_=E<.33?r.error:E<.66?r.warning:r.success;return a.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:"16px 24px"},children:a.jsxs("svg",{width:240,height:140,style:{display:"block",overflow:"visible"},children:[a.jsx("path",{d:`M ${O} ${I} A ${T} ${T} 0 1 1 ${C} ${m}`,fill:"none",stroke:r.tableBorder,strokeWidth:12,strokeLinecap:"round"}),E>0&&a.jsx("path",{d:`M ${O} ${I} A ${T} ${T} 0 ${h} 1 ${p} ${N}`,fill:"none",stroke:_,strokeWidth:12,strokeLinecap:"round"}),a.jsx("text",{x:d,y:u-4,textAnchor:"middle",fontSize:28,fontFamily:r.fontMono,fill:_,fontWeight:700,children:Pe(i)}),a.jsx("text",{x:d,y:u+16,textAnchor:"middle",fontSize:11,fontFamily:r.font,fill:r.textMuted,children:l})]})})}function PR({result:e,themeMode:t,chartConfig:n}){const r=ce[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],i=o[s],l=Number(i),c=isNaN(l)?String(i):l.toLocaleString(void 0,{maximumFractionDigits:2}),E=(n==null?void 0:n.title)??(n!=null&&n.x&&o[n.x]?String(o[n.x]):s);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"32px 24px",gap:8},children:[a.jsx("span",{style:{fontSize:40,fontWeight:700,fontFamily:r.fontMono,color:r.accent,lineHeight:1.1},children:c}),a.jsx("span",{style:{fontSize:13,fontFamily:r.font,color:r.textMuted,textTransform:"uppercase",letterSpacing:"0.08em",fontWeight:500},children:E})]})}function Mg({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 a.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:i=>i.stopPropagation(),children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsx("span",{style:{fontSize:11,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:"Chart Settings"}),a.jsx("button",{onClick:r,style:{background:"none",border:"none",color:o.textMuted,cursor:"pointer",fontSize:14},children:"×"})]}),a.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Title",a.jsx("input",{value:e.title??"",onChange:i=>n({title:i.target.value||void 0}),placeholder:"Chart title",style:{...s,marginTop:2}})]}),a.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["X-axis label",a.jsx("input",{value:e.xLabel??"",onChange:i=>n({xLabel:i.target.value||void 0}),placeholder:"Auto",style:{...s,marginTop:2}})]}),a.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Y-axis label",a.jsx("input",{value:e.yLabel??"",onChange:i=>n({yLabel:i.target.value||void 0}),placeholder:"Auto",style:{...s,marginTop:2}})]}),a.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Legend",a.jsxs("select",{value:e.legendPosition??"top",onChange:i=>n({legendPosition:i.target.value}),style:{...s,marginTop:2},children:[a.jsx("option",{value:"top",children:"Top"}),a.jsx("option",{value:"bottom",children:"Bottom"}),a.jsx("option",{value:"left",children:"Left"}),a.jsx("option",{value:"right",children:"Right"}),a.jsx("option",{value:"none",children:"Hidden"})]})]}),a.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Color palette",a.jsx("select",{value:e.colorPalette??"default",onChange:i=>n({colorPalette:i.target.value}),style:{...s,marginTop:2},children:Object.keys(DR).map(i=>a.jsx("option",{value:i,children:i.charAt(0).toUpperCase()+i.slice(1)},i))})]}),a.jsxs("label",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:["Max items",a.jsx("input",{type:"number",value:e.maxItems??In,min:5,max:200,onChange:i=>n({maxItems:parseInt(i.target.value)||In}),style:{...s,marginTop:2}})]})]})}function bg({result:e,themeMode:t,chartConfig:n,onConfigChange:r}){const o=ce[t],s=Xr(e,n),[i,l]=R.useState(!1);return s==="kpi"?a.jsx(PR,{result:e,themeMode:t,chartConfig:n}):a.jsxs("div",{style:{position:"relative"},children:[(n==null?void 0:n.title)&&a.jsx("div",{style:{padding:"8px 12px 0",fontSize:13,fontWeight:600,color:o.textPrimary,fontFamily:o.font,textAlign:"center"},children:n.title}),r&&a.jsx("button",{onClick:()=>l(!i),title:"Chart settings",style:{position:"absolute",top:4,right:4,zIndex:50,background:i?`${o.accent}18`:"transparent",border:`1px solid ${i?o.accent:"transparent"}`,borderRadius:4,color:i?o.accent:o.textMuted,cursor:"pointer",fontSize:14,padding:"2px 6px",lineHeight:1},children:"⚙"}),i&&r&&a.jsx(Mg,{config:n??{},columns:e.columns,onChange:c=>r(c),onClose:()=>l(!1),t:o}),mc(s,e,t,n)]})}function mc(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,i=o||s?vg(t,o,s):t;switch(e){case"line":return a.jsx(qE,{result:i,themeMode:n});case"area":return a.jsx(qE,{result:i,themeMode:n,showArea:!0});case"bar":return a.jsx(Cc,{result:i,themeMode:n,chartConfig:r});case"grouped-bar":return a.jsx(Cg,{result:i,themeMode:n,chartConfig:r});case"stacked-bar":return a.jsx(mg,{result:i,themeMode:n,chartConfig:r});case"scatter":return a.jsx(Lg,{result:t,themeMode:n,chartConfig:r});case"pie":return a.jsx(QE,{result:t,themeMode:n,chartConfig:r,isDonut:!1});case"donut":return a.jsx(QE,{result:t,themeMode:n,chartConfig:r,isDonut:!0});case"heatmap":return a.jsx(gg,{result:t,themeMode:n});case"histogram":return a.jsx(xg,{result:t,themeMode:n,chartConfig:r});case"funnel":return a.jsx(yg,{result:t,themeMode:n,chartConfig:r});case"waterfall":return a.jsx(Dg,{result:t,themeMode:n,chartConfig:r});case"gauge":return a.jsx(Pg,{result:t,themeMode:n,chartConfig:r});case"kpi":return a.jsx(PR,{result:t,themeMode:n,chartConfig:r});default:return a.jsx(Ni,{result:t,themeMode:n})}}function vg(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 i={};for(const l of o)i[l]=s[l];return i})}}function Ug(e){let t=e;try{const E=JSON.parse(e);E&&typeof E.error=="string"&&(t=E.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 i=t.match(/at or near "([^"]+)"/i);i?s=i[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 c=t.replace(/^(Parser Error|Binder Error|Conversion Error|Invalid Input Error|IO Error|Constraint Error):\s*/i,"").trim();return{type:n,message:c,line:r,near:s,hint:l}}function wg(e,t){const n=e.length,r=t.length,o=Array.from({length:n+1},(s,i)=>Array.from({length:r+1},(l,c)=>i===0?c:c===0?i:0));for(let s=1;s<=n;s++)for(let i=1;i<=r;i++)o[s][i]=e[s-1]===t[i-1]?o[s-1][i-1]:1+Math.min(o[s-1][i],o[s][i-1],o[s-1][i-1]);return o[n][r]}function ZE(e,t){const n=e.toLowerCase();let r=null,o=4;for(const s of t){const i=wg(n,s.toLowerCase());i<o&&(o=i,r=s)}return r}function Bg({message:e,themeMode:t,onFix:n,schemaTables:r}){const o=ce[t],s=Ug(e);let i=null;if(r&&r.length>0&&s.type==="Reference Error"){const c=/column.*not found|Referenced column/i.test(s.message),E=/table.*not found|Table.*does not exist/i.test(s.message);if(c&&s.near){const d=r.flatMap(T=>T.columns.map(S=>S.name)),u=ZE(s.near,d);u&&(i=`Did you mean column "${u}"?`)}else if(E&&s.near){const d=ZE(s.near,r.map(u=>u.name));d&&(i=`Did you mean table "${d}"?`)}}const l=n&&(s.type==="Syntax Error"||s.near===")"||s.near==="("||s.near==="end of input");return a.jsxs("div",{style:{padding:"12px 14px",background:`${o.error}10`,borderLeft:`3px solid ${o.error}`,display:"flex",flexDirection:"column",gap:8},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[a.jsx("div",{style:{flexShrink:0,color:o.error,display:"flex",alignItems:"center"},children:a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:a.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"})})}),a.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&&a.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&&a.jsxs("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textSecondary,flexShrink:0},children:["near ",a.jsxs("span",{style:{color:o.error},children:["“",s.near,"”"]})]})]}),a.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}),i&&a.jsxs("div",{style:{fontSize:12,fontFamily:o.font,color:o.textSecondary,display:"flex",alignItems:"center",gap:6},children:[a.jsx("span",{style:{color:o.accent},children:"→"}),i]}),s.hint&&a.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:[a.jsx("span",{style:{flexShrink:0,fontSize:13,lineHeight:1.5},children:"💡"}),a.jsx("span",{style:{fontSize:12,fontFamily:o.font,color:o.warning,lineHeight:1.6},children:s.hint})]}),l&&a.jsxs("button",{onClick:n,style:{alignSelf:"flex-start",marginTop:2,padding:"5px 12px",background:`${o.accent}15`,border:`1px solid ${o.accent}50`,borderRadius:6,color:o.accent,fontSize:12,fontFamily:o.font,fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center",gap:6,transition:"all 0.15s"},onMouseEnter:c=>{c.currentTarget.style.background=`${o.accent}25`},onMouseLeave:c=>{c.currentTarget.style.background=`${o.accent}15`},children:[a.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 pl({path:e,onNodeClick:t,focalNodeId:n,t:r}){return e.nodes.length===0?null:a.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,alignItems:"center"},children:e.nodes.map((o,s)=>a.jsxs(Ce.Fragment,{children:[a.jsx(Fg,{node:o,isFocal:o.id===n,onClick:t?()=>t(o.id):void 0,t:r}),s<e.nodes.length-1&&a.jsx("span",{style:{color:r.textMuted,fontSize:10,lineHeight:1},children:"→"})]},o.id))})}function ed({title:e,paths:t,onNodeClick:n,focalNodeId:r,maxVisible:o=4,t:s}){const[i,l]=Ce.useState(!1),c=i?t:t.slice(0,o),E=t.length>o;return t.length===0?null:a.jsxs("div",{style:{border:`1px solid ${s.cellBorder}`,borderRadius:10,overflow:"hidden",background:s.inputBg},children:[a.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:[a.jsx("span",{children:e}),a.jsxs("span",{style:{fontWeight:400,fontSize:10},children:[t.length," path",t.length!==1?"s":""]})]}),a.jsxs("div",{style:{display:"grid",gap:8,padding:10},children:[c.map((d,u)=>a.jsx(pl,{path:d,onNodeClick:n,focalNodeId:r,t:s},`path-${u}`)),E&&!i&&a.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 Fg({node:e,isFocal:t,onClick:n,t:r}){const o=we[e.type]??"#8b949e",s=Sc[e.type]??e.type.slice(0,3).toUpperCase();return a.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:[a.jsx("span",{style:{fontSize:8,fontWeight:700,color:"#0d1117",background:o,borderRadius:3,padding:"1px 3px",flexShrink:0},children:s}),a.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]})}function Gg({layerSummary:e,t}){const n=["source","transform","answer","consumption"];if(Object.values(e).reduce((i,l)=>i+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 a.jsx("div",{style:{display:"flex",gap:10,fontSize:10,color:t.textMuted,fontFamily:t.font},children:n.map(i=>{const l=e[i]??0;return l===0?null:a.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3},children:[a.jsx("span",{style:{width:8,height:8,borderRadius:2,background:o[i],display:"inline-block"}}),s[i],": ",l]},i)})})}function _e(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=_e(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var Hg={value:()=>{}};function hi(){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 Rs(n)}function Rs(e){this._=e}function Yg(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}})}Rs.prototype=hi.prototype={constructor:Rs,on:function(e,t){var n=this._,r=Yg(e+"",n),o,s=-1,i=r.length;if(arguments.length<2){for(;++s<i;)if((o=(e=r[s]).type)&&(o=kg(n[o],e.name)))return o;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++s<i;)if(o=(e=r[s]).type)n[o]=td(n[o],e.name,t);else if(t==null)for(o in n)n[o]=td(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 Rs(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 kg(e,t){for(var n=0,r=e.length,o;n<r;++n)if((o=e[n]).name===t)return o.value}function td(e,t,n){for(var r=0,o=e.length;r<o;++r)if(e[r].name===t){e[r]=Hg,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var hl="http://www.w3.org/1999/xhtml";const nd={svg:"http://www.w3.org/2000/svg",xhtml:hl,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Ci(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),nd.hasOwnProperty(t)?{space:nd[t],local:e}:e}function Wg(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===hl&&t.documentElement.namespaceURI===hl?t.createElement(e):t.createElementNS(n,e)}}function Vg(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function MR(e){var t=Ci(e);return(t.local?Vg:Wg)(t)}function jg(){}function Lc(e){return e==null?jg:function(){return this.querySelector(e)}}function $g(e){typeof e!="function"&&(e=Lc(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],i=s.length,l=r[o]=new Array(i),c,E,d=0;d<i;++d)(c=s[d])&&(E=e.call(c,c.__data__,d,s))&&("__data__"in c&&(E.__data__=c.__data__),l[d]=E);return new Ke(r,this._parents)}function Xg(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function Kg(){return[]}function bR(e){return e==null?Kg:function(){return this.querySelectorAll(e)}}function zg(e){return function(){return Xg(e.apply(this,arguments))}}function Jg(e){typeof e=="function"?e=zg(e):e=bR(e);for(var t=this._groups,n=t.length,r=[],o=[],s=0;s<n;++s)for(var i=t[s],l=i.length,c,E=0;E<l;++E)(c=i[E])&&(r.push(e.call(c,c.__data__,E,i)),o.push(c));return new Ke(r,o)}function vR(e){return function(){return this.matches(e)}}function UR(e){return function(t){return t.matches(e)}}var qg=Array.prototype.find;function Qg(e){return function(){return qg.call(this.children,e)}}function Zg(){return this.firstElementChild}function ex(e){return this.select(e==null?Zg:Qg(typeof e=="function"?e:UR(e)))}var tx=Array.prototype.filter;function nx(){return Array.from(this.children)}function rx(e){return function(){return tx.call(this.children,e)}}function ox(e){return this.selectAll(e==null?nx:rx(typeof e=="function"?e:UR(e)))}function sx(e){typeof e!="function"&&(e=vR(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],i=s.length,l=r[o]=[],c,E=0;E<i;++E)(c=s[E])&&e.call(c,c.__data__,E,s)&&l.push(c);return new Ke(r,this._parents)}function wR(e){return new Array(e.length)}function ix(){return new Ke(this._enter||this._groups.map(wR),this._parents)}function Gs(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}Gs.prototype={constructor:Gs,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 ax(e){return function(){return e}}function lx(e,t,n,r,o,s){for(var i=0,l,c=t.length,E=s.length;i<E;++i)(l=t[i])?(l.__data__=s[i],r[i]=l):n[i]=new Gs(e,s[i]);for(;i<c;++i)(l=t[i])&&(o[i]=l)}function cx(e,t,n,r,o,s,i){var l,c,E=new Map,d=t.length,u=s.length,T=new Array(d),S;for(l=0;l<d;++l)(c=t[l])&&(T[l]=S=i.call(c,c.__data__,l,t)+"",E.has(S)?o[l]=c:E.set(S,c));for(l=0;l<u;++l)S=i.call(e,s[l],l,s)+"",(c=E.get(S))?(r[l]=c,c.__data__=s[l],E.delete(S)):n[l]=new Gs(e,s[l]);for(l=0;l<d;++l)(c=t[l])&&E.get(T[l])===c&&(o[l]=c)}function Ex(e){return e.__data__}function dx(e,t){if(!arguments.length)return Array.from(this,Ex);var n=t?cx:lx,r=this._parents,o=this._groups;typeof e!="function"&&(e=ax(e));for(var s=o.length,i=new Array(s),l=new Array(s),c=new Array(s),E=0;E<s;++E){var d=r[E],u=o[E],T=u.length,S=ux(e.call(d,d&&d.__data__,E,r)),f=S.length,A=l[E]=new Array(f),O=i[E]=new Array(f),I=c[E]=new Array(T);n(d,u,A,O,I,S,t);for(var p=0,N=0,h,C;p<f;++p)if(h=A[p]){for(p>=N&&(N=p+1);!(C=O[N])&&++N<f;);h._next=C||null}}return i=new Ke(i,r),i._enter=l,i._exit=c,i}function ux(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function Tx(){return new Ke(this._exit||this._groups.map(wR),this._parents)}function Sx(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 Rx(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,o=n.length,s=r.length,i=Math.min(o,s),l=new Array(o),c=0;c<i;++c)for(var E=n[c],d=r[c],u=E.length,T=l[c]=new Array(u),S,f=0;f<u;++f)(S=E[f]||d[f])&&(T[f]=S);for(;c<o;++c)l[c]=n[c];return new Ke(l,this._parents)}function Ax(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],o=r.length-1,s=r[o],i;--o>=0;)(i=r[o])&&(s&&i.compareDocumentPosition(s)^4&&s.parentNode.insertBefore(i,s),s=i);return this}function fx(e){e||(e=Ix);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 i=n[s],l=i.length,c=o[s]=new Array(l),E,d=0;d<l;++d)(E=i[d])&&(c[d]=E);c.sort(t)}return new Ke(o,this._parents).order()}function Ix(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function Ox(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function Nx(){return Array.from(this)}function px(){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 i=r[o];if(i)return i}return null}function hx(){let e=0;for(const t of this)++e;return e}function Cx(){return!this.node()}function mx(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var o=t[n],s=0,i=o.length,l;s<i;++s)(l=o[s])&&e.call(l,l.__data__,s,o);return this}function Lx(e){return function(){this.removeAttribute(e)}}function _x(e){return function(){this.removeAttributeNS(e.space,e.local)}}function gx(e,t){return function(){this.setAttribute(e,t)}}function xx(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function yx(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function Dx(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 Px(e,t){var n=Ci(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?_x:Lx:typeof t=="function"?n.local?Dx:yx:n.local?xx:gx)(n,t))}function BR(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function Mx(e){return function(){this.style.removeProperty(e)}}function bx(e,t,n){return function(){this.style.setProperty(e,t,n)}}function vx(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function Ux(e,t,n){return arguments.length>1?this.each((t==null?Mx:typeof t=="function"?vx:bx)(e,t,n??"")):nr(this.node(),e)}function nr(e,t){return e.style.getPropertyValue(t)||BR(e).getComputedStyle(e,null).getPropertyValue(t)}function wx(e){return function(){delete this[e]}}function Bx(e,t){return function(){this[e]=t}}function Fx(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function Gx(e,t){return arguments.length>1?this.each((t==null?wx:typeof t=="function"?Fx:Bx)(e,t)):this.node()[e]}function FR(e){return e.trim().split(/^|\s+/)}function _c(e){return e.classList||new GR(e)}function GR(e){this._node=e,this._names=FR(e.getAttribute("class")||"")}GR.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 HR(e,t){for(var n=_c(e),r=-1,o=t.length;++r<o;)n.add(t[r])}function YR(e,t){for(var n=_c(e),r=-1,o=t.length;++r<o;)n.remove(t[r])}function Hx(e){return function(){HR(this,e)}}function Yx(e){return function(){YR(this,e)}}function kx(e,t){return function(){(t.apply(this,arguments)?HR:YR)(this,e)}}function Wx(e,t){var n=FR(e+"");if(arguments.length<2){for(var r=_c(this.node()),o=-1,s=n.length;++o<s;)if(!r.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?kx:t?Hx:Yx)(n,t))}function Vx(){this.textContent=""}function jx(e){return function(){this.textContent=e}}function $x(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function Xx(e){return arguments.length?this.each(e==null?Vx:(typeof e=="function"?$x:jx)(e)):this.node().textContent}function Kx(){this.innerHTML=""}function zx(e){return function(){this.innerHTML=e}}function Jx(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function qx(e){return arguments.length?this.each(e==null?Kx:(typeof e=="function"?Jx:zx)(e)):this.node().innerHTML}function Qx(){this.nextSibling&&this.parentNode.appendChild(this)}function Zx(){return this.each(Qx)}function ey(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function ty(){return this.each(ey)}function ny(e){var t=typeof e=="function"?e:MR(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function ry(){return null}function oy(e,t){var n=typeof e=="function"?e:MR(e),r=t==null?ry:typeof t=="function"?t:Lc(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function sy(){var e=this.parentNode;e&&e.removeChild(this)}function iy(){return this.each(sy)}function ay(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function ly(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function cy(e){return this.select(e?ly:ay)}function Ey(e){return arguments.length?this.property("__data__",e):this.node().__data__}function dy(e){return function(t){e.call(this,t,this.__data__)}}function uy(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 Ty(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 Sy(e,t,n){return function(){var r=this.__on,o,s=dy(t);if(r){for(var i=0,l=r.length;i<l;++i)if((o=r[i]).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 Ry(e,t,n){var r=uy(e+""),o,s=r.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,E=l.length,d;c<E;++c)for(o=0,d=l[c];o<s;++o)if((i=r[o]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?Sy:Ty,o=0;o<s;++o)this.each(l(r[o],t,n));return this}function kR(e,t,n){var r=BR(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 Ay(e,t){return function(){return kR(this,e,t)}}function fy(e,t){return function(){return kR(this,e,t.apply(this,arguments))}}function Iy(e,t){return this.each((typeof t=="function"?fy:Ay)(e,t))}function*Oy(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,s=r.length,i;o<s;++o)(i=r[o])&&(yield i)}var WR=[null];function Ke(e,t){this._groups=e,this._parents=t}function uo(){return new Ke([[document.documentElement]],WR)}function Ny(){return this}Ke.prototype=uo.prototype={constructor:Ke,select:$g,selectAll:Jg,selectChild:ex,selectChildren:ox,filter:sx,data:dx,enter:ix,exit:Tx,join:Sx,merge:Rx,selection:Ny,order:Ax,sort:fx,call:Ox,nodes:Nx,node:px,size:hx,empty:Cx,each:mx,attr:Px,style:Ux,property:Gx,classed:Wx,text:Xx,html:qx,raise:Zx,lower:ty,append:ny,insert:oy,remove:iy,clone:cy,datum:Ey,on:Ry,dispatch:Iy,[Symbol.iterator]:Oy};function $e(e){return typeof e=="string"?new Ke([[document.querySelector(e)]],[document.documentElement]):new Ke([[e]],WR)}function py(e){let t;for(;t=e.sourceEvent;)e=t;return e}function tt(e,t){if(e=py(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 hy={passive:!1},Kr={capture:!0,passive:!1};function Ra(e){e.stopImmediatePropagation()}function zn(e){e.preventDefault(),e.stopImmediatePropagation()}function VR(e){var t=e.document.documentElement,n=$e(e).on("dragstart.drag",zn,Kr);"onselectstart"in t?n.on("selectstart.drag",zn,Kr):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function jR(e,t){var n=e.document.documentElement,r=$e(e).on("dragstart.drag",null);t&&(r.on("click.drag",zn,Kr),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 es=e=>()=>e;function Cl(e,{sourceEvent:t,subject:n,target:r,identifier:o,active:s,x:i,y:l,dx:c,dy:E,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:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:E,enumerable:!0,configurable:!0},_:{value:d}})}Cl.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function Cy(e){return!e.ctrlKey&&!e.button}function my(){return this.parentNode}function Ly(e,t){return t??{x:e.x,y:e.y}}function _y(){return navigator.maxTouchPoints||"ontouchstart"in this}function $R(){var e=Cy,t=my,n=Ly,r=_y,o={},s=hi("start","drag","end"),i=0,l,c,E,d,u=0;function T(h){h.on("mousedown.drag",S).filter(r).on("touchstart.drag",O).on("touchmove.drag",I,hy).on("touchend.drag touchcancel.drag",p).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",f,Kr).on("mouseup.drag",A,Kr),VR(h.view),Ra(h),E=!1,l=h.clientX,c=h.clientY,m("start",h))}}function f(h){if(zn(h),!E){var C=h.clientX-l,m=h.clientY-c;E=C*C+m*m>u}o.mouse("drag",h)}function A(h){$e(h.view).on("mousemove.drag mouseup.drag",null),jR(h.view,E),zn(h),o.mouse("end",h)}function O(h,C){if(e.call(this,h,C)){var m=h.changedTouches,_=t.call(this,h,C),D=m.length,g,b;for(g=0;g<D;++g)(b=N(this,_,h,C,m[g].identifier,m[g]))&&(Ra(h),b("start",h,m[g]))}}function I(h){var C=h.changedTouches,m=C.length,_,D;for(_=0;_<m;++_)(D=o[C[_].identifier])&&(zn(h),D("drag",h,C[_]))}function p(h){var C=h.changedTouches,m=C.length,_,D;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),_=0;_<m;++_)(D=o[C[_].identifier])&&(Ra(h),D("end",h,C[_]))}function N(h,C,m,_,D,g){var b=s.copy(),y=tt(g||m,C),M,F,L;if((L=n.call(h,new Cl("beforestart",{sourceEvent:m,target:T,identifier:D,active:i,x:y[0],y:y[1],dx:0,dy:0,dispatch:b}),_))!=null)return M=L.x-y[0]||0,F=L.y-y[1]||0,function v(P,w,U){var x=y,B;switch(P){case"start":o[D]=v,B=i++;break;case"end":delete o[D],--i;case"drag":y=tt(U||w,C),B=i;break}b.call(P,h,new Cl(P,{sourceEvent:w,subject:L,target:T,identifier:D,active:B,x:y[0]+M,y:y[1]+F,dx:y[0]-x[0],dy:y[1]-x[1],dispatch:b}),_)}}return T.filter=function(h){return arguments.length?(e=typeof h=="function"?h:es(!!h),T):e},T.container=function(h){return arguments.length?(t=typeof h=="function"?h:es(h),T):t},T.subject=function(h){return arguments.length?(n=typeof h=="function"?h:es(h),T):n},T.touchable=function(h){return arguments.length?(r=typeof h=="function"?h:es(!!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 XR(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function To(){}var zr=.7,Hs=1/zr,Jn="\\s*([+-]?\\d+)\\s*",Jr="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Ot="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",gy=/^#([0-9a-f]{3,8})$/,xy=new RegExp(`^rgb\\(${Jn},${Jn},${Jn}\\)$`),yy=new RegExp(`^rgb\\(${Ot},${Ot},${Ot}\\)$`),Dy=new RegExp(`^rgba\\(${Jn},${Jn},${Jn},${Jr}\\)$`),Py=new RegExp(`^rgba\\(${Ot},${Ot},${Ot},${Jr}\\)$`),My=new RegExp(`^hsl\\(${Jr},${Ot},${Ot}\\)$`),by=new RegExp(`^hsla\\(${Jr},${Ot},${Ot},${Jr}\\)$`),rd={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(To,On,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:od,formatHex:od,formatHex8:vy,formatHsl:Uy,formatRgb:sd,toString:sd});function od(){return this.rgb().formatHex()}function vy(){return this.rgb().formatHex8()}function Uy(){return KR(this).formatHsl()}function sd(){return this.rgb().formatRgb()}function On(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=gy.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?id(t):n===3?new Fe(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?ts(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?ts(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=xy.exec(e))?new Fe(t[1],t[2],t[3],1):(t=yy.exec(e))?new Fe(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Dy.exec(e))?ts(t[1],t[2],t[3],t[4]):(t=Py.exec(e))?ts(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=My.exec(e))?cd(t[1],t[2]/100,t[3]/100,1):(t=by.exec(e))?cd(t[1],t[2]/100,t[3]/100,t[4]):rd.hasOwnProperty(e)?id(rd[e]):e==="transparent"?new Fe(NaN,NaN,NaN,0):null}function id(e){return new Fe(e>>16&255,e>>8&255,e&255,1)}function ts(e,t,n,r){return r<=0&&(e=t=n=NaN),new Fe(e,t,n,r)}function wy(e){return e instanceof To||(e=On(e)),e?(e=e.rgb(),new Fe(e.r,e.g,e.b,e.opacity)):new Fe}function ml(e,t,n,r){return arguments.length===1?wy(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,ml,XR(To,{brighter(e){return e=e==null?Hs:Math.pow(Hs,e),new Fe(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?zr:Math.pow(zr,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),Ys(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:ad,formatHex:ad,formatHex8:By,formatRgb:ld,toString:ld}));function ad(){return`#${Tn(this.r)}${Tn(this.g)}${Tn(this.b)}`}function By(){return`#${Tn(this.r)}${Tn(this.g)}${Tn(this.b)}${Tn((isNaN(this.opacity)?1:this.opacity)*255)}`}function ld(){const e=Ys(this.opacity);return`${e===1?"rgb(":"rgba("}${Sn(this.r)}, ${Sn(this.g)}, ${Sn(this.b)}${e===1?")":`, ${e})`}`}function Ys(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 cd(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 KR(e){if(e instanceof nt)return new nt(e.h,e.s,e.l,e.opacity);if(e instanceof To||(e=On(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),i=NaN,l=s-o,c=(s+o)/2;return l?(t===s?i=(n-r)/l+(n<r)*6:n===s?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?s+o:2-s-o,i*=60):l=c>0&&c<1?0:i,new nt(i,l,c,e.opacity)}function Fy(e,t,n,r){return arguments.length===1?KR(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,Fy,XR(To,{brighter(e){return e=e==null?Hs:Math.pow(Hs,e),new nt(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?zr:Math.pow(zr,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(Aa(e>=240?e-240:e+120,o,r),Aa(e,o,r),Aa(e<120?e+240:e-120,o,r),this.opacity)},clamp(){return new nt(Ed(this.h),ns(this.s),ns(this.l),Ys(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=Ys(this.opacity);return`${e===1?"hsl(":"hsla("}${Ed(this.h)}, ${ns(this.s)*100}%, ${ns(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Ed(e){return e=(e||0)%360,e<0?e+360:e}function ns(e){return Math.max(0,Math.min(1,e||0))}function Aa(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 xc=e=>()=>e;function Gy(e,t){return function(n){return e+n*t}}function Hy(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 Yy(e){return(e=+e)==1?zR:function(t,n){return n-t?Hy(t,n,e):xc(isNaN(t)?n:t)}}function zR(e,t){var n=t-e;return n?Gy(e,n):xc(isNaN(e)?t:e)}const ks=(function e(t){var n=Yy(t);function r(o,s){var i=n((o=ml(o)).r,(s=ml(s)).r),l=n(o.g,s.g),c=n(o.b,s.b),E=zR(o.opacity,s.opacity);return function(d){return o.r=i(d),o.g=l(d),o.b=c(d),o.opacity=E(d),o+""}}return r.gamma=e,r})(1);function ky(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 Wy(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Vy(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,o=new Array(r),s=new Array(n),i;for(i=0;i<r;++i)o[i]=wr(e[i],t[i]);for(;i<n;++i)s[i]=t[i];return function(l){for(i=0;i<r;++i)s[i]=o[i](l);return s}}function jy(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 $y(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]=wr(e[o],t[o]):r[o]=t[o];return function(s){for(o in n)r[o]=n[o](s);return r}}var Ll=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,fa=new RegExp(Ll.source,"g");function Xy(e){return function(){return e}}function Ky(e){return function(t){return e(t)+""}}function JR(e,t){var n=Ll.lastIndex=fa.lastIndex=0,r,o,s,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Ll.exec(e))&&(o=fa.exec(t));)(s=o.index)>n&&(s=t.slice(n,s),l[i]?l[i]+=s:l[++i]=s),(r=r[0])===(o=o[0])?l[i]?l[i]+=o:l[++i]=o:(l[++i]=null,c.push({i,x:St(r,o)})),n=fa.lastIndex;return n<t.length&&(s=t.slice(n),l[i]?l[i]+=s:l[++i]=s),l.length<2?c[0]?Ky(c[0].x):Xy(t):(t=c.length,function(E){for(var d=0,u;d<t;++d)l[(u=c[d]).i]=u.x(E);return l.join("")})}function wr(e,t){var n=typeof t,r;return t==null||n==="boolean"?xc(t):(n==="number"?St:n==="string"?(r=On(t))?(t=r,ks):JR:t instanceof On?ks:t instanceof Date?jy:Wy(t)?ky:Array.isArray(t)?Vy:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?$y:St)(e,t)}var dd=180/Math.PI,_l={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function qR(e,t,n,r,o,s){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:o,translateY:s,rotate:Math.atan2(t,e)*dd,skewX:Math.atan(c)*dd,scaleX:i,scaleY:l}}var rs;function zy(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?_l:qR(t.a,t.b,t.c,t.d,t.e,t.f)}function Jy(e){return e==null||(rs||(rs=document.createElementNS("http://www.w3.org/2000/svg","g")),rs.setAttribute("transform",e),!(e=rs.transform.baseVal.consolidate()))?_l:(e=e.matrix,qR(e.a,e.b,e.c,e.d,e.e,e.f))}function QR(e,t,n,r){function o(E){return E.length?E.pop()+" ":""}function s(E,d,u,T,S,f){if(E!==u||d!==T){var A=S.push("translate(",null,t,null,n);f.push({i:A-4,x:St(E,u)},{i:A-2,x:St(d,T)})}else(u||T)&&S.push("translate("+u+t+T+n)}function i(E,d,u,T){E!==d?(E-d>180?d+=360:d-E>180&&(E+=360),T.push({i:u.push(o(u)+"rotate(",null,r)-2,x:St(E,d)})):d&&u.push(o(u)+"rotate("+d+r)}function l(E,d,u,T){E!==d?T.push({i:u.push(o(u)+"skewX(",null,r)-2,x:St(E,d)}):d&&u.push(o(u)+"skewX("+d+r)}function c(E,d,u,T,S,f){if(E!==u||d!==T){var A=S.push(o(S)+"scale(",null,",",null,")");f.push({i:A-4,x:St(E,u)},{i:A-2,x:St(d,T)})}else(u!==1||T!==1)&&S.push(o(S)+"scale("+u+","+T+")")}return function(E,d){var u=[],T=[];return E=e(E),d=e(d),s(E.translateX,E.translateY,d.translateX,d.translateY,u,T),i(E.rotate,d.rotate,u,T),l(E.skewX,d.skewX,u,T),c(E.scaleX,E.scaleY,d.scaleX,d.scaleY,u,T),E=d=null,function(S){for(var f=-1,A=T.length,O;++f<A;)u[(O=T[f]).i]=O.x(S);return u.join("")}}}var qy=QR(zy,"px, ","px)","deg)"),Qy=QR(Jy,", ",")",")"),Zy=1e-12;function ud(e){return((e=Math.exp(e))+1/e)/2}function eD(e){return((e=Math.exp(e))-1/e)/2}function tD(e){return((e=Math.exp(2*e))-1)/(e+1)}const As=(function e(t,n,r){function o(s,i){var l=s[0],c=s[1],E=s[2],d=i[0],u=i[1],T=i[2],S=d-l,f=u-c,A=S*S+f*f,O,I;if(A<Zy)I=Math.log(T/E)/t,O=function(_){return[l+_*S,c+_*f,E*Math.exp(t*_*I)]};else{var p=Math.sqrt(A),N=(T*T-E*E+r*A)/(2*E*n*p),h=(T*T-E*E-r*A)/(2*T*n*p),C=Math.log(Math.sqrt(N*N+1)-N),m=Math.log(Math.sqrt(h*h+1)-h);I=(m-C)/t,O=function(_){var D=_*I,g=ud(C),b=E/(n*p)*(g*tD(t*D+C)-eD(C));return[l+b*S,c+b*f,E*g/ud(t*D+C)]}}return O.duration=I*1e3*t/Math.SQRT2,O}return o.rho=function(s){var i=Math.max(.001,+s),l=i*i,c=l*l;return e(i,l,c)},o})(Math.SQRT2,2,4);var rr=0,Pr=0,gr=0,ZR=1e3,Ws,Mr,Vs=0,Nn=0,mi=0,qr=typeof performance=="object"&&performance.now?performance:Date,eA=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function yc(){return Nn||(eA(nD),Nn=qr.now()+mi)}function nD(){Nn=0}function js(){this._call=this._time=this._next=null}js.prototype=tA.prototype={constructor:js,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?yc():+n)+(t==null?0:+t),!this._next&&Mr!==this&&(Mr?Mr._next=this:Ws=this,Mr=this),this._call=e,this._time=n,gl()},stop:function(){this._call&&(this._call=null,this._time=1/0,gl())}};function tA(e,t,n){var r=new js;return r.restart(e,t,n),r}function rD(){yc(),++rr;for(var e=Ws,t;e;)(t=Nn-e._time)>=0&&e._call.call(void 0,t),e=e._next;--rr}function Td(){Nn=(Vs=qr.now())+mi,rr=Pr=0;try{rD()}finally{rr=0,sD(),Nn=0}}function oD(){var e=qr.now(),t=e-Vs;t>ZR&&(mi-=t,Vs=e)}function sD(){for(var e,t=Ws,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:Ws=n);Mr=e,gl(r)}function gl(e){if(!rr){Pr&&(Pr=clearTimeout(Pr));var t=e-Nn;t>24?(e<1/0&&(Pr=setTimeout(Td,e-qr.now()-mi)),gr&&(gr=clearInterval(gr))):(gr||(Vs=qr.now(),gr=setInterval(oD,ZR)),rr=1,eA(Td))}}function Sd(e,t,n){var r=new js;return t=t==null?0:+t,r.restart(o=>{r.stop(),e(o+t)},t,n),r}var iD=hi("start","end","cancel","interrupt"),aD=[],nA=0,Rd=1,xl=2,fs=3,Ad=4,yl=5,Is=6;function Li(e,t,n,r,o,s){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;lD(e,n,{name:t,index:r,group:o,on:iD,tween:aD,time:s.time,delay:s.delay,duration:s.duration,ease:s.ease,timer:null,state:nA})}function Dc(e,t){var n=Et(e,t);if(n.state>nA)throw new Error("too late; already scheduled");return n}function ht(e,t){var n=Et(e,t);if(n.state>fs)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 lD(e,t,n){var r=e.__transition,o;r[t]=n,n.timer=tA(s,0,n.time);function s(E){n.state=Rd,n.timer.restart(i,n.delay,n.time),n.delay<=E&&i(E-n.delay)}function i(E){var d,u,T,S;if(n.state!==Rd)return c();for(d in r)if(S=r[d],S.name===n.name){if(S.state===fs)return Sd(i);S.state===Ad?(S.state=Is,S.timer.stop(),S.on.call("interrupt",e,e.__data__,S.index,S.group),delete r[d]):+d<t&&(S.state=Is,S.timer.stop(),S.on.call("cancel",e,e.__data__,S.index,S.group),delete r[d])}if(Sd(function(){n.state===fs&&(n.state=Ad,n.timer.restart(l,n.delay,n.time),l(E))}),n.state=xl,n.on.call("start",e,e.__data__,n.index,n.group),n.state===xl){for(n.state=fs,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(E){for(var d=E<n.duration?n.ease.call(null,E/n.duration):(n.timer.restart(c),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),c())}function c(){n.state=Is,n.timer.stop(),delete r[t];for(var E in r)return;delete e.__transition}}function Os(e,t){var n=e.__transition,r,o,s=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){s=!1;continue}o=r.state>xl&&r.state<yl,r.state=Is,r.timer.stop(),r.on.call(o?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}s&&delete e.__transition}}function cD(e){return this.each(function(){Os(this,e)})}function ED(e,t){var n,r;return function(){var o=ht(this,e),s=o.tween;if(s!==n){r=n=s;for(var i=0,l=r.length;i<l;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}o.tween=r}}function dD(e,t,n){var r,o;if(typeof n!="function")throw new Error;return function(){var s=ht(this,e),i=s.tween;if(i!==r){o=(r=i).slice();for(var l={name:t,value:n},c=0,E=o.length;c<E;++c)if(o[c].name===t){o[c]=l;break}c===E&&o.push(l)}s.tween=o}}function uD(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Et(this.node(),n).tween,o=0,s=r.length,i;o<s;++o)if((i=r[o]).name===e)return i.value;return null}return this.each((t==null?ED:dD)(n,e,t))}function Pc(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 rA(e,t){var n;return(typeof t=="number"?St:t instanceof On?ks:(n=On(t))?(t=n,ks):JR)(e,t)}function TD(e){return function(){this.removeAttribute(e)}}function SD(e){return function(){this.removeAttributeNS(e.space,e.local)}}function RD(e,t,n){var r,o=n+"",s;return function(){var i=this.getAttribute(e);return i===o?null:i===r?s:s=t(r=i,n)}}function AD(e,t,n){var r,o=n+"",s;return function(){var i=this.getAttributeNS(e.space,e.local);return i===o?null:i===r?s:s=t(r=i,n)}}function fD(e,t,n){var r,o,s;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===r&&c===o?s:(o=c,s=t(r=i,l)))}}function ID(e,t,n){var r,o,s;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===r&&c===o?s:(o=c,s=t(r=i,l)))}}function OD(e,t){var n=Ci(e),r=n==="transform"?Qy:rA;return this.attrTween(e,typeof t=="function"?(n.local?ID:fD)(n,r,Pc(this,"attr."+e,t)):t==null?(n.local?SD:TD)(n):(n.local?AD:RD)(n,r,t))}function ND(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function pD(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function hD(e,t){var n,r;function o(){var s=t.apply(this,arguments);return s!==r&&(n=(r=s)&&pD(e,s)),n}return o._value=t,o}function CD(e,t){var n,r;function o(){var s=t.apply(this,arguments);return s!==r&&(n=(r=s)&&ND(e,s)),n}return o._value=t,o}function mD(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=Ci(e);return this.tween(n,(r.local?hD:CD)(r,t))}function LD(e,t){return function(){Dc(this,e).delay=+t.apply(this,arguments)}}function _D(e,t){return t=+t,function(){Dc(this,e).delay=t}}function gD(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?LD:_D)(t,e)):Et(this.node(),t).delay}function xD(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 DD(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?xD:yD)(t,e)):Et(this.node(),t).duration}function PD(e,t){if(typeof t!="function")throw new Error;return function(){ht(this,e).ease=t}}function MD(e){var t=this._id;return arguments.length?this.each(PD(t,e)):Et(this.node(),t).ease}function bD(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;ht(this,e).ease=n}}function vD(e){if(typeof e!="function")throw new Error;return this.each(bD(this._id,e))}function UD(e){typeof e!="function"&&(e=vR(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],i=s.length,l=r[o]=[],c,E=0;E<i;++E)(c=s[E])&&e.call(c,c.__data__,E,s)&&l.push(c);return new bt(r,this._parents,this._name,this._id)}function wD(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),i=new Array(r),l=0;l<s;++l)for(var c=t[l],E=n[l],d=c.length,u=i[l]=new Array(d),T,S=0;S<d;++S)(T=c[S]||E[S])&&(u[S]=T);for(;l<r;++l)i[l]=t[l];return new bt(i,this._parents,this._name,this._id)}function BD(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 FD(e,t,n){var r,o,s=BD(t)?Dc:ht;return function(){var i=s(this,e),l=i.on;l!==r&&(o=(r=l).copy()).on(t,n),i.on=o}}function GD(e,t){var n=this._id;return arguments.length<2?Et(this.node(),n).on.on(e):this.each(FD(n,e,t))}function HD(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function YD(){return this.on("end.remove",HD(this._id))}function kD(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Lc(e));for(var r=this._groups,o=r.length,s=new Array(o),i=0;i<o;++i)for(var l=r[i],c=l.length,E=s[i]=new Array(c),d,u,T=0;T<c;++T)(d=l[T])&&(u=e.call(d,d.__data__,T,l))&&("__data__"in d&&(u.__data__=d.__data__),E[T]=u,Li(E[T],t,n,T,E,Et(d,n)));return new bt(s,this._parents,t,n)}function WD(e){var t=this._name,n=this._id;typeof e!="function"&&(e=bR(e));for(var r=this._groups,o=r.length,s=[],i=[],l=0;l<o;++l)for(var c=r[l],E=c.length,d,u=0;u<E;++u)if(d=c[u]){for(var T=e.call(d,d.__data__,u,c),S,f=Et(d,n),A=0,O=T.length;A<O;++A)(S=T[A])&&Li(S,t,n,A,T,f);s.push(T),i.push(d)}return new bt(s,i,t,n)}var VD=uo.prototype.constructor;function jD(){return new VD(this._groups,this._parents)}function $D(e,t){var n,r,o;return function(){var s=nr(this,e),i=(this.style.removeProperty(e),nr(this,e));return s===i?null:s===n&&i===r?o:o=t(n=s,r=i)}}function oA(e){return function(){this.style.removeProperty(e)}}function XD(e,t,n){var r,o=n+"",s;return function(){var i=nr(this,e);return i===o?null:i===r?s:s=t(r=i,n)}}function KD(e,t,n){var r,o,s;return function(){var i=nr(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),nr(this,e))),i===c?null:i===r&&c===o?s:(o=c,s=t(r=i,l))}}function zD(e,t){var n,r,o,s="style."+t,i="end."+s,l;return function(){var c=ht(this,e),E=c.on,d=c.value[s]==null?l||(l=oA(t)):void 0;(E!==n||o!==d)&&(r=(n=E).copy()).on(i,o=d),c.on=r}}function JD(e,t,n){var r=(e+="")=="transform"?qy:rA;return t==null?this.styleTween(e,$D(e,r)).on("end.style."+e,oA(e)):typeof t=="function"?this.styleTween(e,KD(e,r,Pc(this,"style."+e,t))).each(zD(this._id,e)):this.styleTween(e,XD(e,r,t),n).on("end.style."+e,null)}function qD(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function QD(e,t,n){var r,o;function s(){var i=t.apply(this,arguments);return i!==o&&(r=(o=i)&&qD(e,i,n)),r}return s._value=t,s}function ZD(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,QD(e,t,n??""))}function e0(e){return function(){this.textContent=e}}function t0(e){return function(){var t=e(this);this.textContent=t??""}}function n0(e){return this.tween("text",typeof e=="function"?t0(Pc(this,"text",e)):e0(e==null?"":e+""))}function r0(e){return function(t){this.textContent=e.call(this,t)}}function o0(e){var t,n;function r(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&r0(o)),t}return r._value=e,r}function s0(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,o0(e))}function i0(){for(var e=this._name,t=this._id,n=sA(),r=this._groups,o=r.length,s=0;s<o;++s)for(var i=r[s],l=i.length,c,E=0;E<l;++E)if(c=i[E]){var d=Et(c,t);Li(c,e,n,E,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new bt(r,this._parents,e,n)}function a0(){var e,t,n=this,r=n._id,o=n.size();return new Promise(function(s,i){var l={value:i},c={value:function(){--o===0&&s()}};n.each(function(){var E=ht(this,r),d=E.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),E.on=t}),o===0&&s()})}var l0=0;function bt(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function sA(){return++l0}var _t=uo.prototype;bt.prototype={constructor:bt,select:kD,selectAll:WD,selectChild:_t.selectChild,selectChildren:_t.selectChildren,filter:UD,merge:wD,selection:jD,transition:i0,call:_t.call,nodes:_t.nodes,node:_t.node,size:_t.size,empty:_t.empty,each:_t.each,on:GD,attr:OD,attrTween:mD,style:JD,styleTween:ZD,text:n0,textTween:s0,remove:YD,tween:uD,delay:gD,duration:DD,ease:MD,easeVarying:vD,end:a0,[Symbol.iterator]:_t[Symbol.iterator]};function c0(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var E0={time:null,delay:0,duration:250,ease:c0};function d0(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 u0(e){var t,n;e instanceof bt?(t=e._id,e=e._name):(t=sA(),(n=E0).time=yc(),e=e==null?null:e+"");for(var r=this._groups,o=r.length,s=0;s<o;++s)for(var i=r[s],l=i.length,c,E=0;E<l;++E)(c=i[E])&&Li(c,e,t,E,i,n||d0(c,t));return new bt(r,this._parents,e,t)}uo.prototype.interrupt=cD;uo.prototype.transition=u0;const os=e=>()=>e;function T0(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 yt(e,t,n){this.k=e,this.x=t,this.y=n}yt.prototype={constructor:yt,scale:function(e){return e===1?this:new yt(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new yt(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 _i=new yt(1,0,0);iA.prototype=yt.prototype;function iA(e){for(;!e.__zoom;)if(!(e=e.parentNode))return _i;return e.__zoom}function Ia(e){e.stopImmediatePropagation()}function xr(e){e.preventDefault(),e.stopImmediatePropagation()}function S0(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function R0(){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 fd(){return this.__zoom||_i}function A0(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function f0(){return navigator.maxTouchPoints||"ontouchstart"in this}function I0(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],i=e.invertY(t[1][1])-n[1][1];return e.translate(o>r?(r+o)/2:Math.min(0,r)||Math.max(0,o),i>s?(s+i)/2:Math.min(0,s)||Math.max(0,i))}function aA(){var e=S0,t=R0,n=I0,r=A0,o=f0,s=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=As,E=hi("start","zoom","end"),d,u,T,S=500,f=150,A=0,O=10;function I(L){L.property("__zoom",fd).on("wheel.zoom",D,{passive:!1}).on("mousedown.zoom",g).on("dblclick.zoom",b).filter(o).on("touchstart.zoom",y).on("touchmove.zoom",M).on("touchend.zoom touchcancel.zoom",F).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}I.transform=function(L,v,P,w){var U=L.selection?L.selection():L;U.property("__zoom",fd),L!==U?C(L,v,P,w):U.interrupt().each(function(){m(this,arguments).event(w).start().zoom(null,typeof v=="function"?v.apply(this,arguments):v).end()})},I.scaleBy=function(L,v,P,w){I.scaleTo(L,function(){var U=this.__zoom.k,x=typeof v=="function"?v.apply(this,arguments):v;return U*x},P,w)},I.scaleTo=function(L,v,P,w){I.transform(L,function(){var U=t.apply(this,arguments),x=this.__zoom,B=P==null?h(U):typeof P=="function"?P.apply(this,arguments):P,H=x.invert(B),W=typeof v=="function"?v.apply(this,arguments):v;return n(N(p(x,W),B,H),U,i)},P,w)},I.translateBy=function(L,v,P,w){I.transform(L,function(){return n(this.__zoom.translate(typeof v=="function"?v.apply(this,arguments):v,typeof P=="function"?P.apply(this,arguments):P),t.apply(this,arguments),i)},null,w)},I.translateTo=function(L,v,P,w,U){I.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(_i.translate(H[0],H[1]).scale(B.k).translate(typeof v=="function"?-v.apply(this,arguments):-v,typeof P=="function"?-P.apply(this,arguments):-P),x,i)},w,U)};function p(L,v){return v=Math.max(s[0],Math.min(s[1],v)),v===L.k?L:new yt(v,L.x,L.y)}function N(L,v,P){var w=v[0]-P[0]*L.k,U=v[1]-P[1]*L.k;return w===L.x&&U===L.y?L:new yt(L.k,w,U)}function h(L){return[(+L[0][0]+ +L[1][0])/2,(+L[0][1]+ +L[1][1])/2]}function C(L,v,P,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 U=this,x=arguments,B=m(U,x).event(w),H=t.apply(U,x),W=P==null?h(H):typeof P=="function"?P.apply(U,x):P,$=Math.max(H[1][0]-H[0][0],H[1][1]-H[0][1]),X=U.__zoom,J=typeof v=="function"?v.apply(U,x):v,q=c(X.invert(W).concat($/X.k),J.invert(W).concat($/J.k));return function(z){if(z===1)z=J;else{var Y=q(z),K=$/Y[2];z=new yt(K,W[0]-Y[0]*K,W[1]-Y[1]*K)}B.zoom(null,z)}})}function m(L,v,P){return!P&&L.__zooming||new _(L,v)}function _(L,v){this.that=L,this.args=v,this.active=0,this.sourceEvent=null,this.extent=t.apply(L,v),this.taps=0}_.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,v){return this.mouse&&L!=="mouse"&&(this.mouse[1]=v.invert(this.mouse[0])),this.touch0&&L!=="touch"&&(this.touch0[1]=v.invert(this.touch0[0])),this.touch1&&L!=="touch"&&(this.touch1[1]=v.invert(this.touch1[0])),this.that.__zoom=v,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(L){var v=$e(this.that).datum();E.call(L,this.that,new T0(L,{sourceEvent:this.sourceEvent,target:I,transform:this.that.__zoom,dispatch:E}),v)}};function D(L,...v){if(!e.apply(this,arguments))return;var P=m(this,v).event(L),w=this.__zoom,U=Math.max(s[0],Math.min(s[1],w.k*Math.pow(2,r.apply(this,arguments)))),x=tt(L);if(P.wheel)(P.mouse[0][0]!==x[0]||P.mouse[0][1]!==x[1])&&(P.mouse[1]=w.invert(P.mouse[0]=x)),clearTimeout(P.wheel);else{if(w.k===U)return;P.mouse=[x,w.invert(x)],Os(this),P.start()}xr(L),P.wheel=setTimeout(B,f),P.zoom("mouse",n(N(p(w,U),P.mouse[0],P.mouse[1]),P.extent,i));function B(){P.wheel=null,P.end()}}function g(L,...v){if(T||!e.apply(this,arguments))return;var P=L.currentTarget,w=m(this,v,!0).event(L),U=$e(L.view).on("mousemove.zoom",W,!0).on("mouseup.zoom",$,!0),x=tt(L,P),B=L.clientX,H=L.clientY;VR(L.view),Ia(L),w.mouse=[x,this.__zoom.invert(x)],Os(this),w.start();function W(X){if(xr(X),!w.moved){var J=X.clientX-B,q=X.clientY-H;w.moved=J*J+q*q>A}w.event(X).zoom("mouse",n(N(w.that.__zoom,w.mouse[0]=tt(X,P),w.mouse[1]),w.extent,i))}function $(X){U.on("mousemove.zoom mouseup.zoom",null),jR(X.view,w.moved),xr(X),w.event(X).end()}}function b(L,...v){if(e.apply(this,arguments)){var P=this.__zoom,w=tt(L.changedTouches?L.changedTouches[0]:L,this),U=P.invert(w),x=P.k*(L.shiftKey?.5:2),B=n(N(p(P,x),w,U),t.apply(this,v),i);xr(L),l>0?$e(this).transition().duration(l).call(C,B,w,L):$e(this).call(I.transform,B,w,L)}}function y(L,...v){if(e.apply(this,arguments)){var P=L.touches,w=P.length,U=m(this,v,L.changedTouches.length===w).event(L),x,B,H,W;for(Ia(L),B=0;B<w;++B)H=P[B],W=tt(H,this),W=[W,this.__zoom.invert(W),H.identifier],U.touch0?!U.touch1&&U.touch0[2]!==W[2]&&(U.touch1=W,U.taps=0):(U.touch0=W,x=!0,U.taps=1+!!d);d&&(d=clearTimeout(d)),x&&(U.taps<2&&(u=W[0],d=setTimeout(function(){d=null},S)),Os(this),U.start())}}function M(L,...v){if(this.__zooming){var P=m(this,v).event(L),w=L.changedTouches,U=w.length,x,B,H,W;for(xr(L),x=0;x<U;++x)B=w[x],H=tt(B,this),P.touch0&&P.touch0[2]===B.identifier?P.touch0[0]=H:P.touch1&&P.touch1[2]===B.identifier&&(P.touch1[0]=H);if(B=P.that.__zoom,P.touch1){var $=P.touch0[0],X=P.touch0[1],J=P.touch1[0],q=P.touch1[1],z=(z=J[0]-$[0])*z+(z=J[1]-$[1])*z,Y=(Y=q[0]-X[0])*Y+(Y=q[1]-X[1])*Y;B=p(B,Math.sqrt(z/Y)),H=[($[0]+J[0])/2,($[1]+J[1])/2],W=[(X[0]+q[0])/2,(X[1]+q[1])/2]}else if(P.touch0)H=P.touch0[0],W=P.touch0[1];else return;P.zoom("touch",n(N(B,H,W),P.extent,i))}}function F(L,...v){if(this.__zooming){var P=m(this,v).event(L),w=L.changedTouches,U=w.length,x,B;for(Ia(L),T&&clearTimeout(T),T=setTimeout(function(){T=null},S),x=0;x<U;++x)B=w[x],P.touch0&&P.touch0[2]===B.identifier?delete P.touch0:P.touch1&&P.touch1[2]===B.identifier&&delete P.touch1;if(P.touch1&&!P.touch0&&(P.touch0=P.touch1,delete P.touch1),P.touch0)P.touch0[1]=this.__zoom.invert(P.touch0[0]);else if(P.end(),P.taps===2&&(B=tt(B,this),Math.hypot(u[0]-B[0],u[1]-B[1])<O)){var H=$e(this).on("dblclick.zoom");H&&H.apply(this,arguments)}}}return I.wheelDelta=function(L){return arguments.length?(r=typeof L=="function"?L:os(+L),I):r},I.filter=function(L){return arguments.length?(e=typeof L=="function"?L:os(!!L),I):e},I.touchable=function(L){return arguments.length?(o=typeof L=="function"?L:os(!!L),I):o},I.extent=function(L){return arguments.length?(t=typeof L=="function"?L:os([[+L[0][0],+L[0][1]],[+L[1][0],+L[1][1]]]),I):t},I.scaleExtent=function(L){return arguments.length?(s[0]=+L[0],s[1]=+L[1],I):[s[0],s[1]]},I.translateExtent=function(L){return arguments.length?(i[0][0]=+L[0][0],i[1][0]=+L[1][0],i[0][1]=+L[0][1],i[1][1]=+L[1][1],I):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},I.constrain=function(L){return arguments.length?(n=L,I):n},I.duration=function(L){return arguments.length?(l=+L,I):l},I.interpolate=function(L){return arguments.length?(c=L,I):c},I.on=function(){var L=E.on.apply(E,arguments);return L===E?I:L},I.clickDistance=function(L){return arguments.length?(A=(L=+L)*L,I):Math.sqrt(A)},I.tapDistance=function(L){return arguments.length?(O=+L,I):O},I}const Nt={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."},Qr=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],lA=["Enter"," ","Escape"],cA={"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 or;(function(e){e.Strict="strict",e.Loose="loose"})(or||(or={}));var Rn;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Rn||(Rn={}));var Zr;(function(e){e.Partial="partial",e.Full="full"})(Zr||(Zr={}));const EA={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 sr;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(sr||(sr={}));var ee;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(ee||(ee={}));const Id={[ee.Left]:ee.Right,[ee.Right]:ee.Left,[ee.Top]:ee.Bottom,[ee.Bottom]:ee.Top};function dA(e){return e===null?null:e?"valid":"invalid"}const uA=e=>"id"in e&&"source"in e&&"target"in e,O0=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),Mc=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),So=(e,t=[0,0])=>{const{width:n,height:r}=Ut(e),o=e.origin??t,s=n*o[0],i=r*o[1];return{x:e.position.x-s,y:e.position.y-i}},N0=(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 i=!t.nodeLookup&&!s?o:void 0;t.nodeLookup&&(i=s?t.nodeLookup.get(o):Mc(o)?o:t.nodeLookup.get(o.id));const l=i?$s(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return gi(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return xi(n)},Ro=(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=gi(n,$s(o)),r=!0)}),r?xi(n):{x:0,y:0,width:0,height:0}},bc=(e,t,[n,r,o]=[0,0,1],s=!1,i=!1)=>{const l={...fo(t,[n,r,o]),width:t.width/o,height:t.height/o},c=[];for(const E of e.values()){const{measured:d,selectable:u=!0,hidden:T=!1}=E;if(i&&!u||T)continue;const S=d.width??E.width??E.initialWidth??null,f=d.height??E.height??E.initialHeight??null,A=eo(l,ar(E)),O=(S??0)*(f??0),I=s&&A>0;(!E.internals.handleBounds||I||A>=O||E.dragging)&&c.push(E)}return c},p0=(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 h0(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 C0({nodes:e,width:t,height:n,panZoom:r,minZoom:o,maxZoom:s},i){if(e.size===0)return Promise.resolve(!0);const l=h0(e,i),c=Ro(l),E=vc(c,t,n,(i==null?void 0:i.minZoom)??o,(i==null?void 0:i.maxZoom)??s,(i==null?void 0:i.padding)??.1);return await r.setViewport(E,{duration:i==null?void 0:i.duration,ease:i==null?void 0:i.ease,interpolate:i==null?void 0:i.interpolate}),Promise.resolve(!0)}function TA({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:o,onError:s}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:E}=l?l.internals.positionAbsolute:{x:0,y:0},d=i.origin??r;let u=i.extent||o;if(i.extent==="parent"&&!i.expandParent)if(!l)s==null||s("005",Nt.error005());else{const S=l.measured.width,f=l.measured.height;S&&f&&(u=[[c,E],[c+S,E+f]])}else l&&lr(i.extent)&&(u=[[i.extent[0][0]+c,i.extent[0][1]+E],[i.extent[1][0]+c,i.extent[1][1]+E]]);const T=lr(u)?pn(t,u,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&(s==null||s("015",Nt.error015())),{position:{x:T.x-c+(i.measured.width??0)*d[0],y:T.y-E+(i.measured.height??0)*d[1]},positionAbsolute:T}}async function m0({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:o}){const s=new Set(e.map(T=>T.id)),i=[];for(const T of n){if(T.deletable===!1)continue;const S=s.has(T.id),f=!S&&T.parentId&&i.find(A=>A.id===T.parentId);(S||f)&&i.push(T)}const l=new Set(t.map(T=>T.id)),c=r.filter(T=>T.deletable!==!1),d=p0(i,c);for(const T of c)l.has(T.id)&&!d.find(f=>f.id===T.id)&&d.push(T);if(!o)return{edges:d,nodes:i};const u=await o({nodes:i,edges:d});return typeof u=="boolean"?u?{edges:d,nodes:i}:{edges:[],nodes:[]}:u}const ir=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),pn=(e={x:0,y:0},t,n)=>({x:ir(e.x,t[0][0],t[1][0]-((n==null?void 0:n.width)??0)),y:ir(e.y,t[0][1],t[1][1]-((n==null?void 0:n.height)??0))});function SA(e,t,n){const{width:r,height:o}=Ut(n),{x:s,y:i}=n.internals.positionAbsolute;return pn(e,[[s,i],[s+r,i+o]],t)}const Od=(e,t,n)=>e<t?ir(Math.abs(e-t),1,t)/t:e>n?-ir(Math.abs(e-n),1,t)/t:0,RA=(e,t,n=15,r=40)=>{const o=Od(e.x,r,t.width-r)*n,s=Od(e.y,r,t.height-r)*n;return[o,s]},gi=(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)}),Dl=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),xi=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),ar=(e,t=[0,0])=>{var o,s;const{x:n,y:r}=Mc(e)?e.internals.positionAbsolute:So(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}},$s=(e,t=[0,0])=>{var o,s;const{x:n,y:r}=Mc(e)?e.internals.positionAbsolute:So(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)}},AA=(e,t)=>xi(gi(Dl(e),Dl(t))),eo=(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)},Nd=e=>rt(e.width)&&rt(e.height)&&rt(e.x)&&rt(e.y),rt=e=>!isNaN(e)&&isFinite(e),L0=(e,t)=>{},Ao=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),fo=({x:e,y:t},[n,r,o],s=!1,i=[1,1])=>{const l={x:(e-n)/o,y:(t-r)/o};return s?Ao(l,i):l},Xs=({x:e,y:t},[n,r,o])=>({x:e*o+n,y:t*o+r});function Bn(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 _0(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=Bn(e,n),o=Bn(e,t);return{top:r,right:o,bottom:r,left:o,x:o*2,y:r*2}}if(typeof e=="object"){const r=Bn(e.top??e.y??0,n),o=Bn(e.bottom??e.y??0,n),s=Bn(e.left??e.x??0,t),i=Bn(e.right??e.x??0,t);return{top:r,right:i,bottom:o,left:s,x:s+i,y:r+o}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function g0(e,t,n,r,o,s){const{x:i,y:l}=Xs(e,[t,n,r]),{x:c,y:E}=Xs({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=o-c,u=s-E;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(u)}}const vc=(e,t,n,r,o,s)=>{const i=_0(s,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,E=Math.min(l,c),d=ir(E,r,o),u=e.x+e.width/2,T=e.y+e.height/2,S=t/2-u*d,f=n/2-T*d,A=g0(e,S,f,d,t,n),O={left:Math.min(A.left-i.left,0),top:Math.min(A.top-i.top,0),right:Math.min(A.right-i.right,0),bottom:Math.min(A.bottom-i.bottom,0)};return{x:S-O.left+O.right,y:f-O.top+O.bottom,zoom:d}},to=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0};function lr(e){return e!=null&&e!=="parent"}function Ut(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 fA(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 IA(e,t={width:0,height:0},n,r,o){const s={...e},i=r.get(n);if(i){const l=i.origin||o;s.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],s.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return s}function pd(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function x0(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function y0(e){return{...cA,...e||{}}}function Br(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:o}){const{x:s,y:i}=ot(e),l=fo({x:s-((o==null?void 0:o.left)??0),y:i-((o==null?void 0:o.top)??0)},r),{x:c,y:E}=n?Ao(l,t):l;return{xSnapped:c,ySnapped:E,...l}}const Uc=e=>({width:e.offsetWidth,height:e.offsetHeight}),OA=e=>{var t;return((t=e==null?void 0:e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},D0=["INPUT","SELECT","TEXTAREA"];function NA(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:D0.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const pA=e=>"clientX"in e,ot=(e,t)=>{var s,i;const n=pA(e),r=n?e.clientX:(s=e.touches)==null?void 0:s[0].clientX,o=n?e.clientY:(i=e.touches)==null?void 0:i[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(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:o,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...Uc(i)}})};function hA({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:o,sourceControlY:s,targetControlX:i,targetControlY:l}){const c=e*.125+o*.375+i*.375+n*.125,E=t*.125+s*.375+l*.375+r*.125,d=Math.abs(c-e),u=Math.abs(E-t);return[c,E,d,u]}function ss(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Cd({pos:e,x1:t,y1:n,x2:r,y2:o,c:s}){switch(e){case ee.Left:return[t-ss(t-r,s),n];case ee.Right:return[t+ss(r-t,s),n];case ee.Top:return[t,n-ss(n-o,s)];case ee.Bottom:return[t,n+ss(o-n,s)]}}function CA({sourceX:e,sourceY:t,sourcePosition:n=ee.Bottom,targetX:r,targetY:o,targetPosition:s=ee.Top,curvature:i=.25}){const[l,c]=Cd({pos:n,x1:e,y1:t,x2:r,y2:o,c:i}),[E,d]=Cd({pos:s,x1:r,y1:o,x2:e,y2:t,c:i}),[u,T,S,f]=hA({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:l,sourceControlY:c,targetControlX:E,targetControlY:d});return[`M${e},${t} C${l},${c} ${E},${d} ${r},${o}`,u,T,S,f]}function mA({sourceX:e,sourceY:t,targetX:n,targetY:r}){const o=Math.abs(n-e)/2,s=n<e?n+o:n-o,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[s,l,o,i]}function P0({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:o=!1,zIndexMode:s="basic"}){if(s==="manual")return r;const i=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 i+l}function M0({sourceNode:e,targetNode:t,width:n,height:r,transform:o}){const s=gi($s(e),$s(t));s.x===s.x2&&(s.x2+=1),s.y===s.y2&&(s.y2+=1);const i={x:-o[0]/o[2],y:-o[1]/o[2],width:n/o[2],height:r/o[2]};return eo(i,xi(s))>0}const b0=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,v0=(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)),U0=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||b0;let o;return uA(e)?o={...e}:o={...e,id:r(e)},v0(o,t)?t:(o.sourceHandle===null&&delete o.sourceHandle,o.targetHandle===null&&delete o.targetHandle,t.concat(o))};function LA({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[o,s,i,l]=mA({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,o,s,i,l]}const md={[ee.Left]:{x:-1,y:0},[ee.Right]:{x:1,y:0},[ee.Top]:{x:0,y:-1},[ee.Bottom]:{x:0,y:1}},w0=({source:e,sourcePosition:t=ee.Bottom,target:n})=>t===ee.Left||t===ee.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},Ld=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function B0({source:e,sourcePosition:t=ee.Bottom,target:n,targetPosition:r=ee.Top,center:o,offset:s,stepPosition:i}){const l=md[t],c=md[r],E={x:e.x+l.x*s,y:e.y+l.y*s},d={x:n.x+c.x*s,y:n.y+c.y*s},u=w0({source:E,sourcePosition:t,target:d}),T=u.x!==0?"x":"y",S=u[T];let f=[],A,O;const I={x:0,y:0},p={x:0,y:0},[,,N,h]=mA({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[T]*c[T]===-1){T==="x"?(A=o.x??E.x+(d.x-E.x)*i,O=o.y??(E.y+d.y)/2):(A=o.x??(E.x+d.x)/2,O=o.y??E.y+(d.y-E.y)*i);const m=[{x:A,y:E.y},{x:A,y:d.y}],_=[{x:E.x,y:O},{x:d.x,y:O}];l[T]===S?f=T==="x"?m:_:f=T==="x"?_:m}else{const m=[{x:E.x,y:d.y}],_=[{x:d.x,y:E.y}];if(T==="x"?f=l.x===S?_:m:f=l.y===S?m:_,t===r){const M=Math.abs(e[T]-n[T]);if(M<=s){const F=Math.min(s-1,s-M);l[T]===S?I[T]=(E[T]>e[T]?-1:1)*F:p[T]=(d[T]>n[T]?-1:1)*F}}if(t!==r){const M=T==="x"?"y":"x",F=l[T]===c[M],L=E[M]>d[M],v=E[M]<d[M];(l[T]===1&&(!F&&L||F&&v)||l[T]!==1&&(!F&&v||F&&L))&&(f=T==="x"?m:_)}const D={x:E.x+I.x,y:E.y+I.y},g={x:d.x+p.x,y:d.y+p.y},b=Math.max(Math.abs(D.x-f[0].x),Math.abs(g.x-f[0].x)),y=Math.max(Math.abs(D.y-f[0].y),Math.abs(g.y-f[0].y));b>=y?(A=(D.x+g.x)/2,O=f[0].y):(A=f[0].x,O=(D.y+g.y)/2)}return[[e,{x:E.x+I.x,y:E.y+I.y},...f,{x:d.x+p.x,y:d.y+p.y},n],A,O,N,h]}function F0(e,t,n,r){const o=Math.min(Ld(e,t)/2,Ld(t,n)/2,r),{x:s,y:i}=t;if(e.x===s&&s===n.x||e.y===i&&i===n.y)return`L${s} ${i}`;if(e.y===i){const E=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${s+o*E},${i}Q ${s},${i} ${s},${i+o*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${s},${i+o*c}Q ${s},${i} ${s+o*l},${i}`}function Pl({sourceX:e,sourceY:t,sourcePosition:n=ee.Bottom,targetX:r,targetY:o,targetPosition:s=ee.Top,borderRadius:i=5,centerX:l,centerY:c,offset:E=20,stepPosition:d=.5}){const[u,T,S,f,A]=B0({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:o},targetPosition:s,center:{x:l,y:c},offset:E,stepPosition:d});return[u.reduce((I,p,N)=>{let h="";return N>0&&N<u.length-1?h=F0(u[N-1],p,u[N+1],i):h=`${N===0?"M":"L"}${p.x} ${p.y}`,I+=h,I},""),T,S,f,A]}function _d(e){var t;return e&&!!(e.internals.handleBounds||(t=e.handles)!=null&&t.length)&&!!(e.measured.width||e.width||e.initialWidth)}function G0(e){var u;const{sourceNode:t,targetNode:n}=e;if(!_d(t)||!_d(n))return null;const r=t.internals.handleBounds||gd(t.handles),o=n.internals.handleBounds||gd(n.handles),s=xd((r==null?void 0:r.source)??[],e.sourceHandle),i=xd(e.connectionMode===or.Strict?(o==null?void 0:o.target)??[]:((o==null?void 0:o.target)??[]).concat((o==null?void 0:o.source)??[]),e.targetHandle);if(!s||!i)return(u=e.onError)==null||u.call(e,"008",Nt.error008(s?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=(s==null?void 0:s.position)||ee.Bottom,c=(i==null?void 0:i.position)||ee.Top,E=hn(t,s,l),d=hn(n,i,c);return{sourceX:E.x,sourceY:E.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function gd(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=ee.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:i,height:l}=t??Ut(e);if(r)return{x:o+i/2,y:s+l/2};switch((t==null?void 0:t.position)??n){case ee.Top:return{x:o+i/2,y:s};case ee.Right:return{x:o+i,y:s+l/2};case ee.Bottom:return{x:o+i/2,y:s+l};case ee.Left:return{x:o,y:s+l/2}}}function xd(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Ml(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function H0(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:o}){const s=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||o].forEach(c=>{if(c&&typeof c=="object"){const E=Ml(c,t);s.has(E)||(i.push({id:E,color:c.color||n,...c}),s.add(E))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const _A=1e3,Y0=10,wc={nodeOrigin:[0,0],nodeExtent:Qr,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},k0={...wc,checkEquality:!0};function Bc(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function W0(e,t,n){const r=Bc(wc,n);for(const o of e.values())if(o.parentId)Gc(o,e,t,r);else{const s=So(o,r.nodeOrigin),i=lr(o.extent)?o.extent:r.nodeExtent,l=pn(s,i,Ut(o));o.internals.positionAbsolute=l}}function V0(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 Fc(e){return e==="manual"}function bl(e,t,n,r={}){var E,d;const o=Bc(k0,r),s={i:0},i=new Map(t),l=o!=null&&o.elevateNodesOnSelect&&!Fc(o.zIndexMode)?_A:0;let c=e.length>0;t.clear(),n.clear();for(const u of e){let T=i.get(u.id);if(o.checkEquality&&u===(T==null?void 0:T.internals.userNode))t.set(u.id,T);else{const S=So(u,o.nodeOrigin),f=lr(u.extent)?u.extent:o.nodeExtent,A=pn(S,f,Ut(u));T={...o.defaults,...u,measured:{width:(E=u.measured)==null?void 0:E.width,height:(d=u.measured)==null?void 0:d.height},internals:{positionAbsolute:A,handleBounds:V0(u,T),z:gA(u,l,o.zIndexMode),userNode:u}},t.set(u.id,T)}(T.measured===void 0||T.measured.width===void 0||T.measured.height===void 0)&&!T.hidden&&(c=!1),u.parentId&&Gc(T,t,n,r,s)}return c}function j0(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 Gc(e,t,n,r,o){const{elevateNodesOnSelect:s,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=Bc(wc,r),E=e.parentId,d=t.get(E);if(!d){console.warn(`Parent node ${E} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}j0(e,n),o&&!d.parentId&&d.internals.rootParentIndex===void 0&&c==="auto"&&(d.internals.rootParentIndex=++o.i,d.internals.z=d.internals.z+o.i*Y0),o&&d.internals.rootParentIndex!==void 0&&(o.i=d.internals.rootParentIndex);const u=s&&!Fc(c)?_A:0,{x:T,y:S,z:f}=$0(e,d,i,l,u,c),{positionAbsolute:A}=e.internals,O=T!==A.x||S!==A.y;(O||f!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:O?{x:T,y:S}:A,z:f}})}function gA(e,t,n){const r=rt(e.zIndex)?e.zIndex:0;return Fc(n)?r:r+(e.selected?t:0)}function $0(e,t,n,r,o,s){const{x:i,y:l}=t.internals.positionAbsolute,c=Ut(e),E=So(e,n),d=lr(e.extent)?pn(E,e.extent,c):E;let u=pn({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(u=SA(u,c,t));const T=gA(e,o,s),S=t.internals.z??0;return{x:u.x,y:u.y,z:S>=T?S+1:T}}function Hc(e,t,n,r=[0,0]){var i;const o=[],s=new Map;for(const l of e){const c=t.get(l.parentId);if(!c)continue;const E=((i=s.get(l.parentId))==null?void 0:i.expandedRect)??ar(c),d=AA(E,l.rect);s.set(l.parentId,{expandedRect:d,parent:c})}return s.size>0&&s.forEach(({expandedRect:l,parent:c},E)=>{var N;const d=c.internals.positionAbsolute,u=Ut(c),T=c.origin??r,S=l.x<d.x?Math.round(Math.abs(d.x-l.x)):0,f=l.y<d.y?Math.round(Math.abs(d.y-l.y)):0,A=Math.max(u.width,Math.round(l.width)),O=Math.max(u.height,Math.round(l.height)),I=(A-u.width)*T[0],p=(O-u.height)*T[1];(S>0||f>0||I||p)&&(o.push({id:E,type:"position",position:{x:c.position.x-S+I,y:c.position.y-f+p}}),(N=n.get(E))==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+f}})})),(u.width<l.width||u.height<l.height||S||f)&&o.push({id:E,type:"dimensions",setAttributes:!0,dimensions:{width:A+(S?T[0]*S-I:0),height:O+(f?T[1]*f-p:0)}})}),o}function X0(e,t,n,r,o,s,i){const l=r==null?void 0:r.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const E=[],d=window.getComputedStyle(l),{m22:u}=new window.DOMMatrixReadOnly(d.transform),T=[];for(const S of e.values()){const f=t.get(S.id);if(!f)continue;if(f.hidden){t.set(f.id,{...f,internals:{...f.internals,handleBounds:void 0}}),c=!0;continue}const A=Uc(S.nodeElement),O=f.measured.width!==A.width||f.measured.height!==A.height;if(!!(A.width&&A.height&&(O||!f.internals.handleBounds||S.force))){const p=S.nodeElement.getBoundingClientRect(),N=lr(f.extent)?f.extent:s;let{positionAbsolute:h}=f.internals;f.parentId&&f.extent==="parent"?h=SA(h,A,t.get(f.parentId)):N&&(h=pn(h,N,A));const C={...f,measured:A,internals:{...f.internals,positionAbsolute:h,handleBounds:{source:hd("source",S.nodeElement,p,u,f.id),target:hd("target",S.nodeElement,p,u,f.id)}}};t.set(f.id,C),f.parentId&&Gc(C,t,n,{nodeOrigin:o,zIndexMode:i}),c=!0,O&&(E.push({id:f.id,type:"dimensions",dimensions:A}),f.expandParent&&f.parentId&&T.push({id:f.id,parentId:f.parentId,rect:ar(C,o)}))}}if(T.length>0){const S=Hc(T,t,n,o);E.push(...S)}return{changes:E,updatedInternals:c}}async function K0({delta:e,panZoom:t,transform:n,translateExtent:r,width:o,height:s}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[o,s]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function yd(e,t,n,r,o,s){let i=o;const l=r.get(i)||new Map;r.set(i,l.set(n,t)),i=`${o}-${e}`;const c=r.get(i)||new Map;if(r.set(i,c.set(n,t)),s){i=`${o}-${e}-${s}`;const E=r.get(i)||new Map;r.set(i,E.set(n,t))}}function xA(e,t,n){e.clear(),t.clear();for(const r of n){const{source:o,target:s,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:o,target:s,sourceHandle:i,targetHandle:l},E=`${o}-${i}--${s}-${l}`,d=`${s}-${l}--${o}-${i}`;yd("source",c,d,e,o,i),yd("target",c,E,e,s,l),t.set(r.id,r)}}function yA(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:yA(n,t):!1}function Dd(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 z0(e,t,n,r){const o=new Map;for(const[s,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!yA(i,e))&&(i.draggable||t&&typeof i.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 Oa({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){var i,l,c;const o=[];for(const[E,d]of t){const u=(i=n.get(E))==null?void 0:i.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:((c=t.get(e))==null?void 0:c.position)||s.position,dragging:r}:o[0],o]}function J0({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},i=Ao(s,t);return{x:i.x-s.x,y:i.y-s.y}}function q0({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:o}){let s={x:null,y:null},i=0,l=new Map,c=!1,E={x:0,y:0},d=null,u=!1,T=null,S=!1,f=!1,A=null;function O({noDragClassName:p,handleSelector:N,domNode:h,isSelectable:C,nodeId:m,nodeClickDistance:_=0}){T=$e(h);function D({x:M,y:F}){const{nodeLookup:L,nodeExtent:v,snapGrid:P,snapToGrid:w,nodeOrigin:U,onNodeDrag:x,onSelectionDrag:B,onError:H,updateNodePositions:W}=t();s={x:M,y:F};let $=!1;const X=l.size>1,J=X&&v?Dl(Ro(l)):null,q=X&&w?J0({dragItems:l,snapGrid:P,x:M,y:F}):null;for(const[z,Y]of l){if(!L.has(z))continue;let K={x:M-Y.distance.x,y:F-Y.distance.y};w&&(K=q?{x:Math.round(K.x+q.x),y:Math.round(K.y+q.y)}:Ao(K,P));let le=null;if(X&&v&&!Y.extent&&J){const{positionAbsolute:te}=Y.internals,Ee=te.x-J.x+v[0][0],fe=te.x+Y.measured.width-J.x2+v[1][0],de=te.y-J.y+v[0][1],Re=te.y+Y.measured.height-J.y2+v[1][1];le=[[Ee,de],[fe,Re]]}const{position:se,positionAbsolute:ne}=TA({nodeId:z,nextPosition:K,nodeLookup:L,nodeExtent:le||v,nodeOrigin:U,onError:H});$=$||Y.position.x!==se.x||Y.position.y!==se.y,Y.position=se,Y.internals.positionAbsolute=ne}if(f=f||$,!!$&&(W(l,!0),A&&(r||x||!m&&B))){const[z,Y]=Oa({nodeId:m,dragItems:l,nodeLookup:L});r==null||r(A,l,z,Y),x==null||x(A,z,Y),m||B==null||B(A,Y)}}async function g(){if(!d)return;const{transform:M,panBy:F,autoPanSpeed:L,autoPanOnNodeDrag:v}=t();if(!v){c=!1,cancelAnimationFrame(i);return}const[P,w]=RA(E,d,L);(P!==0||w!==0)&&(s.x=(s.x??0)-P/M[2],s.y=(s.y??0)-w/M[2],await F({x:P,y:w})&&D(s)),i=requestAnimationFrame(g)}function b(M){var X;const{nodeLookup:F,multiSelectionActive:L,nodesDraggable:v,transform:P,snapGrid:w,snapToGrid:U,selectNodesOnDrag:x,onNodeDragStart:B,onSelectionDragStart:H,unselectNodesAndEdges:W}=t();u=!0,(!x||!C)&&!L&&m&&((X=F.get(m))!=null&&X.selected||W()),C&&x&&m&&(e==null||e(m));const $=Br(M.sourceEvent,{transform:P,snapGrid:w,snapToGrid:U,containerBounds:d});if(s=$,l=z0(F,v,$,m),l.size>0&&(n||B||!m&&H)){const[J,q]=Oa({nodeId:m,dragItems:l,nodeLookup:F});n==null||n(M.sourceEvent,l,J,q),B==null||B(M.sourceEvent,J,q),m||H==null||H(M.sourceEvent,q)}}const y=$R().clickDistance(_).on("start",M=>{const{domNode:F,nodeDragThreshold:L,transform:v,snapGrid:P,snapToGrid:w}=t();d=(F==null?void 0:F.getBoundingClientRect())||null,S=!1,f=!1,A=M.sourceEvent,L===0&&b(M),s=Br(M.sourceEvent,{transform:v,snapGrid:P,snapToGrid:w,containerBounds:d}),E=ot(M.sourceEvent,d)}).on("drag",M=>{const{autoPanOnNodeDrag:F,transform:L,snapGrid:v,snapToGrid:P,nodeDragThreshold:w,nodeLookup:U}=t(),x=Br(M.sourceEvent,{transform:L,snapGrid:v,snapToGrid:P,containerBounds:d});if(A=M.sourceEvent,(M.sourceEvent.type==="touchmove"&&M.sourceEvent.touches.length>1||m&&!U.has(m))&&(S=!0),!S){if(!c&&F&&u&&(c=!0,g()),!u){const B=ot(M.sourceEvent,d),H=B.x-E.x,W=B.y-E.y;Math.sqrt(H*H+W*W)>w&&b(M)}(s.x!==x.xSnapped||s.y!==x.ySnapped)&&l&&u&&(E=ot(M.sourceEvent,d),D(x))}}).on("end",M=>{if(!(!u||S)&&(c=!1,u=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:F,updateNodePositions:L,onNodeDragStop:v,onSelectionDragStop:P}=t();if(f&&(L(l,!1),f=!1),o||v||!m&&P){const[w,U]=Oa({nodeId:m,dragItems:l,nodeLookup:F,dragging:!1});o==null||o(M.sourceEvent,l,w,U),v==null||v(M.sourceEvent,w,U),m||P==null||P(M.sourceEvent,U)}}}).filter(M=>{const F=M.target;return!M.button&&(!p||!Dd(F,`.${p}`,h))&&(!N||Dd(F,N,h))});T.call(y)}function I(){T==null||T.on(".drag",null)}return{update:O,destroy:I}}function Q0(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())eo(o,ar(s))>0&&r.push(s);return r}const Z0=250;function eP(e,t,n,r){var l,c;let o=[],s=1/0;const i=Q0(e,n,t+Z0);for(const E of i){const d=[...((l=E.internals.handleBounds)==null?void 0:l.source)??[],...((c=E.internals.handleBounds)==null?void 0:c.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(E,u,u.position,!0),f=Math.sqrt(Math.pow(T-e.x,2)+Math.pow(S-e.y,2));f>t||(f<s?(o=[{...u,x:T,y:S}],s=f):f===s&&o.push({...u,x:T,y:S}))}}if(!o.length)return null;if(o.length>1){const E=r.type==="source"?"target":"source";return o.find(d=>d.type===E)??o[0]}return o[0]}function DA(e,t,n,r,o,s=!1){var E,d,u;const i=r.get(e);if(!i)return null;const l=o==="strict"?(E=i.internals.handleBounds)==null?void 0:E[t]:[...((d=i.internals.handleBounds)==null?void 0:d.source)??[],...((u=i.internals.handleBounds)==null?void 0:u.target)??[]],c=(n?l==null?void 0:l.find(T=>T.id===n):l==null?void 0:l[0])??null;return c&&s?{...c,...hn(i,c,c.position,!0)}:c}function PA(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function tP(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const MA=()=>!0;function nP(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:o,edgeUpdaterType:s,isTarget:i,domNode:l,nodeLookup:c,lib:E,autoPanOnConnect:d,flowId:u,panBy:T,cancelConnection:S,onConnectStart:f,onConnect:A,onConnectEnd:O,isValidConnection:I=MA,onReconnectEnd:p,updateConnection:N,getTransform:h,getFromHandle:C,autoPanSpeed:m,dragThreshold:_=1,handleDomNode:D}){const g=OA(e.target);let b=0,y;const{x:M,y:F}=ot(e),L=PA(s,D),v=l==null?void 0:l.getBoundingClientRect();let P=!1;if(!v||!L)return;const w=DA(o,L,r,c,t);if(!w)return;let U=ot(e,v),x=!1,B=null,H=!1,W=null;function $(){if(!d||!v)return;const[se,ne]=RA(U,v,m);T({x:se,y:ne}),b=requestAnimationFrame($)}const X={...w,nodeId:o,type:L,position:w.position},J=c.get(o);let z={inProgress:!0,isValid:null,from:hn(J,X,ee.Left,!0),fromHandle:X,fromPosition:X.position,fromNode:J,to:U,toHandle:null,toPosition:Id[X.position],toNode:null,pointer:U};function Y(){P=!0,N(z),f==null||f(e,{nodeId:o,handleId:r,handleType:L})}_===0&&Y();function K(se){if(!P){const{x:Re,y:He}=ot(se),Me=Re-M,dt=He-F;if(!(Me*Me+dt*dt>_*_))return;Y()}if(!C()||!X){le(se);return}const ne=h();U=ot(se,v),y=eP(fo(U,ne,!1,[1,1]),n,c,X),x||($(),x=!0);const te=bA(se,{handle:y,connectionMode:t,fromNodeId:o,fromHandleId:r,fromType:i?"target":"source",isValidConnection:I,doc:g,lib:E,flowId:u,nodeLookup:c});W=te.handleDomNode,B=te.connection,H=tP(!!y,te.isValid);const Ee=c.get(o),fe=Ee?hn(Ee,X,ee.Left,!0):z.from,de={...z,from:fe,isValid:H,to:te.toHandle&&H?Xs({x:te.toHandle.x,y:te.toHandle.y},ne):U,toHandle:te.toHandle,toPosition:H&&te.toHandle?te.toHandle.position:Id[X.position],toNode:te.toHandle?c.get(te.toHandle.nodeId):null,pointer:U};N(de),z=de}function le(se){if(!("touches"in se&&se.touches.length>0)){if(P){(y||W)&&B&&H&&(A==null||A(B));const{inProgress:ne,...te}=z,Ee={...te,toPosition:z.toHandle?z.toPosition:null};O==null||O(se,Ee),s&&(p==null||p(se,Ee))}S(),cancelAnimationFrame(b),x=!1,H=!1,B=null,W=null,g.removeEventListener("mousemove",K),g.removeEventListener("mouseup",le),g.removeEventListener("touchmove",K),g.removeEventListener("touchend",le)}}g.addEventListener("mousemove",K),g.addEventListener("mouseup",le),g.addEventListener("touchmove",K),g.addEventListener("touchend",le)}function bA(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:o,fromType:s,doc:i,lib:l,flowId:c,isValidConnection:E=MA,nodeLookup:d}){const u=s==="target",T=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t==null?void 0:t.nodeId}-${t==null?void 0:t.id}-${t==null?void 0:t.type}"]`):null,{x:S,y:f}=ot(e),A=i.elementFromPoint(S,f),O=A!=null&&A.classList.contains(`${l}-flow__handle`)?A:T,I={handleDomNode:O,isValid:!1,connection:null,toHandle:null};if(O){const p=PA(void 0,O),N=O.getAttribute("data-nodeid"),h=O.getAttribute("data-handleid"),C=O.classList.contains("connectable"),m=O.classList.contains("connectableend");if(!N||!p)return I;const _={source:u?N:r,sourceHandle:u?h:o,target:u?r:N,targetHandle:u?o:h};I.connection=_;const g=C&&m&&(n===or.Strict?u&&p==="source"||!u&&p==="target":N!==r||h!==o);I.isValid=g&&E(_),I.toHandle=DA(N,p,h,d,n,!0)}return I}const vl={onPointerDown:nP,isValid:bA};function rP({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const o=$e(e);function s({translateExtent:l,width:c,height:E,zoomStep:d=1,pannable:u=!0,zoomable:T=!0,inversePan:S=!1}){const f=N=>{if(N.sourceEvent.type!=="wheel"||!t)return;const h=n(),C=N.sourceEvent.ctrlKey&&to()?10:1,m=-N.sourceEvent.deltaY*(N.sourceEvent.deltaMode===1?.05:N.sourceEvent.deltaMode?1:.002)*d,_=h[2]*Math.pow(2,m*C);t.scaleTo(_)};let A=[0,0];const O=N=>{(N.sourceEvent.type==="mousedown"||N.sourceEvent.type==="touchstart")&&(A=[N.sourceEvent.clientX??N.sourceEvent.touches[0].clientX,N.sourceEvent.clientY??N.sourceEvent.touches[0].clientY])},I=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]-A[0],C[1]-A[1]];A=C;const _=r()*Math.max(h[2],Math.log(h[2]))*(S?-1:1),D={x:h[0]-m[0]*_,y:h[1]-m[1]*_},g=[[0,0],[c,E]];t.setViewportConstrained({x:D.x,y:D.y,zoom:h[2]},g,l)},p=aA().on("start",O).on("zoom",u?I:null).on("zoom.wheel",T?f:null);o.call(p,{})}function i(){o.on("zoom",null)}return{update:s,destroy:i,pointer:tt}}const yi=e=>({x:e.x,y:e.y,zoom:e.k}),Na=({x:e,y:t,zoom:n})=>_i.translate(e,t).scale(n),Vn=(e,t)=>e.target.closest(`.${t}`),vA=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),oP=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,pa=(e,t=0,n=oP,r=()=>{})=>{const o=typeof t=="number"&&t>0;return o||r(),o?e.transition().duration(t).ease(n).on("end",r):e},UA=e=>{const t=e.ctrlKey&&to()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function sP({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:o,panOnScrollSpeed:s,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:E}){return d=>{if(Vn(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const u=n.property("__zoom").k||1;if(d.ctrlKey&&i){const O=tt(d),I=UA(d),p=u*Math.pow(2,I);r.scaleTo(n,p,O,d);return}const T=d.deltaMode===1?20:1;let S=o===Rn.Vertical?0:d.deltaX*T,f=o===Rn.Horizontal?0:d.deltaY*T;!to()&&d.shiftKey&&o!==Rn.Vertical&&(S=d.deltaY*T,f=0),r.translateBy(n,-(S/u)*s,-(f/u)*s,{internal:!0});const A=yi(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c==null||c(d,A),e.panScrollTimeout=setTimeout(()=>{E==null||E(d,A),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l==null||l(d,A))}}function iP({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,o){const s=r.type==="wheel",i=!t&&s&&!r.ctrlKey,l=Vn(r,e);if(r.ctrlKey&&s&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,o)}}function aP({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{var s,i,l;if((s=r.sourceEvent)!=null&&s.internal)return;const o=yi(r.transform);e.mouseButton=((i=r.sourceEvent)==null?void 0:i.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 lP({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:o}){return s=>{var i,l;e.usedRightMouseButton=!!(n&&vA(t,e.mouseButton??0)),(i=s.sourceEvent)!=null&&i.sync||r([s.transform.x,s.transform.y,s.transform.k]),o&&!((l=s.sourceEvent)!=null&&l.internal)&&(o==null||o(s.sourceEvent,yi(s.transform)))}}function cP({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:o,onPaneContextMenu:s}){return i=>{var l;if(!((l=i.sourceEvent)!=null&&l.internal)&&(e.isZoomingOrPanning=!1,s&&vA(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&s(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),o)){const c=yi(i.transform);e.prevViewport=c,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{o==null||o(i.sourceEvent,c)},n?150:0)}}}function EP({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:o,zoomOnDoubleClick:s,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:E,connectionInProgress:d}){return u=>{var O;const T=e||t,S=n&&u.ctrlKey,f=u.type==="wheel";if(u.button===1&&u.type==="mousedown"&&(Vn(u,`${E}-flow__node`)||Vn(u,`${E}-flow__edge`)))return!0;if(!r&&!T&&!o&&!s&&!n||i||d&&!f||Vn(u,l)&&f||Vn(u,c)&&(!f||o&&f&&!e)||!n&&u.ctrlKey&&f)return!1;if(!n&&u.type==="touchstart"&&((O=u.touches)==null?void 0:O.length)>1)return u.preventDefault(),!1;if(!T&&!o&&!S&&f||!r&&(u.type==="mousedown"||u.type==="touchstart")||Array.isArray(r)&&!r.includes(u.button)&&u.type==="mousedown")return!1;const A=Array.isArray(r)&&r.includes(u.button)||!u.button||u.button<=1;return(!u.ctrlKey||f)&&A}}function dP({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:o,onPanZoom:s,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const E={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),u=aA().scaleExtent([t,n]).translateExtent(r),T=$e(e).call(u);p({x:o.x,y:o.y,zoom:ir(o.zoom,t,n)},[[0,0],[d.width,d.height]],r);const S=T.on("wheel.zoom"),f=T.on("dblclick.zoom");u.wheelDelta(UA);function A(y,M){return T?new Promise(F=>{u==null||u.interpolate((M==null?void 0:M.interpolate)==="linear"?wr:As).transform(pa(T,M==null?void 0:M.duration,M==null?void 0:M.ease,()=>F(!0)),y)}):Promise.resolve(!1)}function O({noWheelClassName:y,noPanClassName:M,onPaneContextMenu:F,userSelectionActive:L,panOnScroll:v,panOnDrag:P,panOnScrollMode:w,panOnScrollSpeed:U,preventScrolling:x,zoomOnPinch:B,zoomOnScroll:H,zoomOnDoubleClick:W,zoomActivationKeyPressed:$,lib:X,onTransformChange:J,connectionInProgress:q,paneClickDistance:z,selectionOnDrag:Y}){L&&!E.isZoomingOrPanning&&I();const K=v&&!$&&!L;u.clickDistance(Y?1/0:!rt(z)||z<0?0:z);const le=K?sP({zoomPanValues:E,noWheelClassName:y,d3Selection:T,d3Zoom:u,panOnScrollMode:w,panOnScrollSpeed:U,zoomOnPinch:B,onPanZoomStart:i,onPanZoom:s,onPanZoomEnd:l}):iP({noWheelClassName:y,preventScrolling:x,d3ZoomHandler:S});if(T.on("wheel.zoom",le,{passive:!1}),!L){const ne=aP({zoomPanValues:E,onDraggingChange:c,onPanZoomStart:i});u.on("start",ne);const te=lP({zoomPanValues:E,panOnDrag:P,onPaneContextMenu:!!F,onPanZoom:s,onTransformChange:J});u.on("zoom",te);const Ee=cP({zoomPanValues:E,panOnDrag:P,panOnScroll:v,onPaneContextMenu:F,onPanZoomEnd:l,onDraggingChange:c});u.on("end",Ee)}const se=EP({zoomActivationKeyPressed:$,panOnDrag:P,zoomOnScroll:H,panOnScroll:v,zoomOnDoubleClick:W,zoomOnPinch:B,userSelectionActive:L,noPanClassName:M,noWheelClassName:y,lib:X,connectionInProgress:q});u.filter(se),W?T.on("dblclick.zoom",f):T.on("dblclick.zoom",null)}function I(){u.on("zoom",null)}async function p(y,M,F){const L=Na(y),v=u==null?void 0:u.constrain()(L,M,F);return v&&await A(v),new Promise(P=>P(v))}async function N(y,M){const F=Na(y);return await A(F,M),new Promise(L=>L(F))}function h(y){if(T){const M=Na(y),F=T.property("__zoom");(F.k!==y.zoom||F.x!==y.x||F.y!==y.y)&&(u==null||u.transform(T,M,null,{sync:!0}))}}function C(){const y=T?iA(T.node()):{x:0,y:0,k:1};return{x:y.x,y:y.y,zoom:y.k}}function m(y,M){return T?new Promise(F=>{u==null||u.interpolate((M==null?void 0:M.interpolate)==="linear"?wr:As).scaleTo(pa(T,M==null?void 0:M.duration,M==null?void 0:M.ease,()=>F(!0)),y)}):Promise.resolve(!1)}function _(y,M){return T?new Promise(F=>{u==null||u.interpolate((M==null?void 0:M.interpolate)==="linear"?wr:As).scaleBy(pa(T,M==null?void 0:M.duration,M==null?void 0:M.ease,()=>F(!0)),y)}):Promise.resolve(!1)}function D(y){u==null||u.scaleExtent(y)}function g(y){u==null||u.translateExtent(y)}function b(y){const M=!rt(y)||y<0?0:y;u==null||u.clickDistance(M)}return{update:O,destroy:I,setViewport:N,setViewportConstrained:p,getViewport:C,scaleTo:m,scaleBy:_,setScaleExtent:D,setTranslateExtent:g,syncViewport:h,setClickDistance:b}}var cr;(function(e){e.Line="line",e.Handle="handle"})(cr||(cr={}));function uP({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:o,affectsY:s}){const i=e-t,l=n-r,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&o&&(c[0]=c[0]*-1),l&&s&&(c[1]=c[1]*-1),c}function Pd(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 Wt(e,t){return Math.max(0,t-e)}function Vt(e,t){return Math.max(0,e-t)}function is(e,t,n){return Math.max(0,t-e,e-n)}function Md(e,t){return e?!t:t}function TP(e,t,n,r,o,s,i,l){let{affectsX:c,affectsY:E}=t;const{isHorizontal:d,isVertical:u}=t,T=d&&u,{xSnapped:S,ySnapped:f}=n,{minWidth:A,maxWidth:O,minHeight:I,maxHeight:p}=r,{x:N,y:h,width:C,height:m,aspectRatio:_}=e;let D=Math.floor(d?S-e.pointerX:0),g=Math.floor(u?f-e.pointerY:0);const b=C+(c?-D:D),y=m+(E?-g:g),M=-s[0]*C,F=-s[1]*m;let L=is(b,A,O),v=is(y,I,p);if(i){let U=0,x=0;c&&D<0?U=Wt(N+D+M,i[0][0]):!c&&D>0&&(U=Vt(N+b+M,i[1][0])),E&&g<0?x=Wt(h+g+F,i[0][1]):!E&&g>0&&(x=Vt(h+y+F,i[1][1])),L=Math.max(L,U),v=Math.max(v,x)}if(l){let U=0,x=0;c&&D>0?U=Vt(N+D,l[0][0]):!c&&D<0&&(U=Wt(N+b,l[1][0])),E&&g>0?x=Vt(h+g,l[0][1]):!E&&g<0&&(x=Wt(h+y,l[1][1])),L=Math.max(L,U),v=Math.max(v,x)}if(o){if(d){const U=is(b/_,I,p)*_;if(L=Math.max(L,U),i){let x=0;!c&&!E||c&&!E&&T?x=Vt(h+F+b/_,i[1][1])*_:x=Wt(h+F+(c?D:-D)/_,i[0][1])*_,L=Math.max(L,x)}if(l){let x=0;!c&&!E||c&&!E&&T?x=Wt(h+b/_,l[1][1])*_:x=Vt(h+(c?D:-D)/_,l[0][1])*_,L=Math.max(L,x)}}if(u){const U=is(y*_,A,O)/_;if(v=Math.max(v,U),i){let x=0;!c&&!E||E&&!c&&T?x=Vt(N+y*_+M,i[1][0])/_:x=Wt(N+(E?g:-g)*_+M,i[0][0])/_,v=Math.max(v,x)}if(l){let x=0;!c&&!E||E&&!c&&T?x=Wt(N+y*_,l[1][0])/_:x=Vt(N+(E?g:-g)*_,l[0][0])/_,v=Math.max(v,x)}}}g=g+(g<0?v:-v),D=D+(D<0?L:-L),o&&(T?b>y*_?g=(Md(c,E)?-D:D)/_:D=(Md(c,E)?-g:g)*_:d?(g=D/_,E=c):(D=g*_,c=E));const P=c?N+D:N,w=E?h+g:h;return{width:C+(c?-D:D),height:m+(E?-g:g),x:s[0]*D*(c?-1:1)+P,y:s[1]*g*(E?-1:1)+w}}const wA={width:0,height:0,x:0,y:0},SP={...wA,pointerX:0,pointerY:0,aspectRatio:1};function RP(e){return[[0,0],[e.measured.width,e.measured.height]]}function AP(e,t,n){const r=t.position.x+e.position.x,o=t.position.y+e.position.y,s=e.measured.width??0,i=e.measured.height??0,l=n[0]*s,c=n[1]*i;return[[r-l,o-c],[r+s-l,o+i-c]]}function fP({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:o}){const s=$e(e);let i={controlDirection:Pd("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:E,boundaries:d,keepAspectRatio:u,resizeDirection:T,onResizeStart:S,onResize:f,onResizeEnd:A,shouldResize:O}){let I={...wA},p={...SP};i={boundaries:d,resizeDirection:T,keepAspectRatio:u,controlDirection:Pd(E)};let N,h=null,C=[],m,_,D,g=!1;const b=$R().on("start",y=>{const{nodeLookup:M,transform:F,snapGrid:L,snapToGrid:v,nodeOrigin:P,paneDomNode:w}=n();if(N=M.get(t),!N)return;h=(w==null?void 0:w.getBoundingClientRect())??null;const{xSnapped:U,ySnapped:x}=Br(y.sourceEvent,{transform:F,snapGrid:L,snapToGrid:v,containerBounds:h});I={width:N.measured.width??0,height:N.measured.height??0,x:N.position.x??0,y:N.position.y??0},p={...I,pointerX:U,pointerY:x,aspectRatio:I.width/I.height},m=void 0,N.parentId&&(N.extent==="parent"||N.expandParent)&&(m=M.get(N.parentId),_=m&&N.extent==="parent"?RP(m):void 0),C=[],D=void 0;for(const[B,H]of M)if(H.parentId===t&&(C.push({id:B,position:{...H.position},extent:H.extent}),H.extent==="parent"||H.expandParent)){const W=AP(H,N,H.origin??P);D?D=[[Math.min(W[0][0],D[0][0]),Math.min(W[0][1],D[0][1])],[Math.max(W[1][0],D[1][0]),Math.max(W[1][1],D[1][1])]]:D=W}S==null||S(y,{...I})}).on("drag",y=>{const{transform:M,snapGrid:F,snapToGrid:L,nodeOrigin:v}=n(),P=Br(y.sourceEvent,{transform:M,snapGrid:F,snapToGrid:L,containerBounds:h}),w=[];if(!N)return;const{x:U,y:x,width:B,height:H}=I,W={},$=N.origin??v,{width:X,height:J,x:q,y:z}=TP(p,i.controlDirection,P,i.boundaries,i.keepAspectRatio,$,_,D),Y=X!==B,K=J!==H,le=q!==U&&Y,se=z!==x&&K;if(!le&&!se&&!Y&&!K)return;if((le||se||$[0]===1||$[1]===1)&&(W.x=le?q:I.x,W.y=se?z:I.y,I.x=W.x,I.y=W.y,C.length>0)){const fe=q-U,de=z-x;for(const Re of C)Re.position={x:Re.position.x-fe+$[0]*(X-B),y:Re.position.y-de+$[1]*(J-H)},w.push(Re)}if((Y||K)&&(W.width=Y&&(!i.resizeDirection||i.resizeDirection==="horizontal")?X:I.width,W.height=K&&(!i.resizeDirection||i.resizeDirection==="vertical")?J:I.height,I.width=W.width,I.height=W.height),m&&N.expandParent){const fe=$[0]*(W.width??0);W.x&&W.x<fe&&(I.x=fe,p.x=p.x-(W.x-fe));const de=$[1]*(W.height??0);W.y&&W.y<de&&(I.y=de,p.y=p.y-(W.y-de))}const ne=uP({width:I.width,prevWidth:B,height:I.height,prevHeight:H,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),te={...I,direction:ne};(O==null?void 0:O(y,te))!==!1&&(g=!0,f==null||f(y,te),r(W,w))}).on("end",y=>{g&&(A==null||A(y,{...I}),o==null||o({...I}),g=!1)});s.call(b)}function c(){s.on(".drag",null)}return{update:l,destroy:c}}var ha={exports:{}},Ca={},ma={exports:{}},La={};/**
|
|
474
|
+
* @license React
|
|
475
|
+
* use-sync-external-store-shim.production.js
|
|
476
|
+
*
|
|
477
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
478
|
+
*
|
|
479
|
+
* This source code is licensed under the MIT license found in the
|
|
480
|
+
* LICENSE file in the root directory of this source tree.
|
|
481
|
+
*/var bd;function IP(){if(bd)return La;bd=1;var e=ei();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,i=e.useDebugValue;function l(u,T){var S=T(),f=r({inst:{value:S,getSnapshot:T}}),A=f[0].inst,O=f[1];return s(function(){A.value=S,A.getSnapshot=T,c(A)&&O({inst:A})},[u,S,T]),o(function(){return c(A)&&O({inst:A}),u(function(){c(A)&&O({inst:A})})},[u]),i(S),S}function c(u){var T=u.getSnapshot;u=u.value;try{var S=T();return!n(u,S)}catch{return!0}}function E(u,T){return T()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?E:l;return La.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:d,La}var vd;function OP(){return vd||(vd=1,ma.exports=IP()),ma.exports}/**
|
|
482
|
+
* @license React
|
|
483
|
+
* use-sync-external-store-shim/with-selector.production.js
|
|
484
|
+
*
|
|
485
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
486
|
+
*
|
|
487
|
+
* This source code is licensed under the MIT license found in the
|
|
488
|
+
* LICENSE file in the root directory of this source tree.
|
|
489
|
+
*/var Ud;function NP(){if(Ud)return Ca;Ud=1;var e=ei(),t=OP();function n(E,d){return E===d&&(E!==0||1/E===1/d)||E!==E&&d!==d}var r=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,s=e.useRef,i=e.useEffect,l=e.useMemo,c=e.useDebugValue;return Ca.useSyncExternalStoreWithSelector=function(E,d,u,T,S){var f=s(null);if(f.current===null){var A={hasValue:!1,value:null};f.current=A}else A=f.current;f=l(function(){function I(m){if(!p){if(p=!0,N=m,m=T(m),S!==void 0&&A.hasValue){var _=A.value;if(S(_,m))return h=_}return h=m}if(_=h,r(N,m))return _;var D=T(m);return S!==void 0&&S(_,D)?(N=m,_):(N=m,h=D)}var p=!1,N,h,C=u===void 0?null:u;return[function(){return I(d())},C===null?void 0:function(){return I(C())}]},[d,u,T,S]);var O=o(E,f[0],f[1]);return i(function(){A.hasValue=!0,A.value=O},[O]),c(O),O},Ca}var wd;function pP(){return wd||(wd=1,ha.exports=NP()),ha.exports}var hP=pP();const CP=ti(hP),mP={},Bd=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(f=>f(t,S))}},o=()=>t,c={setState:r,getState:o,getInitialState:()=>E,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(mP?"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()}},E=t=e(r,o,c);return c},LP=e=>e?Bd(e):Bd,{useDebugValue:_P}=Ce,{useSyncExternalStoreWithSelector:gP}=CP,xP=e=>e;function BA(e,t=xP,n){const r=gP(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return _P(r),r}const Fd=(e,t)=>{const n=LP(e),r=(o,s=t)=>BA(n,o,s);return Object.assign(r,n),r},yP=(e,t)=>e?Fd(e,t):Fd;function Oe(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 Di=R.createContext(null),DP=Di.Provider,FA=Nt.error001();function Se(e,t){const n=R.useContext(Di);if(n===null)throw new Error(FA);return BA(n,e,t)}function pe(){const e=R.useContext(Di);if(e===null)throw new Error(FA);return R.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const Gd={display:"none"},PP={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},GA="react-flow__node-desc",HA="react-flow__edge-desc",MP="react-flow__aria-live",bP=e=>e.ariaLiveMessage,vP=e=>e.ariaLabelConfig;function UP({rfId:e}){const t=Se(bP);return a.jsx("div",{id:`${MP}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:PP,children:t})}function wP({rfId:e,disableKeyboardA11y:t}){const n=Se(vP);return a.jsxs(a.Fragment,{children:[a.jsx("div",{id:`${GA}-${e}`,style:Gd,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),a.jsx("div",{id:`${HA}-${e}`,style:Gd,children:n["edge.a11yDescription.default"]}),!t&&a.jsx(UP,{rfId:e})]})}const Er=R.forwardRef(({position:e="top-left",children:t,className:n,style:r,...o},s)=>{const i=`${e}`.split("-");return a.jsx("div",{className:_e(["react-flow__panel",n,...i]),style:r,ref:s,...o,children:t})});Er.displayName="Panel";function BP({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:a.jsx(Er,{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:a.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const FP=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}},as=e=>e.id;function GP(e,t){return Oe(e.selectedNodes.map(as),t.selectedNodes.map(as))&&Oe(e.selectedEdges.map(as),t.selectedEdges.map(as))}function HP({onSelectionChange:e}){const t=pe(),{selectedNodes:n,selectedEdges:r}=Se(FP,GP);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 YP=e=>!!e.onSelectionChangeHandlers;function kP({onSelectionChange:e}){const t=Se(YP);return e||t?a.jsx(HP,{onSelectionChange:e}):null}const YA=[0,0],WP={x:0,y:0,zoom:1},VP=["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"],Hd=[...VP,"rfId"],jP=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}),Yd={translateExtent:Qr,nodeOrigin:YA,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function $P(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:o,setTranslateExtent:s,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Se(jP,Oe),E=pe();R.useEffect(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=Yd,l()}),[]);const d=R.useRef(Yd);return R.useEffect(()=>{for(const u of Hd){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"?i(T):u==="ariaLabelConfig"?E.setState({ariaLabelConfig:y0(T)}):u==="fitView"?E.setState({fitViewQueued:T}):u==="fitViewOptions"?E.setState({fitViewOptions:T}):E.setState({[u]:T})))}d.current=e},Hd.map(u=>e[u])),null}function kd(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function XP(e){var r;const[t,n]=R.useState(e==="system"?null:e);return R.useEffect(()=>{if(e!=="system"){n(e);return}const o=kd(),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=kd())!=null&&r.matches?"dark":"light"}const Wd=typeof document<"u"?document:null;function no(e=null,t={target:Wd,actInsideInputWithModifier:!0}){const[n,r]=R.useState(!1),o=R.useRef(!1),s=R.useRef(new Set([])),[i,l]=R.useMemo(()=>{if(e!==null){const E=(Array.isArray(e)?e:[e]).filter(u=>typeof u=="string").map(u=>u.replace("+",`
|
|
490
|
+
`).replace(`
|
|
491
|
+
|
|
492
|
+
`,`
|
|
493
|
+
+`).split(`
|
|
494
|
+
`)),d=E.reduce((u,T)=>u.concat(...T),[]);return[E,d]}return[[],[]]},[e]);return R.useEffect(()=>{const c=(t==null?void 0:t.target)??Wd,E=(t==null?void 0:t.actInsideInputWithModifier)??!0;if(e!==null){const d=S=>{var O,I;if(o.current=S.ctrlKey||S.metaKey||S.shiftKey||S.altKey,(!o.current||o.current&&!E)&&NA(S))return!1;const A=jd(S.code,l);if(s.current.add(S[A]),Vd(i,s.current,!1)){const p=((I=(O=S.composedPath)==null?void 0:O.call(S))==null?void 0:I[0])||S.target,N=(p==null?void 0:p.nodeName)==="BUTTON"||(p==null?void 0:p.nodeName)==="A";t.preventDefault!==!1&&(o.current||!N)&&S.preventDefault(),r(!0)}},u=S=>{const f=jd(S.code,l);Vd(i,s.current,!0)?(r(!1),s.current.clear()):s.current.delete(S[f]),S.key==="Meta"&&s.current.clear(),o.current=!1},T=()=>{s.current.clear(),r(!1)};return c==null||c.addEventListener("keydown",d),c==null||c.addEventListener("keyup",u),window.addEventListener("blur",T),window.addEventListener("contextmenu",T),()=>{c==null||c.removeEventListener("keydown",d),c==null||c.removeEventListener("keyup",u),window.removeEventListener("blur",T),window.removeEventListener("contextmenu",T)}}},[e,r]),n}function Vd(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(o=>t.has(o)))}function jd(e,t){return t.includes(e)?"code":"key"}const KP=()=>{const e=pe();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:i}=e.getState();return i?(await i.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:i,panZoom:l}=e.getState(),c=vc(t,r,o,s,i,(n==null?void 0:n.padding)??.1);return l?(await l.setViewport(c,{duration:n==null?void 0:n.duration,ease:n==null?void 0:n.ease,interpolate:n==null?void 0:n.interpolate}),Promise.resolve(!0)):Promise.resolve(!1)},screenToFlowPosition:(t,n={})=>{const{transform:r,snapGrid:o,snapToGrid:s,domNode:i}=e.getState();if(!i)return t;const{x:l,y:c}=i.getBoundingClientRect(),E={x:t.x-l,y:t.y-c},d=n.snapGrid??o,u=n.snapToGrid??s;return fo(E,r,u,d)},flowToScreenPosition:t=>{const{transform:n,domNode:r}=e.getState();if(!r)return t;const{x:o,y:s}=r.getBoundingClientRect(),i=Xs(t,n);return{x:i.x+o,y:i.y+s}}}),[])};function kA(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 i=r.get(s.id);i?i.push(s):r.set(s.id,[s])}for(const s of t){const i=r.get(s.id);if(!i){n.push(s);continue}if(i[0].type==="remove")continue;if(i[0].type==="replace"){n.push({...i[0].item});continue}const l={...s};for(const c of i)zP(c,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 zP(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 WA(e,t){return kA(e,t)}function VA(e,t){return kA(e,t)}function dn(e,t){return{id:e,type:"select",selected:t}}function jn(e,t=new Set,n=!1){const r=[];for(const[o,s]of e){const i=t.has(o);!(s.selected===void 0&&!i)&&s.selected!==i&&(n&&(s.selected=i),r.push(dn(s.id,i)))}return r}function $d({items:e=[],lookup:t}){var o;const n=[],r=new Map(e.map(s=>[s.id,s]));for(const[s,i]of e.entries()){const l=t.get(i.id),c=((o=l==null?void 0:l.internals)==null?void 0:o.userNode)??l;c!==void 0&&c!==i&&n.push({id:i.id,item:i,type:"replace"}),c===void 0&&n.push({item:i,type:"add",index:s})}for(const[s]of t)r.get(s)===void 0&&n.push({id:s,type:"remove"});return n}function Xd(e){return{id:e.id,type:"remove"}}const Kd=e=>O0(e),JP=e=>uA(e);function jA(e){return R.forwardRef(e)}const qP=typeof window<"u"?R.useLayoutEffect:R.useEffect;function zd(e){const[t,n]=R.useState(BigInt(0)),[r]=R.useState(()=>QP(()=>n(o=>o+BigInt(1))));return qP(()=>{const o=r.get();o.length&&(e(o),r.reset())},[t]),r}function QP(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}const $A=R.createContext(null);function ZP({children:e}){const t=pe(),n=R.useCallback(l=>{const{nodes:c=[],setNodes:E,hasDefaultNodes:d,onNodesChange:u,nodeLookup:T,fitViewQueued:S,onNodesChangeMiddlewareMap:f}=t.getState();let A=c;for(const I of l)A=typeof I=="function"?I(A):I;let O=$d({items:A,lookup:T});for(const I of f.values())O=I(O);d&&E(A),O.length>0?u==null||u(O):S&&window.requestAnimationFrame(()=>{const{fitViewQueued:I,nodes:p,setNodes:N}=t.getState();I&&N(p)})},[]),r=zd(n),o=R.useCallback(l=>{const{edges:c=[],setEdges:E,hasDefaultEdges:d,onEdgesChange:u,edgeLookup:T}=t.getState();let S=c;for(const f of l)S=typeof f=="function"?f(S):f;d?E(S):u&&u($d({items:S,lookup:T}))},[]),s=zd(o),i=R.useMemo(()=>({nodeQueue:r,edgeQueue:s}),[]);return a.jsx($A.Provider,{value:i,children:e})}function eM(){const e=R.useContext($A);if(!e)throw new Error("useBatchContext must be used within a BatchProvider");return e}const tM=e=>!!e.panZoom;function Yc(){const e=KP(),t=pe(),n=eM(),r=Se(tM),o=R.useMemo(()=>{const s=u=>t.getState().nodeLookup.get(u),i=u=>{n.nodeQueue.push(u)},l=u=>{n.edgeQueue.push(u)},c=u=>{var I,p;const{nodeLookup:T,nodeOrigin:S}=t.getState(),f=Kd(u)?u:T.get(u.id),A=f.parentId?IA(f.position,f.measured,f.parentId,T,S):f.position,O={...f,position:A,width:((I=f.measured)==null?void 0:I.width)??f.width,height:((p=f.measured)==null?void 0:p.height)??f.height};return ar(O)},E=(u,T,S={replace:!1})=>{i(f=>f.map(A=>{if(A.id===u){const O=typeof T=="function"?T(A):T;return S.replace&&Kd(O)?O:{...A,...O}}return A}))},d=(u,T,S={replace:!1})=>{l(f=>f.map(A=>{if(A.id===u){const O=typeof T=="function"?T(A):T;return S.replace&&JP(O)?O:{...A,...O}}return A}))};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:i,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(),[f,A,O]=S;return{nodes:u.map(I=>({...I})),edges:T.map(I=>({...I})),viewport:{x:f,y:A,zoom:O}}},deleteElements:async({nodes:u=[],edges:T=[]})=>{const{nodes:S,edges:f,onNodesDelete:A,onEdgesDelete:O,triggerNodeChanges:I,triggerEdgeChanges:p,onDelete:N,onBeforeDelete:h}=t.getState(),{nodes:C,edges:m}=await m0({nodesToRemove:u,edgesToRemove:T,nodes:S,edges:f,onBeforeDelete:h}),_=m.length>0,D=C.length>0;if(_){const g=m.map(Xd);O==null||O(m),p(g)}if(D){const g=C.map(Xd);A==null||A(C),I(g)}return(D||_)&&(N==null||N({nodes:C,edges:m})),{deletedNodes:C,deletedEdges:m}},getIntersectingNodes:(u,T=!0,S)=>{const f=Nd(u),A=f?u:c(u),O=S!==void 0;return A?(S||t.getState().nodes).filter(I=>{const p=t.getState().nodeLookup.get(I.id);if(p&&!f&&(I.id===u.id||!p.internals.positionAbsolute))return!1;const N=ar(O?I:p),h=eo(N,A);return T&&h>0||h>=N.width*N.height||h>=A.width*A.height}):[]},isNodeIntersecting:(u,T,S=!0)=>{const A=Nd(u)?u:c(u);if(!A)return!1;const O=eo(A,T);return S&&O>0||O>=T.width*T.height||O>=A.width*A.height},updateNode:E,updateNodeData:(u,T,S={replace:!1})=>{E(u,f=>{const A=typeof T=="function"?T(f):T;return S.replace?{...f,data:A}:{...f,data:{...f.data,...A}}},S)},updateEdge:d,updateEdgeData:(u,T,S={replace:!1})=>{d(u,f=>{const A=typeof T=="function"?T(f):T;return S.replace?{...f,data:A}:{...f,data:{...f.data,...A}}},S)},getNodesBounds:u=>{const{nodeLookup:T,nodeOrigin:S}=t.getState();return N0(u,{nodeLookup:T,nodeOrigin:S})},getHandleConnections:({type:u,id:T,nodeId:S})=>{var f;return Array.from(((f=t.getState().connectionLookup.get(`${S}-${u}${T?`-${T}`:""}`))==null?void 0:f.values())??[])},getNodeConnections:({type:u,handleId:T,nodeId:S})=>{var f;return Array.from(((f=t.getState().connectionLookup.get(`${S}${u?T?`-${u}-${T}`:`-${u}`:""}`))==null?void 0:f.values())??[])},fitView:async u=>{const T=t.getState().fitViewResolver??x0();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 Jd=e=>e.selected,nM=typeof window<"u"?window:void 0;function rM({deleteKeyCode:e,multiSelectionKeyCode:t}){const n=pe(),{deleteElements:r}=Yc(),o=no(e,{actInsideInputWithModifier:!1}),s=no(t,{target:nM});R.useEffect(()=>{if(o){const{edges:i,nodes:l}=n.getState();r({nodes:l.filter(Jd),edges:i.filter(Jd)}),n.setState({nodesSelectionActive:!1})}},[o]),R.useEffect(()=>{n.setState({multiSelectionActive:s})},[s])}function oM(e){const t=pe();R.useEffect(()=>{const n=()=>{var o,s,i,l;if(!e.current||!(((s=(o=e.current).checkVisibility)==null?void 0:s.call(o))??!0))return!1;const r=Uc(e.current);(r.height===0||r.width===0)&&((l=(i=t.getState()).onError)==null||l.call(i,"004",Nt.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 Pi={position:"absolute",width:"100%",height:"100%",top:0,left:0},sM=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function iM({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panOnScrollSpeed:o=.5,panOnScrollMode:s=Rn.Free,zoomOnDoubleClick:i=!0,panOnDrag:l=!0,defaultViewport:c,translateExtent:E,minZoom:d,maxZoom:u,zoomActivationKeyCode:T,preventScrolling:S=!0,children:f,noWheelClassName:A,noPanClassName:O,onViewportChange:I,isControlledViewport:p,paneClickDistance:N,selectionOnDrag:h}){const C=pe(),m=R.useRef(null),{userSelectionActive:_,lib:D,connectionInProgress:g}=Se(sM,Oe),b=no(T),y=R.useRef();oM(m);const M=R.useCallback(F=>{I==null||I({x:F[0],y:F[1],zoom:F[2]}),p||C.setState({transform:F})},[I,p]);return R.useEffect(()=>{if(m.current){y.current=dP({domNode:m.current,minZoom:d,maxZoom:u,translateExtent:E,viewport:c,onDraggingChange:P=>C.setState(w=>w.paneDragging===P?w:{paneDragging:P}),onPanZoomStart:(P,w)=>{const{onViewportChangeStart:U,onMoveStart:x}=C.getState();x==null||x(P,w),U==null||U(w)},onPanZoom:(P,w)=>{const{onViewportChange:U,onMove:x}=C.getState();x==null||x(P,w),U==null||U(w)},onPanZoomEnd:(P,w)=>{const{onViewportChangeEnd:U,onMoveEnd:x}=C.getState();x==null||x(P,w),U==null||U(w)}});const{x:F,y:L,zoom:v}=y.current.getViewport();return C.setState({panZoom:y.current,transform:[F,L,v],domNode:m.current.closest(".react-flow")}),()=>{var P;(P=y.current)==null||P.destroy()}}},[]),R.useEffect(()=>{var F;(F=y.current)==null||F.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panOnScrollSpeed:o,panOnScrollMode:s,zoomOnDoubleClick:i,panOnDrag:l,zoomActivationKeyPressed:b,preventScrolling:S,noPanClassName:O,userSelectionActive:_,noWheelClassName:A,lib:D,onTransformChange:M,connectionInProgress:g,selectionOnDrag:h,paneClickDistance:N})},[e,t,n,r,o,s,i,l,b,S,O,_,A,D,M,g,h,N]),a.jsx("div",{className:"react-flow__renderer",ref:m,style:Pi,children:f})}const aM=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function lM(){const{userSelectionActive:e,userSelectionRect:t}=Se(aM,Oe);return e&&t?a.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 _a=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},cM=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function EM({isSelecting:e,selectionKeyPressed:t,selectionMode:n=Zr.Full,panOnDrag:r,paneClickDistance:o,selectionOnDrag:s,onSelectionStart:i,onSelectionEnd:l,onPaneClick:c,onPaneContextMenu:E,onPaneScroll:d,onPaneMouseEnter:u,onPaneMouseMove:T,onPaneMouseLeave:S,children:f}){const A=pe(),{userSelectionActive:O,elementsSelectable:I,dragging:p,connectionInProgress:N}=Se(cM,Oe),h=I&&(e||O),C=R.useRef(null),m=R.useRef(),_=R.useRef(new Set),D=R.useRef(new Set),g=R.useRef(!1),b=U=>{if(g.current||N){g.current=!1;return}c==null||c(U),A.getState().resetSelectedElements(),A.setState({nodesSelectionActive:!1})},y=U=>{if(Array.isArray(r)&&(r!=null&&r.includes(2))){U.preventDefault();return}E==null||E(U)},M=d?U=>d(U):void 0,F=U=>{g.current&&(U.stopPropagation(),g.current=!1)},L=U=>{var J,q;const{domNode:x}=A.getState();if(m.current=x==null?void 0:x.getBoundingClientRect(),!m.current)return;const B=U.target===C.current;if(!B&&!!U.target.closest(".nokey")||!e||!(s&&B||t)||U.button!==0||!U.isPrimary)return;(q=(J=U.target)==null?void 0:J.setPointerCapture)==null||q.call(J,U.pointerId),g.current=!1;const{x:$,y:X}=ot(U.nativeEvent,m.current);A.setState({userSelectionRect:{width:0,height:0,startX:$,startY:X,x:$,y:X}}),B||(U.stopPropagation(),U.preventDefault())},v=U=>{const{userSelectionRect:x,transform:B,nodeLookup:H,edgeLookup:W,connectionLookup:$,triggerNodeChanges:X,triggerEdgeChanges:J,defaultEdgeOptions:q,resetSelectedElements:z}=A.getState();if(!m.current||!x)return;const{x:Y,y:K}=ot(U.nativeEvent,m.current),{startX:le,startY:se}=x;if(!g.current){const de=t?0:o;if(Math.hypot(Y-le,K-se)<=de)return;z(),i==null||i(U)}g.current=!0;const ne={startX:le,startY:se,x:Y<le?Y:le,y:K<se?K:se,width:Math.abs(Y-le),height:Math.abs(K-se)},te=_.current,Ee=D.current;_.current=new Set(bc(H,ne,B,n===Zr.Partial,!0).map(de=>de.id)),D.current=new Set;const fe=(q==null?void 0:q.selectable)??!0;for(const de of _.current){const Re=$.get(de);if(Re)for(const{edgeId:He}of Re.values()){const Me=W.get(He);Me&&(Me.selectable??fe)&&D.current.add(He)}}if(!pd(te,_.current)){const de=jn(H,_.current,!0);X(de)}if(!pd(Ee,D.current)){const de=jn(W,D.current);J(de)}A.setState({userSelectionRect:ne,userSelectionActive:!0,nodesSelectionActive:!1})},P=U=>{var x,B;U.button===0&&((B=(x=U.target)==null?void 0:x.releasePointerCapture)==null||B.call(x,U.pointerId),!O&&U.target===C.current&&A.getState().userSelectionRect&&(b==null||b(U)),A.setState({userSelectionActive:!1,userSelectionRect:null}),g.current&&(l==null||l(U),A.setState({nodesSelectionActive:_.current.size>0})))},w=r===!0||Array.isArray(r)&&r.includes(0);return a.jsxs("div",{className:_e(["react-flow__pane",{draggable:w,dragging:p,selection:e}]),onClick:h?void 0:_a(b,C),onContextMenu:_a(y,C),onWheel:_a(M,C),onPointerEnter:h?void 0:u,onPointerMove:h?v:T,onPointerUp:h?P:void 0,onPointerDownCapture:h?L:void 0,onClickCapture:h?F:void 0,onPointerLeave:S,ref:C,style:Pi,children:[f,a.jsx(lM,{})]})}function Ul({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:o,unselectNodesAndEdges:s,multiSelectionActive:i,nodeLookup:l,onError:c}=t.getState(),E=l.get(e);if(!E){c==null||c("012",Nt.error012(e));return}t.setState({nodesSelectionActive:!1}),E.selected?(n||E.selected&&i)&&(s({nodes:[E],edges:[]}),requestAnimationFrame(()=>{var d;return(d=r==null?void 0:r.current)==null?void 0:d.blur()})):o([e])}function XA({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:o,isSelectable:s,nodeClickDistance:i}){const l=pe(),[c,E]=R.useState(!1),d=R.useRef();return R.useEffect(()=>{d.current=q0({getStoreItems:()=>l.getState(),onNodeMouseDown:u=>{Ul({id:u,store:l,nodeRef:e})},onDragStart:()=>{E(!0)},onDragStop:()=>{E(!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:i}),()=>{var u;(u=d.current)==null||u.destroy()}},[n,r,t,s,e,o,i]),c}const dM=e=>t=>t.selected&&(t.draggable||e&&typeof t.draggable>"u");function KA(){const e=pe();return R.useCallback(n=>{const{nodeExtent:r,snapToGrid:o,snapGrid:s,nodesDraggable:i,onError:l,updateNodePositions:c,nodeLookup:E,nodeOrigin:d}=e.getState(),u=new Map,T=dM(i),S=o?s[0]:5,f=o?s[1]:5,A=n.direction.x*S*n.factor,O=n.direction.y*f*n.factor;for(const[,I]of E){if(!T(I))continue;let p={x:I.internals.positionAbsolute.x+A,y:I.internals.positionAbsolute.y+O};o&&(p=Ao(p,s));const{position:N,positionAbsolute:h}=TA({nodeId:I.id,nextPosition:p,nodeLookup:E,nodeExtent:r,nodeOrigin:d,onError:l});I.position=N,I.internals.positionAbsolute=h,u.set(I.id,I)}c(u)},[])}const kc=R.createContext(null),uM=kc.Provider;kc.Consumer;const zA=()=>R.useContext(kc),TM=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),SM=(e,t,n)=>r=>{const{connectionClickStartHandle:o,connectionMode:s,connection:i}=r,{fromHandle:l,toHandle:c,isValid:E}=i,d=(c==null?void 0:c.nodeId)===e&&(c==null?void 0:c.id)===t&&(c==null?void 0:c.type)===n;return{connectingFrom:(l==null?void 0:l.nodeId)===e&&(l==null?void 0:l.id)===t&&(l==null?void 0:l.type)===n,connectingTo: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===or.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&&E}};function RM({type:e="source",position:t=ee.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:o=!0,isConnectableEnd:s=!0,id:i,onConnect:l,children:c,className:E,onMouseDown:d,onTouchStart:u,...T},S){var v,P;const f=i||null,A=e==="target",O=pe(),I=zA(),{connectOnClick:p,noPanClassName:N,rfId:h}=Se(TM,Oe),{connectingFrom:C,connectingTo:m,clickConnecting:_,isPossibleEndHandle:D,connectionInProcess:g,clickConnectionInProcess:b,valid:y}=Se(SM(I,f,e),Oe);I||(P=(v=O.getState()).onError)==null||P.call(v,"010",Nt.error010());const M=w=>{const{defaultEdgeOptions:U,onConnect:x,hasDefaultEdges:B}=O.getState(),H={...U,...w};if(B){const{edges:W,setEdges:$}=O.getState();$(U0(H,W))}x==null||x(H),l==null||l(H)},F=w=>{if(!I)return;const U=pA(w.nativeEvent);if(o&&(U&&w.button===0||!U)){const x=O.getState();vl.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:A,handleId:f,nodeId:I,flowId:x.rfId,panBy:x.panBy,cancelConnection:x.cancelConnection,onConnectStart:x.onConnectStart,onConnectEnd:(...B)=>{var H,W;return(W=(H=O.getState()).onConnectEnd)==null?void 0:W.call(H,...B)},updateConnection:x.updateConnection,onConnect:M,isValidConnection:n||((...B)=>{var H,W;return((W=(H=O.getState()).isValidConnection)==null?void 0:W.call(H,...B))??!0}),getTransform:()=>O.getState().transform,getFromHandle:()=>O.getState().connection.fromHandle,autoPanSpeed:x.autoPanSpeed,dragThreshold:x.connectionDragThreshold})}U?d==null||d(w):u==null||u(w)},L=w=>{const{onClickConnectStart:U,onClickConnectEnd:x,connectionClickStartHandle:B,connectionMode:H,isValidConnection:W,lib:$,rfId:X,nodeLookup:J,connection:q}=O.getState();if(!I||!B&&!o)return;if(!B){U==null||U(w.nativeEvent,{nodeId:I,handleId:f,handleType:e}),O.setState({connectionClickStartHandle:{nodeId:I,type:e,id:f}});return}const z=OA(w.target),Y=n||W,{connection:K,isValid:le}=vl.isValid(w.nativeEvent,{handle:{nodeId:I,id:f,type:e},connectionMode:H,fromNodeId:B.nodeId,fromHandleId:B.id||null,fromType:B.type,isValidConnection:Y,flowId:X,doc:z,lib:$,nodeLookup:J});le&&K&&M(K);const se=structuredClone(q);delete se.inProgress,se.toPosition=se.toHandle?se.toHandle.position:null,x==null||x(w,se),O.setState({connectionClickStartHandle:null})};return a.jsx("div",{"data-handleid":f,"data-nodeid":I,"data-handlepos":t,"data-id":`${h}-${I}-${f}-${e}`,className:_e(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",N,E,{source:!A,target:A,connectable:r,connectablestart:o,connectableend:s,clickconnecting:_,connectingfrom:C,connectingto:m,valid:y,connectionindicator:r&&(!g||D)&&(g||b?s:o)}]),onMouseDown:F,onTouchStart:F,onClick:p?L:void 0,ref:S,...T,children:c})}const tn=R.memo(jA(RM));function AM({data:e,isConnectable:t,sourcePosition:n=ee.Bottom}){return a.jsxs(a.Fragment,{children:[e==null?void 0:e.label,a.jsx(tn,{type:"source",position:n,isConnectable:t})]})}function fM({data:e,isConnectable:t,targetPosition:n=ee.Top,sourcePosition:r=ee.Bottom}){return a.jsxs(a.Fragment,{children:[a.jsx(tn,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,a.jsx(tn,{type:"source",position:r,isConnectable:t})]})}function IM(){return null}function OM({data:e,isConnectable:t,targetPosition:n=ee.Top}){return a.jsxs(a.Fragment,{children:[a.jsx(tn,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label]})}const Ks={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},qd={input:AM,default:fM,output:OM,group:IM};function NM(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 pM=e=>{const{width:t,height:n,x:r,y:o}=Ro(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 hM({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=pe(),{width:o,height:s,transformString:i,userSelectionActive:l}=Se(pM,Oe),c=KA(),E=R.useRef(null);R.useEffect(()=>{var S;n||(S=E.current)==null||S.focus({preventScroll:!0})},[n]);const d=!l&&o!==null&&s!==null;if(XA({nodeRef:E,disabled:!d}),!d)return null;const u=e?S=>{const f=r.getState().nodes.filter(A=>A.selected);e(S,f)}:void 0,T=S=>{Object.prototype.hasOwnProperty.call(Ks,S.key)&&(S.preventDefault(),c({direction:Ks[S.key],factor:S.shiftKey?4:1}))};return a.jsx("div",{className:_e(["react-flow__nodesselection","react-flow__container",t]),style:{transform:i},children:a.jsx("div",{ref:E,className:"react-flow__nodesselection-rect",onContextMenu:u,tabIndex:n?void 0:-1,onKeyDown:n?void 0:T,style:{width:o,height:s}})})}const Qd=typeof window<"u"?window:void 0,CM=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function JA({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:s,onPaneScroll:i,paneClickDistance:l,deleteKeyCode:c,selectionKeyCode:E,selectionOnDrag:d,selectionMode:u,onSelectionStart:T,onSelectionEnd:S,multiSelectionKeyCode:f,panActivationKeyCode:A,zoomActivationKeyCode:O,elementsSelectable:I,zoomOnScroll:p,zoomOnPinch:N,panOnScroll:h,panOnScrollSpeed:C,panOnScrollMode:m,zoomOnDoubleClick:_,panOnDrag:D,defaultViewport:g,translateExtent:b,minZoom:y,maxZoom:M,preventScrolling:F,onSelectionContextMenu:L,noWheelClassName:v,noPanClassName:P,disableKeyboardA11y:w,onViewportChange:U,isControlledViewport:x}){const{nodesSelectionActive:B,userSelectionActive:H}=Se(CM,Oe),W=no(E,{target:Qd}),$=no(A,{target:Qd}),X=$||D,J=$||h,q=d&&X!==!0,z=W||H||q;return rM({deleteKeyCode:c,multiSelectionKeyCode:f}),a.jsx(iM,{onPaneContextMenu:s,elementsSelectable:I,zoomOnScroll:p,zoomOnPinch:N,panOnScroll:J,panOnScrollSpeed:C,panOnScrollMode:m,zoomOnDoubleClick:_,panOnDrag:!W&&X,defaultViewport:g,translateExtent:b,minZoom:y,maxZoom:M,zoomActivationKeyCode:O,preventScrolling:F,noWheelClassName:v,noPanClassName:P,onViewportChange:U,isControlledViewport:x,paneClickDistance:l,selectionOnDrag:q,children:a.jsxs(EM,{onSelectionStart:T,onSelectionEnd:S,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:s,onPaneScroll:i,panOnDrag:X,isSelecting:!!z,selectionMode:u,selectionKeyPressed:W,paneClickDistance:l,selectionOnDrag:q,children:[e,B&&a.jsx(hM,{onSelectionContextMenu:L,noPanClassName:P,disableKeyboardA11y:w})]})})}JA.displayName="FlowRenderer";const mM=R.memo(JA),LM=e=>t=>e?bc(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 _M(e){return Se(R.useCallback(LM(e),[e]),Oe)}const gM=e=>e.updateNodeInternals;function xM(){const e=Se(gM),[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 yM({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){const o=pe(),s=R.useRef(null),i=R.useRef(null),l=R.useRef(e.sourcePosition),c=R.useRef(e.targetPosition),E=R.useRef(t),d=n&&!!e.internals.handleBounds;return R.useEffect(()=>{s.current&&!e.hidden&&(!d||i.current!==s.current)&&(i.current&&(r==null||r.unobserve(i.current)),r==null||r.observe(s.current),i.current=s.current)},[d,e.hidden]),R.useEffect(()=>()=>{i.current&&(r==null||r.unobserve(i.current),i.current=null)},[]),R.useEffect(()=>{if(s.current){const u=E.current!==t,T=l.current!==e.sourcePosition,S=c.current!==e.targetPosition;(u||T||S)&&(E.current=t,l.current=e.sourcePosition,c.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 DM({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:o,onContextMenu:s,onDoubleClick:i,nodesDraggable:l,elementsSelectable:c,nodesConnectable:E,nodesFocusable:d,resizeObserver:u,noDragClassName:T,noPanClassName:S,disableKeyboardA11y:f,rfId:A,nodeTypes:O,nodeClickDistance:I,onError:p}){const{node:N,internals:h,isParent:C}=Se(Y=>{const K=Y.nodeLookup.get(e),le=Y.parentLookup.has(e);return{node:K,internals:K.internals,isParent:le}},Oe);let m=N.type||"default",_=(O==null?void 0:O[m])||qd[m];_===void 0&&(p==null||p("003",Nt.error003(m)),m="default",_=(O==null?void 0:O.default)||qd.default);const D=!!(N.draggable||l&&typeof N.draggable>"u"),g=!!(N.selectable||c&&typeof N.selectable>"u"),b=!!(N.connectable||E&&typeof N.connectable>"u"),y=!!(N.focusable||d&&typeof N.focusable>"u"),M=pe(),F=fA(N),L=yM({node:N,nodeType:m,hasDimensions:F,resizeObserver:u}),v=XA({nodeRef:L,disabled:N.hidden||!D,noDragClassName:T,handleSelector:N.dragHandle,nodeId:e,isSelectable:g,nodeClickDistance:I}),P=KA();if(N.hidden)return null;const w=Ut(N),U=NM(N),x=g||D||t||n||r||o,B=n?Y=>n(Y,{...h.userNode}):void 0,H=r?Y=>r(Y,{...h.userNode}):void 0,W=o?Y=>o(Y,{...h.userNode}):void 0,$=s?Y=>s(Y,{...h.userNode}):void 0,X=i?Y=>i(Y,{...h.userNode}):void 0,J=Y=>{const{selectNodesOnDrag:K,nodeDragThreshold:le}=M.getState();g&&(!K||!D||le>0)&&Ul({id:e,store:M,nodeRef:L}),t&&t(Y,{...h.userNode})},q=Y=>{if(!(NA(Y.nativeEvent)||f)){if(lA.includes(Y.key)&&g){const K=Y.key==="Escape";Ul({id:e,store:M,unselect:K,nodeRef:L})}else if(D&&N.selected&&Object.prototype.hasOwnProperty.call(Ks,Y.key)){Y.preventDefault();const{ariaLabelConfig:K}=M.getState();M.setState({ariaLiveMessage:K["node.a11yDescription.ariaLiveMessage"]({direction:Y.key.replace("Arrow","").toLowerCase(),x:~~h.positionAbsolute.x,y:~~h.positionAbsolute.y})}),P({direction:Ks[Y.key],factor:Y.shiftKey?4:1})}}},z=()=>{var Ee;if(f||!((Ee=L.current)!=null&&Ee.matches(":focus-visible")))return;const{transform:Y,width:K,height:le,autoPanOnNodeFocus:se,setCenter:ne}=M.getState();if(!se)return;bc(new Map([[e,N]]),{x:0,y:0,width:K,height:le},Y,!0).length>0||ne(N.position.x+w.width/2,N.position.y+w.height/2,{zoom:Y[2]})};return a.jsx("div",{className:_e(["react-flow__node",`react-flow__node-${m}`,{[S]:D},N.className,{selected:N.selected,selectable:g,parent:C,draggable:D,dragging:v}]),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,...U},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:B,onMouseMove:H,onMouseLeave:W,onContextMenu:$,onClick:J,onDoubleClick:X,onKeyDown:y?q:void 0,tabIndex:y?0:void 0,onFocus:y?z:void 0,role:N.ariaRole??(y?"group":void 0),"aria-roledescription":"node","aria-describedby":f?void 0:`${GA}-${A}`,"aria-label":N.ariaLabel,...N.domAttributes,children:a.jsx(uM,{value:e,children:a.jsx(_,{id:e,data:N.data,type:m,positionAbsoluteX:h.positionAbsolute.x,positionAbsoluteY:h.positionAbsolute.y,selected:N.selected??!1,selectable:g,draggable:D,deletable:N.deletable??!0,isConnectable:b,sourcePosition:N.sourcePosition,targetPosition:N.targetPosition,dragging:v,dragHandle:N.dragHandle,zIndex:h.z,parentId:N.parentId,...w})})})}var PM=R.memo(DM);const MM=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function qA(e){const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,onError:s}=Se(MM,Oe),i=_M(e.onlyRenderVisibleElements),l=xM();return a.jsx("div",{className:"react-flow__nodes",style:Pi,children:i.map(c=>a.jsx(PM,{id:c,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:l,nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,nodeClickDistance:e.nodeClickDistance,onError:s},c))})}qA.displayName="NodeRenderer";const bM=R.memo(qA);function vM(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),i=n.nodeLookup.get(o.target);s&&i&&M0({sourceNode:s,targetNode:i,width:n.width,height:n.height,transform:n.transform})&&r.push(o.id)}return r},[e]),Oe)}const UM=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e}};return a.jsx("polyline",{className:"arrow",style:n,strokeLinecap:"round",fill:"none",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4"})},wM=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e,fill:e}};return a.jsx("polyline",{className:"arrowclosed",style:n,strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},Zd={[sr.Arrow]:UM,[sr.ArrowClosed]:wM};function BM(e){const t=pe();return R.useMemo(()=>{var o,s;return Object.prototype.hasOwnProperty.call(Zd,e)?Zd[e]:((s=(o=t.getState()).onError)==null||s.call(o,"009",Nt.error009(e)),null)},[e])}const FM=({id:e,type:t,color:n,width:r=12.5,height:o=12.5,markerUnits:s="strokeWidth",strokeWidth:i,orient:l="auto-start-reverse"})=>{const c=BM(t);return c?a.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:a.jsx(c,{color:n,strokeWidth:i})}):null},QA=({defaultColor:e,rfId:t})=>{const n=Se(s=>s.edges),r=Se(s=>s.defaultEdgeOptions),o=R.useMemo(()=>H0(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?a.jsx("svg",{className:"react-flow__marker","aria-hidden":"true",children:a.jsx("defs",{children:o.map(s=>a.jsx(FM,{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};QA.displayName="MarkerDefinitions";var GM=R.memo(QA);function ZA({x:e,y:t,label:n,labelStyle:r,labelShowBg:o=!0,labelBgStyle:s,labelBgPadding:i=[2,4],labelBgBorderRadius:l=2,children:c,className:E,...d}){const[u,T]=R.useState({x:1,y:0,width:0,height:0}),S=_e(["react-flow__edge-textwrapper",E]),f=R.useRef(null);return R.useEffect(()=>{if(f.current){const A=f.current.getBBox();T({x:A.x,y:A.y,width:A.width,height:A.height})}},[n]),n?a.jsxs("g",{transform:`translate(${e-u.width/2} ${t-u.height/2})`,className:S,visibility:u.width?"visible":"hidden",...d,children:[o&&a.jsx("rect",{width:u.width+2*i[0],x:-i[0],y:-i[1],height:u.height+2*i[1],className:"react-flow__edge-textbg",style:s,rx:l,ry:l}),a.jsx("text",{className:"react-flow__edge-text",y:u.height/2,dy:"0.3em",ref:f,style:r,children:n}),c]}):null}ZA.displayName="EdgeText";const HM=R.memo(ZA);function Mi({path:e,labelX:t,labelY:n,label:r,labelStyle:o,labelShowBg:s,labelBgStyle:i,labelBgPadding:l,labelBgBorderRadius:c,interactionWidth:E=20,...d}){return a.jsxs(a.Fragment,{children:[a.jsx("path",{...d,d:e,fill:"none",className:_e(["react-flow__edge-path",d.className])}),E?a.jsx("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:E,className:"react-flow__edge-interaction"}):null,r&&rt(t)&&rt(n)?a.jsx(HM,{x:t,y:n,label:r,labelStyle:o,labelShowBg:s,labelBgStyle:i,labelBgPadding:l,labelBgBorderRadius:c}):null]})}function eu({pos:e,x1:t,y1:n,x2:r,y2:o}){return e===ee.Left||e===ee.Right?[.5*(t+r),n]:[t,.5*(n+o)]}function ef({sourceX:e,sourceY:t,sourcePosition:n=ee.Bottom,targetX:r,targetY:o,targetPosition:s=ee.Top}){const[i,l]=eu({pos:n,x1:e,y1:t,x2:r,y2:o}),[c,E]=eu({pos:s,x1:r,y1:o,x2:e,y2:t}),[d,u,T,S]=hA({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:i,sourceControlY:l,targetControlX:c,targetControlY:E});return[`M${e},${t} C${i},${l} ${c},${E} ${r},${o}`,d,u,T,S]}function tf(e){return R.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,sourcePosition:i,targetPosition:l,label:c,labelStyle:E,labelShowBg:d,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:S,style:f,markerEnd:A,markerStart:O,interactionWidth:I})=>{const[p,N,h]=ef({sourceX:n,sourceY:r,sourcePosition:i,targetX:o,targetY:s,targetPosition:l}),C=e.isInternal?void 0:t;return a.jsx(Mi,{id:C,path:p,labelX:N,labelY:h,label:c,labelStyle:E,labelShowBg:d,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:S,style:f,markerEnd:A,markerStart:O,interactionWidth:I})})}const YM=tf({isInternal:!1}),nf=tf({isInternal:!0});YM.displayName="SimpleBezierEdge";nf.displayName="SimpleBezierEdgeInternal";function rf(e){return R.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,label:i,labelStyle:l,labelShowBg:c,labelBgStyle:E,labelBgPadding:d,labelBgBorderRadius:u,style:T,sourcePosition:S=ee.Bottom,targetPosition:f=ee.Top,markerEnd:A,markerStart:O,pathOptions:I,interactionWidth:p})=>{const[N,h,C]=Pl({sourceX:n,sourceY:r,sourcePosition:S,targetX:o,targetY:s,targetPosition:f,borderRadius:I==null?void 0:I.borderRadius,offset:I==null?void 0:I.offset,stepPosition:I==null?void 0:I.stepPosition}),m=e.isInternal?void 0:t;return a.jsx(Mi,{id:m,path:N,labelX:h,labelY:C,label:i,labelStyle:l,labelShowBg:c,labelBgStyle:E,labelBgPadding:d,labelBgBorderRadius:u,style:T,markerEnd:A,markerStart:O,interactionWidth:p})})}const of=rf({isInternal:!1}),sf=rf({isInternal:!0});of.displayName="SmoothStepEdge";sf.displayName="SmoothStepEdgeInternal";function af(e){return R.memo(({id:t,...n})=>{var o;const r=e.isInternal?void 0:t;return a.jsx(of,{...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 kM=af({isInternal:!1}),lf=af({isInternal:!0});kM.displayName="StepEdge";lf.displayName="StepEdgeInternal";function cf(e){return R.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,label:i,labelStyle:l,labelShowBg:c,labelBgStyle:E,labelBgPadding:d,labelBgBorderRadius:u,style:T,markerEnd:S,markerStart:f,interactionWidth:A})=>{const[O,I,p]=LA({sourceX:n,sourceY:r,targetX:o,targetY:s}),N=e.isInternal?void 0:t;return a.jsx(Mi,{id:N,path:O,labelX:I,labelY:p,label:i,labelStyle:l,labelShowBg:c,labelBgStyle:E,labelBgPadding:d,labelBgBorderRadius:u,style:T,markerEnd:S,markerStart:f,interactionWidth:A})})}const WM=cf({isInternal:!1}),Ef=cf({isInternal:!0});WM.displayName="StraightEdge";Ef.displayName="StraightEdgeInternal";function df(e){return R.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,sourcePosition:i=ee.Bottom,targetPosition:l=ee.Top,label:c,labelStyle:E,labelShowBg:d,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:S,style:f,markerEnd:A,markerStart:O,pathOptions:I,interactionWidth:p})=>{const[N,h,C]=CA({sourceX:n,sourceY:r,sourcePosition:i,targetX:o,targetY:s,targetPosition:l,curvature:I==null?void 0:I.curvature}),m=e.isInternal?void 0:t;return a.jsx(Mi,{id:m,path:N,labelX:h,labelY:C,label:c,labelStyle:E,labelShowBg:d,labelBgStyle:u,labelBgPadding:T,labelBgBorderRadius:S,style:f,markerEnd:A,markerStart:O,interactionWidth:p})})}const VM=df({isInternal:!1}),uf=df({isInternal:!0});VM.displayName="BezierEdge";uf.displayName="BezierEdgeInternal";const tu={default:uf,straight:Ef,step:lf,smoothstep:sf,simplebezier:nf},nu={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},jM=(e,t,n)=>n===ee.Left?e-t:n===ee.Right?e+t:e,$M=(e,t,n)=>n===ee.Top?e-t:n===ee.Bottom?e+t:e,ru="react-flow__edgeupdater";function ou({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:o,onMouseEnter:s,onMouseOut:i,type:l}){return a.jsx("circle",{onMouseDown:o,onMouseEnter:s,onMouseOut:i,className:_e([ru,`${ru}-${l}`]),cx:jM(t,r,e),cy:$M(n,r,e),r,stroke:"transparent",fill:"transparent"})}function XM({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:o,targetX:s,targetY:i,sourcePosition:l,targetPosition:c,onReconnect:E,onReconnectStart:d,onReconnectEnd:u,setReconnecting:T,setUpdateHover:S}){const f=pe(),A=(h,C)=>{if(h.button!==0)return;const{autoPanOnConnect:m,domNode:_,connectionMode:D,connectionRadius:g,lib:b,onConnectStart:y,cancelConnection:M,nodeLookup:F,rfId:L,panBy:v,updateConnection:P}=f.getState(),w=C.type==="target",U=(H,W)=>{T(!1),u==null||u(H,n,C.type,W)},x=H=>E==null?void 0:E(n,H),B=(H,W)=>{T(!0),d==null||d(h,n,C.type),y==null||y(H,W)};vl.onPointerDown(h.nativeEvent,{autoPanOnConnect:m,connectionMode:D,connectionRadius:g,domNode:_,handleId:C.id,nodeId:C.nodeId,nodeLookup:F,isTarget:w,edgeUpdaterType:C.type,lib:b,flowId:L,cancelConnection:M,panBy:v,isValidConnection:(...H)=>{var W,$;return(($=(W=f.getState()).isValidConnection)==null?void 0:$.call(W,...H))??!0},onConnect:x,onConnectStart:B,onConnectEnd:(...H)=>{var W,$;return($=(W=f.getState()).onConnectEnd)==null?void 0:$.call(W,...H)},onReconnectEnd:U,updateConnection:P,getTransform:()=>f.getState().transform,getFromHandle:()=>f.getState().connection.fromHandle,dragThreshold:f.getState().connectionDragThreshold,handleDomNode:h.currentTarget})},O=h=>A(h,{nodeId:n.target,id:n.targetHandle??null,type:"target"}),I=h=>A(h,{nodeId:n.source,id:n.sourceHandle??null,type:"source"}),p=()=>S(!0),N=()=>S(!1);return a.jsxs(a.Fragment,{children:[(e===!0||e==="source")&&a.jsx(ou,{position:l,centerX:r,centerY:o,radius:t,onMouseDown:O,onMouseEnter:p,onMouseOut:N,type:"source"}),(e===!0||e==="target")&&a.jsx(ou,{position:c,centerX:s,centerY:i,radius:t,onMouseDown:I,onMouseEnter:p,onMouseOut:N,type:"target"})]})}function KM({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:o,onDoubleClick:s,onContextMenu:i,onMouseEnter:l,onMouseMove:c,onMouseLeave:E,reconnectRadius:d,onReconnect:u,onReconnectStart:T,onReconnectEnd:S,rfId:f,edgeTypes:A,noPanClassName:O,onError:I,disableKeyboardA11y:p}){let N=Se(ne=>ne.edgeLookup.get(e));const h=Se(ne=>ne.defaultEdgeOptions);N=h?{...h,...N}:N;let C=N.type||"default",m=(A==null?void 0:A[C])||tu[C];m===void 0&&(I==null||I("011",Nt.error011(C)),C="default",m=(A==null?void 0:A.default)||tu.default);const _=!!(N.focusable||t&&typeof N.focusable>"u"),D=typeof u<"u"&&(N.reconnectable||n&&typeof N.reconnectable>"u"),g=!!(N.selectable||r&&typeof N.selectable>"u"),b=R.useRef(null),[y,M]=R.useState(!1),[F,L]=R.useState(!1),v=pe(),{zIndex:P,sourceX:w,sourceY:U,targetX:x,targetY:B,sourcePosition:H,targetPosition:W}=Se(R.useCallback(ne=>{const te=ne.nodeLookup.get(N.source),Ee=ne.nodeLookup.get(N.target);if(!te||!Ee)return{zIndex:N.zIndex,...nu};const fe=G0({id:e,sourceNode:te,targetNode:Ee,sourceHandle:N.sourceHandle||null,targetHandle:N.targetHandle||null,connectionMode:ne.connectionMode,onError:I});return{zIndex:P0({selected:N.selected,zIndex:N.zIndex,sourceNode:te,targetNode:Ee,elevateOnSelect:ne.elevateEdgesOnSelect,zIndexMode:ne.zIndexMode}),...fe||nu}},[N.source,N.target,N.sourceHandle,N.targetHandle,N.selected,N.zIndex]),Oe),$=R.useMemo(()=>N.markerStart?`url('#${Ml(N.markerStart,f)}')`:void 0,[N.markerStart,f]),X=R.useMemo(()=>N.markerEnd?`url('#${Ml(N.markerEnd,f)}')`:void 0,[N.markerEnd,f]);if(N.hidden||w===null||U===null||x===null||B===null)return null;const J=ne=>{var de;const{addSelectedEdges:te,unselectNodesAndEdges:Ee,multiSelectionActive:fe}=v.getState();g&&(v.setState({nodesSelectionActive:!1}),N.selected&&fe?(Ee({nodes:[],edges:[N]}),(de=b.current)==null||de.blur()):te([e])),o&&o(ne,N)},q=s?ne=>{s(ne,{...N})}:void 0,z=i?ne=>{i(ne,{...N})}:void 0,Y=l?ne=>{l(ne,{...N})}:void 0,K=c?ne=>{c(ne,{...N})}:void 0,le=E?ne=>{E(ne,{...N})}:void 0,se=ne=>{var te;if(!p&&lA.includes(ne.key)&&g){const{unselectNodesAndEdges:Ee,addSelectedEdges:fe}=v.getState();ne.key==="Escape"?((te=b.current)==null||te.blur(),Ee({edges:[N]})):fe([e])}};return a.jsx("svg",{style:{zIndex:P},children:a.jsxs("g",{className:_e(["react-flow__edge",`react-flow__edge-${C}`,N.className,O,{selected:N.selected,animated:N.animated,inactive:!g&&!o,updating:y,selectable:g}]),onClick:J,onDoubleClick:q,onContextMenu:z,onMouseEnter:Y,onMouseMove:K,onMouseLeave:le,onKeyDown:_?se:void 0,tabIndex:_?0:void 0,role:N.ariaRole??(_?"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":_?`${HA}-${f}`:void 0,ref:b,...N.domAttributes,children:[!F&&a.jsx(m,{id:e,source:N.source,target:N.target,type:N.type,selected:N.selected,animated:N.animated,selectable:g,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:U,targetX:x,targetY:B,sourcePosition:H,targetPosition:W,data:N.data,style:N.style,sourceHandleId:N.sourceHandle,targetHandleId:N.targetHandle,markerStart:$,markerEnd:X,pathOptions:"pathOptions"in N?N.pathOptions:void 0,interactionWidth:N.interactionWidth}),D&&a.jsx(XM,{edge:N,isReconnectable:D,reconnectRadius:d,onReconnect:u,onReconnectStart:T,onReconnectEnd:S,sourceX:w,sourceY:U,targetX:x,targetY:B,sourcePosition:H,targetPosition:W,setUpdateHover:M,setReconnecting:L})]})})}var zM=R.memo(KM);const JM=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function Tf({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:o,onReconnect:s,onEdgeContextMenu:i,onEdgeMouseEnter:l,onEdgeMouseMove:c,onEdgeMouseLeave:E,onEdgeClick:d,reconnectRadius:u,onEdgeDoubleClick:T,onReconnectStart:S,onReconnectEnd:f,disableKeyboardA11y:A}){const{edgesFocusable:O,edgesReconnectable:I,elementsSelectable:p,onError:N}=Se(JM,Oe),h=vM(t);return a.jsxs("div",{className:"react-flow__edges",children:[a.jsx(GM,{defaultColor:e,rfId:n}),h.map(C=>a.jsx(zM,{id:C,edgesFocusable:O,edgesReconnectable:I,elementsSelectable:p,noPanClassName:o,onReconnect:s,onContextMenu:i,onMouseEnter:l,onMouseMove:c,onMouseLeave:E,onClick:d,reconnectRadius:u,onDoubleClick:T,onReconnectStart:S,onReconnectEnd:f,rfId:n,onError:N,edgeTypes:r,disableKeyboardA11y:A},C))]})}Tf.displayName="EdgeRenderer";const qM=R.memo(Tf),QM=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function ZM({children:e}){const t=Se(QM);return a.jsx("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:t},children:e})}function e1(e){const t=Yc(),n=R.useRef(!1);R.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const t1=e=>{var t;return(t=e.panZoom)==null?void 0:t.syncViewport};function n1(e){const t=Se(t1),n=pe();return R.useEffect(()=>{e&&(t==null||t(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function r1(e){return e.connection.inProgress?{...e.connection,to:fo(e.connection.to,e.transform)}:{...e.connection}}function o1(e){return r1}function s1(e){const t=o1();return Se(t,Oe)}const i1=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function a1({containerStyle:e,style:t,type:n,component:r}){const{nodesConnectable:o,width:s,height:i,isValid:l,inProgress:c}=Se(i1,Oe);return!(s&&o&&c)?null:a.jsx("svg",{style:e,width:s,height:i,className:"react-flow__connectionline react-flow__container",children:a.jsx("g",{className:_e(["react-flow__connection",dA(l)]),children:a.jsx(Sf,{style:t,type:n,CustomComponent:r,isValid:l})})})}const Sf=({style:e,type:t=$t.Bezier,CustomComponent:n,isValid:r})=>{const{inProgress:o,from:s,fromNode:i,fromHandle:l,fromPosition:c,to:E,toNode:d,toHandle:u,toPosition:T,pointer:S}=s1();if(!o)return;if(n)return a.jsx(n,{connectionLineType:t,connectionLineStyle:e,fromNode:i,fromHandle:l,fromX:s.x,fromY:s.y,toX:E.x,toY:E.y,fromPosition:c,toPosition:T,connectionStatus:dA(r),toNode:d,toHandle:u,pointer:S});let f="";const A={sourceX:s.x,sourceY:s.y,sourcePosition:c,targetX:E.x,targetY:E.y,targetPosition:T};switch(t){case $t.Bezier:[f]=CA(A);break;case $t.SimpleBezier:[f]=ef(A);break;case $t.Step:[f]=Pl({...A,borderRadius:0});break;case $t.SmoothStep:[f]=Pl(A);break;default:[f]=LA(A)}return a.jsx("path",{d:f,fill:"none",className:"react-flow__connection-path",style:e})};Sf.displayName="ConnectionLine";const l1={};function su(e=l1){R.useRef(e),pe(),R.useEffect(()=>{},[e])}function c1(){pe(),R.useRef(!1),R.useEffect(()=>{},[])}function Rf({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:o,onNodeDoubleClick:s,onEdgeDoubleClick:i,onNodeMouseEnter:l,onNodeMouseMove:c,onNodeMouseLeave:E,onNodeContextMenu:d,onSelectionContextMenu:u,onSelectionStart:T,onSelectionEnd:S,connectionLineType:f,connectionLineStyle:A,connectionLineComponent:O,connectionLineContainerStyle:I,selectionKeyCode:p,selectionOnDrag:N,selectionMode:h,multiSelectionKeyCode:C,panActivationKeyCode:m,zoomActivationKeyCode:_,deleteKeyCode:D,onlyRenderVisibleElements:g,elementsSelectable:b,defaultViewport:y,translateExtent:M,minZoom:F,maxZoom:L,preventScrolling:v,defaultMarkerColor:P,zoomOnScroll:w,zoomOnPinch:U,panOnScroll:x,panOnScrollSpeed:B,panOnScrollMode:H,zoomOnDoubleClick:W,panOnDrag:$,onPaneClick:X,onPaneMouseEnter:J,onPaneMouseMove:q,onPaneMouseLeave:z,onPaneScroll:Y,onPaneContextMenu:K,paneClickDistance:le,nodeClickDistance:se,onEdgeContextMenu:ne,onEdgeMouseEnter:te,onEdgeMouseMove:Ee,onEdgeMouseLeave:fe,reconnectRadius:de,onReconnect:Re,onReconnectStart:He,onReconnectEnd:Me,noDragClassName:dt,noWheelClassName:an,noPanClassName:wt,disableKeyboardA11y:Dn,nodeExtent:Oo,rfId:Bt,viewport:Ct,onViewportChange:Ft}){return su(e),su(t),c1(),e1(n),n1(Ct),a.jsx(mM,{onPaneClick:X,onPaneMouseEnter:J,onPaneMouseMove:q,onPaneMouseLeave:z,onPaneContextMenu:K,onPaneScroll:Y,paneClickDistance:le,deleteKeyCode:D,selectionKeyCode:p,selectionOnDrag:N,selectionMode:h,onSelectionStart:T,onSelectionEnd:S,multiSelectionKeyCode:C,panActivationKeyCode:m,zoomActivationKeyCode:_,elementsSelectable:b,zoomOnScroll:w,zoomOnPinch:U,zoomOnDoubleClick:W,panOnScroll:x,panOnScrollSpeed:B,panOnScrollMode:H,panOnDrag:$,defaultViewport:y,translateExtent:M,minZoom:F,maxZoom:L,onSelectionContextMenu:u,preventScrolling:v,noDragClassName:dt,noWheelClassName:an,noPanClassName:wt,disableKeyboardA11y:Dn,onViewportChange:Ft,isControlledViewport:!!Ct,children:a.jsxs(ZM,{children:[a.jsx(qM,{edgeTypes:t,onEdgeClick:o,onEdgeDoubleClick:i,onReconnect:Re,onReconnectStart:He,onReconnectEnd:Me,onlyRenderVisibleElements:g,onEdgeContextMenu:ne,onEdgeMouseEnter:te,onEdgeMouseMove:Ee,onEdgeMouseLeave:fe,reconnectRadius:de,defaultMarkerColor:P,noPanClassName:wt,disableKeyboardA11y:Dn,rfId:Bt}),a.jsx(a1,{style:A,type:f,component:O,containerStyle:I}),a.jsx("div",{className:"react-flow__edgelabel-renderer"}),a.jsx(bM,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:s,onNodeMouseEnter:l,onNodeMouseMove:c,onNodeMouseLeave:E,onNodeContextMenu:d,nodeClickDistance:se,onlyRenderVisibleElements:g,noPanClassName:wt,noDragClassName:dt,disableKeyboardA11y:Dn,nodeExtent:Oo,rfId:Bt}),a.jsx("div",{className:"react-flow__viewport-portal"})]})})}Rf.displayName="GraphView";const E1=R.memo(Rf),iu=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:i,fitViewOptions:l,minZoom:c=.5,maxZoom:E=2,nodeOrigin:d,nodeExtent:u,zIndexMode:T="basic"}={})=>{const S=new Map,f=new Map,A=new Map,O=new Map,I=r??t??[],p=n??e??[],N=d??[0,0],h=u??Qr;xA(A,O,I);const C=bl(p,S,f,{nodeOrigin:N,nodeExtent:h,zIndexMode:T});let m=[0,0,1];if(i&&o&&s){const _=Ro(S,{filter:y=>!!((y.width||y.initialWidth)&&(y.height||y.initialHeight))}),{x:D,y:g,zoom:b}=vc(_,o,s,c,E,(l==null?void 0:l.padding)??.1);m=[D,g,b]}return{rfId:"1",width:o??0,height:s??0,transform:m,nodes:p,nodesInitialized:C,nodeLookup:S,parentLookup:f,edges:I,edgeLookup:O,connectionLookup:A,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:c,maxZoom:E,translateExtent:Qr,nodeExtent:h,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:or.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:i??!1,fitViewOptions:l,fitViewResolver:null,connection:{...EA},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:L0,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:cA,zIndexMode:T,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},d1=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:i,fitViewOptions:l,minZoom:c,maxZoom:E,nodeOrigin:d,nodeExtent:u,zIndexMode:T})=>yP((S,f)=>{async function A(){const{nodeLookup:O,panZoom:I,fitViewOptions:p,fitViewResolver:N,width:h,height:C,minZoom:m,maxZoom:_}=f();I&&(await C0({nodes:O,width:h,height:C,panZoom:I,minZoom:m,maxZoom:_},p),N==null||N.resolve(!0),S({fitViewResolver:null}))}return{...iu({nodes:e,edges:t,width:o,height:s,fitView:i,fitViewOptions:l,minZoom:c,maxZoom:E,nodeOrigin:d,nodeExtent:u,defaultNodes:n,defaultEdges:r,zIndexMode:T}),setNodes:O=>{const{nodeLookup:I,parentLookup:p,nodeOrigin:N,elevateNodesOnSelect:h,fitViewQueued:C,zIndexMode:m}=f(),_=bl(O,I,p,{nodeOrigin:N,nodeExtent:u,elevateNodesOnSelect:h,checkEquality:!0,zIndexMode:m});C&&_?(A(),S({nodes:O,nodesInitialized:_,fitViewQueued:!1,fitViewOptions:void 0})):S({nodes:O,nodesInitialized:_})},setEdges:O=>{const{connectionLookup:I,edgeLookup:p}=f();xA(I,p,O),S({edges:O})},setDefaultNodesAndEdges:(O,I)=>{if(O){const{setNodes:p}=f();p(O),S({hasDefaultNodes:!0})}if(I){const{setEdges:p}=f();p(I),S({hasDefaultEdges:!0})}},updateNodeInternals:O=>{const{triggerNodeChanges:I,nodeLookup:p,parentLookup:N,domNode:h,nodeOrigin:C,nodeExtent:m,debug:_,fitViewQueued:D,zIndexMode:g}=f(),{changes:b,updatedInternals:y}=X0(O,p,N,h,C,m,g);y&&(W0(p,N,{nodeOrigin:C,nodeExtent:m,zIndexMode:g}),D?(A(),S({fitViewQueued:!1,fitViewOptions:void 0})):S({}),(b==null?void 0:b.length)>0&&(_&&console.log("React Flow: trigger node changes",b),I==null||I(b)))},updateNodePositions:(O,I=!1)=>{const p=[];let N=[];const{nodeLookup:h,triggerNodeChanges:C,connection:m,updateConnection:_,onNodesChangeMiddlewareMap:D}=f();for(const[g,b]of O){const y=h.get(g),M=!!(y!=null&&y.expandParent&&(y!=null&&y.parentId)&&(b!=null&&b.position)),F={id:g,type:"position",position:M?{x:Math.max(0,b.position.x),y:Math.max(0,b.position.y)}:b.position,dragging:I};if(y&&m.inProgress&&m.fromNode.id===y.id){const L=hn(y,m.fromHandle,ee.Left,!0);_({...m,from:L})}M&&y.parentId&&p.push({id:g,parentId:y.parentId,rect:{...b.internals.positionAbsolute,width:b.measured.width??0,height:b.measured.height??0}}),N.push(F)}if(p.length>0){const{parentLookup:g,nodeOrigin:b}=f(),y=Hc(p,h,g,b);N.push(...y)}for(const g of D.values())N=g(N);C(N)},triggerNodeChanges:O=>{const{onNodesChange:I,setNodes:p,nodes:N,hasDefaultNodes:h,debug:C}=f();if(O!=null&&O.length){if(h){const m=WA(O,N);p(m)}C&&console.log("React Flow: trigger node changes",O),I==null||I(O)}},triggerEdgeChanges:O=>{const{onEdgesChange:I,setEdges:p,edges:N,hasDefaultEdges:h,debug:C}=f();if(O!=null&&O.length){if(h){const m=VA(O,N);p(m)}C&&console.log("React Flow: trigger edge changes",O),I==null||I(O)}},addSelectedNodes:O=>{const{multiSelectionActive:I,edgeLookup:p,nodeLookup:N,triggerNodeChanges:h,triggerEdgeChanges:C}=f();if(I){const m=O.map(_=>dn(_,!0));h(m);return}h(jn(N,new Set([...O]),!0)),C(jn(p))},addSelectedEdges:O=>{const{multiSelectionActive:I,edgeLookup:p,nodeLookup:N,triggerNodeChanges:h,triggerEdgeChanges:C}=f();if(I){const m=O.map(_=>dn(_,!0));C(m);return}C(jn(p,new Set([...O]))),h(jn(N,new Set,!0))},unselectNodesAndEdges:({nodes:O,edges:I}={})=>{const{edges:p,nodes:N,nodeLookup:h,triggerNodeChanges:C,triggerEdgeChanges:m}=f(),_=O||N,D=I||p,g=[];for(const y of _){if(!y.selected)continue;const M=h.get(y.id);M&&(M.selected=!1),g.push(dn(y.id,!1))}const b=[];for(const y of D)y.selected&&b.push(dn(y.id,!1));C(g),m(b)},setMinZoom:O=>{const{panZoom:I,maxZoom:p}=f();I==null||I.setScaleExtent([O,p]),S({minZoom:O})},setMaxZoom:O=>{const{panZoom:I,minZoom:p}=f();I==null||I.setScaleExtent([p,O]),S({maxZoom:O})},setTranslateExtent:O=>{var I;(I=f().panZoom)==null||I.setTranslateExtent(O),S({translateExtent:O})},resetSelectedElements:()=>{const{edges:O,nodes:I,triggerNodeChanges:p,triggerEdgeChanges:N,elementsSelectable:h}=f();if(!h)return;const C=I.reduce((_,D)=>D.selected?[..._,dn(D.id,!1)]:_,[]),m=O.reduce((_,D)=>D.selected?[..._,dn(D.id,!1)]:_,[]);p(C),N(m)},setNodeExtent:O=>{const{nodes:I,nodeLookup:p,parentLookup:N,nodeOrigin:h,elevateNodesOnSelect:C,nodeExtent:m,zIndexMode:_}=f();O[0][0]===m[0][0]&&O[0][1]===m[0][1]&&O[1][0]===m[1][0]&&O[1][1]===m[1][1]||(bl(I,p,N,{nodeOrigin:h,nodeExtent:O,elevateNodesOnSelect:C,checkEquality:!1,zIndexMode:_}),S({nodeExtent:O}))},panBy:O=>{const{transform:I,width:p,height:N,panZoom:h,translateExtent:C}=f();return K0({delta:O,panZoom:h,transform:I,translateExtent:C,width:p,height:N})},setCenter:async(O,I,p)=>{const{width:N,height:h,maxZoom:C,panZoom:m}=f();if(!m)return Promise.resolve(!1);const _=typeof(p==null?void 0:p.zoom)<"u"?p.zoom:C;return await m.setViewport({x:N/2-O*_,y:h/2-I*_,zoom:_},{duration:p==null?void 0:p.duration,ease:p==null?void 0:p.ease,interpolate:p==null?void 0:p.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{S({connection:{...EA}})},updateConnection:O=>{S({connection:O})},reset:()=>S({...iu()})}},Object.is);function u1({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:o,initialHeight:s,initialMinZoom:i,initialMaxZoom:l,initialFitViewOptions:c,fitView:E,nodeOrigin:d,nodeExtent:u,zIndexMode:T,children:S}){const[f]=R.useState(()=>d1({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:E,minZoom:i,maxZoom:l,fitViewOptions:c,nodeOrigin:d,nodeExtent:u,zIndexMode:T}));return a.jsx(DP,{value:f,children:a.jsx(ZP,{children:S})})}function T1({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:o,width:s,height:i,fitView:l,fitViewOptions:c,minZoom:E,maxZoom:d,nodeOrigin:u,nodeExtent:T,zIndexMode:S}){return R.useContext(Di)?a.jsx(a.Fragment,{children:e}):a.jsx(u1,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:o,initialWidth:s,initialHeight:i,fitView:l,initialFitViewOptions:c,initialMinZoom:E,initialMaxZoom:d,nodeOrigin:u,nodeExtent:T,zIndexMode:S,children:e})}const S1={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};function R1({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:o,nodeTypes:s,edgeTypes:i,onNodeClick:l,onEdgeClick:c,onInit:E,onMove:d,onMoveStart:u,onMoveEnd:T,onConnect:S,onConnectStart:f,onConnectEnd:A,onClickConnectStart:O,onClickConnectEnd:I,onNodeMouseEnter:p,onNodeMouseMove:N,onNodeMouseLeave:h,onNodeContextMenu:C,onNodeDoubleClick:m,onNodeDragStart:_,onNodeDrag:D,onNodeDragStop:g,onNodesDelete:b,onEdgesDelete:y,onDelete:M,onSelectionChange:F,onSelectionDragStart:L,onSelectionDrag:v,onSelectionDragStop:P,onSelectionContextMenu:w,onSelectionStart:U,onSelectionEnd:x,onBeforeDelete:B,connectionMode:H,connectionLineType:W=$t.Bezier,connectionLineStyle:$,connectionLineComponent:X,connectionLineContainerStyle:J,deleteKeyCode:q="Backspace",selectionKeyCode:z="Shift",selectionOnDrag:Y=!1,selectionMode:K=Zr.Full,panActivationKeyCode:le="Space",multiSelectionKeyCode:se=to()?"Meta":"Control",zoomActivationKeyCode:ne=to()?"Meta":"Control",snapToGrid:te,snapGrid:Ee,onlyRenderVisibleElements:fe=!1,selectNodesOnDrag:de,nodesDraggable:Re,autoPanOnNodeFocus:He,nodesConnectable:Me,nodesFocusable:dt,nodeOrigin:an=YA,edgesFocusable:wt,edgesReconnectable:Dn,elementsSelectable:Oo=!0,defaultViewport:Bt=WP,minZoom:Ct=.5,maxZoom:Ft=2,translateExtent:No=Qr,preventScrolling:po=!0,nodeExtent:Ir,defaultMarkerColor:ho="#b1b1b7",zoomOnScroll:wi=!0,zoomOnPinch:Gt=!0,panOnScroll:Co=!1,panOnScrollSpeed:Ht=.5,panOnScrollMode:mo=Rn.Free,zoomOnDoubleClick:Pn=!0,panOnDrag:Or=!0,onPaneClick:Ze,onPaneMouseEnter:Bi,onPaneMouseMove:Fi,onPaneMouseLeave:Gi,onPaneScroll:Mn,onPaneContextMenu:ln,paneClickDistance:Hi=1,nodeClickDistance:Yi=0,children:Nr,onReconnect:ki,onReconnectStart:Lo,onReconnectEnd:bn,onEdgeContextMenu:ut,onEdgeDoubleClick:Ye,onEdgeMouseEnter:_o,onEdgeMouseMove:go,onEdgeMouseLeave:xo,reconnectRadius:Wi=10,onNodesChange:Vi,onEdgesChange:yo,noDragClassName:ji="nodrag",noWheelClassName:$i="nowheel",noPanClassName:Do="nopan",fitView:Po,fitViewOptions:Mo,connectOnClick:Xi,attributionPosition:bo,proOptions:vo,defaultEdgeOptions:Uo,elevateNodesOnSelect:wo=!0,elevateEdgesOnSelect:Bo=!1,disableKeyboardA11y:pr=!1,autoPanOnConnect:Fo,autoPanOnNodeDrag:Go,autoPanSpeed:Ho,connectionRadius:k,isValidConnection:ie,onError:he,style:Le,id:Yt,nodeDragThreshold:hr,connectionDragThreshold:Cr,viewport:TI,onViewportChange:SI,width:RI,height:AI,colorMode:fI="light",debug:II,onScroll:Yo,ariaLabelConfig:OI,zIndexMode:zc="basic",...NI},pI){const Ki=Yt||"1",hI=XP(fI),CI=R.useCallback(Jc=>{Jc.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),Yo==null||Yo(Jc)},[Yo]);return a.jsx("div",{"data-testid":"rf__wrapper",...NI,onScroll:CI,style:{...Le,...S1},ref:pI,className:_e(["react-flow",o,hI]),id:Yt,role:"application",children:a.jsxs(T1,{nodes:e,edges:t,width:RI,height:AI,fitView:Po,fitViewOptions:Mo,minZoom:Ct,maxZoom:Ft,nodeOrigin:an,nodeExtent:Ir,zIndexMode:zc,children:[a.jsx(E1,{onInit:E,onNodeClick:l,onEdgeClick:c,onNodeMouseEnter:p,onNodeMouseMove:N,onNodeMouseLeave:h,onNodeContextMenu:C,onNodeDoubleClick:m,nodeTypes:s,edgeTypes:i,connectionLineType:W,connectionLineStyle:$,connectionLineComponent:X,connectionLineContainerStyle:J,selectionKeyCode:z,selectionOnDrag:Y,selectionMode:K,deleteKeyCode:q,multiSelectionKeyCode:se,panActivationKeyCode:le,zoomActivationKeyCode:ne,onlyRenderVisibleElements:fe,defaultViewport:Bt,translateExtent:No,minZoom:Ct,maxZoom:Ft,preventScrolling:po,zoomOnScroll:wi,zoomOnPinch:Gt,zoomOnDoubleClick:Pn,panOnScroll:Co,panOnScrollSpeed:Ht,panOnScrollMode:mo,panOnDrag:Or,onPaneClick:Ze,onPaneMouseEnter:Bi,onPaneMouseMove:Fi,onPaneMouseLeave:Gi,onPaneScroll:Mn,onPaneContextMenu:ln,paneClickDistance:Hi,nodeClickDistance:Yi,onSelectionContextMenu:w,onSelectionStart:U,onSelectionEnd:x,onReconnect:ki,onReconnectStart:Lo,onReconnectEnd:bn,onEdgeContextMenu:ut,onEdgeDoubleClick:Ye,onEdgeMouseEnter:_o,onEdgeMouseMove:go,onEdgeMouseLeave:xo,reconnectRadius:Wi,defaultMarkerColor:ho,noDragClassName:ji,noWheelClassName:$i,noPanClassName:Do,rfId:Ki,disableKeyboardA11y:pr,nodeExtent:Ir,viewport:TI,onViewportChange:SI}),a.jsx($P,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:S,onConnectStart:f,onConnectEnd:A,onClickConnectStart:O,onClickConnectEnd:I,nodesDraggable:Re,autoPanOnNodeFocus:He,nodesConnectable:Me,nodesFocusable:dt,edgesFocusable:wt,edgesReconnectable:Dn,elementsSelectable:Oo,elevateNodesOnSelect:wo,elevateEdgesOnSelect:Bo,minZoom:Ct,maxZoom:Ft,nodeExtent:Ir,onNodesChange:Vi,onEdgesChange:yo,snapToGrid:te,snapGrid:Ee,connectionMode:H,translateExtent:No,connectOnClick:Xi,defaultEdgeOptions:Uo,fitView:Po,fitViewOptions:Mo,onNodesDelete:b,onEdgesDelete:y,onDelete:M,onNodeDragStart:_,onNodeDrag:D,onNodeDragStop:g,onSelectionDrag:v,onSelectionDragStart:L,onSelectionDragStop:P,onMove:d,onMoveStart:u,onMoveEnd:T,noPanClassName:Do,nodeOrigin:an,rfId:Ki,autoPanOnConnect:Fo,autoPanOnNodeDrag:Go,autoPanSpeed:Ho,onError:he,connectionRadius:k,isValidConnection:ie,selectNodesOnDrag:de,nodeDragThreshold:hr,connectionDragThreshold:Cr,onBeforeDelete:B,debug:II,ariaLabelConfig:OI,zIndexMode:zc}),a.jsx(kP,{onSelectionChange:F}),Nr,a.jsx(BP,{proOptions:vo,position:bo}),a.jsx(wP,{rfId:Ki,disableKeyboardA11y:pr})]})})}var Af=jA(R1);function ff(e){const[t,n]=R.useState(e),r=R.useCallback(o=>n(s=>WA(o,s)),[]);return[t,n,r]}function If(e){const[t,n]=R.useState(e),r=R.useCallback(o=>n(s=>VA(o,s)),[]);return[t,n,r]}function A1({dimensions:e,lineWidth:t,variant:n,className:r}){return a.jsx("path",{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:_e(["react-flow__background-pattern",n,r])})}function f1({radius:e,className:t}){return a.jsx("circle",{cx:e,cy:e,r:e,className:_e(["react-flow__background-pattern","dots",t])})}var Jt;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(Jt||(Jt={}));const I1={[Jt.Dots]:1,[Jt.Lines]:1,[Jt.Cross]:6},O1=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Of({id:e,variant:t=Jt.Dots,gap:n=20,size:r,lineWidth:o=1,offset:s=0,color:i,bgColor:l,style:c,className:E,patternClassName:d}){const u=R.useRef(null),{transform:T,patternId:S}=Se(O1,Oe),f=r||I1[t],A=t===Jt.Dots,O=t===Jt.Cross,I=Array.isArray(n)?n:[n,n],p=[I[0]*T[2]||1,I[1]*T[2]||1],N=f*T[2],h=Array.isArray(s)?s:[s,s],C=O?[N,N]:p,m=[h[0]*T[2]||1+C[0]/2,h[1]*T[2]||1+C[1]/2],_=`${S}${e||""}`;return a.jsxs("svg",{className:_e(["react-flow__background",E]),style:{...c,...Pi,"--xy-background-color-props":l,"--xy-background-pattern-color-props":i},ref:u,"data-testid":"rf__background",children:[a.jsx("pattern",{id:_,x:T[0]%p[0],y:T[1]%p[1],width:p[0],height:p[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${m[0]},-${m[1]})`,children:A?a.jsx(f1,{radius:N/2,className:d}):a.jsx(A1,{dimensions:C,lineWidth:o,variant:t,className:d})}),a.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${_})`})]})}Of.displayName="Background";const Nf=R.memo(Of);function N1(){return a.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:a.jsx("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function p1(){return a.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:a.jsx("path",{d:"M0 0h32v4.2H0z"})})}function h1(){return a.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:a.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 C1(){return a.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:a.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 m1(){return a.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:a.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 ls({children:e,className:t,...n}){return a.jsx("button",{type:"button",className:_e(["react-flow__controls-button",t]),...n,children:e})}const L1=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function pf({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:o,onZoomIn:s,onZoomOut:i,onFitView:l,onInteractiveChange:c,className:E,children:d,position:u="bottom-left",orientation:T="vertical","aria-label":S}){const f=pe(),{isInteractive:A,minZoomReached:O,maxZoomReached:I,ariaLabelConfig:p}=Se(L1,Oe),{zoomIn:N,zoomOut:h,fitView:C}=Yc(),m=()=>{N(),s==null||s()},_=()=>{h(),i==null||i()},D=()=>{C(o),l==null||l()},g=()=>{f.setState({nodesDraggable:!A,nodesConnectable:!A,elementsSelectable:!A}),c==null||c(!A)},b=T==="horizontal"?"horizontal":"vertical";return a.jsxs(Er,{className:_e(["react-flow__controls",b,E]),position:u,style:e,"data-testid":"rf__controls","aria-label":S??p["controls.ariaLabel"],children:[t&&a.jsxs(a.Fragment,{children:[a.jsx(ls,{onClick:m,className:"react-flow__controls-zoomin",title:p["controls.zoomIn.ariaLabel"],"aria-label":p["controls.zoomIn.ariaLabel"],disabled:I,children:a.jsx(N1,{})}),a.jsx(ls,{onClick:_,className:"react-flow__controls-zoomout",title:p["controls.zoomOut.ariaLabel"],"aria-label":p["controls.zoomOut.ariaLabel"],disabled:O,children:a.jsx(p1,{})})]}),n&&a.jsx(ls,{className:"react-flow__controls-fitview",onClick:D,title:p["controls.fitView.ariaLabel"],"aria-label":p["controls.fitView.ariaLabel"],children:a.jsx(h1,{})}),r&&a.jsx(ls,{className:"react-flow__controls-interactive",onClick:g,title:p["controls.interactive.ariaLabel"],"aria-label":p["controls.interactive.ariaLabel"],children:A?a.jsx(m1,{}):a.jsx(C1,{})}),d]})}pf.displayName="Controls";const _1=R.memo(pf);function g1({id:e,x:t,y:n,width:r,height:o,style:s,color:i,strokeColor:l,strokeWidth:c,className:E,borderRadius:d,shapeRendering:u,selected:T,onClick:S}){const{background:f,backgroundColor:A}=s||{},O=i||f||A;return a.jsx("rect",{className:_e(["react-flow__minimap-node",{selected:T},E]),x:t,y:n,rx:d,ry:d,width:r,height:o,style:{fill:O,stroke:l,strokeWidth:c},shapeRendering:u,onClick:S?I=>S(I,e):void 0})}const x1=R.memo(g1),y1=e=>e.nodes.map(t=>t.id),ga=e=>e instanceof Function?e:()=>e;function D1({nodeStrokeColor:e,nodeColor:t,nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:o,nodeComponent:s=x1,onClick:i}){const l=Se(y1,Oe),c=ga(t),E=ga(e),d=ga(n),u=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return a.jsx(a.Fragment,{children:l.map(T=>a.jsx(M1,{id:T,nodeColorFunc:c,nodeStrokeColorFunc:E,nodeClassNameFunc:d,nodeBorderRadius:r,nodeStrokeWidth:o,NodeComponent:s,onClick:i,shapeRendering:u},T))})}function P1({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:o,nodeStrokeWidth:s,shapeRendering:i,NodeComponent:l,onClick:c}){const{node:E,x:d,y:u,width:T,height:S}=Se(f=>{const A=f.nodeLookup.get(e);if(!A)return{node:void 0,x:0,y:0,width:0,height:0};const O=A.internals.userNode,{x:I,y:p}=A.internals.positionAbsolute,{width:N,height:h}=Ut(O);return{node:O,x:I,y:p,width:N,height:h}},Oe);return!E||E.hidden||!fA(E)?null:a.jsx(l,{x:d,y:u,width:T,height:S,style:E.style,selected:!!E.selected,className:r(E),color:t(E),borderRadius:o,strokeColor:n(E),strokeWidth:s,shapeRendering:i,onClick:c,id:E.id})}const M1=R.memo(P1);var b1=R.memo(D1);const v1=200,U1=150,w1=e=>!e.hidden,B1=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?AA(Ro(e.nodeLookup,{filter:w1}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},F1="react-flow__minimap-desc";function hf({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:o="",nodeBorderRadius:s=5,nodeStrokeWidth:i,nodeComponent:l,bgColor:c,maskColor:E,maskStrokeColor:d,maskStrokeWidth:u,position:T="bottom-right",onClick:S,onNodeClick:f,pannable:A=!1,zoomable:O=!1,ariaLabel:I,inversePan:p,zoomStep:N=1,offsetScale:h=5}){const C=pe(),m=R.useRef(null),{boundingRect:_,viewBB:D,rfId:g,panZoom:b,translateExtent:y,flowWidth:M,flowHeight:F,ariaLabelConfig:L}=Se(B1,Oe),v=(e==null?void 0:e.width)??v1,P=(e==null?void 0:e.height)??U1,w=_.width/v,U=_.height/P,x=Math.max(w,U),B=x*v,H=x*P,W=h*x,$=_.x-(B-_.width)/2-W,X=_.y-(H-_.height)/2-W,J=B+W*2,q=H+W*2,z=`${F1}-${g}`,Y=R.useRef(0),K=R.useRef();Y.current=x,R.useEffect(()=>{if(m.current&&b)return K.current=rP({domNode:m.current,panZoom:b,getTransform:()=>C.getState().transform,getViewScale:()=>Y.current}),()=>{var te;(te=K.current)==null||te.destroy()}},[b]),R.useEffect(()=>{var te;(te=K.current)==null||te.update({translateExtent:y,width:M,height:F,inversePan:p,pannable:A,zoomStep:N,zoomable:O})},[A,O,p,N,y,M,F]);const le=S?te=>{var de;const[Ee,fe]=((de=K.current)==null?void 0:de.pointer(te))||[0,0];S(te,{x:Ee,y:fe})}:void 0,se=f?R.useCallback((te,Ee)=>{const fe=C.getState().nodeLookup.get(Ee).internals.userNode;f(te,fe)},[]):void 0,ne=I??L["minimap.ariaLabel"];return a.jsx(Er,{position:T,style:{...e,"--xy-minimap-background-color-props":typeof c=="string"?c:void 0,"--xy-minimap-mask-background-color-props":typeof E=="string"?E: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 i=="number"?i:void 0},className:_e(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:a.jsxs("svg",{width:v,height:P,viewBox:`${$} ${X} ${J} ${q}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":z,ref:m,onClick:le,children:[ne&&a.jsx("title",{id:z,children:ne}),a.jsx(b1,{onClick:se,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:s,nodeClassName:o,nodeStrokeWidth:i,nodeComponent:l}),a.jsx("path",{className:"react-flow__minimap-mask",d:`M${$-W},${X-W}h${J+W*2}v${q+W*2}h${-J-W*2}z
|
|
495
|
+
M${D.x},${D.y}h${D.width}v${D.height}h${-D.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}hf.displayName="MiniMap";const G1=R.memo(hf),H1=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,Y1={[cr.Line]:"right",[cr.Handle]:"bottom-right"};function k1({nodeId:e,position:t,variant:n=cr.Handle,className:r,style:o=void 0,children:s,color:i,minWidth:l=10,minHeight:c=10,maxWidth:E=Number.MAX_VALUE,maxHeight:d=Number.MAX_VALUE,keepAspectRatio:u=!1,resizeDirection:T,autoScale:S=!0,shouldResize:f,onResizeStart:A,onResize:O,onResizeEnd:I}){const p=zA(),N=typeof e=="string"?e:p,h=pe(),C=R.useRef(null),m=n===cr.Handle,_=Se(R.useCallback(H1(m&&S),[m,S]),Oe),D=R.useRef(null),g=t??Y1[n];R.useEffect(()=>{if(!(!C.current||!N))return D.current||(D.current=fP({domNode:C.current,nodeId:N,getStoreItems:()=>{const{nodeLookup:y,transform:M,snapGrid:F,snapToGrid:L,nodeOrigin:v,domNode:P}=h.getState();return{nodeLookup:y,transform:M,snapGrid:F,snapToGrid:L,nodeOrigin:v,paneDomNode:P}},onChange:(y,M)=>{const{triggerNodeChanges:F,nodeLookup:L,parentLookup:v,nodeOrigin:P}=h.getState(),w=[],U={x:y.x,y:y.y},x=L.get(N);if(x&&x.expandParent&&x.parentId){const B=x.origin??P,H=y.width??x.measured.width??0,W=y.height??x.measured.height??0,$={id:x.id,parentId:x.parentId,rect:{width:H,height:W,...IA({x:y.x??x.position.x,y:y.y??x.position.y},{width:H,height:W},x.parentId,L,B)}},X=Hc([$],L,v,P);w.push(...X),U.x=y.x?Math.max(B[0]*H,y.x):void 0,U.y=y.y?Math.max(B[1]*W,y.y):void 0}if(U.x!==void 0&&U.y!==void 0){const B={id:N,type:"position",position:{...U}};w.push(B)}if(y.width!==void 0&&y.height!==void 0){const H={id:N,type:"dimensions",resizing:!0,setAttributes:T?T==="horizontal"?"width":"height":!0,dimensions:{width:y.width,height:y.height}};w.push(H)}for(const B of M){const H={...B,type:"position"};w.push(H)}F(w)},onEnd:({width:y,height:M})=>{const F={id:N,type:"dimensions",resizing:!1,dimensions:{width:y,height:M}};h.getState().triggerNodeChanges([F])}})),D.current.update({controlPosition:g,boundaries:{minWidth:l,minHeight:c,maxWidth:E,maxHeight:d},keepAspectRatio:u,resizeDirection:T,onResizeStart:A,onResize:O,onResizeEnd:I,shouldResize:f}),()=>{var y;(y=D.current)==null||y.destroy()}},[g,l,c,E,d,u,A,O,I,f]);const b=g.split("-");return a.jsx("div",{className:_e(["react-flow__resize-control","nodrag",...b,n,r]),ref:C,style:{...o,scale:_,...i&&{[m?"backgroundColor":"borderColor"]:i}},children:s})}R.memo(k1);var Cf=Object.defineProperty,W1=(e,t,n)=>t in e?Cf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,V1=(e,t)=>{for(var n in t)Cf(e,n,{get:t[n],enumerable:!0})},j1=(e,t,n)=>W1(e,t+"",n),mf={};V1(mf,{Graph:()=>Qe,alg:()=>Wc,json:()=>_f,version:()=>K1});var $1=Object.defineProperty,Lf=(e,t)=>{for(var n in t)$1(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,i,l,c=!1;typeof e=="object"&&e!==null&&"v"in e?(o=e.v,s=e.w,i=e.name,arguments.length===2&&(l=t,c=!0)):(o=e,s=t,i=r,arguments.length>2&&(l=n,c=!0)),o=""+o,s=""+s,i!==void 0&&(i=""+i);let E=br(this._isDirected,o,s,i);if(E in this._edgeLabels)return c&&(this._edgeLabels[E]=l),this;if(i!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(o),this.setNode(s),this._edgeLabels[E]=c?l:this._defaultEdgeLabelFn(o,s,i);let d=X1(this._isDirected,o,s,i);return o=d.v,s=d.w,Object.freeze(d),this._edgeObjs[E]=d,au(this._preds[s],o),au(this._sucs[o],s),this._in[s][E]=d,this._out[o][E]=d,this._edgeCount++,this}edge(e,t,n){let r=arguments.length===1?xa(this._isDirected,e):br(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?xa(this._isDirected,e):br(this._isDirected,e,t,n))in this._edgeLabels}removeEdge(e,t,n){let r=arguments.length===1?xa(this._isDirected,e):br(this._isDirected,e,t,n),o=this._edgeObjs[r];if(o){let s=o.v,i=o.w;delete this._edgeLabels[r],delete this._edgeObjs[r],lu(this._preds[i],s),lu(this._sucs[s],i),delete this._in[i][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 au(e,t){e[t]?e[t]++:e[t]=1}function lu(e,t){e[t]!==void 0&&!--e[t]&&delete e[t]}function br(e,t,n,r){let o=""+t,s=""+n;if(!e&&o>s){let i=o;o=s,s=i}return o+""+s+""+(r===void 0?"\0":r)}function X1(e,t,n,r){let o=""+t,s=""+n;if(!e&&o>s){let l=o;o=s,s=l}let i={v:o,w:s};return r&&(i.name=r),i}function xa(e,t){return br(e,t.v,t.w,t.name)}var K1="4.0.1",_f={};Lf(_f,{read:()=>Q1,write:()=>z1});function z1(e){let t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:J1(e),edges:q1(e)},n=e.graph();return n!==void 0&&(t.value=structuredClone(n)),t}function J1(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 q1(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 Q1(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 Wc={};Lf(Wc,{CycleException:()=>Js,bellmanFord:()=>gf,components:()=>tb,dijkstra:()=>zs,dijkstraAll:()=>ob,findCycles:()=>sb,floydWarshall:()=>ab,isAcyclic:()=>cb,postorder:()=>db,preorder:()=>ub,prim:()=>Tb,shortestPaths:()=>Sb,tarjan:()=>yf,topsort:()=>Df});var Z1=()=>1;function gf(e,t,n,r){return eb(e,String(t),n||Z1,r||function(o){return e.outEdges(o)})}function eb(e,t,n,r){let o={},s,i=0,l=e.nodes(),c=function(u){let T=n(u);o[u.v].distance+T<o[u.w].distance&&(o[u.w]={distance:o[u.v].distance+T,predecessor:u.v},s=!0)},E=function(){l.forEach(function(u){r(u).forEach(function(T){let S=T.v===u?T.v:T.w,f=S===T.v?T.w:T.v;c({v:S,w:f})})})};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,i++,E(),!!s);u++);if(i===d-1&&(s=!1,E(),s))throw new Error("The graph contains a negative weight cycle");return o}function tb(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 xf=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}},nb=()=>1;function zs(e,t,n,r){let o=function(s){return e.outEdges(s)};return rb(e,String(t),n||nb,r||o)}function rb(e,t,n,r){let o={},s=new xf,i,l,c=function(E){let d=E.v!==i?E.v:E.w,u=o[d],T=n(E),S=l.distance+T;if(T<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+E+" Weight: "+T);S<u.distance&&(u.distance=S,u.predecessor=i,s.decrease(d,S))};for(e.nodes().forEach(function(E){let d=E===t?0:Number.POSITIVE_INFINITY;o[E]={distance:d,predecessor:""},s.add(E,d)});s.size()>0&&(i=s.removeMin(),l=o[i],l.distance!==Number.POSITIVE_INFINITY);)r(i).forEach(c);return o}function ob(e,t,n){return e.nodes().reduce(function(r,o){return r[o]=zs(e,o,t,n),r},{})}function yf(e){let t=0,n=[],r={},o=[];function s(i){let l=r[i]={onStack:!0,lowlink:t,index:t++};if(n.push(i),e.successors(i).forEach(function(c){c in r?r[c].onStack&&(l.lowlink=Math.min(l.lowlink,r[c].index)):(s(c),l.lowlink=Math.min(l.lowlink,r[c].lowlink))}),l.lowlink===l.index){let c=[],E;do E=n.pop(),r[E].onStack=!1,c.push(E);while(i!==E);o.push(c)}}return e.nodes().forEach(function(i){i in r||s(i)}),o}function sb(e){return yf(e).filter(function(t){return t.length>1||t.length===1&&e.hasEdge(t[0],t[0])})}var ib=()=>1;function ab(e,t,n){return lb(e,t||ib,n||function(r){return e.outEdges(r)})}function lb(e,t,n){let r={},o=e.nodes();return o.forEach(function(s){r[s]={},r[s][s]={distance:0,predecessor:""},o.forEach(function(i){s!==i&&(r[s][i]={distance:Number.POSITIVE_INFINITY,predecessor:""})}),n(s).forEach(function(i){let l=i.v===s?i.w:i.v,c=t(i);r[s][l]={distance:c,predecessor:s}})}),o.forEach(function(s){let i=r[s];o.forEach(function(l){let c=r[l];o.forEach(function(E){let d=c[s],u=i[E],T=c[E],S=d.distance+u.distance;S<T.distance&&(T.distance=S,T.predecessor=u.predecessor)})})}),r}var Js=class extends Error{constructor(...e){super(...e)}};function Df(e){let t={},n={},r=[];function o(s){if(s in n)throw new Js;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 Js;return r}function cb(e){try{Df(e)}catch(t){if(t instanceof Js)return!1;throw t}return!0}function Eb(e,t,n,r,o){Array.isArray(t)||(t=[t]);let s=(l=>{var c;return(c=e.isDirected()?e.successors(l):e.neighbors(l))!=null?c:[]}),i={};return t.forEach(function(l){if(!e.hasNode(l))throw new Error("Graph does not have node: "+l);o=Pf(e,l,n==="post",i,s,r,o)}),o}function Pf(e,t,n,r,o,s,i){return t in r||(r[t]=!0,n||(i=s(i,t)),o(t).forEach(function(l){i=Pf(e,l,n,r,o,s,i)}),n&&(i=s(i,t))),i}function Mf(e,t,n){return Eb(e,t,n,function(r,o){return r.push(o),r},[])}function db(e,t){return Mf(e,t,"post")}function ub(e,t){return Mf(e,t,"pre")}function Tb(e,t){let n=new Qe,r={},o=new xf,s;function i(c){let E=c.v===s?c.w:c.v,d=o.priority(E);if(d!==void 0){let u=t(c);u<d&&(r[E]=s,o.decrease(E,u))}}if(e.nodeCount()===0)return n;e.nodes().forEach(function(c){o.add(c,Number.POSITIVE_INFINITY),n.setNode(c)}),o.decrease(e.nodes()[0],0);let l=!1;for(;o.size()>0;){if(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(i)}return n}function Sb(e,t,n,r){return Rb(e,t,n,r??(o=>{let s=e.outEdges(o);return s??[]}))}function Rb(e,t,n,r){if(n===void 0)return zs(e,t,n,r);let o=!1,s=e.nodes();for(let i=0;i<s.length;i++){let l=r(s[i]);for(let c=0;c<l.length;c++){let E=l[c],d=E.v===s[i]?E.v:E.w,u=d===E.v?E.w:E.v;n({v:d,w:u})<0&&(o=!0)}if(o)return gf(e,t,n,r)}return zs(e,t,n,r)}function Ar(e,t,n,r){let o=r;for(;e.hasNode(o);)o=Vc(r);return n.dummy=t,e.setNode(o,n),o}function Ab(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 bf(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 cu(e,t){let n=e.x,r=e.y,o=t.x-n,s=t.y-r,i=e.width/2,l=e.height/2;if(!o&&!s)throw new Error("Not possible to find intersection inside of the rectangle");let c,E;return Math.abs(s)*i>Math.abs(o)*l?(s<0&&(l=-l),c=l*o/s,E=l):(o<0&&(i=-i),c=i,E=i*s/o),{x:n+c,y:r+E}}function Io(e){let t=ro(Uf(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 fb(e){let t=e.nodes().map(r=>{let o=e.node(r).rank;return o===void 0?Number.MAX_VALUE:o}),n=ft(Math.min,t);e.nodes().forEach(r=>{let o=e.node(r);Object.hasOwn(o,"rank")&&(o.rank-=n)})}function Ib(e){let t=e.nodes().map(i=>e.node(i).rank).filter(i=>i!==void 0),n=ft(Math.min,t),r=[];e.nodes().forEach(i=>{let l=e.node(i).rank-n;r[l]||(r[l]=[]),r[l].push(i)});let o=0,s=e.graph().nodeRankFactor;Array.from(r).forEach((i,l)=>{i===void 0&&l%s!==0?--o:i!==void 0&&o&&i.forEach(c=>e.node(c).rank+=o)})}function Eu(e,t,n,r){let o={width:0,height:0};return arguments.length>=4&&(o.rank=n,o.order=r),Ar(e,"border",o,t)}function Ob(e,t=vf){let n=[];for(let r=0;r<e.length;r+=t){let o=e.slice(r,r+t);n.push(o)}return n}var vf=65535;function ft(e,t){if(t.length>vf){let n=Ob(t);return e(...n.map(r=>e(...r)))}else return e(...t)}function Uf(e){let t=e.nodes().map(n=>{let r=e.node(n).rank;return r===void 0?Number.MIN_VALUE:r});return ft(Math.max,t)}function Nb(e,t){let n={lhs:[],rhs:[]};return e.forEach(r=>{t(r)?n.lhs.push(r):n.rhs.push(r)}),n}function wf(e,t){let n=Date.now();try{return t()}finally{console.log(e+" time: "+(Date.now()-n)+"ms")}}function Bf(e,t){return t()}var pb=0;function Vc(e){let t=++pb;return e+(""+t)}function ro(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 qs(e,t){let n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return n}function bi(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 hb(e,t){return e.reduce((n,r,o)=>(n[r]=t[o],n),{})}var vi="\0",Cb="3.0.0",mb=class{constructor(){j1(this,"_sentinel");let e={};e._next=e._prev=e,this._sentinel=e}dequeue(){let e=this._sentinel,t=e._prev;if(t!==e)return du(t),t}enqueue(e){let t=this._sentinel;e._prev&&e._next&&du(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,Lb)),n=n._prev;return"["+e.join(", ")+"]"}};function du(e){e._prev._next=e._next,e._next._prev=e._prev,delete e._next,delete e._prev}function Lb(e,t){if(e!=="_next"&&e!=="_prev")return t}var _b=mb,gb=()=>1;function xb(e,t){if(e.nodeCount()<=1)return[];let n=Db(e,t||gb);return yb(n.graph,n.buckets,n.zeroIdx).flatMap(r=>e.outEdges(r.v,r.w)||[])}function yb(e,t,n){var r;let o=[],s=t[t.length-1],i=t[0],l;for(;e.nodeCount();){for(;l=i.dequeue();)ya(e,t,n,l);for(;l=s.dequeue();)ya(e,t,n,l);if(e.nodeCount()){for(let c=t.length-2;c>0;--c)if(l=(r=t[c])==null?void 0:r.dequeue(),l){o=o.concat(ya(e,t,n,l,!0)||[]);break}}}return o}function ya(e,t,n,r,o){let s=[],i=o?s:void 0;return(e.inEdges(r.v)||[]).forEach(l=>{let c=e.edge(l),E=e.node(l.v);o&&s.push({v:l.v,w:l.w}),E.out-=c,wl(t,n,E)}),(e.outEdges(r.v)||[]).forEach(l=>{let c=e.edge(l),E=l.w,d=e.node(E);d.in-=c,wl(t,n,d)}),e.removeNode(r.v),i}function Db(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 c=n.edge(l.v,l.w)||0,E=t(l),d=c+E;n.setEdge(l.v,l.w,d);let u=n.node(l.v),T=n.node(l.w);o=Math.max(o,u.out+=E),r=Math.max(r,T.in+=E)});let s=Pb(o+r+3).map(()=>new _b),i=r+1;return n.nodes().forEach(l=>{wl(s,i,n.node(l))}),{graph:n,buckets:s,zeroIdx:i}}function wl(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 Pb(e){let t=[];for(let n=0;n<e;n++)t.push(n);return t}function Mb(e){(e.graph().acyclicer==="greedy"?xb(e,t(e)):bb(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,Vc("rev"))});function t(n){return r=>n.edge(r).weight}}function bb(e){let t=[],n={},r={};function o(s){Object.hasOwn(r,s)||(r[s]=!0,n[s]=!0,e.outEdges(s).forEach(i=>{Object.hasOwn(n,i.w)?t.push(i):o(i.w)}),delete n[s])}return e.nodes().forEach(o),t}function vb(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 Ub(e){e.graph().dummyChains=[],e.edges().forEach(t=>wb(e,t))}function wb(e,t){let n=t.v,r=e.node(n).rank,o=t.w,s=e.node(o).rank,i=t.name,l=e.edge(t),c=l.labelRank;if(s===r+1)return;e.removeEdge(t);let E,d,u;for(u=0,++r;r<s;++u,++r)l.points=[],d={width:0,height:0,edgeLabel:l,edgeObj:t,rank:r},E=Ar(e,"edge",d,"_d"),r===c&&(d.width=l.width,d.height=l.height,d.dummy="edge-label",d.labelpos=l.labelpos),e.setEdge(n,E,{weight:l.weight},i),u===0&&e.graph().dummyChains.push(E),n=E;e.setEdge(n,o,{weight:l.weight},i)}function Bb(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 jc(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),i=s?s.map(c=>c==null?Number.POSITIVE_INFINITY:n(c.w)-e.edge(c).minlen):[],l=ft(Math.min,i);return l===Number.POSITIVE_INFINITY&&(l=0),o.rank=l}e.sources().forEach(n)}function dr(e,t){return e.node(t.w).rank-e.node(t.v).rank-e.edge(t).minlen}var Ff=Fb;function Fb(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,i;for(;Gb(t,e)<o&&(s=Hb(t,e),!!s);)i=t.hasNode(s.v)?dr(e,s):-dr(e,s),Yb(t,e,i);return t}function Gb(e,t){function n(r){let o=t.nodeEdges(r);o&&o.forEach(s=>{let i=s.v,l=r===i?s.w:i;!e.hasNode(l)&&!dr(t,s)&&(e.setNode(l,{}),e.setEdge(r,l,{}),n(l))})}return e.nodes().forEach(n),e.nodeCount()}function Hb(e,t){return t.edges().reduce((n,r)=>{let o=Number.POSITIVE_INFINITY;return e.hasNode(r.v)!==e.hasNode(r.w)&&(o=dr(t,r)),o<n[0]?[o,r]:n},[Number.POSITIVE_INFINITY,null])[1]}function Yb(e,t,n){e.nodes().forEach(r=>t.node(r).rank+=n)}var{preorder:kb,postorder:Wb}=Wc,Vb=xn;xn.initLowLimValues=Xc;xn.initCutValues=$c;xn.calcCutValue=Gf;xn.leaveEdge=Yf;xn.enterEdge=kf;xn.exchangeEdges=Wf;function xn(e){e=Ab(e),jc(e);let t=Ff(e);Xc(t),$c(t,e);let n,r;for(;n=Yf(t);)r=kf(t,e,n),Wf(t,e,n,r)}function $c(e,t){let n=Wb(e,e.nodes());n=n.slice(0,n.length-1),n.forEach(r=>jb(e,t,r))}function jb(e,t,n){let r=e.node(n).parent,o=e.edge(n,r);o.cutvalue=Gf(e,t,n)}function Gf(e,t,n){let r=e.node(n).parent,o=!0,s=t.edge(n,r),i=0;s||(o=!1,s=t.edge(r,n)),i=s.weight;let l=t.nodeEdges(n);return l&&l.forEach(c=>{let E=c.v===n,d=E?c.w:c.v;if(d!==r){let u=E===o,T=t.edge(c).weight;if(i+=u?T:-T,Xb(e,n,d)){let S=e.edge(n,d).cutvalue;i+=u?-S:S}}}),i}function Xc(e,t){arguments.length<2&&(t=e.nodes()[0]),Hf(e,{},1,t)}function Hf(e,t,n,r,o){let s=n,i=e.node(r);t[r]=!0;let l=e.neighbors(r);return l&&l.forEach(c=>{Object.hasOwn(t,c)||(n=Hf(e,t,n,c,r))}),i.low=s,i.lim=n++,o?i.parent=o:delete i.parent,n}function Yf(e){return e.edges().find(t=>e.edge(t).cutvalue<0)}function kf(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),i=e.node(o),l=s,c=!1;return s.lim>i.lim&&(l=i,c=!0),t.edges().filter(E=>c===uu(e,e.node(E.v),l)&&c!==uu(e,e.node(E.w),l)).reduce((E,d)=>dr(t,d)<dr(t,E)?d:E)}function Wf(e,t,n,r){let o=n.v,s=n.w;e.removeEdge(o,s),e.setEdge(r.v,r.w,{}),Xc(e),$c(e,t),$b(e,t)}function $b(e,t){let n=e.nodes().find(o=>!e.node(o).parent);if(!n)return;let r=kb(e,[n]);r=r.slice(1),r.forEach(o=>{let s=e.node(o).parent,i=t.edge(o,s),l=!1;i||(i=t.edge(s,o),l=!0),t.node(o).rank=t.node(s).rank+(l?i.minlen:-i.minlen)})}function Xb(e,t,n){return e.hasEdge(t,n)}function uu(e,t,n){return n.low<=t.lim&&t.lim<=n.lim}var Kb=zb;function zb(e){let t=e.graph().ranker;if(typeof t=="function")return t(e);switch(t){case"network-simplex":Tu(e);break;case"tight-tree":qb(e);break;case"longest-path":Jb(e);break;case"none":break;default:Tu(e)}}var Jb=jc;function qb(e){jc(e),Ff(e)}function Tu(e){Vb(e)}var Qb=Zb;function Zb(e){let t=tv(e);e.graph().dummyChains.forEach(n=>{let r=e.node(n),o=r.edgeObj,s=ev(e,t,o.v,o.w),i=s.path,l=s.lca,c=0,E=i[c],d=!0;for(;n!==o.w;){if(r=e.node(n),d){for(;(E=i[c])!==l&&e.node(E).maxRank<r.rank;)c++;E===l&&(d=!1)}if(!d){for(;c<i.length-1&&e.node(i[c+1]).minRank<=r.rank;)c++;E=i[c]}E!==void 0&&e.setParent(n,E),n=e.successors(n)[0]}})}function ev(e,t,n,r){let o=[],s=[],i=Math.min(t[n].low,t[r].low),l=Math.max(t[n].lim,t[r].lim),c;c=n;do c=e.parent(c),o.push(c);while(c&&(t[c].low>i||l>t[c].lim));let E=c,d=r;for(;(d=e.parent(d))!==E;)s.push(d);return{path:o.concat(s.reverse()),lca:E}}function tv(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(vi).forEach(r),t}function nv(e){let t=Ar(e,"root",{},"_root"),n=rv(e),r=Object.values(n),o=ft(Math.max,r)-1,s=2*o+1;e.graph().nestingRoot=t,e.edges().forEach(l=>e.edge(l).minlen*=s);let i=ov(e)+1;e.children(vi).forEach(l=>Vf(e,t,s,i,o,n,l)),e.graph().nodeRankFactor=s}function Vf(e,t,n,r,o,s,i){var l;let c=e.children(i);if(!c.length){i!==t&&e.setEdge(t,i,{weight:0,minlen:n});return}let E=Eu(e,"_bt"),d=Eu(e,"_bb"),u=e.node(i);e.setParent(E,i),u.borderTop=E,e.setParent(d,i),u.borderBottom=d,c.forEach(T=>{var S;Vf(e,t,n,r,o,s,T);let f=e.node(T),A=f.borderTop?f.borderTop:T,O=f.borderBottom?f.borderBottom:T,I=f.borderTop?r:2*r,p=A!==O?1:o-((S=s[i])!=null?S:0)+1;e.setEdge(E,A,{weight:I,minlen:p,nestingEdge:!0}),e.setEdge(O,d,{weight:I,minlen:p,nestingEdge:!0})}),e.parent(i)||e.setEdge(t,E,{weight:0,minlen:o+((l=s[i])!=null?l:0)})}function rv(e){let t={};function n(r,o){let s=e.children(r);s&&s.length&&s.forEach(i=>n(i,o+1)),t[r]=o}return e.children(vi).forEach(r=>n(r,1)),t}function ov(e){return e.edges().reduce((t,n)=>t+e.edge(n).weight,0)}function sv(e){let t=e.graph();e.removeNode(t.nestingRoot),delete t.nestingRoot,e.edges().forEach(n=>{e.edge(n).nestingEdge&&e.removeEdge(n)})}var iv=av;function av(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,i=o.maxRank+1;s<i;++s)Su(e,"borderLeft","_bl",n,o,s),Su(e,"borderRight","_br",n,o,s)}}e.children(vi).forEach(t)}function Su(e,t,n,r,o,s){let i={width:0,height:0,rank:s,borderType:t},l=o[t][s-1],c=Ar(e,"border",i,n);o[t][s]=c,e.setParent(c,r),l&&e.setEdge(l,c,{weight:1})}function lv(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="lr"||n==="rl")&&jf(e)}function cv(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="bt"||n==="rl")&&Ev(e),(n==="lr"||n==="rl")&&(dv(e),jf(e))}function jf(e){e.nodes().forEach(t=>Ru(e.node(t))),e.edges().forEach(t=>Ru(e.edge(t)))}function Ru(e){let t=e.width;e.width=e.height,e.height=t}function Ev(e){e.nodes().forEach(t=>Da(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(Da),Object.hasOwn(r,"y")&&Da(r)})}function Da(e){e.y=-e.y}function dv(e){e.nodes().forEach(t=>Pa(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(Pa),Object.hasOwn(r,"x")&&Pa(r)})}function Pa(e){let t=e.x;e.x=e.y,e.y=t}function uv(e){let t={},n=e.nodes().filter(l=>!e.children(l).length),r=n.map(l=>e.node(l).rank),o=ft(Math.max,r),s=ro(o+1).map(()=>[]);function i(l){if(t[l])return;t[l]=!0;let c=e.node(l);s[c.rank].push(l);let E=e.successors(l);E&&E.forEach(i)}return n.sort((l,c)=>e.node(l).rank-e.node(c).rank).forEach(i),s}function Tv(e,t){let n=0;for(let r=1;r<t.length;++r)n+=Sv(e,t[r-1],t[r]);return n}function Sv(e,t,n){let r=hb(n,n.map((E,d)=>d)),o=t.flatMap(E=>{let d=e.outEdges(E);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 i=2*s-1;s-=1;let l=new Array(i).fill(0),c=0;return o.forEach(E=>{let d=E.pos+s;l[d]+=E.weight;let u=0;for(;d>0;)d%2&&(u+=l[d+1]),d=d-1>>1,l[d]+=E.weight;c+=E.weight*u}),c}function Rv(e,t=[]){return t.map(n=>{let r=e.inEdges(n);if(!r||!r.length)return{v:n};{let o=r.reduce((s,i)=>{let l=e.edge(i),c=e.node(i.v);return{sum:s.sum+l.weight*c.order,weight:s.weight+l.weight}},{sum:0,weight:0});return{v:n,barycenter:o.sum/o.weight,weight:o.weight}}})}function Av(e,t){let n={};e.forEach((o,s)=>{let i={indegree:0,in:[],out:[],vs:[o.v],i:s};o.barycenter!==void 0&&(i.barycenter=o.barycenter,i.weight=o.weight),n[o.v]=i}),t.edges().forEach(o=>{let s=n[o.v],i=n[o.w];s!==void 0&&i!==void 0&&(i.indegree++,s.out.push(i))});let r=Object.values(n).filter(o=>!o.indegree);return fv(r)}function fv(e){let t=[];function n(o){return s=>{s.merged||(s.barycenter===void 0||o.barycenter===void 0||s.barycenter>=o.barycenter)&&Iv(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=>qs(o,["vs","i","barycenter","weight"]))}function Iv(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 Ov(e,t){let n=Nb(e,d=>Object.hasOwn(d,"barycenter")),r=n.lhs,o=n.rhs.sort((d,u)=>u.i-d.i),s=[],i=0,l=0,c=0;r.sort(Nv(!!t)),c=Au(s,o,c),r.forEach(d=>{c+=d.vs.length,s.push(d.vs),i+=d.barycenter*d.weight,l+=d.weight,c=Au(s,o,c)});let E={vs:s.flat(1)};return l&&(E.barycenter=i/l,E.weight=l),E}function Au(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 Nv(e){return(t,n)=>t.barycenter<n.barycenter?-1:t.barycenter>n.barycenter?1:e?n.i-t.i:t.i-n.i}function $f(e,t,n,r){let o=e.children(t),s=e.node(t),i=s?s.borderLeft:void 0,l=s?s.borderRight:void 0,c={};i&&(o=o.filter(T=>T!==i&&T!==l));let E=Rv(e,o);E.forEach(T=>{if(e.children(T.v).length){let S=$f(e,T.v,n,r);c[T.v]=S,Object.hasOwn(S,"barycenter")&&hv(T,S)}});let d=Av(E,n);pv(d,c);let u=Ov(d,r);if(i&&l){u.vs=[i,u.vs,l].flat(1);let T=e.predecessors(i);if(T&&T.length){let S=e.node(T[0]),f=e.predecessors(l),A=e.node(f[0]);Object.hasOwn(u,"barycenter")||(u.barycenter=0,u.weight=0),u.barycenter=(u.barycenter*u.weight+S.order+A.order)/(u.weight+2),u.weight+=2}}return u}function pv(e,t){e.forEach(n=>{n.vs=n.vs.flatMap(r=>t[r]?t[r].vs:r)})}function hv(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 Cv(e,t,n,r){r||(r=e.nodes());let o=mv(e),s=new Qe({compound:!0}).setGraph({root:o}).setDefaultNodeLabel(i=>e.node(i));return r.forEach(i=>{let l=e.node(i),c=e.parent(i);if(l.rank===t||l.minRank<=t&&t<=l.maxRank){s.setNode(i),s.setParent(i,c||o);let E=e[n](i);E&&E.forEach(d=>{let u=d.v===i?d.w:d.v,T=s.edge(u,i),S=T!==void 0?T.weight:0;s.setEdge(u,i,{weight:e.edge(d).weight+S})}),Object.hasOwn(l,"minRank")&&s.setNode(i,{borderLeft:l.borderLeft[t],borderRight:l.borderRight[t]})}}),s}function mv(e){let t;for(;e.hasNode(t=Vc("_root")););return t}function Lv(e,t,n){let r={},o;n.forEach(s=>{let i=e.parent(s),l,c;for(;i;){if(l=e.parent(i),l?(c=r[l],r[l]=i):(c=o,o=i),c&&c!==i){t.setEdge(c,i);return}i=l}})}function Xf(e,t={}){if(typeof t.customOrder=="function"){t.customOrder(e,Xf);return}let n=Uf(e),r=fu(e,ro(1,n+1),"inEdges"),o=fu(e,ro(n-1,-1,-1),"outEdges"),s=uv(e);if(Iu(e,s),t.disableOptimalOrderHeuristic)return;let i=Number.POSITIVE_INFINITY,l,c=t.constraints||[];for(let E=0,d=0;d<4;++E,++d){_v(E%2?r:o,E%4>=2,c),s=Io(e);let u=Tv(e,s);u<i?(d=0,l=Object.assign({},s),i=u):u===i&&(l=structuredClone(s))}Iu(e,l)}function fu(e,t,n){let r=new Map,o=(s,i)=>{r.has(s)||r.set(s,[]),r.get(s).push(i)};for(let s of e.nodes()){let i=e.node(s);if(typeof i.rank=="number"&&o(i.rank,s),typeof i.minRank=="number"&&typeof i.maxRank=="number")for(let l=i.minRank;l<=i.maxRank;l++)l!==i.rank&&o(l,s)}return t.map(function(s){return Cv(e,s,n,r.get(s)||[])})}function _v(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,i=$f(o,s,r,t);i.vs.forEach((l,c)=>o.node(l).order=c),Lv(o,r,i.vs)})}function Iu(e,t){Object.values(t).forEach(n=>n.forEach((r,o)=>e.node(r).order=o))}function gv(e,t){let n={};function r(o,s){let i=0,l=0,c=o.length,E=s[s.length-1];return s.forEach((d,u)=>{let T=yv(e,d),S=T?e.node(T).order:c;(T||d===E)&&(s.slice(l,u+1).forEach(f=>{let A=e.predecessors(f);A&&A.forEach(O=>{let I=e.node(O),p=I.order;(p<i||S<p)&&!(I.dummy&&e.node(f).dummy)&&Kf(n,O,f)})}),l=u+1,i=S)}),s}return t.length&&t.reduce(r),n}function xv(e,t){let n={};function r(s,i,l,c,E){ro(i,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 f=e.node(S);f.dummy&&(f.order<c||f.order>E)&&Kf(n,S,u)})}})}function o(s,i){let l=-1,c=-1,E=0;return i.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;c=e.node(S).order,r(i,E,u,l,c),E=u,l=c}}r(i,E,i.length,c,s.length)}),i}return t.length&&t.reduce(o),n}function yv(e,t){if(e.node(t).dummy){let n=e.predecessors(t);if(n)return n.find(r=>e.node(r).dummy)}}function Kf(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 Dv(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 Pv(e,t,n,r){let o={},s={},i={};return t.forEach(l=>{l.forEach((c,E)=>{o[c]=c,s[c]=c,i[c]=E})}),t.forEach(l=>{let c=-1;l.forEach(E=>{let d=r(E);if(d&&d.length){let u=d.sort((S,f)=>{let A=i[S],O=i[f];return(A!==void 0?A:0)-(O!==void 0?O:0)}),T=(u.length-1)/2;for(let S=Math.floor(T),f=Math.ceil(T);S<=f;++S){let A=u[S];if(A===void 0)continue;let O=i[A];if(O!==void 0&&s[E]===E&&c<O&&!Dv(n,E,A)){let I=o[A];I!==void 0&&(s[A]=E,s[E]=o[E]=I,c=O)}}}})}),{root:o,align:s}}function Mv(e,t,n,r,o=!1){let s={},i=bv(e,t,n,o),l=o?"borderLeft":"borderRight";function c(S,f){let A=i.nodes().slice(),O={},I=A.pop();for(;I;){if(O[I])S(I);else{O[I]=!0,A.push(I);for(let p of f(I))A.push(p)}I=A.pop()}}function E(S){let f=i.inEdges(S);f?s[S]=f.reduce((A,O)=>{var I;let p=(I=s[O.v])!=null?I:0,N=i.edge(O);return Math.max(A,p+(N!==void 0?N:0))},0):s[S]=0}function d(S){let f=i.outEdges(S),A=Number.POSITIVE_INFINITY;f&&(A=f.reduce((I,p)=>{let N=s[p.w],h=i.edge(p);return Math.min(I,(N!==void 0?N:0)-(h!==void 0?h:0))},Number.POSITIVE_INFINITY));let O=e.node(S);A!==Number.POSITIVE_INFINITY&&O.borderType!==l&&(s[S]=Math.max(s[S]!==void 0?s[S]:0,A))}function u(S){return i.predecessors(S)||[]}function T(S){return i.successors(S)||[]}return c(E,u),c(d,T),Object.keys(r).forEach(S=>{var f;let A=n[S];A!==void 0&&(s[S]=(f=s[A])!=null?f:0)}),s}function bv(e,t,n,r){let o=new Qe,s=e.graph(),i=Fv(s.nodesep,s.edgesep,r);return t.forEach(l=>{let c;l.forEach(E=>{let d=n[E];if(d!==void 0){if(o.setNode(d),c!==void 0){let u=n[c];if(u!==void 0){let T=o.edge(u,d);o.setEdge(u,d,Math.max(i(e,E,c),T||0))}}c=E}})}),o}function vv(e,t){return Object.values(t).reduce((n,r)=>{let o=Number.NEGATIVE_INFINITY,s=Number.POSITIVE_INFINITY;Object.entries(r).forEach(([l,c])=>{let E=Gv(e,l)/2;o=Math.max(c+E,o),s=Math.min(c-E,s)});let i=o-s;return i<n[0]&&(n=[i,r]),n},[Number.POSITIVE_INFINITY,null])[1]}function Uv(e,t){let n=Object.values(t),r=ft(Math.min,n),o=ft(Math.max,n);["u","d"].forEach(s=>{["l","r"].forEach(i=>{let l=s+i,c=e[l];if(!c||c===t)return;let E=Object.values(c),d=r-ft(Math.min,E);i!=="l"&&(d=o-ft(Math.max,E)),d&&(e[l]=bi(c,u=>u+d))})})}function wv(e,t=void 0){let n=e.ul;return n?bi(n,(r,o)=>{var s,i;if(t){let c=t.toLowerCase(),E=e[c];if(E&&E[o]!==void 0)return E[o]}let l=Object.values(e).map(c=>{let E=c[o];return E!==void 0?E:0}).sort((c,E)=>c-E);return(((s=l[1])!=null?s:0)+((i=l[2])!=null?i:0))/2}):{}}function Bv(e){let t=Io(e),n=Object.assign(gv(e,t),xv(e,t)),r={},o;["u","d"].forEach(i=>{o=i==="u"?t:Object.values(t).reverse(),["l","r"].forEach(l=>{l==="r"&&(o=o.map(d=>Object.values(d).reverse()));let c=Pv(e,o,n,d=>(i==="u"?e.predecessors(d):e.successors(d))||[]),E=Mv(e,o,c.root,c.align,l==="r");l==="r"&&(E=bi(E,d=>-d)),r[i+l]=E})});let s=vv(e,r);return Uv(r,s),wv(r,e.graph().align)}function Fv(e,t,n){return(r,o,s)=>{let i=r.node(o),l=r.node(s),c=0,E;if(c+=i.width/2,Object.hasOwn(i,"labelpos"))switch(i.labelpos.toLowerCase()){case"l":E=-i.width/2;break;case"r":E=i.width/2;break}if(E&&(c+=n?E:-E),E=void 0,c+=(i.dummy?t:e)/2,c+=(l.dummy?t:e)/2,c+=l.width/2,Object.hasOwn(l,"labelpos"))switch(l.labelpos.toLowerCase()){case"l":E=l.width/2;break;case"r":E=-l.width/2;break}return E&&(c+=n?E:-E),c}}function Gv(e,t){return e.node(t).width}function Hv(e){e=bf(e),Yv(e),Object.entries(Bv(e)).forEach(([t,n])=>e.node(t).x=n)}function Yv(e){let t=Io(e),n=e.graph(),r=n.ranksep,o=n.rankalign,s=0;t.forEach(i=>{let l=i.reduce((c,E)=>{var d;let u=(d=e.node(E).height)!=null?d:0;return c>u?c:u},0);i.forEach(c=>{let E=e.node(c);o==="top"?E.y=s+E.height/2:o==="bottom"?E.y=s+l-E.height/2:E.y=s+l/2}),s+=l+r})}function kv(e,t={}){let n=t.debugTiming?wf:Bf;return n("layout",()=>{let r=n(" buildLayoutGraph",()=>Qv(e));return n(" runLayout",()=>Wv(r,n,t)),n(" updateInputGraph",()=>Vv(e,r)),r})}function Wv(e,t,n){t(" makeSpaceForEdgeLabels",()=>Zv(e)),t(" removeSelfEdges",()=>lU(e)),t(" acyclic",()=>Mb(e)),t(" nestingGraph.run",()=>nv(e)),t(" rank",()=>Kb(bf(e))),t(" injectEdgeLabelProxies",()=>eU(e)),t(" removeEmptyRanks",()=>Ib(e)),t(" nestingGraph.cleanup",()=>sv(e)),t(" normalizeRanks",()=>fb(e)),t(" assignRankMinMax",()=>tU(e)),t(" removeEdgeLabelProxies",()=>nU(e)),t(" normalize.run",()=>Ub(e)),t(" parentDummyChains",()=>Qb(e)),t(" addBorderSegments",()=>iv(e)),t(" order",()=>Xf(e,n)),t(" insertSelfEdges",()=>cU(e)),t(" adjustCoordinateSystem",()=>lv(e)),t(" position",()=>Hv(e)),t(" positionSelfEdges",()=>EU(e)),t(" removeBorderNodes",()=>aU(e)),t(" normalize.undo",()=>Bb(e)),t(" fixupEdgeLabelCoords",()=>sU(e)),t(" undoCoordinateSystem",()=>cv(e)),t(" translateGraph",()=>rU(e)),t(" assignNodeIntersects",()=>oU(e)),t(" reversePoints",()=>iU(e)),t(" acyclic.undo",()=>vb(e))}function Vv(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 jv=["nodesep","edgesep","ranksep","marginx","marginy"],$v={ranksep:50,edgesep:20,nodesep:50,rankdir:"TB",rankalign:"center"},Xv=["acyclicer","ranker","rankdir","align","rankalign"],Kv=["width","height","rank"],Ou={width:0,height:0},zv=["minlen","weight","width","height","labeloffset"],Jv={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},qv=["labelpos"];function Qv(e){let t=new Qe({multigraph:!0,compound:!0}),n=ba(e.graph());return t.setGraph(Object.assign({},$v,Ma(n,jv),qs(n,Xv))),e.nodes().forEach(r=>{let o=ba(e.node(r)),s=Ma(o,Kv);Object.keys(Ou).forEach(l=>{s[l]===void 0&&(s[l]=Ou[l])}),t.setNode(r,s);let i=e.parent(r);i!==void 0&&t.setParent(r,i)}),e.edges().forEach(r=>{let o=ba(e.edge(r));t.setEdge(r,Object.assign({},Jv,Ma(o,zv),qs(o,qv)))}),t}function Zv(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 eU(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};Ar(e,"edge-proxy",o,"_ep")}})}function tU(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 nU(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 rU(e){let t=Number.POSITIVE_INFINITY,n=0,r=Number.POSITIVE_INFINITY,o=0,s=e.graph(),i=s.marginx||0,l=s.marginy||0;function c(E){let d=E.x,u=E.y,T=E.width,S=E.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(E=>c(e.node(E))),e.edges().forEach(E=>{let d=e.edge(E);Object.hasOwn(d,"x")&&c(d)}),t-=i,r-=l,e.nodes().forEach(E=>{let d=e.node(E);d.x-=t,d.y-=r}),e.edges().forEach(E=>{let d=e.edge(E);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+i,s.height=o-r+l}function oU(e){e.edges().forEach(t=>{let n=e.edge(t),r=e.node(t.v),o=e.node(t.w),s,i;n.points?(s=n.points[0],i=n.points[n.points.length-1]):(n.points=[],s=o,i=r),n.points.unshift(cu(r,s)),n.points.push(cu(o,i))})}function sU(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 iU(e){e.edges().forEach(t=>{let n=e.edge(t);n.reversed&&n.points.reverse()})}function aU(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]),i=e.node(n.borderRight[n.borderRight.length-1]);n.width=Math.abs(i.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 lU(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 cU(e){Io(e).forEach(t=>{let n=0;t.forEach((r,o)=>{let s=e.node(r);s.order=o+n,(s.selfEdges||[]).forEach(i=>{Ar(e,"selfedge",{width:i.label.width,height:i.label.height,rank:s.rank,order:o+ ++n,e:i.e,label:i.label},"_se")}),delete s.selfEdges})})}function EU(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,i=o.y,l=n.x-s,c=o.height/2;e.setEdge(r.e,r.label),e.removeNode(t),r.label.points=[{x:s+2*l/3,y:i-c},{x:s+5*l/6,y:i-c},{x:s+l,y:i},{x:s+5*l/6,y:i+c},{x:s+2*l/3,y:i+c}],r.label.x=n.x,r.label.y=n.y}})}function Ma(e,t){return bi(qs(e,t),Number)}function ba(e){let t={};return e&&Object.entries(e).forEach(([n,r])=>{typeof n=="string"&&(n=n.toLowerCase()),t[n]=r}),t}function dU(e){let t=Io(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((i,l)=>(n.setEdge(i,l,{style:"invis"}),l))}),n}var uU={graphlib:mf,version:Cb,layout:kv,debug:dU,util:{time:wf,notime:Bf}},Qs=uU;/*! For license information please see dagre.esm.js.LEGAL.txt */function TU(e,t,n={}){var o;if(e.length===0)return e;const r=new Qs.graphlib.Graph().setDefaultEdgeLabel(()=>({}));r.setGraph({rankdir:"LR",ranksep:60,nodesep:30,marginx:20,marginy:20});for(const s of e){const i={width:170,height:52};if(n.mode==="layered"&&((o=s.data)!=null&&o.layer)){const l=Ms.indexOf(s.data.layer);l>=0&&(i.rank=l)}r.setNode(s.id,i)}for(const s of t)r.setEdge(s.source,s.target);return Qs.layout(r),e.map(s=>{const i=r.node(s.id);return{...s,position:{x:i.x-85,y:i.y-26}}})}function SU({data:e,selected:t}){const n=e.nodeType,r=e.isFocal,o=we[n]??"#8b949e",s=Sc[n]??n.toUpperCase();return a.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:[a.jsx(tn,{type:"target",position:ee.Left,style:{width:6,height:6,background:o,border:"none"}}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginBottom:2},children:[a.jsx("span",{style:{fontSize:8,fontWeight:700,letterSpacing:"0.04em",color:"#0d1117",background:o,borderRadius:3,padding:"1px 4px"},children:s}),e.domain&&a.jsx("span",{style:{color:"#8b949e",fontSize:9},children:e.domain})]}),a.jsx("div",{style:{color:"#e6edf3",fontSize:10,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.label,children:e.label}),a.jsx(tn,{type:"source",position:ee.Right,style:{width:6,height:6,background:o,border:"none"}})]})}const RU={miniDagNode:SU};function zf({nodes:e,edges:t,focalNodeId:n,height:r=250,onNodeClick:o,interactive:s=!0,layoutMode:i="flow"}){const[l,c,E]=ff([]),[d,u,T]=If([]);return R.useEffect(()=>{const S=e.map(A=>({id:A.id,type:"miniDagNode",position:{x:0,y:0},data:{label:A.name,nodeType:A.type,domain:A.domain,layer:Rc(A),isFocal:A.id===n}})),f=t.map((A,O)=>({id:`mini-edge-${O}-${A.source}-${A.target}`,source:A.source,target:A.target,style:{stroke:Ur[A.type]??"#8b949e",strokeWidth:1.4},markerEnd:{type:sr.ArrowClosed,color:Ur[A.type]??"#8b949e",width:10,height:10}}));c(TU(S,f,{mode:i})),u(f)},[e,t,n,i,c,u]),e.length===0?a.jsx("div",{style:{height:r,display:"flex",alignItems:"center",justifyContent:"center",color:"#8b949e",fontSize:11},children:"No lineage nodes to display"}):a.jsx("div",{style:{height:r,width:"100%",borderRadius:8,overflow:"hidden",border:"1px solid #30363d"},children:a.jsx(Af,{nodes:l,edges:d,onNodesChange:s?E:void 0,onEdgesChange:s?T:void 0,onNodeClick:o?(S,f)=>o(f.id):void 0,nodeTypes:RU,fitView:!0,fitViewOptions:{padding:.15},proOptions:{hideAttribution:!0},nodesDraggable:s,nodesConnectable:!1,zoomOnScroll:s,panOnDrag:s,style:{background:"#0d1117"},children:a.jsx(Nf,{color:"#21262d",gap:20,size:1})})})}function AU(e){const t=e.match(/^\s*block\s+"([^"]+)"/i);return t?t[1]:null}function fU(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 IU(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 OU({cellContent:e,cellType:t,cellName:n,themeMode:r,t:o,onFocusNode:s}){const[i,l]=R.useState(!1),[c,E]=R.useState(!1),[d,u]=R.useState([]),[T,S]=R.useState([]),[f,A]=R.useState(),[O,I]=R.useState([]),[p,N]=R.useState({metrics:[],dimensions:[]}),[h,C]=R.useState(null),[m,_]=R.useState(null),g=(t==="dql"?AU(e):null)||n,b=R.useCallback(async()=>{if(!(!g&&t!=="sql")){E(!0),_(null);try{const M=fU(e);if(I(M),N(IU(e)),g){const F=`block:${g}`;A(F);const[L,v]=await Promise.all([Z.queryLineage({focus:F}),Z.fetchLineagePaths(F)]);L!=null&&L.graph&&(u(L.graph.nodes??[]),S(L.graph.edges??[])),v&&C(v)}else{A(void 0);const L=((await Z.fetchLineage()).nodes??[]).filter(v=>M.some(P=>v.name===P||v.id===`table:${P}`));u(L),S([])}}catch{_("Failed to load lineage")}finally{E(!1)}}},[g,e,t]);R.useEffect(()=>{i&&b()},[i,b]);const y=O.length>0||p.metrics.length>0||p.dimensions.length>0;return e.trim()?a.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[a.jsxs("button",{onClick:()=>l(M=>!M),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 12px",background:i?`${o.tableHeaderBg}60`:"transparent",border:"none",cursor:"pointer",color:o.textMuted,fontSize:10,fontFamily:o.font,transition:"background 0.15s"},children:[a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",style:{flexShrink:0},children:[a.jsx("circle",{cx:"4",cy:"4",r:"2"}),a.jsx("circle",{cx:"12",cy:"8",r:"2"}),a.jsx("circle",{cx:"4",cy:"12",r:"2"}),a.jsx("line",{x1:"6",y1:"4",x2:"10",y2:"8"}),a.jsx("line",{x1:"6",y1:"12",x2:"10",y2:"8"})]}),a.jsx("span",{children:"Lineage"}),a.jsx("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:i?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.15s"},children:a.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})}),i&&g&&s&&a.jsx("span",{onClick:M=>{M.stopPropagation(),s(`block:${g}`)},style:{marginLeft:"auto",fontSize:9,color:o.accent,cursor:"pointer",textDecoration:"underline"},children:"View in DAG"})]}),i&&a.jsx("div",{style:{fontSize:11},children:c?a.jsx("div",{style:{color:o.textMuted,padding:"8px 12px"},children:"Loading lineage..."}):m?a.jsx("div",{style:{color:o.error,padding:"8px 12px"},children:m}):a.jsxs(a.Fragment,{children:[d.length>0&&f&&a.jsx("div",{style:{borderBottom:`1px solid ${o.cellBorder}`},children:a.jsx(zf,{nodes:d,edges:T,focalNodeId:f,height:200,onNodeClick:s,interactive:!0,layoutMode:"flow"})}),a.jsxs("div",{style:{padding:"6px 12px 8px"},children:[h&&(h.upstreamPaths.length>0||h.downstreamPaths.length>0)&&a.jsxs("div",{style:{marginBottom:8},children:[a.jsx("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:4},children:"Complete Paths"}),a.jsxs("div",{style:{display:"grid",gap:6},children:[h.upstreamPaths.slice(0,3).map((M,F)=>a.jsx(pl,{path:M,onNodeClick:s,focalNodeId:f,t:o},`up-${F}`)),h.downstreamPaths.slice(0,2).map((M,F)=>a.jsx(pl,{path:M,onNodeClick:s,focalNodeId:f,t:o},`down-${F}`))]})]}),O.length>0&&a.jsxs("div",{style:{marginBottom:6},children:[a.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Reads From (",O.length,")"]}),O.map(M=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[a.jsx("span",{style:{color:we.source_table,fontSize:9,fontWeight:700,width:26},children:"TBL"}),a.jsx("span",{children:M})]},M))]}),p.metrics.length>0&&a.jsxs("div",{style:{marginBottom:6},children:[a.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Metrics (",p.metrics.length,")"]}),p.metrics.map(M=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[a.jsx("span",{style:{color:we.metric,fontSize:9,fontWeight:700,width:26},children:"MET"}),a.jsx("span",{children:M})]},M))]}),p.dimensions.length>0&&a.jsxs("div",{style:{marginBottom:6},children:[a.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Dimensions (",p.dimensions.length,")"]}),p.dimensions.map(M=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[a.jsx("span",{style:{color:we.dimension,fontSize:9,fontWeight:700,width:26},children:"DIM"}),a.jsx("span",{children:M})]},M))]}),!y&&d.length===0&&!h&&a.jsx("div",{style:{color:o.textMuted,padding:"2px 0"},children:"No lineage dependencies detected for this cell."})]})]})})]}):null}const G=e=>e.flatMap(NU),NU=e=>Ns(hU(e)).map(pU),pU=e=>e.replace(/ +/g," ").trim(),hU=e=>({type:"mandatory_block",items:Kc(e,0)[0]}),Kc=(e,t,n)=>{const r=[];for(;e[t];){const[o,s]=CU(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]},CU=(e,t)=>{const n=[];for(;;){const[r,o]=mU(e,t);if(r)n.push(r),t=o;else break}return n.length===1?[n[0],t]:[{type:"concatenation",items:n},t]},mU=(e,t)=>{if(e[t]==="{")return LU(e,t+1);if(e[t]==="[")return _U(e,t+1);{let n="";for(;e[t]&&/[A-Za-z0-9_ ]/.test(e[t]);)n+=e[t],t++;return[n,t]}},LU=(e,t)=>{const[n,r]=Kc(e,t,"}");return[{type:"mandatory_block",items:n},r]},_U=(e,t)=>{const[n,r]=Kc(e,t,"]");return[{type:"optional_block",items:n},r]},Ns=e=>{if(typeof e=="string")return[e];if(e.type==="concatenation")return e.items.map(Ns).reduce(gU,[""]);if(e.type==="mandatory_block")return e.items.flatMap(Ns);if(e.type==="optional_block")return["",...e.items.flatMap(Ns)];throw new Error(`Unknown node type: ${e}`)},gU=(e,t)=>{const n=[];for(const r of e)for(const o of t)n.push(r+o);return n};var j;(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"})(j=j||(j={}));const Jf=e=>({type:j.EOF,raw:"«EOF»",text:"«EOF»",start:e}),nn=Jf(1/0),Fn=e=>t=>t.type===e.type&&t.text===e.text,rn={ARRAY:Fn({text:"ARRAY",type:j.RESERVED_DATA_TYPE}),BY:Fn({text:"BY",type:j.RESERVED_KEYWORD}),SET:Fn({text:"SET",type:j.RESERVED_CLAUSE}),STRUCT:Fn({text:"STRUCT",type:j.RESERVED_DATA_TYPE}),WINDOW:Fn({text:"WINDOW",type:j.RESERVED_CLAUSE}),VALUES:Fn({text:"VALUES",type:j.RESERVED_CLAUSE})},qf=e=>e===j.RESERVED_DATA_TYPE||e===j.RESERVED_KEYWORD||e===j.RESERVED_FUNCTION_NAME||e===j.RESERVED_KEYWORD_PHRASE||e===j.RESERVED_DATA_TYPE_PHRASE||e===j.RESERVED_CLAUSE||e===j.RESERVED_SELECT||e===j.RESERVED_SET_OPERATION||e===j.RESERVED_JOIN||e===j.ARRAY_KEYWORD||e===j.CASE||e===j.END||e===j.WHEN||e===j.ELSE||e===j.THEN||e===j.LIMIT||e===j.BETWEEN||e===j.AND||e===j.OR||e===j.XOR,xU=e=>e===j.AND||e===j.OR||e===j.XOR,yU=["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"],DU=["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"],PU=["ARRAY","BOOL","BYTES","DATE","DATETIME","GEOGRAPHY","INTERVAL","INT64","INT","SMALLINT","INTEGER","BIGINT","TINYINT","BYTEINT","NUMERIC","DECIMAL","BIGNUMERIC","BIGDECIMAL","FLOAT64","STRING","STRUCT","TIME","TIMEZONE"],MU=G(["SELECT [ALL | DISTINCT] [AS STRUCT | AS VALUE]"]),bU=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"]),Nu=G(["CREATE [OR REPLACE] [TEMP|TEMPORARY|SNAPSHOT|EXTERNAL] TABLE [IF NOT EXISTS]"]),va=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"]),vU=G(["UNION {ALL | DISTINCT}","EXCEPT DISTINCT","INTERSECT DISTINCT"]),UU=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),wU=G(["TABLESAMPLE SYSTEM","ANY TYPE","ALL COLUMNS","NOT DETERMINISTIC","{ROWS | RANGE} BETWEEN","IS [NOT] DISTINCT FROM"]),BU=G([]),FU={name:"bigquery",tokenizerOptions:{reservedSelect:MU,reservedClauses:[...bU,...va,...Nu],reservedSetOperations:vU,reservedJoins:UU,reservedKeywordPhrases:wU,reservedDataTypePhrases:BU,reservedKeywords:DU,reservedDataTypes:PU,reservedFunctionNames:yU,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:GU},formatOptions:{onelineClauses:[...Nu,...va],tabularOnelineClauses:va}};function GU(e){return HU(YU(e))}function HU(e){let t=nn;return e.map(n=>n.text==="OFFSET"&&t.text==="["?(t=n,Object.assign(Object.assign({},n),{type:j.RESERVED_FUNCTION_NAME})):(t=n,n))}function YU(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=kU(e,r+1),i=e.slice(r,s+1);n.push({type:j.IDENTIFIER,raw:i.map(pu("raw")).join(""),text:i.map(pu("text")).join(""),start:o.start}),r=s}else n.push(o)}return n}const pu=e=>t=>t.type===j.IDENTIFIER||t.type===j.COMMA?t[e]+" ":t[e];function kU(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 WU=["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"],VU=["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"],jU=["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"],$U=G(["SELECT [DISTINCT]","MODIFY QUERY SELECT [DISTINCT]"]),XU=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]"]),Ua=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"]),KU=G(["UNION [ALL | DISTINCT]","PARALLEL WITH"]),zU=G(["[GLOBAL] [INNER|LEFT|RIGHT|FULL|CROSS] [OUTER|SEMI|ANTI|ANY|ALL|ASOF] JOIN","[LEFT] ARRAY JOIN"]),JU=G(["{ROWS | RANGE} BETWEEN","ALTER MATERIALIZE STATISTICS"]),qU={name:"clickhouse",tokenizerOptions:{reservedSelect:$U,reservedClauses:[...XU,...hu,...Ua],reservedSetOperations:KU,reservedJoins:zU,reservedKeywordPhrases:JU,reservedKeywords:VU,reservedDataTypes:jU,reservedFunctionNames:WU,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:QU},formatOptions:{onelineClauses:[...hu,...Ua],tabularOnelineClauses:Ua}};function QU(e){return e.map((t,n)=>{const r=e[n+1]||nn,o=e[n-1]||nn;return t.type===j.RESERVED_SELECT&&(r.type===j.COMMA||o.type===j.RESERVED_CLAUSE||o.type===j.COMMA)?Object.assign(Object.assign({},t),{type:j.RESERVED_KEYWORD}):rn.SET(t)&&r.type===j.OPEN_PAREN?Object.assign(Object.assign({},t),{type:j.RESERVED_FUNCTION_NAME}):t})}const ZU=["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"],ew=["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"],tw=["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"],nw=G(["SELECT [ALL | DISTINCT]"]),rw=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"]),Cu=G(["CREATE [GLOBAL TEMPORARY | EXTERNAL] TABLE [IF NOT EXISTS]"]),wa=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"]),ow=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),sw=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),iw=G(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),aw=G([]),lw={name:"db2",tokenizerOptions:{reservedSelect:nw,reservedClauses:[...rw,...Cu,...wa],reservedSetOperations:ow,reservedJoins:sw,reservedKeywordPhrases:iw,reservedDataTypePhrases:aw,reservedKeywords:ew,reservedDataTypes:tw,reservedFunctionNames:ZU,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:[...Cu,...wa],tabularOnelineClauses:wa}},cw=["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"],Ew=["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"],dw=["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"],uw=G(["SELECT [ALL | DISTINCT]"]),Tw=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"]),mu=G(["CREATE [OR REPLACE] TABLE"]),Ba=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}"]),Sw=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),Rw=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","[LEFT | RIGHT] EXCEPTION JOIN","{INNER | CROSS} JOIN"]),Aw=G(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),fw=G([]),Iw={name:"db2i",tokenizerOptions:{reservedSelect:uw,reservedClauses:[...Tw,...mu,...Ba],reservedSetOperations:Sw,reservedJoins:Rw,reservedKeywordPhrases:Aw,reservedDataTypePhrases:fw,reservedKeywords:Ew,reservedDataTypes:dw,reservedFunctionNames:cw,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:[...mu,...Ba],tabularOnelineClauses:Ba}},Ow=["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"],Nw=["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"],pw=["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"],hw=G(["SELECT [ALL | DISTINCT]"]),Cw=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"]),Lu=G(["CREATE [OR REPLACE] [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),Fa=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]"]),mw=G(["UNION [ALL | BY NAME]","EXCEPT [ALL]","INTERSECT [ALL]"]),Lw=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"]),_w=G(["{ROWS | RANGE | GROUPS} BETWEEN","SIMILAR TO","IS [NOT] DISTINCT FROM"]),gw=G(["TIMESTAMP WITH TIME ZONE"]),xw={name:"duckdb",tokenizerOptions:{reservedSelect:hw,reservedClauses:[...Cw,...Lu,...Fa],reservedSetOperations:mw,reservedJoins:Lw,reservedKeywordPhrases:_w,reservedDataTypePhrases:gw,supportsXor:!0,reservedKeywords:Nw,reservedDataTypes:pw,reservedFunctionNames:Ow,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:[...Lu,...Fa],tabularOnelineClauses:Fa}},yw=["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"],Dw=["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"],Pw=["ARRAY","BIGINT","BINARY","BOOLEAN","CHAR","DATE","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","INTERVAL","MAP","NUMERIC","PRECISION","SMALLINT","STRUCT","TIMESTAMP","VARCHAR"],Mw=G(["SELECT [ALL | DISTINCT]"]),bw=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"]),_u=G(["CREATE [TEMPORARY] [EXTERNAL] TABLE [IF NOT EXISTS]"]),Ga=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"]),vw=G(["UNION [ALL | DISTINCT]"]),Uw=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","LEFT SEMI JOIN"]),ww=G(["{ROWS | RANGE} BETWEEN"]),Bw=G([]),Fw={name:"hive",tokenizerOptions:{reservedSelect:Mw,reservedClauses:[...bw,..._u,...Ga],reservedSetOperations:vw,reservedJoins:Uw,reservedKeywordPhrases:ww,reservedDataTypePhrases:Bw,reservedKeywords:Dw,reservedDataTypes:Pw,reservedFunctionNames:yw,extraParens:["[]"],stringTypes:['""-bs',"''-bs"],identTypes:["``"],variableTypes:[{quote:"{}",prefixes:["$"],requirePrefix:!0}],operators:["%","~","^","|","&","<=>","==","!","||"]},formatOptions:{onelineClauses:[..._u,...Ga],tabularOnelineClauses:Ga}};function Ui(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:j.RESERVED_FUNCTION_NAME});const o=e[n-1]||nn;return rn.VALUES(t)&&o.text==="="?Object.assign(Object.assign({},t),{type:j.RESERVED_FUNCTION_NAME}):t})}const Gw=["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"],Hw=["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"],Yw=["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"],kw=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),Ww=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"]),gu=G(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),Ha=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"]),Vw=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]","MINUS [ALL | DISTINCT]"]),jw=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),$w=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),Xw=G([]),Kw={name:"mariadb",tokenizerOptions:{reservedSelect:kw,reservedClauses:[...Ww,...gu,...Ha],reservedSetOperations:Vw,reservedJoins:jw,reservedKeywordPhrases:$w,reservedDataTypePhrases:Xw,supportsXor:!0,reservedKeywords:Gw,reservedDataTypes:Hw,reservedFunctionNames:Yw,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:Ui},formatOptions:{onelineClauses:[...gu,...Ha],tabularOnelineClauses:Ha}},zw=["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"],Jw=["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"],qw=["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"],Qw=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),Zw=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]"]),Ya=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"]),eB=G(["UNION [ALL | DISTINCT]"]),tB=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),nB=G(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),rB=G([]),oB={name:"mysql",tokenizerOptions:{reservedSelect:Qw,reservedClauses:[...Zw,...xu,...Ya],reservedSetOperations:eB,reservedJoins:tB,reservedKeywordPhrases:nB,reservedDataTypePhrases:rB,supportsXor:!0,reservedKeywords:zw,reservedDataTypes:Jw,reservedFunctionNames:qw,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:Ui},formatOptions:{onelineClauses:[...xu,...Ya],tabularOnelineClauses:Ya}},sB=["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"],iB=["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"],aB=["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"],lB=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),cB=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"]),yu=G(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),ka=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"]),EB=G(["UNION [ALL | DISTINCT]"]),dB=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),uB=G(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),TB=G([]),SB={name:"tidb",tokenizerOptions:{reservedSelect:lB,reservedClauses:[...cB,...yu,...ka],reservedSetOperations:EB,reservedJoins:dB,reservedKeywordPhrases:uB,reservedDataTypePhrases:TB,supportsXor:!0,reservedKeywords:sB,reservedDataTypes:iB,reservedFunctionNames:aB,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:Ui},formatOptions:{onelineClauses:[...yu,...ka],tabularOnelineClauses:ka}},RB=["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"],AB=["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"],fB=[],IB=G(["SELECT [ALL | DISTINCT]"]),OB=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"]),Du=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"]),NB=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),pB=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","INNER JOIN"]),hB=G(["{ROWS | RANGE | GROUPS} BETWEEN"]),CB=G([]),mB={name:"n1ql",tokenizerOptions:{reservedSelect:IB,reservedClauses:[...OB,...Du],reservedSetOperations:NB,reservedJoins:pB,reservedKeywordPhrases:hB,reservedDataTypePhrases:CB,supportsXor:!0,reservedKeywords:AB,reservedDataTypes:fB,reservedFunctionNames:RB,stringTypes:['""-bs',"''-bs"],identTypes:["``"],extraParens:["[]","{}"],paramTypes:{positional:!0,numbered:["$"],named:["$"]},lineCommentTypes:["#","--"],operators:["%","==",":","||"]},formatOptions:{onelineClauses:Du}},LB=["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"],_B=["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"],gB=["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"],xB=G(["SELECT [ALL | DISTINCT | UNIQUE]"]),yB=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"]),Pu=G(["CREATE [GLOBAL TEMPORARY | PRIVATE TEMPORARY | SHARDED | DUPLICATED | IMMUTABLE BLOCKCHAIN | BLOCKCHAIN | IMMUTABLE] TABLE"]),Wa=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"]),DB=G(["UNION [ALL]","MINUS","INTERSECT"]),PB=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | OUTER} APPLY"]),MB=G(["ON {UPDATE | DELETE} [SET NULL]","ON COMMIT","{ROWS | RANGE} BETWEEN"]),bB=G([]),vB={name:"plsql",tokenizerOptions:{reservedSelect:xB,reservedClauses:[...yB,...Pu,...Wa],reservedSetOperations:DB,reservedJoins:PB,reservedKeywordPhrases:MB,reservedDataTypePhrases:bB,supportsXor:!0,reservedKeywords:LB,reservedDataTypes:_B,reservedFunctionNames:gB,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:UB},formatOptions:{alwaysDenseOperators:["@"],onelineClauses:[...Pu,...Wa],tabularOnelineClauses:Wa}};function UB(e){let t=nn;return e.map(n=>rn.SET(n)&&rn.BY(t)?Object.assign(Object.assign({},n),{type:j.RESERVED_KEYWORD}):(qf(n.type)&&(t=n),n))}const wB=["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"],BB=["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"],FB=["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"],GB=G(["SELECT [ALL | DISTINCT]"]),HB=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"]),Mu=G(["CREATE [GLOBAL | LOCAL] [TEMPORARY | TEMP | UNLOGGED] TABLE [IF NOT EXISTS]"]),Va=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"]),YB=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),kB=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),WB=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"]),VB=G(["[TIMESTAMP | TIME] {WITH | WITHOUT} TIME ZONE"]),jB={name:"postgresql",tokenizerOptions:{reservedSelect:GB,reservedClauses:[...HB,...Mu,...Va],reservedSetOperations:YB,reservedJoins:kB,reservedKeywordPhrases:WB,reservedDataTypePhrases:VB,reservedKeywords:BB,reservedDataTypes:FB,reservedFunctionNames:wB,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:[...Mu,...Va],tabularOnelineClauses:Va}},$B=["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"],XB=["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"],KB=["ARRAY","BIGINT","BPCHAR","CHAR","CHARACTER VARYING","CHARACTER","DECIMAL","INT","INT2","INT4","INT8","INTEGER","NCHAR","NUMERIC","NVARCHAR","SMALLINT","TEXT","VARBYTE","VARCHAR"],zB=G(["SELECT [ALL | DISTINCT]"]),JB=G(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","QUALIFY","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT INTO","VALUES","SET"]),bu=G(["CREATE [TEMPORARY | TEMP | LOCAL TEMPORARY | LOCAL TEMP] TABLE [IF NOT EXISTS]"]),ja=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"]),qB=G(["UNION [ALL]","EXCEPT","INTERSECT","MINUS"]),QB=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),ZB=G(["NULL AS","DATA CATALOG","HIVE METASTORE","{ROWS | RANGE} BETWEEN"]),eF=G([]),tF={name:"redshift",tokenizerOptions:{reservedSelect:zB,reservedClauses:[...JB,...bu,...ja],reservedSetOperations:qB,reservedJoins:QB,reservedKeywordPhrases:ZB,reservedDataTypePhrases:eF,reservedKeywords:XB,reservedDataTypes:KB,reservedFunctionNames:$B,extraParens:["[]"],stringTypes:["''-qq"],identTypes:['""-qq'],identChars:{first:"#"},paramTypes:{numbered:["$"]},operators:["^","%","@","|/","||/","&","|","~","<<",">>","||","::"]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...bu,...ja],tabularOnelineClauses:ja}},nF=["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"],rF=["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"],oF=["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"],sF=G(["SELECT [ALL | DISTINCT]"]),iF=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"]),vu=G(["CREATE [EXTERNAL] TABLE [IF NOT EXISTS]"]),$a=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"]),aF=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),lF=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"]),cF=G(["ON DELETE","ON UPDATE","CURRENT ROW","{ROWS | RANGE} BETWEEN"]),EF=G([]),dF={name:"spark",tokenizerOptions:{reservedSelect:sF,reservedClauses:[...iF,...vu,...$a],reservedSetOperations:aF,reservedJoins:lF,reservedKeywordPhrases:cF,reservedDataTypePhrases:EF,supportsXor:!0,reservedKeywords:nF,reservedDataTypes:rF,reservedFunctionNames:oF,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:uF},formatOptions:{onelineClauses:[...vu,...$a],tabularOnelineClauses:$a}};function uF(e){return e.map((t,n)=>{const r=e[n-1]||nn,o=e[n+1]||nn;return rn.WINDOW(t)&&o.type===j.OPEN_PAREN?Object.assign(Object.assign({},t),{type:j.RESERVED_FUNCTION_NAME}):t.text==="ITEMS"&&t.type===j.RESERVED_KEYWORD&&!(r.text==="COLLECTION"&&o.text==="TERMINATED")?Object.assign(Object.assign({},t),{type:j.IDENTIFIER,text:t.raw}):t})}const TF=["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"],SF=["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"],RF=["ANY","ARRAY","BLOB","CHARACTER","DECIMAL","INT","INTEGER","NATIVE CHARACTER","NCHAR","NUMERIC","NVARCHAR","REAL","TEXT","VARCHAR","VARYING CHARACTER"],AF=G(["SELECT [ALL | DISTINCT]"]),fF=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"]),Uu=G(["CREATE [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),Xa=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"]),IF=G(["UNION [ALL]","EXCEPT","INTERSECT"]),OF=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),NF=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE | GROUPS} BETWEEN","DO UPDATE"]),pF=G([]),hF={name:"sqlite",tokenizerOptions:{reservedSelect:AF,reservedClauses:[...fF,...Uu,...Xa],reservedSetOperations:IF,reservedJoins:OF,reservedKeywordPhrases:NF,reservedDataTypePhrases:pF,reservedKeywords:SF,reservedDataTypes:RF,reservedFunctionNames:TF,stringTypes:["''-qq",{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``","[]"],paramTypes:{positional:!0,numbered:["?"],named:[":","@","$"]},operators:["%","~","&","|","<<",">>","==","->","->>","||"]},formatOptions:{onelineClauses:[...Uu,...Xa],tabularOnelineClauses:Xa}},CF=["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"],mF=["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"],LF=["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"],_F=G(["SELECT [ALL | DISTINCT]"]),gF=G(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY [ALL | DISTINCT]","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","FETCH {FIRST | NEXT}","INSERT INTO","VALUES","SET"]),wu=G(["CREATE [GLOBAL TEMPORARY | LOCAL TEMPORARY] TABLE"]),Ka=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"]),xF=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),yF=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),DF=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),PF=G([]),MF={name:"sql",tokenizerOptions:{reservedSelect:_F,reservedClauses:[...gF,...wu,...Ka],reservedSetOperations:xF,reservedJoins:yF,reservedKeywordPhrases:DF,reservedDataTypePhrases:PF,reservedKeywords:mF,reservedDataTypes:LF,reservedFunctionNames:CF,stringTypes:[{quote:"''-qq-bs",prefixes:["N","U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``"],paramTypes:{positional:!0},operators:["||"]},formatOptions:{onelineClauses:[...wu,...Ka],tabularOnelineClauses:Ka}},bF=["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"],vF=["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"],UF=["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"],wF=G(["SELECT [ALL | DISTINCT]"]),BF=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"]),Bu=G(["CREATE TABLE [IF NOT EXISTS]"]),za=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"]),FF=G(["UNION [ALL | DISTINCT] [CORRESPONDING]","EXCEPT [ALL | DISTINCT] [CORRESPONDING]","INTERSECT [ALL | DISTINCT] [CORRESPONDING]"]),GF=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),HF=G(["{ROWS | RANGE | GROUPS} BETWEEN","IS [NOT] DISTINCT FROM"]),YF=G([]),kF={name:"trino",tokenizerOptions:{reservedSelect:wF,reservedClauses:[...BF,...Bu,...za],reservedSetOperations:FF,reservedJoins:GF,reservedKeywordPhrases:HF,reservedDataTypePhrases:YF,reservedKeywords:vF,reservedDataTypes:UF,reservedFunctionNames:bF,extraParens:["[]","{}"],stringTypes:[{quote:"''-qq",prefixes:["U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq'],paramTypes:{positional:!0},operators:["%","->","=>",":","||","|","^","$"]},formatOptions:{onelineClauses:[...Bu,...za],tabularOnelineClauses:za}},WF=["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"],VF=["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"],jF=["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"],$F=G(["SELECT [ALL | DISTINCT]"]),XF=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"]),Fu=G(["CREATE TABLE"]),Ja=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"]),KF=G(["UNION [ALL]","EXCEPT","INTERSECT"]),zF=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","{CROSS | OUTER} APPLY"]),JF=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),qF=G([]),QF={name:"transactsql",tokenizerOptions:{reservedSelect:$F,reservedClauses:[...XF,...Fu,...Ja],reservedSetOperations:KF,reservedJoins:zF,reservedKeywordPhrases:JF,reservedDataTypePhrases:qF,reservedKeywords:VF,reservedDataTypes:jF,reservedFunctionNames:WF,nestedBlockComments:!0,stringTypes:[{quote:"''-qq",prefixes:["N"]},"{}"],identTypes:['""-qq',"[]"],identChars:{first:"#@",rest:"#@$"},paramTypes:{named:["@"],quoted:["@"]},operators:["%","&","|","^","~","!<","!>","+=","-=","*=","/=","%=","|=","&=","^=","::",":"],propertyAccessOperators:[".."]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...Fu,...Ja],tabularOnelineClauses:Ja}},ZF=["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"],eG=["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"],tG=["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"],nG=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),rG=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"]),Gu=G(["CREATE [ROWSTORE] [REFERENCE | TEMPORARY | GLOBAL TEMPORARY] TABLE [IF NOT EXISTS]"]),qa=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"]),oG=G(["UNION [ALL | DISTINCT]","EXCEPT","INTERSECT","MINUS"]),sG=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),iG=G(["ON DELETE","ON UPDATE","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),aG=G([]),lG={name:"singlestoredb",tokenizerOptions:{reservedSelect:nG,reservedClauses:[...rG,...Gu,...qa],reservedSetOperations:oG,reservedJoins:sG,reservedKeywordPhrases:iG,reservedDataTypePhrases:aG,reservedKeywords:ZF,reservedDataTypes:eG,reservedFunctionNames:tG,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:Ui},formatOptions:{alwaysDenseOperators:["::","::$","::%"],onelineClauses:[...Gu,...qa],tabularOnelineClauses:qa}},cG=["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"],EG=["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"],dG=["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"],uG=G(["SELECT [ALL | DISTINCT]"]),TG=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"]),Hu=G(["CREATE [OR REPLACE] [VOLATILE] TABLE [IF NOT EXISTS]","CREATE [OR REPLACE] [LOCAL | GLOBAL] {TEMP|TEMPORARY} TABLE [IF NOT EXISTS]"]),Qa=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"]),SG=G(["UNION [ALL]","MINUS","EXCEPT","INTERSECT"]),RG=G(["[INNER] JOIN","[NATURAL] {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | NATURAL} JOIN"]),AG=G(["{ROWS | RANGE} BETWEEN","ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]"]),fG=G([]),IG={name:"snowflake",tokenizerOptions:{reservedSelect:uG,reservedClauses:[...TG,...Hu,...Qa],reservedSetOperations:SG,reservedJoins:RG,reservedKeywordPhrases:AG,reservedDataTypePhrases:fG,reservedKeywords:EG,reservedDataTypes:dG,reservedFunctionNames:cG,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:[...Hu,...Qa],tabularOnelineClauses:Qa}},OG=Object.freeze(Object.defineProperty({__proto__:null,bigquery:FU,clickhouse:qU,db2:lw,db2i:Iw,duckdb:xw,hive:Fw,mariadb:Kw,mysql:oB,n1ql:mB,plsql:vB,postgresql:jB,redshift:tF,singlestoredb:lG,snowflake:IG,spark:dF,sql:MF,sqlite:hF,tidb:SB,transactsql:QF,trino:kF},Symbol.toStringTag,{value:"Module"})),Fr=e=>e[e.length-1],Qf=e=>e.sort((t,n)=>n.length-t.length||t.localeCompare(n)),ps=e=>e.replace(/\s+/gu," "),Za=e=>/\n/.test(e),st=e=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),Yu=/\s+/uy,yn=e=>new RegExp(`(?:${e})`,"uy"),NG=e=>e.split("").map(t=>/ /gu.test(t)?"\\s+":`[${t.toUpperCase()}${t.toLowerCase()}]`).join(""),pG=e=>e+"(?:-"+e+")*",hG=({prefixes:e,requirePrefix:t})=>`(?:${e.map(NG).join("|")}${t?"":"|"})`,CG=e=>new RegExp(`(?:${e.map(st).join("|")}).*?(?=\r
|
|
496
|
+
|\r|
|
|
497
|
+
|$)`,"uy"),ku=(e,t=[])=>{const n=e==="open"?0:1,r=["()",...t].map(o=>o[n]);return yn(r.map(st).join("|"))},Wu=e=>yn(`${Qf(e).map(st).join("|")}`),mG=({rest:e,dashes:t})=>e||t?`(?![${e||""}${t?"-":""}])`:"",gt=(e,t={})=>{if(e.length===0)return/^\b$/u;const n=mG(t),r=Qf(e).map(st).join("|").replace(/ /gu,"\\s+");return new RegExp(`(?:${r})${n}\\b`,"iuy")},el=(e,t)=>{if(!e.length)return;const n=e.map(st).join("|");return yn(`(?:${n})(?:${t})`)},LG=()=>{const e={"<":">","[":"]","(":")","{":"}"},t="{left}(?:(?!{right}').)*?{right}",n=Object.entries(e).map(([i,l])=>t.replace(/{left}/g,st(i)).replace(/{right}/g,st(l))),r=st(Object.keys(e).join(""));return`[Qq]'(?:${String.raw`(?<tag>[^\s${r}])(?:(?!\k<tag>').)*?\k<tag>`}|${n.join("|")})'`},Vu={"``":"(?:`[^`]*`)+","[]":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''":LG()},Zf=e=>typeof e=="string"?Vu[e]:"regex"in e?e.regex:hG(e)+Vu[e.quote],_G=e=>yn(e.map(t=>"regex"in t?t.regex:Zf(t)).join("|")),eI=e=>e.map(Zf).join("|"),ju=e=>yn(eI(e)),gG=(e={})=>yn(tI(e)),tI=({first:e,rest:t,dashes:n,allowFirstCharNumber:r}={})=>{const o="\\p{Alphabetic}\\p{Mark}_",s="\\p{Decimal_Number}",i=st(e??""),l=st(t??""),c=r?`[${o}${s}${i}][${o}${s}${l}]*`:`[${o}${i}][${o}${s}${l}]*`;return n?pG(c):c};function nI(e,t){const n=e.slice(0,t).split(/\n/);return{line:n.length,col:n[n.length-1].length+1}}class xG{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}=nI(this.input,this.index);return new Error(`Parse error: Unexpected "${t}" at line ${n} column ${r}.
|
|
498
|
+
${this.dialectInfo()}`)}dialectInfo(){return this.dialectName==="sql"?`This likely happens because you're using the default "sql" dialect.
|
|
499
|
+
If possible, please select a more specific dialect (like sqlite, postgresql, etc).`:`SQL dialect used: "${this.dialectName}".`}getWhitespace(){Yu.lastIndex=this.index;const t=Yu.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 $u=/\/\*/uy,yG=/[\s\S]/uy,DG=/\*\//uy;class PG{constructor(){this.lastIndex=0}exec(t){let n="",r,o=0;if(r=this.matchSection($u,t))n+=r,o++;else return null;for(;o>0;)if(r=this.matchSection($u,t))n+=r,o++;else if(r=this.matchSection(DG,t))n+=r,o--;else if(r=this.matchSection(yG,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 MG{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 xG(r,this.dialectName).tokenize(t);return this.cfg.postProcess?this.cfg.postProcess(o):o}buildRulesBeforeParams(t){var n,r,o;return this.validRules([{type:j.DISABLE_COMMENT,regex:/(\/\* *sql-formatter-disable *\*\/[\s\S]*?(?:\/\* *sql-formatter-enable *\*\/|$))/uy},{type:j.BLOCK_COMMENT,regex:t.nestedBlockComments?new PG:/(\/\*[^]*?\*\/)/uy},{type:j.LINE_COMMENT,regex:CG((n=t.lineCommentTypes)!==null&&n!==void 0?n:["--"])},{type:j.QUOTED_IDENTIFIER,regex:ju(t.identTypes)},{type:j.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:j.RESERVED_KEYWORD_PHRASE,regex:gt((r=t.reservedKeywordPhrases)!==null&&r!==void 0?r:[],t.identChars),text:ge},{type:j.RESERVED_DATA_TYPE_PHRASE,regex:gt((o=t.reservedDataTypePhrases)!==null&&o!==void 0?o:[],t.identChars),text:ge},{type:j.CASE,regex:/CASE\b/iuy,text:ge},{type:j.END,regex:/END\b/iuy,text:ge},{type:j.BETWEEN,regex:/BETWEEN\b/iuy,text:ge},{type:j.LIMIT,regex:t.reservedClauses.includes("LIMIT")?/LIMIT\b/iuy:void 0,text:ge},{type:j.RESERVED_CLAUSE,regex:gt(t.reservedClauses,t.identChars),text:ge},{type:j.RESERVED_SELECT,regex:gt(t.reservedSelect,t.identChars),text:ge},{type:j.RESERVED_SET_OPERATION,regex:gt(t.reservedSetOperations,t.identChars),text:ge},{type:j.WHEN,regex:/WHEN\b/iuy,text:ge},{type:j.ELSE,regex:/ELSE\b/iuy,text:ge},{type:j.THEN,regex:/THEN\b/iuy,text:ge},{type:j.RESERVED_JOIN,regex:gt(t.reservedJoins,t.identChars),text:ge},{type:j.AND,regex:/AND\b/iuy,text:ge},{type:j.OR,regex:/OR\b/iuy,text:ge},{type:j.XOR,regex:t.supportsXor?/XOR\b/iuy:void 0,text:ge},...t.operatorKeyword?[{type:j.OPERATOR,regex:/OPERATOR *\([^)]+\)/iuy}]:[],{type:j.RESERVED_FUNCTION_NAME,regex:gt(t.reservedFunctionNames,t.identChars),text:ge},{type:j.RESERVED_DATA_TYPE,regex:gt(t.reservedDataTypes,t.identChars),text:ge},{type:j.RESERVED_KEYWORD,regex:gt(t.reservedKeywords,t.identChars),text:ge}])}buildRulesAfterParams(t){var n,r;return this.validRules([{type:j.VARIABLE,regex:t.variableTypes?_G(t.variableTypes):void 0},{type:j.STRING,regex:ju(t.stringTypes)},{type:j.IDENTIFIER,regex:gG(t.identChars)},{type:j.DELIMITER,regex:/[;]/uy},{type:j.COMMA,regex:/[,]/y},{type:j.OPEN_PAREN,regex:ku("open",t.extraParens)},{type:j.CLOSE_PAREN,regex:ku("close",t.extraParens)},{type:j.OPERATOR,regex:Wu(["+","-","/",">","<","=","<>","<=",">=","!=",...(n=t.operators)!==null&&n!==void 0?n:[]])},{type:j.ASTERISK,regex:/[*]/uy},{type:j.PROPERTY_ACCESS_OPERATOR,regex:Wu([".",...(r=t.propertyAccessOperators)!==null&&r!==void 0?r:[]])}])}buildParamRules(t,n){var r,o,s,i,l;const c={named:(n==null?void 0:n.named)||((r=t.paramTypes)===null||r===void 0?void 0:r.named)||[],quoted:(n==null?void 0:n.quoted)||((o=t.paramTypes)===null||o===void 0?void 0:o.quoted)||[],numbered:(n==null?void 0:n.numbered)||((s=t.paramTypes)===null||s===void 0?void 0:s.numbered)||[],positional:typeof(n==null?void 0:n.positional)=="boolean"?n.positional:(i=t.paramTypes)===null||i===void 0?void 0:i.positional,custom:(n==null?void 0:n.custom)||((l=t.paramTypes)===null||l===void 0?void 0:l.custom)||[]};return this.validRules([{type:j.NAMED_PARAMETER,regex:el(c.named,tI(t.paramChars||t.identChars)),key:E=>E.slice(1)},{type:j.QUOTED_PARAMETER,regex:el(c.quoted,eI(t.identTypes)),key:E=>(({tokenKey:d,quoteChar:u})=>d.replace(new RegExp(st("\\"+u),"gu"),u))({tokenKey:E.slice(2,-1),quoteChar:E.slice(-1)})},{type:j.NUMBERED_PARAMETER,regex:el(c.numbered,"[0-9]+"),key:E=>E.slice(1)},{type:j.POSITIONAL_PARAMETER,regex:c.positional?/[?]/y:void 0},...c.custom.map(E=>{var d;return{type:j.CUSTOM_PARAMETER,regex:yn(E.regex),key:(d=E.key)!==null&&d!==void 0?d:(u=>u)}})])}validRules(t){return t.filter(n=>!!n.regex)}}const ge=e=>ps(e.toUpperCase()),Xu=new Map,bG=e=>{let t=Xu.get(e);return t||(t=vG(e),Xu.set(e,t)),t},vG=e=>({tokenizer:new MG(e.tokenizerOptions,e.name),formatOptions:UG(e.formatOptions)}),UG=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 wG(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"?" ".repeat(10):e.useTabs?" ":" ".repeat(e.tabWidth)}function Gn(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"}class BG{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 hs={exports:{}},FG=hs.exports,Ku;function GG(){return Ku||(Ku=1,(function(e){(function(t,n){e.exports?e.exports=n():t.nearley=n()})(FG,function(){function t(E,d,u){return this.id=++t.highestId,this.name=E,this.symbols=d,this.postprocess=u,this}t.highestId=0,t.prototype.toString=function(E){var d=typeof E>"u"?this.symbols.map(c).join(" "):this.symbols.slice(0,E).map(c).join(" ")+" ● "+this.symbols.slice(E).map(c).join(" ");return this.name+" → "+d};function n(E,d,u,T){this.rule=E,this.dot=d,this.reference=u,this.data=[],this.wantedBy=T,this.isComplete=this.dot===E.symbols.length}n.prototype.toString=function(){return"{"+this.rule.toString(this.dot)+"}, from: "+(this.reference||0)},n.prototype.nextState=function(E){var d=new n(this.rule,this.dot+1,this.reference,this.wantedBy);return d.left=this,d.right=E,d.isComplete&&(d.data=d.build(),d.right=void 0),d},n.prototype.build=function(){var E=[],d=this;do E.push(d.right.data),d=d.left;while(d.left);return E.reverse(),E},n.prototype.finish=function(){this.rule.postprocess&&(this.data=this.rule.postprocess(this.data,this.reference,i.fail))};function r(E,d){this.grammar=E,this.index=d,this.states=[],this.wants={},this.scannable=[],this.completed={}}r.prototype.process=function(E){for(var d=this.states,u=this.wants,T=this.completed,S=0;S<d.length;S++){var f=d[S];if(f.isComplete){if(f.finish(),f.data!==i.fail){for(var A=f.wantedBy,O=A.length;O--;){var I=A[O];this.complete(I,f)}if(f.reference===this.index){var p=f.rule.name;(this.completed[p]=this.completed[p]||[]).push(f)}}}else{var p=f.rule.symbols[f.dot];if(typeof p!="string"){this.scannable.push(f);continue}if(u[p]){if(u[p].push(f),T.hasOwnProperty(p))for(var N=T[p],O=0;O<N.length;O++){var h=N[O];this.complete(f,h)}}else u[p]=[f],this.predict(p)}}},r.prototype.predict=function(E){for(var d=this.grammar.byName[E]||[],u=0;u<d.length;u++){var T=d[u],S=this.wants[E],f=new n(T,0,this.index,S);this.states.push(f)}},r.prototype.complete=function(E,d){var u=E.nextState(d);this.states.push(u)};function o(E,d){this.rules=E,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(f){return new t(f.name,f.symbols,f.postprocess)}),S=new o(T,d);return S.lexer=u,S};function s(){this.reset("")}s.prototype.reset=function(E,d){this.buffer=E,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 E=this.buffer[this.index++];return E===`
|
|
500
|
+
`&&(this.line+=1,this.lastLineBreak=this.index),{value:E}}},s.prototype.save=function(){return{line:this.line,col:this.index-this.lastLineBreak}},s.prototype.formatError=function(E,d){var u=this.buffer;if(typeof u=="string"){var T=u.split(`
|
|
501
|
+
`).slice(Math.max(0,this.line-5),this.line),S=u.indexOf(`
|
|
502
|
+
`,this.index);S===-1&&(S=u.length);var f=this.index-this.lastLineBreak,A=String(this.line).length;return d+=" at line "+this.line+" col "+f+`:
|
|
503
|
+
|
|
504
|
+
`,d+=T.map(function(I,p){return O(this.line-T.length+p+1,A)+" "+I},this).join(`
|
|
505
|
+
`),d+=`
|
|
506
|
+
`+O("",A+f)+`^
|
|
507
|
+
`,d}else return d+" at index "+(this.index-1);function O(I,p){var N=String(I);return Array(p-N.length+1).join(" ")+N}};function i(E,d,u){if(E instanceof o)var T=E,u=d;else var T=o.fromCompiled(E,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 f=new r(T,0);this.table=[f],f.wants[T.start]=[],f.predict(T.start),f.process(),this.current=0}i.fail={},i.prototype.feed=function(E){var d=this.lexer;d.reset(E,this.lexerState);for(var u;;){try{if(u=d.next(),!u)break}catch(_){var A=new r(this.grammar,this.current+1);this.table.push(A);var T=new Error(this.reportLexerError(_));throw T.offset=this.current,T.token=_.token,T}var S=this.table[this.current];this.options.keepHistory||delete this.table[this.current-1];var f=this.current+1,A=new r(this.grammar,f);this.table.push(A);for(var O=u.text!==void 0?u.text:u.value,I=d.constructor===s?u.value:u,p=S.scannable,N=p.length;N--;){var h=p[N],C=h.rule.symbols[h.dot];if(C.test?C.test(I):C.type?C.type===u.type:C.literal===O){var m=h.nextState({data:I,token:u,isToken:!0,reference:f-1});A.states.push(m)}}if(A.process(),A.states.length===0){var T=new Error(this.reportError(u));throw T.offset=this.current,T.token=u,T}this.options.keepHistory&&(S.lexerState=d.save()),this.current++}return S&&(this.lexerState=d.save()),this.results=this.finish(),this},i.prototype.reportLexerError=function(E){var d,u,T=E.token;return T?(d="input "+JSON.stringify(T.text[0])+" (lexer error)",u=this.lexer.formatError(T,"Syntax error")):(d="input (lexer error)",u=E.message),this.reportErrorCommon(u,d)},i.prototype.reportError=function(E){var d=(E.type?E.type+" token: ":"")+JSON.stringify(E.value!==void 0?E.value:E),u=this.lexer.formatError(E,"Syntax error");return this.reportErrorCommon(u,d)},i.prototype.reportErrorCommon=function(E,d){var u=[];u.push(E);var T=this.table.length-2,S=this.table[T],f=S.states.filter(function(O){var I=O.rule.symbols[O.dot];return I&&typeof I!="string"});if(f.length===0)u.push("Unexpected "+d+`. I did not expect any more input. Here is the state of my parse table:
|
|
508
|
+
`),this.displayStateStack(S.states,u);else{u.push("Unexpected "+d+`. Instead, I was expecting to see one of the following:
|
|
509
|
+
`);var A=f.map(function(O){return this.buildFirstStateStack(O,[])||[O]},this);A.forEach(function(O){var I=O[0],p=I.rule.symbols[I.dot],N=this.getSymbolDisplay(p);u.push("A "+N+" based on:"),this.displayStateStack(O,u)},this)}return u.push(""),u.join(`
|
|
510
|
+
`)},i.prototype.displayStateStack=function(E,d){for(var u,T=0,S=0;S<E.length;S++){var f=E[S],A=f.rule.toString(f.dot);A===u?T++:(T>0&&d.push(" ^ "+T+" more lines identical to this"),T=0,d.push(" "+A)),u=A}},i.prototype.getSymbolDisplay=function(E){return l(E)},i.prototype.buildFirstStateStack=function(E,d){if(d.indexOf(E)!==-1)return null;if(E.wantedBy.length===0)return[E];var u=E.wantedBy[0],T=[E].concat(d),S=this.buildFirstStateStack(u,T);return S===null?null:[E].concat(S)},i.prototype.save=function(){var E=this.table[this.current];return E.lexerState=this.lexerState,E},i.prototype.restore=function(E){var d=E.index;this.current=d,this.table[d]=E,this.table.splice(d+1),this.lexerState=E.lexerState,this.results=this.finish()},i.prototype.rewind=function(E){if(!this.options.keepHistory)throw new Error("set option `keepHistory` to enable rewinding");this.restore(this.table[E])},i.prototype.finish=function(){var E=[],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!==i.fail&&E.push(T)}),E.map(function(T){return T.data})};function l(E){var d=typeof E;if(d==="string")return E;if(d==="object"){if(E.literal)return JSON.stringify(E.literal);if(E instanceof RegExp)return"character matching "+E;if(E.type)return E.type+" token";if(E.test)return"token matching "+String(E.test);throw new Error("Unknown symbol type: "+E)}}function c(E){var d=typeof E;if(d==="string")return E;if(d==="object"){if(E.literal)return JSON.stringify(E.literal);if(E instanceof RegExp)return E.toString();if(E.type)return"%"+E.type;if(E.test)return"<"+String(E.test)+">";throw new Error("Unknown symbol type: "+E)}}return{Parser:i,Grammar:o,Rule:t}})})(hs)),hs.exports}var HG=GG();const YG=ti(HG);function kG(e){return e.map(WG).map(VG).map(jG).map($G).map(XG)}const WG=(e,t,n)=>{if(qf(e.type)){const r=KG(n,t);if(r&&r.type===j.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:j.IDENTIFIER,text:e.raw});const o=fr(n,t);if(o&&o.type===j.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:j.IDENTIFIER,text:e.raw})}return e},VG=(e,t,n)=>{if(e.type===j.RESERVED_FUNCTION_NAME){const r=fr(n,t);if(!r||!rI(r))return Object.assign(Object.assign({},e),{type:j.IDENTIFIER,text:e.raw})}return e},jG=(e,t,n)=>{if(e.type===j.RESERVED_DATA_TYPE){const r=fr(n,t);if(r&&rI(r))return Object.assign(Object.assign({},e),{type:j.RESERVED_PARAMETERIZED_DATA_TYPE})}return e},$G=(e,t,n)=>{if(e.type===j.IDENTIFIER){const r=fr(n,t);if(r&&oI(r))return Object.assign(Object.assign({},e),{type:j.ARRAY_IDENTIFIER})}return e},XG=(e,t,n)=>{if(e.type===j.RESERVED_DATA_TYPE){const r=fr(n,t);if(r&&oI(r))return Object.assign(Object.assign({},e),{type:j.ARRAY_KEYWORD})}return e},KG=(e,t)=>fr(e,t,-1),fr=(e,t,n=1)=>{let r=1;for(;e[t+r*n]&&zG(e[t+r*n]);)r++;return e[t+r*n]},rI=e=>e.type===j.OPEN_PAREN&&e.text==="(",oI=e=>e.type===j.OPEN_PAREN&&e.text==="[",zG=e=>e.type===j.BLOCK_COMMENT||e.type===j.LINE_COMMENT;class sI{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}=nI(this.input,t.start);return`Parse error at token: ${t.text} at line ${n} column ${r}`}has(t){return t in j}}var Q;(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"})(Q=Q||(Q={}));function tl(e){return e[0]}const re=new sI(e=>[]),En=([[e]])=>e,xe=e=>({type:Q.keyword,tokenType:e.type,text:e.text,raw:e.raw}),zu=e=>({type:Q.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),JG=(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},qG={Lexer:re,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:[re.has("DELIMITER")?{type:"DELIMITER"}:DELIMITER]},{name:"statement$subexpression$1",symbols:[re.has("EOF")?{type:"EOF"}:EOF]},{name:"statement",symbols:["expressions_or_clauses","statement$subexpression$1"],postprocess:([e,[t]])=>({type:Q.statement,children:e,hasSemicolon:t.type===j.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:[re.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:tl},{name:"limit_clause$ebnf$1",symbols:[],postprocess:()=>null},{name:"limit_clause",symbols:[re.has("LIMIT")?{type:"LIMIT"}:LIMIT,"_","expression_chain_","limit_clause$ebnf$1"],postprocess:([e,t,n,r])=>{if(r){const[o,s]=r;return{type:Q.limit_clause,limitKw:ye(xe(e),{trailing:t}),offset:n,count:s}}else return{type:Q.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:[re.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT,"select_clause$subexpression$1"],postprocess:([e,[t,n]])=>({type:Q.clause,nameKw:xe(e),children:[t,...n]})},{name:"select_clause",symbols:[re.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT],postprocess:([e])=>({type:Q.clause,nameKw:xe(e),children:[]})},{name:"all_columns_asterisk",symbols:[re.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK],postprocess:()=>({type:Q.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:[re.has("RESERVED_CLAUSE")?{type:"RESERVED_CLAUSE"}:RESERVED_CLAUSE,"other_clause$ebnf$1"],postprocess:([e,t])=>({type:Q.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:[re.has("RESERVED_SET_OPERATION")?{type:"RESERVED_SET_OPERATION"}:RESERVED_SET_OPERATION,"set_operation$ebnf$1"],postprocess:([e,t])=>({type:Q.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:tl},{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:[re.has("ARRAY_IDENTIFIER")?{type:"ARRAY_IDENTIFIER"}:ARRAY_IDENTIFIER,"_","square_brackets"],postprocess:([e,t,n])=>({type:Q.array_subscript,array:ye({type:Q.identifier,quoted:!1,text:e.text},{trailing:t}),parenthesis:n})},{name:"array_subscript",symbols:[re.has("ARRAY_KEYWORD")?{type:"ARRAY_KEYWORD"}:ARRAY_KEYWORD,"_","square_brackets"],postprocess:([e,t,n])=>({type:Q.array_subscript,array:ye(xe(e),{trailing:t}),parenthesis:n})},{name:"function_call",symbols:[re.has("RESERVED_FUNCTION_NAME")?{type:"RESERVED_FUNCTION_NAME"}:RESERVED_FUNCTION_NAME,"_","parenthesis"],postprocess:([e,t,n])=>({type:Q.function_call,nameKw:ye(xe(e),{trailing:t}),parenthesis:n})},{name:"parenthesis",symbols:[{literal:"("},"expressions_or_clauses",{literal:")"}],postprocess:([e,t,n])=>({type:Q.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:Q.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:Q.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","_",re.has("PROPERTY_ACCESS_OPERATOR")?{type:"PROPERTY_ACCESS_OPERATOR"}:PROPERTY_ACCESS_OPERATOR,"_","property_access$subexpression$1"],postprocess:([e,t,n,r,[o]])=>({type:Q.property_access,object:ye(e,{trailing:t}),operator:n.text,property:ye(o,{leading:r})})},{name:"between_predicate",symbols:[re.has("BETWEEN")?{type:"BETWEEN"}:BETWEEN,"_","andless_expression_chain","_",re.has("AND")?{type:"AND"}:AND,"_","andless_expression"],postprocess:([e,t,n,r,o,s,i])=>({type:Q.between_predicate,betweenKw:xe(e),expr1:JG(n,{leading:t,trailing:r}),andKw:xe(o),expr2:[ye(i,{leading:s})]})},{name:"case_expression$ebnf$1",symbols:["expression_chain_"],postprocess:tl},{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:[re.has("CASE")?{type:"CASE"}:CASE,"_","case_expression$ebnf$1","case_expression$ebnf$2",re.has("END")?{type:"END"}:END],postprocess:([e,t,n,r,o])=>({type:Q.case_expression,caseKw:ye(xe(e),{trailing:t}),endKw:xe(o),expr:n||[],clauses:r})},{name:"case_clause",symbols:[re.has("WHEN")?{type:"WHEN"}:WHEN,"_","expression_chain_",re.has("THEN")?{type:"THEN"}:THEN,"_","expression_chain_"],postprocess:([e,t,n,r,o,s])=>({type:Q.case_when,whenKw:ye(xe(e),{trailing:t}),thenKw:ye(xe(r),{trailing:o}),condition:n,result:s})},{name:"case_clause",symbols:[re.has("ELSE")?{type:"ELSE"}:ELSE,"_","expression_chain_"],postprocess:([e,t,n])=>({type:Q.case_else,elseKw:ye(xe(e),{trailing:t}),result:n})},{name:"comma$subexpression$1",symbols:[re.has("COMMA")?{type:"COMMA"}:COMMA]},{name:"comma",symbols:["comma$subexpression$1"],postprocess:([[e]])=>({type:Q.comma})},{name:"asterisk$subexpression$1",symbols:[re.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK]},{name:"asterisk",symbols:["asterisk$subexpression$1"],postprocess:([[e]])=>({type:Q.operator,text:e.text})},{name:"operator$subexpression$1",symbols:[re.has("OPERATOR")?{type:"OPERATOR"}:OPERATOR]},{name:"operator",symbols:["operator$subexpression$1"],postprocess:([[e]])=>({type:Q.operator,text:e.text})},{name:"identifier$subexpression$1",symbols:[re.has("IDENTIFIER")?{type:"IDENTIFIER"}:IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[re.has("QUOTED_IDENTIFIER")?{type:"QUOTED_IDENTIFIER"}:QUOTED_IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[re.has("VARIABLE")?{type:"VARIABLE"}:VARIABLE]},{name:"identifier",symbols:["identifier$subexpression$1"],postprocess:([[e]])=>({type:Q.identifier,quoted:e.type!=="IDENTIFIER",text:e.text})},{name:"parameter$subexpression$1",symbols:[re.has("NAMED_PARAMETER")?{type:"NAMED_PARAMETER"}:NAMED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[re.has("QUOTED_PARAMETER")?{type:"QUOTED_PARAMETER"}:QUOTED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[re.has("NUMBERED_PARAMETER")?{type:"NUMBERED_PARAMETER"}:NUMBERED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[re.has("POSITIONAL_PARAMETER")?{type:"POSITIONAL_PARAMETER"}:POSITIONAL_PARAMETER]},{name:"parameter$subexpression$1",symbols:[re.has("CUSTOM_PARAMETER")?{type:"CUSTOM_PARAMETER"}:CUSTOM_PARAMETER]},{name:"parameter",symbols:["parameter$subexpression$1"],postprocess:([[e]])=>({type:Q.parameter,key:e.key,text:e.text})},{name:"literal$subexpression$1",symbols:[re.has("NUMBER")?{type:"NUMBER"}:NUMBER]},{name:"literal$subexpression$1",symbols:[re.has("STRING")?{type:"STRING"}:STRING]},{name:"literal",symbols:["literal$subexpression$1"],postprocess:([[e]])=>({type:Q.literal,text:e.text})},{name:"keyword$subexpression$1",symbols:[re.has("RESERVED_KEYWORD")?{type:"RESERVED_KEYWORD"}:RESERVED_KEYWORD]},{name:"keyword$subexpression$1",symbols:[re.has("RESERVED_KEYWORD_PHRASE")?{type:"RESERVED_KEYWORD_PHRASE"}:RESERVED_KEYWORD_PHRASE]},{name:"keyword$subexpression$1",symbols:[re.has("RESERVED_JOIN")?{type:"RESERVED_JOIN"}:RESERVED_JOIN]},{name:"keyword",symbols:["keyword$subexpression$1"],postprocess:([[e]])=>xe(e)},{name:"data_type$subexpression$1",symbols:[re.has("RESERVED_DATA_TYPE")?{type:"RESERVED_DATA_TYPE"}:RESERVED_DATA_TYPE]},{name:"data_type$subexpression$1",symbols:[re.has("RESERVED_DATA_TYPE_PHRASE")?{type:"RESERVED_DATA_TYPE_PHRASE"}:RESERVED_DATA_TYPE_PHRASE]},{name:"data_type",symbols:["data_type$subexpression$1"],postprocess:([[e]])=>zu(e)},{name:"data_type",symbols:[re.has("RESERVED_PARAMETERIZED_DATA_TYPE")?{type:"RESERVED_PARAMETERIZED_DATA_TYPE"}:RESERVED_PARAMETERIZED_DATA_TYPE,"_","parenthesis"],postprocess:([e,t,n])=>({type:Q.parameterized_data_type,dataType:ye(zu(e),{trailing:t}),parenthesis:n})},{name:"logic_operator$subexpression$1",symbols:[re.has("AND")?{type:"AND"}:AND]},{name:"logic_operator$subexpression$1",symbols:[re.has("OR")?{type:"OR"}:OR]},{name:"logic_operator$subexpression$1",symbols:[re.has("XOR")?{type:"XOR"}:XOR]},{name:"logic_operator",symbols:["logic_operator$subexpression$1"],postprocess:([[e]])=>xe(e)},{name:"other_keyword$subexpression$1",symbols:[re.has("WHEN")?{type:"WHEN"}:WHEN]},{name:"other_keyword$subexpression$1",symbols:[re.has("THEN")?{type:"THEN"}:THEN]},{name:"other_keyword$subexpression$1",symbols:[re.has("ELSE")?{type:"ELSE"}:ELSE]},{name:"other_keyword$subexpression$1",symbols:[re.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:[re.has("LINE_COMMENT")?{type:"LINE_COMMENT"}:LINE_COMMENT],postprocess:([e])=>({type:Q.line_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[re.has("BLOCK_COMMENT")?{type:"BLOCK_COMMENT"}:BLOCK_COMMENT],postprocess:([e])=>({type:Q.block_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[re.has("DISABLE_COMMENT")?{type:"DISABLE_COMMENT"}:DISABLE_COMMENT],postprocess:([e])=>({type:Q.disable_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})}],ParserStart:"main"},{Parser:QG,Grammar:ZG}=YG;function eH(e){let t={};const n=new sI(o=>[...kG(e.tokenize(o,t)),Jf(o.length)]),r=new QG(ZG.fromCompiled(qG),{lexer:n});return{parse:(o,s)=>{t=s;const{results:i}=r.feed(o);if(i.length===1)return i[0];throw i.length===0?new Error("Parse error: Invalid SQL"):new Error(`Parse error: Ambiguous grammar
|
|
511
|
+
${JSON.stringify(i,void 0,2)}`)}}}var V;(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"})(V=V||(V={}));class iI{constructor(t){this.indentation=t,this.items=[]}add(...t){for(const n of t)switch(n){case V.SPACE:this.items.push(V.SPACE);break;case V.NO_SPACE:this.trimHorizontalWhitespace();break;case V.NO_NEWLINE:this.trimWhitespace();break;case V.NEWLINE:this.trimHorizontalWhitespace(),this.addNewline(V.NEWLINE);break;case V.MANDATORY_NEWLINE:this.trimHorizontalWhitespace(),this.addNewline(V.MANDATORY_NEWLINE);break;case V.INDENT:this.addIndentation();break;case V.SINGLE_INDENT:this.items.push(V.SINGLE_INDENT);break;default:this.items.push(n)}}trimHorizontalWhitespace(){for(;tH(Fr(this.items));)this.items.pop()}trimWhitespace(){for(;nH(Fr(this.items));)this.items.pop()}addNewline(t){if(this.items.length>0)switch(Fr(this.items)){case V.NEWLINE:this.items.pop(),this.items.push(t);break;case V.MANDATORY_NEWLINE:break;default:this.items.push(t);break}}addIndentation(){for(let t=0;t<this.indentation.getLevel();t++)this.items.push(V.SINGLE_INDENT)}toString(){return this.items.map(t=>this.itemToString(t)).join("")}getLayoutItems(){return this.items}itemToString(t){switch(t){case V.SPACE:return" ";case V.NEWLINE:case V.MANDATORY_NEWLINE:return`
|
|
512
|
+
`;case V.SINGLE_INDENT:return this.indentation.getSingleIndent();default:return t}}}const tH=e=>e===V.SPACE||e===V.SINGLE_INDENT,nH=e=>e===V.SPACE||e===V.SINGLE_INDENT||e===V.NEWLINE;function Ju(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 qu(e){return xU(e)||e===j.RESERVED_CLAUSE||e===j.RESERVED_SELECT||e===j.RESERVED_SET_OPERATION||e===j.RESERVED_JOIN||e===j.LIMIT}const nl="top-level",rH="block-level";class aI{constructor(t){this.indent=t,this.indentTypes=[]}getSingleIndent(){return this.indent}getLevel(){return this.indentTypes.length}increaseTopLevel(){this.indentTypes.push(nl)}increaseBlockLevel(){this.indentTypes.push(rH)}decreaseTopLevel(){this.indentTypes.length>0&&Fr(this.indentTypes)===nl&&this.indentTypes.pop()}decreaseBlockLevel(){for(;this.indentTypes.length>0&&this.indentTypes.pop()===nl;);}}class oH extends iI{constructor(t){super(new aI("")),this.expressionWidth=t,this.length=0,this.trailingSpace=!1}add(...t){if(t.forEach(n=>this.addToLength(n)),this.length>this.expressionWidth)throw new Bl;super.add(...t)}addToLength(t){if(typeof t=="string")this.length+=t.length,this.trailingSpace=!1;else{if(t===V.MANDATORY_NEWLINE||t===V.NEWLINE)throw new Bl;t===V.INDENT||t===V.SINGLE_INDENT||t===V.SPACE?this.trailingSpace||(this.length++,this.trailingSpace=!0):(t===V.NO_NEWLINE||t===V.NO_SPACE)&&this.trailingSpace&&(this.trailingSpace=!1,this.length--)}}}class Bl extends Error{}class Zs{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 Q.function_call:return this.formatFunctionCall(t);case Q.parameterized_data_type:return this.formatParameterizedDataType(t);case Q.array_subscript:return this.formatArraySubscript(t);case Q.property_access:return this.formatPropertyAccess(t);case Q.parenthesis:return this.formatParenthesis(t);case Q.between_predicate:return this.formatBetweenPredicate(t);case Q.case_expression:return this.formatCaseExpression(t);case Q.case_when:return this.formatCaseWhen(t);case Q.case_else:return this.formatCaseElse(t);case Q.clause:return this.formatClause(t);case Q.set_operation:return this.formatSetOperation(t);case Q.limit_clause:return this.formatLimitClause(t);case Q.all_columns_asterisk:return this.formatAllColumnsAsterisk(t);case Q.literal:return this.formatLiteral(t);case Q.identifier:return this.formatIdentifier(t);case Q.parameter:return this.formatParameter(t);case Q.operator:return this.formatOperator(t);case Q.comma:return this.formatComma(t);case Q.line_comment:return this.formatLineComment(t);case Q.block_comment:return this.formatBlockComment(t);case Q.disable_comment:return this.formatBlockComment(t);case Q.data_type:return this.formatDataType(t);case Q.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 Q.data_type:n=this.showDataType(t.array);break;case Q.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(V.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(V.NO_SPACE,t.closeParen,V.SPACE)):(this.layout.add(t.openParen,V.NEWLINE),Gn(this.cfg)?(this.layout.add(V.INDENT),this.layout=this.formatSubExpression(t.children)):(this.layout.indentation.increaseBlockLevel(),this.layout.add(V.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseBlockLevel()),this.layout.add(V.NEWLINE,V.INDENT,t.closeParen,V.SPACE))}formatBetweenPredicate(t){this.layout.add(this.showKw(t.betweenKw),V.SPACE),this.layout=this.formatSubExpression(t.expr1),this.layout.add(V.NO_SPACE,V.SPACE,this.showNonTabularKw(t.andKw),V.SPACE),this.layout=this.formatSubExpression(t.expr2),this.layout.add(V.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(V.NEWLINE,V.INDENT),this.formatNode(t.endKw)}formatCaseWhen(t){this.layout.add(V.NEWLINE,V.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(V.NEWLINE,V.INDENT),this.formatNode(t.elseKw),this.layout=this.formatSubExpression(t.result)}formatClause(t){this.isOnelineClause(t)?this.formatClauseInOnelineStyle(t):Gn(this.cfg)?this.formatClauseInTabularStyle(t):this.formatClauseInIndentedStyle(t)}isOnelineClause(t){return Gn(this.cfg)?this.dialectCfg.tabularOnelineClauses[t.nameKw.text]:this.dialectCfg.onelineClauses[t.nameKw.text]}formatClauseInIndentedStyle(t){this.layout.add(V.NEWLINE,V.INDENT,this.showKw(t.nameKw),V.NEWLINE),this.layout.indentation.increaseTopLevel(),this.layout.add(V.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatClauseInOnelineStyle(t){this.layout.add(V.NEWLINE,V.INDENT,this.showKw(t.nameKw),V.SPACE),this.layout=this.formatSubExpression(t.children)}formatClauseInTabularStyle(t){this.layout.add(V.NEWLINE,V.INDENT,this.showKw(t.nameKw),V.SPACE),this.layout.indentation.increaseTopLevel(),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatSetOperation(t){this.layout.add(V.NEWLINE,V.INDENT,this.showKw(t.nameKw),V.NEWLINE),this.layout.add(V.INDENT),this.layout=this.formatSubExpression(t.children)}formatLimitClause(t){this.withComments(t.limitKw,()=>{this.layout.add(V.NEWLINE,V.INDENT,this.showKw(t.limitKw))}),this.layout.indentation.increaseTopLevel(),Gn(this.cfg)?this.layout.add(V.SPACE):this.layout.add(V.NEWLINE,V.INDENT),t.offset?(this.layout=this.formatSubExpression(t.offset),this.layout.add(V.NO_SPACE,",",V.SPACE),this.layout=this.formatSubExpression(t.count)):this.layout=this.formatSubExpression(t.count),this.layout.indentation.decreaseTopLevel()}formatAllColumnsAsterisk(t){this.layout.add("*",V.SPACE)}formatLiteral(t){this.layout.add(t.text,V.SPACE)}formatIdentifier(t){this.layout.add(this.showIdentifier(t),V.SPACE)}formatParameter(t){this.layout.add(this.params.get(t),V.SPACE)}formatOperator({text:t}){this.cfg.denseOperators||this.dialectCfg.alwaysDenseOperators.includes(t)?this.layout.add(V.NO_SPACE,t):t===":"?this.layout.add(V.NO_SPACE,t,V.SPACE):this.layout.add(t,V.SPACE)}formatComma(t){this.inline?this.layout.add(V.NO_SPACE,",",V.SPACE):this.layout.add(V.NO_SPACE,",",V.NEWLINE,V.INDENT)}withComments(t,n){this.formatComments(t.leadingComments),n(),this.formatComments(t.trailingComments)}formatComments(t){t&&t.forEach(n=>{n.type===Q.line_comment?this.formatLineComment(n):this.formatBlockComment(n)})}formatLineComment(t){Za(t.precedingWhitespace||"")?this.layout.add(V.NEWLINE,V.INDENT,t.text,V.MANDATORY_NEWLINE,V.INDENT):this.layout.getLayoutItems().length>0?this.layout.add(V.NO_NEWLINE,V.SPACE,t.text,V.MANDATORY_NEWLINE,V.INDENT):this.layout.add(t.text,V.MANDATORY_NEWLINE,V.INDENT)}formatBlockComment(t){t.type===Q.block_comment&&this.isMultilineBlockComment(t)?(this.splitBlockComment(t.text).forEach(n=>{this.layout.add(V.NEWLINE,V.INDENT,n)}),this.layout.add(V.NEWLINE,V.INDENT)):this.layout.add(t.text,V.SPACE)}isMultilineBlockComment(t){return Za(t.text)||Za(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(Fr(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 Zs({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 Zs({cfg:this.cfg,dialectCfg:this.dialectCfg,params:this.params,layout:new oH(this.cfg.expressionWidth),inline:!0}).format(t)}catch(r){if(r instanceof Bl){this.params.setPositionalParameterIndex(n);return}else throw r}}formatKeywordNode(t){switch(t.tokenType){case j.RESERVED_JOIN:return this.formatJoin(t);case j.AND:case j.OR:case j.XOR:return this.formatLogicalOperator(t);default:return this.formatKeyword(t)}}formatJoin(t){Gn(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add(V.NEWLINE,V.INDENT,this.showKw(t),V.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add(V.NEWLINE,V.INDENT,this.showKw(t),V.SPACE)}formatKeyword(t){this.layout.add(this.showKw(t),V.SPACE)}formatLogicalOperator(t){this.cfg.logicalOperatorNewline==="before"?Gn(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add(V.NEWLINE,V.INDENT,this.showKw(t),V.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add(V.NEWLINE,V.INDENT,this.showKw(t),V.SPACE):this.layout.add(this.showKw(t),V.NEWLINE,V.INDENT)}formatDataType(t){this.layout.add(this.showDataType(t),V.SPACE)}showKw(t){return qu(t.tokenType)?Ju(this.showNonTabularKw(t),this.cfg.indentStyle):this.showNonTabularKw(t)}showNonTabularKw(t){switch(this.cfg.keywordCase){case"preserve":return ps(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}showFunctionKw(t){return qu(t.tokenType)?Ju(this.showNonTabularFunctionKw(t),this.cfg.indentStyle):this.showNonTabularFunctionKw(t)}showNonTabularFunctionKw(t){switch(this.cfg.functionCase){case"preserve":return ps(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 ps(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}}class sH{constructor(t,n){this.dialect=t,this.cfg=n,this.params=new BG(this.cfg.params)}format(t){const n=this.parse(t);return this.formatAst(n).trimEnd()}parse(t){return eH(this.dialect.tokenizer).parse(t,this.cfg.paramTypes||{})}formatAst(t){return t.map(n=>this.formatStatement(n)).join(`
|
|
513
|
+
`.repeat(this.cfg.linesBetweenQueries+1))}formatStatement(t){const n=new Zs({cfg:this.cfg,dialectCfg:this.dialect.formatOptions,params:this.params,layout:new iI(new aI(wG(this.cfg)))}).format(t.children);return t.hasSemicolon&&(this.cfg.newlineBeforeSemicolon?n.add(V.NEWLINE,";"):n.add(V.NO_NEWLINE,";")),n.toString()}}class Cs extends Error{}function iH(e){const t=["multilineLists","newlineBeforeOpenParen","newlineBeforeCloseParen","aliasAs","commaPosition","tabulateAlias"];for(const n of t)if(n in e)throw new Cs(`${n} config is no more supported.`);if(e.expressionWidth<=0)throw new Cs(`expressionWidth config must be positive number. Received ${e.expressionWidth} instead.`);if(e.params&&!aH(e.params)&&console.warn('WARNING: All "params" option values should be strings.'),e.paramTypes&&!lH(e.paramTypes))throw new Cs("Empty regex given in custom paramTypes. That would result in matching infinite amount of parameters.");return e}function aH(e){return(e instanceof Array?e:Object.values(e)).every(n=>typeof n=="string")}function lH(e){return e.custom&&Array.isArray(e.custom)?e.custom.every(t=>t.regex!==""):!0}var cH=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 lI={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"},EH=Object.keys(lI),dH={tabWidth:2,useTabs:!1,keywordCase:"preserve",identifierCase:"preserve",dataTypeCase:"preserve",functionCase:"preserve",indentStyle:"standard",logicalOperatorNewline:"before",expressionWidth:50,linesBetweenQueries:1,denseOperators:!1,newlineBeforeSemicolon:!1},uH=(e,t={})=>{if(typeof t.language=="string"&&!EH.includes(t.language))throw new Cs(`Unsupported SQL dialect: ${t.language}`);const n=lI[t.language||"sql"];return TH(e,Object.assign(Object.assign({},t),{dialect:OG[n]}))},TH=(e,t)=>{var{dialect:n}=t,r=cH(t,["dialect"]);if(typeof e!="string")throw new Error("Invalid query argument. Expected string, instead got "+typeof e);const o=iH(Object.assign(Object.assign({},dH),r));return new sH(bG(n),o).format(e)},SH={sql:"SQL",markdown:"MD",dql:"DQL",param:"PARAM"},rl={sql:"#388bfd",markdown:"#56d364",dql:"#e3b341",param:"#e3b341"};function RH(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 AH({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 i=e.result.executionTime;o=i<1e3?`${i}ms`:`${(i/1e3).toFixed(1)}s`}}else n="[ ]",r=t.textMuted;return a.jsxs("div",{style:{width:40,display:"flex",flexDirection:"column",alignItems:"center",paddingTop:12,flexShrink:0,gap:2},children:[a.jsx("span",{style:{fontFamily:t.fontMono,fontSize:11,color:r,lineHeight:1.4,userSelect:"none",transition:"color 0.2s"},children:e.status==="running"?a.jsxs("span",{style:{display:"inline-block",animation:"spin 0.8s linear infinite"},children:[a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:a.jsx("circle",{cx:"6",cy:"6",r:"4.5",stroke:r,strokeWidth:"1.5",strokeDasharray:"14 7"})}),a.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}):n}),o&&a.jsx("span",{style:{fontFamily:t.fontMono,fontSize:8,color:t.textMuted,lineHeight:1,userSelect:"none"},children:o})]})}function fH(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 ol(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 IH(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 OH({content:e,onChange:t,t:n}){const r=fH(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},i={display:"flex",alignItems:"center",gap:4};return a.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px",padding:"5px 10px",borderBottom:`1px solid ${n.cellBorder}`,background:`${n.tableHeaderBg}40`},children:[a.jsxs("div",{style:i,children:[a.jsx("span",{style:s,children:"domain"}),a.jsx("input",{style:{...o,width:80},value:r.domain,placeholder:"e.g. finance",onChange:l=>t(ol(e,"domain",l.target.value))})]}),a.jsxs("div",{style:i,children:[a.jsx("span",{style:s,children:"owner"}),a.jsx("input",{style:{...o,width:90},value:r.owner,placeholder:"e.g. data-team",onChange:l=>t(ol(e,"owner",l.target.value))})]}),a.jsxs("div",{style:i,children:[a.jsx("span",{style:s,children:"tags"}),a.jsx("input",{style:{...o,width:110},value:r.tags.join(", "),placeholder:"revenue, kpi",onChange:l=>{const c=l.target.value.split(",").map(E=>E.trim()).filter(Boolean);t(IH(e,c))}})]}),a.jsxs("div",{style:{...i,flex:1},children:[a.jsx("span",{style:s,children:"description"}),a.jsx("input",{style:{...o,flex:1,minWidth:120},value:r.description,placeholder:"What this block measures",onChange:l=>t(ol(e,"description",l.target.value))})]})]})}function NH({cell:e,index:t}){var z;const{state:n,dispatch:r}=Te(),o=ce[n.themeMode],{executeCell:s,executeDependents:i,cancelCell:l}=Oi(),[c,E]=R.useState(!1),[d,u]=R.useState(!1),[T,S]=R.useState(e.name??""),[f,A]=R.useState(!0),[O,I]=R.useState("table"),[p,N]=R.useState(null),[h,C]=R.useState(!1),[m,_]=R.useState(!1),[D,g]=R.useState(!1),b=RH(e,o),y=e.type!=="markdown"&&e.type!=="param",M=R.useRef(null),F=R.useRef(e.content),[L,v]=R.useState(!1),P=R.useMemo(()=>n.schemaTables.length>0?Object.fromEntries(n.schemaTables.map(Y=>[Y.name,Y.columns.map(K=>K.name)])):void 0,[n.schemaTables]);if(e.type==="param")return a.jsxs("div",{onMouseEnter:()=>E(!0),onMouseLeave:()=>E(!1),style:{display:"flex",gap:0,marginBottom:2},children:[a.jsx("div",{style:{width:40,flexShrink:0}}),a.jsx("div",{style:{flex:1,minWidth:0},children:a.jsx(lg,{cell:e,themeMode:n.themeMode,onApplyParam:i})})]});R.useEffect(()=>{if(e.status==="success"&&e.result){const Y=Xr(e.result,e.chartConfig);N(Y!=="table"?Y:null),I(Y!=="table"?"chart":"table")}},[e.status,e.result,e.chartConfig]);const w=R.useCallback(()=>{y&&s(e.id)},[e.id,s,y]),U=R.useCallback(Y=>{r({type:"UPDATE_CELL",id:e.id,updates:{content:Y}}),v(Y!==F.current)},[e.id,r]),x=R.useCallback(()=>{var K;const Y=F.current;r({type:"UPDATE_CELL",id:e.id,updates:{content:Y}}),(K=M.current)==null||K.resetTo(Y),v(!1)},[e.id,r]),B=R.useCallback(()=>{if(e.content.trim())try{const Y=uH(e.content,{language:"sql",tabWidth:2,keywordCase:"upper",linesBetweenQueries:1});r({type:"UPDATE_CELL",id:e.id,updates:{content:Y}})}catch{}},[e.content,e.id,r]),H=R.useCallback(()=>{B(),setTimeout(()=>s(e.id),80)},[B,s,e.id]),W=()=>{r({type:"DELETE_CELL",id:e.id})},$=()=>{r({type:"MOVE_CELL",id:e.id,direction:"up"})},X=()=>{r({type:"MOVE_CELL",id:e.id,direction:"down"})},J=()=>{u(!1),r({type:"UPDATE_CELL",id:e.id,updates:{name:T.trim()||void 0}})},q=(e.result||e.error)&&e.type!=="markdown";return e.result&&Xr(e.result,e.chartConfig),a.jsxs("div",{onMouseEnter:()=>E(!0),onMouseLeave:()=>E(!1),style:{display:"flex",gap:0,marginBottom:2},children:[D&&a.jsx(ug,{cell:e,onClose:()=>g(!1),onSaved:({path:Y,name:K})=>{r({type:"FILE_ADDED",file:{name:K,path:Y,type:"block",folder:"blocks"}})}}),a.jsx(AH,{cell:e,t:o}),a.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${c||e.status!=="idle"?b:o.cellBorder}`,borderLeft:`2px solid ${b}`,background:o.cellBg,overflow:"hidden",transition:"border-color 0.2s"},children:[a.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:[a.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:rl[e.type]??o.accent,background:`${rl[e.type]??o.accent}18`,border:`1px solid ${rl[e.type]??o.accent}40`,borderRadius:4,padding:"1px 6px",flexShrink:0,textTransform:"uppercase"},children:SH[e.type]}),c&&(e.type==="sql"||e.type==="dql")&&a.jsx(Eg,{themeMode:n.themeMode,cellType:e.type,onInsert:Y=>U(Y)}),c&&(e.type==="sql"||e.type==="dql")&&a.jsx("button",{title:"Format SQL (clean up whitespace & keywords)",onClick:B,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:Y=>{Y.currentTarget.style.color=o.textSecondary,Y.currentTarget.style.borderColor=o.accent},onMouseLeave:Y=>{Y.currentTarget.style.color=o.textMuted,Y.currentTarget.style.borderColor=o.btnBorder},children:"Format"}),L&&(e.type==="sql"||e.type==="dql")&&a.jsx("button",{title:"Reset to last saved version (discard changes)",onClick:x,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:Y=>{Y.currentTarget.style.borderColor="#f85149"},onMouseLeave:Y=>{Y.currentTarget.style.borderColor=o.btnBorder},children:"↺ Reset"}),c&&(e.type==="sql"||e.type==="dql")&&a.jsx("button",{title:"Save this cell as a reusable block",onClick:()=>g(!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:Y=>{Y.currentTarget.style.color=o.textSecondary,Y.currentTarget.style.borderColor=o.accent},onMouseLeave:Y=>{Y.currentTarget.style.color=o.textMuted,Y.currentTarget.style.borderColor=o.btnBorder},children:"Save as Block"}),d?a.jsx("input",{autoFocus:!0,value:T,onChange:Y=>S(Y.target.value),onBlur:J,onKeyDown:Y=>{Y.key==="Enter"&&J(),Y.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&&a.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}),a.jsx("div",{style:{flex:1}}),c&&a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[!e.name&&!d&&a.jsx(Hn,{title:"Name this cell",onClick:()=>{S(""),u(!0)},t:o,children:a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:a.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"})})}),y&&e.status==="running"?a.jsx(Hn,{title:"Cancel execution",onClick:()=>l(e.id),t:o,danger:!0,children:a.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:a.jsx("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1"})})}):y?a.jsx(Hn,{title:"Run cell (Shift+Enter)",onClick:w,t:o,accent:!0,children:a.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:a.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})})}):null,a.jsx(Hn,{title:"Move up",onClick:$,t:o,children:a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:a.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"})})}),a.jsx(Hn,{title:"Move down",onClick:X,t:o,children:a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:a.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"})})}),a.jsx(Hn,{title:"Delete cell",onClick:W,t:o,danger:!0,children:a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:a.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"&&a.jsx(OH,{content:e.content,onChange:U,t:o}),e.type==="markdown"?a.jsx(ag,{value:e.content,onChange:U,themeMode:n.themeMode}):a.jsx(pc,{value:e.content,onChange:U,onRun:w,themeMode:n.themeMode,schema:P,errorMessage:e.status==="error"?e.error:void 0,editorRef:M}),q&&a.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[a.jsxs("div",{style:{height:28,display:"flex",alignItems:"center",padding:"0 12px",gap:10,borderBottom:e.result&&f?`1px solid ${o.cellBorder}`:"none",background:`${o.tableHeaderBg}60`},children:[e.result&&a.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&&a.jsxs(a.Fragment,{children:[" · ",e.result.executionTime<1e3?`${e.result.executionTime}ms`:`${(e.result.executionTime/1e3).toFixed(2)}s`]})]}),e.error&&a.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.error},children:"Error"}),a.jsx("div",{style:{flex:1}}),e.result&&f&&a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:3,position:"relative"},children:[a.jsx("button",{onClick:()=>{I("table"),C(!1)},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${O==="table"?o.accent:o.btnBorder}`,background:O==="table"?`${o.accent}20`:"transparent",color:O==="table"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s"},children:"Table"}),a.jsxs("div",{style:{position:"relative"},children:[a.jsxs("button",{onClick:()=>{O==="chart"&&h?C(!1):(I("chart"),C(Y=>!Y))},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${O==="chart"?o.accent:o.btnBorder}`,background:O==="chart"?`${o.accent}20`:"transparent",color:O==="chart"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s",display:"flex",alignItems:"center",gap:3},children:[p?((z=hc.find(Y=>Y.value===p))==null?void 0:z.label)??"Chart":"Chart",a.jsx("svg",{width:"6",height:"6",viewBox:"0 0 8 8",fill:"currentColor",children:a.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),h&&a.jsx(pH,{selected:p,onSelect:Y=>{N(Y),I("chart"),C(!1)},onClose:()=>C(!1),t:o})]}),O==="chart"&&a.jsx("button",{onClick:()=>_(Y=>!Y),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:a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:a.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"})})})]}),a.jsxs("button",{onClick:()=>A(Y=>!Y),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:[a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:f?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.15s"},children:a.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})}),f?"Hide":"Show"]})]}),f&&a.jsxs(a.Fragment,{children:[e.error&&a.jsx(Bg,{message:e.error,themeMode:n.themeMode,onFix:y?H:void 0,schemaTables:n.schemaTables}),e.result&&!e.error&&(O==="chart"&&p?a.jsxs(a.Fragment,{children:[mc(p,e.result,n.themeMode,e.chartConfig),m&&a.jsx(hH,{columns:e.result.columns,chartConfig:e.chartConfig,onChange:Y=>r({type:"UPDATE_CELL",id:e.id,updates:{chartConfig:{...e.chartConfig,...Y}}}),t:o})]}):a.jsx(Ni,{result:e.result,themeMode:n.themeMode}))]})]}),y&&a.jsx(OU,{cellContent:e.content,cellType:e.type,cellName:e.name,themeMode:n.themeMode,t:o,onFocusNode:Y=>{r({type:"SET_LINEAGE_FOCUS",nodeId:Y}),n.lineageFullscreen||r({type:"TOGGLE_LINEAGE_FULLSCREEN"})}})]})]})}function Hn({title:e,onClick:t,children:n,t:r,accent:o,danger:s}){const[i,l]=R.useState(!1);return a.jsx("button",{title:e,onClick:t,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",background:i?s?`${r.error}18`:o?`${r.accent}18`:r.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:i?s?r.error:o?r.accent:r.textSecondary:r.textMuted,transition:"all 0.15s",padding:0},children:n})}function pH({selected:e,onSelect:t,onClose:n,t:r}){const[o,s]=R.useState(null);return Ce.useEffect(()=>{const i=l=>{setTimeout(()=>n(),0)};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[n]),a.jsx("div",{onMouseDown:i=>i.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:hc.map(({value:i,label:l})=>a.jsx("button",{onClick:()=>t(i),onMouseEnter:()=>s(i),onMouseLeave:()=>s(null),style:{background:e===i?`${r.accent}20`:o===i?r.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:e===i?r.accent:r.textSecondary,fontSize:11,fontFamily:r.font,fontWeight:e===i?600:400,padding:"4px 10px",textAlign:"left",transition:"background 0.1s"},children:l},i))})}function hH({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 a.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px 16px",padding:"8px 12px",borderTop:`1px solid ${r.cellBorder}`,background:`${r.tableHeaderBg}40`},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[a.jsx("span",{style:s,children:"X axis"}),a.jsxs("select",{style:o,value:(t==null?void 0:t.x)??"",onChange:i=>n({x:i.target.value||void 0}),children:[a.jsx("option",{value:"",children:"Auto"}),e.map(i=>a.jsx("option",{value:i,children:i},i))]})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[a.jsx("span",{style:s,children:"Y axis"}),a.jsxs("select",{style:o,value:(t==null?void 0:t.y)??"",onChange:i=>n({y:i.target.value||void 0}),children:[a.jsx("option",{value:"",children:"Auto"}),e.map(i=>a.jsx("option",{value:i,children:i},i))]})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[a.jsx("span",{style:s,children:"Color"}),a.jsxs("select",{style:o,value:(t==null?void 0:t.color)??"",onChange:i=>n({color:i.target.value||void 0}),children:[a.jsx("option",{value:"",children:"None"}),e.map(i=>a.jsx("option",{value:i,children:i},i))]})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:150},children:[a.jsx("span",{style:s,children:"Title"}),a.jsx("input",{style:{...o,fontFamily:r.font},value:(t==null?void 0:t.title)??"",placeholder:"Chart title",onChange:i=>n({title:i.target.value||void 0})})]})]})}const CH=[{type:"sql",label:"SQL",color:"#388bfd"},{type:"markdown",label:"Markdown",color:"#56d364"},{type:"dql",label:"DQL",color:"#e3b341"},{type:"param",label:"Param",color:"#e3b341"}];function sl({afterId:e}){const{state:t,dispatch:n}=Te(),r=ce[t.themeMode],[o,s]=R.useState(!1),[i,l]=R.useState(!1),[c,E]=R.useState(!1),[d,u]=R.useState(""),[T,S]=R.useState(!1),f=R.useRef(null),A=R.useRef(null);R.useEffect(()=>{if(!i)return;function h(C){f.current&&!f.current.contains(C.target)&&l(!1)}return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[i]);const O=h=>{const C=Ve(h);n({type:"ADD_CELL",cell:C,afterId:e}),l(!1),E(!1)},I=t.files.filter(h=>h.type==="block"),p=d?I.filter(h=>h.name.toLowerCase().includes(d.toLowerCase())):I,N=h=>{const C=Ve("sql",`-- Block: ${h.path}
|
|
514
|
+
@include('${h.path}')`);n({type:"ADD_CELL",cell:C,afterId:e}),l(!1),E(!1),u("")};return a.jsxs("div",{ref:f,onDragOver:h=>{h.dataTransfer.types.includes(Fs)&&(h.preventDefault(),S(!0))},onDragLeave:()=>S(!1),onDrop:h=>{const C=LR(h.dataTransfer.getData(Fs));if(!C)return;h.preventDefault(),S(!1);const m=Ve("sql",C.reference);n({type:"ADD_CELL",cell:m,afterId:e}),Z.trackUsage(C.name),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:C.name}}))},onMouseEnter:()=>s(!0),onMouseLeave:()=>{s(!1),S(!1)},style:{position:"relative",height:28,display:"flex",alignItems:"center",justifyContent:"center",cursor:"default"},children:[a.jsx("div",{style:{position:"absolute",left:0,right:0,height:1,background:T?r.accent:o||i?r.cellBorderActive:"transparent",transition:"background 0.15s"}}),(o||i||T)&&a.jsxs("button",{onClick:()=>l(h=>!h),style:{position:"relative",zIndex:2,height:22,padding:"0 10px",borderRadius:11,border:`1px solid ${T?r.accent:r.cellBorderActive}`,background:T?`${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:[a.jsx("span",{style:{fontSize:14,lineHeight:1,marginTop:-1},children:"+"}),"Add cell"]}),i&&a.jsxs("div",{style:{position:"absolute",top:26,left:"50%",transform:"translateX(-50%)",zIndex:100,background:r.modalBg,border:`1px solid ${r.cellBorder}`,borderRadius:8,boxShadow:"0 8px 24px rgba(0,0,0,0.3)",padding:4,display:"flex",flexDirection:"column",gap:4},children:[a.jsxs("div",{style:{display:"flex",gap:4},children:[CH.map(({type:h,label:C,color:m})=>a.jsx(Qu,{label:C,color:m,onClick:()=>O(h),t:r},h)),a.jsx(Qu,{label:"Block",color:"#d2a8ff",onClick:()=>{E(h=>!h),setTimeout(()=>{var h;return(h=A.current)==null?void 0:h.focus()},50)},t:r})]}),c&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"4px 2px"},children:[a.jsx("input",{ref:A,value:d,onChange:h=>u(h.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:"4px 8px",outline:"none"}}),a.jsx("div",{style:{maxHeight:160,overflow:"auto",display:"flex",flexDirection:"column",gap:2},children:p.length===0?a.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,padding:"4px 8px",fontStyle:"italic"},children:I.length===0?"No blocks yet":"No matches"}):p.map(h=>a.jsx(mH,{file:h,onClick:()=>N(h),t:r},h.path))})]})]})]})}function Qu({label:e,color:t,onClick:n,t:r}){const[o,s]=R.useState(!1);return a.jsx("button",{onClick:n,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),style:{background:o?`${t}18`:"transparent",border:`1px solid ${o?t:r.cellBorder}`,borderRadius:6,cursor:"pointer",color:o?t:r.textSecondary,fontSize:11,fontFamily:r.fontMono,fontWeight:600,padding:"4px 10px",letterSpacing:"0.04em",transition:"all 0.15s",whiteSpace:"nowrap"},children:e})}function mH({file:e,onClick:t,t:n}){const[r,o]=R.useState(!1);return a.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:"4px 8px",textAlign:"left",display:"flex",flexDirection:"column",gap:1,transition:"background 0.1s"},children:[a.jsx("span",{style:{fontWeight:500},children:e.name.replace(/\.dql$/,"")}),a.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.fontMono},children:e.path})]})}function LH({registerCellRef:e}){const{state:t,dispatch:n}=Te(),{executeCell:r}=Oi(),o=ce[t.themeMode],[s,i]=R.useState(null),l=R.useRef(0),[c,E]=R.useState(null),[d,u]=R.useState(null);R.useCallback(O=>{i(O)},[]),R.useEffect(()=>{s&&t.inspectorOpen&&n({type:"SET_INSPECTOR_CONTEXT",context:{kind:"cell",cellId:s}})},[s,t.inspectorOpen,n]),R.useEffect(()=>{function O(I){var C;if(!s)return;const p=I.target;if(p.tagName==="TEXTAREA"||p.tagName==="INPUT"||p.isContentEditable||p.closest(".cm-editor")){i(null);return}const N=t.cells,h=N.findIndex(m=>m.id===s);if(h!==-1)switch(I.key){case"a":{I.preventDefault();const m=Ve("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 _=N[h-1].id;n({type:"ADD_CELL",cell:m,afterId:_})}i(m.id);break}case"b":{I.preventDefault();const m=Ve("sql");n({type:"ADD_CELL",cell:m,afterId:s}),i(m.id);break}case"d":{I.preventDefault();const m=Date.now();if(m-l.current<=500){if(n({type:"DELETE_CELL",id:s}),N.length>1){const _=h>0?h-1:1;i(((C=N[_])==null?void 0:C.id)??null)}else i(null);l.current=0}else l.current=m;break}case"Enter":{if(I.shiftKey){I.preventDefault();const m=N[h];m&&m.type!=="markdown"&&r(m.id)}break}}}return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[s,t.cells,n,r]),R.useEffect(()=>{function O(I){I.target.closest("[data-cell-id]")||i(null)}return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[]);const T=R.useCallback((O,I)=>{E(I),O.dataTransfer.effectAllowed="move",O.dataTransfer.setData("text/plain",String(I));const p=O.currentTarget;setTimeout(()=>{p.style.opacity="0.4"},0)},[]),S=R.useCallback(O=>{O.currentTarget.style.opacity="1",E(null),u(null)},[]),f=R.useCallback((O,I)=>{O.preventDefault(),O.dataTransfer.dropEffect="move",u(I)},[]),A=R.useCallback((O,I)=>{O.preventDefault(),c!==null&&c!==I&&n({type:"REORDER_CELL",fromIndex:c,toIndex:I}),E(null),u(null)},[c,n]);return t.cells.length===0?a.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[a.jsx(sl,{}),a.jsx(_H,{t:o})]}):a.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[a.jsx(sl,{afterId:void 0}),t.cells.map((O,I)=>a.jsxs(Ce.Fragment,{children:[a.jsxs("div",{ref:p=>e(O.id,p),"data-cell-id":O.id,draggable:!0,onDragStart:p=>T(p,I),onDragEnd:S,onDragOver:p=>f(p,I),onDrop:p=>A(p,I),onClick:p=>{const N=p.target;!N.closest(".cm-editor")&&!N.closest("textarea")&&!N.closest("input")&&i(O.id)},style:{outline:s===O.id?`2px solid ${o.accent}40`:"none",outlineOffset:2,borderRadius:10,transition:"outline 0.1s, transform 0.15s",position:"relative",...d===I&&c!==null&&c!==I?{borderTop:`2px solid ${o.accent}`}:{}},children:[a.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:a.jsxs("svg",{width:"8",height:"14",viewBox:"0 0 8 14",fill:"currentColor",children:[a.jsx("circle",{cx:"2",cy:"2",r:"1.2"}),a.jsx("circle",{cx:"6",cy:"2",r:"1.2"}),a.jsx("circle",{cx:"2",cy:"7",r:"1.2"}),a.jsx("circle",{cx:"6",cy:"7",r:"1.2"}),a.jsx("circle",{cx:"2",cy:"12",r:"1.2"}),a.jsx("circle",{cx:"6",cy:"12",r:"1.2"})]})}),a.jsx(NH,{cell:O,index:I})]}),a.jsx(sl,{afterId:O.id})]},O.id)),a.jsx("style",{children:`
|
|
515
|
+
[data-cell-id]:hover .drag-handle { opacity: 0.5 !important; }
|
|
516
|
+
[data-cell-id]:hover .drag-handle:hover { opacity: 1 !important; }
|
|
517
|
+
`})]})}function _H({t:e}){return a.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"48px 0",gap:12,color:e.textMuted},children:[a.jsx("svg",{width:"40",height:"40",viewBox:"0 0 16 16",fill:"currentColor",style:{opacity:.3},children:a.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"})}),a.jsx("span",{style:{fontSize:13,fontFamily:e.font},children:"Empty notebook. Click + to add your first cell."})]})}function gH(){const{state:e}=Te(),t=ce[e.themeMode],n=e.cells.filter(r=>r.type==="markdown"||r.result&&r.status!=="running"||r.error);return a.jsx("div",{style:{flex:1,overflow:"auto",background:t.appBg,padding:"32px 24px 48px"},children:a.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",display:"flex",flexDirection:"column",gap:24},children:[a.jsxs("div",{style:{textAlign:"center",marginBottom:8},children:[a.jsx("h1",{style:{fontSize:28,fontWeight:700,color:t.textPrimary,fontFamily:t.font,letterSpacing:"-0.3px",margin:0},children:e.notebookTitle||"Untitled"}),a.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?a.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=>a.jsx(xH,{cell:r},r.id))]})})}function xH({cell:e}){const{state:t}=Te(),n=ce[t.themeMode];if(e.type==="markdown")return a.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:DH(e.content,n)}});if(e.error)return a.jsxs("div",{style:{background:n.cellBg,borderRadius:10,border:`1px solid ${n.error}40`,padding:"16px 24px"},children:[e.name&&a.jsx(yH,{name:e.name,t:n}),a.jsx("div",{style:{color:n.error,fontSize:12,fontFamily:n.fontMono,whiteSpace:"pre-wrap"},children:e.error})]});if(!e.result)return null;const r=Xr(e.result,e.chartConfig),o=r!=="table";return a.jsxs("div",{style:{background:n.cellBg,borderRadius:10,border:`1px solid ${n.cellBorder}`,overflow:"hidden"},children:[a.jsxs("div",{style:{padding:"10px 20px",borderBottom:`1px solid ${n.cellBorder}`,display:"flex",alignItems:"center",gap:8},children:[e.name?a.jsx("span",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,fontFamily:n.font,flex:1},children:e.name}):a.jsx("span",{style:{flex:1}}),a.jsxs("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.fontMono},children:[e.result.rowCount??e.result.rows.length," rows",e.result.executionTime!=null&&a.jsxs(a.Fragment,{children:[" · ",e.result.executionTime<1e3?`${e.result.executionTime}ms`:`${(e.result.executionTime/1e3).toFixed(1)}s`]})]})]}),a.jsx("div",{style:{padding:o?"16px 20px":0},children:o?mc(r,e.result,t.themeMode,e.chartConfig):a.jsx(Ni,{result:e.result,themeMode:t.themeMode})})]})}function yH({name:e,t}){return a.jsx("div",{style:{fontSize:13,fontWeight:600,color:t.textPrimary,fontFamily:t.font,marginBottom:8},children:e})}function DH(e,t){const n=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");return e.split(`
|
|
518
|
+
`).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 i=n(o);return i=i.replace(/\*{2}(.+?)\*{2}/g,"<strong>$1</strong>"),i=i.replace(/\*(.+?)\*/g,"<em>$1</em>"),i=i.replace(/`(.+?)`/g,`<code style="background:${t.editorBg};padding:1px 4px;border-radius:3px;font-size:0.9em">$1</code>`),`<div style="margin-bottom:4px">${i}</div>`}).join("")}function PH({onOpenFile:e,registerCellRef:t}){const{state:n}=Te(),r=ce[n.themeMode];return n.activeFile?n.dashboardMode?a.jsx(gH,{}):a.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",background:r.appBg},children:[a.jsx(MH,{t:r}),a.jsx("div",{style:{flex:1,overflow:"auto",padding:"24px 0 40px"},children:a.jsx(LH,{registerCellRef:t})})]}):a.jsx(N_,{onOpenFile:e})}function MH({t:e}){const{state:t}=Te(),n=t.cells.length;return a.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:[a.jsx(bH,{t:e}),a.jsx("div",{style:{flex:1}}),a.jsxs("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.font,display:"flex",alignItems:"center",gap:12},children:[a.jsxs("span",{children:[n," ",n===1?"cell":"cells"]}),t.notebookDirty&&a.jsx("span",{style:{color:e.warning},children:"● unsaved"})]})]})}function bH({t:e}){const{state:t}=Te();if(!t.activeFile)return null;const n=t.activeFile.path.split("/").filter(Boolean);return a.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,fontSize:12,fontFamily:e.fontMono,color:e.textMuted,overflow:"hidden"},children:n.map((r,o)=>a.jsxs(Ce.Fragment,{children:[o>0&&a.jsx("span",{style:{color:e.textMuted,opacity:.5},children:"/"}),a.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 Zu={blank:"Blank",revenue:"Revenue Analysis",pipeline:"Pipeline Health"},vH={blank:"Start with an empty notebook.",revenue:"Pre-built queries for revenue metrics and trends.",pipeline:"Templates for data pipeline health monitoring."};function eT(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function UH(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function wH(e){switch(e){case"revenue":return[Ve("markdown",`# Revenue Analysis
|
|
519
|
+
|
|
520
|
+
This notebook analyzes revenue metrics and trends over time.`),{...Ve("sql",`SELECT
|
|
521
|
+
DATE_TRUNC('month', order_date) AS month,
|
|
522
|
+
SUM(amount) AS revenue
|
|
523
|
+
FROM orders
|
|
524
|
+
GROUP BY 1
|
|
525
|
+
ORDER BY 1`),name:"monthly_revenue"},{...Ve("sql",`SELECT
|
|
526
|
+
product_category,
|
|
527
|
+
SUM(amount) AS total_revenue,
|
|
528
|
+
COUNT(*) AS orders
|
|
529
|
+
FROM orders
|
|
530
|
+
GROUP BY 1
|
|
531
|
+
ORDER BY 2 DESC`),name:"revenue_by_category"}];case"pipeline":return[Ve("markdown",`# Pipeline Health
|
|
532
|
+
|
|
533
|
+
Monitor data pipeline performance, SLA compliance, and error rates.`),{...Ve("sql",`SELECT
|
|
534
|
+
pipeline_name,
|
|
535
|
+
COUNT(*) AS runs,
|
|
536
|
+
AVG(duration_seconds) AS avg_duration,
|
|
537
|
+
SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failures
|
|
538
|
+
FROM pipeline_runs
|
|
539
|
+
GROUP BY 1
|
|
540
|
+
ORDER BY 4 DESC`),name:"pipeline_summary"},{...Ve("sql",`SELECT
|
|
541
|
+
*
|
|
542
|
+
FROM pipeline_runs
|
|
543
|
+
WHERE status = 'failed'
|
|
544
|
+
AND run_date >= CURRENT_DATE - INTERVAL '7 days'
|
|
545
|
+
ORDER BY run_date DESC`),name:"recent_failures"}];default:return[Ve("sql")]}}function BH({onFileOpened:e}){const{state:t,dispatch:n}=Te(),r=ce[t.themeMode],[o,s]=R.useState(""),[i,l]=R.useState("blank"),[c,E]=R.useState(null),[d,u]=R.useState(!1),T=R.useRef(null);R.useEffect(()=>{var A;(A=T.current)==null||A.focus()},[]),R.useEffect(()=>{const A=O=>{O.key==="Escape"&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[n]);const S=async()=>{const A=UH(o);if(A){E(A);return}u(!0),E(null);const O=eT(o),I=wH(i);try{const p=await Z.createNotebook(O,i),N={name:`${O}.dqlnb`,path:p.path,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:N}),n({type:"OPEN_FILE",file:N,cells:I,title:o.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(N)}catch{const p=`notebooks/${O}.dqlnb`,N={name:`${O}.dqlnb`,path:p,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:N}),n({type:"OPEN_FILE",file:N,cells:I,title:o.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(N)}finally{u(!1)}},f=A=>{A.target===A.currentTarget&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return a.jsx("div",{onClick:f,style:{position:"fixed",inset:0,background:r.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:a.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:[a.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[a.jsx("h2",{style:{fontSize:16,fontWeight:600,color:r.textPrimary,fontFamily:r.font,margin:0},children:"New Notebook"}),a.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:"×"})]}),a.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:20},children:[a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[a.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Name"}),a.jsx("input",{ref:T,value:o,onChange:A=>{s(A.target.value),E(null)},onKeyDown:A=>{A.key==="Enter"&&S()},placeholder:"my-analysis",style:{background:r.inputBg,border:`1px solid ${c?r.error:r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:13,fontFamily:r.font,padding:"8px 12px",outline:"none",transition:"border-color 0.15s"}}),c&&a.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:c}),o&&!c&&a.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["File: ",eT(o),".dqlnb"]})]}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[a.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Template"}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:Object.keys(Zu).map(A=>a.jsx(FH,{value:A,selected:i===A,onSelect:()=>l(A),label:Zu[A],description:vH[A],t:r},A))})]})]}),a.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${r.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[a.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"}),a.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 FH({value:e,selected:t,onSelect:n,label:r,description:o,t:s}){const[i,l]=R.useState(!1);return a.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:i?s.textMuted:s.inputBorder}`,background:t?`${s.cellBorderActive}10`:i?s.sidebarItemHover:"transparent",cursor:"pointer",transition:"all 0.15s"},children:[a.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&&a.jsx("div",{style:{width:8,height:8,borderRadius:4,background:s.accent}})}),a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:13,fontWeight:500,color:s.textPrimary,fontFamily:s.font,marginBottom:2},children:r}),a.jsx("div",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:o})]})]})}function tT(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function GH(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function HH({onFileOpened:e}){const{state:t,dispatch:n}=Te(),r=ce[t.themeMode],[o,s]=R.useState(""),[i,l]=R.useState(null),[c,E]=R.useState(!1),d=R.useRef(null);R.useEffect(()=>{var S;(S=d.current)==null||S.focus()},[]),R.useEffect(()=>{const S=f=>{f.key==="Escape"&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[n]);const u=async()=>{var A;const S=GH(o);if(S){l(S);return}E(!0),l(null);const f=tT(o);try{const O=await Z.createBlock(o.trim()),I={name:`${f}.dql`,path:O.path,type:"block",folder:"blocks",isNew:!0};n({type:"FILE_ADDED",file:I}),n({type:"CLOSE_NEW_BLOCK_MODAL"}),e(I)}catch(O){(A=O.message)!=null&&A.includes("already exists")?l("A block with this name already exists."):l(O.message??"Failed to create block.")}finally{E(!1)}},T=S=>{S.target===S.currentTarget&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return a.jsx("div",{onClick:T,style:{position:"fixed",inset:0,background:r.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:a.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:[a.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[a.jsx("h2",{style:{fontSize:16,fontWeight:600,color:r.textPrimary,fontFamily:r.font,margin:0},children:"New Block"}),a.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:"×"})]}),a.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},children:[a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[a.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Block Name"}),a.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 ${i?r.error:r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:13,fontFamily:r.font,padding:"8px 12px",outline:"none",transition:"border-color 0.15s"}}),i&&a.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:i}),o&&!i&&a.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["blocks/",tT(o),".dql"]})]}),a.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 ",a.jsx("code",{style:{fontFamily:r.fontMono,fontSize:11},children:"blocks/"})," folder. They can be referenced from notebooks and other blocks."]})]}),a.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${r.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[a.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"}),a.jsx("button",{onClick:u,disabled:c||!o.trim(),style:{background:r.accent,border:`1px solid ${r.accent}`,borderRadius:6,color:"#ffffff",cursor:c||!o.trim()?"not-allowed":"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 20px",opacity:c||!o.trim()?.6:1,display:"flex",alignItems:"center",gap:6},children:c?"Creating...":"Create Block"})]})]})})}function YH({item:e,favorite:t,onInsert:n,onPreview:r,onCopySql:o,onToggleFavorite:s,t:i}){if(!e)return null;const l=e.kind==="metric"||e.kind==="dimension",c=!!e.sql,E=e.source?`${e.source.provider} · ${e.source.objectType}`:null;return a.jsxs("div",{style:{borderTop:`1px solid ${i.headerBorder}`,padding:"12px 10px",display:"flex",flexDirection:"column",gap:10,background:`${i.cellBg}cc`},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[a.jsxs("div",{style:{flex:1,minWidth:0},children:[a.jsx("div",{style:{fontSize:12,fontWeight:600,color:i.textPrimary,fontFamily:i.font},children:e.label||e.name}),a.jsxs("div",{style:{fontSize:10,color:i.textMuted,fontFamily:i.fontMono},children:[e.kind," · ",e.name]})]}),a.jsx("button",{onClick:s,style:{background:t?"#e3b34122":"transparent",border:`1px solid ${t?"#e3b34166":i.cellBorder}`,borderRadius:6,color:t?"#e3b341":i.textMuted,cursor:"pointer",fontSize:11,fontFamily:i.font,padding:"4px 8px"},children:t?"Favorited":"Favorite"})]}),e.description&&a.jsx("div",{style:{fontSize:12,color:i.textSecondary,fontFamily:i.font,lineHeight:1.5},children:e.description}),a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,fontSize:11,fontFamily:i.fontMono,color:i.textMuted},children:[a.jsxs("div",{children:["domain: ",e.domain||"uncategorized"]}),a.jsxs("div",{children:["owner: ",e.owner??"unassigned"]}),e.table?a.jsxs("div",{children:["table: ",e.table]}):a.jsx("div",{}),e.cube?a.jsxs("div",{children:["cube: ",e.cube]}):a.jsx("div",{}),e.type?a.jsxs("div",{children:["type: ",e.type]}):a.jsx("div",{}),E?a.jsxs("div",{children:["source: ",E]}):a.jsx("div",{})]}),e.tags.length>0&&a.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:e.tags.map(d=>a.jsx("span",{style:{fontSize:10,color:i.textMuted,background:i.pillBg,borderRadius:999,padding:"2px 8px",fontFamily:i.font},children:d},d))}),e.sql&&a.jsxs("div",{style:{position:"relative"},children:[a.jsx("pre",{style:{margin:0,padding:"8px 10px",paddingRight:32,background:i.editorBg,border:`1px solid ${i.cellBorder}`,borderRadius:6,fontSize:10,fontFamily:i.fontMono,color:i.textSecondary,overflowX:"auto",whiteSpace:"pre-wrap"},children:e.sql}),a.jsx("button",{onClick:o,title:"Copy SQL",style:{position:"absolute",top:6,right:6,background:i.btnBg,border:`1px solid ${i.cellBorder}`,borderRadius:4,color:i.textMuted,cursor:"pointer",fontSize:10,fontFamily:i.font,padding:"2px 6px",opacity:.7,lineHeight:1},children:"Copy"})]}),e.joins&&e.joins.length>0&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[a.jsx("div",{style:{fontSize:11,fontWeight:600,color:i.textSecondary,fontFamily:i.font},children:"Joins"}),e.joins.map(d=>a.jsxs("div",{style:{fontSize:10,color:i.textMuted,fontFamily:i.fontMono},children:[d.left," ",d.type," ",d.right]},d.name))]}),e.levels&&e.levels.length>0&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[a.jsx("div",{style:{fontSize:11,fontWeight:600,color:i.textSecondary,fontFamily:i.font},children:"Levels"}),e.levels.map(d=>a.jsxs("div",{style:{fontSize:10,color:i.textMuted,fontFamily:i.fontMono},children:[d.order,". ",d.label," → ",d.dimension]},d.name))]}),a.jsxs("div",{style:{display:"flex",gap:8},children:[a.jsx("button",{onClick:r,disabled:!c,style:{flex:1,background:i.btnBg,border:`1px solid ${i.btnBorder}`,borderRadius:6,color:i.textSecondary,cursor:"pointer",fontSize:11,fontFamily:i.font,padding:"6px 10px"},children:"Preview Data"}),a.jsx("button",{onClick:o,disabled:!e.sql,style:{flex:1,background:i.btnBg,border:`1px solid ${i.btnBorder}`,borderRadius:6,color:i.textSecondary,cursor:"pointer",fontSize:11,fontFamily:i.font,padding:"6px 10px"},children:"Copy SQL"}),a.jsx("button",{onClick:n,disabled:!l,style:{flex:1,background:i.accent,border:`1px solid ${i.accent}`,borderRadius:6,color:"#fff",cursor:"pointer",fontSize:11,fontFamily:i.font,padding:"6px 10px"},children:l?"Insert":"Inspect"})]})]})}function kH({query:e,provider:t,cube:n,owner:r,domain:o,tag:s,type:i,providers:l,cubes:c,owners:E,domains:d,tags:u,onQueryChange:T,onProviderChange:S,onCubeChange:f,onOwnerChange:A,onDomainChange:O,onTagChange:I,onTypeChange:p,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 a.jsxs("div",{style:{padding:"10px",display:"flex",flexDirection:"column",gap:8,borderBottom:`1px solid ${N.headerBorder}`},children:[a.jsx("input",{value:e,onChange:C=>T(C.target.value),placeholder:"Search labels, cubes, owners, tags...",style:h}),a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:6},children:[a.jsxs("select",{value:t,onChange:C=>S(C.target.value),style:h,children:[a.jsx("option",{value:"",children:"All providers"}),l.map(C=>a.jsx("option",{value:C,children:C},C))]}),a.jsxs("select",{value:o,onChange:C=>O(C.target.value),style:h,children:[a.jsx("option",{value:"",children:"All domains"}),d.map(C=>a.jsx("option",{value:C,children:C},C))]}),a.jsxs("select",{value:n,onChange:C=>f(C.target.value),style:h,children:[a.jsx("option",{value:"",children:"All cubes"}),c.map(C=>a.jsx("option",{value:C,children:C},C))]}),a.jsxs("select",{value:r,onChange:C=>A(C.target.value),style:h,children:[a.jsx("option",{value:"",children:"All owners"}),E.map(C=>a.jsx("option",{value:C,children:C},C))]}),a.jsxs("select",{value:s,onChange:C=>I(C.target.value),style:h,children:[a.jsx("option",{value:"",children:"All tags"}),u.map(C=>a.jsx("option",{value:C,children:C},C))]}),a.jsxs("select",{value:i,onChange:C=>p(C.target.value),style:h,children:[a.jsx("option",{value:"",children:"All types"}),a.jsx("option",{value:"cube",children:"Cubes"}),a.jsx("option",{value:"metric",children:"Metrics"}),a.jsx("option",{value:"dimension",children:"Dimensions"}),a.jsx("option",{value:"hierarchy",children:"Hierarchies"}),a.jsx("option",{value:"segment",children:"Segments"}),a.jsx("option",{value:"pre_aggregation",children:"Pre-aggregations"})]})]})]})}function Fl({label:e,depth:t=0,badge:n,badgeColor:r,count:o,expanded:s,favorite:i,selected:l,onClick:c,onDoubleClick:E,onToggle:d,onFavoriteToggle:u,onDragStart:T,title:S,muted:f,t:A}){const[O,I]=R.useState(!1);return a.jsxs("button",{draggable:!!T,onDragStart:T,onClick:c,onDoubleClick:E,onMouseEnter:()=>I(!0),onMouseLeave:()=>I(!1),title:S,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:`5px 8px 5px ${10+t*14}px`,background:l?`${A.accent}18`:O?A.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:f?A.textMuted:A.textPrimary,fontSize:12,fontFamily:A.font,textAlign:"left"},children:[d?a.jsx("span",{onClick:p=>{p.stopPropagation(),d()},style:{display:"inline-flex",transform:s?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s",color:A.textMuted},children:a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:a.jsx("path",{d:"M3 2l4 3-4 3V2Z"})})}):a.jsx("span",{style:{width:10,flexShrink:0}}),a.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),n&&a.jsx("span",{style:{fontSize:9,fontFamily:A.fontMono,color:r??A.accent,background:`${r??A.accent}18`,borderRadius:4,padding:"1px 4px",flexShrink:0},children:n}),typeof o=="number"&&a.jsx("span",{style:{fontSize:10,color:A.textMuted,background:A.pillBg,borderRadius:999,padding:"1px 6px",flexShrink:0},children:o}),typeof i=="boolean"&&a.jsx("span",{onClick:p=>{p.stopPropagation(),u==null||u()},style:{color:i?"#e3b341":A.textMuted,display:"inline-flex",flexShrink:0},children:a.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:a.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 cs=31,nT=10;function WH(){var bo,vo,Uo,wo,Bo,pr,Fo,Go,Ho;const{state:e,dispatch:t}=Te(),n=ce[e.themeMode],[r,o]=R.useState("semantic"),[s,i]=R.useState("validate"),[l,c]=R.useState(""),[E,d]=R.useState(""),[u,T]=R.useState(""),[S,f]=R.useState(""),[A,O]=R.useState(""),[I,p]=R.useState(""),[N,h]=R.useState(""),[C,m]=R.useState({}),[_,D]=R.useState(null),[g,b]=R.useState(null),[y,M]=R.useState([]),[F,L]=R.useState({}),[v,P]=R.useState(""),[w,U]=R.useState(new Set),[x,B]=R.useState(!1),[H,W]=R.useState(!1),[$,X]=R.useState(null),[J,q]=R.useState(null),[z,Y]=R.useState([]),[K,le]=R.useState(!1),[se,ne]=R.useState(null),[te,Ee]=R.useState(!1),[fe,de]=R.useState(!1),[Re,He]=R.useState(null),[Me,dt]=R.useState(null),[an,wt]=R.useState(null),[Dn,Oo]=R.useState(!1),[Bt,Ct]=R.useState(0),[Ft,No]=R.useState(400),[po,Ir]=R.useState(360),[ho,wi]=R.useState(280),[Gt,Co]=R.useState(!1),[Ht,mo]=R.useState(!1),Pn=R.useRef(null);R.useEffect(()=>{t({type:"SET_BLOCK_STUDIO_CATALOG_LOADING",loading:!0}),q(null),Z.getBlockStudioCatalog().then(k=>{t({type:"SET_BLOCK_STUDIO_CATALOG",catalog:k}),M(k.databaseTree)}).catch(()=>{q("Failed to load schema. Check your connection and try refreshing.")}).finally(()=>t({type:"SET_BLOCK_STUDIO_CATALOG_LOADING",loading:!1}))},[t]),R.useEffect(()=>{if(!_||_.startsWith("provider:")||_.startsWith("domain:")||_.startsWith("group:")){b(null);return}Z.getSemanticObject(_).then(b).catch(()=>b(null))},[_]),R.useEffect(()=>{const k=window.setTimeout(()=>{e.blockStudioDraft.trim()&&Z.validateBlockStudio(e.blockStudioDraft,e.activeBlockPath).then(ie=>t({type:"SET_BLOCK_STUDIO_VALIDATION",validation:ie})).catch(()=>{})},250);return()=>window.clearTimeout(k)},[e.blockStudioDraft,e.activeBlockPath,t]);const Or=((bo=e.blockStudioCatalog)==null?void 0:bo.semanticTree)??null,Ze=R.useMemo(()=>o2(Or)?Or:s2(e.semanticLayer),[Or,e.semanticLayer]),Bi=R.useMemo(()=>il(Ze,"provider"),[Ze]),Fi=R.useMemo(()=>il(Ze,"cube"),[Ze]),Gi=R.useMemo(()=>il(Ze,"owner"),[Ze]),Mn=R.useMemo(()=>Ze?cI(Ze,{query:l,provider:E,domain:u,cube:S,owner:A,tag:I,type:N}):null,[Ze,l,E,u,S,A,I,N]),ln=R.useMemo(()=>EI((Mn==null?void 0:Mn.children)??[],C),[Mn,C]),Hi=R.useMemo(()=>n2(y,v),[y,v]),Yi=R.useMemo(()=>r2(y),[y]),Nr={metrics:e.semanticLayer.metrics.length,dimensions:e.semanticLayer.dimensions.length,hierarchies:e.semanticLayer.hierarchies.length},ki=ln.length*cs,Lo=R.useMemo(()=>{const k=Math.max(0,Math.floor(Bt/cs)-nT),ie=Math.min(ln.length,Math.ceil((Bt+Ft)/cs)+nT);return{offsetTop:k*cs,rows:ln.slice(k,ie)}},[ln,Bt,Ft]);R.useEffect(()=>{const k=Pn.current;if(!k)return;const ie=()=>No(k.clientHeight||400);if(ie(),typeof ResizeObserver>"u")return window.addEventListener("resize",ie),()=>window.removeEventListener("resize",ie);const he=new ResizeObserver(()=>ie());return he.observe(k),()=>he.disconnect()},[]),R.useEffect(()=>{Ct(0),Pn.current&&(Pn.current.scrollTop=0)},[l,E,u,S,A,I,N]);const bn=R.useMemo(()=>{var ie;const k=wE(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:(ie=k==null?void 0:k.tags)!=null&&ie.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)??((vo=e.blockStudioMetadata)==null?void 0:vo.name)??null;R.useEffect(()=>{if(!ut)return;const k=`block:${ut}`;t({type:"SET_LINEAGE_FOCUS",nodeId:k}),de(!0),Promise.all([Z.fetchLineageNode(k),Z.queryLineage({focus:k}),Z.fetchLineagePaths(k)]).then(([ie,he,Le])=>{He(ie),dt(he.graph??null),wt(Le)}).catch(()=>{He(null),dt(null),wt(null)}).finally(()=>de(!1))},[ut,t]);const Ye=k=>{t({type:"SET_BLOCK_STUDIO_DRAFT",draft:k})},_o=async()=>{var k,ie,he;B(!0);try{const Le=await Z.runBlockStudio(e.blockStudioDraft,e.activeBlockPath);t({type:"SET_BLOCK_STUDIO_PREVIEW",preview:Le}),i("results")}catch(Le){t({type:"SET_BLOCK_STUDIO_VALIDATION",validation:{valid:!1,chartConfig:(k=e.blockStudioValidation)==null?void 0:k.chartConfig,executableSql:((ie=e.blockStudioValidation)==null?void 0:ie.executableSql)??null,semanticRefs:((he=e.blockStudioValidation)==null?void 0:he.semanticRefs)??{metrics:[],dimensions:[],segments:[]},diagnostics:[{severity:"error",code:"block_run_failed",message:Le instanceof Error?Le.message:String(Le)}]}}),i("validate")}finally{B(!1)}},go=async()=>{if(!e.blockStudioMetadata){t({type:"OPEN_NEW_BLOCK_MODAL"});return}W(!0),X(null);try{const k=await Z.saveBlockStudio({path:e.activeBlockPath,source:e.blockStudioDraft,metadata:{name:e.blockStudioMetadata.name,domain:e.blockStudioMetadata.domain,description:e.blockStudioMetadata.description,owner:e.blockStudioMetadata.owner,tags:e.blockStudioMetadata.tags}});t({type:"OPEN_BLOCK_STUDIO",file:{name:`${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"}}),i("save")}catch(k){const ie=(k==null?void 0:k.message)??"Save failed";X(ie.includes("409")||ie.includes("BLOCK_EXISTS")?"A block with this name already exists. Rename and try again.":ie),setTimeout(()=>X(null),5e3)}finally{W(!1)}},xo=k=>{var ie;if(k.kind==="metric"||k.kind==="dimension"){const he=QL(k.kind==="metric"?"metric":"dimension",k.name);(((ie=wE(e.blockStudioDraft))==null?void 0:ie.blockType)??"custom")==="semantic"?Ye(ZL(e.blockStudioDraft,{kind:k.kind==="metric"?"metric":"dimension",name:k.name})):q_(he)||Ye(e_(e.blockStudioDraft,he)),t({type:"ADD_SEMANTIC_RECENT",name:k.name});return}if(k.kind==="segment"&&k.sql){Ye(Es(e.blockStudioDraft,`/* segment:${k.name} */ (${k.sql})`));return}k.kind==="pre_aggregation"&&Ye(Es(e.blockStudioDraft,`/* pre_aggregation:${k.name} */`))},Wi=k=>{Ye(Es(e.blockStudioDraft,k))},Vi=async k=>{if(!(!k.path||k.kind!=="table"||k.children&&k.children.length>0)){U(ie=>new Set(ie).add(k.id));try{const ie=await Z.describeTable(k.path);M(he=>dI(he,k.id,{...k,children:ie.map(Le=>({id:`db-column:${k.path}:${Le.name}`,label:Le.name,kind:"column",path:k.path,type:Le.type}))}))}finally{U(ie=>{const he=new Set(ie);return he.delete(k.id),he})}}},yo=R.useCallback(async()=>{try{const k=await Z.getBlockStudioCatalog();k!=null&&k.databaseTree&&M(k.databaseTree),t({type:"SET_BLOCK_STUDIO_CATALOG",catalog:k})}catch{}},[t]),ji=((Uo=e.blockStudioValidation)==null?void 0:Uo.chartConfig)??((wo=e.blockStudioPreview)==null?void 0:wo.chartConfig)??{chart:"table"},$i=e.blockStudioPreview?Xr(e.blockStudioPreview.result,e.blockStudioPreview.chartConfig):"table",Do=R.useMemo(()=>((Re==null?void 0:Re.incoming)??[]).filter(k=>k.node),[Re]),Po=R.useMemo(()=>((Re==null?void 0:Re.outgoing)??[]).filter(k=>k.node),[Re]),Mo=k=>{k.preventDefault();const ie=k.clientX,he=po,Le=hr=>{const Cr=Math.min(520,Math.max(280,he+hr.clientX-ie));Ir(Cr)},Yt=()=>{window.removeEventListener("mousemove",Le),window.removeEventListener("mouseup",Yt)};window.addEventListener("mousemove",Le),window.addEventListener("mouseup",Yt)},Xi=k=>{k.preventDefault();const ie=k.clientY,he=ho,Le=hr=>{const Cr=Math.min(520,Math.max(180,he-(hr.clientY-ie)));wi(Cr)},Yt=()=>{window.removeEventListener("mousemove",Le),window.removeEventListener("mouseup",Yt)};window.addEventListener("mousemove",Le),window.addEventListener("mouseup",Yt)};return a.jsxs("div",{style:{flex:1,position:"relative",display:"grid",gridTemplateColumns:Gt?"0 0 minmax(0, 1fr)":`${po}px 6px minmax(0, 1fr)`,gridTemplateRows:Ht?"minmax(0, 1fr) 0 0":`minmax(0, 1fr) 6px ${ho}px`,overflow:"hidden",background:n.appBg},children:[a.jsxs("div",{style:{borderRight:Gt?"none":`1px solid ${n.headerBorder}`,display:Gt?"none":"flex",flexDirection:"column",overflow:"hidden",background:n.sidebarBg,minWidth:0},children:[a.jsxs("div",{style:{padding:14,display:"grid",gap:12,borderBottom:`1px solid ${n.headerBorder}`},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:12,fontWeight:700,color:n.textPrimary,fontFamily:n.font},children:"Block Studio"}),a.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:"Build DQL with semantic models and live database structure in one workspace."})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.semanticLayer.provider&&a.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}),a.jsx("button",{onClick:()=>Co(!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:"‹"})]})]}),a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8},children:[a.jsx(qn,{label:"Metrics",value:Nr.metrics,t:n}),a.jsx(qn,{label:"Dimensions",value:Nr.dimensions,t:n}),a.jsx(qn,{label:"Hierarchies",value:Nr.hierarchies,t:n})]})]}),a.jsxs("div",{style:{display:"flex",padding:"10px 12px",gap:8,borderBottom:`1px solid ${n.headerBorder}`},children:[a.jsx(Tt,{active:r==="semantic",onClick:()=>o("semantic"),label:"Semantic Layer"}),a.jsx(Tt,{active:r==="database",onClick:()=>o("database"),label:"Database"})]}),r==="semantic"?a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{padding:12,borderBottom:`1px solid ${n.headerBorder}`,background:`${n.cellBg}66`},children:a.jsx(kH,{query:l,provider:E,cube:S,owner:A,domain:u,tag:I,type:N,providers:Bi,cubes:Fi,owners:Gi,domains:e.semanticLayer.domains,tags:e.semanticLayer.tags,onQueryChange:c,onProviderChange:d,onCubeChange:f,onOwnerChange:O,onDomainChange:T,onTagChange:p,onTypeChange:h,t:n})}),a.jsx("div",{ref:Pn,onScroll:k=>Ct(k.currentTarget.scrollTop),style:{flex:1,overflowY:"auto",borderBottom:`1px solid ${n.headerBorder}`,background:n.cellBg},children:J?a.jsxs("div",{style:{padding:16,display:"grid",gap:8,textAlign:"center"},children:[a.jsx("div",{style:{fontSize:12,color:"#f85149",fontFamily:n.font},children:J}),a.jsx("button",{onClick:()=>{q(null),yo()},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?a.jsx(Dt,{message:"Loading semantic catalog…"}):ln.length===0?a.jsx(Dt,{message:"No semantic objects match the current filters."}):a.jsx("div",{style:{height:ki,position:"relative"},children:a.jsx("div",{style:{position:"absolute",top:Lo.offsetTop,left:0,right:0},children:Lo.rows.map(k=>a.jsx(ZH,{row:k,selectedId:_,setSelectedId:D,expanded:C,setExpanded:m,onInsert:xo,favorites:new Set(e.semanticLayer.favorites),dispatch:t,t:n},k.node.id))})})}),a.jsx(YH,{item:g,favorite:!!(g&&e.semanticLayer.favorites.includes(g.name)),onInsert:()=>g&&xo(g),onPreview:()=>{g!=null&&g.sql&&Ye(Es(e.blockStudioDraft,g.sql))},onCopySql:()=>{g!=null&&g.sql&&navigator.clipboard.writeText(g.sql)},onToggleFavorite:()=>{!g||g.kind!=="metric"&&g.kind!=="dimension"||Z.toggleFavorite(g.name).then(k=>t({type:"SET_SEMANTIC_FAVORITES",favorites:k}))},t:n})]}):a.jsx(QH,{tree:Hi,totalTree:y,expanded:F,setExpanded:L,onEnsureColumns:Vi,onInsert:Wi,query:v,onQueryChange:P,stats:Yi,connectionName:((Bo=e.blockStudioCatalog)==null?void 0:Bo.connection.current)??"default",loadingNodes:w,onRefresh:yo,t:n})]}),a.jsx("div",{onMouseDown:Gt?void 0:Mo,style:{display:Gt?"none":"block",cursor:"col-resize",background:n.headerBorder}}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden",gridColumn:"3",gridRow:"1"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"12px 14px",borderBottom:`1px solid ${n.headerBorder}`,background:n.cellBg},children:[Gt&&a.jsx("button",{onClick:()=>Co(!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"}),a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:12,fontWeight:700,color:n.textPrimary,fontFamily:n.font},children:"DQL Source"}),a.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:"Use templates, insert semantic refs, run, validate, and save from one editor."})]}),a.jsx("div",{style:{flex:1}}),a.jsx(yr,{label:"Semantic Skeleton",onClick:()=>{var k;return Ye(e2(((k=e.blockStudioMetadata)==null?void 0:k.name)??"New Block"))}}),a.jsx(yr,{label:"Custom Skeleton",onClick:()=>{var k;return Ye(t2(((k=e.blockStudioMetadata)==null?void 0:k.name)??"New Block"))}}),a.jsx(yr,{label:"Lineage",onClick:()=>i("lineage")}),a.jsx(yr,{label:"Run",onClick:()=>void _o(),busy:x}),a.jsx(yr,{label:"Save",onClick:()=>void go(),busy:H}),$&&a.jsx("span",{style:{fontSize:11,color:"#f85149",fontFamily:n.font,padding:"4px 8px",background:"#f8514918",borderRadius:6},children:$})]}),a.jsxs("div",{style:{padding:"10px 14px",display:"flex",gap:10,alignItems:"center",borderBottom:`1px solid ${n.headerBorder}`,background:`${n.pillBg}66`,flexWrap:"wrap"},children:[a.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Active lineage"}),a.jsx(rT,{label:"Upstream",count:Do.length,t:n}),a.jsx(rT,{label:"Downstream",count:Po.length,t:n}),((pr=Re==null?void 0:Re.node)==null?void 0:pr.domain)&&a.jsxs("span",{style:{fontSize:11,color:n.textSecondary,fontFamily:n.font},children:["Domain: ",Re.node.domain]}),a.jsx("div",{style:{flex:1}}),a.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"})]}),a.jsx("div",{style:{flex:1,overflow:"hidden"},children:a.jsx(pc,{value:e.blockStudioDraft,onChange:Ye,onRun:()=>void _o(),themeMode:e.themeMode,autoFocus:!0,errorMessage:(Go=(Fo=e.blockStudioValidation)==null?void 0:Fo.diagnostics.find(k=>k.severity==="error"))==null?void 0:Go.message})})]}),a.jsx("div",{onMouseDown:Ht?void 0:Xi,style:{gridColumn:"1 / -1",gridRow:"2",display:Ht?"none":"block",cursor:"row-resize",background:n.headerBorder}}),a.jsxs("div",{style:{gridColumn:"1 / -1",gridRow:"3",borderTop:Ht?"none":`1px solid ${n.headerBorder}`,display:Ht?"none":"flex",flexDirection:"column",overflow:"hidden",background:n.cellBg},children:[a.jsxs("div",{style:{padding:"12px 14px",display:"grid",gap:10,borderBottom:`1px solid ${n.headerBorder}`},children:[a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:12,fontWeight:700,color:n.textPrimary,fontFamily:n.font},children:"Preview & Governance"}),a.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:"Validate references, inspect results, tune visualization, and save companion metadata."})]}),a.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[a.jsx(Tt,{active:s==="results",onClick:()=>i("results"),label:"Results"}),a.jsx(Tt,{active:s==="visualization",onClick:()=>i("visualization"),label:"Visualization"}),a.jsx(Tt,{active:s==="lineage",onClick:()=>i("lineage"),label:"Lineage"}),a.jsx(Tt,{active:s==="validate",onClick:()=>i("validate"),label:"Validate"}),a.jsx(Tt,{active:s==="tests",onClick:()=>i("tests"),label:"Tests"}),a.jsx(Tt,{active:s==="history",onClick:()=>{i("history"),!K&&e.activeBlockPath&&Z.getBlockHistory(e.activeBlockPath).then(k=>{Y(k.entries),le(!0)})},label:"History"}),a.jsx(Tt,{active:s==="save",onClick:()=>i("save"),label:"Save"}),a.jsx("div",{style:{flex:1}}),a.jsx("button",{onClick:()=>mo(!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"})]})]}),a.jsxs("div",{style:{flex:1,overflow:"auto"},children:[s==="results"&&(e.blockStudioPreview?a.jsxs("div",{style:{display:"grid",gap:12,padding:12},children:[a.jsx("div",{style:{fontSize:11,color:n.textMuted,fontFamily:n.fontMono},children:e.blockStudioPreview.sql}),$i==="table"?a.jsx(Ni,{result:e.blockStudioPreview.result,themeMode:e.themeMode}):a.jsx(bg,{result:e.blockStudioPreview.result,chartConfig:e.blockStudioPreview.chartConfig,themeMode:e.themeMode})]}):a.jsx(Dt,{message:"Run the block to preview results and visualization."})),s==="visualization"&&a.jsx(jH,{chartConfig:ji,onChange:k=>Ye(qL(e.blockStudioDraft,k)),t:n}),s==="lineage"&&a.jsx($H,{blockName:ut,loading:fe,detail:Re,graph:Me,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"&&a.jsx(JH,{source:e.blockStudioDraft,blockPath:e.activeBlockPath,testResults:se,running:te,onRunTests:async()=>{if(e.activeBlockPath){Ee(!0);try{const k=await Z.runBlockTests(e.blockStudioDraft,e.activeBlockPath);ne(k.assertions??[])}catch{ne([])}finally{Ee(!1)}}},t:n}),s==="validate"&&a.jsx(VH,{diagnostics:((Ho=e.blockStudioValidation)==null?void 0:Ho.diagnostics)??[],t:n}),s==="history"&&a.jsx(qH,{entries:z,t:n}),s==="save"&&a.jsxs("div",{style:{display:"grid",gap:12},children:[e.activeBlockPath&&e.blockStudioMetadata&&a.jsx("div",{style:{padding:"12px 12px 0"},children:a.jsx(zH,{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})}),a.jsx(XH,{metadata:e.blockStudioMetadata,draftMetadata:bn,onChange:k=>{if(!e.blockStudioMetadata)return;t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,...k}});let ie=e.blockStudioDraft;typeof k.name=="string"&&(ie=TR(ie,k.name)),typeof k.domain=="string"&&(ie=da(ie,"domain",k.domain)),typeof k.owner=="string"&&(ie=da(ie,"owner",k.owner)),typeof k.description=="string"&&(ie=da(ie,"description",k.description)),k.tags&&(ie=JL(ie,k.tags)),Ye(ie)},onSave:()=>void go(),saving:H,t:n})]})]})]}),Ht&&a.jsx("div",{style:{position:"absolute",right:16,bottom:16},children:a.jsx("button",{onClick:()=>mo(!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}=Te(),s=ce[o.themeMode];return a.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 yr(e){return a.jsx(Tt,{active:!1,...e})}function qn({label:e,value:t,t:n}){return a.jsxs("div",{style:{background:n.cellBg,border:`1px solid ${n.headerBorder}`,borderRadius:10,padding:"10px 12px"},children:[a.jsx("div",{style:{fontSize:10,fontWeight:700,color:n.textMuted,fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em"},children:e}),a.jsx("div",{style:{fontSize:20,fontWeight:700,color:n.textPrimary,fontFamily:n.font,marginTop:4},children:t})]})}function VH({diagnostics:e,t}){return e.length===0?a.jsx(Dt,{message:"No validation messages."}):a.jsx("div",{style:{display:"grid",gap:8,padding:12},children:e.map((n,r)=>a.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:[a.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}),a.jsx("div",{style:{fontSize:12,color:t.textPrimary,marginTop:4},children:n.message})]},`${n.code??n.message}-${r}`))})}function jH({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 a.jsxs("div",{style:{display:"grid",gap:10,padding:12},children:[a.jsxs("select",{value:e.chart??"table",onChange:o=>t({...e,chart:o.target.value}),style:r,children:[a.jsx("option",{value:"table",children:"Table"}),hc.map(o=>a.jsx("option",{value:o.value,children:o.label},o.value))]}),a.jsx("input",{value:e.x??"",onChange:o=>t({...e,x:o.target.value}),placeholder:"x binding",style:r}),a.jsx("input",{value:e.y??"",onChange:o=>t({...e,y:o.target.value}),placeholder:"y binding",style:r}),a.jsx("input",{value:e.color??"",onChange:o=>t({...e,color:o.target.value}),placeholder:"color binding",style:r}),a.jsx("input",{value:e.title??"",onChange:o=>t({...e,title:o.target.value}),placeholder:"title",style:r})]})}function rT({label:e,count:t,t:n}){return a.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 $H({blockName:e,loading:t,detail:n,graph:r,paths:o,onSelectNode:s,onOpenFull:i,t:l}){const[c,E]=R.useState(!1);if(!e)return a.jsx(Dt,{message:"Lineage will appear once the block has a name."});if(t)return a.jsx(Dt,{message:"Loading block lineage…"});if(!(n!=null&&n.node))return a.jsxs("div",{style:{padding:12,display:"grid",gap:12},children:[a.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."}),a.jsx("div",{children:a.jsx("button",{onClick:i,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 a.jsxs("div",{style:{padding:12,display:"grid",gap:12,overflowY:"auto"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:12,fontWeight:700,color:l.textPrimary,fontFamily:l.font},children:n.node.name}),a.jsx("div",{style:{fontSize:11,color:l.textMuted,fontFamily:l.font},children:n.node.domain?`Domain: ${n.node.domain}`:"Block lineage focus"})]}),a.jsx("div",{style:{flex:1}}),a.jsx("button",{onClick:i,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)&&a.jsx(Gg,{layerSummary:o.layerSummary,t:l}),r&&r.nodes.length>0&&a.jsx(zf,{nodes:r.nodes,edges:r.edges,focalNodeId:d,height:220,onNodeClick:s,layoutMode:"flow"}),o&&(o.upstreamPaths.length>0||o.downstreamPaths.length>0)&&a.jsxs("div",{style:{display:"grid",gap:10},children:[a.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&&a.jsx(ed,{title:"Source to Block",paths:o.upstreamPaths,onNodeClick:s,focalNodeId:d,t:l}),o.downstreamPaths.length>0&&a.jsx(ed,{title:"Block to Consumption",paths:o.downstreamPaths,onNodeClick:s,focalNodeId:d,t:l})]}),a.jsxs("button",{onClick:()=>E(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:[c?"▾":"▸"," Upstream / Downstream Details"]}),c&&a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, minmax(0, 1fr))",gap:12},children:[a.jsx(oT,{title:"Upstream",entries:n.incoming,emptyMessage:"No upstream dependencies yet.",onSelectNode:s,t:l}),a.jsx(oT,{title:"Downstream",entries:n.outgoing,emptyMessage:"No downstream dependencies yet.",onSelectNode:s,t:l})]})]})}function oT({title:e,entries:t,emptyMessage:n,onSelectNode:r,t:o}){const s=t.filter(i=>i.node);return a.jsxs("div",{style:{border:`1px solid ${o.cellBorder}`,borderRadius:10,overflow:"hidden",background:o.inputBg},children:[a.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?a.jsx("div",{style:{padding:12,fontSize:12,color:o.textMuted,fontFamily:o.font},children:n}):a.jsx("div",{style:{display:"grid"},children:s.map(i=>a.jsxs("button",{onClick:()=>r(i.node.id),style:{background:"transparent",border:"none",borderTop:`1px solid ${o.cellBorder}`,padding:"10px 12px",textAlign:"left",cursor:"pointer"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[a.jsx("span",{style:{fontSize:10,fontWeight:700,color:o.accent,fontFamily:o.font,textTransform:"uppercase"},children:i.node.type.replace("_"," ")}),a.jsx("span",{style:{fontSize:12,color:o.textPrimary,fontFamily:o.font,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.node.name})]}),a.jsxs("div",{style:{marginTop:3,fontSize:11,color:o.textMuted,fontFamily:o.font},children:["via ",i.edge.type,i.node.domain?` · ${i.node.domain}`:""]})]},`${i.node.id}-${i.edge.type}`))})]})}function XH({metadata:e,draftMetadata:t,onChange:n,onSave:r,saving:o,t:s}){const i={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 a.jsxs("div",{style:{display:"grid",gap:10,padding:12},children:[a.jsx("input",{value:l.name,onChange:c=>n({name:c.target.value}),placeholder:"Block name",style:i}),a.jsx("input",{value:l.domain,onChange:c=>n({domain:c.target.value}),placeholder:"Domain",style:i}),a.jsx("input",{value:l.owner,onChange:c=>n({owner:c.target.value}),placeholder:"Owner",style:i}),a.jsx("input",{value:l.description,onChange:c=>n({description:c.target.value}),placeholder:"Description",style:i}),a.jsx("input",{value:l.tags.join(", "),onChange:c=>n({tags:c.target.value.split(",").map(E=>E.trim()).filter(Boolean)}),placeholder:"Tags",style:i}),a.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 Dt({message:e}){const{state:t}=Te(),n=ce[t.themeMode];return a.jsx("div",{style:{padding:16,fontSize:12,color:n.textMuted},children:e})}const sT={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149"},KH={draft:["review"],review:["certified","draft"],certified:["deprecated"],deprecated:["draft"]};function zH({currentStatus:e,blockPath:t,onStatusChanged:n,t:r}){const[o,s]=R.useState(!1),i=KH[e]??[],l=async c=>{if(t){s(!0);try{const E=await Z.updateBlockStatus(t,c);E.ok&&E.status&&n(E.status)}finally{s(!1)}}};return a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 12px",background:r.pillBg,borderRadius:8},children:[a.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:"Status:"}),a.jsx("span",{style:{fontSize:11,fontWeight:600,color:sT[e]??r.textMuted,background:`${sT[e]??r.textMuted}18`,padding:"2px 8px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em",fontFamily:r.font},children:e}),a.jsx("span",{style:{flex:1}}),i.map(c=>a.jsx("button",{onClick:()=>void l(c),disabled:o,style:{background:c==="certified"?"#3fb950":c==="deprecated"?"#f85149":r.btnBg,border:`1px solid ${c==="certified"?"#3fb950":c==="deprecated"?"#f85149":r.btnBorder}`,borderRadius:4,color:c==="certified"||c==="deprecated"?"#fff":r.textSecondary,cursor:o?"not-allowed":"pointer",fontSize:10,fontWeight:600,fontFamily:r.font,padding:"3px 10px",textTransform:"capitalize",opacity:o?.5:1},children:o?"...":c==="certified"?"Certify":c==="deprecated"?"Deprecate":`Move to ${c}`},c))]})}function JH({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(c=>({field:c[1],operator:c[2],expected:c[3]}));return a.jsxs("div",{style:{padding:12,display:"grid",gap:10},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[a.jsx("span",{style:{fontSize:12,fontWeight:600,color:s.textPrimary,fontFamily:s.font},children:"Test Assertions"}),a.jsx("span",{style:{flex:1}}),a.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&&a.jsxs("div",{style:{fontSize:12,color:s.textMuted,fontFamily:s.font,lineHeight:1.5},children:["No test assertions found. Add assertions in your block:",a.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 {
|
|
546
|
+
assert row_count > 0
|
|
547
|
+
assert max_value <= 1000000
|
|
548
|
+
}`})]}),l.map((c,E)=>{const d=n==null?void 0:n[E],u=d==null?void 0:d.passed;return a.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&&a.jsx("span",{style:{fontSize:14,color:u?"#3fb950":"#f85149",fontWeight:700},children:u?"✓":"✗"}),a.jsxs("div",{style:{flex:1},children:[a.jsxs("div",{style:{fontSize:12,color:s.textPrimary,fontFamily:s.fontMono},children:[c.field," ",c.operator," ",c.expected]}),d&&!u&&d.actual&&a.jsxs("div",{style:{fontSize:11,color:"#f85149",fontFamily:s.font,marginTop:2},children:["Actual: ",d.actual]})]})]},E)}),n&&n.length>0&&a.jsxs("div",{style:{padding:"8px 12px",background:s.pillBg,borderRadius:8,fontSize:12,fontFamily:s.font,color:s.textSecondary},children:[n.filter(c=>c.passed).length,"/",n.length," passed"]})]})}function qH({entries:e,t}){return e.length===0?a.jsx(Dt,{message:"No version history available. Commit changes to build history."}):a.jsxs("div",{style:{padding:12,display:"grid",gap:8},children:[a.jsx("div",{style:{fontSize:12,fontWeight:600,color:t.textPrimary,fontFamily:t.font},children:"Version History"}),e.map(n=>a.jsxs("div",{style:{padding:"8px 12px",border:`1px solid ${t.cellBorder}`,borderRadius:8,background:t.inputBg},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[a.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)}),a.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font},children:new Date(n.date).toLocaleDateString()}),a.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font,marginLeft:"auto"},children:n.author})]}),a.jsx("div",{style:{fontSize:12,color:t.textPrimary,fontFamily:t.font},children:n.message})]},n.hash))]})}function QH({tree:e,totalTree:t,expanded:n,setExpanded:r,onEnsureColumns:o,onInsert:s,query:i,onQueryChange:l,stats:c,connectionName:E,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"},f=(A,O=0)=>{var _,D,g;const I=A.kind!=="column",p=n[A.id]??O<1,N=d.has(A.id),h=A.kind==="schema"?(_=A.children)==null?void 0:_.length:A.kind==="table"?(D=A.children)==null?void 0:D.length:void 0,C=A.kind==="column"?A.type:A.kind,m=A.kind==="column"&&A.type?Al(A.type,T.accent):void 0;return a.jsxs("div",{children:[a.jsx(Fl,{label:N?`${A.label} …`:A.label,depth:O,count:h,expanded:I?p:void 0,onToggle:I?()=>{r(b=>({...b,[A.id]:!p})),p||o(A)}:void 0,badge:C,badgeColor:m,onClick:()=>{if(A.kind==="table"&&A.path&&s(A.path),A.kind==="column"){const b=A.path?A.path.split(".").pop():"";s(b?`${b}.${A.label}`:A.label)}},onDoubleClick:()=>{A.kind==="table"&&A.path&&s(`SELECT *
|
|
549
|
+
FROM ${A.path}
|
|
550
|
+
LIMIT 100`)},t:T}),I&&p&&((g=A.children)==null?void 0:g.map(b=>f(b,O+1)))]},A.id)};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{style:{padding:12,display:"grid",gap:12,borderBottom:`1px solid ${T.headerBorder}`,background:`${T.cellBg}66`},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:12,fontWeight:700,color:T.textPrimary,fontFamily:T.font},children:"Database Browser"}),a.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."})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[a.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:"↻"}),a.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:E})]})]}),a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8},children:[a.jsx(qn,{label:"Schemas",value:c.schemas,t:T}),a.jsx(qn,{label:"Tables",value:c.tables,t:T}),a.jsx(qn,{label:"Columns",value:c.columns,t:T})]}),a.jsx("input",{value:i,onChange:A=>l(A.target.value),placeholder:"Search schemas, tables, columns...",style:S})]}),a.jsx("div",{style:{flex:1,overflowY:"auto",padding:e.length>0?"6px 0 0":0},children:t.length===0?a.jsx(Dt,{message:"No schemas were found for the active connection yet."}):e.length===0?a.jsx(Dt,{message:"No database objects match the current search."}):e.map(A=>f(A))})]})}function ZH({row:e,selectedId:t,setSelectedId:n,expanded:r,setExpanded:o,onInsert:s,favorites:i,dispatch:l,t:c}){var f;const{node:E,depth:d,hasChildren:u,isExpanded:T}=e,S=E.id.split(":").slice(1).join(":");return u?a.jsx(Fl,{label:E.label,depth:d,count:(f=E.children)==null?void 0:f.length,expanded:T,onToggle:()=>o(A=>({...A,[E.id]:!T})),onClick:()=>n(E.id),selected:t===E.id,t:c}):a.jsx(Fl,{label:E.label,depth:d,badge:E.kind,selected:t===E.id,onClick:()=>n(E.id),onDoubleClick:()=>{Z.getSemanticObject(E.id).then(s).catch(()=>{})},onFavoriteToggle:E.kind==="metric"||E.kind==="dimension"?()=>void Z.toggleFavorite(S).then(A=>l({type:"SET_SEMANTIC_FAVORITES",favorites:A})):void 0,favorite:E.kind==="metric"||E.kind==="dimension"?i.has(S):void 0,t:c})}function Es(e,t){const n=e.match(/query\s*=\s*"""([\s\S]*?)"""/i);return n?e.replace(n[0],`query = """${n[1].trimEnd()}
|
|
551
|
+
${t}
|
|
552
|
+
"""`):/^\s*block\s+"/i.test(e.trim())?e.replace(/\n\}\s*$/,`
|
|
553
|
+
|
|
554
|
+
query = """
|
|
555
|
+
${t}
|
|
556
|
+
"""
|
|
557
|
+
}
|
|
558
|
+
`):`${e.trimEnd()}
|
|
559
|
+
${t}
|
|
560
|
+
`}function e2(e){return`block "${e}" {
|
|
561
|
+
domain = "uncategorized"
|
|
562
|
+
type = "semantic"
|
|
563
|
+
description = ""
|
|
564
|
+
owner = ""
|
|
565
|
+
tags = []
|
|
566
|
+
metric = "total_revenue"
|
|
567
|
+
|
|
568
|
+
visualization {
|
|
569
|
+
chart = "table"
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
`}function t2(e){return`block "${e}" {
|
|
573
|
+
domain = "uncategorized"
|
|
574
|
+
type = "custom"
|
|
575
|
+
description = ""
|
|
576
|
+
owner = ""
|
|
577
|
+
tags = []
|
|
578
|
+
|
|
579
|
+
query = """
|
|
580
|
+
SELECT 1 AS value
|
|
581
|
+
"""
|
|
582
|
+
|
|
583
|
+
visualization {
|
|
584
|
+
chart = "table"
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
`}function il(e,t){if(!e)return[];const n=new Set,r=o=>{var i;const s=(i=o.meta)==null?void 0:i[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 cI(e,t){var T,S,f,A,O;const n=t.query.trim().toLowerCase(),r=Object.values(e.meta??{}).filter(I=>I!=null).map(I=>String(I).toLowerCase()),o=!n||e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)||r.some(I=>I.includes(n)),s=!t.type||e.kind===t.type||e.kind==="provider"||e.kind==="domain"||e.kind==="group",i=!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}`,c=!t.cube||((f=e.meta)==null?void 0:f.cube)===t.cube,E=!t.owner||((A=e.meta)==null?void 0:A.owner)===t.owner,d=!t.tag||String(((O=e.meta)==null?void 0:O.tags)??"").split(",").filter(Boolean).includes(t.tag),u=(e.children??[]).map(I=>cI(I,t)).filter(I=>!!I);return u.length>0?{...e,children:u,count:e.kind==="provider"||e.kind==="domain"||e.kind==="group"?u.length:e.count}:o&&s&&i&&l&&c&&E&&d?{...e,children:[]}:null}function EI(e,t,n=0){const r=[];for(const o of e){const s=!!(o.children&&o.children.length>0),i=t[o.id]??n<3;r.push({node:o,depth:n,hasChildren:s,isExpanded:i}),s&&i&&r.push(...EI(o.children??[],t,n+1))}return r}function dI(e,t,n){return e.map(r=>r.id===t?n:r.children?{...r,children:dI(r.children,t,n)}:r)}function n2(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)),i=(o.children??[]).map(l=>r(l)).filter(l=>!!l);return s||i.length>0?{...o,children:i}:null};return e.map(o=>r(o)).filter(o=>!!o)}function r2(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 i of s.children??[])o(i)};for(const s of e)o(s);return{schemas:t,tables:n,columns:r}}function o2(e){return!!(e&&e.children&&e.children.length>0)}function s2(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,i)=>{const l=n.get(s)??[];l.push(i),n.set(s,l)};for(const s of e.metrics){const i=s.domain||"uncategorized";r(i,{id:`metric:${s.name}`,label:s.label||s.name,kind:"metric",meta:{provider:t,domain:i,cube:s.table,owner:s.owner??"",tags:s.tags.join(",")}})}for(const s of e.dimensions){const i=s.domain||"uncategorized";r(i,{id:`dimension:${s.name}`,label:s.label||s.name,kind:"dimension",meta:{provider:t,domain:i,cube:s.table,owner:s.owner??"",tags:s.tags.join(",")}})}for(const s of e.hierarchies){const i=s.domain||"uncategorized";r(i,{id:`hierarchy:${s.name}`,label:s.label||s.name,kind:"hierarchy",meta:{provider:t,domain:i}})}const o=Array.from(n.entries()).sort((s,i)=>s[0].localeCompare(i[0])).map(([s,i])=>{const l=i.filter(u=>u.kind==="metric"),c=i.filter(u=>u.kind==="dimension"),E=i.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))}),c.length>0&&d.push({id:`group:${s}:dimensions`,label:"Dimensions",kind:"group",count:c.length,meta:{provider:t,domain:s},children:c.sort((u,T)=>u.label.localeCompare(T.label))}),E.length>0&&d.push({id:`group:${s}:hierarchies`,label:"Hierarchies",kind:"group",count:E.length,meta:{provider:t,domain:s},children:E.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 uI={source_table:"TABLE",dbt_model:"DBT",dbt_source:"SOURCE",block:"BLOCK",metric:"METRIC",dimension:"DIM",domain:"DOMAIN",chart:"CHART",dashboard:"NOTEBOOK"};function i2(e,t,n="flow",r="LR"){var i;const o=new Qs.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 c={width:190,height:58};if(n==="layered"&&((i=l.data)!=null&&i.layer)){const E=Ms.indexOf(l.data.layer);E>=0&&(c.rank=E)}o.setNode(l.id,c)}for(const l of t)o.setEdge(l.source,l.target);return Qs.layout(o),e.map(l=>{const c=o.node(l.id);return{...l,position:{x:c.x-95,y:c.y-29},data:{...l.data,direction:r}}})}function a2({data:e,selected:t}){const n=e.nodeType,r=we[n]??"#8b949e",o=uI[n]??n.toUpperCase(),s=e.direction??"LR",i=s==="LR"?ee.Left:ee.Top,l=s==="LR"?ee.Right:ee.Bottom;return a.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:[a.jsx(tn,{type:"target",position:i,style:{width:7,height:7,background:r,border:"none"}}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[a.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.04em",color:"#0d1117",background:r,borderRadius:4,padding:"2px 6px"},children:o}),e.domain&&a.jsx("span",{style:{color:"#8b949e",fontSize:10},children:e.domain})]}),a.jsx("div",{style:{color:"#e6edf3",fontSize:11,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.label,children:e.label}),a.jsx("div",{style:{color:"#8b949e",fontSize:10,marginTop:3},children:Ii[n]??n}),a.jsx(tn,{type:"source",position:l,style:{width:7,height:7,background:r,border:"none"}})]})}const l2={dagNode:a2};function Yn({label:e,active:t,color:n,onClick:r}){return a.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 c2(){const{state:e,dispatch:t}=Te(),n=ce[e.themeMode],[r,o]=R.useState(!0),[s,i]=R.useState({nodes:[],edges:[]}),[l,c]=R.useState({nodes:[],edges:[]}),[E,d]=R.useState(null),[u,T]=R.useState(null),[S,f]=R.useState(""),[A,O]=R.useState([]),[I,p]=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"),[_,D,g]=ff([]),[b,y,M]=If([]),F=R.useCallback(async()=>{o(!0);const x=await Z.fetchLineage(),B={nodes:x.nodes??[],edges:x.edges??[]};i(B),c(B),o(!1)},[]);R.useEffect(()=>{F()},[F]),R.useEffect(()=>{let x=!1;if(S.trim().length<2){O([]);return}return Z.searchLineage(S.trim()).then(B=>{x||O(B.matches??[])}),()=>{x=!0}},[S]);const L=R.useMemo(()=>{const x=new Set(l.nodes.filter(B=>I[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,I]);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:Rc(H)}})),B=L.edges.map((H,W)=>({id:`edge-${W}-${H.source}-${H.target}-${H.type}`,source:H.source,target:H.target,style:{stroke:Ur[H.type]??"#8b949e",strokeWidth:1.6},markerEnd:{type:sr.ArrowClosed,color:Ur[H.type]??"#8b949e",width:12,height:12}}));D(i2(x,B,N,C)),y(B)},[L,N,C,y,D]);const v=R.useCallback(async x=>{const B=await Z.queryLineage({focus:x});c(B.graph??{nodes:[],edges:[]}),d(B.focalNode??null),T(B.focalNode??null),t({type:"SET_LINEAGE_FOCUS",nodeId:x}),f(""),O([])},[t]);R.useEffect(()=>{e.lineageFocusNodeId&&v(e.lineageFocusNodeId)},[v,e.lineageFocusNodeId]);const P=R.useCallback(()=>{c(s),d(null),T(null),t({type:"SET_LINEAGE_FOCUS",nodeId:null})},[t,s]),w=R.useCallback(async(x,B)=>{await v(B.id)},[v]),U=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?a.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"Loading lineage graph..."}):s.nodes.length===0?a.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"No lineage graph available yet."}):a.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",background:"#0d1117"},children:[a.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`,background:n.sidebarBg},children:[a.jsxs("div",{style:{display:"flex",gap:6,marginBottom:8,flexWrap:"wrap",alignItems:"center"},children:[a.jsxs("div",{style:{display:"flex",borderRadius:6,border:`1px solid ${n.headerBorder}`,overflow:"hidden"},children:[a.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"}),a.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"})]}),a.jsxs("div",{style:{display:"flex",borderRadius:6,border:`1px solid ${n.headerBorder}`,overflow:"hidden",marginRight:4},children:[a.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:[a.jsxs("svg",{width:"14",height:"10",viewBox:"0 0 14 10",fill:"none",children:[a.jsx("rect",{x:"0",y:"2",width:"4",height:"6",rx:"1",fill:"currentColor",opacity:"0.7"}),a.jsx("line",{x1:"4",y1:"5",x2:"10",y2:"5",stroke:"currentColor",strokeWidth:"1.2"}),a.jsx("path",{d:"M9 3l2 2-2 2",stroke:"currentColor",strokeWidth:"1.2",fill:"none"}),a.jsx("rect",{x:"10",y:"2",width:"4",height:"6",rx:"1",fill:"currentColor"})]}),"LR"]}),a.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:[a.jsxs("svg",{width:"10",height:"14",viewBox:"0 0 10 14",fill:"none",children:[a.jsx("rect",{x:"2",y:"0",width:"6",height:"4",rx:"1",fill:"currentColor",opacity:"0.7"}),a.jsx("line",{x1:"5",y1:"4",x2:"5",y2:"10",stroke:"currentColor",strokeWidth:"1.2"}),a.jsx("path",{d:"M3 9l2 2 2-2",stroke:"currentColor",strokeWidth:"1.2",fill:"none"}),a.jsx("rect",{x:"2",y:"10",width:"6",height:"4",rx:"1",fill:"currentColor"})]}),"TB"]})]}),a.jsx(Yn,{label:"Tables",active:I.source_table,color:we.source_table,onClick:()=>p(x=>({...x,source_table:!x.source_table}))}),a.jsx(Yn,{label:"dbt Models",active:I.dbt_model,color:we.dbt_model,onClick:()=>p(x=>({...x,dbt_model:!x.dbt_model}))}),a.jsx(Yn,{label:"dbt Sources",active:I.dbt_source,color:we.dbt_source,onClick:()=>p(x=>({...x,dbt_source:!x.dbt_source}))}),a.jsx(Yn,{label:"DQL Blocks",active:I.block,color:we.block,onClick:()=>p(x=>({...x,block:!x.block}))}),a.jsx(Yn,{label:"Notebooks",active:I.dashboard,color:we.dashboard,onClick:()=>p(x=>({...x,dashboard:!x.dashboard}))}),a.jsx(Yn,{label:"Domains",active:I.domain,color:we.domain,onClick:()=>p(x=>({...x,domain:!x.domain}))})]}),a.jsxs("div",{style:{display:"flex",gap:8},children:[a.jsx("input",{value:S,onChange:x=>f(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"}}),E&&a.jsx("button",{onClick:P,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"})]}),a.jsx("div",{style:{marginTop:8,color:n.textMuted,fontSize:11,lineHeight:1.5},children:"This graph connects raw source tables and dbt DAGs to DQL blocks and the notebooks that consume them. Search to focus on a single path instead of scanning the full project graph."}),A.length>0&&a.jsx("div",{style:{marginTop:8,border:`1px solid ${n.headerBorder}`,borderRadius:8,overflow:"hidden"},children:A.slice(0,8).map(x=>a.jsxs("button",{onClick:()=>void v(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:[a.jsx("span",{style:{color:we[x.node.type]??"#8b949e",fontSize:10,fontWeight:700,marginRight:8},children:uI[x.node.type]??x.node.type.toUpperCase()}),x.node.name]},x.node.id))})]}),a.jsx("div",{style:{flex:1,position:"relative"},children:a.jsxs(Af,{nodes:_,edges:b,onNodesChange:g,onEdgesChange:M,onNodeClick:w,nodeTypes:l2,fitView:!0,fitViewOptions:{padding:.18},proOptions:{hideAttribution:!0},style:{background:"#0d1117"},children:[a.jsx(Nf,{color:"#21262d",gap:24,size:1}),a.jsx(_1,{showInteractive:!1}),a.jsx(G1,{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"}}),a.jsx(Er,{position:"top-left",children:a.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:[a.jsx("div",{style:{fontWeight:700,marginBottom:4},children:E?E.name:"Full Lineage View"}),a.jsxs("div",{style:{color:"#8b949e",fontSize:11},children:[l.nodes.length," node(s), ",l.edges.length," edge(s)"]}),a.jsx("div",{style:{color:"#8b949e",fontSize:11,marginTop:6,lineHeight:1.5},children:E?`Focused on ${Ii[E.type]??E.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&&U&&a.jsxs("div",{style:{marginTop:8,color:"#8b949e",fontSize:11},children:[U.incoming," upstream, ",U.outgoing," downstream"]})]})}),a.jsx(Er,{position:"bottom-left",children:a.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(Ur).map(([x,B])=>a.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[a.jsx("span",{style:{width:10,height:2,background:B,display:"inline-block"}}),ML[x]??x]},x))})})]})})]})}function E2(){const{state:e,dispatch:t}=Te(),{executeAll:n}=Oi();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])}function d2(){const{state:e,dispatch:t}=Te(),n=ce[e.themeMode],r=R.useRef({}),[o,s]=R.useState(!1);E2(),R.useEffect(()=>{const c=E=>{(E.metaKey||E.ctrlKey)&&E.key.toLowerCase()==="k"&&!E.shiftKey&&(E.preventDefault(),s(d=>!d)),(E.metaKey||E.ctrlKey)&&E.shiftKey&&E.key.toLowerCase()==="i"&&(E.preventDefault(),t({type:"TOGGLE_INSPECTOR"}))};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[t]);const i=R.useCallback(async c=>{try{if(c.type==="block"){const T=await Z.openBlockStudio(c.path);t({type:"OPEN_BLOCK_STUDIO",file:c,payload:T});return}const{content:E}=await Z.readNotebook(c.path),{title:d,cells:u}=WL(c.path,E);t({type:"OPEN_FILE",file:c,cells:u,title:d}),e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"})}catch(E){if(console.error("Failed to open file:",E),c.type==="block")try{const{content:d}=await Z.readNotebook(c.path);t({type:"OPEN_BLOCK_STUDIO",file:c,payload:{path:c.path,source:d,companionPath:null,metadata:{name:c.name.replace(/\.dql$/i,""),path:c.path,domain:c.path.split("/").slice(1,-1).join("/")||"uncategorized",description:"",owner:"",tags:[]},validation:{valid:!1,diagnostics:[{severity:"warning",message:"Opened block without studio metadata. Save once to normalize it."}],semanticRefs:{metrics:[],dimensions:[],segments:[]}}}});return}catch(d){console.error("Failed to open block fallback:",d)}else t({type:"OPEN_FILE",file:c,cells:[Ve("sql")],title:c.name})}},[t,e.sidebarPanel]);R.useCallback(c=>{const E=r.current[c];E&&E.scrollIntoView({behavior:"smooth",block:"start"})},[]);const l=R.useCallback((c,E)=>{E?r.current[c]=E:delete r.current[c]},[]);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100vh",width:"100vw",background:n.appBg,fontFamily:n.font,color:n.textPrimary,overflow:"hidden"},children:[a.jsx(S_,{}),a.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[a.jsx(tL,{}),e.sidebarOpen&&a.jsx(GL,{onOpenFile:i}),a.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:e.lineageFullscreen?a.jsx(c2,{}):e.mainView==="connection"?a.jsx(iT,{title:"Connections",description:"Manage database connections, edit driver settings, and test connectivity in a full-page workspace.",children:a.jsx(cR,{})}):e.mainView==="reference"?a.jsx(iT,{title:"Quick Reference",description:"Browse the complete DQL guide, semantic workflows, and authoring patterns in a documentation-style view.",children:a.jsx(ER,{themeMode:e.themeMode})}):a.jsx(a.Fragment,{children:e.mainView==="block_studio"?a.jsx(WH,{}):a.jsxs(a.Fragment,{children:[a.jsx(PH,{onOpenFile:i,registerCellRef:l}),a.jsx(I_,{})]})})}),e.inspectorOpen&&!e.lineageFullscreen&&!e.dashboardMode&&a.jsx(Gm,{})]}),e.newNotebookModalOpen&&a.jsx(BH,{onFileOpened:i}),e.newBlockModalOpen&&a.jsx(HH,{onFileOpened:i}),a.jsx(Bm,{open:o,onClose:()=>s(!1)})]})}function iT({title:e,description:t,children:n}){return a.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden"},children:[a.jsxs("div",{style:{padding:"18px 24px 12px",borderBottom:"1px solid rgba(127, 127, 127, 0.16)"},children:[a.jsx("div",{style:{fontSize:22,fontWeight:700},children:e}),a.jsx("div",{style:{fontSize:13,opacity:.72,marginTop:6,maxWidth:760,lineHeight:1.5},children:t})]}),a.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:n})]})}function u2(){const{state:e,dispatch:t}=Te(),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",i=>{try{const l=JSON.parse(i.data);(l.type==="file-added"||l.type==="file-deleted")&&Z.listNotebooks().then(c=>{t({type:"SET_FILES",files:c})}),l.type==="file-changed"&&Z.listNotebooks().then(c=>{t({type:"SET_FILES",files:c})}),l.type==="semantic-reload"&&(t({type:"SET_SEMANTIC_LOADING",loading:!0}),Z.getSemanticLayer().then(c=>{t({type:"SET_SEMANTIC_LAYER",layer:c})}))}catch{}}),s.addEventListener("error",()=>{s.close(),setTimeout(o,5e3)})};return o(),()=>{var s;(s=r.current)==null||s.close(),r.current=null}},[t])}function T2(){const{state:e,dispatch:t}=Te(),n=ce[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=`
|
|
588
|
+
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
589
|
+
body {
|
|
590
|
+
font-family: ${n.font};
|
|
591
|
+
overflow: hidden;
|
|
592
|
+
background: ${n.appBg};
|
|
593
|
+
color: ${n.textPrimary};
|
|
594
|
+
}
|
|
595
|
+
::-webkit-scrollbar { width: 6px; height: 6px; }
|
|
596
|
+
::-webkit-scrollbar-track { background: transparent; }
|
|
597
|
+
::-webkit-scrollbar-thumb {
|
|
598
|
+
background: ${n.scrollbarThumb};
|
|
599
|
+
border-radius: 3px;
|
|
600
|
+
}
|
|
601
|
+
::-webkit-scrollbar-thumb:hover {
|
|
602
|
+
background: ${n.textMuted};
|
|
603
|
+
}
|
|
604
|
+
::selection {
|
|
605
|
+
background: ${n.accent}40;
|
|
606
|
+
color: ${n.textPrimary};
|
|
607
|
+
}
|
|
608
|
+
`},[n]),R.useEffect(()=>{t({type:"SET_FILES_LOADING",loading:!0}),Z.listNotebooks().then(r=>{t({type:"SET_FILES",files:r}),t({type:"SET_FILES_LOADING",loading:!1})})},[t]),R.useEffect(()=>{t({type:"SET_SCHEMA_LOADING",loading:!0}),Z.getSchema().then(r=>{t({type:"SET_SCHEMA",tables:r}),t({type:"SET_SCHEMA_LOADING",loading:!1})})},[t]),u2(),a.jsx(TO,{theme:e.themeMode,applyGlobal:!0,children:a.jsx(Lp,{delayDuration:200,skipDelayDuration:400,children:a.jsx(d2,{})})})}function S2(){return a.jsx(Um,{children:a.jsx(T2,{})})}lO.createRoot(document.getElementById("root")).render(a.jsx(S2,{}));
|