@duckcodeailabs/dql-cli 0.8.5 → 0.8.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -4
- package/dist/args.d.ts +1 -0
- package/dist/args.d.ts.map +1 -1
- package/dist/args.js +4 -0
- package/dist/args.js.map +1 -1
- package/dist/assets/dql-notebook/assets/index-CTmiMNUc.js +558 -0
- package/dist/assets/dql-notebook/index.html +1 -1
- package/dist/block-templates.d.ts +8 -0
- package/dist/block-templates.d.ts.map +1 -0
- package/dist/block-templates.js +60 -0
- package/dist/block-templates.js.map +1 -0
- package/dist/commands/build.test.js +1 -1
- package/dist/commands/build.test.js.map +1 -1
- package/dist/commands/doctor.d.ts.map +1 -1
- package/dist/commands/doctor.js +17 -1
- package/dist/commands/doctor.js.map +1 -1
- package/dist/commands/doctor.test.js +1 -1
- package/dist/commands/doctor.test.js.map +1 -1
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +73 -5
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/init.test.js +82 -2
- package/dist/commands/init.test.js.map +1 -1
- package/dist/commands/new.test.js +7 -7
- package/dist/commands/new.test.js.map +1 -1
- package/dist/commands/notebook.d.ts.map +1 -1
- package/dist/commands/notebook.js +2 -2
- package/dist/commands/notebook.js.map +1 -1
- package/dist/commands/semantic.d.ts +2 -0
- package/dist/commands/semantic.d.ts.map +1 -1
- package/dist/commands/semantic.js +115 -1
- package/dist/commands/semantic.js.map +1 -1
- package/dist/index.js +18 -0
- package/dist/index.js.map +1 -1
- package/dist/local-runtime.d.ts +35 -0
- package/dist/local-runtime.d.ts.map +1 -1
- package/dist/local-runtime.js +1668 -45
- package/dist/local-runtime.js.map +1 -1
- package/dist/local-runtime.test.js +69 -1
- package/dist/local-runtime.test.js.map +1 -1
- package/dist/semantic-import.d.ts +127 -0
- package/dist/semantic-import.d.ts.map +1 -0
- package/dist/semantic-import.js +713 -0
- package/dist/semantic-import.js.map +1 -0
- package/dist/semantic-import.test.d.ts +2 -0
- package/dist/semantic-import.test.d.ts.map +1 -0
- package/dist/semantic-import.test.js +278 -0
- package/dist/semantic-import.test.js.map +1 -0
- package/package.json +8 -7
- package/dist/assets/dql-notebook/assets/index-Rushqlh8.js +0 -524
|
@@ -1,524 +0,0 @@
|
|
|
1
|
-
import{r as gr,a as fa,g as As}from"./react-CRB3T2We.js";import{S as Mr,g as ha,E as Be,s as CR,a as Ce,b as Ca,c as LR,P as pR,d as _R,e as mR,F as DR,f as gR,h as La,V as MR,D as Rt,R as xR,i as PR,C as rt,j as pa,k as Me,r as yR,l as UR,m as bR,t as vR,n as BR,o as GR,p as HR,q as FR,u as wR,v as YR,w as Bn,x as VR,y as WR,z as kR,A as jR,B as XR,G as $R,H as KR,I as zR,J as JR,K as qR,L as ZR}from"./codemirror-CCrEt63p.js";(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 zr={exports:{}},Zt={};/**
|
|
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 Qs;function QR(){if(Qs)return Zt;Qs=1;var e=gr(),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(a,T,l){var R,c={},S=null,A=null;l!==void 0&&(S=""+l),T.key!==void 0&&(S=""+T.key),T.ref!==void 0&&(A=T.ref);for(R in T)r.call(T,R)&&!s.hasOwnProperty(R)&&(c[R]=T[R]);if(a&&a.defaultProps)for(R in T=a.defaultProps,T)c[R]===void 0&&(c[R]=T[R]);return{$$typeof:t,type:a,key:S,ref:A,props:c,_owner:o.current}}return Zt.Fragment=n,Zt.jsx=i,Zt.jsxs=i,Zt}var ei;function eS(){return ei||(ei=1,zr.exports=QR()),zr.exports}var E=eS(),Gn={},ti;function tS(){if(ti)return Gn;ti=1;var e=fa();return Gn.createRoot=e.createRoot,Gn.hydrateRoot=e.hydrateRoot,Gn}var nS=tS(),h=gr();const Bt=As(h),rS={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:[],loading:!1},devPanelOpen:!1,devPanelTab:"logs",queryLog:[],newNotebookModalOpen:!1,newBlockModalOpen:!1,autoSave:!1,executionCounter:0,savingFile:!1,lineageFullscreen:!1,dashboardMode:!1};function oS(e,t){switch(t.type){case"SET_THEME":return{...e,themeMode:t.mode};case"SET_SIDEBAR_PANEL":return{...e,sidebarPanel:t.panel,sidebarOpen:t.panel!==null};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};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 n=e.cells.findIndex(o=>o.id===t.afterId);if(n===-1)return{...e,cells:[...e.cells,t.cell],notebookDirty:!0};const r=[...e.cells];return r.splice(n+1,0,t.cell),{...e,cells:r,notebookDirty:!0}}case"UPDATE_CELL":{const n=e.cells.map(o=>o.id===t.id?{...o,...t.updates}:o),r=t.updates.executionCount!==void 0?e.executionCounter+1:e.executionCounter;return{...e,cells:n,notebookDirty:!0,executionCounter:r}}case"DELETE_CELL":return{...e,cells:e.cells.filter(n=>n.id!==t.id),notebookDirty:!0};case"MOVE_CELL":{const n=e.cells.findIndex(o=>o.id===t.id);if(n===-1)return e;const r=[...e.cells];return t.direction==="up"&&n>0?[r[n-1],r[n]]=[r[n],r[n-1]]:t.direction==="down"&&n<r.length-1&&([r[n],r[n+1]]=[r[n+1],r[n]]),{...e,cells:r,notebookDirty:!0}}case"REORDER_CELL":{const{fromIndex:n,toIndex:r}=t;if(n===r||n<0||r<0||n>=e.cells.length||r>=e.cells.length)return e;const o=[...e.cells],[s]=o.splice(n,1);return o.splice(r,0,s),{...e,cells:o,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(n=>n.name===t.tableName?{...n,expanded:!n.expanded}:n)};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(n=>n.name===t.tableName?{...n,columns:t.columns}:n)};case"SET_PARAM_VALUE":return{...e,cells:e.cells.map(n=>n.id===t.id?{...n,paramValue:t.value}:n),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"TOGGLE_LINEAGE_FULLSCREEN":return{...e,lineageFullscreen:!e.lineageFullscreen};case"TOGGLE_DASHBOARD_MODE":return{...e,dashboardMode:!e.dashboardMode};default:return e}}const _a=h.createContext(null);function sS({children:e}){const[t,n]=h.useReducer(oS,rS);return E.jsx(_a.Provider,{value:{state:t,dispatch:n},children:e})}function ae(){const e=h.useContext(_a);if(!e)throw new Error("useNotebook must be used within NotebookProvider");return e}function ze(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Le(e,t=""){const n={id:ze(),type:e,content:t,status:"idle"};return e==="param"&&(n.content="",n.paramConfig={paramType:"text",label:"Parameter",defaultValue:"",options:[]}),n}const iS={appBg:"#0d1117",sidebarBg:"#161b22",activityBarBg:"#0d1117",headerBg:"#161b22",headerBorder:"#21262d",cellBg:"#161b22",cellBorder:"#30363d",cellBorderActive:"#388bfd",cellBorderRunning:"#56d364",textPrimary:"#e6edf3",textSecondary:"#8b949e",textMuted:"#484f58",editorBg:"#0d1117",editorBorder:"#30363d",tableBorder:"#30363d",tableHeaderBg:"#1c2128",tableRowHover:"#21262d",accent:"#388bfd",accentHover:"#58a6ff",success:"#56d364",error:"#f85149",warning:"#e3b341",btnBg:"#21262d",btnBorder:"#30363d",btnHover:"#30363d",sidebarItemHover:"#21262d",sidebarItemActive:"#1f2d3d",scrollbarThumb:"#30363d",modalBg:"#161b22",modalOverlay:"rgba(0,0,0,0.7)",inputBg:"#0d1117",inputBorder:"#30363d",pillBg:"#21262d",font:"Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontMono:"'JetBrains Mono', 'Fira Code', Consolas, monospace",fontSerif:"Georgia, 'Times New Roman', serif"},ES={appBg:"#ffffff",sidebarBg:"#f6f8fa",activityBarBg:"#eff1f3",headerBg:"#ffffff",headerBorder:"#d0d7de",cellBg:"#ffffff",cellBorder:"#d0d7de",cellBorderActive:"#0969da",cellBorderRunning:"#1f883d",textPrimary:"#1f2328",textSecondary:"#57606a",textMuted:"#8c959f",editorBg:"#f6f8fa",editorBorder:"#d0d7de",tableBorder:"#d0d7de",tableHeaderBg:"#f6f8fa",tableRowHover:"#f6f8fa",accent:"#0969da",accentHover:"#0550ae",success:"#1f883d",error:"#cf222e",warning:"#9a6700",btnBg:"#f6f8fa",btnBorder:"#d0d7de",btnHover:"#eaeef2",sidebarItemHover:"#eaeef2",sidebarItemActive:"#dbeafe",scrollbarThumb:"#d0d7de",modalBg:"#ffffff",modalOverlay:"rgba(0,0,0,0.4)",inputBg:"#ffffff",inputBorder:"#d0d7de",pillBg:"#eaeef2",font:"Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontMono:"'JetBrains Mono', 'Fira Code', Consolas, monospace",fontSerif:"Georgia, 'Times New Roman', serif"},re={dark:iS,light:ES};function je({title:e,active:t,onClick:n,children:r,t:o}){const[s,i]=h.useState(!1);return E.jsx("button",{title: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 aS(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 lS(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 TS(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M8 1.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm6.5-2a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Zm-2 4.5a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Zm5 0a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Z"})})}function cS(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 RS(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M2 2h12a1 1 0 0 1 0 2H2a1 1 0 0 1 0-2Zm0 4h8a1 1 0 0 1 0 2H2a1 1 0 0 1 0-2Zm0 4h10a1 1 0 0 1 0 2H2a1 1 0 0 1 0-2Z"})})}function SS(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 AS(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 dS(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 uS(){return E.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.103-.303c.644-.176 1.392.021 1.82.63.27.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 IS(){const{state:e,dispatch:t}=ae(),n=re[e.themeMode];function r(o){e.sidebarPanel===o&&e.sidebarOpen?t({type:"TOGGLE_SIDEBAR"}):t({type:"SET_SIDEBAR_PANEL",panel:o})}return E.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:[E.jsx(je,{title:"Files",active:e.sidebarPanel==="files"&&e.sidebarOpen,onClick:()=>r("files"),t:n,children:E.jsx(aS,{})}),E.jsx(je,{title:"Schema",active:e.sidebarPanel==="schema"&&e.sidebarOpen,onClick:()=>r("schema"),t:n,children:E.jsx(lS,{})}),E.jsx(je,{title:"Semantic Layer",active:e.sidebarPanel==="semantic"&&e.sidebarOpen,onClick:()=>r("semantic"),t:n,children:E.jsx(TS,{})}),E.jsx(je,{title:"Lineage",active:e.sidebarPanel==="lineage"&&e.sidebarOpen,onClick:()=>r("lineage"),t:n,children:E.jsx(cS,{})}),E.jsx(je,{title:"Outline",active:e.sidebarPanel==="outline"&&e.sidebarOpen,onClick:()=>r("outline"),t:n,children:E.jsx(RS,{})}),E.jsx(je,{title:"Connection",active:e.sidebarPanel==="connection"&&e.sidebarOpen,onClick:()=>r("connection"),t:n,children:E.jsx(SS,{})}),E.jsx(je,{title:"Reference",active:e.sidebarPanel==="reference"&&e.sidebarOpen,onClick:()=>r("reference"),t:n,children:E.jsx(AS,{})}),E.jsx("div",{style:{flex:1}}),E.jsx(je,{title:"Help & Reference",active:e.sidebarPanel==="reference"&&e.sidebarOpen,onClick:()=>r("reference"),t:n,children:E.jsx(dS,{})}),E.jsx(je,{title:"Settings",active:!1,onClick:()=>{},t:n,children:E.jsx(uS,{})})]})}const Jr={notebooks:"Notebooks",workbooks:"Workbooks",blocks:"Blocks",dashboards:"Dashboards"};function NS({type:e}){switch(e){case"notebook":return E.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 E.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 E.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 E.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 OS({expanded:e}){return E.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",children:e?E.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"}):E.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 fS(e){return e.name.replace(/\.(dqlnb|dql)$/,"")}function hS({onOpenFile:e}){const{state:t,dispatch:n}=ae(),r=re[t.themeMode],[o,s]=h.useState({notebooks:!0,workbooks:!0,blocks:!1,dashboards:!1}),[i,a]=h.useState(!1),T={notebooks:[],workbooks:[],blocks:[],dashboards:[]};for(const R of t.files){const c=R.folder.toLowerCase();c in T&&T[c].push(R)}const l=R=>{s(c=>({...c,[R]:!c[R]}))};return E.jsxs("div",{style:{flex:1,overflow:"auto",padding:"8px 0",display:"flex",flexDirection:"column",gap:0},children:[E.jsx("div",{style:{padding:"0 8px 8px"},children:E.jsxs("button",{onClick:()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!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:[E.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"New Notebook"]})}),t.filesLoading&&E.jsx("div",{style:{padding:"8px 14px",color:r.textMuted,fontSize:12,fontFamily:r.font},children:"Loading files…"}),Object.keys(Jr).map(R=>{const c=T[R],S=o[R],A=R==="notebooks"?()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}):R==="blocks"?()=>n({type:"OPEN_NEW_BLOCK_MODAL"}):void 0;return E.jsxs("div",{children:[E.jsx(CS,{label:Jr[R],count:c.length,expanded:S,onToggle:()=>l(R),onAdd:A,t:r}),S&&E.jsx("div",{children:c.length===0?E.jsxs("div",{style:{padding:"4px 14px 4px 32px",fontSize:12,color:r.textMuted,fontFamily:r.font,fontStyle:"italic"},children:["No ",Jr[R].toLowerCase()]}):c.map(d=>{var N;return E.jsx(LS,{file:d,active:((N=t.activeFile)==null?void 0:N.path)===d.path,onClick:()=>e(d),t:r},d.path)})})]},R)})]})}function CS({label:e,count:t,expanded:n,onToggle:r,onAdd:o,t:s}){const[i,a]=h.useState(!1),[T,l]=h.useState(!1);return E.jsxs("div",{onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{display:"flex",alignItems:"center",background:i?s.sidebarItemHover:"transparent",transition:"background 0.1s"},children:[E.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:[E.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:E.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),E.jsx(OS,{expanded:n}),E.jsx("span",{style:{flex:1},children:e}),t>0&&E.jsx("span",{style:{background:s.pillBg,color:s.textMuted,borderRadius:10,padding:"0 5px",fontSize:10,fontWeight:500},children:t})]}),o&&i&&E.jsx("button",{onClick:R=>{R.stopPropagation(),o()},onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),title:`New ${e.slice(0,-1)}`,style:{background:T?s.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:T?s.accent:s.textMuted,fontSize:14,lineHeight:1,padding:"2px 8px",marginRight:4,flexShrink:0,transition:"color 0.1s"},children:"+"})]})}function LS({file:e,active:t,onClick:n,t:r}){const[o,s]=h.useState(!1);return E.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:[E.jsx("span",{style:{flexShrink:0,color:t?r.accent:r.textMuted},children:E.jsx(NS,{type:e.type})}),E.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:fS(e)}),e.isNew&&E.jsx("span",{style:{fontSize:9,fontWeight:600,color:r.accent,background:r.sidebarItemActive,borderRadius:4,padding:"1px 4px",flexShrink:0},children:"NEW"})]})}const pS=window.location.origin;async function Ie(e,t){const n=await fetch(`${pS}${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 le={async listNotebooks(){try{return await Ie("/api/notebooks")}catch{return[]}},async readNotebook(e){return Ie(`/api/notebook-content?path=${encodeURIComponent(e)}`)},async createNotebook(e,t){return Ie("/api/notebooks",{method:"POST",body:JSON.stringify({name:e,template:t})})},async createBlock(e){return Ie("/api/blocks",{method:"POST",body:JSON.stringify({name:e})})},async saveNotebook(e,t){return Ie("/api/notebook-content",{method:"PUT",body:JSON.stringify({path:e,content:t})})},async executeQuery(e,t){var o;const n=await Ie("/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 Ie("/api/schema")}catch{return[]}},async getConnections(){try{return await Ie("/api/connections")}catch{return{default:"unknown",connections:{}}}},async saveConnections(e){return Ie("/api/connections",{method:"PUT",body:JSON.stringify({connections:e})})},async testConnection(){try{return await Ie("/api/test-connection",{method:"POST",body:JSON.stringify({})})}catch(e){return{ok:!1,message:e.message??"Connection failed"}}},async getSemanticLayer(){try{return await Ie("/api/semantic-layer")}catch{return{available:!1,provider:null,metrics:[],dimensions:[],hierarchies:[]}}},async composeQuery(e,t,n){try{return await Ie("/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 createMetric(e){try{return await Ie("/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=/\.(csv|parquet|json)$/i.test(e)||e.startsWith("data/"),n=e.replace(/'/g,"''"),r=t?`DESCRIBE SELECT * FROM read_csv_auto('${n}') LIMIT 0`:`DESCRIBE "${n}"`;try{return(await Ie("/api/query",{method:"POST",body:JSON.stringify({sql:r})})).rows.map(s=>({name:String(s.column_name??s.Field??""),type:String(s.column_type??s.Type??"")}))}catch{return[]}},async fetchLineage(){try{return await Ie("/api/lineage")}catch{return{nodes:[],edges:[]}}},async fetchBlockLineage(e){try{return await Ie(`/api/lineage/block/${encodeURIComponent(e)}`)}catch{return null}},async fetchImpactAnalysis(e){try{return await Ie(`/api/lineage/impact/${encodeURIComponent(e)}`)}catch{return null}}},_S={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 ni(e,t){const n=e.toLowerCase().split("(")[0].trim();return _S[n]??t}function mS({t:e}){return E.jsxs("div",{style:{padding:"8px 12px",display:"flex",flexDirection:"column",gap:8},children:[[1,2,3].map(t=>E.jsx("div",{style:{height:28,borderRadius:4,background:e.pillBg,opacity:.6,animation:"pulse 1.5s ease-in-out infinite"}},t)),E.jsx("style",{children:"@keyframes pulse { 0%,100%{opacity:.6} 50%{opacity:.3} }"})]})}function DS(){const{state:e,dispatch:t}=ae(),n=re[e.themeMode],[r,o]=h.useState(!1),s=async()=>{t({type:"SET_SCHEMA_LOADING",loading:!0});try{const i=await le.getSchema();t({type:"SET_SCHEMA",tables:i})}catch(i){console.error("Schema refresh failed:",i)}finally{t({type:"SET_SCHEMA_LOADING",loading:!1})}};return E.jsxs("div",{style:{flex:1,overflow:"auto",display:"flex",flexDirection:"column"},children:[E.jsxs("div",{style:{padding:"8px 10px",display:"flex",alignItems:"center",gap:6,borderBottom:`1px solid ${n.headerBorder}`},children:[E.jsxs("span",{style:{flex:1,fontSize:11,color:n.textMuted,fontFamily:n.font},children:[e.schemaTables.length," tables"]}),E.jsxs("button",{onClick:s,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),title:"Refresh schema",style:{background:r?n.btnHover:"transparent",border:`1px solid ${r?n.btnBorder:"transparent"}`,borderRadius:4,cursor:"pointer",color:r?n.textSecondary:n.textMuted,fontSize:11,fontFamily:n.font,padding:"2px 6px",display:"flex",alignItems:"center",gap:4,transition:"all 0.15s"},children:[E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:E.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"]})]}),e.schemaLoading?E.jsx(mS,{t:n}):e.schemaTables.length===0?E.jsxs("div",{style:{padding:"24px 14px",color:n.textMuted,fontSize:12,fontFamily:n.font,textAlign:"center",fontStyle:"italic"},children:["No tables found.",E.jsx("br",{}),"Connect a data source to explore schema."]}):E.jsx("div",{style:{overflow:"auto",flex:1},children:e.schemaTables.map(i=>E.jsx(gS,{table:i,t:n},i.name))})]})}function gS({table:e,t}){var T;const{dispatch:n}=ae(),[r,o]=h.useState(!1),[s,i]=h.useState(!1),a=async()=>{if(n({type:"TOGGLE_SCHEMA_TABLE",tableName:e.name}),!e.expanded&&e.columns.length===0){i(!0);try{const l=await le.describeTable(e.path);l.length>0&&n({type:"SET_TABLE_COLUMNS",tableName:e.name,columns:l})}catch(l){console.error("describeTable failed:",l)}finally{i(!1)}}};return E.jsxs("div",{children:[E.jsxs("button",{onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onClick:a,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:[E.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:E.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),e.source==="database"?E.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",style:{color:"#56d364",flexShrink:0},children:E.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"})}):E.jsx("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"currentColor",style:{color:t.accent,flexShrink:0},children:E.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"})}),E.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),((T=e.governance)==null?void 0:T.status)&&E.jsx(PS,{status:e.governance.status,t}),e.columns.length>0&&E.jsx("span",{style:{fontSize:10,color:t.textMuted,background:t.pillBg,borderRadius:8,padding:"1px 5px",flexShrink:0},children:e.columns.length})]}),e.expanded&&E.jsxs("div",{style:{paddingLeft:26},children:[e.governance&&(e.governance.owner||e.governance.domain)&&E.jsxs("div",{style:{padding:"3px 10px",display:"flex",gap:8,flexWrap:"wrap"},children:[e.governance.domain&&E.jsxs("span",{style:{fontSize:9,fontFamily:t.font,color:t.textMuted},children:[E.jsx("span",{style:{fontWeight:600},children:"domain:"})," ",e.governance.domain]}),e.governance.owner&&E.jsxs("span",{style:{fontSize:9,fontFamily:t.font,color:t.textMuted},children:[E.jsx("span",{style:{fontWeight:600},children:"owner:"})," ",e.governance.owner]})]}),s?E.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:"..."}):e.columns.length===0?E.jsx("div",{style:{padding:"4px 10px",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:"No columns"}):e.columns.map(l=>E.jsx(MS,{col:l,t},l.name))]})]})}function MS({col:e,t}){const[n,r]=h.useState(!1);return E.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:[E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",style:{color:t.textMuted,flexShrink:0},children:E.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"})}),E.jsx("span",{style:{flex:1,fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),E.jsx("span",{style:{fontSize:10,fontFamily:t.fontMono,color:ni(e.type,t.accent),background:`${ni(e.type,t.accent)}18`,borderRadius:4,padding:"1px 5px",flexShrink:0},children:e.type.toLowerCase()})]})}const xS={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 PS({status:e,t}){const n=xS[e];return n?E.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}function yS(e){if(e.type==="markdown"){const t=e.content.match(/^#{1,6}\s+(.+)$/m);if(t)return t[1];const n=e.content.split(`
|
|
10
|
-
`).find(r=>r.trim());return(n==null?void 0:n.trim())||null}return e.name?e.name:null}function ma(e){if(e.type!=="markdown")return 0;const t=e.content.match(/^(#{1,6})\s/m);return t?t[1].length:0}function US({cell:e,t}){if(e.type==="markdown")return E.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",style:{color:t.textMuted,flexShrink:0},children:[E.jsx("path",{d:"M14.85 3H7.39L6.74.translateX(.5.25C6.45.11 6.23 0 6 0H1.75A1.75 1.75 0 0 0 0 1.75v12.5C0 15.216.784 16 1.75 16h12.5A1.75 1.75 0 0 0 16 14.25V4.75A1.75 1.75 0 0 0 14.25 3ZM1.5 1.75a.25.25 0 0 1 .25-.25H6l.5 1.5H1.5Z"}),E.jsx("path",{d:"M2 2h12v12H2z",fill:"none",stroke:"currentColor",strokeWidth:"1.5"})]});const n=e.type==="sql"?t.accent:t.warning;return E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",style:{color:n,flexShrink:0},children:E.jsx("path",{d:"M0 5.75C0 4.784.784 4 1.75 4h12.5c.966 0 1.75.784 1.75 1.75v4.5A1.75 1.75 0 0 1 14.25 12H1.75A1.75 1.75 0 0 1 0 10.25Zm1.75-.25a.25.25 0 0 0-.25.25v4.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-4.5a.25.25 0 0 0-.25-.25Z"})})}function bS({onNavigate:e}){const{state:t}=ae(),n=re[t.themeMode];if(!t.activeFile)return E.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:20,textAlign:"center"},children:E.jsxs("div",{children:[E.jsx("svg",{width:"32",height:"32",viewBox:"0 0 16 16",fill:"currentColor",style:{color:n.textMuted,marginBottom:8},children:E.jsx("path",{d:"M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25ZM1.75 1.5a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25ZM3.5 6.25a.75.75 0 0 1 .75-.75h7a.75.75 0 0 1 0 1.5h-7a.75.75 0 0 1-.75-.75Zm.75 2.25h4a.75.75 0 0 1 0 1.5h-4a.75.75 0 0 1 0-1.5Z"})}),E.jsx("div",{style:{fontSize:12,color:n.textMuted,fontFamily:n.font,lineHeight:1.5},children:"Open a notebook to see its outline."})]})});const r=t.cells.map(o=>({cell:o,label:yS(o)})).filter(o=>o.label!==null);return r.length===0?E.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:20,color:n.textMuted,fontSize:12,fontFamily:n.font,fontStyle:"italic",textAlign:"center"},children:["No named cells or headings yet.",E.jsx("br",{}),"Name your cells or add markdown headings."]}):E.jsx("div",{style:{flex:1,overflow:"auto",padding:"6px 0"},children:r.map(({cell:o,label:s})=>{const i=ma(o),a=o.type==="markdown"?Math.max(0,(i-1)*12):0;return E.jsx(vS,{cell:o,label:s,indent:a,onClick:()=>e(o.id),t:n},o.id)})})}function vS({cell:e,label:t,indent:n,onClick:r,t:o}){const[s,i]=h.useState(!1);return E.jsxs("button",{onClick:r,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:`4px 10px 4px ${14+n}px`,background:s?o.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:s?o.textPrimary:o.textSecondary,fontSize:12,fontFamily:e.type==="markdown"?o.font:o.fontMono,textAlign:"left",transition:"background 0.1s, color 0.1s",overflow:"hidden"},children:[E.jsx(US,{cell:e,t:o}),E.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,fontWeight:e.type==="markdown"&&ma(e)===1?600:400},children:t})]})}const $o={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"},ri={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"},BS={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"]};function GS(){const{state:e}=ae(),t=re[e.themeMode],[n,r]=h.useState(null),[o,s]=h.useState(!1),[i,a]=h.useState(null),[T,l]=h.useState(null),[R,c]=h.useState(!1),[S,A]=h.useState(!1),[d,N]=h.useState(null),[I,u]=h.useState(""),[f,O]=h.useState("duckdb"),[C,m]=h.useState({});h.useEffect(()=>{le.getConnections().then(r)},[]);const L=async()=>{s(!0),a(null);const P=await le.testConnection();a(P),s(!1)},D=(P,v)=>{l(P),c(!1),u(P),O((v==null?void 0:v.driver)??"duckdb");const b={};Object.entries(v??{}).forEach(([y,w])=>{y!=="driver"&&y!=="type"&&(b[y]=String(w??""))}),m(b)},M=()=>{c(!0),l(null),u(""),O("duckdb"),m({})},x=()=>{l(null),c(!1)},B=async()=>{if(!n)return;A(!0),N(null);const P=I.trim()||(T??"default"),v={driver:f};Object.entries(C).forEach(([y,w])=>{w.trim()&&(y==="port"&&!isNaN(Number(w))?v[y]=Number(w):v[y]=w)});const b={...n.connections};T&&T!==P&&delete b[T],b[P]=v;try{await le.saveConnections(b);const y=await le.getConnections();r(y),N("Saved"),setTimeout(()=>N(null),2e3),l(null),c(!1)}catch(y){N(`Error: ${y.message}`)}finally{A(!1)}},g=async P=>{if(!n)return;const v={...n.connections};delete v[P],A(!0);try{await le.saveConnections(v);const b=await le.getConnections();r(b),l(null)}finally{A(!1)}},p={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},_=(n==null?void 0:n.connections)??{},U=(n==null?void 0:n.default)??"";return E.jsxs("div",{style:{flex:1,overflow:"auto",padding:"12px 12px 20px"},children:[E.jsx("div",{style:p,children:"Connections"}),n===null?E.jsx("div",{style:{fontSize:12,color:t.textMuted,fontFamily:t.font},children:"Loading…"}):Object.entries(_).map(([P,v])=>{const b=(v==null?void 0:v.driver)??(v==null?void 0:v.type)??"unknown",y=P===U||Object.keys(_).length===1,w=ri[b]??t.accent;return T===P?E.jsx(oi,{t,editName:I,setEditName:u,editDriver:f,setEditDriver:O,editFields:C,setEditFields:m,onSave:B,onCancel:x,onDelete:()=>g(P),saving:S,isNew:!1},P):E.jsxs("div",{style:{...F,borderLeft:y?`3px solid ${w}`:`1px solid ${t.cellBorder}`},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[E.jsx("span",{style:{fontSize:10,fontWeight:700,fontFamily:t.fontMono,color:w,background:`${w}18`,border:`1px solid ${w}40`,borderRadius:4,padding:"1px 6px",letterSpacing:"0.05em",textTransform:"uppercase"},children:$o[b]??b}),E.jsx("span",{style:{fontSize:11,fontFamily:t.fontMono,color:t.textSecondary,fontWeight:500},children:P}),y&&E.jsx("span",{style:{fontSize:9,color:t.accent,fontFamily:t.font,fontWeight:600},children:"DEFAULT"}),E.jsx("div",{style:{flex:1}}),E.jsx("button",{onClick:()=>D(P,v),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"})]}),E.jsx("div",{style:{display:"flex",flexDirection:"column",gap:3},children:Object.entries(v??{}).filter(([H])=>H!=="driver"&&H!=="type").map(([H,Y])=>E.jsxs("div",{style:{display:"flex",gap:6,alignItems:"baseline"},children:[E.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.fontMono,minWidth:70,flexShrink:0},children:H}),E.jsx("span",{style:{fontSize:11,color:t.textSecondary,fontFamily:t.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:H.toLowerCase().includes("password")||H.toLowerCase().includes("token")?"••••••••":String(Y)})]},H))})]},P)}),R?E.jsx(oi,{t,editName:I,setEditName:u,editDriver:f,setEditDriver:O,editFields:C,setEditFields:m,onSave:B,onCancel:x,saving:S,isNew:!0}):E.jsxs("button",{onClick:M,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:[E.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"Add Connection"]}),d&&E.jsx("div",{style:{fontSize:11,fontFamily:t.font,padding:"4px 10px",borderRadius:4,marginBottom:8,color:d.startsWith("Error")?t.error:t.success,background:d.startsWith("Error")?`${t.error}12`:`${t.success}12`},children:d}),E.jsx("button",{onClick:L,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&&E.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]}),E.jsx("div",{style:{...p,marginTop:4},children:"Supported Drivers"}),E.jsx("div",{style:{...F,display:"flex",flexDirection:"column",gap:4},children:Object.entries($o).map(([P,v])=>E.jsxs("div",{style:{display:"flex",gap:8,alignItems:"baseline"},children:[E.jsx("code",{style:{fontSize:10,fontFamily:t.fontMono,color:ri[P]??t.textMuted,minWidth:80,flexShrink:0},children:P}),E.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font},children:v})]},P))})]})}function oi({t:e,editName:t,setEditName:n,editDriver:r,setEditDriver:o,editFields:s,setEditFields:i,onSave:a,onCancel:T,onDelete:l,saving:R,isNew:c}){const S=BS[r]??[],A={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%"},d={fontSize:9,fontWeight:600,color:e.textMuted,fontFamily:e.font,letterSpacing:"0.05em",textTransform:"uppercase",marginBottom:2};return E.jsxs("div",{style:{background:e.cellBg,border:`1px solid ${e.accent}40`,borderRadius:7,padding:"10px 12px",marginBottom:10},children:[E.jsx("div",{style:{fontSize:11,fontWeight:600,color:e.accent,fontFamily:e.font,marginBottom:8},children:c?"New Connection":"Edit Connection"}),E.jsxs("div",{style:{marginBottom:6},children:[E.jsx("div",{style:d,children:"Name"}),E.jsx("input",{style:A,value:t,onChange:N=>n(N.target.value),placeholder:"e.g. production"})]}),E.jsxs("div",{style:{marginBottom:6},children:[E.jsx("div",{style:d,children:"Driver"}),E.jsx("select",{style:{...A,fontFamily:e.font},value:r,onChange:N=>{o(N.target.value),i({})},children:Object.entries($o).map(([N,I])=>E.jsx("option",{value:N,children:I},N))})]}),S.map(N=>E.jsxs("div",{style:{marginBottom:6},children:[E.jsx("div",{style:d,children:N}),E.jsx("input",{style:A,type:N.toLowerCase().includes("password")||N.toLowerCase().includes("token")?"password":"text",value:s[N]??"",placeholder:N==="port"?"5432":N==="filepath"?":memory:":"",onChange:I=>i({...s,[N]:I.target.value})})]},N)),E.jsxs("div",{style:{display:"flex",gap:6,marginTop:8},children:[E.jsx("button",{onClick:a,disabled:R,style:{flex:1,padding:"5px 0",borderRadius:5,border:"none",background:e.accent,color:"#fff",fontSize:11,fontFamily:e.font,fontWeight:600,cursor:R?"not-allowed":"pointer",opacity:R?.6:1},children:R?"Saving…":"Save"}),E.jsx("button",{onClick:T,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"}),l&&!c&&E.jsx("button",{onClick:l,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 Xe({title:e,defaultOpen:t=!1,children:n,t:r}){const[o,s]=h.useState(t),[i,a]=h.useState(!1);return E.jsxs("div",{style:{borderBottom:`1px solid ${r.headerBorder}`},children:[E.jsxs("button",{onClick:()=>s(T=>!T),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!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:[E.jsx("span",{style:{fontSize:9,color:r.textMuted,display:"inline-block",transition:"transform 0.15s",transform:o?"rotate(90deg)":"rotate(0deg)",lineHeight:1},children:"▶"}),E.jsx("span",{style:{fontSize:11,fontWeight:600,fontFamily:r.font,color:r.textSecondary,letterSpacing:"0.04em"},children:e})]}),o&&E.jsx("div",{style:{padding:"4px 12px 10px"},children:n})]})}function HS({code:e,t}){const[n,r]=h.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 E.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 Ne({code:e,t}){return E.jsxs("div",{style:{position:"relative",marginTop:6},children:[E.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}),E.jsx(HS,{code:e,t})]})}function si({rows:e,t}){return E.jsx("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11,fontFamily:t.font,marginTop:6},children:E.jsx("tbody",{children:e.map(([n,r],o)=>E.jsxs("tr",{style:{borderBottom:`1px solid ${t.tableBorder}`},children:[E.jsx("td",{style:{padding:"5px 6px 5px 0",fontFamily:t.fontMono,fontSize:11,color:t.accent,whiteSpace:"nowrap",verticalAlign:"top",width:"45%"},children:n}),E.jsx("td",{style:{padding:"5px 0",color:t.textSecondary,verticalAlign:"top",lineHeight:1.5},children:r})]},o))})})}const FS=`block "Revenue by Channel" {
|
|
11
|
-
domain = "revenue"
|
|
12
|
-
type = "custom"
|
|
13
|
-
description = "Revenue grouped by sales channel"
|
|
14
|
-
owner = "data-team"
|
|
15
|
-
tags = ["revenue"]
|
|
16
|
-
|
|
17
|
-
params {
|
|
18
|
-
period = "current_quarter"
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
query = """
|
|
22
|
-
SELECT channel,
|
|
23
|
-
SUM(order_total) AS revenue
|
|
24
|
-
FROM read_csv_auto('data/orders.csv')
|
|
25
|
-
WHERE fiscal_period = \${period}
|
|
26
|
-
GROUP BY channel
|
|
27
|
-
ORDER BY revenue DESC
|
|
28
|
-
"""
|
|
29
|
-
|
|
30
|
-
visualization {
|
|
31
|
-
chart = "bar"
|
|
32
|
-
x = channel
|
|
33
|
-
y = revenue
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
tests {
|
|
37
|
-
assert row_count > 0
|
|
38
|
-
}
|
|
39
|
-
}`,wS=`# semantic-layer/metrics/total_revenue.yaml
|
|
40
|
-
name: total_revenue
|
|
41
|
-
label: Total Revenue
|
|
42
|
-
description: Sum of all recognized revenue.
|
|
43
|
-
domain: finance
|
|
44
|
-
sql: SUM(amount)
|
|
45
|
-
type: sum # sum|count|count_distinct|avg|min|max|custom
|
|
46
|
-
table: fct_revenue
|
|
47
|
-
tags:
|
|
48
|
-
- revenue
|
|
49
|
-
- kpi`,YS=`# semantic-layer/dimensions/segment.yaml
|
|
50
|
-
name: segment
|
|
51
|
-
label: Customer Segment
|
|
52
|
-
description: Customer segment tier.
|
|
53
|
-
sql: segment_tier
|
|
54
|
-
type: string # string|number|date|boolean
|
|
55
|
-
table: fct_revenue`,VS=`# semantic-layer/hierarchies/time.yaml
|
|
56
|
-
name: fiscal_time
|
|
57
|
-
label: Fiscal Time
|
|
58
|
-
description: Drill from year to quarter.
|
|
59
|
-
domain: finance
|
|
60
|
-
levels:
|
|
61
|
-
- name: fiscal_year
|
|
62
|
-
dimension: fiscal_year
|
|
63
|
-
order: 1
|
|
64
|
-
- name: fiscal_quarter
|
|
65
|
-
dimension: fiscal_quarter
|
|
66
|
-
order: 2
|
|
67
|
-
defaultRollup: sum`,WS=`# semantic-layer/cubes/revenue_cube.yaml
|
|
68
|
-
name: revenue
|
|
69
|
-
label: Revenue Cube
|
|
70
|
-
table: fct_revenue
|
|
71
|
-
domain: finance
|
|
72
|
-
|
|
73
|
-
measures:
|
|
74
|
-
- name: total_revenue
|
|
75
|
-
sql: SUM(amount)
|
|
76
|
-
type: sum
|
|
77
|
-
- name: deal_count
|
|
78
|
-
sql: COUNT(*)
|
|
79
|
-
type: count
|
|
80
|
-
|
|
81
|
-
dimensions:
|
|
82
|
-
- name: segment_tier
|
|
83
|
-
sql: segment_tier
|
|
84
|
-
type: string
|
|
85
|
-
|
|
86
|
-
time_dimensions:
|
|
87
|
-
- name: recognized_at
|
|
88
|
-
sql: recognized_at
|
|
89
|
-
primary_time: true
|
|
90
|
-
granularities: [day, month, quarter, year]
|
|
91
|
-
|
|
92
|
-
joins:
|
|
93
|
-
- name: customers
|
|
94
|
-
type: left
|
|
95
|
-
sql: "\${left}.customer_id = \${right}.id"`,kS=`{
|
|
96
|
-
"semanticLayer": {
|
|
97
|
-
"provider": "dql"
|
|
98
|
-
}
|
|
99
|
-
}`,jS=`{
|
|
100
|
-
"semanticLayer": {
|
|
101
|
-
"provider": "dbt",
|
|
102
|
-
"projectPath": "/path/to/your/dbt-project"
|
|
103
|
-
}
|
|
104
|
-
}`,XS=`{
|
|
105
|
-
"semanticLayer": {
|
|
106
|
-
"provider": "cubejs",
|
|
107
|
-
"projectPath": "/path/to/your/cube-project"
|
|
108
|
-
}
|
|
109
|
-
}`,$S=`{
|
|
110
|
-
"defaultConnection": {
|
|
111
|
-
"driver": "file",
|
|
112
|
-
"filepath": ":memory:"
|
|
113
|
-
}
|
|
114
|
-
}`,KS=`{
|
|
115
|
-
"defaultConnection": {
|
|
116
|
-
"driver": "snowflake",
|
|
117
|
-
"account": "acme.snowflakecomputing.com",
|
|
118
|
-
"username": "your_user",
|
|
119
|
-
"password": "\${SNOWFLAKE_PASSWORD}",
|
|
120
|
-
"database": "ANALYTICS",
|
|
121
|
-
"schema": "PUBLIC",
|
|
122
|
-
"warehouse": "COMPUTE_WH",
|
|
123
|
-
"role": "ANALYST"
|
|
124
|
-
}
|
|
125
|
-
}`,zS=`{
|
|
126
|
-
"defaultConnection": {
|
|
127
|
-
"driver": "bigquery",
|
|
128
|
-
"project": "your-gcp-project-id",
|
|
129
|
-
"dataset": "analytics",
|
|
130
|
-
"keyFilename": "./service-account.json"
|
|
131
|
-
}
|
|
132
|
-
}`,JS=`{
|
|
133
|
-
"defaultConnection": {
|
|
134
|
-
"driver": "postgres",
|
|
135
|
-
"host": "localhost",
|
|
136
|
-
"port": 5432,
|
|
137
|
-
"database": "analytics",
|
|
138
|
-
"username": "your_user",
|
|
139
|
-
"password": "\${POSTGRES_PASSWORD}"
|
|
140
|
-
}
|
|
141
|
-
}`,qS=`-- Primary workflow: use Compose Query in the Semantic Layer panel
|
|
142
|
-
-- 1. Pick metrics + dimensions (+ optional time dimension)
|
|
143
|
-
-- 2. Click "Compose SQL"
|
|
144
|
-
-- 3. Click "+ Insert as Cell" → edit and run
|
|
145
|
-
|
|
146
|
-
-- Advanced: reference metrics inline in any SQL cell
|
|
147
|
-
-- DQL resolves @metric() and @dim() at query time
|
|
148
|
-
SELECT
|
|
149
|
-
@dim(segment_tier),
|
|
150
|
-
@metric(total_revenue)
|
|
151
|
-
FROM fct_revenue
|
|
152
|
-
GROUP BY @dim(segment_tier)
|
|
153
|
-
ORDER BY @metric(total_revenue) DESC`,ZS=`{
|
|
154
|
-
"semanticLayer": {
|
|
155
|
-
"provider": "snowflake",
|
|
156
|
-
"projectPath": "MY_DATABASE"
|
|
157
|
-
}
|
|
158
|
-
}`;function QS({themeMode:e}){const t=re[e];return E.jsxs("div",{style:{flex:1,overflowY:"auto",fontFamily:t.font},children:[E.jsx(Xe,{title:"SQL Essentials",defaultOpen:!0,t,children:E.jsx(Ne,{t,code:`-- Basic select
|
|
159
|
-
SELECT col1, col2
|
|
160
|
-
FROM table_name
|
|
161
|
-
WHERE condition
|
|
162
|
-
ORDER BY col1 DESC
|
|
163
|
-
LIMIT 100
|
|
164
|
-
|
|
165
|
-
-- GROUP BY
|
|
166
|
-
SELECT col, COUNT(*), SUM(val)
|
|
167
|
-
FROM table_name
|
|
168
|
-
GROUP BY col
|
|
169
|
-
|
|
170
|
-
-- JOIN
|
|
171
|
-
SELECT a.*, b.col
|
|
172
|
-
FROM table_a AS a
|
|
173
|
-
JOIN table_b AS b ON a.id = b.id
|
|
174
|
-
|
|
175
|
-
-- CTE (WITH)
|
|
176
|
-
WITH cte AS (
|
|
177
|
-
SELECT * FROM table_name WHERE val > 0
|
|
178
|
-
)
|
|
179
|
-
SELECT * FROM cte
|
|
180
|
-
|
|
181
|
-
-- Window function
|
|
182
|
-
SELECT *,
|
|
183
|
-
ROW_NUMBER() OVER (
|
|
184
|
-
PARTITION BY group_col
|
|
185
|
-
ORDER BY val DESC
|
|
186
|
-
) AS rank
|
|
187
|
-
FROM table_name`})}),E.jsx(Xe,{title:"DuckDB Functions",defaultOpen:!1,t,children:E.jsx(si,{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"]]})}),E.jsxs(Xe,{title:"DQL Block Structure",defaultOpen:!0,t,children:[E.jsx(Ne,{t,code:FS}),E.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.6},children:["Run ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql certify <file> --connection duckdb"})," to execute ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"tests {}"})," assertions against live data. Use ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"--skip-tests"})," to check governance fields only."]})]}),E.jsxs(Xe,{title:"DQL Chart Types",defaultOpen:!1,t,children:[E.jsx(si,{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)"]]}),E.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.6},children:["Set chart type inside the"," ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:'visualization { chart = "pie"; x = label_col; y = value_col }'})," ","block."]})]}),E.jsxs(Xe,{title:"Semantic Layer Usage",defaultOpen:!1,t,children:[E.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:6},children:["Primary workflow: open the ",E.jsx("strong",{children:"Semantic Layer"})," panel → Compose Query → pick metrics and dimensions → Compose SQL → + Insert as Cell. Advanced: use ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"@metric(name)"})," and ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"@dim(name)"})," refs directly in any SQL cell."]}),E.jsx(Ne,{t,code:qS})]}),E.jsxs(Xe,{title:"Semantic Layer",defaultOpen:!1,t,children:[E.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"," ",E.jsx("strong",{style:{color:t.textPrimary},children:"Semantic Layer"})," sidebar panel."]}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"10px 0 4px",letterSpacing:"0.03em"},children:"Directory Structure"}),E.jsx(Ne,{t,code:`my-project/
|
|
188
|
-
├── dql.config.json
|
|
189
|
-
└── semantic-layer/
|
|
190
|
-
├── metrics/ ← one YAML per metric
|
|
191
|
-
├── dimensions/ ← one YAML per dimension
|
|
192
|
-
├── hierarchies/ ← optional drill paths
|
|
193
|
-
└── cubes/ ← optional (groups all into one)`}),E.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:[E.jsx("strong",{style:{color:t.textPrimary},children:"Recommended:"})," For multi-table projects, use a ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"cubes/"})," file — it keeps metrics, dimensions, and joins together. Use standalone ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"metrics/"})," and ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dimensions/"})," files only for simple single-table projects."]}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Metric YAML"}),E.jsx(Ne,{t,code:wS}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Dimension YAML"}),E.jsx(Ne,{t,code:YS}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Hierarchy YAML"}),E.jsx(Ne,{t,code:VS}),E.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)"}),E.jsx(Ne,{t,code:WS})]}),E.jsxs(Xe,{title:"Semantic Layer Providers",defaultOpen:!1,t,children:[E.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Add to your ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"})," to connect a semantic layer provider."]}),E.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/)"}),E.jsx(Ne,{t,code:kS}),E.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)"}),E.jsx(Ne,{t,code:jS}),E.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 ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dbt_project.yml"}),"). Reads ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"semantic_models"})," and"," ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"metrics"})," blocks (dbt 1.6+)."]}),E.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/)"}),E.jsx(Ne,{t,code:XS}),E.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"," ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"cubes:"})," blocks from YAML schema files."]}),E.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)"}),E.jsx(Ne,{t,code:ZS}),E.jsxs("div",{style:{marginTop:4,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Introspects Snowflake semantic views via"," ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"SHOW SEMANTIC VIEWS"}),". Set ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"projectPath"})," to your database name to scope discovery. Requires a Snowflake connection in ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"defaultConnection"}),"."]})]}),E.jsxs(Xe,{title:"Connection Setup",defaultOpen:!1,t,children:[E.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Configure ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"defaultConnection"})," in"," ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"dql.config.json"}),"."]}),E.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)"}),E.jsx(Ne,{t,code:$S}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"Snowflake"}),E.jsx(Ne,{t,code:KS}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"BigQuery"}),E.jsx(Ne,{t,code:zS}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:t.textSecondary,fontFamily:t.font,margin:"12px 0 4px",letterSpacing:"0.03em"},children:"PostgreSQL"}),E.jsx(Ne,{t,code:JS}),E.jsxs("div",{style:{marginTop:8,fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:["Use ",E.jsxs("code",{style:{fontFamily:t.fontMono,fontSize:10},children:["$","${ENV_VAR}"]})," syntax for secrets. Run ",E.jsx("code",{style:{fontFamily:t.fontMono,fontSize:10},children:"dql doctor"})," to verify your connection."]})]}),E.jsxs(Xe,{title:"Variable References",defaultOpen:!1,t,children:[E.jsxs("div",{style:{fontSize:12,color:t.textSecondary,lineHeight:1.7,fontFamily:t.font,marginBottom:8},children:["Use"," ",E.jsx("code",{style:{fontFamily:t.fontMono,color:t.accent,fontSize:11},children:"{{cell_name}}"})," ","to reference other cells:",E.jsxs("ul",{style:{margin:"6px 0 0",paddingLeft:18},children:[E.jsxs("li",{children:[E.jsx("strong",{children:"Param cell"})," → substituted as a SQL literal value"]}),E.jsxs("li",{children:[E.jsx("strong",{children:"SQL cell"})," → injected as a CTE"]})]})]}),E.jsx(Ne,{t,code:`-- Param cell named "start_date" holds '2024-01-01'
|
|
194
|
-
SELECT *
|
|
195
|
-
FROM read_csv_auto('data/sales.csv')
|
|
196
|
-
WHERE date >= {{start_date}}
|
|
197
|
-
|
|
198
|
-
-- SQL cell named "base_query" used as CTE
|
|
199
|
-
SELECT segment, SUM(revenue) AS total
|
|
200
|
-
FROM {{base_query}}
|
|
201
|
-
GROUP BY segment`})]})]})}const Da={sum:"#56d364",count:"#388bfd",count_distinct:"#388bfd",avg:"#e3b341",min:"#f778ba",max:"#f778ba",custom:"#d2a8ff"};function eA(){return E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1Zm0 1.5a5.5 5.5 0 1 1 0 11 5.5 5.5 0 0 1 0-11Zm0 2a.75.75 0 0 1 .75.75v2h2a.75.75 0 0 1 0 1.5h-2v2a.75.75 0 0 1-1.5 0v-2h-2a.75.75 0 0 1 0-1.5h2v-2A.75.75 0 0 1 8 4.5Z"})})}function tA(){return E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M1 2.75C1 1.784 1.784 1 2.75 1h10.5c.966 0 1.75.784 1.75 1.75v10.5A1.75 1.75 0 0 1 13.25 15H2.75A1.75 1.75 0 0 1 1 13.25Zm1.75-.25a.25.25 0 0 0-.25.25v10.5c0 .138.112.25.25.25h10.5a.25.25 0 0 0 .25-.25V2.75a.25.25 0 0 0-.25-.25ZM8 4a.75.75 0 0 1 .75.75v6.5a.75.75 0 0 1-1.5 0v-6.5A.75.75 0 0 1 8 4Zm-3 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 5 7Zm6-1a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-1.5 0v-4.5A.75.75 0 0 1 11 6Z"})})}function nA(){return E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M8 1a1 1 0 0 1 1 1v2.586l2.293-2.293a1 1 0 0 1 1.414 1.414L10.414 6H13a1 1 0 1 1 0 2h-2.586l2.293 2.293a1 1 0 0 1-1.414 1.414L9 9.414V12a1 1 0 1 1-2 0V9.414l-2.293 2.293a1 1 0 0 1-1.414-1.414L5.586 8H3a1 1 0 0 1 0-2h2.586L3.293 3.707a1 1 0 0 1 1.414-1.414L7 4.586V2a1 1 0 0 1 1-1Z"})})}function qr({label:e,count:t,expanded:n,onToggle:r,t:o}){const[s,i]=h.useState(!1);return E.jsxs("button",{onClick:r,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"3px 8px 3px 10px",background:s?o.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:o.textSecondary,fontSize:11,fontWeight:600,fontFamily:o.font,letterSpacing:"0.04em",textTransform:"uppercase",textAlign:"left",transition:"background 0.1s"},children:[E.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:E.jsx("path",{d:"M3 2l4 3-4 3V2Z"})}),E.jsx("span",{style:{flex:1},children:e}),t>0&&E.jsx("span",{style:{background:o.pillBg,color:o.textMuted,borderRadius:10,padding:"0 5px",fontSize:10,fontWeight:500},children:t})]})}function rA({metric:e,t}){const[n,r]=h.useState(!1),[o,s]=h.useState(!1),i=Da[e.type]??t.accent;return E.jsxs("div",{children:[E.jsxs("button",{onClick:()=>s(!o),onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 8px 4px 22px",background:n?t.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:t.textPrimary,fontSize:12,fontFamily:t.font,textAlign:"left",transition:"background 0.1s"},children:[E.jsx("span",{style:{color:i,flexShrink:0},children:E.jsx(eA,{})}),E.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.label||e.name}),E.jsx("span",{style:{fontSize:9,fontFamily:t.fontMono,color:i,background:`${i}18`,borderRadius:4,padding:"1px 4px",flexShrink:0},children:e.type})]}),o&&E.jsxs("div",{style:{padding:"2px 8px 6px 40px",fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.5},children:[e.description&&E.jsx("div",{children:e.description}),E.jsxs("div",{style:{fontFamily:t.fontMono,fontSize:10,color:t.textSecondary,marginTop:2},children:["table: ",e.table]}),e.domain&&E.jsxs("div",{style:{fontFamily:t.fontMono,fontSize:10,color:t.textSecondary},children:["domain: ",e.domain]}),e.tags.length>0&&E.jsx("div",{style:{display:"flex",gap:3,flexWrap:"wrap",marginTop:3},children:e.tags.map(a=>E.jsx("span",{style:{fontSize:9,background:t.pillBg,color:t.textMuted,borderRadius:3,padding:"1px 4px"},children:a},a))})]})]})}function oA({dimension:e,t}){const[n,r]=h.useState(!1),o=e.type==="date"?"#e3b341":e.type==="number"?"#56d364":"#388bfd";return E.jsxs("div",{onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 8px 4px 22px",background:n?t.sidebarItemHover:"transparent",cursor:"default",transition:"background 0.1s"},children:[E.jsx("span",{style:{color:t.textMuted,flexShrink:0},children:E.jsx(tA,{})}),E.jsx("span",{style:{flex:1,fontSize:12,fontFamily:t.font,color:t.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.description,children:e.label||e.name}),E.jsx("span",{style:{fontSize:9,fontFamily:t.fontMono,color:o,background:`${o}18`,borderRadius:4,padding:"1px 4px",flexShrink:0},children:e.type})]})}function sA({hierarchy:e,t}){const[n,r]=h.useState(!1),[o,s]=h.useState(!1);return E.jsxs("div",{children:[E.jsxs("button",{onClick:()=>s(!o),onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 8px 4px 22px",background:n?t.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:t.textSecondary,fontSize:12,fontFamily:t.font,textAlign:"left",transition:"background 0.1s"},children:[E.jsx("span",{style:{color:"#d2a8ff",flexShrink:0},children:E.jsx(nA,{})}),E.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.label||e.name}),E.jsx("span",{style:{fontSize:10,color:t.textMuted,background:t.pillBg,borderRadius:8,padding:"1px 5px",flexShrink:0},children:e.levels.length})]}),o&&E.jsx("div",{style:{paddingLeft:40},children:e.levels.map((i,a)=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"2px 0",fontSize:11,fontFamily:t.fontMono,color:t.textMuted},children:[E.jsxs("span",{style:{color:t.textMuted,fontSize:9},children:[a+1,"."]}),i.label||i.name]},i.name))})]})}const iA=["day","week","month","quarter","year"];function EA({t:e,metrics:t,dimensions:n,onInsertCell:r}){const[o,s]=h.useState(!1),[i,a]=h.useState(new Set),[T,l]=h.useState(new Set),[R,c]=h.useState(""),[S,A]=h.useState("month"),[d,N]=h.useState(null),[I,u]=h.useState(null),[f,O]=h.useState(!1),[C,m]=h.useState(!1),L=n.filter(p=>p.type==="date"),D=p=>{a(F=>{const _=new Set(F);return _.has(p)?_.delete(p):_.add(p),_}),N(null)},M=p=>{l(F=>{const _=new Set(F);return _.has(p)?_.delete(p):_.add(p),_}),N(null)},x=async()=>{if(i.size!==0){O(!0),u(null);try{const p=R?{name:R,granularity:S}:void 0,F=await le.composeQuery(Array.from(i),Array.from(T),p);"error"in F?u(F.error):N(F.sql)}catch(p){u(p.message??"Failed to compose")}finally{O(!1)}}},B=()=>{d&&(navigator.clipboard.writeText(d),m(!0),setTimeout(()=>m(!1),1500))},g=p=>({width:14,height:14,borderRadius:3,border:`1.5px solid ${p?e.accent:e.cellBorder}`,background:p?e.accent:"transparent",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,transition:"all 0.15s"});return E.jsxs("div",{style:{borderBottom:`1px solid ${e.headerBorder}`},children:[E.jsxs("button",{onClick:()=>s(!o),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"6px 10px",background:o?`${e.accent}10`:"transparent",border:"none",cursor:"pointer",color:e.accent,fontSize:11,fontWeight:600,fontFamily:e.font,textAlign:"left"},children:[E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M8 1.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm6.5-2a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Zm-2 4.5a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Zm5 0a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Z"})}),"Compose Query",E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{marginLeft:"auto",transform:o?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.15s"},children:E.jsx("path",{d:"M3 2l4 3-4 3V2Z"})})]}),o&&E.jsxs("div",{style:{padding:"6px 10px 10px",fontSize:11,fontFamily:e.font},children:[E.jsx("div",{style:{fontSize:10,fontWeight:600,color:e.textSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Select Metrics"}),E.jsx("div",{style:{maxHeight:120,overflowY:"auto",marginBottom:8},children:t.map(p=>E.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,padding:"2px 0",cursor:"pointer",color:e.textPrimary,fontSize:11},onClick:()=>D(p.name),children:[E.jsx("div",{style:g(i.has(p.name)),children:i.has(p.name)&&E.jsx("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"#fff",children:E.jsx("path",{d:"M8.5 2.5L4 7 1.5 4.5",stroke:"#fff",strokeWidth:"1.5",fill:"none"})})}),E.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p.label||p.name}),E.jsx("span",{style:{fontSize:9,color:Da[p.type]??e.accent,marginLeft:"auto",flexShrink:0},children:p.type})]},p.name))}),E.jsx("div",{style:{fontSize:10,fontWeight:600,color:e.textSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Select Dimensions (optional)"}),E.jsx("div",{style:{maxHeight:120,overflowY:"auto",marginBottom:8},children:n.map(p=>E.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,padding:"2px 0",cursor:"pointer",color:e.textPrimary,fontSize:11},onClick:()=>M(p.name),children:[E.jsx("div",{style:g(T.has(p.name)),children:T.has(p.name)&&E.jsx("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"#fff",children:E.jsx("path",{d:"M8.5 2.5L4 7 1.5 4.5",stroke:"#fff",strokeWidth:"1.5",fill:"none"})})}),E.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p.label||p.name})]},p.name))}),L.length>0&&E.jsxs("div",{style:{marginBottom:8},children:[E.jsx("div",{style:{fontSize:10,fontWeight:600,color:e.textSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Time Dimension (optional)"}),E.jsxs("select",{value:R,onChange:p=>{c(p.target.value),N(null)},style:{width:"100%",padding:"3px 6px",background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:4,color:R?e.textPrimary:e.textMuted,fontSize:11,fontFamily:e.font,marginBottom:4,cursor:"pointer"},children:[E.jsx("option",{value:"",children:"None"}),L.map(p=>E.jsx("option",{value:p.name,children:p.label||p.name},p.name))]}),R&&E.jsx("div",{style:{display:"flex",gap:4},children:iA.map(p=>E.jsx("button",{onClick:()=>{A(p),N(null)},style:{flex:1,padding:"2px 0",background:S===p?e.accent:e.pillBg,border:"none",borderRadius:3,color:S===p?"#fff":e.textMuted,fontSize:9,fontWeight:600,fontFamily:e.font,cursor:"pointer",textTransform:"capitalize"},children:p},p))})]}),E.jsx("button",{onClick:x,disabled:i.size===0||f,style:{width:"100%",padding:"5px 12px",background:i.size===0?e.pillBg:e.accent,color:i.size===0?e.textMuted:"#fff",border:"none",borderRadius:5,cursor:i.size===0?"not-allowed":"pointer",fontSize:11,fontWeight:600,fontFamily:e.font,opacity:f?.7:1},children:f?"Composing...":`Compose SQL (${i.size} metric${i.size!==1?"s":""})`}),I&&E.jsx("div",{style:{marginTop:6,padding:"4px 8px",background:"#f8514922",border:"1px solid #f8514944",borderRadius:4,fontSize:10,color:"#f85149"},children:I}),d&&E.jsxs("div",{style:{marginTop:8},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[E.jsx("span",{style:{fontSize:10,fontWeight:600,color:e.textSecondary,textTransform:"uppercase",letterSpacing:"0.04em"},children:"Generated SQL"}),E.jsxs("div",{style:{display:"flex",gap:4},children:[r&&E.jsx("button",{onClick:()=>d&&r(d),style:{background:e.accent,border:"none",borderRadius:3,color:"#fff",cursor:"pointer",fontSize:9,fontWeight:600,fontFamily:e.font,padding:"2px 8px"},children:"+ Insert as Cell"}),E.jsx("button",{onClick:B,style:{background:"transparent",border:`1px solid ${e.cellBorder}`,borderRadius:3,color:C?"#56d364":e.textMuted,cursor:"pointer",fontSize:9,fontFamily:e.font,padding:"1px 6px"},children:C?"Copied!":"Copy"})]})]}),E.jsx("pre",{style:{margin:0,padding:"6px 8px",background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:4,fontFamily:e.fontMono,fontSize:10,color:e.textSecondary,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-all",maxHeight:200,overflowY:"auto"},children:d})]})]})]})}const aA=["sum","count","count_distinct","avg","min","max"];function lA({t:e,onClose:t,onCreated:n}){const[r,o]=h.useState(""),[s,i]=h.useState(""),[a,T]=h.useState(""),[l,R]=h.useState("sum"),[c,S]=h.useState(""),[A,d]=h.useState(""),[N,I]=h.useState(""),[u,f]=h.useState(!1),[O,C]=h.useState(null),m={width:"100%",padding:"4px 7px",background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:4,color:e.textPrimary,fontSize:11,fontFamily:e.fontMono,outline:"none",boxSizing:"border-box"},L={fontSize:10,fontWeight:600,color:e.textSecondary,fontFamily:e.font,letterSpacing:"0.04em",textTransform:"uppercase",display:"block",marginBottom:3,marginTop:8},D=async()=>{if(!r.trim()||!a.trim()||!c.trim()){C("Name, SQL expression, and table are required.");return}f(!0),C(null);const M=await le.createMetric({name:r.trim(),label:s.trim()||r.trim(),description:N.trim(),domain:A.trim()||"general",sql:a.trim(),type:l,table:c.trim()});f(!1),M.ok?(n(),t()):C(M.error??"Unknown error")};return E.jsxs("div",{style:{position:"absolute",inset:0,zIndex:100,background:`${e.sidebarBg}f0`,display:"flex",flexDirection:"column",padding:"12px 14px",overflowY:"auto"},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10},children:[E.jsx("span",{style:{fontSize:12,fontWeight:600,color:e.textPrimary,fontFamily:e.font},children:"New Metric"}),E.jsx("button",{onClick:t,style:{background:"transparent",border:"none",cursor:"pointer",color:e.textMuted,fontSize:16,fontFamily:e.font,padding:"0 2px"},children:"×"})]}),E.jsx("span",{style:L,children:"Name *"}),E.jsx("input",{style:m,value:r,onChange:M=>o(M.target.value),placeholder:"total_revenue"}),E.jsx("span",{style:L,children:"Label"}),E.jsx("input",{style:m,value:s,onChange:M=>i(M.target.value),placeholder:"Total Revenue"}),E.jsx("span",{style:L,children:"SQL Expression *"}),E.jsx("input",{style:m,value:a,onChange:M=>T(M.target.value),placeholder:"SUM(amount)"}),E.jsx("span",{style:L,children:"Aggregation Type *"}),E.jsx("select",{value:l,onChange:M=>R(M.target.value),style:{...m,cursor:"pointer"},children:aA.map(M=>E.jsx("option",{value:M,children:M},M))}),E.jsx("span",{style:L,children:"Table / Source *"}),E.jsx("input",{style:m,value:c,onChange:M=>S(M.target.value),placeholder:"fct_revenue or read_csv_auto('data/revenue.csv')"}),E.jsx("span",{style:L,children:"Domain"}),E.jsx("input",{style:m,value:A,onChange:M=>d(M.target.value),placeholder:"finance"}),E.jsx("span",{style:L,children:"Description"}),E.jsx("input",{style:m,value:N,onChange:M=>I(M.target.value),placeholder:"Sum of all recognized revenue"}),O&&E.jsx("div",{style:{marginTop:8,padding:"4px 8px",background:"#f8514922",border:"1px solid #f8514944",borderRadius:4,fontSize:10,color:"#f85149"},children:O}),E.jsxs("div",{style:{display:"flex",gap:6,marginTop:12},children:[E.jsx("button",{onClick:D,disabled:u,style:{flex:1,padding:"5px 0",background:e.accent,color:"#fff",border:"none",borderRadius:5,fontSize:11,fontWeight:600,fontFamily:e.font,cursor:u?"not-allowed":"pointer",opacity:u?.7:1},children:u?"Creating...":"Create Metric"}),E.jsx("button",{onClick:t,style:{padding:"5px 12px",background:"transparent",border:`1px solid ${e.cellBorder}`,borderRadius:5,fontSize:11,fontFamily:e.font,color:e.textMuted,cursor:"pointer"},children:"Cancel"})]}),E.jsxs("div",{style:{marginTop:10,fontSize:10,color:e.textMuted,fontFamily:e.font,lineHeight:1.5},children:["Creates ",E.jsxs("code",{style:{fontFamily:e.fontMono},children:["semantic-layer/metrics/","{name}",".yaml"]})," and reloads the panel automatically."]})]})}function TA(){const{state:e,dispatch:t}=ae(),n=re[e.themeMode],[r,o]=h.useState(""),[s,i]=h.useState(!1),[a,T]=h.useState(!1),[l,R]=h.useState({metrics:!0,dimensions:!0,hierarchies:!1}),c=e.semanticLayer,S=async()=>{t({type:"SET_SEMANTIC_LOADING",loading:!0});try{const L=await le.getSemanticLayer();t({type:"SET_SEMANTIC_LAYER",layer:L})}catch(L){console.error("Semantic layer refresh failed:",L)}finally{t({type:"SET_SEMANTIC_LOADING",loading:!1})}};h.useEffect(()=>{c.metrics.length===0&&!c.loading&&S()},[]);const A=r.toLowerCase(),d=h.useMemo(()=>A?c.metrics.filter(L=>L.name.toLowerCase().includes(A)||L.label.toLowerCase().includes(A)||L.description.toLowerCase().includes(A)||L.tags.some(D=>D.toLowerCase().includes(A))):c.metrics,[c.metrics,A]),N=h.useMemo(()=>A?c.dimensions.filter(L=>L.name.toLowerCase().includes(A)||L.label.toLowerCase().includes(A)||L.description.toLowerCase().includes(A)):c.dimensions,[c.dimensions,A]),I=h.useMemo(()=>A?c.hierarchies.filter(L=>L.name.toLowerCase().includes(A)||L.label.toLowerCase().includes(A)):c.hierarchies,[c.hierarchies,A]),u=L=>{R(D=>({...D,[L]:!D[L]}))},f={background:n.pillBg,padding:"1px 4px",borderRadius:3,fontSize:10,fontFamily:n.fontMono},O={fontSize:11,fontWeight:600,color:n.textPrimary,fontFamily:n.font,marginBottom:4},C={fontSize:11,color:n.textMuted,fontFamily:n.font,lineHeight:1.6,marginBottom:2},m={margin:"4px 0 0",padding:"6px 8px",background:n.editorBg,border:`1px solid ${n.cellBorder}`,borderRadius:4,fontFamily:n.fontMono,fontSize:10,color:n.textSecondary,lineHeight:1.5,whiteSpace:"pre",overflowX:"auto"};return!c.available&&!c.loading?E.jsxs("div",{style:{flex:1,overflowY:"auto",padding:"12px 14px",fontFamily:n.font},children:[E.jsxs("div",{style:{textAlign:"center",marginBottom:14},children:[E.jsx("svg",{width:"28",height:"28",viewBox:"0 0 16 16",fill:n.accent,style:{opacity:.7},children:E.jsx("path",{d:"M8 1.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm6.5-2a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Zm-2 4.5a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Zm5 0a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Z"})}),E.jsx("div",{style:{fontSize:12,fontWeight:600,color:n.textPrimary,marginTop:6},children:"Set Up Semantic Layer"}),E.jsx("div",{style:{fontSize:11,color:n.textMuted,marginTop:2,lineHeight:1.5},children:"Choose a provider below, then click Retry."})]}),E.jsxs("div",{style:{marginBottom:12},children:[E.jsx("div",{style:O,children:"Step 1: Pick a provider"}),E.jsxs("div",{style:C,children:["Add ",E.jsx("code",{style:f,children:"semanticLayer"})," to your ",E.jsx("code",{style:f,children:"dql.config.json"}),":"]}),E.jsx("div",{style:{fontSize:10,fontWeight:600,color:n.accent,marginTop:8,letterSpacing:"0.03em"},children:"A) DQL Native — write YAML files directly"}),E.jsx("pre",{style:m,children:`"semanticLayer": {
|
|
202
|
-
"provider": "dql"
|
|
203
|
-
}`}),E.jsx("div",{style:{fontSize:10,fontWeight:600,color:n.accent,marginTop:8,letterSpacing:"0.03em"},children:"B) dbt — point to your dbt project"}),E.jsx("pre",{style:m,children:`"semanticLayer": {
|
|
204
|
-
"provider": "dbt",
|
|
205
|
-
"projectPath": "/path/to/dbt-project"
|
|
206
|
-
}`}),E.jsx("div",{style:{fontSize:10,fontWeight:600,color:n.accent,marginTop:8,letterSpacing:"0.03em"},children:"C) Cube.js — point to your Cube project"}),E.jsx("pre",{style:m,children:`"semanticLayer": {
|
|
207
|
-
"provider": "cubejs",
|
|
208
|
-
"projectPath": "/path/to/cube-project"
|
|
209
|
-
}`}),E.jsx("div",{style:{fontSize:10,fontWeight:600,color:n.accent,marginTop:8,letterSpacing:"0.03em"},children:"D) Snowflake — introspects Snowflake semantic views"}),E.jsx("pre",{style:m,children:`"semanticLayer": {
|
|
210
|
-
"provider": "snowflake",
|
|
211
|
-
"projectPath": "MY_DATABASE"
|
|
212
|
-
}`}),E.jsxs("div",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font,marginTop:3,lineHeight:1.5},children:["Requires a Snowflake ",E.jsx("code",{style:{fontFamily:n.fontMono,fontSize:9},children:"defaultConnection"}),". DQL introspects semantic views automatically."]})]}),E.jsxs("div",{style:{marginBottom:12},children:[E.jsx("div",{style:O,children:"Step 2: Add definitions (DQL native only)"}),E.jsx("div",{style:C,children:"Create YAML files in your project:"}),E.jsx("pre",{style:m,children:`semantic-layer/
|
|
213
|
-
metrics/total_revenue.yaml
|
|
214
|
-
dimensions/segment.yaml
|
|
215
|
-
hierarchies/time.yaml (optional)
|
|
216
|
-
cubes/revenue_cube.yaml (optional)`}),E.jsx("div",{style:{...C,marginTop:6},children:"Minimal metric example:"}),E.jsx("pre",{style:m,children:`name: total_revenue
|
|
217
|
-
label: Total Revenue
|
|
218
|
-
sql: SUM(amount)
|
|
219
|
-
type: sum
|
|
220
|
-
table: fct_revenue`})]}),E.jsxs("div",{style:{marginBottom:14},children:[E.jsx("div",{style:O,children:"Step 3: Restart & refresh"}),E.jsxs("div",{style:C,children:["Restart ",E.jsx("code",{style:f,children:"dql notebook"}),", then click Retry below."]})]}),E.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"center"},children:[E.jsx("button",{onClick:S,style:{background:n.accent,border:"none",borderRadius:6,color:"#fff",cursor:"pointer",fontSize:11,fontWeight:600,fontFamily:n.font,padding:"6px 16px"},children:"Retry"}),E.jsx("button",{onClick:()=>t({type:"SET_SIDEBAR_PANEL",panel:"reference"}),style:{background:"transparent",border:`1px solid ${n.cellBorder}`,borderRadius:6,color:n.textSecondary,cursor:"pointer",fontSize:11,fontFamily:n.font,padding:"6px 12px"},children:"Full Reference"})]})]}):E.jsxs("div",{style:{flex:1,overflow:"auto",display:"flex",flexDirection:"column",position:"relative"},children:[a&&E.jsx(lA,{t:n,onClose:()=>T(!1),onCreated:()=>S()}),E.jsxs("div",{style:{padding:"8px 10px",display:"flex",alignItems:"center",gap:6,borderBottom:`1px solid ${n.headerBorder}`},children:[c.provider&&E.jsx("span",{style:{fontSize:9,fontWeight:600,color:n.accent,background:`${n.accent}18`,borderRadius:4,padding:"1px 5px",textTransform:"uppercase",letterSpacing:"0.04em"},children:c.provider}),E.jsxs("span",{style:{flex:1,fontSize:11,color:n.textMuted,fontFamily:n.font},children:[c.metrics.length," metrics"]}),E.jsx("button",{onClick:()=>T(!0),title:"Create a new metric YAML file",style:{background:n.accent,border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:10,fontWeight:600,fontFamily:n.font,padding:"2px 8px"},children:"+ New"}),E.jsx("button",{onClick:S,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),title:"Refresh semantic layer",style:{background:s?n.btnHover:"transparent",border:`1px solid ${s?n.btnBorder:"transparent"}`,borderRadius:4,cursor:"pointer",color:s?n.textSecondary:n.textMuted,fontSize:11,fontFamily:n.font,padding:"2px 6px",display:"flex",alignItems:"center",gap:4,transition:"all 0.15s"},children:E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:E.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"})})})]}),E.jsx(EA,{t:n,metrics:c.metrics,dimensions:c.dimensions,onInsertCell:L=>{const D=Le("sql",L);t({type:"ADD_CELL",cell:D})}}),E.jsx("div",{style:{padding:"6px 8px",borderBottom:`1px solid ${n.headerBorder}`},children:E.jsx("input",{type:"text",placeholder:"Search metrics, dimensions...",value:r,onChange:L=>o(L.target.value),style:{width:"100%",padding:"4px 8px",background:n.cellBg,border:`1px solid ${n.cellBorder}`,borderRadius:4,color:n.textPrimary,fontSize:11,fontFamily:n.font,outline:"none"}})}),c.loading?E.jsxs("div",{style:{padding:"8px 12px",display:"flex",flexDirection:"column",gap:8},children:[[1,2,3].map(L=>E.jsx("div",{style:{height:28,borderRadius:4,background:n.pillBg,opacity:.6,animation:"pulse 1.5s ease-in-out infinite"}},L)),E.jsx("style",{children:"@keyframes pulse { 0%,100%{opacity:.6} 50%{opacity:.3} }"})]}):E.jsxs("div",{style:{overflow:"auto",flex:1},children:[E.jsx(qr,{label:"Metrics",count:d.length,expanded:l.metrics,onToggle:()=>u("metrics"),t:n}),l.metrics&&E.jsx("div",{children:d.length===0?E.jsx("div",{style:{padding:"4px 14px 4px 32px",fontSize:12,color:n.textMuted,fontFamily:n.font,fontStyle:"italic"},children:A?"No matching metrics":"No metrics defined"}):d.map(L=>E.jsx(rA,{metric:L,t:n},L.name))}),E.jsx(qr,{label:"Dimensions",count:N.length,expanded:l.dimensions,onToggle:()=>u("dimensions"),t:n}),l.dimensions&&E.jsx("div",{children:N.length===0?E.jsx("div",{style:{padding:"4px 14px 4px 32px",fontSize:12,color:n.textMuted,fontFamily:n.font,fontStyle:"italic"},children:A?"No matching dimensions":"No dimensions defined"}):N.map(L=>E.jsx(oA,{dimension:L,t:n},L.name))}),c.hierarchies.length>0&&E.jsxs(E.Fragment,{children:[E.jsx(qr,{label:"Hierarchies",count:I.length,expanded:l.hierarchies,onToggle:()=>u("hierarchies"),t:n}),l.hierarchies&&E.jsx("div",{children:I.map(L=>E.jsx(sA,{hierarchy:L,t:n},L.name))})]})]})]})}const ga={source_table:"#8b949e",block:"#56d364",metric:"#388bfd",dimension:"#e3b341",domain:"#d2a8ff",chart:"#f778ba"},cA={certified:{label:"CERTIFIED",color:"#56d364"},draft:{label:"DRAFT",color:"#8b949e"},review:{label:"REVIEW",color:"#e3b341"},deprecated:{label:"DEPRECATED",color:"#f85149"},pending_recertification:{label:"PENDING",color:"#d29922"}};function Ma({type:e}){const t=ga[e]??"#8b949e";return E.jsx("span",{style:{color:t,fontSize:10,fontWeight:600,textTransform:"uppercase",marginRight:4},children:e==="source_table"?"TBL":e==="block"?"BLK":e==="metric"?"MET":e==="dimension"?"DIM":e==="chart"?"CHT":e.slice(0,3).toUpperCase()})}function RA({status:e}){if(!e)return null;const t=cA[e];return t?E.jsx("span",{style:{fontSize:9,fontWeight:600,color:t.color,border:`1px solid ${t.color}`,borderRadius:3,padding:"0 3px",marginLeft:4},children:t.label}):null}function Hn({label:e,count:t,expanded:n,onToggle:r,t:o}){const[s,i]=h.useState(!1);return E.jsxs("button",{onClick:r,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{width:"100%",display:"flex",alignItems:"center",gap:4,padding:"6px 8px",background:s?o.sidebarItemHover:"transparent",border:"none",cursor:"pointer",color:o.textPrimary,fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.5px",textAlign:"left"},children:[E.jsx("span",{style:{fontSize:10},children:n?"▼":"▶"}),E.jsx("span",{style:{flex:1},children:e}),E.jsx("span",{style:{color:o.textMuted,fontWeight:400},children:t})]})}function Qt({node:e,t,onClick:n}){const[r,o]=h.useState(!1);return E.jsxs("div",{onClick:n,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),style:{padding:"3px 8px 3px 20px",cursor:n?"pointer":"default",background:r?t.sidebarItemHover:"transparent",display:"flex",alignItems:"center",gap:2,fontSize:12,color:t.textPrimary},children:[E.jsx(Ma,{type:e.type}),E.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),E.jsx(RA,{status:e.status})]})}function SA(){const{state:e,dispatch:t}=ae(),n=re[e.themeMode],[r,o]=h.useState(!0),[s,i]=h.useState([]),[a,T]=h.useState([]),[l,R]=h.useState(null),[c,S]=h.useState(null),[A,d]=h.useState(!0),[N,I]=h.useState(!0),[u,f]=h.useState(!0),[O,C]=h.useState(!0),m=h.useCallback(async()=>{o(!0);const p=await le.fetchLineage();i(p.nodes),T(p.edges),o(!1)},[]);h.useEffect(()=>{m()},[m]);const L=h.useCallback(async p=>{if(l===p){R(null),S(null);return}R(p);const F=await le.fetchBlockLineage(p);F&&S({ancestors:F.ancestors,descendants:F.descendants})},[l]),D=s.filter(p=>p.type==="block"),M=s.filter(p=>p.type==="metric"),x=s.filter(p=>p.type==="source_table"),B=[...new Set(s.map(p=>p.domain).filter(Boolean))],g=a.filter(p=>p.type==="crosses_domain");return r?E.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"Loading lineage..."}):s.length===0?E.jsx("div",{style:{padding:16,color:n.textMuted,fontSize:12},children:"No lineage data found. Add blocks and semantic layer definitions to see the lineage graph."}):E.jsxs("div",{style:{overflow:"auto",flex:1,fontSize:12},children:[E.jsxs("div",{style:{padding:"6px 8px",borderBottom:`1px solid ${n.headerBorder}`},children:[E.jsxs("button",{onClick:()=>t({type:"TOGGLE_LINEAGE_FULLSCREEN"}),style:{width:"100%",padding:"6px 10px",marginBottom:6,background:e.lineageFullscreen?"#388bfd":"transparent",border:`1px solid ${e.lineageFullscreen?"#388bfd":"#30363d"}`,borderRadius:5,color:e.lineageFullscreen?"#fff":n.textPrimary,fontSize:11,fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,transition:"all 0.15s"},children:[E.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[E.jsx("circle",{cx:"6",cy:"6",r:"3"}),E.jsx("circle",{cx:"18",cy:"6",r:"3"}),E.jsx("circle",{cx:"18",cy:"18",r:"3"}),E.jsx("line",{x1:"8.6",y1:"7.4",x2:"15.4",y2:"16.6"}),E.jsx("line",{x1:"9",y1:"6",x2:"15",y2:"6"})]}),e.lineageFullscreen?"Close Graph View":"Open Graph View"]}),E.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",fontSize:11,color:n.textMuted},children:[E.jsxs("span",{children:[D.length," blocks"]}),E.jsxs("span",{children:[M.length," metrics"]}),E.jsxs("span",{children:[x.length," tables"]}),g.length>0&&E.jsxs("span",{style:{color:"#d2a8ff"},children:[g.length," cross-domain"]})]})]}),l&&c&&E.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${n.headerBorder}`},children:[E.jsxs("div",{style:{fontWeight:600,color:n.textPrimary,marginBottom:4,display:"flex",alignItems:"center",gap:4},children:[E.jsx(Ma,{type:"block"}),l,E.jsx("button",{onClick:()=>{R(null),S(null)},style:{marginLeft:"auto",background:"transparent",border:"none",color:n.textMuted,cursor:"pointer",fontSize:14},children:"×"})]}),c.ancestors.length>0&&E.jsxs("div",{style:{marginTop:4},children:[E.jsxs("div",{style:{color:n.textMuted,fontSize:10,fontWeight:600,textTransform:"uppercase",marginBottom:2},children:["Upstream (",c.ancestors.length,")"]}),c.ancestors.map(p=>E.jsx(Qt,{node:p,t:n},p.id))]}),c.descendants.length>0&&E.jsxs("div",{style:{marginTop:4},children:[E.jsxs("div",{style:{color:n.textMuted,fontSize:10,fontWeight:600,textTransform:"uppercase",marginBottom:2},children:["Downstream (",c.descendants.length,")"]}),c.descendants.map(p=>E.jsx(Qt,{node:p,t:n},p.id))]})]}),E.jsx(Hn,{label:"Blocks",count:D.length,expanded:A,onToggle:()=>d(!A),t:n}),A&&D.map(p=>E.jsx(Qt,{node:p,t:n,onClick:()=>L(p.name)},p.id)),E.jsx(Hn,{label:"Metrics",count:M.length,expanded:N,onToggle:()=>I(!N),t:n}),N&&M.map(p=>E.jsx(Qt,{node:p,t:n},p.id)),E.jsx(Hn,{label:"Source Tables",count:x.length,expanded:u,onToggle:()=>f(!u),t:n}),u&&x.map(p=>E.jsx(Qt,{node:p,t:n},p.id)),E.jsx(Hn,{label:"Domains",count:B.length,expanded:O,onToggle:()=>C(!O),t:n}),O&&B.map(p=>{const F=D.filter(P=>P.domain===p),_=F.filter(P=>P.status==="certified").length,U=F.length>0?Math.round(_/F.length*100):0;return E.jsxs("div",{style:{padding:"3px 8px 3px 20px",fontSize:12,color:n.textPrimary,display:"flex",gap:4,alignItems:"center"},children:[E.jsx("span",{style:{color:ga.domain,fontSize:10,fontWeight:600},children:"DOM"}),E.jsx("span",{style:{flex:1},children:p}),E.jsxs("span",{style:{color:n.textMuted,fontSize:10},children:[_,"/",F.length," (",U,"%)"]})]},p)}),g.length>0&&E.jsxs(E.Fragment,{children:[E.jsx("div",{style:{padding:"6px 8px",fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.5px",color:n.textPrimary},children:"Cross-Domain Flows"}),g.map((p,F)=>E.jsxs("div",{style:{padding:"2px 8px 2px 20px",fontSize:11,color:n.textMuted},children:[p.sourceDomain," → ",p.targetDomain]},F))]})]})}const AA={files:"Explorer",schema:"Schema",semantic:"Semantic Layer",lineage:"Lineage",outline:"Outline",connection:"Connection",reference:"Quick Reference"};function dA({onOpenFile:e,onNavigateToCell:t}){const{state:n,dispatch:r}=ae(),o=re[n.themeMode],[s,i]=h.useState(!1),a=n.sidebarPanel;return E.jsxs("div",{style:{width:240,flexShrink:0,background:o.sidebarBg,borderRight:`1px solid ${o.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden"},children:[E.jsxs("div",{style:{height:36,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 10px 0 14px",borderBottom:`1px solid ${o.headerBorder}`},children:[E.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",color:o.textSecondary,fontFamily:o.font},children:AA[a??""]??""}),E.jsx("button",{title:"Collapse sidebar",onClick:()=>r({type:"TOGGLE_SIDEBAR"}),onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:"transparent",border:"none",cursor:"pointer",color:s?o.textPrimary:o.textMuted,padding:"2px 4px",borderRadius:4,fontSize:14,lineHeight:1,transition:"color 0.15s",display:"flex",alignItems:"center"},children:"‹"})]}),E.jsxs("div",{style:{flex:1,overflow:"hidden",display:"flex",flexDirection:"column"},children:[a==="files"&&E.jsx(hS,{onOpenFile:e}),a==="schema"&&E.jsx(DS,{}),a==="semantic"&&E.jsx(TA,{}),a==="lineage"&&E.jsx(SA,{}),a==="outline"&&E.jsx(bS,{onNavigate:t}),a==="connection"&&E.jsx(GS,{}),a==="reference"&&E.jsx(QS,{themeMode:n.themeMode})]})]})}function uA(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],a=s[2].trim();r.push({id:ze(),type:"markdown",content:`# ${i}`,status:"idle"}),a&&r.push({id:ze(),type:"dql",name:i.toLowerCase().replace(/\s+/g,"_"),content:a,status:"idle"})}return r.length===0&&r.push({id:ze(),type:"dql",content:e.trim(),status:"idle"}),{title:n,cells:r}}catch{return{title:"Untitled Workbook",cells:[{id:ze(),type:"dql",content:e.trim(),status:"idle"}]}}}function IA(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||ze(),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:ze(),type:"sql",content:e,status:"idle"}]}}}function NA(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 OA(e,t){return e.endsWith(".dql")?uA(t):IA(t)}function fA(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(T=>{const l=i[T];return l==null?"NULL":typeof l=="number"?String(l):typeof l=="boolean"?l?"TRUE":"FALSE":`'${String(l).replace(/'/g,"''")}'`}).join(", ")})`).join(`,
|
|
221
|
-
`),s=n.map(i=>`"${i.replace(/"/g,'""')}"`).join(", ");return`${e} AS (
|
|
222
|
-
SELECT * FROM (VALUES
|
|
223
|
-
${o}
|
|
224
|
-
) AS _t(${s})
|
|
225
|
-
)`}function hA(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function CA(){const{state:e}=ae();return{substituteVariables:h.useCallback(n=>{var R;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 a=n;const T=new Map,l=new Map;for(const c of e.cells){const S=(R=c.name)==null?void 0:R.trim();S&&(c.type==="param"?T.set(S,c):c.status==="success"&&c.result&&l.set(S,c.result))}for(const c of o){const S=c[1];if(T.has(S)){const A=T.get(S),d=A.paramConfig,N=A.paramValue??(d==null?void 0:d.defaultValue)??"",I=(d==null?void 0:d.paramType)??"text",u=hA(N,I);a=a.replace(c[0],u),s.push(S)}else l.has(S)&&(i.push(fA(S,l.get(S))),a=a.replace(c[0],`"${S}"`),s.push(S))}if(i.length===0&&s.length===0)return{sql:n,substituted:[]};if(i.length>0){const c=a.trimStart();/^WITH\s+/i.test(c)?a=a.replace(/^(\s*WITH\s+)/i,`$1${i.join(`,
|
|
226
|
-
`)},
|
|
227
|
-
`):a=`WITH ${i.join(`,
|
|
228
|
-
`)}
|
|
229
|
-
${a}`}return{sql:a,substituted:s}},[e.cells])}}const en=new Map;function LA(e){const t=e.match(/visualization\s*\{([^}]+)\}/is);if(!t)return;const n=t[1],r=s=>{var i;return(i=n.match(new RegExp(`\\b${s}\\s*=\\s*["']?([\\w-]+)["']?`,"i")))==null?void 0:i[1]},o=r("chart");if(o)return{chart:o,x:r("x"),y:r("y"),color:r("color"),title:r("title")}}function pA(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?_A(t):null}function _A(e){const t=e.match(/query\s*=\s*"""([\s\S]*?)"""/i);if(t)return t[1].trim()||null;const n=e.match(/"""([\s\S]*?)"""/);if(n)return n[1].trim()||null;if(/^\s*(dashboard|workbook)\s+"/i.test(e))return null;const r=e.match(/\b(SELECT|WITH|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|SHOW|DESCRIBE|EXPLAIN)\b([\s\S]*)/i);if(r){let o=r[0];const s=o.search(/\b(visualization|tests|block)\s*\{/i);return s>0&&(o=o.slice(0,s)),o=mA(o),o.trim()||null}return null}function mA(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 xr(){const{state:e,dispatch:t}=ae(),{substituteVariables:n}=CA(),r=h.useCallback(async a=>{const T=e.cells.find(d=>d.id===a);if(!T)return;const l=pA(T);if(!l)return;if(T.type==="dql"){const d=LA(T.content);d&&JSON.stringify(d)!==JSON.stringify(T.chartConfig)&&t({type:"UPDATE_CELL",id:a,updates:{chartConfig:d}})}const{sql:R}=n(l),c=Date.now(),S=en.get(a);S&&S.abort();const A=new AbortController;en.set(a,A),t({type:"UPDATE_CELL",id:a,updates:{status:"running",error:void 0,result:void 0}});try{const d=await le.executeQuery(R,A.signal),N=Date.now()-c,I=(T.executionCount??0)+1;t({type:"UPDATE_CELL",id:a,updates:{status:"success",result:{...d,executionTime:d.executionTime??N,rowCount:d.rowCount??d.rows.length},executionCount:I}}),t({type:"APPEND_QUERY_LOG",entry:{id:ze(),cellName:T.name??T.id,rows:d.rowCount??d.rows.length,time:d.executionTime??N,ts:new Date}}),setTimeout(()=>{t({type:"UPDATE_CELL",id:a,updates:{status:"idle"}})},2e3)}catch(d){if(A.signal.aborted){t({type:"UPDATE_CELL",id:a,updates:{status:"idle",error:void 0}});return}const N=Date.now()-c,I=d instanceof Error?d.message:String(d);t({type:"UPDATE_CELL",id:a,updates:{status:"error",error:I,executionCount:(T.executionCount??0)+1}}),t({type:"APPEND_QUERY_LOG",entry:{id:ze(),cellName:T.name??T.id,rows:0,time:N,ts:new Date,error:I}})}finally{en.delete(a)}},[e.cells,t]),o=h.useCallback(async()=>{for(const a of e.cells)a.type!=="markdown"&&await r(a.id)},[e.cells,r]),s=h.useCallback(async a=>{if(!a)return;const T=`{{${a}}}`;for(const l of e.cells)l.type==="markdown"||l.type==="param"||l.content.includes(T)&&await r(l.id)},[e.cells,r]),i=h.useCallback(a=>{const T=en.get(a);T&&(T.abort(),en.delete(a)),t({type:"UPDATE_CELL",id:a,updates:{status:"idle"}})},[t]);return{executeCell:r,executeAll:o,executeDependents:s,cancelCell:i}}function pe(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function DA(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 gA(e){const t=e.split(`
|
|
230
|
-
`),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(pe(i));continue}if(i.startsWith("### ")){o&&(n.push("</ul>"),o=!1),n.push(`<h3>${pe(i.slice(4))}</h3>`);continue}if(i.startsWith("## ")){o&&(n.push("</ul>"),o=!1),n.push(`<h2>${pe(i.slice(3))}</h2>`);continue}if(i.startsWith("# ")){o&&(n.push("</ul>"),o=!1),n.push(`<h1>${pe(i.slice(2))}</h1>`);continue}if(i.startsWith("> ")){o&&(n.push("</ul>"),o=!1),n.push(`<blockquote><p>${pe(i.slice(2))}</p></blockquote>`);continue}if(i.startsWith("- ")||i.startsWith("* ")){o||(n.push("<ul>"),o=!0),n.push(`<li>${ii(i.slice(2))}</li>`);continue}if(o&&(n.push("</ul>"),o=!1),i.trim()===""){n.push("<br>");continue}n.push(`<p>${ii(i)}</p>`)}return o&&n.push("</ul>"),r&&n.push("</code></pre>"),n.join(`
|
|
231
|
-
`)}function ii(e){return pe(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>")}function MA(e){const{columns:t,rows:n}=e,r=n.slice(0,200),o=n.length>200,s=t.map(a=>`<th>${pe(a)}</th>`).join(""),i=r.map(a=>`<tr>${t.map(l=>{const R=a[l],c=typeof R=="number",S=R==null?"—":String(R);return`<td${c?' class="num"':""}>${pe(S)}</td>`}).join("")}</tr>`).join("");return`
|
|
232
|
-
<div class="table-wrap">
|
|
233
|
-
<table>
|
|
234
|
-
<thead><tr>${s}</tr></thead>
|
|
235
|
-
<tbody>${i}</tbody>
|
|
236
|
-
</table>
|
|
237
|
-
${o?`<p class="truncated">Showing first 200 of ${n.length.toLocaleString()} rows</p>`:""}
|
|
238
|
-
</div>`}function xA(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 PA(e){const t=xA(e);if(!t)return null;const n=e.rows.slice(0,20).map(R=>({label:String(R[t.labelCol]??""),value:Number(R[t.valueCol]??0)})),r=Math.max(...n.map(R=>R.value),1),o=28,s=6,i=140,a=440,T=n.length*(o+s)+40,l=n.map((R,c)=>{const S=c*(o+s)+20,A=Math.max(R.value/r*a,2);return`
|
|
239
|
-
<text x="${i-6}" y="${S+o/2+4}" text-anchor="end" font-size="11" fill="#8b949e">${pe(R.label.slice(0,20))}</text>
|
|
240
|
-
<rect x="${i}" y="${S}" width="${A}" height="${o}" rx="3" fill="#388bfd" />
|
|
241
|
-
<text x="${i+A+5}" y="${S+o/2+4}" font-size="11" fill="#e6edf3">${DA(R.value)}</text>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" width="${i+a+80}" height="${T}" style="max-width:100%">${l}</svg>`}function yA(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${gA(r.content)}</section>`;const o=r.name?`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span><span class="cell-name">${pe(r.name)}</span></div>`:`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span></div>`,s=`<pre class="cell-code"><code>${pe(r.content)}</code></pre>`;let i="";if(r.result&&r.result.rows.length>0){const a=PA(r.result),T=MA(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>`}${a??""}${a?"":T}</div>`}else r.error&&(i=`<div class="cell-error">⚠ ${pe(r.error)}</div>`);return`<section class="cell sql-cell">${o}${s}${i}</section>`}).join(`
|
|
242
|
-
`);return`<!DOCTYPE html>
|
|
243
|
-
<html lang="en">
|
|
244
|
-
<head>
|
|
245
|
-
<meta charset="UTF-8">
|
|
246
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
247
|
-
<title>${pe(e)}</title>
|
|
248
|
-
<style>
|
|
249
|
-
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
|
250
|
-
body {
|
|
251
|
-
font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
252
|
-
background: #0d1117; color: #e6edf3;
|
|
253
|
-
line-height: 1.6; padding: 0;
|
|
254
|
-
}
|
|
255
|
-
.page-header {
|
|
256
|
-
background: #161b22; border-bottom: 1px solid #21262d;
|
|
257
|
-
padding: 16px 32px; display: flex; align-items: center; gap: 12px;
|
|
258
|
-
}
|
|
259
|
-
.logo {
|
|
260
|
-
width: 28px; height: 28px; border-radius: 6px;
|
|
261
|
-
background: linear-gradient(135deg, #388bfd, #1f6feb);
|
|
262
|
-
display: flex; align-items: center; justify-content: center;
|
|
263
|
-
font-size: 10px; font-weight: 700; color: #fff;
|
|
264
|
-
font-family: monospace; letter-spacing: -0.5px; flex-shrink: 0;
|
|
265
|
-
}
|
|
266
|
-
.page-title { font-size: 18px; font-weight: 600; color: #e6edf3; }
|
|
267
|
-
.page-meta { font-size: 12px; color: #8b949e; margin-left: auto; }
|
|
268
|
-
.content { max-width: 900px; margin: 0 auto; padding: 32px 24px; display: flex; flex-direction: column; gap: 24px; }
|
|
269
|
-
.cell { border-radius: 8px; overflow: hidden; }
|
|
270
|
-
.md-cell { padding: 4px 0; }
|
|
271
|
-
.md-cell h1 { font-size: 26px; font-weight: 700; color: #e6edf3; margin: 0 0 12px; }
|
|
272
|
-
.md-cell h2 { font-size: 20px; font-weight: 600; color: #e6edf3; margin: 20px 0 10px; }
|
|
273
|
-
.md-cell h3 { font-size: 16px; font-weight: 600; color: #e6edf3; margin: 16px 0 8px; }
|
|
274
|
-
.md-cell p { color: #c9d1d9; margin-bottom: 8px; }
|
|
275
|
-
.md-cell ul { padding-left: 20px; color: #c9d1d9; margin-bottom: 8px; }
|
|
276
|
-
.md-cell code { background: #21262d; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 13px; }
|
|
277
|
-
.md-cell pre { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 14px; overflow-x: auto; margin-bottom: 8px; }
|
|
278
|
-
.md-cell pre code { background: none; padding: 0; }
|
|
279
|
-
.md-cell blockquote { border-left: 3px solid #388bfd; padding-left: 14px; color: #8b949e; }
|
|
280
|
-
.sql-cell { background: #161b22; border: 1px solid #30363d; }
|
|
281
|
-
.cell-header { display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-bottom: 1px solid #21262d; background: #1c2128; }
|
|
282
|
-
.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; }
|
|
283
|
-
.cell-name { font-size: 12px; color: #388bfd; font-family: monospace; }
|
|
284
|
-
.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; }
|
|
285
|
-
.cell-output { padding: 14px; }
|
|
286
|
-
.output-meta { font-size: 11px; color: #8b949e; margin-bottom: 10px; }
|
|
287
|
-
.table-wrap { overflow-x: auto; }
|
|
288
|
-
table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
|
289
|
-
th { background: #1c2128; color: #8b949e; font-weight: 600; text-align: left; padding: 7px 12px; border-bottom: 1px solid #30363d; white-space: nowrap; }
|
|
290
|
-
td { padding: 6px 12px; border-bottom: 1px solid #21262d; color: #e6edf3; }
|
|
291
|
-
td.num { text-align: right; font-family: monospace; }
|
|
292
|
-
tr:last-child td { border-bottom: none; }
|
|
293
|
-
.truncated { font-size: 11px; color: #8b949e; margin-top: 8px; }
|
|
294
|
-
.cell-error { padding: 12px 14px; background: #3d1a1a; border-top: 1px solid #f85149; color: #f85149; font-size: 13px; }
|
|
295
|
-
.exported-by { text-align: center; color: #484f58; font-size: 11px; padding: 40px 0 24px; }
|
|
296
|
-
</style>
|
|
297
|
-
</head>
|
|
298
|
-
<body>
|
|
299
|
-
<div class="page-header">
|
|
300
|
-
<div class="logo">DQL</div>
|
|
301
|
-
<span class="page-title">${pe(e)}</span>
|
|
302
|
-
<span class="page-meta">Exported ${new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}</span>
|
|
303
|
-
</div>
|
|
304
|
-
<div class="content">
|
|
305
|
-
${n}
|
|
306
|
-
</div>
|
|
307
|
-
<p class="exported-by">Built with DQL Notebook</p>
|
|
308
|
-
</body>
|
|
309
|
-
</html>`}function UA(e,t){const n=yA(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 bA(e,t){var s,i;const n=[];n.push(`workbook "${e}" {`);let r=0,o=0;for(const a of t)if(a.type!=="param"){if(a.type==="markdown"){o++;const T=`Markdown ${o}`;n.push(""),n.push(` page "${T}" {`);const l=a.content.split(`
|
|
310
|
-
`);for(const R of l)n.push(` // ${R}`);n.push(" }")}else if(a.type==="sql"){r++;const T=((s=a.name)==null?void 0:s.trim())||`Query ${r}`;n.push(""),n.push(` page "${T}" {`);const R=a.content.trim().split(`
|
|
311
|
-
`).map(c=>` ${c}`).join(`
|
|
312
|
-
`);n.push(" chart.table("),n.push(R+","),n.push(` title = "${T}"`),n.push(" )"),n.push(" }")}else if(a.type==="dql"){r++;const T=((i=a.name)==null?void 0:i.trim())||`Query ${r}`;n.push(""),n.push(` page "${T}" {`);const l=a.content.trim().split(`
|
|
313
|
-
`);for(const R of l)n.push(` ${R}`);n.push(" }")}}return n.push("}"),n.join(`
|
|
314
|
-
`)}function vA(e,t){const n=bA(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 BA({t:e}){return E.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:E.jsx("span",{style:{color:"#ffffff",fontSize:10,fontWeight:700,fontFamily:e.fontMono,letterSpacing:"-0.5px"},children:"DQL"})})}function GA(){const{state:e,dispatch:t}=ae(),n=re[e.themeMode],{executeAll:r}=xr(),[o,s]=h.useState(!1),[i,a]=h.useState(""),[T,l]=h.useState(!1),[R,c]=h.useState(!1),[S,A]=h.useState(!1),[d,N]=h.useState(!1),[I,u]=h.useState(!1),[f,O]=h.useState(!1),C=h.useRef(null),m=h.useRef(null);h.useEffect(()=>{o&&m.current&&(m.current.focus(),m.current.select())},[o]),h.useEffect(()=>{if(!f)return;function g(p){C.current&&!C.current.contains(p.target)&&O(!1)}return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[f]);const L=()=>{a(e.notebookTitle),s(!0)},D=()=>{s(!1),i.trim()&&i!==e.notebookTitle&&t({type:"SET_NOTEBOOK_DIRTY",dirty:!0})},M=h.useCallback(async()=>{var g;if(e.activeFile){t({type:"SET_SAVING",saving:!0});try{const p=e.activeFile.type==="block"?((g=e.cells[0])==null?void 0:g.content)??"":NA(e.notebookTitle,e.cells);await le.saveNotebook(e.activeFile.path,p),t({type:"SET_NOTEBOOK_DIRTY",dirty:!1}),l(!0),setTimeout(()=>l(!1),2e3)}catch(p){console.error("Save failed:",p)}finally{t({type:"SET_SAVING",saving:!1})}}},[e.activeFile,e.notebookTitle,e.cells,t]);h.useEffect(()=>{const g=p=>{(p.metaKey||p.ctrlKey)&&p.key==="s"&&(p.preventDefault(),M())};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[M]),h.useEffect(()=>{if(!e.autoSave||!e.notebookDirty||!e.activeFile)return;const g=setTimeout(()=>{M()},2e3);return()=>clearTimeout(g)},[e.autoSave,e.notebookDirty,e.activeFile,e.cells,M]);const x=()=>{t({type:"SET_THEME",mode:e.themeMode==="dark"?"light":"dark"})},B={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 E.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:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[E.jsx(BA,{t:n}),E.jsx("div",{style:{width:1,height:20,background:n.headerBorder,flexShrink:0}}),e.activeFile&&E.jsx("span",{style:{fontSize:10,fontWeight:600,color:e.activeFile.type==="block"?"#e3b341":n.accent,background:`${e.activeFile.type==="block"?"#e3b341":n.accent}18`,borderRadius:4,padding:"2px 6px",fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em",flexShrink:0},children:e.activeFile.type}),e.activeFile?o?E.jsx("input",{ref:m,value:i,onChange:g=>a(g.target.value),onBlur:D,onKeyDown:g=>{g.key==="Enter"&&D(),g.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}}):E.jsxs("span",{onClick:L,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:[e.notebookTitle||"Untitled",e.notebookDirty&&E.jsx("span",{style:{color:n.textMuted,marginLeft:4},children:"●"})]}):E.jsx("span",{style:{color:n.textSecondary,fontSize:13,fontFamily:n.font,padding:"2px 4px"},children:"DQL Notebook"})]}),E.jsx("div",{style:{flex:1}}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[E.jsxs("button",{onClick:r,disabled:!e.activeFile,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{...B,background:(R&&e.activeFile,n.accent),color:"#ffffff",border:`1px solid ${n.accent}`,opacity:e.activeFile?R?.9:1:.4},children:[E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:E.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})}),"Run All"]}),E.jsx("div",{style:{width:1,height:20,background:n.headerBorder}}),E.jsx("button",{onClick:x,onMouseEnter:()=>N(!0),onMouseLeave:()=>N(!1),title:e.themeMode==="dark"?"Switch to light mode":"Switch to dark mode",style:{...B,background:d?n.btnHover:n.btnBg,color:n.textSecondary,padding:"0 8px",fontSize:14},children:e.themeMode==="dark"?"☀":"☾"}),E.jsx("button",{onClick:M,disabled:!e.activeFile||e.savingFile,onMouseEnter:()=>A(!0),onMouseLeave:()=>A(!1),title:"Save (Cmd+S)",style:{...B,background:S&&e.activeFile?n.btnHover:n.btnBg,color:T?n.success:n.textSecondary,opacity:e.activeFile?1:.4},children:e.savingFile?E.jsxs(E.Fragment,{children:[E.jsx(HA,{}),"Saving…"]}):T?E.jsx(E.Fragment,{children:"✓ Saved"}):E.jsx(E.Fragment,{children:"Save"})}),E.jsx("button",{onClick:()=>t({type:"SET_AUTO_SAVE",enabled:!e.autoSave}),title:e.autoSave?"Auto-save on":"Auto-save off",style:{...B,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"}),E.jsxs("button",{onClick:()=>t({type:"TOGGLE_DASHBOARD_MODE"}),disabled:!e.activeFile,title:e.dashboardMode?"Switch to editor mode":"Switch to dashboard mode",style:{...B,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:[E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:e.dashboardMode?E.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"}):E.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"]}),E.jsx("div",{style:{width:1,height:20,background:n.headerBorder}}),E.jsxs("div",{ref:C,style:{position:"relative"},children:[E.jsxs("button",{onClick:()=>{e.activeFile&&O(g=>!g)},disabled:!e.activeFile,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),title:"Export options",style:{...B,background:(I||f)&&e.activeFile?n.btnHover:n.btnBg,color:n.textSecondary,opacity:e.activeFile?1:.4},children:[E.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:[E.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"}),E.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",E.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"currentColor",style:{marginLeft:1},children:E.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),f&&E.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:[E.jsx(Ei,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{UA(e.notebookTitle||"dashboard",e.cells),O(!1)}}),E.jsx(Ei,{label:"Export .dql",description:"DQL workbook file",t:n,onClick:()=>{vA(e.notebookTitle||"notebook",e.cells),O(!1)}})]})]})]})]})}function Ei({label:e,description:t,t:n,onClick:r}){const[o,s]=h.useState(!1);return E.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:[E.jsx("span",{style:{fontSize:12,fontWeight:500,color:n.textPrimary,fontFamily:n.font},children:e}),E.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:t})]})}function HA(){return E.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",style:{animation:"spin 0.8s linear infinite"},children:[E.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"}),E.jsx("circle",{cx:"6",cy:"6",r:"4.5",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"14 7"})]})}function FA(e){return e.toTimeString().slice(0,8)}function wA(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function YA(){const{state:e,dispatch:t}=ae(),n=re[e.themeMode],[r,o]=h.useState(!1),s=e.queryLog.filter(a=>a.error),i=a=>t({type:"SET_DEV_PANEL_TAB",tab:a});return E.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&&E.jsxs(E.Fragment,{children:[E.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(a=>E.jsx(VA,{label:a==="errors"?`Errors${s.length>0?` (${s.length})`:""}`:`Logs (${e.queryLog.length})`,active:e.devPanelTab===a,onClick:()=>i(a),t:n},a)),E.jsx("div",{style:{flex:1}}),E.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"})]}),E.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[e.devPanelTab==="logs"&&(e.queryLog.length===0?E.jsx(ai,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(a=>E.jsx(li,{entry:a,t:n},a.id))),e.devPanelTab==="errors"&&(s.length===0?E.jsx(ai,{t:n,message:"No errors."}):[...s].reverse().map(a=>E.jsx(li,{entry:a,t:n},a.id)))]})]}),E.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:[E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:E.jsx("path",{d:e.devPanelOpen?"M1 7l4-4 4 4":"M1 3l4 4 4-4",strokeWidth:"1.5",stroke:"currentColor",fill:"none"})}),"Dev"]})]})}function VA({label:e,active:t,onClick:n,t:r}){const[o,s]=h.useState(!1);return E.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 ai({t:e,message:t}){return E.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:e.textMuted,fontSize:12,fontFamily:e.font,fontStyle:"italic"},children:t})}function li({entry:e,t}){return E.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:[E.jsx("span",{style:{color:t.textMuted,flexShrink:0},children:FA(e.ts)}),E.jsx("span",{style:{flexShrink:0,color:t.textPrimary,maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.cellName}),e.error?E.jsx("span",{style:{color:t.error,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.error}):E.jsxs(E.Fragment,{children:[E.jsxs("span",{style:{color:t.textMuted},children:[e.rows.toLocaleString()," rows"]}),E.jsx("span",{style:{color:t.textMuted},children:wA(e.time)})]})]})}function WA({onOpenFile:e}){const{state:t,dispatch:n}=ae(),r=re[t.themeMode],o=t.files.slice(0,3);return E.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",background:r.appBg,padding:40,overflow:"auto"},children:E.jsxs("div",{style:{maxWidth:720,width:"100%",display:"flex",flexDirection:"column",alignItems:"center",gap:48},children:[E.jsxs("div",{style:{textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[E.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:E.jsx("span",{style:{color:"#fff",fontSize:26,fontWeight:800,fontFamily:r.fontMono,letterSpacing:"-1px"},children:"DQL"})}),E.jsxs("div",{children:[E.jsx("h1",{style:{fontSize:32,fontWeight:700,color:r.textPrimary,fontFamily:r.font,marginBottom:8,letterSpacing:"-0.5px"},children:"DQL Notebook"}),E.jsx("p",{style:{fontSize:15,color:r.textSecondary,fontFamily:r.font,letterSpacing:"0.02em"},children:"Analytics as Code"})]})]}),E.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:16,width:"100%"},children:[E.jsx(Ti,{title:"New Notebook",description:"Start a fresh analysis with an empty notebook.",icon:E.jsx(XA,{}),accent:r.accent,onClick:()=>n({type:"OPEN_NEW_NOTEBOOK_MODAL"}),t:r}),E.jsx(kA,{recentFiles:o,onOpenFile:e,t:r}),E.jsx(Ti,{title:"New Block",description:"Create a reusable SQL block file.",icon:E.jsx(KA,{}),accent:"#e3b341",onClick:()=>n({type:"OPEN_NEW_BLOCK_MODAL"}),t:r})]}),E.jsxs("div",{style:{width:"100%",borderRadius:10,border:`1px solid ${r.cellBorder}`,padding:"16px 20px",background:r.cellBg},children:[E.jsx("div",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.08em",textTransform:"uppercase",color:r.textMuted,fontFamily:r.font,marginBottom:12},children:"Quick Tips"}),E.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])=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[E.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}),E.jsx("span",{style:{fontSize:12,color:r.textMuted,fontFamily:r.font},children:i})]},s))})]})]})})}function Ti({title:e,description:t,icon:n,accent:r,onClick:o,t:s}){const[i,a]=h.useState(!1);return E.jsxs("button",{onClick:o,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!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:[E.jsx("div",{style:{width:36,height:36,borderRadius:8,background:`${r}18`,display:"flex",alignItems:"center",justifyContent:"center",color:r},children:n}),E.jsxs("div",{children:[E.jsx("div",{style:{fontSize:13,fontWeight:600,color:s.textPrimary,fontFamily:s.font,marginBottom:4},children:e}),E.jsx("div",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font,lineHeight:1.5},children:t})]})]})}function kA({recentFiles:e,onOpenFile:t,t:n}){const[r,o]=h.useState(!1);return E.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:[E.jsx("div",{style:{width:36,height:36,borderRadius:8,background:`${n.warning}18`,display:"flex",alignItems:"center",justifyContent:"center",color:n.warning},children:E.jsx($A,{})}),E.jsxs("div",{children:[E.jsx("div",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,fontFamily:n.font,marginBottom:8},children:"Open Recent"}),e.length===0?E.jsx("div",{style:{fontSize:12,color:n.textMuted,fontFamily:n.font,fontStyle:"italic"},children:"No recent files."}):E.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:e.map(s=>E.jsx(jA,{file:s,onClick:()=>t(s),t:n},s.path))})]})]})}function jA({file:e,onClick:t,t:n}){const[r,o]=h.useState(!1);return E.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 XA(){return E.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 $A(){return E.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 KA(){return E.jsx("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"currentColor",children:E.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 ci=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class Rn{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?a=>s(ci(a)):ci,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 _R(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=PR(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=mR(t);let o=this.normalize(n);if(o.length)for(let s=0,i=r;;s++){let a=o.charCodeAt(s),T=this.match(a,i,this.bufferPos+this.bufferStart);if(s==o.length-1){if(T)return this.value=T,this;break}i==r&&s<n.length&&n.charCodeAt(s)==a&&i++}}}match(t,n,r){let o=null;for(let s=0;s<this.matches.length;s+=2){let i=this.matches[s],a=!1;this.query.charCodeAt(i)==t&&(i==this.query.length-1?o={from:this.matches[s+1],to:r}:(this.matches[s]++,a=!0)),a||(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"&&(Rn.prototype[Symbol.iterator]=function(){return this});const xa={from:-1,to:-1,match:/.*/.exec("")},ds="gm"+(/x/.unicode==null?"":"u");class Pa{constructor(t,n,r,o=0,s=t.length){if(this.text=t,this.to=s,this.curLine="",this.done=!1,this.value=xa,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new ya(t,n,r,o,s);this.re=new RegExp(n,ds+(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=lr(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=lr(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 Zr=new WeakMap;class yt{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let o=Zr.get(t);if(!o||o.from>=r||o.to<=n){let a=new yt(n,t.sliceString(n,r));return Zr.set(t,a),a}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)),Zr.set(t,new yt(i,s)),new yt(n,s.slice(n-i,r-i))}}class ya{constructor(t,n,r,o,s){this.text=t,this.to=s,this.done=!1,this.value=xa,this.matchPos=lr(t,o),this.re=new RegExp(n,ds+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=yt.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=lr(this.text,o+(r==o?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=yt.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(Pa.prototype[Symbol.iterator]=ya.prototype[Symbol.iterator]=function(){return this});function zA(e){try{return new RegExp(e,ds),!0}catch{return!1}}function lr(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 JA=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:o}=CR(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 a=t.doc.lineAt(t.selection.main.head),[,T,l,R,c]=i,S=R?+R.slice(1):0,A=l?+l:a.number;if(l&&c){let I=A/100;T&&(I=I*(T=="-"?-1:1)+a.number/t.doc.lines),A=Math.round(t.doc.lines*I)}else l&&T&&(A=A*(T=="-"?-1:1)+a.number);let d=t.doc.line(Math.max(1,Math.min(t.doc.lines,A))),N=Be.cursor(d.from+Math.max(0,Math.min(S,d.length)));e.dispatch({effects:[r,Ce.scrollIntoView(N.from,{y:"center"})],selection:N})}),!0},qA=({state:e,dispatch:t})=>{let{selection:n}=e,r=Be.create(n.ranges.map(o=>e.wordAt(o.head)||Be.cursor(o.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function ZA(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,a=new Rn(e.doc,t,r[r.length-1].to);;)if(a.next(),a.done){if(i)return null;a=new Rn(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),i=!0}else{if(i&&r.some(T=>T.from==a.value.from))continue;if(s){let T=e.wordAt(a.value.from);if(!T||T.from!=a.value.from||T.to!=a.value.to)continue}return a.value}}const QA=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(s=>s.from===s.to))return qA({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=ZA(e,r);return o?(t(e.update({selection:e.selection.addRange(Be.range(o.from,o.to),!1),effects:Ce.scrollIntoView(o.to)})),!0):!1},ft=DR.define({combine(e){return gR(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new Ad(t),scrollToMatch:t=>Ce.scrollIntoView(t)})}});function ed(e){return e?[ft.of(e),zo]:zo}class Ua{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||zA(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"?`
|
|
315
|
-
`: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 id(this):new rd(this)}getCursor(t,n=0,r){let o=t.doc?t:La.create({doc:t});return r==null&&(r=o.doc.length),this.regexp?Mt(this,o,n,r):gt(this,o,n,r)}}class ba{constructor(t){this.spec=t}}function td(e,t,n){return(r,o,s,i)=>{if(n&&!n(r,o,s,i))return!1;let a=r>=i&&o<=i+s.length?s.slice(r-i,o-i):t.doc.sliceString(r,o);return e(a,t,r,o)}}function gt(e,t,n,r){let o;return e.wholeWord&&(o=nd(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(o=td(e.test,t,o)),new Rn(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:s=>s.toLowerCase(),o)}function nd(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(Tr(o,n-s))!=rt.Word||t(cr(o,n-s))!=rt.Word)&&(t(cr(o,r-s))!=rt.Word||t(Tr(o,r-s))!=rt.Word))}class rd extends ba{constructor(t){super(t)}nextMatch(t,n,r){let o=gt(this.spec,t,r,t.doc.length).nextOverlapping();if(o.done){let s=Math.min(t.doc.length,n+this.spec.unquoted.length);o=gt(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=gt(this.spec,t,s,o),a=null;for(;!i.nextOverlapping().done;)a=i.value;if(a)return a;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=gt(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=gt(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 od(e,t,n){return(r,o,s)=>(!n||n(r,o,s))&&e(s[0],t,r,o)}function Mt(e,t,n,r){let o;return e.wholeWord&&(o=sd(t.charCategorizer(t.selection.main.head))),e.test&&(o=od(e.test,t,o)),new Pa(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:o},n,r)}function Tr(e,t){return e.slice(pa(e,t,!1),t)}function cr(e,t){return e.slice(t,pa(e,t))}function sd(e){return(t,n,r)=>!r[0].length||(e(Tr(r.input,r.index))!=rt.Word||e(cr(r.input,r.index))!=rt.Word)&&(e(cr(r.input,r.index+r[0].length))!=rt.Word||e(Tr(r.input,r.index+r[0].length))!=rt.Word)}class id extends ba{nextMatch(t,n,r){let o=Mt(this.spec,t,r,t.doc.length).next();return o.done&&(o=Mt(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=Mt(this.spec,t,s,r),a=null;for(;!i.next().done;)a=i.value;if(a&&(s==n||a.from>s+10))return a;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=Mt(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=Mt(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 Sn=Mr.define(),us=Mr.define(),ot=Ca.define({create(e){return new Qr(Ko(e).create(),null)},update(e,t){for(let n of t.effects)n.is(Sn)?e=new Qr(n.value.create(),e.panel):n.is(us)&&(e=new Qr(e.query,n.value?Is:null));return e},provide:e=>LR.from(e,t=>t.panel)});class Qr{constructor(t,n){this.query=t,this.panel=n}}const Ed=Rt.mark({class:"cm-searchMatch"}),ad=Rt.mark({class:"cm-searchMatch cm-searchMatch-selected"}),ld=MR.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(ot))}update(e){let t=e.state.field(ot);(t!=e.startState.field(ot)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Rt.none;let{view:n}=this,r=new xR;for(let o=0,s=n.visibleRanges,i=s.length;o<i;o++){let{from:a,to:T}=s[o];for(;o<i-1&&T>s[o+1].from-500;)T=s[++o].to;e.highlight(n.state,a,T,(l,R)=>{let c=n.state.selection.ranges.some(S=>S.from==l&&S.to==R);r.add(l,R,c?ad:Ed)})}return r.finish()}},{decorations:e=>e.decorations});function _n(e){return t=>{let n=t.state.field(ot,!1);return n&&n.query.spec.valid?e(t,n):Ga(t)}}const Rr=_n((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let o=Be.single(r.from,r.to),s=e.state.facet(ft);return e.dispatch({selection:o,effects:[Ns(e,r),s.scrollToMatch(o.main,e)],userEvent:"select.search"}),Ba(e),!0}),Sr=_n((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,o=t.prevMatch(n,r,r);if(!o)return!1;let s=Be.single(o.from,o.to),i=e.state.facet(ft);return e.dispatch({selection:s,effects:[Ns(e,o),i.scrollToMatch(s.main,e)],userEvent:"select.search"}),Ba(e),!0}),Td=_n((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:Be.create(n.map(r=>Be.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),cd=({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 a=new Rn(e.doc,e.sliceDoc(r,o));!a.next().done;){if(s.length>1e3)return!1;a.value.from==r&&(i=s.length),s.push(Be.range(a.value.from,a.value.to))}return t(e.update({selection:Be.create(s,i),userEvent:"select.search.matches"})),!0},Ri=_n((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,a=[],T,l,R=[];i.from==r&&i.to==o&&(l=n.toText(t.getReplacement(i)),a.push({from:i.from,to:i.to,insert:l}),i=t.nextMatch(n,i.from,i.to),R.push(Ce.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+".")));let c=e.state.changes(a);return i&&(T=Be.single(i.from,i.to).map(c),R.push(Ns(e,i)),R.push(n.facet(ft).scrollToMatch(T.main,e))),e.dispatch({changes:c,selection:T,effects:R,userEvent:"input.replace"}),!0}),Rd=_n((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:Ce.announce.of(r),userEvent:"input.replace.all"}),!0});function Is(e){return e.state.facet(ft).createPanel(e)}function Ko(e,t){var n,r,o,s,i;let a=e.selection.main,T=a.empty||a.to>a.from+100?"":e.sliceDoc(a.from,a.to);if(t&&!T)return t;let l=e.facet(ft);return new Ua({search:((n=t==null?void 0:t.literal)!==null&&n!==void 0?n:l.literal)?T:T.replace(/\n/g,"\\n"),caseSensitive:(r=t==null?void 0:t.caseSensitive)!==null&&r!==void 0?r:l.caseSensitive,literal:(o=t==null?void 0:t.literal)!==null&&o!==void 0?o:l.literal,regexp:(s=t==null?void 0:t.regexp)!==null&&s!==void 0?s:l.regexp,wholeWord:(i=t==null?void 0:t.wholeWord)!==null&&i!==void 0?i:l.wholeWord})}function va(e){let t=ha(e,Is);return t&&t.dom.querySelector("[main-field]")}function Ba(e){let t=va(e);t&&t==e.root.activeElement&&t.select()}const Ga=e=>{let t=e.state.field(ot,!1);if(t&&t.panel){let n=va(e);if(n&&n!=e.root.activeElement){let r=Ko(e.state,t.query.spec);r.valid&&e.dispatch({effects:Sn.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[us.of(!0),t?Sn.of(Ko(e.state,t.query.spec)):Mr.appendConfig.of(zo)]});return!0},Ha=e=>{let t=e.state.field(ot,!1);if(!t||!t.panel)return!1;let n=ha(e,Is);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:us.of(!1)}),!0},Sd=[{key:"Mod-f",run:Ga,scope:"editor search-panel"},{key:"F3",run:Rr,shift:Sr,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:Rr,shift:Sr,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Ha,scope:"editor search-panel"},{key:"Mod-Shift-l",run:cd},{key:"Mod-Alt-g",run:JA},{key:"Mod-d",run:QA,preventDefault:!0}];class Ad{constructor(t){this.view=t;let n=this.query=t.state.field(ot).query.spec;this.commit=this.commit.bind(this),this.searchField=Me("input",{value:n.search,placeholder:me(t,"Find"),"aria-label":me(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=Me("input",{value:n.replace,placeholder:me(t,"Replace"),"aria-label":me(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=Me("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=Me("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=Me("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(o,s,i){return Me("button",{class:"cm-button",name:o,onclick:s,type:"button"},i)}this.dom=Me("div",{onkeydown:o=>this.keydown(o),class:"cm-search"},[this.searchField,r("next",()=>Rr(t),[me(t,"next")]),r("prev",()=>Sr(t),[me(t,"previous")]),r("select",()=>Td(t),[me(t,"all")]),Me("label",null,[this.caseField,me(t,"match case")]),Me("label",null,[this.reField,me(t,"regexp")]),Me("label",null,[this.wordField,me(t,"by word")]),...t.state.readOnly?[]:[Me("br"),this.replaceField,r("replace",()=>Ri(t),[me(t,"replace")]),r("replaceAll",()=>Rd(t),[me(t,"replace all")])],Me("button",{name:"close",onclick:()=>Ha(t),"aria-label":me(t,"close"),type:"button"},["×"])])}commit(){let t=new Ua({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:Sn.of(t)}))}keydown(t){yR(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?Sr:Rr)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),Ri(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(Sn)&&!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(ft).top}}function me(e,t){return e.state.phrase(t)}const Fn=30,wn=/[\s\.,:;?!]/;function Ns(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-Fn),i=Math.min(o,n+Fn),a=e.state.sliceDoc(s,i);if(s!=r.from){for(let T=0;T<Fn;T++)if(!wn.test(a[T+1])&&wn.test(a[T])){a=a.slice(T);break}}if(i!=o){for(let T=a.length-1;T>a.length-Fn;T--)if(!wn.test(a[T-1])&&wn.test(a[T])){a=a.slice(0,T);break}}return Ce.announce.of(`${e.state.phrase("current match")}. ${a} ${e.state.phrase("on line")} ${r.number}.`)}const dd=Ce.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"}}),zo=[ot,pR.low(ld),dd];function ud(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 qn=Mr.define(),Id=Ca.define({create(){return Rt.none},update(e,t){for(const n of t.effects)if(n.is(qn)){if(!n.value)return Rt.none;const{from:r,to:o,message:s}=n.value;return Rt.set([Rt.mark({class:"cm-sql-error",attributes:{title:s}}).range(r,o)])}return e},provide:e=>Ce.decorations.from(e)}),Nd=Ce.baseTheme({".cm-sql-error":{textDecoration:"underline wavy #f85149",textUnderlineOffset:"3px",background:"rgba(248, 81, 73, 0.08)"}}),Od=Ce.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}),fd=Ce.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 Fa({value:e,onChange:t,onRun:n,themeMode:r,autoFocus:o,schema:s,errorMessage:i}){const a=re[r],T=h.useRef(null),l=h.useRef(null),R=h.useRef(n),c=h.useRef(t),S=h.useRef(new UR);return R.current=n,c.current=t,h.useEffect(()=>{if(!T.current)return;const A=bR.of([{key:"Shift-Enter",run:()=>(R.current(),!0)},{key:"Ctrl-Enter",mac:"Cmd-Enter",run:()=>(R.current(),!0)},{key:"Ctrl-/",mac:"Cmd-/",run:vR},BR,...GR,...HR,...FR,...Sd,...wR,...YR]),d=Ce.updateListener.of(C=>{C.docChanged&&c.current(C.state.doc.toString())}),N=Ce.theme({"&":{background:a.editorBg,fontFamily:a.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"}}),I=s?Bn({schema:s,upperCaseKeywords:!1}):Bn({upperCaseKeywords:!1}),u=[A,d,N,S.current.of(I),WR({closeOnBlur:!1}),kR(),jR(),XR(),$R(),KR(),zR(),JR(),Ce.lineWrapping,ed({top:!0}),Id,Nd,...r==="dark"?[VR,fd]:[Od,qR(ZR)]],f=La.create({doc:e,extensions:u}),O=new Ce({state:f,parent:T.current});return l.current=O,o&&O.focus(),()=>{O.destroy(),l.current=null}},[r]),h.useEffect(()=>{const A=l.current;if(!A)return;const d=s?Bn({schema:s,upperCaseKeywords:!1}):Bn({upperCaseKeywords:!1});A.dispatch({effects:S.current.reconfigure(d)})},[s]),h.useEffect(()=>{const A=l.current;if(!A)return;const d=A.state.doc.toString();d!==e&&A.dispatch({changes:{from:0,to:d.length,insert:e}})},[e]),h.useEffect(()=>{const A=l.current;if(!A)return;if(!i){A.dispatch({effects:qn.of(null)});return}const d=ud(i),N=A.state.doc;if(d&&d.line>=1&&d.line<=N.lines){const I=N.line(d.line),u=I.from+Math.max(0,d.col-1),f=Math.max(u+1,I.to);A.dispatch({effects:qn.of({from:Math.min(u,N.length),to:Math.min(f,N.length),message:i})})}else if(N.lines>=1){const I=N.line(1);A.dispatch({effects:qn.of({from:I.from,to:Math.max(I.from+1,I.to),message:i})})}},[i]),E.jsx("div",{ref:T,style:{background:a.editorBg,minHeight:80}})}Fa.displayName="SQLCellEditor";function hd(e,t){const n=e.split(`
|
|
316
|
-
`),r=[];let o=0;for(;o<n.length;){const s=n[o],i=s.match(/^(#{1,6})\s+(.+)$/);if(i){const a=i[1].length,T=i[2],R=[28,22,18,16,14,13][a-1];r.push(E.jsx("div",{style:{fontSize:R,fontWeight:a<=2?700:600,color:t.textPrimary,fontFamily:t.font,lineHeight:1.3,marginBottom:a===1?12:8,marginTop:o>0?a===1?16:10:0,borderBottom:a===1?`1px solid ${t.cellBorder}`:void 0,paddingBottom:a===1?8:void 0},children:tn(T,t)},o)),o++;continue}if(/^[-*_]{3,}$/.test(s.trim())){r.push(E.jsx("hr",{style:{border:"none",borderTop:`1px solid ${t.cellBorder}`,margin:"12px 0"}},o)),o++;continue}if(s.startsWith("> ")){r.push(E.jsx("div",{style:{borderLeft:`3px solid ${t.textMuted}`,paddingLeft:12,marginLeft:4,color:t.textSecondary,fontStyle:"italic",fontFamily:t.fontSerif,fontSize:14},children:tn(s.slice(2),t)},o)),o++;continue}if(s.startsWith("```")){const a=[];for(o++;o<n.length&&!n[o].startsWith("```");)a.push(n[o]),o++;r.push(E.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:a.join(`
|
|
317
|
-
`)},o)),o++;continue}if(/^[-*+]\s/.test(s)){const a=[];for(;o<n.length&&/^[-*+]\s/.test(n[o]);)a.push(n[o].replace(/^[-*+]\s/,"")),o++;r.push(E.jsx("ul",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:a.map((T,l)=>E.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:tn(T,t)},l))},o));continue}if(/^\d+\.\s/.test(s)){const a=[];for(;o<n.length&&/^\d+\.\s/.test(n[o]);)a.push(n[o].replace(/^\d+\.\s/,"")),o++;r.push(E.jsx("ol",{style:{paddingLeft:20,marginBottom:8,color:t.textSecondary},children:a.map((T,l)=>E.jsx("li",{style:{fontSize:14,fontFamily:t.font,lineHeight:1.6,marginBottom:2},children:tn(T,t)},l))},o));continue}if(!s.trim()){r.push(E.jsx("div",{style:{height:8}},o)),o++;continue}r.push(E.jsx("p",{style:{fontSize:14,lineHeight:1.7,fontFamily:t.fontSerif,color:t.textSecondary,marginBottom:6},children:tn(s,t)},o)),o++}return r}function tn(e,t){const n=[];let r=e,o=0;for(;r.length>0;){const s=r.match(/\*{3}(.+?)\*{3}/),i=r.match(/\*{2}(.+?)\*{2}/),a=r.match(/\*(.+?)\*/),T=r.match(/`(.+?)`/),l=r.match(/\[(.+?)\]\((.+?)\)/),R=[s?{match:s,type:"boldItalic"}:null,i?{match:i,type:"bold"}:null,a?{match:a,type:"italic"}:null,T?{match:T,type:"code"}:null,l?{match:l,type:"link"}:null].filter(Boolean);if(R.length===0){n.push(E.jsx(Bt.Fragment,{children:r},o++));break}const c=R.reduce((A,d)=>(A.match.index??0)<(d.match.index??0)?A:d),S=c.match.index??0;switch(S>0&&n.push(E.jsx(Bt.Fragment,{children:r.slice(0,S)},o++)),c.type){case"boldItalic":n.push(E.jsx("strong",{style:{fontStyle:"italic"},children:c.match[1]},o++));break;case"bold":n.push(E.jsx("strong",{children:c.match[1]},o++));break;case"italic":n.push(E.jsx("em",{children:c.match[1]},o++));break;case"code":n.push(E.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:c.match[1]},o++));break;case"link":n.push(E.jsx("a",{href:c.match[2],target:"_blank",rel:"noopener noreferrer",style:{color:t.accent,textDecoration:"underline"},children:c.match[1]},o++));break}r=r.slice(S+c.match[0].length)}return E.jsx(E.Fragment,{children:n})}function Cd({value:e,onChange:t,onRun:n,themeMode:r}){const o=re[r],[s,i]=h.useState(!1),a=h.useRef(null);h.useEffect(()=>{if(s&&a.current){a.current.focus();const c=a.current;c.style.height="auto",c.style.height=`${Math.max(c.scrollHeight,80)}px`}},[s]);const T=()=>{i(!1)},l=c=>{if(c.key==="Escape"&&i(!1),c.key==="Enter"&&c.shiftKey&&(c.preventDefault(),i(!1),n==null||n()),c.key==="Tab"){c.preventDefault();const S=c.currentTarget,A=S.selectionStart,d=S.selectionEnd,N=e.slice(0,A)+" "+e.slice(d);t(N),requestAnimationFrame(()=>{S.selectionStart=S.selectionEnd=A+2})}},R=c=>{t(c.target.value);const S=c.target;S.style.height="auto",S.style.height=`${Math.max(S.scrollHeight,80)}px`};return s?E.jsx("textarea",{ref:a,value:e,onChange:R,onBlur:T,onKeyDown:l,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()?E.jsx("div",{onDoubleClick:()=>i(!0),title:"Double-click to edit",style:{padding:"12px 16px",cursor:"text",minHeight:48},children:hd(e,o)}):E.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 Ld({cell:e,themeMode:t,onApplyParam:n}){const{dispatch:r}=ae(),o=re[t],[s,i]=h.useState(!1),a=e.paramConfig??{paramType:"text",label:"Parameter",defaultValue:"",options:[]},T=e.paramValue??a.defaultValue,l=A=>{r({type:"UPDATE_CELL",id:e.id,updates:{paramConfig:{...a,...A}}})},R=A=>{r({type:"SET_PARAM_VALUE",id:e.id,value:A})},c=(a.options??[]).map(A=>A.trim()).filter(Boolean),S=e.name?`{{${e.name}}}`:null;return E.jsxs("div",{style:{background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderLeft:"3px solid #e3b341",borderRadius:8,overflow:"hidden"},children:[s&&E.jsxs("div",{style:{background:o.tableHeaderBg,borderBottom:`1px solid ${o.cellBorder}`,padding:"12px 14px",display:"flex",flexDirection:"column",gap:10},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:2},children:[E.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",color:"#e3b341",fontFamily:o.fontMono,textTransform:"uppercase"},children:"Configure Parameter"}),E.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"})]}),E.jsxs("div",{style:{display:"flex",gap:10,flexWrap:"wrap"},children:[E.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[E.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Variable name"}),E.jsx("input",{value:e.name??"",onChange:A=>r({type:"UPDATE_CELL",id:e.id,updates:{name:A.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"}})]}),E.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[E.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Display label"}),E.jsx("input",{value:a.label,onChange:A=>l({label:A.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"}})]}),E.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 100px"},children:[E.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Type"}),E.jsxs("select",{value:a.paramType,onChange:A=>l({paramType:A.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:[E.jsx("option",{value:"text",children:"Text"}),E.jsx("option",{value:"number",children:"Number"}),E.jsx("option",{value:"date",children:"Date"}),E.jsx("option",{value:"select",children:"Select"})]})]}),E.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,flex:"1 1 120px"},children:[E.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Default value"}),E.jsx("input",{type:a.paramType==="number"?"number":a.paramType==="date"?"date":"text",value:a.defaultValue,onChange:A=>l({defaultValue:A.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"}})]})]}),a.paramType==="select"&&E.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3},children:[E.jsx("span",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:"Options (one per line)"}),E.jsx("textarea",{value:(a.options??[]).join(`
|
|
318
|
-
`),onChange:A=>l({options:A.target.value.split(`
|
|
319
|
-
`)}),rows:4,placeholder:`Option A
|
|
320
|
-
Option B
|
|
321
|
-
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"}})]})]}),E.jsxs("div",{style:{padding:"12px 14px",display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[E.jsx("button",{onClick:()=>i(A=>!A),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?E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.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"})}):E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.103-.303c.644-.176 1.392.021 1.82.63.27.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"})})}),E.jsx("span",{style:{fontSize:13,fontWeight:500,fontFamily:o.font,color:o.textSecondary,flexShrink:0},children:a.label}),E.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[a.paramType==="select"?E.jsx("select",{value:T,onChange:A=>R(A.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:c.length===0?E.jsx("option",{value:"",children:"— no options configured —"}):c.map(A=>E.jsx("option",{value:A,children:A},A))}):E.jsx("input",{type:a.paramType,value:T,onChange:A=>R(A.target.value),style:{background:o.inputBg,border:`1px solid ${o.inputBorder}`,borderRadius:5,color:o.textPrimary,fontSize:13,fontFamily:a.paramType==="number"?o.fontMono:o.font,padding:"5px 10px",outline:"none",minWidth:160}}),S&&E.jsx("span",{style:{fontSize:10,fontFamily:o.fontMono,color:"#e3b341",opacity:.8},children:S})]}),T&&E.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:T}),e.name&&n&&E.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 pd=[{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
|
|
322
|
-
category,
|
|
323
|
-
COUNT(*) AS count,
|
|
324
|
-
SUM(amount) AS total
|
|
325
|
-
FROM read_csv_auto('data/filename.csv')
|
|
326
|
-
GROUP BY category
|
|
327
|
-
ORDER BY total DESC`},{id:"filter-date",label:"Filter by date range",description:"Filter rows between two dates",category:"SQL",code:`SELECT *
|
|
328
|
-
FROM read_csv_auto('data/filename.csv')
|
|
329
|
-
WHERE date_column >= '2024-01-01'
|
|
330
|
-
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
|
|
331
|
-
*,
|
|
332
|
-
ROW_NUMBER() OVER (PARTITION BY category ORDER BY amount DESC) AS rank
|
|
333
|
-
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 (
|
|
334
|
-
SELECT *
|
|
335
|
-
FROM read_csv_auto('data/filename.csv')
|
|
336
|
-
WHERE amount > 0
|
|
337
|
-
)
|
|
338
|
-
SELECT
|
|
339
|
-
category,
|
|
340
|
-
SUM(amount) AS total
|
|
341
|
-
FROM base
|
|
342
|
-
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
|
|
343
|
-
FROM read_csv_auto('data/table_a.csv') AS a
|
|
344
|
-
JOIN read_csv_auto('data/table_b.csv') AS b
|
|
345
|
-
ON a.id = b.id`},{id:"pivot",label:"Pivot / unpivot",description:"Pivot a column into multiple columns",category:"SQL",code:`SELECT *
|
|
346
|
-
FROM (
|
|
347
|
-
SELECT category, quarter, amount
|
|
348
|
-
FROM read_csv_auto('data/filename.csv')
|
|
349
|
-
) 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" {
|
|
350
|
-
domain = "analytics"
|
|
351
|
-
type = "custom"
|
|
352
|
-
description = "Describe what this block does"
|
|
353
|
-
owner = "data-team"
|
|
354
|
-
tags = ["analytics"]
|
|
355
|
-
|
|
356
|
-
query = """
|
|
357
|
-
SELECT *
|
|
358
|
-
FROM read_csv_auto('data/filename.csv')
|
|
359
|
-
LIMIT 100
|
|
360
|
-
"""
|
|
361
|
-
|
|
362
|
-
visualization {
|
|
363
|
-
chart = "table"
|
|
364
|
-
}
|
|
365
|
-
}`},{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" {
|
|
366
|
-
domain = "revenue"
|
|
367
|
-
type = "custom"
|
|
368
|
-
description = "Revenue grouped by segment"
|
|
369
|
-
owner = "data-team"
|
|
370
|
-
tags = ["revenue"]
|
|
371
|
-
|
|
372
|
-
params {
|
|
373
|
-
period = "current_quarter"
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
query = """
|
|
377
|
-
SELECT
|
|
378
|
-
segment_tier AS segment,
|
|
379
|
-
SUM(amount) AS revenue
|
|
380
|
-
FROM read_csv_auto('data/revenue.csv')
|
|
381
|
-
WHERE fiscal_period = \${period}
|
|
382
|
-
GROUP BY segment_tier
|
|
383
|
-
ORDER BY revenue DESC
|
|
384
|
-
"""
|
|
385
|
-
|
|
386
|
-
visualization {
|
|
387
|
-
chart = "bar"
|
|
388
|
-
x = segment
|
|
389
|
-
y = revenue
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
tests {
|
|
393
|
-
assert row_count > 0
|
|
394
|
-
}
|
|
395
|
-
}`},{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)
|
|
396
|
-
FROM fct_revenue
|
|
397
|
-
GROUP BY @dim(segment)
|
|
398
|
-
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" {
|
|
399
|
-
domain = "revenue"
|
|
400
|
-
type = "semantic"
|
|
401
|
-
owner = "data-team"
|
|
402
|
-
description = "Annual Recurring Revenue by subscription plan tier"
|
|
403
|
-
tags = ["arr", "revenue", "saas"]
|
|
404
|
-
|
|
405
|
-
metric = "arr"
|
|
406
|
-
dimensions = ["plan_tier"]
|
|
407
|
-
|
|
408
|
-
visualization {
|
|
409
|
-
chart = "bar"
|
|
410
|
-
x = plan_tier
|
|
411
|
-
y = arr
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
tests {
|
|
415
|
-
assert row_count > 0
|
|
416
|
-
}
|
|
417
|
-
}`},{id:"revenue-by-segment",label:"Revenue by segment",description:"Aggregate revenue totals, deal count, and average deal size per segment",category:"Analysis",code:`SELECT
|
|
418
|
-
segment_tier,
|
|
419
|
-
SUM(amount) AS total_revenue,
|
|
420
|
-
COUNT(*) AS deals,
|
|
421
|
-
ROUND(AVG(amount), 0) AS avg_deal
|
|
422
|
-
FROM read_csv_auto('data/revenue.csv')
|
|
423
|
-
GROUP BY segment_tier
|
|
424
|
-
ORDER BY total_revenue DESC`},{id:"quarterly-trend",label:"Quarterly trend",description:"Revenue totals grouped by fiscal year and quarter",category:"Analysis",code:`SELECT
|
|
425
|
-
fiscal_year || ' ' || fiscal_quarter AS period,
|
|
426
|
-
SUM(amount) AS revenue
|
|
427
|
-
FROM read_csv_auto('data/revenue.csv')
|
|
428
|
-
GROUP BY fiscal_year, fiscal_quarter
|
|
429
|
-
ORDER BY fiscal_year, fiscal_quarter`}];function _d({onInsert:e,themeMode:t,cellType:n}){const r=re[t],[o,s]=h.useState(!1),[i,a]=h.useState(null),T=h.useRef(null),l=pd.filter(S=>n==="dql"?S.category==="DQL":S.category==="SQL"||S.category==="Analysis"),R=Array.from(new Set(l.map(S=>S.category)));h.useEffect(()=>{if(!o)return;function S(A){T.current&&!T.current.contains(A.target)&&s(!1)}return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[o]);function c(S){e(S),s(!1)}return E.jsxs("div",{ref:T,style:{position:"relative",display:"inline-block"},children:[E.jsxs("button",{title:"Insert template snippet",onClick:()=>s(S=>!S),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:[E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:E.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&&E.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:R.map(S=>E.jsxs("div",{children:[E.jsx("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:700,fontFamily:r.font,letterSpacing:"0.08em",textTransform:"uppercase",color:r.textMuted},children:S}),l.filter(A=>A.category===S).map(A=>E.jsxs("button",{onMouseEnter:()=>a(A.id),onMouseLeave:()=>a(null),onClick:()=>c(A.code),style:{width:"100%",padding:"7px 12px",textAlign:"left",background:i===A.id?r.sidebarItemHover:"transparent",border:"none",cursor:"pointer",display:"flex",flexDirection:"column",gap:2,transition:"background 0.1s"},children:[E.jsx("span",{style:{fontSize:12,fontWeight:600,fontFamily:r.font,color:r.textPrimary,lineHeight:1.4},children:A.label}),E.jsx("span",{style:{fontSize:11,fontFamily:r.font,color:r.textMuted,lineHeight:1.4},children:A.description})]},A.id))]},S))})]})}const md=[25,50,100,500];function Jo(e){return typeof e=="number"?!0:typeof e=="string"?!isNaN(Number(e))&&e.trim()!=="":!1}function wa(e){return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function Dd(e,t){return e==null?1:t==null?-1:Jo(e)&&Jo(t)?Number(e)-Number(t):String(e).localeCompare(String(t))}function gd(e,t){const n=i=>i.includes(",")||i.includes('"')||i.includes(`
|
|
430
|
-
`)?`"${i.replace(/"/g,'""')}"`:i,r=e.columns.map(n).join(","),o=e.rows.map(i=>e.columns.map(a=>n(wa(i[a]))).join(",")),s=[r,...o].join(`
|
|
431
|
-
`);Ya(s,"export.csv","text/csv")}function Md(e,t){const n=JSON.stringify(e.rows,null,2);Ya(n,"export.json","application/json")}function Ya(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 xd({dir:e,color:t}){return e?E.jsx("svg",{width:"8",height:"10",viewBox:"0 0 8 10",fill:t,style:{marginLeft:3,flexShrink:0},children:e==="asc"?E.jsx("path",{d:"M4 0L7 4H1L4 0Z"}):E.jsx("path",{d:"M4 10L1 6H7L4 10Z"})}):E.jsxs("svg",{width:"8",height:"10",viewBox:"0 0 8 10",fill:t,opacity:.3,style:{marginLeft:3,flexShrink:0},children:[E.jsx("path",{d:"M4 0L7 3.5H1L4 0Z"}),E.jsx("path",{d:"M4 10L1 6.5H7L4 10Z"})]})}function Os({result:e,themeMode:t}){const n=re[t],[r,o]=h.useState(null),[s,i]=h.useState(null),[a,T]=h.useState(null),[l,R]=h.useState(""),[c,S]=h.useState(50),[A,d]=h.useState(0),N=h.useCallback(m=>{s===m?a==="asc"?T("desc"):a==="desc"?(i(null),T(null)):T("asc"):(i(m),T("asc")),d(0)},[s,a]),I=h.useMemo(()=>{if(!l.trim())return e.rows;const m=l.toLowerCase();return e.rows.filter(L=>e.columns.some(D=>{const M=L[D];return M==null?!1:String(M).toLowerCase().includes(m)}))},[e.rows,e.columns,l]),u=h.useMemo(()=>{if(!s||!a)return I;const m=[...I];return m.sort((L,D)=>{const M=Dd(L[s],D[s]);return a==="desc"?-M:M}),m},[I,s,a]),f=Math.max(1,Math.ceil(u.length/c)),O=Math.min(A,f-1),C=u.slice(O*c,(O+1)*c);return e.columns.length===0?E.jsx("div",{style:{padding:"12px 16px",color:n.textMuted,fontSize:12,fontFamily:n.font,fontStyle:"italic"},children:"Query executed successfully. No columns to display."}):E.jsxs("div",{children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 8px",borderBottom:`1px solid ${n.tableBorder}`,background:`${n.tableHeaderBg}60`,flexWrap:"wrap"},children:[E.jsxs("div",{style:{position:"relative",flex:"0 1 200px",minWidth:120},children:[E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:n.textMuted,style:{position:"absolute",left:6,top:6},children:E.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"})}),E.jsx("input",{value:l,onChange:m=>{R(m.target.value),d(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"}}),l&&E.jsx("button",{onClick:()=>R(""),style:{position:"absolute",right:4,top:3,background:"none",border:"none",color:n.textMuted,cursor:"pointer",fontSize:12,padding:"0 2px"},children:"×"})]}),E.jsxs("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:[l?`${u.length} of ${e.rows.length}`:`${e.rows.length}`," rows"]}),E.jsx("div",{style:{flex:1}}),E.jsx(Si,{label:"CSV",onClick:()=>gd(e),t:n}),E.jsx(Si,{label:"JSON",onClick:()=>Md(e),t:n}),E.jsx("select",{value:c,onChange:m=>{S(Number(m.target.value)),d(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:md.map(m=>E.jsxs("option",{value:m,children:[m," / page"]},m))}),f>1&&E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[E.jsx(Yn,{disabled:O===0,onClick:()=>d(0),t:n,children:"«"}),E.jsx(Yn,{disabled:O===0,onClick:()=>d(O-1),t:n,children:"‹"}),E.jsxs("span",{style:{fontSize:10,color:n.textSecondary,fontFamily:n.font,padding:"0 4px"},children:[O+1,"/",f]}),E.jsx(Yn,{disabled:O>=f-1,onClick:()=>d(O+1),t:n,children:"›"}),E.jsx(Yn,{disabled:O>=f-1,onClick:()=>d(f-1),t:n,children:"»"})]})]}),E.jsx("div",{style:{maxHeight:400,overflow:"auto",position:"relative"},children:E.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",tableLayout:"auto",fontSize:12,fontFamily:n.fontMono},children:[E.jsx("thead",{children:E.jsx("tr",{children:e.columns.map(m=>E.jsx("th",{onClick:()=>N(m),style:{background:n.tableHeaderBg,color:n.textSecondary,fontWeight:600,fontSize:11,textAlign:"left",padding:"6px 12px",borderBottom:`1px solid ${n.tableBorder}`,borderRight:`1px solid ${n.tableBorder}`,minWidth:80,maxWidth:300,whiteSpace:"nowrap",position:"sticky",top:0,zIndex:1,fontFamily:n.font,letterSpacing:"0.03em",overflow:"hidden",textOverflow:"ellipsis",cursor:"pointer",userSelect:"none",transition:"background 0.1s"},children:E.jsxs("span",{style:{display:"flex",alignItems:"center"},children:[m,E.jsx(xd,{dir:s===m?a:null,color:s===m?n.accent:n.textMuted})]})},m))})}),E.jsx("tbody",{children:C.map((m,L)=>E.jsx("tr",{onMouseEnter:()=>o(L),onMouseLeave:()=>o(null),style:{background:r===L?n.tableRowHover:"transparent",transition:"background 0.1s"},children:e.columns.map(D=>{const M=m[D],x=M==null,B=Jo(M);return E.jsx("td",{style:{padding:"5px 12px",borderBottom:`1px solid ${n.tableBorder}`,borderRight:`1px solid ${n.tableBorder}`,color:x?n.textMuted:n.textPrimary,fontStyle:x?"italic":"normal",textAlign:B?"right":"left",whiteSpace:"nowrap",maxWidth:300,overflow:"hidden",textOverflow:"ellipsis"},children:x?"—":wa(M)},D)})},L))})]})}),(l||u.length>c)&&E.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:[E.jsxs("span",{children:["Showing ",O*c+1,"–",Math.min((O+1)*c,u.length)," of ",u.length,l&&` (filtered from ${e.rows.length})`]}),s&&E.jsxs("span",{children:["Sorted by ",s," ",a]})]})]})}function Si({label:e,onClick:t,t:n}){const[r,o]=h.useState(!1);return E.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:[E.jsxs("svg",{width:"9",height:"9",viewBox:"0 0 16 16",fill:"currentColor",children:[E.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"}),E.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 Yn({disabled:e,onClick:t,children:n,t:r}){return E.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 Va=[{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"}],Pd=/date|time|at|day|month|year/i,Wa=/^(label|name|category|status|type|group)$/i,ka=/^(value|count|total|revenue|amount|sum|avg|price|quantity|sales)$/i;function st(e){return typeof e=="number"?!0:typeof e=="string"?e.trim()!==""&&!isNaN(Number(e)):!1}function yd(e){return typeof e=="string"||typeof e=="number"}const Ud=new Set(["bar","line","area","pie","donut","scatter","heatmap","funnel","waterfall","histogram","gauge","stacked-bar","grouped-bar","kpi","table"]);function qo(e,t){if(t!=null&&t.chart){const n=t.chart.toLowerCase().replace(/_/g,"-");if(Ud.has(n))return n}return bd(e)}function bd(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(c=>st(c[o])),a=s.every(c=>yd(c[r]));if(Pd.test(r)&&i&&a)return"line";const T=t.find(c=>Wa.test(c)),l=t.find(c=>ka.test(c));return T&&l&&s.every(S=>st(S[l]))?"bar":s.every(c=>st(c[r]))&&i&&t.length>=2?"scatter":t.length===2&&a&&i?"bar":"table"}const he=["#388bfd","#56d364","#e3b341","#f78166","#a371f7","#39c5cf","#ffa657","#ff7b72","#89d185","#d2a8ff","#58a6ff","#3fb950"];function Oe(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 vd(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 Pr(e,t){const n=(t!=null&&t.x&&e.columns.includes(t.x)?t.x:void 0)??e.columns.find(o=>Wa.test(o))??e.columns[0],r=(t!=null&&t.y&&e.columns.includes(t.y)?t.y:void 0)??e.columns.find(o=>ka.test(o))??e.columns[1];return{labelCol:n,valueCol:r}}const Ut=20;function fs({result:e,themeMode:t,chartConfig:n}){const r=re[t],[o,s]=h.useState(null),{labelCol:i,valueCol:a}=Pr(e,n),T=e.rows.slice(0,Ut).map(I=>({label:String(I[i]??""),value:Number(I[a]??0)})),l=e.rows.length>Ut,R=Math.max(...T.map(I=>I.value),1),c=28,S=120,A=6,d=12,N=T.length*(c+A)+d*2;return E.jsxs("div",{style:{padding:"8px 0"},children:[E.jsx("svg",{width:"100%",height:N,viewBox:`0 0 600 ${N}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:T.map((I,u)=>{const f=d+u*(c+A),O=600-S-84,C=Math.max(I.value/R*O,2),m=o===u;return E.jsxs("g",{onMouseEnter:()=>s(u),onMouseLeave:()=>s(null),style:{cursor:"default"},children:[E.jsx("text",{x:S-8,y:f+c/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:I.label.length>16?I.label.slice(0,15)+"…":I.label}),E.jsx("rect",{x:S,y:f,width:C,height:c,rx:3,fill:m?r.accentHover:r.accent,style:{transition:"fill 0.15s"}}),E.jsx("text",{x:S+C+6,y:f+c/2+4,textAnchor:"start",fontSize:11,fontFamily:r.fontMono,fill:r.textMuted,children:Oe(I.value)})]},u)})}),l&&E.jsxs("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,fontStyle:"italic",padding:"4px 12px"},children:["Showing ",Ut," of ",e.rows.length," rows"]})]})}function Bd({result:e,themeMode:t,chartConfig:n}){const r=re[t],[o,s]=h.useState(null),i=n!=null&&n.x&&e.columns.includes(n.x)?n.x:e.columns[0],a=e.rows.slice(0,5),T=e.columns.filter(u=>u!==i&&a.some(f=>st(f[u])));if(T.length===0)return E.jsx(fs,{result:e,themeMode:t,chartConfig:n});const l=e.rows.slice(0,Ut).map(u=>String(u[i]??"")),R=Math.max(...e.rows.slice(0,Ut).flatMap(u=>T.map(f=>Math.abs(Number(u[f]??0)))),1),c=24,S=c/T.length,A=120,d=12,N=8,I=l.length*(c+N)+d*2;return E.jsxs("div",{style:{padding:"8px 0"},children:[E.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:T.map((u,f)=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[E.jsx("div",{style:{width:10,height:10,borderRadius:2,background:he[f%he.length]}}),E.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:u})]},u))}),E.jsx("svg",{width:"100%",height:I,viewBox:`0 0 600 ${I}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:l.map((u,f)=>{const O=d+f*(c+N),C=e.rows[f];return E.jsxs("g",{children:[E.jsx("text",{x:A-8,y:O+c/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:u.length>16?u.slice(0,15)+"…":u}),T.map((m,L)=>{const D=Number(C[m]??0),M=600-A-60,x=Math.max(Math.abs(D)/R*M,1),B=O+L*S,g=`${f}-${L}`;return E.jsxs("g",{onMouseEnter:()=>s(g),onMouseLeave:()=>s(null),children:[E.jsx("rect",{x:A,y:B,width:x,height:S-1,rx:2,fill:he[L%he.length],opacity:o===g?1:.85,style:{transition:"opacity 0.15s"}}),o===g&&E.jsx("text",{x:A+x+4,y:B+S/2+3,fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Oe(D)})]},L)})]},f)})})]})}function Gd({result:e,themeMode:t,chartConfig:n}){const r=re[t],[o,s]=h.useState(null),i=n!=null&&n.x&&e.columns.includes(n.x)?n.x:e.columns[0],a=e.rows.slice(0,5),T=e.columns.filter(u=>u!==i&&a.some(f=>st(f[u])));if(T.length===0)return E.jsx(fs,{result:e,themeMode:t,chartConfig:n});const l=e.rows.slice(0,Ut),R=l.map(u=>String(u[i]??"")),c=Math.max(...l.map(u=>T.reduce((f,O)=>f+Math.abs(Number(u[O]??0)),0)),1),S=28,A=120,d=12,N=6,I=R.length*(S+N)+d*2;return E.jsxs("div",{style:{padding:"8px 0"},children:[E.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:T.map((u,f)=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[E.jsx("div",{style:{width:10,height:10,borderRadius:2,background:he[f%he.length]}}),E.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:u})]},u))}),E.jsx("svg",{width:"100%",height:I,viewBox:`0 0 600 ${I}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:R.map((u,f)=>{const O=d+f*(S+N),C=l[f],m=600-A-60;let L=A;return E.jsxs("g",{children:[E.jsx("text",{x:A-8,y:O+S/2+4,textAnchor:"end",fontSize:11,fontFamily:r.font,fill:r.textSecondary,children:u.length>16?u.slice(0,15)+"…":u}),T.map((D,M)=>{const x=Math.abs(Number(C[D]??0)),B=Math.max(x/c*m,0),g=L;L+=B;const p=`${f}-${M}`;return E.jsxs("g",{onMouseEnter:()=>s(p),onMouseLeave:()=>s(null),children:[E.jsx("rect",{x:g,y:O,width:B,height:S,rx:M===0?3:0,fill:he[M%he.length],opacity:o===p?1:.85,style:{transition:"opacity 0.15s"}}),o===p&&B>30&&E.jsx("text",{x:g+B/2,y:O+S/2+4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:"#fff",fontWeight:600,children:Oe(x)})]},M)})]},f)})})]})}function Ai({result:e,themeMode:t,showArea:n}){const r=re[t],[o,s]=h.useState(null),i=e.columns[0],a=e.columns[1],T=e.rows.map(_=>({label:String(_[i]??""),value:Number(_[a]??0)}));if(T.length<2)return null;const l=560,R=200,c=52,S=16,A=16,d=36,N=l-c-S,I=R-A-d,u=Math.min(...T.map(_=>_.value)),O=Math.max(...T.map(_=>_.value))-u||1,C=N/(T.length-1),m=_=>c+_*C,L=_=>A+I-(_-u)/O*I,D=T.map((_,U)=>({x:m(U),y:L(_.value)})),M=D.reduce((_,U,P)=>{if(P===0)return`M ${U.x},${U.y}`;const v=D[P-1],b=v.x+(U.x-v.x)/2;return`${_} C ${b},${v.y} ${b},${U.y} ${U.x},${U.y}`},""),x=`${M} L ${D[D.length-1].x},${A+I} L ${c},${A+I} Z`,B=5,g=Array.from({length:B+1},(_,U)=>{const P=u+O*U/B;return{val:P,y:L(P)}}),p=Math.ceil(T.length/8),F=T.filter((_,U)=>U%p===0||U===T.length-1);return E.jsx("div",{style:{position:"relative",padding:"8px 0"},children:E.jsxs("svg",{width:"100%",height:R,viewBox:`0 0 ${l} ${R}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},onMouseLeave:()=>s(null),children:[g.map((_,U)=>E.jsxs("g",{children:[E.jsx("line",{x1:c,y1:_.y,x2:c+N,y2:_.y,stroke:r.tableBorder,strokeWidth:.5}),E.jsx("text",{x:c-6,y:_.y+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Oe(_.val)})]},U)),E.jsx("path",{d:x,fill:r.accent,opacity:n?.3:.15}),E.jsx("path",{d:M,fill:"none",stroke:r.accent,strokeWidth:2,strokeLinejoin:"round"}),D.map((_,U)=>E.jsx("circle",{cx:_.x,cy:_.y,r:3,fill:r.accent,style:{cursor:"crosshair"},onMouseEnter:()=>s({x:_.x,y:_.y,label:T[U].label,value:T[U].value})},U)),F.map((_,U)=>{const P=T.indexOf(_);return E.jsx("text",{x:m(P),y:A+I+16,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:vd(_.label)},U)}),E.jsx("line",{x1:c,y1:A,x2:c,y2:A+I,stroke:r.tableBorder,strokeWidth:1}),E.jsx("line",{x1:c,y1:A+I,x2:c+N,y2:A+I,stroke:r.tableBorder,strokeWidth:1}),o&&E.jsxs("g",{children:[E.jsx("rect",{x:o.x+8,y:o.y-20,width:90,height:32,rx:4,fill:r.cellBg,stroke:r.cellBorder,strokeWidth:1}),E.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}),E.jsx("text",{x:o.x+13,y:o.y+6,fontSize:11,fontFamily:r.fontMono,fill:r.textPrimary,fontWeight:600,children:Oe(o.value)})]})]})})}function Hd({result:e,themeMode:t,chartConfig:n}){const r=re[t],[o,s]=h.useState(null),i=n!=null&&n.x&&e.columns.includes(n.x)?n.x:e.columns[0],a=n!=null&&n.y&&e.columns.includes(n.y)?n.y:e.columns[1],T=n!=null&&n.color&&e.columns.includes(n.color)?n.color:void 0,l=e.rows.slice(0,200).map(g=>({x:Number(g[i]??0),y:Number(g[a]??0),color:T?String(g[T]??""):void 0})),R=560,c=300,S=52,A=16,d=16,N=36,I=R-S-A,u=c-d-N,f=Math.min(...l.map(g=>g.x)),O=Math.max(...l.map(g=>g.x)),C=Math.min(...l.map(g=>g.y)),m=Math.max(...l.map(g=>g.y)),L=O-f||1,D=m-C||1,M=g=>S+(g-f)/L*I,x=g=>d+u-(g-C)/D*u,B=T?[...new Set(l.map(g=>g.color))]:[];return E.jsxs("div",{style:{padding:"8px 0"},children:[T&&B.length>0&&E.jsx("div",{style:{display:"flex",gap:12,padding:"0 12px 6px",flexWrap:"wrap"},children:B.slice(0,12).map((g,p)=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[E.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:he[p%he.length]}}),E.jsx("span",{style:{fontSize:10,fontFamily:r.font,color:r.textSecondary},children:g})]},g))}),E.jsxs("svg",{width:"100%",height:c,viewBox:`0 0 ${R} ${c}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:6},(g,p)=>{const F=C+D*p/5,_=x(F);return E.jsxs("g",{children:[E.jsx("line",{x1:S,y1:_,x2:S+I,y2:_,stroke:r.tableBorder,strokeWidth:.5}),E.jsx("text",{x:S-6,y:_+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Oe(F)})]},p)}),Array.from({length:6},(g,p)=>{const F=f+L*p/5,_=M(F);return E.jsx("text",{x:_,y:d+u+16,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Oe(F)},p)}),E.jsx("line",{x1:S,y1:d,x2:S,y2:d+u,stroke:r.tableBorder,strokeWidth:1}),E.jsx("line",{x1:S,y1:d+u,x2:S+I,y2:d+u,stroke:r.tableBorder,strokeWidth:1}),E.jsx("text",{x:S+I/2,y:c-2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:i}),E.jsx("text",{x:10,y:d+u/2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,transform:`rotate(-90, 10, ${d+u/2})`,children:a}),l.map((g,p)=>{const F=T?B.indexOf(g.color):0;return E.jsx("circle",{cx:M(g.x),cy:x(g.y),r:o===p?5:3.5,fill:he[F%he.length],opacity:o===p?1:.7,style:{cursor:"crosshair",transition:"r 0.1s, opacity 0.1s"},onMouseEnter:()=>s(p),onMouseLeave:()=>s(null)},p)}),o!==null&&E.jsxs("g",{children:[E.jsx("rect",{x:M(l[o].x)+8,y:x(l[o].y)-24,width:100,height:28,rx:4,fill:r.cellBg,stroke:r.cellBorder,strokeWidth:1}),E.jsxs("text",{x:M(l[o].x)+13,y:x(l[o].y)-8,fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:["(",Oe(l[o].x),", ",Oe(l[o].y),")"]})]})]})]})}const Fd=12;function di({result:e,themeMode:t,chartConfig:n,isDonut:r}){const o=re[t],[s,i]=h.useState(null),{labelCol:a,valueCol:T}=Pr(e,n),l=e.rows.slice(0,Fd).map(f=>({label:String(f[a]??""),value:Math.abs(Number(f[T]??0))})),R=l.reduce((f,O)=>f+O.value,0)||1,c=90,S=90,A=70,d=r?40:0,N=[];let I=-Math.PI/2;l.forEach((f,O)=>{const C=f.value/R*2*Math.PI,m=I,L=I+C,D=c+A*Math.cos(m),M=S+A*Math.sin(m),x=c+A*Math.cos(L),B=S+A*Math.sin(L),g=C>Math.PI?1:0;let p;if(d>0){const F=c+d*Math.cos(m),_=S+d*Math.sin(m),U=c+d*Math.cos(L),P=S+d*Math.sin(L);p=`M ${D} ${M} A ${A} ${A} 0 ${g} 1 ${x} ${B} L ${U} ${P} A ${d} ${d} 0 ${g} 0 ${F} ${_} Z`}else p=`M ${c} ${S} L ${D} ${M} A ${A} ${A} 0 ${g} 1 ${x} ${B} Z`;N.push({path:p,color:he[O%he.length],label:f.label,value:f.value,pct:f.value/R*100}),I=L});const u=s!==null?N[s]:null;return E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:16,padding:"8px 12px",flexWrap:"wrap"},children:[E.jsxs("svg",{width:180,height:180,style:{flexShrink:0},onMouseLeave:()=>i(null),children:[N.map((f,O)=>E.jsx("path",{d:f.path,fill:f.color,opacity:s===null||s===O?1:.55,style:{cursor:"pointer",transition:"opacity 0.15s"},onMouseEnter:()=>i(O)},O)),r&&E.jsxs(E.Fragment,{children:[E.jsx("text",{x:c,y:S-5,textAnchor:"middle",fontSize:11,fontFamily:o.fontMono,fill:o.textSecondary,children:Oe(u?u.value:R)}),E.jsx("text",{x:c,y:S+9,textAnchor:"middle",fontSize:9,fontFamily:o.font,fill:o.textMuted,children:u?`${u.pct.toFixed(1)}%`:"total"})]})]}),E.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4,maxHeight:180,overflowY:"auto",flex:1},children:N.map((f,O)=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,cursor:"default",opacity:s===null||s===O?1:.5},onMouseEnter:()=>i(O),onMouseLeave:()=>i(null),children:[E.jsx("div",{style:{width:10,height:10,borderRadius:2,background:f.color,flexShrink:0}}),E.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.textSecondary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f.label}),E.jsxs("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textMuted,marginLeft:"auto",flexShrink:0},children:[f.pct.toFixed(1),"%"]})]},O))})]})}function wd({result:e,themeMode:t}){const n=re[t],[r,o]=h.useState(null),s=e.columns[0],i=e.columns.slice(1),a=e.rows.slice(0,30),T=a.flatMap(I=>i.map(u=>Number(I[u]??0))),l=Math.min(...T),c=Math.max(...T)-l||1,S=Math.min(50,480/i.length),A=24,d=100;function N(I){const u=(I-l)/c,f=Math.round(56+u*192),O=Math.round(139+u*-58),C=Math.round(253+u*-180);return`rgb(${f},${O},${C})`}return E.jsx("div",{style:{padding:"8px 0",overflowX:"auto"},children:E.jsxs("svg",{width:d+i.length*S+20,height:a.length*A+A+16,style:{display:"block",overflow:"visible"},children:[i.map((I,u)=>E.jsx("text",{x:d+u*S+S/2,y:14,textAnchor:"middle",fontSize:9,fontFamily:n.font,fill:n.textMuted,transform:`rotate(-30, ${d+u*S+S/2}, 14)`,children:I.length>8?I.slice(0,7)+"…":I},u)),a.map((I,u)=>{const f=String(I[s]??""),O=A+u*A;return E.jsxs("g",{children:[E.jsx("text",{x:d-6,y:O+A/2+4,textAnchor:"end",fontSize:10,fontFamily:n.font,fill:n.textSecondary,children:f.length>14?f.slice(0,13)+"…":f}),i.map((C,m)=>{const L=Number(I[C]??0),D=(r==null?void 0:r.r)===u&&(r==null?void 0:r.c)===m;return E.jsxs("g",{onMouseEnter:()=>o({r:u,c:m}),onMouseLeave:()=>o(null),children:[E.jsx("rect",{x:d+m*S,y:O,width:S-1,height:A-1,rx:2,fill:N(L),opacity:D?1:.85,stroke:D?n.accent:"none",strokeWidth:D?1.5:0}),D&&E.jsx("text",{x:d+m*S+S/2,y:O+A/2+4,textAnchor:"middle",fontSize:10,fontFamily:n.fontMono,fill:"#fff",fontWeight:600,children:Oe(L)})]},m)})]},u)})]})})}function Yd({result:e,themeMode:t,chartConfig:n}){const r=re[t],[o,s]=h.useState(null),i=(n!=null&&n.x&&e.columns.includes(n.x)?n.x:void 0)??e.columns.find(M=>e.rows.slice(0,5).some(x=>st(x[M])))??e.columns[0],a=e.rows.map(M=>Number(M[i]??0)).filter(M=>!isNaN(M));if(a.length===0)return null;const T=Math.min(20,Math.max(5,Math.ceil(Math.sqrt(a.length)))),l=Math.min(...a),S=(Math.max(...a)-l||1)/T,A=Array.from({length:T},(M,x)=>({low:l+x*S,high:l+(x+1)*S,count:0}));a.forEach(M=>{const x=Math.min(Math.floor((M-l)/S),T-1);A[x].count++});const d=Math.max(...A.map(M=>M.count),1),N=560,I=200,u=52,f=16,O=16,C=36,m=N-u-f,L=I-O-C,D=m/T;return E.jsx("div",{style:{padding:"8px 0"},children:E.jsxs("svg",{width:"100%",height:I,viewBox:`0 0 ${N} ${I}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:5},(M,x)=>{const B=d*(x+1)/5,g=O+L-B/d*L;return E.jsxs("g",{children:[E.jsx("line",{x1:u,y1:g,x2:u+m,y2:g,stroke:r.tableBorder,strokeWidth:.5}),E.jsx("text",{x:u-6,y:g+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Math.round(B)})]},x)}),A.map((M,x)=>{const B=M.count/d*L,g=u+x*D,p=O+L-B,F=o===x;return E.jsxs("g",{onMouseEnter:()=>s(x),onMouseLeave:()=>s(null),children:[E.jsx("rect",{x:g+1,y:p,width:D-2,height:B,rx:1,fill:F?r.accentHover:r.accent,opacity:F?1:.85,style:{transition:"fill 0.1s"}}),F&&E.jsx("text",{x:g+D/2,y:p-4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:M.count})]},x)}),A.filter((M,x)=>x%Math.ceil(T/6)===0).map((M,x)=>{const B=A.indexOf(M);return E.jsx("text",{x:u+B*D+D/2,y:O+L+16,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Oe(M.low)},x)}),E.jsx("line",{x1:u,y1:O,x2:u,y2:O+L,stroke:r.tableBorder,strokeWidth:1}),E.jsx("line",{x1:u,y1:O+L,x2:u+m,y2:O+L,stroke:r.tableBorder,strokeWidth:1}),E.jsx("text",{x:u+m/2,y:I-2,textAnchor:"middle",fontSize:10,fontFamily:r.font,fill:r.textMuted,children:i})]})})}function Vd({result:e,themeMode:t,chartConfig:n}){const r=re[t],[o,s]=h.useState(null),{labelCol:i,valueCol:a}=Pr(e,n),T=e.rows.slice(0,10).map(I=>({label:String(I[i]??""),value:Math.abs(Number(I[a]??0))}));if(T.length===0)return null;const l=T[0].value||1,R=400,c=36,S=4,A=16,d=T.length*(c+S)+A*2,N=R/2;return E.jsx("div",{style:{padding:"8px 0",display:"flex",justifyContent:"center"},children:E.jsx("svg",{width:R,height:d,style:{display:"block"},children:T.map((I,u)=>{const f=A+u*(c+S),O=I.value/l,C=Math.max(O*(R-80),40),m=o===u,L=u<T.length-1?T[u+1].value/l:O*.8,D=Math.max(L*(R-80),40),M=N-C/2,x=N+C/2,B=N+D/2,g=N-D/2,p=`M ${M} ${f} L ${x} ${f} L ${B} ${f+c} L ${g} ${f+c} Z`;return E.jsxs("g",{onMouseEnter:()=>s(u),onMouseLeave:()=>s(null),style:{cursor:"default"},children:[E.jsx("path",{d:p,fill:he[u%he.length],opacity:m?1:.85,style:{transition:"opacity 0.15s"}}),E.jsx("text",{x:N,y:f+c/2+1,textAnchor:"middle",fontSize:11,fontFamily:r.font,fill:"#fff",fontWeight:500,children:I.label}),E.jsxs("text",{x:N,y:f+c/2+13,textAnchor:"middle",fontSize:9,fontFamily:r.fontMono,fill:"rgba(255,255,255,0.7)",children:[Oe(I.value)," (",(O*100).toFixed(0),"%)"]})]},u)})})})}function Wd({result:e,themeMode:t,chartConfig:n}){const r=re[t],[o,s]=h.useState(null),{labelCol:i,valueCol:a}=Pr(e,n),T=e.rows.slice(0,15).map(x=>({label:String(x[i]??""),value:Number(x[a]??0)}));if(T.length===0)return null;let l=0;const R=T.map(x=>{const B=l;return l+=x.value,{...x,start:B,end:l}}),c=R.flatMap(x=>[x.start,x.end]),S=Math.min(0,...c),d=Math.max(0,...c)-S||1,N=560,I=240,u=52,f=16,O=16,C=44,m=N-u-f,L=I-O-C,D=m/R.length,M=x=>O+L-(x-S)/d*L;return E.jsx("div",{style:{padding:"8px 0"},children:E.jsxs("svg",{width:"100%",height:I,viewBox:`0 0 ${N} ${I}`,preserveAspectRatio:"xMidYMid meet",style:{display:"block",overflow:"visible"},children:[Array.from({length:6},(x,B)=>{const g=S+d*B/5,p=M(g);return E.jsxs("g",{children:[E.jsx("line",{x1:u,y1:p,x2:u+m,y2:p,stroke:r.tableBorder,strokeWidth:.5}),E.jsx("text",{x:u-6,y:p+4,textAnchor:"end",fontSize:10,fontFamily:r.fontMono,fill:r.textMuted,children:Oe(g)})]},B)}),E.jsx("line",{x1:u,y1:M(0),x2:u+m,y2:M(0),stroke:r.textMuted,strokeWidth:1,strokeDasharray:"3,3"}),R.map((x,B)=>{const g=u+B*D,p=M(Math.max(x.start,x.end)),_=M(Math.min(x.start,x.end))-p,U=x.value>=0,P=o===B;return E.jsxs("g",{onMouseEnter:()=>s(B),onMouseLeave:()=>s(null),children:[B<R.length-1&&E.jsx("line",{x1:g+D-2,y1:M(x.end),x2:g+D+2,y2:M(x.end),stroke:r.textMuted,strokeWidth:1,strokeDasharray:"2,2"}),E.jsx("rect",{x:g+4,y:p,width:D-8,height:Math.max(_,1),rx:2,fill:U?r.success:r.error,opacity:P?1:.8,style:{transition:"opacity 0.1s"}}),P&&E.jsxs("text",{x:g+D/2,y:p-4,textAnchor:"middle",fontSize:10,fontFamily:r.fontMono,fill:r.textPrimary,children:[x.value>=0?"+":"",Oe(x.value)]})]},B)}),R.map((x,B)=>E.jsx("text",{x:u+B*D+D/2,y:I-6,textAnchor:"middle",fontSize:9,fontFamily:r.font,fill:r.textMuted,transform:`rotate(-20, ${u+B*D+D/2}, ${I-6})`,children:x.label.length>8?x.label.slice(0,7)+"…":x.label},B)),E.jsx("line",{x1:u,y1:O,x2:u,y2:O+L,stroke:r.tableBorder,strokeWidth:1}),E.jsx("line",{x1:u,y1:O+L,x2:u+m,y2:O+L,stroke:r.tableBorder,strokeWidth:1})]})})}function kd({result:e,themeMode:t,chartConfig:n}){const r=re[t],o=e.rows[0];if(!o)return null;const s=(n!=null&&n.y&&e.columns.includes(n.y)?n.y:void 0)??e.columns.find(M=>st(o[M]))??e.columns[0],i=Number(o[s]??0),a=(n==null?void 0:n.title)??s,T=i>100?i*1.2:100,l=Math.min(Math.max(i/T,0),1),R=120,c=110,S=80,A=Math.PI,d=0,N=A-(A-d)*l,I=R+S*Math.cos(A),u=c+S*Math.sin(A),f=R+S*Math.cos(N),O=c+S*Math.sin(N),C=l>.5?1:0,m=R+S*Math.cos(d),L=c+S*Math.sin(d),D=l<.33?r.error:l<.66?r.warning:r.success;return E.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:"16px 24px"},children:E.jsxs("svg",{width:240,height:140,style:{display:"block",overflow:"visible"},children:[E.jsx("path",{d:`M ${I} ${u} A ${S} ${S} 0 1 1 ${m} ${L}`,fill:"none",stroke:r.tableBorder,strokeWidth:12,strokeLinecap:"round"}),l>0&&E.jsx("path",{d:`M ${I} ${u} A ${S} ${S} 0 ${C} 1 ${f} ${O}`,fill:"none",stroke:D,strokeWidth:12,strokeLinecap:"round"}),E.jsx("text",{x:R,y:c-4,textAnchor:"middle",fontSize:28,fontFamily:r.fontMono,fill:D,fontWeight:700,children:Oe(i)}),E.jsx("text",{x:R,y:c+16,textAnchor:"middle",fontSize:11,fontFamily:r.font,fill:r.textMuted,children:a})]})})}function jd({result:e,themeMode:t,chartConfig:n}){const r=re[t],o=e.rows[0];if(!o)return null;const s=n!=null&&n.y&&e.columns.includes(n.y)?n.y:e.columns.find(R=>st(o[R]))??e.columns[0],i=o[s],a=Number(i),T=isNaN(a)?String(i):a.toLocaleString(void 0,{maximumFractionDigits:2}),l=(n==null?void 0:n.title)??(n!=null&&n.x&&o[n.x]?String(o[n.x]):s);return E.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"32px 24px",gap:8},children:[E.jsx("span",{style:{fontSize:40,fontWeight:700,fontFamily:r.fontMono,color:r.accent,lineHeight:1.1},children:T}),E.jsx("span",{style:{fontSize:13,fontFamily:r.font,color:r.textMuted,textTransform:"uppercase",letterSpacing:"0.08em",fontWeight:500},children:l})]})}function ja(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?Xd(t,o,s):t;switch(e){case"line":return E.jsx(Ai,{result:i,themeMode:n});case"area":return E.jsx(Ai,{result:i,themeMode:n,showArea:!0});case"bar":return E.jsx(fs,{result:i,themeMode:n,chartConfig:r});case"grouped-bar":return E.jsx(Bd,{result:i,themeMode:n,chartConfig:r});case"stacked-bar":return E.jsx(Gd,{result:i,themeMode:n,chartConfig:r});case"scatter":return E.jsx(Hd,{result:t,themeMode:n,chartConfig:r});case"pie":return E.jsx(di,{result:t,themeMode:n,chartConfig:r,isDonut:!1});case"donut":return E.jsx(di,{result:t,themeMode:n,chartConfig:r,isDonut:!0});case"heatmap":return E.jsx(wd,{result:t,themeMode:n});case"histogram":return E.jsx(Yd,{result:t,themeMode:n,chartConfig:r});case"funnel":return E.jsx(Vd,{result:t,themeMode:n,chartConfig:r});case"waterfall":return E.jsx(Wd,{result:t,themeMode:n,chartConfig:r});case"gauge":return E.jsx(kd,{result:t,themeMode:n,chartConfig:r});case"kpi":return E.jsx(jd,{result:t,themeMode:n,chartConfig:r});default:return E.jsx(Os,{result:t,themeMode:n})}}function Xd(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 a of o)i[a]=s[a];return i})}}function $d(e){let t=e;try{const l=JSON.parse(e);l&&typeof l.error=="string"&&(t=l.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 a;n==="Syntax Error"?s==='"""'||t.includes('"""')?a="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)?a="Query is incomplete — check for unclosed parentheses, missing keywords, or a dangling comma.":(s===")"||s==="(")&&(a="Mismatched parentheses — check that every opening ( has a closing )."):n==="Reference Error"?/column.*not found|Referenced column/i.test(t)?a="Column not found — check the column name in the Schema panel (left sidebar).":/table.*not found|Table.*does not exist/i.test(t)&&(a="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)&&(a="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"?a="File could not be read — use read_csv_auto('./data/filename.csv'). Open the Schema panel to browse available data files.":n==="Type Error"&&(a="Type mismatch — you may be comparing or casting incompatible types (e.g. text vs number).");const T=t.replace(/^(Parser Error|Binder Error|Conversion Error|Invalid Input Error|IO Error|Constraint Error):\s*/i,"").trim();return{type:n,message:T,line:r,near:s,hint:a}}function Kd(e,t){const n=e.length,r=t.length,o=Array.from({length:n+1},(s,i)=>Array.from({length:r+1},(a,T)=>i===0?T:T===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 ui(e,t){const n=e.toLowerCase();let r=null,o=4;for(const s of t){const i=Kd(n,s.toLowerCase());i<o&&(o=i,r=s)}return r}function zd({message:e,themeMode:t,onFix:n,schemaTables:r}){const o=re[t],s=$d(e);let i=null;if(r&&r.length>0&&s.type==="Reference Error"){const T=/column.*not found|Referenced column/i.test(s.message),l=/table.*not found|Table.*does not exist/i.test(s.message);if(T&&s.near){const R=r.flatMap(S=>S.columns.map(A=>A.name)),c=ui(s.near,R);c&&(i=`Did you mean column "${c}"?`)}else if(l&&s.near){const R=ui(s.near,r.map(c=>c.name));R&&(i=`Did you mean table "${R}"?`)}}const a=n&&(s.type==="Syntax Error"||s.near===")"||s.near==="("||s.near==="end of input");return E.jsxs("div",{style:{padding:"12px 14px",background:`${o.error}10`,borderLeft:`3px solid ${o.error}`,display:"flex",flexDirection:"column",gap:8},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[E.jsx("div",{style:{flexShrink:0,color:o.error,display:"flex",alignItems:"center"},children:E.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:E.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"})})}),E.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&&E.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&&E.jsxs("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textSecondary,flexShrink:0},children:["near ",E.jsxs("span",{style:{color:o.error},children:["“",s.near,"”"]})]})]}),E.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&&E.jsxs("div",{style:{fontSize:12,fontFamily:o.font,color:o.textSecondary,display:"flex",alignItems:"center",gap:6},children:[E.jsx("span",{style:{color:o.accent},children:"→"}),i]}),s.hint&&E.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:[E.jsx("span",{style:{flexShrink:0,fontSize:13,lineHeight:1.5},children:"💡"}),E.jsx("span",{style:{fontSize:12,fontFamily:o.font,color:o.warning,lineHeight:1.6},children:s.hint})]}),a&&E.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:T=>{T.currentTarget.style.background=`${o.accent}25`},onMouseLeave:T=>{T.currentTarget.style.background=`${o.accent}15`},children:[E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M11.013 1.427a1.75 1.75 0 0 1 2.474 0l1.086 1.086a1.75 1.75 0 0 1 0 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 0 1-.927-.928l.929-3.25c.081-.286.235-.547.445-.758l8.61-8.61Zm.176 4.823L9.75 4.81l-6.286 6.287a.253.253 0 0 0-.064.108l-.558 1.953 1.953-.558a.253.253 0 0 0 .108-.064Zm1.238-3.763a.25.25 0 0 0-.354 0L10.811 3.75l1.439 1.44 1.263-1.263a.25.25 0 0 0 0-.354Z"})}),"Format & Run"]})]})}const Zn={source_table:"#8b949e",block:"#56d364",metric:"#388bfd",dimension:"#e3b341",domain:"#d2a8ff",chart:"#f778ba"},Jd={source_table:"TBL",block:"BLK",metric:"MET",dimension:"DIM",chart:"CHT",domain:"DOM"},qd={certified:"#56d364",draft:"#8b949e",review:"#e3b341",deprecated:"#f85149"};function Zd(e){const t=e.match(/^\s*block\s+"([^"]+)"/i);return t?t[1]:null}function Qd(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 eu(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 Ii({node:e,t}){const n=Zn[e.type]??"#8b949e",r=Jd[e.type]??e.type.slice(0,3).toUpperCase(),o=e.status?qd[e.status]:void 0;return E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"2px 0",fontSize:11,color:t.textPrimary},children:[E.jsx("span",{style:{color:n,fontSize:9,fontWeight:700,width:26,flexShrink:0},children:r}),E.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:e.name}),e.domain&&E.jsx("span",{style:{fontSize:9,color:t.textMuted},children:e.domain}),o&&E.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:o,flexShrink:0}})]})}function tu({cellContent:e,cellType:t,cellName:n,themeMode:r,t:o}){const[s,i]=h.useState(!1),[a,T]=h.useState(!1),[l,R]=h.useState([]),[c,S]=h.useState([]),[A,d]=h.useState([]),[N,I]=h.useState({metrics:[],dimensions:[]}),[u,f]=h.useState(null),C=(t==="dql"?Zd(e):null)||n,m=h.useCallback(async()=>{if(!(!C&&t!=="sql")){T(!0),f(null);try{const D=Qd(e);if(d(D),I(eu(e)),C){const M=await le.fetchBlockLineage(C);M&&(R(M.ancestors??[]),S(M.descendants??[]))}else{const x=(await le.fetchLineage()).nodes.filter(B=>D.some(g=>B.name===g||B.id===`table:${g}`||B.id===`block:${g}`));R(x),S([])}}catch{f("Failed to load lineage")}finally{T(!1)}}},[C,e,t]);h.useEffect(()=>{s&&m()},[s,m]);const L=A.length>0||N.metrics.length>0||N.dimensions.length>0;return e.trim()?E.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[E.jsxs("button",{onClick:()=>i(D=>!D),style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"4px 12px",background:s?`${o.tableHeaderBg}60`:"transparent",border:"none",cursor:"pointer",color:o.textMuted,fontSize:10,fontFamily:o.font,transition:"background 0.15s"},children:[E.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",style:{flexShrink:0},children:[E.jsx("circle",{cx:"4",cy:"4",r:"2"}),E.jsx("circle",{cx:"12",cy:"8",r:"2"}),E.jsx("circle",{cx:"4",cy:"12",r:"2"}),E.jsx("line",{x1:"6",y1:"4",x2:"10",y2:"8"}),E.jsx("line",{x1:"6",y1:"12",x2:"10",y2:"8"})]}),E.jsx("span",{children:"Lineage"}),E.jsx("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:s?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.15s"},children:E.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})})]}),s&&E.jsx("div",{style:{padding:"6px 12px 8px",fontSize:11},children:a?E.jsx("div",{style:{color:o.textMuted,padding:"4px 0"},children:"Loading lineage..."}):u?E.jsx("div",{style:{color:o.error,padding:"4px 0"},children:u}):E.jsxs(E.Fragment,{children:[A.length>0&&E.jsxs("div",{style:{marginBottom:6},children:[E.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Reads From (",A.length,")"]}),A.map(D=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[E.jsx("span",{style:{color:Zn.source_table,fontSize:9,fontWeight:700,width:26},children:"TBL"}),E.jsx("span",{children:D})]},D))]}),N.metrics.length>0&&E.jsxs("div",{style:{marginBottom:6},children:[E.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Metrics (",N.metrics.length,")"]}),N.metrics.map(D=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[E.jsx("span",{style:{color:Zn.metric,fontSize:9,fontWeight:700,width:26},children:"MET"}),E.jsx("span",{children:D})]},D))]}),N.dimensions.length>0&&E.jsxs("div",{style:{marginBottom:6},children:[E.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Dimensions (",N.dimensions.length,")"]}),N.dimensions.map(D=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"1px 0",fontSize:11,color:o.textPrimary},children:[E.jsx("span",{style:{color:Zn.dimension,fontSize:9,fontWeight:700,width:26},children:"DIM"}),E.jsx("span",{children:D})]},D))]}),l.length>0&&E.jsxs("div",{style:{marginBottom:6},children:[E.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Upstream (",l.length,")"]}),l.map(D=>E.jsx(Ii,{node:D,t:o},D.id))]}),c.length>0&&E.jsxs("div",{style:{marginBottom:6},children:[E.jsxs("div",{style:{fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:o.textMuted,marginBottom:3},children:["Downstream (",c.length,")"]}),c.map(D=>E.jsx(Ii,{node:D,t:o},D.id))]}),!L&&l.length===0&&c.length===0&&E.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=>Qn(ou(e)).map(ru),ru=e=>e.replace(/ +/g," ").trim(),ou=e=>({type:"mandatory_block",items:hs(e,0)[0]}),hs=(e,t,n)=>{const r=[];for(;e[t];){const[o,s]=su(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]},su=(e,t)=>{const n=[];for(;;){const[r,o]=iu(e,t);if(r)n.push(r),t=o;else break}return n.length===1?[n[0],t]:[{type:"concatenation",items:n},t]},iu=(e,t)=>{if(e[t]==="{")return Eu(e,t+1);if(e[t]==="[")return au(e,t+1);{let n="";for(;e[t]&&/[A-Za-z0-9_ ]/.test(e[t]);)n+=e[t],t++;return[n,t]}},Eu=(e,t)=>{const[n,r]=hs(e,t,"}");return[{type:"mandatory_block",items:n},r]},au=(e,t)=>{const[n,r]=hs(e,t,"]");return[{type:"optional_block",items:n},r]},Qn=e=>{if(typeof e=="string")return[e];if(e.type==="concatenation")return e.items.map(Qn).reduce(lu,[""]);if(e.type==="mandatory_block")return e.items.flatMap(Qn);if(e.type==="optional_block")return["",...e.items.flatMap(Qn)];throw new Error(`Unknown node type: ${e}`)},lu=(e,t)=>{const n=[];for(const r of e)for(const o of t)n.push(r+o);return n};var W;(function(e){e.QUOTED_IDENTIFIER="QUOTED_IDENTIFIER",e.IDENTIFIER="IDENTIFIER",e.STRING="STRING",e.VARIABLE="VARIABLE",e.RESERVED_DATA_TYPE="RESERVED_DATA_TYPE",e.RESERVED_PARAMETERIZED_DATA_TYPE="RESERVED_PARAMETERIZED_DATA_TYPE",e.RESERVED_KEYWORD="RESERVED_KEYWORD",e.RESERVED_FUNCTION_NAME="RESERVED_FUNCTION_NAME",e.RESERVED_KEYWORD_PHRASE="RESERVED_KEYWORD_PHRASE",e.RESERVED_DATA_TYPE_PHRASE="RESERVED_DATA_TYPE_PHRASE",e.RESERVED_SET_OPERATION="RESERVED_SET_OPERATION",e.RESERVED_CLAUSE="RESERVED_CLAUSE",e.RESERVED_SELECT="RESERVED_SELECT",e.RESERVED_JOIN="RESERVED_JOIN",e.ARRAY_IDENTIFIER="ARRAY_IDENTIFIER",e.ARRAY_KEYWORD="ARRAY_KEYWORD",e.CASE="CASE",e.END="END",e.WHEN="WHEN",e.ELSE="ELSE",e.THEN="THEN",e.LIMIT="LIMIT",e.BETWEEN="BETWEEN",e.AND="AND",e.OR="OR",e.XOR="XOR",e.OPERATOR="OPERATOR",e.COMMA="COMMA",e.ASTERISK="ASTERISK",e.PROPERTY_ACCESS_OPERATOR="PROPERTY_ACCESS_OPERATOR",e.OPEN_PAREN="OPEN_PAREN",e.CLOSE_PAREN="CLOSE_PAREN",e.LINE_COMMENT="LINE_COMMENT",e.BLOCK_COMMENT="BLOCK_COMMENT",e.DISABLE_COMMENT="DISABLE_COMMENT",e.NUMBER="NUMBER",e.NAMED_PARAMETER="NAMED_PARAMETER",e.QUOTED_PARAMETER="QUOTED_PARAMETER",e.NUMBERED_PARAMETER="NUMBERED_PARAMETER",e.POSITIONAL_PARAMETER="POSITIONAL_PARAMETER",e.CUSTOM_PARAMETER="CUSTOM_PARAMETER",e.DELIMITER="DELIMITER",e.EOF="EOF"})(W=W||(W={}));const Xa=e=>({type:W.EOF,raw:"«EOF»",text:"«EOF»",start:e}),Et=Xa(1/0),pt=e=>t=>t.type===e.type&&t.text===e.text,at={ARRAY:pt({text:"ARRAY",type:W.RESERVED_DATA_TYPE}),BY:pt({text:"BY",type:W.RESERVED_KEYWORD}),SET:pt({text:"SET",type:W.RESERVED_CLAUSE}),STRUCT:pt({text:"STRUCT",type:W.RESERVED_DATA_TYPE}),WINDOW:pt({text:"WINDOW",type:W.RESERVED_CLAUSE}),VALUES:pt({text:"VALUES",type:W.RESERVED_CLAUSE})},$a=e=>e===W.RESERVED_DATA_TYPE||e===W.RESERVED_KEYWORD||e===W.RESERVED_FUNCTION_NAME||e===W.RESERVED_KEYWORD_PHRASE||e===W.RESERVED_DATA_TYPE_PHRASE||e===W.RESERVED_CLAUSE||e===W.RESERVED_SELECT||e===W.RESERVED_SET_OPERATION||e===W.RESERVED_JOIN||e===W.ARRAY_KEYWORD||e===W.CASE||e===W.END||e===W.WHEN||e===W.ELSE||e===W.THEN||e===W.LIMIT||e===W.BETWEEN||e===W.AND||e===W.OR||e===W.XOR,Tu=e=>e===W.AND||e===W.OR||e===W.XOR,cu=["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"],Ru=["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"],Su=["ARRAY","BOOL","BYTES","DATE","DATETIME","GEOGRAPHY","INTERVAL","INT64","INT","SMALLINT","INTEGER","BIGINT","TINYINT","BYTEINT","NUMERIC","DECIMAL","BIGNUMERIC","BIGDECIMAL","FLOAT64","STRING","STRUCT","TIME","TIMEZONE"],Au=G(["SELECT [ALL | DISTINCT] [AS STRUCT | AS VALUE]"]),du=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"]),Ni=G(["CREATE [OR REPLACE] [TEMP|TEMPORARY|SNAPSHOT|EXTERNAL] TABLE [IF NOT EXISTS]"]),eo=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"]),uu=G(["UNION {ALL | DISTINCT}","EXCEPT DISTINCT","INTERSECT DISTINCT"]),Iu=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),Nu=G(["TABLESAMPLE SYSTEM","ANY TYPE","ALL COLUMNS","NOT DETERMINISTIC","{ROWS | RANGE} BETWEEN","IS [NOT] DISTINCT FROM"]),Ou=G([]),fu={name:"bigquery",tokenizerOptions:{reservedSelect:Au,reservedClauses:[...du,...eo,...Ni],reservedSetOperations:uu,reservedJoins:Iu,reservedKeywordPhrases:Nu,reservedDataTypePhrases:Ou,reservedKeywords:Ru,reservedDataTypes:Su,reservedFunctionNames:cu,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:hu},formatOptions:{onelineClauses:[...Ni,...eo],tabularOnelineClauses:eo}};function hu(e){return Cu(Lu(e))}function Cu(e){let t=Et;return e.map(n=>n.text==="OFFSET"&&t.text==="["?(t=n,Object.assign(Object.assign({},n),{type:W.RESERVED_FUNCTION_NAME})):(t=n,n))}function Lu(e){var t;const n=[];for(let r=0;r<e.length;r++){const o=e[r];if((at.ARRAY(o)||at.STRUCT(o))&&((t=e[r+1])===null||t===void 0?void 0:t.text)==="<"){const s=pu(e,r+1),i=e.slice(r,s+1);n.push({type:W.IDENTIFIER,raw:i.map(Oi("raw")).join(""),text:i.map(Oi("text")).join(""),start:o.start}),r=s}else n.push(o)}return n}const Oi=e=>t=>t.type===W.IDENTIFIER||t.type===W.COMMA?t[e]+" ":t[e];function pu(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 _u=["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"],mu=["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"],Du=["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"],gu=G(["SELECT [DISTINCT]","MODIFY QUERY SELECT [DISTINCT]"]),Mu=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]"]),fi=G(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),to=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"]),xu=G(["UNION [ALL | DISTINCT]","PARALLEL WITH"]),Pu=G(["[GLOBAL] [INNER|LEFT|RIGHT|FULL|CROSS] [OUTER|SEMI|ANTI|ANY|ALL|ASOF] JOIN","[LEFT] ARRAY JOIN"]),yu=G(["{ROWS | RANGE} BETWEEN","ALTER MATERIALIZE STATISTICS"]),Uu={name:"clickhouse",tokenizerOptions:{reservedSelect:gu,reservedClauses:[...Mu,...fi,...to],reservedSetOperations:xu,reservedJoins:Pu,reservedKeywordPhrases:yu,reservedKeywords:mu,reservedDataTypes:Du,reservedFunctionNames:_u,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:bu},formatOptions:{onelineClauses:[...fi,...to],tabularOnelineClauses:to}};function bu(e){return e.map((t,n)=>{const r=e[n+1]||Et,o=e[n-1]||Et;return t.type===W.RESERVED_SELECT&&(r.type===W.COMMA||o.type===W.RESERVED_CLAUSE||o.type===W.COMMA)?Object.assign(Object.assign({},t),{type:W.RESERVED_KEYWORD}):at.SET(t)&&r.type===W.OPEN_PAREN?Object.assign(Object.assign({},t),{type:W.RESERVED_FUNCTION_NAME}):t})}const vu=["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"],Bu=["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"],Gu=["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"],Hu=G(["SELECT [ALL | DISTINCT]"]),Fu=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"]),hi=G(["CREATE [GLOBAL TEMPORARY | EXTERNAL] TABLE [IF NOT EXISTS]"]),no=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"]),wu=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),Yu=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN"]),Vu=G(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),Wu=G([]),ku={name:"db2",tokenizerOptions:{reservedSelect:Hu,reservedClauses:[...Fu,...hi,...no],reservedSetOperations:wu,reservedJoins:Yu,reservedKeywordPhrases:Vu,reservedDataTypePhrases:Wu,reservedKeywords:Bu,reservedDataTypes:Gu,reservedFunctionNames:vu,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:[...hi,...no],tabularOnelineClauses:no}},ju=["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"],Xu=["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"],$u=["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"],Ku=G(["SELECT [ALL | DISTINCT]"]),zu=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"]),Ci=G(["CREATE [OR REPLACE] TABLE"]),ro=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}"]),Ju=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),qu=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","[LEFT | RIGHT] EXCEPTION JOIN","{INNER | CROSS} JOIN"]),Zu=G(["ON DELETE","ON UPDATE","SET NULL","{ROWS | RANGE} BETWEEN"]),Qu=G([]),eI={name:"db2i",tokenizerOptions:{reservedSelect:Ku,reservedClauses:[...zu,...Ci,...ro],reservedSetOperations:Ju,reservedJoins:qu,reservedKeywordPhrases:Zu,reservedDataTypePhrases:Qu,reservedKeywords:Xu,reservedDataTypes:$u,reservedFunctionNames:ju,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:[...Ci,...ro],tabularOnelineClauses:ro}},tI=["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"],nI=["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"],rI=["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"],oI=G(["SELECT [ALL | DISTINCT]"]),sI=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"]),Li=G(["CREATE [OR REPLACE] [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),oo=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]"]),iI=G(["UNION [ALL | BY NAME]","EXCEPT [ALL]","INTERSECT [ALL]"]),EI=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"]),aI=G(["{ROWS | RANGE | GROUPS} BETWEEN","SIMILAR TO","IS [NOT] DISTINCT FROM"]),lI=G(["TIMESTAMP WITH TIME ZONE"]),TI={name:"duckdb",tokenizerOptions:{reservedSelect:oI,reservedClauses:[...sI,...Li,...oo],reservedSetOperations:iI,reservedJoins:EI,reservedKeywordPhrases:aI,reservedDataTypePhrases:lI,supportsXor:!0,reservedKeywords:nI,reservedDataTypes:rI,reservedFunctionNames:tI,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:[...Li,...oo],tabularOnelineClauses:oo}},cI=["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"],RI=["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"],SI=["ARRAY","BIGINT","BINARY","BOOLEAN","CHAR","DATE","DECIMAL","DOUBLE","FLOAT","INT","INTEGER","INTERVAL","MAP","NUMERIC","PRECISION","SMALLINT","STRUCT","TIMESTAMP","VARCHAR"],AI=G(["SELECT [ALL | DISTINCT]"]),dI=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"]),pi=G(["CREATE [TEMPORARY] [EXTERNAL] TABLE [IF NOT EXISTS]"]),so=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"]),uI=G(["UNION [ALL | DISTINCT]"]),II=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","LEFT SEMI JOIN"]),NI=G(["{ROWS | RANGE} BETWEEN"]),OI=G([]),fI={name:"hive",tokenizerOptions:{reservedSelect:AI,reservedClauses:[...dI,...pi,...so],reservedSetOperations:uI,reservedJoins:II,reservedKeywordPhrases:NI,reservedDataTypePhrases:OI,reservedKeywords:RI,reservedDataTypes:SI,reservedFunctionNames:cI,extraParens:["[]"],stringTypes:['""-bs',"''-bs"],identTypes:["``"],variableTypes:[{quote:"{}",prefixes:["$"],requirePrefix:!0}],operators:["%","~","^","|","&","<=>","==","!","||"]},formatOptions:{onelineClauses:[...pi,...so],tabularOnelineClauses:so}};function yr(e){return e.map((t,n)=>{const r=e[n+1]||Et;if(at.SET(t)&&r.text==="(")return Object.assign(Object.assign({},t),{type:W.RESERVED_FUNCTION_NAME});const o=e[n-1]||Et;return at.VALUES(t)&&o.text==="="?Object.assign(Object.assign({},t),{type:W.RESERVED_FUNCTION_NAME}):t})}const hI=["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"],CI=["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"],LI=["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"],pI=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),_I=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"]),_i=G(["CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]"]),io=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"]),mI=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]","MINUS [ALL | DISTINCT]"]),DI=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),gI=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),MI=G([]),xI={name:"mariadb",tokenizerOptions:{reservedSelect:pI,reservedClauses:[..._I,..._i,...io],reservedSetOperations:mI,reservedJoins:DI,reservedKeywordPhrases:gI,reservedDataTypePhrases:MI,supportsXor:!0,reservedKeywords:hI,reservedDataTypes:CI,reservedFunctionNames:LI,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:yr},formatOptions:{onelineClauses:[..._i,...io],tabularOnelineClauses:io}},PI=["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"],yI=["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"],UI=["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"],bI=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),vI=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"]),mi=G(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),Eo=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"]),BI=G(["UNION [ALL | DISTINCT]"]),GI=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),HI=G(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),FI=G([]),wI={name:"mysql",tokenizerOptions:{reservedSelect:bI,reservedClauses:[...vI,...mi,...Eo],reservedSetOperations:BI,reservedJoins:GI,reservedKeywordPhrases:HI,reservedDataTypePhrases:FI,supportsXor:!0,reservedKeywords:PI,reservedDataTypes:yI,reservedFunctionNames:UI,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:yr},formatOptions:{onelineClauses:[...mi,...Eo],tabularOnelineClauses:Eo}},YI=["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"],VI=["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"],WI=["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"],kI=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),jI=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"]),Di=G(["CREATE [TEMPORARY] TABLE [IF NOT EXISTS]"]),ao=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"]),XI=G(["UNION [ALL | DISTINCT]"]),$I=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),KI=G(["ON {UPDATE | DELETE} [SET NULL]","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),zI=G([]),JI={name:"tidb",tokenizerOptions:{reservedSelect:kI,reservedClauses:[...jI,...Di,...ao],reservedSetOperations:XI,reservedJoins:$I,reservedKeywordPhrases:KI,reservedDataTypePhrases:zI,supportsXor:!0,reservedKeywords:YI,reservedDataTypes:VI,reservedFunctionNames:WI,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:yr},formatOptions:{onelineClauses:[...Di,...ao],tabularOnelineClauses:ao}},qI=["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"],ZI=["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"],QI=[],eN=G(["SELECT [ALL | DISTINCT]"]),tN=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"]),gi=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"]),nN=G(["UNION [ALL]","EXCEPT [ALL]","INTERSECT [ALL]"]),rN=G(["JOIN","{LEFT | RIGHT} [OUTER] JOIN","INNER JOIN"]),oN=G(["{ROWS | RANGE | GROUPS} BETWEEN"]),sN=G([]),iN={name:"n1ql",tokenizerOptions:{reservedSelect:eN,reservedClauses:[...tN,...gi],reservedSetOperations:nN,reservedJoins:rN,reservedKeywordPhrases:oN,reservedDataTypePhrases:sN,supportsXor:!0,reservedKeywords:ZI,reservedDataTypes:QI,reservedFunctionNames:qI,stringTypes:['""-bs',"''-bs"],identTypes:["``"],extraParens:["[]","{}"],paramTypes:{positional:!0,numbered:["$"],named:["$"]},lineCommentTypes:["#","--"],operators:["%","==",":","||"]},formatOptions:{onelineClauses:gi}},EN=["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"],aN=["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"],lN=["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"],TN=G(["SELECT [ALL | DISTINCT | UNIQUE]"]),cN=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"]),Mi=G(["CREATE [GLOBAL TEMPORARY | PRIVATE TEMPORARY | SHARDED | DUPLICATED | IMMUTABLE BLOCKCHAIN | BLOCKCHAIN | IMMUTABLE] TABLE"]),lo=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"]),RN=G(["UNION [ALL]","MINUS","INTERSECT"]),SN=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | OUTER} APPLY"]),AN=G(["ON {UPDATE | DELETE} [SET NULL]","ON COMMIT","{ROWS | RANGE} BETWEEN"]),dN=G([]),uN={name:"plsql",tokenizerOptions:{reservedSelect:TN,reservedClauses:[...cN,...Mi,...lo],reservedSetOperations:RN,reservedJoins:SN,reservedKeywordPhrases:AN,reservedDataTypePhrases:dN,supportsXor:!0,reservedKeywords:EN,reservedDataTypes:aN,reservedFunctionNames:lN,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:IN},formatOptions:{alwaysDenseOperators:["@"],onelineClauses:[...Mi,...lo],tabularOnelineClauses:lo}};function IN(e){let t=Et;return e.map(n=>at.SET(n)&&at.BY(t)?Object.assign(Object.assign({},n),{type:W.RESERVED_KEYWORD}):($a(n.type)&&(t=n),n))}const NN=["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"],ON=["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"],fN=["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"],hN=G(["SELECT [ALL | DISTINCT]"]),CN=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"]),xi=G(["CREATE [GLOBAL | LOCAL] [TEMPORARY | TEMP | UNLOGGED] TABLE [IF NOT EXISTS]"]),To=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"]),LN=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),pN=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),_N=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"]),mN=G(["[TIMESTAMP | TIME] {WITH | WITHOUT} TIME ZONE"]),DN={name:"postgresql",tokenizerOptions:{reservedSelect:hN,reservedClauses:[...CN,...xi,...To],reservedSetOperations:LN,reservedJoins:pN,reservedKeywordPhrases:_N,reservedDataTypePhrases:mN,reservedKeywords:ON,reservedDataTypes:fN,reservedFunctionNames:NN,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:[...xi,...To],tabularOnelineClauses:To}},gN=["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"],MN=["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"],xN=["ARRAY","BIGINT","BPCHAR","CHAR","CHARACTER VARYING","CHARACTER","DECIMAL","INT","INT2","INT4","INT8","INTEGER","NCHAR","NUMERIC","NVARCHAR","SMALLINT","TEXT","VARBYTE","VARCHAR"],PN=G(["SELECT [ALL | DISTINCT]"]),yN=G(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY","HAVING","QUALIFY","PARTITION BY","ORDER BY","LIMIT","OFFSET","INSERT INTO","VALUES","SET"]),Pi=G(["CREATE [TEMPORARY | TEMP | LOCAL TEMPORARY | LOCAL TEMP] TABLE [IF NOT EXISTS]"]),co=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"]),UN=G(["UNION [ALL]","EXCEPT","INTERSECT","MINUS"]),bN=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),vN=G(["NULL AS","DATA CATALOG","HIVE METASTORE","{ROWS | RANGE} BETWEEN"]),BN=G([]),GN={name:"redshift",tokenizerOptions:{reservedSelect:PN,reservedClauses:[...yN,...Pi,...co],reservedSetOperations:UN,reservedJoins:bN,reservedKeywordPhrases:vN,reservedDataTypePhrases:BN,reservedKeywords:MN,reservedDataTypes:xN,reservedFunctionNames:gN,extraParens:["[]"],stringTypes:["''-qq"],identTypes:['""-qq'],identChars:{first:"#"},paramTypes:{numbered:["$"]},operators:["^","%","@","|/","||/","&","|","~","<<",">>","||","::"]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...Pi,...co],tabularOnelineClauses:co}},HN=["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"],FN=["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"],wN=["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"],YN=G(["SELECT [ALL | DISTINCT]"]),VN=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"]),yi=G(["CREATE [EXTERNAL] TABLE [IF NOT EXISTS]"]),Ro=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"]),WN=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),kN=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"]),jN=G(["ON DELETE","ON UPDATE","CURRENT ROW","{ROWS | RANGE} BETWEEN"]),XN=G([]),$N={name:"spark",tokenizerOptions:{reservedSelect:YN,reservedClauses:[...VN,...yi,...Ro],reservedSetOperations:WN,reservedJoins:kN,reservedKeywordPhrases:jN,reservedDataTypePhrases:XN,supportsXor:!0,reservedKeywords:HN,reservedDataTypes:FN,reservedFunctionNames:wN,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:KN},formatOptions:{onelineClauses:[...yi,...Ro],tabularOnelineClauses:Ro}};function KN(e){return e.map((t,n)=>{const r=e[n-1]||Et,o=e[n+1]||Et;return at.WINDOW(t)&&o.type===W.OPEN_PAREN?Object.assign(Object.assign({},t),{type:W.RESERVED_FUNCTION_NAME}):t.text==="ITEMS"&&t.type===W.RESERVED_KEYWORD&&!(r.text==="COLLECTION"&&o.text==="TERMINATED")?Object.assign(Object.assign({},t),{type:W.IDENTIFIER,text:t.raw}):t})}const zN=["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"],JN=["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"],qN=["ANY","ARRAY","BLOB","CHARACTER","DECIMAL","INT","INTEGER","NATIVE CHARACTER","NCHAR","NUMERIC","NVARCHAR","REAL","TEXT","VARCHAR","VARYING CHARACTER"],ZN=G(["SELECT [ALL | DISTINCT]"]),QN=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"]),Ui=G(["CREATE [TEMPORARY | TEMP] TABLE [IF NOT EXISTS]"]),So=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"]),eO=G(["UNION [ALL]","EXCEPT","INTERSECT"]),tO=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),nO=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE | GROUPS} BETWEEN","DO UPDATE"]),rO=G([]),oO={name:"sqlite",tokenizerOptions:{reservedSelect:ZN,reservedClauses:[...QN,...Ui,...So],reservedSetOperations:eO,reservedJoins:tO,reservedKeywordPhrases:nO,reservedDataTypePhrases:rO,reservedKeywords:JN,reservedDataTypes:qN,reservedFunctionNames:zN,stringTypes:["''-qq",{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``","[]"],paramTypes:{positional:!0,numbered:["?"],named:[":","@","$"]},operators:["%","~","&","|","<<",">>","==","->","->>","||"]},formatOptions:{onelineClauses:[...Ui,...So],tabularOnelineClauses:So}},sO=["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"],iO=["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"],EO=["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"],aO=G(["SELECT [ALL | DISTINCT]"]),lO=G(["WITH [RECURSIVE]","FROM","WHERE","GROUP BY [ALL | DISTINCT]","HAVING","WINDOW","PARTITION BY","ORDER BY","LIMIT","OFFSET","FETCH {FIRST | NEXT}","INSERT INTO","VALUES","SET"]),bi=G(["CREATE [GLOBAL TEMPORARY | LOCAL TEMPORARY] TABLE"]),Ao=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"]),TO=G(["UNION [ALL | DISTINCT]","EXCEPT [ALL | DISTINCT]","INTERSECT [ALL | DISTINCT]"]),cO=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),RO=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),SO=G([]),AO={name:"sql",tokenizerOptions:{reservedSelect:aO,reservedClauses:[...lO,...bi,...Ao],reservedSetOperations:TO,reservedJoins:cO,reservedKeywordPhrases:RO,reservedDataTypePhrases:SO,reservedKeywords:iO,reservedDataTypes:EO,reservedFunctionNames:sO,stringTypes:[{quote:"''-qq-bs",prefixes:["N","U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq',"``"],paramTypes:{positional:!0},operators:["||"]},formatOptions:{onelineClauses:[...bi,...Ao],tabularOnelineClauses:Ao}},dO=["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"],uO=["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"],IO=["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"],NO=G(["SELECT [ALL | DISTINCT]"]),OO=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"]),vi=G(["CREATE TABLE [IF NOT EXISTS]"]),uo=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"]),fO=G(["UNION [ALL | DISTINCT] [CORRESPONDING]","EXCEPT [ALL | DISTINCT] [CORRESPONDING]","INTERSECT [ALL | DISTINCT] [CORRESPONDING]"]),hO=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL [INNER] JOIN","NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN"]),CO=G(["{ROWS | RANGE | GROUPS} BETWEEN","IS [NOT] DISTINCT FROM"]),LO=G([]),pO={name:"trino",tokenizerOptions:{reservedSelect:NO,reservedClauses:[...OO,...vi,...uo],reservedSetOperations:fO,reservedJoins:hO,reservedKeywordPhrases:CO,reservedDataTypePhrases:LO,reservedKeywords:uO,reservedDataTypes:IO,reservedFunctionNames:dO,extraParens:["[]","{}"],stringTypes:[{quote:"''-qq",prefixes:["U&"]},{quote:"''-raw",prefixes:["X"],requirePrefix:!0}],identTypes:['""-qq'],paramTypes:{positional:!0},operators:["%","->","=>",":","||","|","^","$"]},formatOptions:{onelineClauses:[...vi,...uo],tabularOnelineClauses:uo}},_O=["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"],mO=["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"],DO=["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"],gO=G(["SELECT [ALL | DISTINCT]"]),MO=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"]),Bi=G(["CREATE TABLE"]),Io=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"]),xO=G(["UNION [ALL]","EXCEPT","INTERSECT"]),PO=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","{CROSS | OUTER} APPLY"]),yO=G(["ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]","{ROWS | RANGE} BETWEEN"]),UO=G([]),bO={name:"transactsql",tokenizerOptions:{reservedSelect:gO,reservedClauses:[...MO,...Bi,...Io],reservedSetOperations:xO,reservedJoins:PO,reservedKeywordPhrases:yO,reservedDataTypePhrases:UO,reservedKeywords:mO,reservedDataTypes:DO,reservedFunctionNames:_O,nestedBlockComments:!0,stringTypes:[{quote:"''-qq",prefixes:["N"]},"{}"],identTypes:['""-qq',"[]"],identChars:{first:"#@",rest:"#@$"},paramTypes:{named:["@"],quoted:["@"]},operators:["%","&","|","^","~","!<","!>","+=","-=","*=","/=","%=","|=","&=","^=","::",":"],propertyAccessOperators:[".."]},formatOptions:{alwaysDenseOperators:["::"],onelineClauses:[...Bi,...Io],tabularOnelineClauses:Io}},vO=["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"],BO=["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"],GO=["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"],HO=G(["SELECT [ALL | DISTINCT | DISTINCTROW]"]),FO=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"]),Gi=G(["CREATE [ROWSTORE] [REFERENCE | TEMPORARY | GLOBAL TEMPORARY] TABLE [IF NOT EXISTS]"]),No=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"]),wO=G(["UNION [ALL | DISTINCT]","EXCEPT","INTERSECT","MINUS"]),YO=G(["JOIN","{LEFT | RIGHT | FULL} [OUTER] JOIN","{INNER | CROSS} JOIN","NATURAL {LEFT | RIGHT} [OUTER] JOIN","STRAIGHT_JOIN"]),VO=G(["ON DELETE","ON UPDATE","CHARACTER SET","{ROWS | RANGE} BETWEEN","IDENTIFIED BY"]),WO=G([]),kO={name:"singlestoredb",tokenizerOptions:{reservedSelect:HO,reservedClauses:[...FO,...Gi,...No],reservedSetOperations:wO,reservedJoins:YO,reservedKeywordPhrases:VO,reservedDataTypePhrases:WO,reservedKeywords:vO,reservedDataTypes:BO,reservedFunctionNames:GO,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:yr},formatOptions:{alwaysDenseOperators:["::","::$","::%"],onelineClauses:[...Gi,...No],tabularOnelineClauses:No}},jO=["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"],XO=["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"],$O=["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"],KO=G(["SELECT [ALL | DISTINCT]"]),zO=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"]),Hi=G(["CREATE [OR REPLACE] [VOLATILE] TABLE [IF NOT EXISTS]","CREATE [OR REPLACE] [LOCAL | GLOBAL] {TEMP|TEMPORARY} TABLE [IF NOT EXISTS]"]),Oo=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"]),JO=G(["UNION [ALL]","MINUS","EXCEPT","INTERSECT"]),qO=G(["[INNER] JOIN","[NATURAL] {LEFT | RIGHT | FULL} [OUTER] JOIN","{CROSS | NATURAL} JOIN"]),ZO=G(["{ROWS | RANGE} BETWEEN","ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]"]),QO=G([]),ef={name:"snowflake",tokenizerOptions:{reservedSelect:KO,reservedClauses:[...zO,...Hi,...Oo],reservedSetOperations:JO,reservedJoins:qO,reservedKeywordPhrases:ZO,reservedDataTypePhrases:QO,reservedKeywords:XO,reservedDataTypes:$O,reservedFunctionNames:jO,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:[...Hi,...Oo],tabularOnelineClauses:Oo}},tf=Object.freeze(Object.defineProperty({__proto__:null,bigquery:fu,clickhouse:Uu,db2:ku,db2i:eI,duckdb:TI,hive:fI,mariadb:xI,mysql:wI,n1ql:iN,plsql:uN,postgresql:DN,redshift:GN,singlestoredb:kO,snowflake:ef,spark:$N,sql:AO,sqlite:oO,tidb:JI,transactsql:bO,trino:pO},Symbol.toStringTag,{value:"Module"})),ln=e=>e[e.length-1],Ka=e=>e.sort((t,n)=>n.length-t.length||t.localeCompare(n)),er=e=>e.replace(/\s+/gu," "),fo=e=>/\n/.test(e),ve=e=>e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),Fi=/\s+/uy,ht=e=>new RegExp(`(?:${e})`,"uy"),nf=e=>e.split("").map(t=>/ /gu.test(t)?"\\s+":`[${t.toUpperCase()}${t.toLowerCase()}]`).join(""),rf=e=>e+"(?:-"+e+")*",of=({prefixes:e,requirePrefix:t})=>`(?:${e.map(nf).join("|")}${t?"":"|"})`,sf=e=>new RegExp(`(?:${e.map(ve).join("|")}).*?(?=\r
|
|
432
|
-
|\r|
|
|
433
|
-
|$)`,"uy"),wi=(e,t=[])=>{const n=e==="open"?0:1,r=["()",...t].map(o=>o[n]);return ht(r.map(ve).join("|"))},Yi=e=>ht(`${Ka(e).map(ve).join("|")}`),Ef=({rest:e,dashes:t})=>e||t?`(?![${e||""}${t?"-":""}])`:"",$e=(e,t={})=>{if(e.length===0)return/^\b$/u;const n=Ef(t),r=Ka(e).map(ve).join("|").replace(/ /gu,"\\s+");return new RegExp(`(?:${r})${n}\\b`,"iuy")},ho=(e,t)=>{if(!e.length)return;const n=e.map(ve).join("|");return ht(`(?:${n})(?:${t})`)},af=()=>{const e={"<":">","[":"]","(":")","{":"}"},t="{left}(?:(?!{right}').)*?{right}",n=Object.entries(e).map(([i,a])=>t.replace(/{left}/g,ve(i)).replace(/{right}/g,ve(a))),r=ve(Object.keys(e).join(""));return`[Qq]'(?:${String.raw`(?<tag>[^\s${r}])(?:(?!\k<tag>').)*?\k<tag>`}|${n.join("|")})'`},Vi={"``":"(?:`[^`]*`)+","[]":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''":af()},za=e=>typeof e=="string"?Vi[e]:"regex"in e?e.regex:of(e)+Vi[e.quote],lf=e=>ht(e.map(t=>"regex"in t?t.regex:za(t)).join("|")),Ja=e=>e.map(za).join("|"),Wi=e=>ht(Ja(e)),Tf=(e={})=>ht(qa(e)),qa=({first:e,rest:t,dashes:n,allowFirstCharNumber:r}={})=>{const o="\\p{Alphabetic}\\p{Mark}_",s="\\p{Decimal_Number}",i=ve(e??""),a=ve(t??""),T=r?`[${o}${s}${i}][${o}${s}${a}]*`:`[${o}${i}][${o}${s}${a}]*`;return n?rf(T):T};function Za(e,t){const n=e.slice(0,t).split(/\n/);return{line:n.length,col:n[n.length-1].length+1}}class cf{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}=Za(this.input,this.index);return new Error(`Parse error: Unexpected "${t}" at line ${n} column ${r}.
|
|
434
|
-
${this.dialectInfo()}`)}dialectInfo(){return this.dialectName==="sql"?`This likely happens because you're using the default "sql" dialect.
|
|
435
|
-
If possible, please select a more specific dialect (like sqlite, postgresql, etc).`:`SQL dialect used: "${this.dialectName}".`}getWhitespace(){Fi.lastIndex=this.index;const t=Fi.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 ki=/\/\*/uy,Rf=/[\s\S]/uy,Sf=/\*\//uy;class Af{constructor(){this.lastIndex=0}exec(t){let n="",r,o=0;if(r=this.matchSection(ki,t))n+=r,o++;else return null;for(;o>0;)if(r=this.matchSection(ki,t))n+=r,o++;else if(r=this.matchSection(Sf,t))n+=r,o--;else if(r=this.matchSection(Rf,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 df{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 cf(r,this.dialectName).tokenize(t);return this.cfg.postProcess?this.cfg.postProcess(o):o}buildRulesBeforeParams(t){var n,r,o;return this.validRules([{type:W.DISABLE_COMMENT,regex:/(\/\* *sql-formatter-disable *\*\/[\s\S]*?(?:\/\* *sql-formatter-enable *\*\/|$))/uy},{type:W.BLOCK_COMMENT,regex:t.nestedBlockComments?new Af:/(\/\*[^]*?\*\/)/uy},{type:W.LINE_COMMENT,regex:sf((n=t.lineCommentTypes)!==null&&n!==void 0?n:["--"])},{type:W.QUOTED_IDENTIFIER,regex:Wi(t.identTypes)},{type:W.NUMBER,regex:t.underscoresInNumbers?/(?:0x[0-9a-fA-F_]+|0b[01_]+|(?:-\s*)?(?:[0-9_]*\.[0-9_]+|[0-9_]+(?:\.[0-9_]*)?)(?:[eE][-+]?[0-9_]+(?:\.[0-9_]+)?)?)(?![\w\p{Alphabetic}])/uy:/(?:0x[0-9a-fA-F]+|0b[01]+|(?:-\s*)?(?:[0-9]*\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+(?:\.[0-9]+)?)?)(?![\w\p{Alphabetic}])/uy},{type:W.RESERVED_KEYWORD_PHRASE,regex:$e((r=t.reservedKeywordPhrases)!==null&&r!==void 0?r:[],t.identChars),text:Ae},{type:W.RESERVED_DATA_TYPE_PHRASE,regex:$e((o=t.reservedDataTypePhrases)!==null&&o!==void 0?o:[],t.identChars),text:Ae},{type:W.CASE,regex:/CASE\b/iuy,text:Ae},{type:W.END,regex:/END\b/iuy,text:Ae},{type:W.BETWEEN,regex:/BETWEEN\b/iuy,text:Ae},{type:W.LIMIT,regex:t.reservedClauses.includes("LIMIT")?/LIMIT\b/iuy:void 0,text:Ae},{type:W.RESERVED_CLAUSE,regex:$e(t.reservedClauses,t.identChars),text:Ae},{type:W.RESERVED_SELECT,regex:$e(t.reservedSelect,t.identChars),text:Ae},{type:W.RESERVED_SET_OPERATION,regex:$e(t.reservedSetOperations,t.identChars),text:Ae},{type:W.WHEN,regex:/WHEN\b/iuy,text:Ae},{type:W.ELSE,regex:/ELSE\b/iuy,text:Ae},{type:W.THEN,regex:/THEN\b/iuy,text:Ae},{type:W.RESERVED_JOIN,regex:$e(t.reservedJoins,t.identChars),text:Ae},{type:W.AND,regex:/AND\b/iuy,text:Ae},{type:W.OR,regex:/OR\b/iuy,text:Ae},{type:W.XOR,regex:t.supportsXor?/XOR\b/iuy:void 0,text:Ae},...t.operatorKeyword?[{type:W.OPERATOR,regex:/OPERATOR *\([^)]+\)/iuy}]:[],{type:W.RESERVED_FUNCTION_NAME,regex:$e(t.reservedFunctionNames,t.identChars),text:Ae},{type:W.RESERVED_DATA_TYPE,regex:$e(t.reservedDataTypes,t.identChars),text:Ae},{type:W.RESERVED_KEYWORD,regex:$e(t.reservedKeywords,t.identChars),text:Ae}])}buildRulesAfterParams(t){var n,r;return this.validRules([{type:W.VARIABLE,regex:t.variableTypes?lf(t.variableTypes):void 0},{type:W.STRING,regex:Wi(t.stringTypes)},{type:W.IDENTIFIER,regex:Tf(t.identChars)},{type:W.DELIMITER,regex:/[;]/uy},{type:W.COMMA,regex:/[,]/y},{type:W.OPEN_PAREN,regex:wi("open",t.extraParens)},{type:W.CLOSE_PAREN,regex:wi("close",t.extraParens)},{type:W.OPERATOR,regex:Yi(["+","-","/",">","<","=","<>","<=",">=","!=",...(n=t.operators)!==null&&n!==void 0?n:[]])},{type:W.ASTERISK,regex:/[*]/uy},{type:W.PROPERTY_ACCESS_OPERATOR,regex:Yi([".",...(r=t.propertyAccessOperators)!==null&&r!==void 0?r:[]])}])}buildParamRules(t,n){var r,o,s,i,a;const T={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)||((a=t.paramTypes)===null||a===void 0?void 0:a.custom)||[]};return this.validRules([{type:W.NAMED_PARAMETER,regex:ho(T.named,qa(t.paramChars||t.identChars)),key:l=>l.slice(1)},{type:W.QUOTED_PARAMETER,regex:ho(T.quoted,Ja(t.identTypes)),key:l=>(({tokenKey:R,quoteChar:c})=>R.replace(new RegExp(ve("\\"+c),"gu"),c))({tokenKey:l.slice(2,-1),quoteChar:l.slice(-1)})},{type:W.NUMBERED_PARAMETER,regex:ho(T.numbered,"[0-9]+"),key:l=>l.slice(1)},{type:W.POSITIONAL_PARAMETER,regex:T.positional?/[?]/y:void 0},...T.custom.map(l=>{var R;return{type:W.CUSTOM_PARAMETER,regex:ht(l.regex),key:(R=l.key)!==null&&R!==void 0?R:(c=>c)}})])}validRules(t){return t.filter(n=>!!n.regex)}}const Ae=e=>er(e.toUpperCase()),ji=new Map,uf=e=>{let t=ji.get(e);return t||(t=If(e),ji.set(e,t)),t},If=e=>({tokenizer:new df(e.tokenizerOptions,e.name),formatOptions:Nf(e.formatOptions)}),Nf=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 Of(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"?" ".repeat(10):e.useTabs?" ":" ".repeat(e.tabWidth)}function _t(e){return e.indentStyle==="tabularLeft"||e.indentStyle==="tabularRight"}class ff{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 tr={exports:{}},hf=tr.exports,Xi;function Cf(){return Xi||(Xi=1,(function(e){(function(t,n){e.exports?e.exports=n():t.nearley=n()})(hf,function(){function t(l,R,c){return this.id=++t.highestId,this.name=l,this.symbols=R,this.postprocess=c,this}t.highestId=0,t.prototype.toString=function(l){var R=typeof l>"u"?this.symbols.map(T).join(" "):this.symbols.slice(0,l).map(T).join(" ")+" ● "+this.symbols.slice(l).map(T).join(" ");return this.name+" → "+R};function n(l,R,c,S){this.rule=l,this.dot=R,this.reference=c,this.data=[],this.wantedBy=S,this.isComplete=this.dot===l.symbols.length}n.prototype.toString=function(){return"{"+this.rule.toString(this.dot)+"}, from: "+(this.reference||0)},n.prototype.nextState=function(l){var R=new n(this.rule,this.dot+1,this.reference,this.wantedBy);return R.left=this,R.right=l,R.isComplete&&(R.data=R.build(),R.right=void 0),R},n.prototype.build=function(){var l=[],R=this;do l.push(R.right.data),R=R.left;while(R.left);return l.reverse(),l},n.prototype.finish=function(){this.rule.postprocess&&(this.data=this.rule.postprocess(this.data,this.reference,i.fail))};function r(l,R){this.grammar=l,this.index=R,this.states=[],this.wants={},this.scannable=[],this.completed={}}r.prototype.process=function(l){for(var R=this.states,c=this.wants,S=this.completed,A=0;A<R.length;A++){var d=R[A];if(d.isComplete){if(d.finish(),d.data!==i.fail){for(var N=d.wantedBy,I=N.length;I--;){var u=N[I];this.complete(u,d)}if(d.reference===this.index){var f=d.rule.name;(this.completed[f]=this.completed[f]||[]).push(d)}}}else{var f=d.rule.symbols[d.dot];if(typeof f!="string"){this.scannable.push(d);continue}if(c[f]){if(c[f].push(d),S.hasOwnProperty(f))for(var O=S[f],I=0;I<O.length;I++){var C=O[I];this.complete(d,C)}}else c[f]=[d],this.predict(f)}}},r.prototype.predict=function(l){for(var R=this.grammar.byName[l]||[],c=0;c<R.length;c++){var S=R[c],A=this.wants[l],d=new n(S,0,this.index,A);this.states.push(d)}},r.prototype.complete=function(l,R){var c=l.nextState(R);this.states.push(c)};function o(l,R){this.rules=l,this.start=R||this.rules[0].name;var c=this.byName={};this.rules.forEach(function(S){c.hasOwnProperty(S.name)||(c[S.name]=[]),c[S.name].push(S)})}o.fromCompiled=function(S,R){var c=S.Lexer;S.ParserStart&&(R=S.ParserStart,S=S.ParserRules);var S=S.map(function(d){return new t(d.name,d.symbols,d.postprocess)}),A=new o(S,R);return A.lexer=c,A};function s(){this.reset("")}s.prototype.reset=function(l,R){this.buffer=l,this.index=0,this.line=R?R.line:1,this.lastLineBreak=R?-R.col:0},s.prototype.next=function(){if(this.index<this.buffer.length){var l=this.buffer[this.index++];return l===`
|
|
436
|
-
`&&(this.line+=1,this.lastLineBreak=this.index),{value:l}}},s.prototype.save=function(){return{line:this.line,col:this.index-this.lastLineBreak}},s.prototype.formatError=function(l,R){var c=this.buffer;if(typeof c=="string"){var S=c.split(`
|
|
437
|
-
`).slice(Math.max(0,this.line-5),this.line),A=c.indexOf(`
|
|
438
|
-
`,this.index);A===-1&&(A=c.length);var d=this.index-this.lastLineBreak,N=String(this.line).length;return R+=" at line "+this.line+" col "+d+`:
|
|
439
|
-
|
|
440
|
-
`,R+=S.map(function(u,f){return I(this.line-S.length+f+1,N)+" "+u},this).join(`
|
|
441
|
-
`),R+=`
|
|
442
|
-
`+I("",N+d)+`^
|
|
443
|
-
`,R}else return R+" at index "+(this.index-1);function I(u,f){var O=String(u);return Array(f-O.length+1).join(" ")+O}};function i(l,R,c){if(l instanceof o)var S=l,c=R;else var S=o.fromCompiled(l,R);this.grammar=S,this.options={keepHistory:!1,lexer:S.lexer||new s};for(var A in c||{})this.options[A]=c[A];this.lexer=this.options.lexer,this.lexerState=void 0;var d=new r(S,0);this.table=[d],d.wants[S.start]=[],d.predict(S.start),d.process(),this.current=0}i.fail={},i.prototype.feed=function(l){var R=this.lexer;R.reset(l,this.lexerState);for(var c;;){try{if(c=R.next(),!c)break}catch(D){var N=new r(this.grammar,this.current+1);this.table.push(N);var S=new Error(this.reportLexerError(D));throw S.offset=this.current,S.token=D.token,S}var A=this.table[this.current];this.options.keepHistory||delete this.table[this.current-1];var d=this.current+1,N=new r(this.grammar,d);this.table.push(N);for(var I=c.text!==void 0?c.text:c.value,u=R.constructor===s?c.value:c,f=A.scannable,O=f.length;O--;){var C=f[O],m=C.rule.symbols[C.dot];if(m.test?m.test(u):m.type?m.type===c.type:m.literal===I){var L=C.nextState({data:u,token:c,isToken:!0,reference:d-1});N.states.push(L)}}if(N.process(),N.states.length===0){var S=new Error(this.reportError(c));throw S.offset=this.current,S.token=c,S}this.options.keepHistory&&(A.lexerState=R.save()),this.current++}return A&&(this.lexerState=R.save()),this.results=this.finish(),this},i.prototype.reportLexerError=function(l){var R,c,S=l.token;return S?(R="input "+JSON.stringify(S.text[0])+" (lexer error)",c=this.lexer.formatError(S,"Syntax error")):(R="input (lexer error)",c=l.message),this.reportErrorCommon(c,R)},i.prototype.reportError=function(l){var R=(l.type?l.type+" token: ":"")+JSON.stringify(l.value!==void 0?l.value:l),c=this.lexer.formatError(l,"Syntax error");return this.reportErrorCommon(c,R)},i.prototype.reportErrorCommon=function(l,R){var c=[];c.push(l);var S=this.table.length-2,A=this.table[S],d=A.states.filter(function(I){var u=I.rule.symbols[I.dot];return u&&typeof u!="string"});if(d.length===0)c.push("Unexpected "+R+`. I did not expect any more input. Here is the state of my parse table:
|
|
444
|
-
`),this.displayStateStack(A.states,c);else{c.push("Unexpected "+R+`. Instead, I was expecting to see one of the following:
|
|
445
|
-
`);var N=d.map(function(I){return this.buildFirstStateStack(I,[])||[I]},this);N.forEach(function(I){var u=I[0],f=u.rule.symbols[u.dot],O=this.getSymbolDisplay(f);c.push("A "+O+" based on:"),this.displayStateStack(I,c)},this)}return c.push(""),c.join(`
|
|
446
|
-
`)},i.prototype.displayStateStack=function(l,R){for(var c,S=0,A=0;A<l.length;A++){var d=l[A],N=d.rule.toString(d.dot);N===c?S++:(S>0&&R.push(" ^ "+S+" more lines identical to this"),S=0,R.push(" "+N)),c=N}},i.prototype.getSymbolDisplay=function(l){return a(l)},i.prototype.buildFirstStateStack=function(l,R){if(R.indexOf(l)!==-1)return null;if(l.wantedBy.length===0)return[l];var c=l.wantedBy[0],S=[l].concat(R),A=this.buildFirstStateStack(c,S);return A===null?null:[l].concat(A)},i.prototype.save=function(){var l=this.table[this.current];return l.lexerState=this.lexerState,l},i.prototype.restore=function(l){var R=l.index;this.current=R,this.table[R]=l,this.table.splice(R+1),this.lexerState=l.lexerState,this.results=this.finish()},i.prototype.rewind=function(l){if(!this.options.keepHistory)throw new Error("set option `keepHistory` to enable rewinding");this.restore(this.table[l])},i.prototype.finish=function(){var l=[],R=this.grammar.start,c=this.table[this.table.length-1];return c.states.forEach(function(S){S.rule.name===R&&S.dot===S.rule.symbols.length&&S.reference===0&&S.data!==i.fail&&l.push(S)}),l.map(function(S){return S.data})};function a(l){var R=typeof l;if(R==="string")return l;if(R==="object"){if(l.literal)return JSON.stringify(l.literal);if(l instanceof RegExp)return"character matching "+l;if(l.type)return l.type+" token";if(l.test)return"token matching "+String(l.test);throw new Error("Unknown symbol type: "+l)}}function T(l){var R=typeof l;if(R==="string")return l;if(R==="object"){if(l.literal)return JSON.stringify(l.literal);if(l instanceof RegExp)return l.toString();if(l.type)return"%"+l.type;if(l.test)return"<"+String(l.test)+">";throw new Error("Unknown symbol type: "+l)}}return{Parser:i,Grammar:o,Rule:t}})})(tr)),tr.exports}var Lf=Cf();const pf=As(Lf);function _f(e){return e.map(mf).map(Df).map(gf).map(Mf).map(xf)}const mf=(e,t,n)=>{if($a(e.type)){const r=Pf(n,t);if(r&&r.type===W.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:W.IDENTIFIER,text:e.raw});const o=Xt(n,t);if(o&&o.type===W.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:W.IDENTIFIER,text:e.raw})}return e},Df=(e,t,n)=>{if(e.type===W.RESERVED_FUNCTION_NAME){const r=Xt(n,t);if(!r||!Qa(r))return Object.assign(Object.assign({},e),{type:W.IDENTIFIER,text:e.raw})}return e},gf=(e,t,n)=>{if(e.type===W.RESERVED_DATA_TYPE){const r=Xt(n,t);if(r&&Qa(r))return Object.assign(Object.assign({},e),{type:W.RESERVED_PARAMETERIZED_DATA_TYPE})}return e},Mf=(e,t,n)=>{if(e.type===W.IDENTIFIER){const r=Xt(n,t);if(r&&el(r))return Object.assign(Object.assign({},e),{type:W.ARRAY_IDENTIFIER})}return e},xf=(e,t,n)=>{if(e.type===W.RESERVED_DATA_TYPE){const r=Xt(n,t);if(r&&el(r))return Object.assign(Object.assign({},e),{type:W.ARRAY_KEYWORD})}return e},Pf=(e,t)=>Xt(e,t,-1),Xt=(e,t,n=1)=>{let r=1;for(;e[t+r*n]&&yf(e[t+r*n]);)r++;return e[t+r*n]},Qa=e=>e.type===W.OPEN_PAREN&&e.text==="(",el=e=>e.type===W.OPEN_PAREN&&e.text==="[",yf=e=>e.type===W.BLOCK_COMMENT||e.type===W.LINE_COMMENT;class tl{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}=Za(this.input,t.start);return`Parse error at token: ${t.text} at line ${n} column ${r}`}has(t){return t in W}}var z;(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"})(z=z||(z={}));function Co(e){return e[0]}const ne=new tl(e=>[]),Tt=([[e]])=>e,de=e=>({type:z.keyword,tokenType:e.type,text:e.text,raw:e.raw}),$i=e=>({type:z.data_type,text:e.text,raw:e.raw}),ue=(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),Uf=(e,{leading:t,trailing:n})=>{if(t!=null&&t.length){const[r,...o]=e;e=[ue(r,{leading:t}),...o]}if(n!=null&&n.length){const r=e.slice(0,-1),o=e[e.length-1];e=[...r,ue(o,{trailing:n})]}return e},bf={Lexer:ne,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:[ne.has("DELIMITER")?{type:"DELIMITER"}:DELIMITER]},{name:"statement$subexpression$1",symbols:[ne.has("EOF")?{type:"EOF"}:EOF]},{name:"statement",symbols:["expressions_or_clauses","statement$subexpression$1"],postprocess:([e,[t]])=>({type:z.statement,children:e,hasSemicolon:t.type===W.DELIMITER})},{name:"expressions_or_clauses$ebnf$1",symbols:[]},{name:"expressions_or_clauses$ebnf$1",symbols:["expressions_or_clauses$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"expressions_or_clauses$ebnf$2",symbols:[]},{name:"expressions_or_clauses$ebnf$2",symbols:["expressions_or_clauses$ebnf$2","clause"],postprocess:e=>e[0].concat([e[1]])},{name:"expressions_or_clauses",symbols:["expressions_or_clauses$ebnf$1","expressions_or_clauses$ebnf$2"],postprocess:([e,t])=>[...e,...t]},{name:"clause$subexpression$1",symbols:["limit_clause"]},{name:"clause$subexpression$1",symbols:["select_clause"]},{name:"clause$subexpression$1",symbols:["other_clause"]},{name:"clause$subexpression$1",symbols:["set_operation"]},{name:"clause",symbols:["clause$subexpression$1"],postprocess:Tt},{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:[ne.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:Co},{name:"limit_clause$ebnf$1",symbols:[],postprocess:()=>null},{name:"limit_clause",symbols:[ne.has("LIMIT")?{type:"LIMIT"}:LIMIT,"_","expression_chain_","limit_clause$ebnf$1"],postprocess:([e,t,n,r])=>{if(r){const[o,s]=r;return{type:z.limit_clause,limitKw:ue(de(e),{trailing:t}),offset:n,count:s}}else return{type:z.limit_clause,limitKw:ue(de(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:[ne.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT,"select_clause$subexpression$1"],postprocess:([e,[t,n]])=>({type:z.clause,nameKw:de(e),children:[t,...n]})},{name:"select_clause",symbols:[ne.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT],postprocess:([e])=>({type:z.clause,nameKw:de(e),children:[]})},{name:"all_columns_asterisk",symbols:[ne.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK],postprocess:()=>({type:z.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:[ne.has("RESERVED_CLAUSE")?{type:"RESERVED_CLAUSE"}:RESERVED_CLAUSE,"other_clause$ebnf$1"],postprocess:([e,t])=>({type:z.clause,nameKw:de(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:[ne.has("RESERVED_SET_OPERATION")?{type:"RESERVED_SET_OPERATION"}:RESERVED_SET_OPERATION,"set_operation$ebnf$1"],postprocess:([e,t])=>({type:z.set_operation,nameKw:de(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:Co},{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])=>ue(e,{trailing:t})},{name:"_expression_with_comments",symbols:["_","expression"],postprocess:([e,t])=>ue(t,{leading:e})},{name:"_andless_expression_with_comments",symbols:["_","andless_expression"],postprocess:([e,t])=>ue(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:Tt},{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:Tt},{name:"expression$subexpression$1",symbols:["andless_expression"]},{name:"expression$subexpression$1",symbols:["logic_operator"]},{name:"expression",symbols:["expression$subexpression$1"],postprocess:Tt},{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:Tt},{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:Tt},{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:Tt},{name:"array_subscript",symbols:[ne.has("ARRAY_IDENTIFIER")?{type:"ARRAY_IDENTIFIER"}:ARRAY_IDENTIFIER,"_","square_brackets"],postprocess:([e,t,n])=>({type:z.array_subscript,array:ue({type:z.identifier,quoted:!1,text:e.text},{trailing:t}),parenthesis:n})},{name:"array_subscript",symbols:[ne.has("ARRAY_KEYWORD")?{type:"ARRAY_KEYWORD"}:ARRAY_KEYWORD,"_","square_brackets"],postprocess:([e,t,n])=>({type:z.array_subscript,array:ue(de(e),{trailing:t}),parenthesis:n})},{name:"function_call",symbols:[ne.has("RESERVED_FUNCTION_NAME")?{type:"RESERVED_FUNCTION_NAME"}:RESERVED_FUNCTION_NAME,"_","parenthesis"],postprocess:([e,t,n])=>({type:z.function_call,nameKw:ue(de(e),{trailing:t}),parenthesis:n})},{name:"parenthesis",symbols:[{literal:"("},"expressions_or_clauses",{literal:")"}],postprocess:([e,t,n])=>({type:z.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:z.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:z.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","_",ne.has("PROPERTY_ACCESS_OPERATOR")?{type:"PROPERTY_ACCESS_OPERATOR"}:PROPERTY_ACCESS_OPERATOR,"_","property_access$subexpression$1"],postprocess:([e,t,n,r,[o]])=>({type:z.property_access,object:ue(e,{trailing:t}),operator:n.text,property:ue(o,{leading:r})})},{name:"between_predicate",symbols:[ne.has("BETWEEN")?{type:"BETWEEN"}:BETWEEN,"_","andless_expression_chain","_",ne.has("AND")?{type:"AND"}:AND,"_","andless_expression"],postprocess:([e,t,n,r,o,s,i])=>({type:z.between_predicate,betweenKw:de(e),expr1:Uf(n,{leading:t,trailing:r}),andKw:de(o),expr2:[ue(i,{leading:s})]})},{name:"case_expression$ebnf$1",symbols:["expression_chain_"],postprocess:Co},{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:[ne.has("CASE")?{type:"CASE"}:CASE,"_","case_expression$ebnf$1","case_expression$ebnf$2",ne.has("END")?{type:"END"}:END],postprocess:([e,t,n,r,o])=>({type:z.case_expression,caseKw:ue(de(e),{trailing:t}),endKw:de(o),expr:n||[],clauses:r})},{name:"case_clause",symbols:[ne.has("WHEN")?{type:"WHEN"}:WHEN,"_","expression_chain_",ne.has("THEN")?{type:"THEN"}:THEN,"_","expression_chain_"],postprocess:([e,t,n,r,o,s])=>({type:z.case_when,whenKw:ue(de(e),{trailing:t}),thenKw:ue(de(r),{trailing:o}),condition:n,result:s})},{name:"case_clause",symbols:[ne.has("ELSE")?{type:"ELSE"}:ELSE,"_","expression_chain_"],postprocess:([e,t,n])=>({type:z.case_else,elseKw:ue(de(e),{trailing:t}),result:n})},{name:"comma$subexpression$1",symbols:[ne.has("COMMA")?{type:"COMMA"}:COMMA]},{name:"comma",symbols:["comma$subexpression$1"],postprocess:([[e]])=>({type:z.comma})},{name:"asterisk$subexpression$1",symbols:[ne.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK]},{name:"asterisk",symbols:["asterisk$subexpression$1"],postprocess:([[e]])=>({type:z.operator,text:e.text})},{name:"operator$subexpression$1",symbols:[ne.has("OPERATOR")?{type:"OPERATOR"}:OPERATOR]},{name:"operator",symbols:["operator$subexpression$1"],postprocess:([[e]])=>({type:z.operator,text:e.text})},{name:"identifier$subexpression$1",symbols:[ne.has("IDENTIFIER")?{type:"IDENTIFIER"}:IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[ne.has("QUOTED_IDENTIFIER")?{type:"QUOTED_IDENTIFIER"}:QUOTED_IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[ne.has("VARIABLE")?{type:"VARIABLE"}:VARIABLE]},{name:"identifier",symbols:["identifier$subexpression$1"],postprocess:([[e]])=>({type:z.identifier,quoted:e.type!=="IDENTIFIER",text:e.text})},{name:"parameter$subexpression$1",symbols:[ne.has("NAMED_PARAMETER")?{type:"NAMED_PARAMETER"}:NAMED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ne.has("QUOTED_PARAMETER")?{type:"QUOTED_PARAMETER"}:QUOTED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ne.has("NUMBERED_PARAMETER")?{type:"NUMBERED_PARAMETER"}:NUMBERED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ne.has("POSITIONAL_PARAMETER")?{type:"POSITIONAL_PARAMETER"}:POSITIONAL_PARAMETER]},{name:"parameter$subexpression$1",symbols:[ne.has("CUSTOM_PARAMETER")?{type:"CUSTOM_PARAMETER"}:CUSTOM_PARAMETER]},{name:"parameter",symbols:["parameter$subexpression$1"],postprocess:([[e]])=>({type:z.parameter,key:e.key,text:e.text})},{name:"literal$subexpression$1",symbols:[ne.has("NUMBER")?{type:"NUMBER"}:NUMBER]},{name:"literal$subexpression$1",symbols:[ne.has("STRING")?{type:"STRING"}:STRING]},{name:"literal",symbols:["literal$subexpression$1"],postprocess:([[e]])=>({type:z.literal,text:e.text})},{name:"keyword$subexpression$1",symbols:[ne.has("RESERVED_KEYWORD")?{type:"RESERVED_KEYWORD"}:RESERVED_KEYWORD]},{name:"keyword$subexpression$1",symbols:[ne.has("RESERVED_KEYWORD_PHRASE")?{type:"RESERVED_KEYWORD_PHRASE"}:RESERVED_KEYWORD_PHRASE]},{name:"keyword$subexpression$1",symbols:[ne.has("RESERVED_JOIN")?{type:"RESERVED_JOIN"}:RESERVED_JOIN]},{name:"keyword",symbols:["keyword$subexpression$1"],postprocess:([[e]])=>de(e)},{name:"data_type$subexpression$1",symbols:[ne.has("RESERVED_DATA_TYPE")?{type:"RESERVED_DATA_TYPE"}:RESERVED_DATA_TYPE]},{name:"data_type$subexpression$1",symbols:[ne.has("RESERVED_DATA_TYPE_PHRASE")?{type:"RESERVED_DATA_TYPE_PHRASE"}:RESERVED_DATA_TYPE_PHRASE]},{name:"data_type",symbols:["data_type$subexpression$1"],postprocess:([[e]])=>$i(e)},{name:"data_type",symbols:[ne.has("RESERVED_PARAMETERIZED_DATA_TYPE")?{type:"RESERVED_PARAMETERIZED_DATA_TYPE"}:RESERVED_PARAMETERIZED_DATA_TYPE,"_","parenthesis"],postprocess:([e,t,n])=>({type:z.parameterized_data_type,dataType:ue($i(e),{trailing:t}),parenthesis:n})},{name:"logic_operator$subexpression$1",symbols:[ne.has("AND")?{type:"AND"}:AND]},{name:"logic_operator$subexpression$1",symbols:[ne.has("OR")?{type:"OR"}:OR]},{name:"logic_operator$subexpression$1",symbols:[ne.has("XOR")?{type:"XOR"}:XOR]},{name:"logic_operator",symbols:["logic_operator$subexpression$1"],postprocess:([[e]])=>de(e)},{name:"other_keyword$subexpression$1",symbols:[ne.has("WHEN")?{type:"WHEN"}:WHEN]},{name:"other_keyword$subexpression$1",symbols:[ne.has("THEN")?{type:"THEN"}:THEN]},{name:"other_keyword$subexpression$1",symbols:[ne.has("ELSE")?{type:"ELSE"}:ELSE]},{name:"other_keyword$subexpression$1",symbols:[ne.has("END")?{type:"END"}:END]},{name:"other_keyword",symbols:["other_keyword$subexpression$1"],postprocess:([[e]])=>de(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:[ne.has("LINE_COMMENT")?{type:"LINE_COMMENT"}:LINE_COMMENT],postprocess:([e])=>({type:z.line_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[ne.has("BLOCK_COMMENT")?{type:"BLOCK_COMMENT"}:BLOCK_COMMENT],postprocess:([e])=>({type:z.block_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[ne.has("DISABLE_COMMENT")?{type:"DISABLE_COMMENT"}:DISABLE_COMMENT],postprocess:([e])=>({type:z.disable_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})}],ParserStart:"main"},{Parser:vf,Grammar:Bf}=pf;function Gf(e){let t={};const n=new tl(o=>[..._f(e.tokenize(o,t)),Xa(o.length)]),r=new vf(Bf.fromCompiled(bf),{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
|
|
447
|
-
${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 nl{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(;Hf(ln(this.items));)this.items.pop()}trimWhitespace(){for(;Ff(ln(this.items));)this.items.pop()}addNewline(t){if(this.items.length>0)switch(ln(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`
|
|
448
|
-
`;case V.SINGLE_INDENT:return this.indentation.getSingleIndent();default:return t}}}const Hf=e=>e===V.SPACE||e===V.SINGLE_INDENT,Ff=e=>e===V.SPACE||e===V.SINGLE_INDENT||e===V.NEWLINE;function Ki(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 zi(e){return Tu(e)||e===W.RESERVED_CLAUSE||e===W.RESERVED_SELECT||e===W.RESERVED_SET_OPERATION||e===W.RESERVED_JOIN||e===W.LIMIT}const Lo="top-level",wf="block-level";class rl{constructor(t){this.indent=t,this.indentTypes=[]}getSingleIndent(){return this.indent}getLevel(){return this.indentTypes.length}increaseTopLevel(){this.indentTypes.push(Lo)}increaseBlockLevel(){this.indentTypes.push(wf)}decreaseTopLevel(){this.indentTypes.length>0&&ln(this.indentTypes)===Lo&&this.indentTypes.pop()}decreaseBlockLevel(){for(;this.indentTypes.length>0&&this.indentTypes.pop()===Lo;);}}class Yf extends nl{constructor(t){super(new rl("")),this.expressionWidth=t,this.length=0,this.trailingSpace=!1}add(...t){if(t.forEach(n=>this.addToLength(n)),this.length>this.expressionWidth)throw new Zo;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 Zo;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 Zo extends Error{}class Ar{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 z.function_call:return this.formatFunctionCall(t);case z.parameterized_data_type:return this.formatParameterizedDataType(t);case z.array_subscript:return this.formatArraySubscript(t);case z.property_access:return this.formatPropertyAccess(t);case z.parenthesis:return this.formatParenthesis(t);case z.between_predicate:return this.formatBetweenPredicate(t);case z.case_expression:return this.formatCaseExpression(t);case z.case_when:return this.formatCaseWhen(t);case z.case_else:return this.formatCaseElse(t);case z.clause:return this.formatClause(t);case z.set_operation:return this.formatSetOperation(t);case z.limit_clause:return this.formatLimitClause(t);case z.all_columns_asterisk:return this.formatAllColumnsAsterisk(t);case z.literal:return this.formatLiteral(t);case z.identifier:return this.formatIdentifier(t);case z.parameter:return this.formatParameter(t);case z.operator:return this.formatOperator(t);case z.comma:return this.formatComma(t);case z.line_comment:return this.formatLineComment(t);case z.block_comment:return this.formatBlockComment(t);case z.disable_comment:return this.formatBlockComment(t);case z.data_type:return this.formatDataType(t);case z.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 z.data_type:n=this.showDataType(t.array);break;case z.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),_t(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):_t(this.cfg)?this.formatClauseInTabularStyle(t):this.formatClauseInIndentedStyle(t)}isOnelineClause(t){return _t(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(),_t(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===z.line_comment?this.formatLineComment(n):this.formatBlockComment(n)})}formatLineComment(t){fo(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===z.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 fo(t.text)||fo(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(ln(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 Ar({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 Ar({cfg:this.cfg,dialectCfg:this.dialectCfg,params:this.params,layout:new Yf(this.cfg.expressionWidth),inline:!0}).format(t)}catch(r){if(r instanceof Zo){this.params.setPositionalParameterIndex(n);return}else throw r}}formatKeywordNode(t){switch(t.tokenType){case W.RESERVED_JOIN:return this.formatJoin(t);case W.AND:case W.OR:case W.XOR:return this.formatLogicalOperator(t);default:return this.formatKeyword(t)}}formatJoin(t){_t(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"?_t(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 zi(t.tokenType)?Ki(this.showNonTabularKw(t),this.cfg.indentStyle):this.showNonTabularKw(t)}showNonTabularKw(t){switch(this.cfg.keywordCase){case"preserve":return er(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}showFunctionKw(t){return zi(t.tokenType)?Ki(this.showNonTabularFunctionKw(t),this.cfg.indentStyle):this.showNonTabularFunctionKw(t)}showNonTabularFunctionKw(t){switch(this.cfg.functionCase){case"preserve":return er(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 er(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}}class Vf{constructor(t,n){this.dialect=t,this.cfg=n,this.params=new ff(this.cfg.params)}format(t){const n=this.parse(t);return this.formatAst(n).trimEnd()}parse(t){return Gf(this.dialect.tokenizer).parse(t,this.cfg.paramTypes||{})}formatAst(t){return t.map(n=>this.formatStatement(n)).join(`
|
|
449
|
-
`.repeat(this.cfg.linesBetweenQueries+1))}formatStatement(t){const n=new Ar({cfg:this.cfg,dialectCfg:this.dialect.formatOptions,params:this.params,layout:new nl(new rl(Of(this.cfg)))}).format(t.children);return t.hasSemicolon&&(this.cfg.newlineBeforeSemicolon?n.add(V.NEWLINE,";"):n.add(V.NO_NEWLINE,";")),n.toString()}}class nr extends Error{}function Wf(e){const t=["multilineLists","newlineBeforeOpenParen","newlineBeforeCloseParen","aliasAs","commaPosition","tabulateAlias"];for(const n of t)if(n in e)throw new nr(`${n} config is no more supported.`);if(e.expressionWidth<=0)throw new nr(`expressionWidth config must be positive number. Received ${e.expressionWidth} instead.`);if(e.params&&!kf(e.params)&&console.warn('WARNING: All "params" option values should be strings.'),e.paramTypes&&!jf(e.paramTypes))throw new nr("Empty regex given in custom paramTypes. That would result in matching infinite amount of parameters.");return e}function kf(e){return(e instanceof Array?e:Object.values(e)).every(n=>typeof n=="string")}function jf(e){return e.custom&&Array.isArray(e.custom)?e.custom.every(t=>t.regex!==""):!0}var Xf=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 ol={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"},$f=Object.keys(ol),Kf={tabWidth:2,useTabs:!1,keywordCase:"preserve",identifierCase:"preserve",dataTypeCase:"preserve",functionCase:"preserve",indentStyle:"standard",logicalOperatorNewline:"before",expressionWidth:50,linesBetweenQueries:1,denseOperators:!1,newlineBeforeSemicolon:!1},zf=(e,t={})=>{if(typeof t.language=="string"&&!$f.includes(t.language))throw new nr(`Unsupported SQL dialect: ${t.language}`);const n=ol[t.language||"sql"];return Jf(e,Object.assign(Object.assign({},t),{dialect:tf[n]}))},Jf=(e,t)=>{var{dialect:n}=t,r=Xf(t,["dialect"]);if(typeof e!="string")throw new Error("Invalid query argument. Expected string, instead got "+typeof e);const o=Wf(Object.assign(Object.assign({},Kf),r));return new Vf(uf(n),o).format(e)},qf={sql:"SQL",markdown:"MD",dql:"DQL",param:"PARAM"},po={sql:"#388bfd",markdown:"#56d364",dql:"#e3b341",param:"#e3b341"};function Zf(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 Qf({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 E.jsxs("div",{style:{width:40,display:"flex",flexDirection:"column",alignItems:"center",paddingTop:12,flexShrink:0,gap:2},children:[E.jsx("span",{style:{fontFamily:t.fontMono,fontSize:11,color:r,lineHeight:1.4,userSelect:"none",transition:"color 0.2s"},children:e.status==="running"?E.jsxs("span",{style:{display:"inline-block",animation:"spin 0.8s linear infinite"},children:[E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:E.jsx("circle",{cx:"6",cy:"6",r:"4.5",stroke:r,strokeWidth:"1.5",strokeDasharray:"14 7"})}),E.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}):n}),o&&E.jsx("span",{style:{fontFamily:t.fontMono,fontSize:8,color:t.textMuted,lineHeight:1,userSelect:"none"},children:o})]})}function eh(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 _o(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 th(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 nh({content:e,onChange:t,t:n}){const r=eh(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 E.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px",padding:"5px 10px",borderBottom:`1px solid ${n.cellBorder}`,background:`${n.tableHeaderBg}40`},children:[E.jsxs("div",{style:i,children:[E.jsx("span",{style:s,children:"domain"}),E.jsx("input",{style:{...o,width:80},value:r.domain,placeholder:"e.g. finance",onChange:a=>t(_o(e,"domain",a.target.value))})]}),E.jsxs("div",{style:i,children:[E.jsx("span",{style:s,children:"owner"}),E.jsx("input",{style:{...o,width:90},value:r.owner,placeholder:"e.g. data-team",onChange:a=>t(_o(e,"owner",a.target.value))})]}),E.jsxs("div",{style:i,children:[E.jsx("span",{style:s,children:"tags"}),E.jsx("input",{style:{...o,width:110},value:r.tags.join(", "),placeholder:"revenue, kpi",onChange:a=>{const T=a.target.value.split(",").map(l=>l.trim()).filter(Boolean);t(th(e,T))}})]}),E.jsxs("div",{style:{...i,flex:1},children:[E.jsx("span",{style:s,children:"description"}),E.jsx("input",{style:{...o,flex:1,minWidth:120},value:r.description,placeholder:"What this block measures",onChange:a=>t(_o(e,"description",a.target.value))})]})]})}function rh({cell:e,index:t}){var w;const{state:n,dispatch:r}=ae(),o=re[n.themeMode],{executeCell:s,executeDependents:i,cancelCell:a}=xr(),[T,l]=h.useState(!1),[R,c]=h.useState(!1),[S,A]=h.useState(e.name??""),[d,N]=h.useState(!0),[I,u]=h.useState("table"),[f,O]=h.useState(null),[C,m]=h.useState(!1),[L,D]=h.useState(!1),M=Zf(e,o),x=e.type!=="markdown"&&e.type!=="param",B=h.useMemo(()=>n.schemaTables.length>0?Object.fromEntries(n.schemaTables.map(H=>[H.name,H.columns.map(Y=>Y.name)])):void 0,[n.schemaTables]);if(e.type==="param")return E.jsxs("div",{onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{display:"flex",gap:0,marginBottom:2},children:[E.jsx("div",{style:{width:40,flexShrink:0}}),E.jsx("div",{style:{flex:1,minWidth:0},children:E.jsx(Ld,{cell:e,themeMode:n.themeMode,onApplyParam:i})})]});h.useEffect(()=>{if(e.status==="success"&&e.result){const H=qo(e.result,e.chartConfig);O(H!=="table"?H:null),u(H!=="table"?"chart":"table")}},[e.status,e.result,e.chartConfig]);const g=h.useCallback(()=>{x&&s(e.id)},[e.id,s,x]),p=h.useCallback(H=>{r({type:"UPDATE_CELL",id:e.id,updates:{content:H}})},[e.id,r]),F=h.useCallback(()=>{if(e.content.trim())try{const H=zf(e.content,{language:"sql",tabWidth:2,keywordCase:"upper",linesBetweenQueries:1});r({type:"UPDATE_CELL",id:e.id,updates:{content:H}})}catch{}},[e.content,e.id,r]),_=h.useCallback(()=>{F(),setTimeout(()=>s(e.id),80)},[F,s,e.id]),U=()=>{r({type:"DELETE_CELL",id:e.id})},P=()=>{r({type:"MOVE_CELL",id:e.id,direction:"up"})},v=()=>{r({type:"MOVE_CELL",id:e.id,direction:"down"})},b=()=>{c(!1),r({type:"UPDATE_CELL",id:e.id,updates:{name:S.trim()||void 0}})},y=(e.result||e.error)&&e.type!=="markdown";return e.result&&qo(e.result,e.chartConfig),E.jsxs("div",{onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{display:"flex",gap:0,marginBottom:2},children:[E.jsx(Qf,{cell:e,t:o}),E.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${T||e.status!=="idle"?M:o.cellBorder}`,borderLeft:`2px solid ${M}`,background:o.cellBg,overflow:"hidden",transition:"border-color 0.2s"},children:[E.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:[E.jsx("span",{title:e.type==="dql"?"DQL cell — write a governed block (type, owner, description, tests) or use @metric()/@dim() refs":e.type==="sql"?"SQL cell — write raw SQL, reference other cells with {{name}}":void 0,style:{fontSize:10,fontWeight:700,fontFamily:o.fontMono,letterSpacing:"0.08em",color:po[e.type]??o.accent,background:`${po[e.type]??o.accent}18`,border:`1px solid ${po[e.type]??o.accent}40`,borderRadius:4,padding:"1px 6px",flexShrink:0,textTransform:"uppercase"},children:qf[e.type]}),T&&(e.type==="sql"||e.type==="dql")&&E.jsx(_d,{themeMode:n.themeMode,cellType:e.type,onInsert:H=>p(H)}),T&&(e.type==="sql"||e.type==="dql")&&E.jsx("button",{title:"Format SQL (clean up whitespace & keywords)",onClick:F,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:H=>{H.currentTarget.style.color=o.textSecondary,H.currentTarget.style.borderColor=o.accent},onMouseLeave:H=>{H.currentTarget.style.color=o.textMuted,H.currentTarget.style.borderColor=o.btnBorder},children:"Format"}),R?E.jsx("input",{autoFocus:!0,value:S,onChange:H=>A(H.target.value),onBlur:b,onKeyDown:H=>{H.key==="Enter"&&b(),H.key==="Escape"&&c(!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&&E.jsx("span",{onClick:()=>{A(e.name??""),c(!0)},title:"Click to rename",style:{color:o.textSecondary,fontSize:12,fontFamily:o.fontMono,cursor:"text",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:200},children:e.name}),E.jsx("div",{style:{flex:1}}),T&&E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[!e.name&&!R&&E.jsx(mt,{title:"Name this cell",onClick:()=>{A(""),c(!0)},t:o,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M11.013 1.427a1.75 1.75 0 0 1 2.474 0l1.086 1.086a1.75 1.75 0 0 1 0 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 0 1-.927-.928l.929-3.25c.081-.286.235-.547.445-.758l8.61-8.61Zm.176 4.823L9.75 4.81l-6.286 6.287a.253.253 0 0 0-.064.108l-.558 1.953 1.953-.558a.253.253 0 0 0 .108-.064Zm1.238-3.763a.25.25 0 0 0-.354 0L10.811 3.75l1.439 1.44 1.263-1.263a.25.25 0 0 0 0-.354Z"})})}),x&&e.status==="running"?E.jsx(mt,{title:"Cancel execution",onClick:()=>a(e.id),t:o,danger:!0,children:E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:E.jsx("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1"})})}):x?E.jsx(mt,{title:"Run cell (Shift+Enter)",onClick:g,t:o,accent:!0,children:E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:E.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})})}):null,E.jsx(mt,{title:"Move up",onClick:P,t:o,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M3.47 7.78a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1-1.06 1.06L8.75 4.81v7.44a.75.75 0 0 1-1.5 0V4.81L4.53 7.78a.75.75 0 0 1-1.06 0Z"})})}),E.jsx(mt,{title:"Move down",onClick:v,t:o,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M12.53 8.22a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L2.97 9.28a.75.75 0 0 1 1.06-1.06l2.72 2.97V3.75a.75.75 0 0 1 1.5 0v7.44l2.72-2.97a.75.75 0 0 1 1.06 0Z"})})}),E.jsx(mt,{title:"Delete cell",onClick:U,t:o,danger:!0,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M11 1.75V3h2.25a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1 0-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75ZM4.496 6.675l.66 6.6a.25.25 0 0 0 .249.225h5.19a.25.25 0 0 0 .249-.225l.66-6.6a.75.75 0 0 1 1.492.149l-.66 6.6A1.748 1.748 0 0 1 10.595 15h-5.19a1.75 1.75 0 0 1-1.741-1.575l-.66-6.6a.75.75 0 1 1 1.492-.15ZM6.5 1.75V3h3V1.75a.25.25 0 0 0-.25-.25h-2.5a.25.25 0 0 0-.25.25Z"})})})]})]}),e.type==="dql"&&E.jsx(nh,{content:e.content,onChange:p,t:o}),e.type==="markdown"?E.jsx(Cd,{value:e.content,onChange:p,themeMode:n.themeMode}):E.jsx(Fa,{value:e.content,onChange:p,onRun:g,themeMode:n.themeMode,schema:B,errorMessage:e.status==="error"?e.error:void 0}),y&&E.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[E.jsxs("div",{style:{height:28,display:"flex",alignItems:"center",padding:"0 12px",gap:10,borderBottom:e.result&&d?`1px solid ${o.cellBorder}`:"none",background:`${o.tableHeaderBg}60`},children:[e.result&&E.jsxs("span",{style:{fontSize:11,fontFamily:o.font,color:o.textMuted},children:[(e.result.rowCount??e.result.rows.length).toLocaleString()," rows",e.result.executionTime!==void 0&&E.jsxs(E.Fragment,{children:[" · ",e.result.executionTime<1e3?`${e.result.executionTime}ms`:`${(e.result.executionTime/1e3).toFixed(2)}s`]})]}),e.error&&E.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.error},children:"Error"}),E.jsx("div",{style:{flex:1}}),e.result&&d&&E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:3,position:"relative"},children:[E.jsx("button",{onClick:()=>{u("table"),m(!1)},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${I==="table"?o.accent:o.btnBorder}`,background:I==="table"?`${o.accent}20`:"transparent",color:I==="table"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s"},children:"Table"}),E.jsxs("div",{style:{position:"relative"},children:[E.jsxs("button",{onClick:()=>{I==="chart"&&C?m(!1):(u("chart"),m(H=>!H))},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${I==="chart"?o.accent:o.btnBorder}`,background:I==="chart"?`${o.accent}20`:"transparent",color:I==="chart"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s",display:"flex",alignItems:"center",gap:3},children:[f?((w=Va.find(H=>H.value===f))==null?void 0:w.label)??"Chart":"Chart",E.jsx("svg",{width:"6",height:"6",viewBox:"0 0 8 8",fill:"currentColor",children:E.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),C&&E.jsx(oh,{selected:f,onSelect:H=>{O(H),u("chart"),m(!1)},onClose:()=>m(!1),t:o})]}),I==="chart"&&E.jsx("button",{onClick:()=>D(H=>!H),title:"Chart configuration",style:{padding:"1px 5px",fontSize:11,borderRadius:3,cursor:"pointer",border:`1px solid ${L?o.accent:o.btnBorder}`,background:L?`${o.accent}20`:"transparent",color:L?o.accent:o.textMuted,transition:"all 0.15s",display:"flex",alignItems:"center"},children:E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.103-.303c.644-.176 1.392.021 1.82.63.27.386.506.798.704 1.23.315.698.043 1.44-.476 1.89l-.815.806a.338.338 0 0 0-.079.262c.02.267.02.538 0 .805a.338.338 0 0 0 .079.262l.815.806c.52.45.79 1.192.476 1.89a7.22 7.22 0 0 1-.704 1.23c-.428.609-1.176.806-1.82.63l-1.103-.303c-.066-.019-.176-.011-.299.071a5.09 5.09 0 0 1-.668.386c-.133.066-.194.158-.212.224l-.288 1.107c-.169.645-.715 1.196-1.458 1.26a8.006 8.006 0 0 1-1.402 0c-.743-.064-1.29-.614-1.458-1.26l-.289-1.106c-.018-.066-.079-.158-.212-.224a5.09 5.09 0 0 1-.668-.387c-.123-.082-.233-.09-.299-.071l-1.103.303c-.644.176-1.392-.021-1.82-.63a7.12 7.12 0 0 1-.704-1.23c-.315-.698-.043-1.44.476-1.89l.815-.806a.338.338 0 0 0 .079-.262 6.08 6.08 0 0 1 0-.805.338.338 0 0 0-.079-.262l-.815-.806c-.52-.45-.79-1.192-.476-1.89a7.22 7.22 0 0 1 .704-1.23c.428-.609 1.176-.806 1.82-.63l1.103.303c.066.019.176.011.299-.071.214-.143.437-.272.668-.386.133-.066.194-.158.212-.224L6.54 1.29C6.71.645 7.256.095 7.999.031 8.236.01 8.474 0 8.713 0H8ZM8 5a3 3 0 1 0 0 6 3 3 0 0 0 0-6Z"})})})]}),E.jsxs("button",{onClick:()=>N(H=>!H),style:{background:"transparent",border:"none",cursor:"pointer",color:o.textMuted,fontSize:11,fontFamily:o.font,padding:"2px 4px",display:"flex",alignItems:"center",gap:4},children:[E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:d?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.15s"},children:E.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})}),d?"Hide":"Show"]})]}),d&&E.jsxs(E.Fragment,{children:[e.error&&E.jsx(zd,{message:e.error,themeMode:n.themeMode,onFix:x?_:void 0,schemaTables:n.schemaTables}),e.result&&!e.error&&(I==="chart"&&f?E.jsxs(E.Fragment,{children:[ja(f,e.result,n.themeMode,e.chartConfig),L&&E.jsx(sh,{columns:e.result.columns,chartConfig:e.chartConfig,onChange:H=>r({type:"UPDATE_CELL",id:e.id,updates:{chartConfig:{...e.chartConfig,...H}}}),t:o})]}):E.jsx(Os,{result:e.result,themeMode:n.themeMode}))]})]}),x&&E.jsx(tu,{cellContent:e.content,cellType:e.type,cellName:e.name,themeMode:n.themeMode,t:o})]})]})}function mt({title:e,onClick:t,children:n,t:r,accent:o,danger:s}){const[i,a]=h.useState(!1);return E.jsx("button",{title:e,onClick:t,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!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 oh({selected:e,onSelect:t,onClose:n,t:r}){const[o,s]=h.useState(null);return Bt.useEffect(()=>{const i=a=>{setTimeout(()=>n(),0)};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[n]),E.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:Va.map(({value:i,label:a})=>E.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:a},i))})}function sh({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 E.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px 16px",padding:"8px 12px",borderTop:`1px solid ${r.cellBorder}`,background:`${r.tableHeaderBg}40`},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[E.jsx("span",{style:s,children:"X axis"}),E.jsxs("select",{style:o,value:(t==null?void 0:t.x)??"",onChange:i=>n({x:i.target.value||void 0}),children:[E.jsx("option",{value:"",children:"Auto"}),e.map(i=>E.jsx("option",{value:i,children:i},i))]})]}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[E.jsx("span",{style:s,children:"Y axis"}),E.jsxs("select",{style:o,value:(t==null?void 0:t.y)??"",onChange:i=>n({y:i.target.value||void 0}),children:[E.jsx("option",{value:"",children:"Auto"}),e.map(i=>E.jsx("option",{value:i,children:i},i))]})]}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[E.jsx("span",{style:s,children:"Color"}),E.jsxs("select",{style:o,value:(t==null?void 0:t.color)??"",onChange:i=>n({color:i.target.value||void 0}),children:[E.jsx("option",{value:"",children:"None"}),e.map(i=>E.jsx("option",{value:i,children:i},i))]})]}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:150},children:[E.jsx("span",{style:s,children:"Title"}),E.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 ih=[{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 mo({afterId:e}){const{state:t,dispatch:n}=ae(),r=re[t.themeMode],[o,s]=h.useState(!1),[i,a]=h.useState(!1),[T,l]=h.useState(!1),[R,c]=h.useState(""),S=h.useRef(null),A=h.useRef(null);h.useEffect(()=>{if(!i)return;function f(O){S.current&&!S.current.contains(O.target)&&a(!1)}return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[i]);const d=f=>{const O=Le(f);n({type:"ADD_CELL",cell:O,afterId:e}),a(!1),l(!1)},N=t.files.filter(f=>f.type==="block"),I=R?N.filter(f=>f.name.toLowerCase().includes(R.toLowerCase())):N,u=f=>{const O=Le("sql",`-- Block: ${f.path}
|
|
450
|
-
@include('${f.path}')`);n({type:"ADD_CELL",cell:O,afterId:e}),a(!1),l(!1),c("")};return E.jsxs("div",{ref:S,onMouseEnter:()=>s(!0),onMouseLeave:()=>{s(!1)},style:{position:"relative",height:28,display:"flex",alignItems:"center",justifyContent:"center",cursor:"default"},children:[E.jsx("div",{style:{position:"absolute",left:0,right:0,height:1,background:o||i?r.cellBorderActive:"transparent",transition:"background 0.15s"}}),(o||i)&&E.jsxs("button",{onClick:()=>a(f=>!f),style:{position:"relative",zIndex:2,height:22,padding:"0 10px",borderRadius:11,border:`1px solid ${r.cellBorderActive}`,background:`${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:[E.jsx("span",{style:{fontSize:14,lineHeight:1,marginTop:-1},children:"+"}),"Add cell"]}),i&&E.jsxs("div",{style:{position:"absolute",top:26,left:"50%",transform:"translateX(-50%)",zIndex:100,background: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:[E.jsxs("div",{style:{display:"flex",gap:4},children:[ih.map(({type:f,label:O,color:C})=>E.jsx(Ji,{label:O,color:C,onClick:()=>d(f),t:r},f)),E.jsx(Ji,{label:"Block",color:"#d2a8ff",onClick:()=>{l(f=>!f),setTimeout(()=>{var f;return(f=A.current)==null?void 0:f.focus()},50)},t:r})]}),T&&E.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"4px 2px"},children:[E.jsx("input",{ref:A,value:R,onChange:f=>c(f.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"}}),E.jsx("div",{style:{maxHeight:160,overflow:"auto",display:"flex",flexDirection:"column",gap:2},children:I.length===0?E.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,padding:"4px 8px",fontStyle:"italic"},children:N.length===0?"No blocks yet":"No matches"}):I.map(f=>E.jsx(Eh,{file:f,onClick:()=>u(f),t:r},f.path))})]})]})]})}function Ji({label:e,color:t,onClick:n,t:r}){const[o,s]=h.useState(!1);return E.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 Eh({file:e,onClick:t,t:n}){const[r,o]=h.useState(!1);return E.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:[E.jsx("span",{style:{fontWeight:500},children:e.name.replace(/\.dql$/,"")}),E.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.fontMono},children:e.path})]})}function ah({registerCellRef:e}){const{state:t,dispatch:n}=ae(),{executeCell:r}=xr(),o=re[t.themeMode],[s,i]=h.useState(null),a=h.useRef(0),[T,l]=h.useState(null),[R,c]=h.useState(null);h.useCallback(I=>{i(I)},[]),h.useEffect(()=>{function I(u){var m;if(!s)return;const f=u.target;if(f.tagName==="TEXTAREA"||f.tagName==="INPUT"||f.isContentEditable||f.closest(".cm-editor")){i(null);return}const O=t.cells,C=O.findIndex(L=>L.id===s);if(C!==-1)switch(u.key){case"a":{u.preventDefault();const L=Le("sql");if(C===0)n({type:"ADD_CELL",cell:L,afterId:O[0].id}),n({type:"MOVE_CELL",id:L.id,direction:"up"});else{const D=O[C-1].id;n({type:"ADD_CELL",cell:L,afterId:D})}i(L.id);break}case"b":{u.preventDefault();const L=Le("sql");n({type:"ADD_CELL",cell:L,afterId:s}),i(L.id);break}case"d":{u.preventDefault();const L=Date.now();if(L-a.current<=500){if(n({type:"DELETE_CELL",id:s}),O.length>1){const D=C>0?C-1:1;i(((m=O[D])==null?void 0:m.id)??null)}else i(null);a.current=0}else a.current=L;break}case"Enter":{if(u.shiftKey){u.preventDefault();const L=O[C];L&&L.type!=="markdown"&&r(L.id)}break}}}return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[s,t.cells,n,r]),h.useEffect(()=>{function I(u){u.target.closest("[data-cell-id]")||i(null)}return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[]);const S=h.useCallback((I,u)=>{l(u),I.dataTransfer.effectAllowed="move",I.dataTransfer.setData("text/plain",String(u));const f=I.currentTarget;setTimeout(()=>{f.style.opacity="0.4"},0)},[]),A=h.useCallback(I=>{I.currentTarget.style.opacity="1",l(null),c(null)},[]),d=h.useCallback((I,u)=>{I.preventDefault(),I.dataTransfer.dropEffect="move",c(u)},[]),N=h.useCallback((I,u)=>{I.preventDefault(),T!==null&&T!==u&&n({type:"REORDER_CELL",fromIndex:T,toIndex:u}),l(null),c(null)},[T,n]);return t.cells.length===0?E.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[E.jsx(mo,{}),E.jsx(lh,{t:o})]}):E.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[E.jsx(mo,{afterId:void 0}),t.cells.map((I,u)=>E.jsxs(Bt.Fragment,{children:[E.jsxs("div",{ref:f=>e(I.id,f),"data-cell-id":I.id,draggable:!0,onDragStart:f=>S(f,u),onDragEnd:A,onDragOver:f=>d(f,u),onDrop:f=>N(f,u),onClick:f=>{const O=f.target;!O.closest(".cm-editor")&&!O.closest("textarea")&&!O.closest("input")&&i(I.id)},style:{outline:s===I.id?`2px solid ${o.accent}40`:"none",outlineOffset:2,borderRadius:10,transition:"outline 0.1s, transform 0.15s",position:"relative",...R===u&&T!==null&&T!==u?{borderTop:`2px solid ${o.accent}`}:{}},children:[E.jsx("div",{style:{position:"absolute",left:-20,top:8,width:16,height:24,display:"flex",alignItems:"center",justifyContent:"center",cursor:"grab",color:o.textMuted,opacity:0,transition:"opacity 0.15s",zIndex:5},className:"drag-handle",children:E.jsxs("svg",{width:"8",height:"14",viewBox:"0 0 8 14",fill:"currentColor",children:[E.jsx("circle",{cx:"2",cy:"2",r:"1.2"}),E.jsx("circle",{cx:"6",cy:"2",r:"1.2"}),E.jsx("circle",{cx:"2",cy:"7",r:"1.2"}),E.jsx("circle",{cx:"6",cy:"7",r:"1.2"}),E.jsx("circle",{cx:"2",cy:"12",r:"1.2"}),E.jsx("circle",{cx:"6",cy:"12",r:"1.2"})]})}),E.jsx(rh,{cell:I,index:u})]}),E.jsx(mo,{afterId:I.id})]},I.id)),E.jsx("style",{children:`
|
|
451
|
-
[data-cell-id]:hover .drag-handle { opacity: 0.5 !important; }
|
|
452
|
-
[data-cell-id]:hover .drag-handle:hover { opacity: 1 !important; }
|
|
453
|
-
`})]})}function lh({t:e}){return E.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"48px 0",gap:12,color:e.textMuted},children:[E.jsx("svg",{width:"40",height:"40",viewBox:"0 0 16 16",fill:"currentColor",style:{opacity:.3},children:E.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"})}),E.jsx("span",{style:{fontSize:13,fontFamily:e.font},children:"Empty notebook. Click + to add your first cell."})]})}function Th(){const{state:e}=ae(),t=re[e.themeMode],n=e.cells.filter(r=>r.type==="markdown"||r.result&&r.status!=="running"||r.error);return E.jsx("div",{style:{flex:1,overflow:"auto",background:t.appBg,padding:"32px 24px 48px"},children:E.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",display:"flex",flexDirection:"column",gap:24},children:[E.jsxs("div",{style:{textAlign:"center",marginBottom:8},children:[E.jsx("h1",{style:{fontSize:28,fontWeight:700,color:t.textPrimary,fontFamily:t.font,letterSpacing:"-0.3px",margin:0},children:e.notebookTitle||"Untitled"}),E.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?E.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=>E.jsx(ch,{cell:r},r.id))]})})}function ch({cell:e}){const{state:t}=ae(),n=re[t.themeMode];if(e.type==="markdown")return E.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:Sh(e.content,n)}});if(e.error)return E.jsxs("div",{style:{background:n.cellBg,borderRadius:10,border:`1px solid ${n.error}40`,padding:"16px 24px"},children:[e.name&&E.jsx(Rh,{name:e.name,t:n}),E.jsx("div",{style:{color:n.error,fontSize:12,fontFamily:n.fontMono,whiteSpace:"pre-wrap"},children:e.error})]});if(!e.result)return null;const r=qo(e.result,e.chartConfig),o=r!=="table";return E.jsxs("div",{style:{background:n.cellBg,borderRadius:10,border:`1px solid ${n.cellBorder}`,overflow:"hidden"},children:[E.jsxs("div",{style:{padding:"10px 20px",borderBottom:`1px solid ${n.cellBorder}`,display:"flex",alignItems:"center",gap:8},children:[e.name?E.jsx("span",{style:{fontSize:13,fontWeight:600,color:n.textPrimary,fontFamily:n.font,flex:1},children:e.name}):E.jsx("span",{style:{flex:1}}),E.jsxs("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.fontMono},children:[e.result.rowCount??e.result.rows.length," rows",e.result.executionTime!=null&&E.jsxs(E.Fragment,{children:[" · ",e.result.executionTime<1e3?`${e.result.executionTime}ms`:`${(e.result.executionTime/1e3).toFixed(1)}s`]})]})]}),E.jsx("div",{style:{padding:o?"16px 20px":0},children:o?ja(r,e.result,t.themeMode,e.chartConfig):E.jsx(Os,{result:e.result,themeMode:t.themeMode})})]})}function Rh({name:e,t}){return E.jsx("div",{style:{fontSize:13,fontWeight:600,color:t.textPrimary,fontFamily:t.font,marginBottom:8},children:e})}function Sh(e,t){const n=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");return e.split(`
|
|
454
|
-
`).map(r=>{const o=r.trim(),s=o.match(/^(#{1,6})\s+(.+)$/);if(s){const a=s[1].length;return`<div style="font-size:${["28px","22px","18px","16px","14px","13px"][a-1]};font-weight:${a<=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 Ah({onOpenFile:e,registerCellRef:t}){const{state:n}=ae(),r=re[n.themeMode];return n.activeFile?n.dashboardMode?E.jsx(Th,{}):E.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",background:r.appBg},children:[E.jsx(dh,{t:r}),E.jsx("div",{style:{flex:1,overflow:"auto",padding:"24px 0 40px"},children:E.jsx(ah,{registerCellRef:t})})]}):E.jsx(WA,{onOpenFile:e})}function dh({t:e}){const{state:t}=ae(),n=t.cells.length;return E.jsxs("div",{style:{height:32,flexShrink:0,borderBottom:`1px solid ${e.headerBorder}`,background:e.cellBg,display:"flex",alignItems:"center",padding:"0 16px",gap:12},children:[E.jsx(uh,{t:e}),E.jsx("div",{style:{flex:1}}),E.jsxs("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.font,display:"flex",alignItems:"center",gap:12},children:[E.jsxs("span",{children:[n," ",n===1?"cell":"cells"]}),t.notebookDirty&&E.jsx("span",{style:{color:e.warning},children:"● unsaved"})]})]})}function uh({t:e}){const{state:t}=ae();if(!t.activeFile)return null;const n=t.activeFile.path.split("/").filter(Boolean);return E.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,fontSize:12,fontFamily:e.fontMono,color:e.textMuted,overflow:"hidden"},children:n.map((r,o)=>E.jsxs(Bt.Fragment,{children:[o>0&&E.jsx("span",{style:{color:e.textMuted,opacity:.5},children:"/"}),E.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 qi={blank:"Blank",revenue:"Revenue Analysis",pipeline:"Pipeline Health"},Ih={blank:"Start with an empty notebook.",revenue:"Pre-built queries for revenue metrics and trends.",pipeline:"Templates for data pipeline health monitoring."};function Zi(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function Nh(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function Oh(e){switch(e){case"revenue":return[Le("markdown",`# Revenue Analysis
|
|
455
|
-
|
|
456
|
-
This notebook analyzes revenue metrics and trends over time.`),{...Le("sql",`SELECT
|
|
457
|
-
DATE_TRUNC('month', order_date) AS month,
|
|
458
|
-
SUM(amount) AS revenue
|
|
459
|
-
FROM orders
|
|
460
|
-
GROUP BY 1
|
|
461
|
-
ORDER BY 1`),name:"monthly_revenue"},{...Le("sql",`SELECT
|
|
462
|
-
product_category,
|
|
463
|
-
SUM(amount) AS total_revenue,
|
|
464
|
-
COUNT(*) AS orders
|
|
465
|
-
FROM orders
|
|
466
|
-
GROUP BY 1
|
|
467
|
-
ORDER BY 2 DESC`),name:"revenue_by_category"}];case"pipeline":return[Le("markdown",`# Pipeline Health
|
|
468
|
-
|
|
469
|
-
Monitor data pipeline performance, SLA compliance, and error rates.`),{...Le("sql",`SELECT
|
|
470
|
-
pipeline_name,
|
|
471
|
-
COUNT(*) AS runs,
|
|
472
|
-
AVG(duration_seconds) AS avg_duration,
|
|
473
|
-
SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failures
|
|
474
|
-
FROM pipeline_runs
|
|
475
|
-
GROUP BY 1
|
|
476
|
-
ORDER BY 4 DESC`),name:"pipeline_summary"},{...Le("sql",`SELECT
|
|
477
|
-
*
|
|
478
|
-
FROM pipeline_runs
|
|
479
|
-
WHERE status = 'failed'
|
|
480
|
-
AND run_date >= CURRENT_DATE - INTERVAL '7 days'
|
|
481
|
-
ORDER BY run_date DESC`),name:"recent_failures"}];default:return[Le("sql")]}}function fh({onFileOpened:e}){const{state:t,dispatch:n}=ae(),r=re[t.themeMode],[o,s]=h.useState(""),[i,a]=h.useState("blank"),[T,l]=h.useState(null),[R,c]=h.useState(!1),S=h.useRef(null);h.useEffect(()=>{var N;(N=S.current)==null||N.focus()},[]),h.useEffect(()=>{const N=I=>{I.key==="Escape"&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[n]);const A=async()=>{const N=Nh(o);if(N){l(N);return}c(!0),l(null);const I=Zi(o),u=Oh(i);try{const f=await le.createNotebook(I,i),O={name:`${I}.dqlnb`,path:f.path,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:O}),n({type:"OPEN_FILE",file:O,cells:u,title:o.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(O)}catch{const f=`notebooks/${I}.dqlnb`,O={name:`${I}.dqlnb`,path:f,type:"notebook",folder:"notebooks",isNew:!0};n({type:"FILE_ADDED",file:O}),n({type:"OPEN_FILE",file:O,cells:u,title:o.trim()}),n({type:"CLOSE_NEW_NOTEBOOK_MODAL"}),e(O)}finally{c(!1)}},d=N=>{N.target===N.currentTarget&&n({type:"CLOSE_NEW_NOTEBOOK_MODAL"})};return E.jsx("div",{onClick:d,style:{position:"fixed",inset:0,background:r.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:E.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:[E.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[E.jsx("h2",{style:{fontSize:16,fontWeight:600,color:r.textPrimary,fontFamily:r.font,margin:0},children:"New Notebook"}),E.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:"×"})]}),E.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:20},children:[E.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[E.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Name"}),E.jsx("input",{ref:S,value:o,onChange:N=>{s(N.target.value),l(null)},onKeyDown:N=>{N.key==="Enter"&&A()},placeholder:"my-analysis",style:{background:r.inputBg,border:`1px solid ${T?r.error:r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:13,fontFamily:r.font,padding:"8px 12px",outline:"none",transition:"border-color 0.15s"}}),T&&E.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:T}),o&&!T&&E.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["File: ",Zi(o),".dqlnb"]})]}),E.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[E.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Template"}),E.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:Object.keys(qi).map(N=>E.jsx(hh,{value:N,selected:i===N,onSelect:()=>a(N),label:qi[N],description:Ih[N],t:r},N))})]})]}),E.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${r.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[E.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"}),E.jsx("button",{onClick:A,disabled:R||!o.trim(),style:{background:r.accent,border:`1px solid ${r.accent}`,borderRadius:6,color:"#ffffff",cursor:R||!o.trim()?"not-allowed":"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 20px",opacity:R||!o.trim()?.6:1,display:"flex",alignItems:"center",gap:6},children:R?"Creating…":"Create Notebook"})]})]})})}function hh({value:e,selected:t,onSelect:n,label:r,description:o,t:s}){const[i,a]=h.useState(!1);return E.jsxs("div",{onClick:n,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!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:[E.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&&E.jsx("div",{style:{width:8,height:8,borderRadius:4,background:s.accent}})}),E.jsxs("div",{children:[E.jsx("div",{style:{fontSize:13,fontWeight:500,color:s.textPrimary,fontFamily:s.font,marginBottom:2},children:r}),E.jsx("div",{style:{fontSize:12,color:s.textSecondary,fontFamily:s.font},children:o})]})]})}function Qi(e){return e.toLowerCase().replace(/[^a-z0-9\-_\s]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,64)}function Ch(e){return e.trim()?/^[a-zA-Z0-9\-_ ]+$/.test(e)?null:"Only letters, numbers, hyphens, underscores, and spaces allowed.":"Name is required."}function Lh({onFileOpened:e}){const{state:t,dispatch:n}=ae(),r=re[t.themeMode],[o,s]=h.useState(""),[i,a]=h.useState(null),[T,l]=h.useState(!1),R=h.useRef(null);h.useEffect(()=>{var A;(A=R.current)==null||A.focus()},[]),h.useEffect(()=>{const A=d=>{d.key==="Escape"&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[n]);const c=async()=>{var N;const A=Ch(o);if(A){a(A);return}l(!0),a(null);const d=Qi(o);try{const I=await le.createBlock(o),u={name:`${d}.dql`,path:I.path,type:"block",folder:"blocks",isNew:!0};n({type:"FILE_ADDED",file:u}),n({type:"OPEN_FILE",file:u,cells:[Le("sql",I.content)],title:o.trim()}),n({type:"CLOSE_NEW_BLOCK_MODAL"}),e(u)}catch(I){(N=I.message)!=null&&N.includes("already exists")?a("A block with this name already exists."):a(I.message??"Failed to create block.")}finally{l(!1)}},S=A=>{A.target===A.currentTarget&&n({type:"CLOSE_NEW_BLOCK_MODAL"})};return E.jsx("div",{onClick:S,style:{position:"fixed",inset:0,background:r.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(4px)"},children:E.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:[E.jsxs("div",{style:{padding:"20px 24px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[E.jsx("h2",{style:{fontSize:16,fontWeight:600,color:r.textPrimary,fontFamily:r.font,margin:0},children:"New Block"}),E.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:"×"})]}),E.jsxs("div",{style:{padding:"20px 24px 24px",display:"flex",flexDirection:"column",gap:16},children:[E.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[E.jsx("label",{style:{fontSize:12,fontWeight:500,color:r.textSecondary,fontFamily:r.font},children:"Block Name"}),E.jsx("input",{ref:R,value:o,onChange:A=>{s(A.target.value),a(null)},onKeyDown:A=>{A.key==="Enter"&&c()},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&&E.jsx("span",{style:{fontSize:11,color:r.error,fontFamily:r.font},children:i}),o&&!i&&E.jsxs("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono},children:["blocks/",Qi(o),".dql"]})]}),E.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 ",E.jsx("code",{style:{fontFamily:r.fontMono,fontSize:11},children:"blocks/"})," folder. They can be referenced from notebooks and other blocks."]})]}),E.jsxs("div",{style:{padding:"14px 24px",borderTop:`1px solid ${r.cellBorder}`,display:"flex",justifyContent:"flex-end",gap:10},children:[E.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"}),E.jsx("button",{onClick:c,disabled:T||!o.trim(),style:{background:r.accent,border:`1px solid ${r.accent}`,borderRadius:6,color:"#ffffff",cursor:T||!o.trim()?"not-allowed":"pointer",fontSize:13,fontFamily:r.font,fontWeight:500,padding:"7px 20px",opacity:T||!o.trim()?.6:1,display:"flex",alignItems:"center",gap:6},children:T?"Creating...":"Create Block"})]})]})})}function Se(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=Se(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var ph={value:()=>{}};function Ur(){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 rr(n)}function rr(e){this._=e}function _h(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}})}rr.prototype=Ur.prototype={constructor:rr,on:function(e,t){var n=this._,r=_h(e+"",n),o,s=-1,i=r.length;if(arguments.length<2){for(;++s<i;)if((o=(e=r[s]).type)&&(o=mh(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]=eE(n[o],e.name,t);else if(t==null)for(o in n)n[o]=eE(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 rr(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 mh(e,t){for(var n=0,r=e.length,o;n<r;++n)if((o=e[n]).name===t)return o.value}function eE(e,t,n){for(var r=0,o=e.length;r<o;++r)if(e[r].name===t){e[r]=ph,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Qo="http://www.w3.org/1999/xhtml";const tE={svg:"http://www.w3.org/2000/svg",xhtml:Qo,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function br(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),tE.hasOwnProperty(t)?{space:tE[t],local:e}:e}function Dh(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Qo&&t.documentElement.namespaceURI===Qo?t.createElement(e):t.createElementNS(n,e)}}function gh(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function sl(e){var t=br(e);return(t.local?gh:Dh)(t)}function Mh(){}function Cs(e){return e==null?Mh:function(){return this.querySelector(e)}}function xh(e){typeof e!="function"&&(e=Cs(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,a=r[o]=new Array(i),T,l,R=0;R<i;++R)(T=s[R])&&(l=e.call(T,T.__data__,R,s))&&("__data__"in T&&(l.__data__=T.__data__),a[R]=l);return new ge(r,this._parents)}function Ph(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function yh(){return[]}function il(e){return e==null?yh:function(){return this.querySelectorAll(e)}}function Uh(e){return function(){return Ph(e.apply(this,arguments))}}function bh(e){typeof e=="function"?e=Uh(e):e=il(e);for(var t=this._groups,n=t.length,r=[],o=[],s=0;s<n;++s)for(var i=t[s],a=i.length,T,l=0;l<a;++l)(T=i[l])&&(r.push(e.call(T,T.__data__,l,i)),o.push(T));return new ge(r,o)}function El(e){return function(){return this.matches(e)}}function al(e){return function(t){return t.matches(e)}}var vh=Array.prototype.find;function Bh(e){return function(){return vh.call(this.children,e)}}function Gh(){return this.firstElementChild}function Hh(e){return this.select(e==null?Gh:Bh(typeof e=="function"?e:al(e)))}var Fh=Array.prototype.filter;function wh(){return Array.from(this.children)}function Yh(e){return function(){return Fh.call(this.children,e)}}function Vh(e){return this.selectAll(e==null?wh:Yh(typeof e=="function"?e:al(e)))}function Wh(e){typeof e!="function"&&(e=El(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,a=r[o]=[],T,l=0;l<i;++l)(T=s[l])&&e.call(T,T.__data__,l,s)&&a.push(T);return new ge(r,this._parents)}function ll(e){return new Array(e.length)}function kh(){return new ge(this._enter||this._groups.map(ll),this._parents)}function dr(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}dr.prototype={constructor:dr,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 jh(e){return function(){return e}}function Xh(e,t,n,r,o,s){for(var i=0,a,T=t.length,l=s.length;i<l;++i)(a=t[i])?(a.__data__=s[i],r[i]=a):n[i]=new dr(e,s[i]);for(;i<T;++i)(a=t[i])&&(o[i]=a)}function $h(e,t,n,r,o,s,i){var a,T,l=new Map,R=t.length,c=s.length,S=new Array(R),A;for(a=0;a<R;++a)(T=t[a])&&(S[a]=A=i.call(T,T.__data__,a,t)+"",l.has(A)?o[a]=T:l.set(A,T));for(a=0;a<c;++a)A=i.call(e,s[a],a,s)+"",(T=l.get(A))?(r[a]=T,T.__data__=s[a],l.delete(A)):n[a]=new dr(e,s[a]);for(a=0;a<R;++a)(T=t[a])&&l.get(S[a])===T&&(o[a]=T)}function Kh(e){return e.__data__}function zh(e,t){if(!arguments.length)return Array.from(this,Kh);var n=t?$h:Xh,r=this._parents,o=this._groups;typeof e!="function"&&(e=jh(e));for(var s=o.length,i=new Array(s),a=new Array(s),T=new Array(s),l=0;l<s;++l){var R=r[l],c=o[l],S=c.length,A=Jh(e.call(R,R&&R.__data__,l,r)),d=A.length,N=a[l]=new Array(d),I=i[l]=new Array(d),u=T[l]=new Array(S);n(R,c,N,I,u,A,t);for(var f=0,O=0,C,m;f<d;++f)if(C=N[f]){for(f>=O&&(O=f+1);!(m=I[O])&&++O<d;);C._next=m||null}}return i=new ge(i,r),i._enter=a,i._exit=T,i}function Jh(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function qh(){return new ge(this._exit||this._groups.map(ll),this._parents)}function Zh(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 Qh(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),a=new Array(o),T=0;T<i;++T)for(var l=n[T],R=r[T],c=l.length,S=a[T]=new Array(c),A,d=0;d<c;++d)(A=l[d]||R[d])&&(S[d]=A);for(;T<o;++T)a[T]=n[T];return new ge(a,this._parents)}function eC(){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 tC(e){e||(e=nC);function t(c,S){return c&&S?e(c.__data__,S.__data__):!c-!S}for(var n=this._groups,r=n.length,o=new Array(r),s=0;s<r;++s){for(var i=n[s],a=i.length,T=o[s]=new Array(a),l,R=0;R<a;++R)(l=i[R])&&(T[R]=l);T.sort(t)}return new ge(o,this._parents).order()}function nC(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function rC(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function oC(){return Array.from(this)}function sC(){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 iC(){let e=0;for(const t of this)++e;return e}function EC(){return!this.node()}function aC(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var o=t[n],s=0,i=o.length,a;s<i;++s)(a=o[s])&&e.call(a,a.__data__,s,o);return this}function lC(e){return function(){this.removeAttribute(e)}}function TC(e){return function(){this.removeAttributeNS(e.space,e.local)}}function cC(e,t){return function(){this.setAttribute(e,t)}}function RC(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function SC(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function AC(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 dC(e,t){var n=br(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?TC:lC:typeof t=="function"?n.local?AC:SC:n.local?RC:cC)(n,t))}function Tl(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function uC(e){return function(){this.style.removeProperty(e)}}function IC(e,t,n){return function(){this.style.setProperty(e,t,n)}}function NC(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function OC(e,t,n){return arguments.length>1?this.each((t==null?uC:typeof t=="function"?NC:IC)(e,t,n??"")):Gt(this.node(),e)}function Gt(e,t){return e.style.getPropertyValue(t)||Tl(e).getComputedStyle(e,null).getPropertyValue(t)}function fC(e){return function(){delete this[e]}}function hC(e,t){return function(){this[e]=t}}function CC(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function LC(e,t){return arguments.length>1?this.each((t==null?fC:typeof t=="function"?CC:hC)(e,t)):this.node()[e]}function cl(e){return e.trim().split(/^|\s+/)}function Ls(e){return e.classList||new Rl(e)}function Rl(e){this._node=e,this._names=cl(e.getAttribute("class")||"")}Rl.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 Sl(e,t){for(var n=Ls(e),r=-1,o=t.length;++r<o;)n.add(t[r])}function Al(e,t){for(var n=Ls(e),r=-1,o=t.length;++r<o;)n.remove(t[r])}function pC(e){return function(){Sl(this,e)}}function _C(e){return function(){Al(this,e)}}function mC(e,t){return function(){(t.apply(this,arguments)?Sl:Al)(this,e)}}function DC(e,t){var n=cl(e+"");if(arguments.length<2){for(var r=Ls(this.node()),o=-1,s=n.length;++o<s;)if(!r.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?mC:t?pC:_C)(n,t))}function gC(){this.textContent=""}function MC(e){return function(){this.textContent=e}}function xC(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function PC(e){return arguments.length?this.each(e==null?gC:(typeof e=="function"?xC:MC)(e)):this.node().textContent}function yC(){this.innerHTML=""}function UC(e){return function(){this.innerHTML=e}}function bC(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function vC(e){return arguments.length?this.each(e==null?yC:(typeof e=="function"?bC:UC)(e)):this.node().innerHTML}function BC(){this.nextSibling&&this.parentNode.appendChild(this)}function GC(){return this.each(BC)}function HC(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function FC(){return this.each(HC)}function wC(e){var t=typeof e=="function"?e:sl(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function YC(){return null}function VC(e,t){var n=typeof e=="function"?e:sl(e),r=t==null?YC:typeof t=="function"?t:Cs(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function WC(){var e=this.parentNode;e&&e.removeChild(this)}function kC(){return this.each(WC)}function jC(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function XC(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function $C(e){return this.select(e?XC:jC)}function KC(e){return arguments.length?this.property("__data__",e):this.node().__data__}function zC(e){return function(t){e.call(this,t,this.__data__)}}function JC(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 qC(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 ZC(e,t,n){return function(){var r=this.__on,o,s=zC(t);if(r){for(var i=0,a=r.length;i<a;++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 QC(e,t,n){var r=JC(e+""),o,s=r.length,i;if(arguments.length<2){var a=this.node().__on;if(a){for(var T=0,l=a.length,R;T<l;++T)for(o=0,R=a[T];o<s;++o)if((i=r[o]).type===R.type&&i.name===R.name)return R.value}return}for(a=t?ZC:qC,o=0;o<s;++o)this.each(a(r[o],t,n));return this}function dl(e,t,n){var r=Tl(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 eL(e,t){return function(){return dl(this,e,t)}}function tL(e,t){return function(){return dl(this,e,t.apply(this,arguments))}}function nL(e,t){return this.each((typeof t=="function"?tL:eL)(e,t))}function*rL(){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 ul=[null];function ge(e,t){this._groups=e,this._parents=t}function mn(){return new ge([[document.documentElement]],ul)}function oL(){return this}ge.prototype=mn.prototype={constructor:ge,select:xh,selectAll:bh,selectChild:Hh,selectChildren:Vh,filter:Wh,data:zh,enter:kh,exit:qh,join:Zh,merge:Qh,selection:oL,order:eC,sort:tC,call:rC,nodes:oC,node:sC,size:iC,empty:EC,each:aC,attr:dC,style:OC,property:LC,classed:DC,text:PC,html:vC,raise:GC,lower:FC,append:wC,insert:VC,remove:kC,clone:$C,datum:KC,on:QC,dispatch:nL,[Symbol.iterator]:rL};function De(e){return typeof e=="string"?new ge([[document.querySelector(e)]],[document.documentElement]):new ge([[e]],ul)}function sL(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Pe(e,t){if(e=sL(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 iL={passive:!1},An={capture:!0,passive:!1};function Do(e){e.stopImmediatePropagation()}function bt(e){e.preventDefault(),e.stopImmediatePropagation()}function Il(e){var t=e.document.documentElement,n=De(e).on("dragstart.drag",bt,An);"onselectstart"in t?n.on("selectstart.drag",bt,An):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function Nl(e,t){var n=e.document.documentElement,r=De(e).on("dragstart.drag",null);t&&(r.on("click.drag",bt,An),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 Vn=e=>()=>e;function es(e,{sourceEvent:t,subject:n,target:r,identifier:o,active:s,x:i,y:a,dx:T,dy:l,dispatch:R}){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:a,enumerable:!0,configurable:!0},dx:{value:T,enumerable:!0,configurable:!0},dy:{value:l,enumerable:!0,configurable:!0},_:{value:R}})}es.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function EL(e){return!e.ctrlKey&&!e.button}function aL(){return this.parentNode}function lL(e,t){return t??{x:e.x,y:e.y}}function TL(){return navigator.maxTouchPoints||"ontouchstart"in this}function Ol(){var e=EL,t=aL,n=lL,r=TL,o={},s=Ur("start","drag","end"),i=0,a,T,l,R,c=0;function S(C){C.on("mousedown.drag",A).filter(r).on("touchstart.drag",I).on("touchmove.drag",u,iL).on("touchend.drag touchcancel.drag",f).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function A(C,m){if(!(R||!e.call(this,C,m))){var L=O(this,t.call(this,C,m),C,m,"mouse");L&&(De(C.view).on("mousemove.drag",d,An).on("mouseup.drag",N,An),Il(C.view),Do(C),l=!1,a=C.clientX,T=C.clientY,L("start",C))}}function d(C){if(bt(C),!l){var m=C.clientX-a,L=C.clientY-T;l=m*m+L*L>c}o.mouse("drag",C)}function N(C){De(C.view).on("mousemove.drag mouseup.drag",null),Nl(C.view,l),bt(C),o.mouse("end",C)}function I(C,m){if(e.call(this,C,m)){var L=C.changedTouches,D=t.call(this,C,m),M=L.length,x,B;for(x=0;x<M;++x)(B=O(this,D,C,m,L[x].identifier,L[x]))&&(Do(C),B("start",C,L[x]))}}function u(C){var m=C.changedTouches,L=m.length,D,M;for(D=0;D<L;++D)(M=o[m[D].identifier])&&(bt(C),M("drag",C,m[D]))}function f(C){var m=C.changedTouches,L=m.length,D,M;for(R&&clearTimeout(R),R=setTimeout(function(){R=null},500),D=0;D<L;++D)(M=o[m[D].identifier])&&(Do(C),M("end",C,m[D]))}function O(C,m,L,D,M,x){var B=s.copy(),g=Pe(x||L,m),p,F,_;if((_=n.call(C,new es("beforestart",{sourceEvent:L,target:S,identifier:M,active:i,x:g[0],y:g[1],dx:0,dy:0,dispatch:B}),D))!=null)return p=_.x-g[0]||0,F=_.y-g[1]||0,function U(P,v,b){var y=g,w;switch(P){case"start":o[M]=U,w=i++;break;case"end":delete o[M],--i;case"drag":g=Pe(b||v,m),w=i;break}B.call(P,C,new es(P,{sourceEvent:v,subject:_,target:S,identifier:M,active:w,x:g[0]+p,y:g[1]+F,dx:g[0]-y[0],dy:g[1]-y[1],dispatch:B}),D)}}return S.filter=function(C){return arguments.length?(e=typeof C=="function"?C:Vn(!!C),S):e},S.container=function(C){return arguments.length?(t=typeof C=="function"?C:Vn(C),S):t},S.subject=function(C){return arguments.length?(n=typeof C=="function"?C:Vn(C),S):n},S.touchable=function(C){return arguments.length?(r=typeof C=="function"?C:Vn(!!C),S):r},S.on=function(){var C=s.on.apply(s,arguments);return C===s?S:C},S.clickDistance=function(C){return arguments.length?(c=(C=+C)*C,S):Math.sqrt(c)},S}function ps(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function fl(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Dn(){}var dn=.7,ur=1/dn,vt="\\s*([+-]?\\d+)\\s*",un="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Ye="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",cL=/^#([0-9a-f]{3,8})$/,RL=new RegExp(`^rgb\\(${vt},${vt},${vt}\\)$`),SL=new RegExp(`^rgb\\(${Ye},${Ye},${Ye}\\)$`),AL=new RegExp(`^rgba\\(${vt},${vt},${vt},${un}\\)$`),dL=new RegExp(`^rgba\\(${Ye},${Ye},${Ye},${un}\\)$`),uL=new RegExp(`^hsl\\(${un},${Ye},${Ye}\\)$`),IL=new RegExp(`^hsla\\(${un},${Ye},${Ye},${un}\\)$`),nE={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};ps(Dn,ut,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:rE,formatHex:rE,formatHex8:NL,formatHsl:OL,formatRgb:oE,toString:oE});function rE(){return this.rgb().formatHex()}function NL(){return this.rgb().formatHex8()}function OL(){return hl(this).formatHsl()}function oE(){return this.rgb().formatRgb()}function ut(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=cL.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?sE(t):n===3?new _e(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Wn(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Wn(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=RL.exec(e))?new _e(t[1],t[2],t[3],1):(t=SL.exec(e))?new _e(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=AL.exec(e))?Wn(t[1],t[2],t[3],t[4]):(t=dL.exec(e))?Wn(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=uL.exec(e))?aE(t[1],t[2]/100,t[3]/100,1):(t=IL.exec(e))?aE(t[1],t[2]/100,t[3]/100,t[4]):nE.hasOwnProperty(e)?sE(nE[e]):e==="transparent"?new _e(NaN,NaN,NaN,0):null}function sE(e){return new _e(e>>16&255,e>>8&255,e&255,1)}function Wn(e,t,n,r){return r<=0&&(e=t=n=NaN),new _e(e,t,n,r)}function fL(e){return e instanceof Dn||(e=ut(e)),e?(e=e.rgb(),new _e(e.r,e.g,e.b,e.opacity)):new _e}function ts(e,t,n,r){return arguments.length===1?fL(e):new _e(e,t,n,r??1)}function _e(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}ps(_e,ts,fl(Dn,{brighter(e){return e=e==null?ur:Math.pow(ur,e),new _e(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?dn:Math.pow(dn,e),new _e(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new _e(At(this.r),At(this.g),At(this.b),Ir(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:iE,formatHex:iE,formatHex8:hL,formatRgb:EE,toString:EE}));function iE(){return`#${St(this.r)}${St(this.g)}${St(this.b)}`}function hL(){return`#${St(this.r)}${St(this.g)}${St(this.b)}${St((isNaN(this.opacity)?1:this.opacity)*255)}`}function EE(){const e=Ir(this.opacity);return`${e===1?"rgb(":"rgba("}${At(this.r)}, ${At(this.g)}, ${At(this.b)}${e===1?")":`, ${e})`}`}function Ir(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function At(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function St(e){return e=At(e),(e<16?"0":"")+e.toString(16)}function aE(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new ye(e,t,n,r)}function hl(e){if(e instanceof ye)return new ye(e.h,e.s,e.l,e.opacity);if(e instanceof Dn||(e=ut(e)),!e)return new ye;if(e instanceof ye)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,a=s-o,T=(s+o)/2;return a?(t===s?i=(n-r)/a+(n<r)*6:n===s?i=(r-t)/a+2:i=(t-n)/a+4,a/=T<.5?s+o:2-s-o,i*=60):a=T>0&&T<1?0:i,new ye(i,a,T,e.opacity)}function CL(e,t,n,r){return arguments.length===1?hl(e):new ye(e,t,n,r??1)}function ye(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}ps(ye,CL,fl(Dn,{brighter(e){return e=e==null?ur:Math.pow(ur,e),new ye(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?dn:Math.pow(dn,e),new ye(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 _e(go(e>=240?e-240:e+120,o,r),go(e,o,r),go(e<120?e+240:e-120,o,r),this.opacity)},clamp(){return new ye(lE(this.h),kn(this.s),kn(this.l),Ir(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=Ir(this.opacity);return`${e===1?"hsl(":"hsla("}${lE(this.h)}, ${kn(this.s)*100}%, ${kn(this.l)*100}%${e===1?")":`, ${e})`}`}}));function lE(e){return e=(e||0)%360,e<0?e+360:e}function kn(e){return Math.max(0,Math.min(1,e||0))}function go(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 _s=e=>()=>e;function LL(e,t){return function(n){return e+n*t}}function pL(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 _L(e){return(e=+e)==1?Cl:function(t,n){return n-t?pL(t,n,e):_s(isNaN(t)?n:t)}}function Cl(e,t){var n=t-e;return n?LL(e,n):_s(isNaN(e)?t:e)}const Nr=(function e(t){var n=_L(t);function r(o,s){var i=n((o=ts(o)).r,(s=ts(s)).r),a=n(o.g,s.g),T=n(o.b,s.b),l=Cl(o.opacity,s.opacity);return function(R){return o.r=i(R),o.g=a(R),o.b=T(R),o.opacity=l(R),o+""}}return r.gamma=e,r})(1);function mL(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 DL(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function gL(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]=Tn(e[i],t[i]);for(;i<n;++i)s[i]=t[i];return function(a){for(i=0;i<r;++i)s[i]=o[i](a);return s}}function ML(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function Fe(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function xL(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]=Tn(e[o],t[o]):r[o]=t[o];return function(s){for(o in n)r[o]=n[o](s);return r}}var ns=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Mo=new RegExp(ns.source,"g");function PL(e){return function(){return e}}function yL(e){return function(t){return e(t)+""}}function Ll(e,t){var n=ns.lastIndex=Mo.lastIndex=0,r,o,s,i=-1,a=[],T=[];for(e=e+"",t=t+"";(r=ns.exec(e))&&(o=Mo.exec(t));)(s=o.index)>n&&(s=t.slice(n,s),a[i]?a[i]+=s:a[++i]=s),(r=r[0])===(o=o[0])?a[i]?a[i]+=o:a[++i]=o:(a[++i]=null,T.push({i,x:Fe(r,o)})),n=Mo.lastIndex;return n<t.length&&(s=t.slice(n),a[i]?a[i]+=s:a[++i]=s),a.length<2?T[0]?yL(T[0].x):PL(t):(t=T.length,function(l){for(var R=0,c;R<t;++R)a[(c=T[R]).i]=c.x(l);return a.join("")})}function Tn(e,t){var n=typeof t,r;return t==null||n==="boolean"?_s(t):(n==="number"?Fe:n==="string"?(r=ut(t))?(t=r,Nr):Ll:t instanceof ut?Nr:t instanceof Date?ML:DL(t)?mL:Array.isArray(t)?gL:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?xL:Fe)(e,t)}var TE=180/Math.PI,rs={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function pl(e,t,n,r,o,s){var i,a,T;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(T=e*n+t*r)&&(n-=e*T,r-=t*T),(a=Math.sqrt(n*n+r*r))&&(n/=a,r/=a,T/=a),e*r<t*n&&(e=-e,t=-t,T=-T,i=-i),{translateX:o,translateY:s,rotate:Math.atan2(t,e)*TE,skewX:Math.atan(T)*TE,scaleX:i,scaleY:a}}var jn;function UL(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?rs:pl(t.a,t.b,t.c,t.d,t.e,t.f)}function bL(e){return e==null||(jn||(jn=document.createElementNS("http://www.w3.org/2000/svg","g")),jn.setAttribute("transform",e),!(e=jn.transform.baseVal.consolidate()))?rs:(e=e.matrix,pl(e.a,e.b,e.c,e.d,e.e,e.f))}function _l(e,t,n,r){function o(l){return l.length?l.pop()+" ":""}function s(l,R,c,S,A,d){if(l!==c||R!==S){var N=A.push("translate(",null,t,null,n);d.push({i:N-4,x:Fe(l,c)},{i:N-2,x:Fe(R,S)})}else(c||S)&&A.push("translate("+c+t+S+n)}function i(l,R,c,S){l!==R?(l-R>180?R+=360:R-l>180&&(l+=360),S.push({i:c.push(o(c)+"rotate(",null,r)-2,x:Fe(l,R)})):R&&c.push(o(c)+"rotate("+R+r)}function a(l,R,c,S){l!==R?S.push({i:c.push(o(c)+"skewX(",null,r)-2,x:Fe(l,R)}):R&&c.push(o(c)+"skewX("+R+r)}function T(l,R,c,S,A,d){if(l!==c||R!==S){var N=A.push(o(A)+"scale(",null,",",null,")");d.push({i:N-4,x:Fe(l,c)},{i:N-2,x:Fe(R,S)})}else(c!==1||S!==1)&&A.push(o(A)+"scale("+c+","+S+")")}return function(l,R){var c=[],S=[];return l=e(l),R=e(R),s(l.translateX,l.translateY,R.translateX,R.translateY,c,S),i(l.rotate,R.rotate,c,S),a(l.skewX,R.skewX,c,S),T(l.scaleX,l.scaleY,R.scaleX,R.scaleY,c,S),l=R=null,function(A){for(var d=-1,N=S.length,I;++d<N;)c[(I=S[d]).i]=I.x(A);return c.join("")}}}var vL=_l(UL,"px, ","px)","deg)"),BL=_l(bL,", ",")",")"),GL=1e-12;function cE(e){return((e=Math.exp(e))+1/e)/2}function HL(e){return((e=Math.exp(e))-1/e)/2}function FL(e){return((e=Math.exp(2*e))-1)/(e+1)}const or=(function e(t,n,r){function o(s,i){var a=s[0],T=s[1],l=s[2],R=i[0],c=i[1],S=i[2],A=R-a,d=c-T,N=A*A+d*d,I,u;if(N<GL)u=Math.log(S/l)/t,I=function(D){return[a+D*A,T+D*d,l*Math.exp(t*D*u)]};else{var f=Math.sqrt(N),O=(S*S-l*l+r*N)/(2*l*n*f),C=(S*S-l*l-r*N)/(2*S*n*f),m=Math.log(Math.sqrt(O*O+1)-O),L=Math.log(Math.sqrt(C*C+1)-C);u=(L-m)/t,I=function(D){var M=D*u,x=cE(m),B=l/(n*f)*(x*FL(t*M+m)-HL(m));return[a+B*A,T+B*d,l*x/cE(t*M+m)]}}return I.duration=u*1e3*t/Math.SQRT2,I}return o.rho=function(s){var i=Math.max(.001,+s),a=i*i,T=a*a;return e(i,a,T)},o})(Math.SQRT2,2,4);var Ht=0,sn=0,nn=0,ml=1e3,Or,En,fr=0,It=0,vr=0,In=typeof performance=="object"&&performance.now?performance:Date,Dl=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function ms(){return It||(Dl(wL),It=In.now()+vr)}function wL(){It=0}function hr(){this._call=this._time=this._next=null}hr.prototype=gl.prototype={constructor:hr,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?ms():+n)+(t==null?0:+t),!this._next&&En!==this&&(En?En._next=this:Or=this,En=this),this._call=e,this._time=n,os()},stop:function(){this._call&&(this._call=null,this._time=1/0,os())}};function gl(e,t,n){var r=new hr;return r.restart(e,t,n),r}function YL(){ms(),++Ht;for(var e=Or,t;e;)(t=It-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Ht}function RE(){It=(fr=In.now())+vr,Ht=sn=0;try{YL()}finally{Ht=0,WL(),It=0}}function VL(){var e=In.now(),t=e-fr;t>ml&&(vr-=t,fr=e)}function WL(){for(var e,t=Or,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:Or=n);En=e,os(r)}function os(e){if(!Ht){sn&&(sn=clearTimeout(sn));var t=e-It;t>24?(e<1/0&&(sn=setTimeout(RE,e-In.now()-vr)),nn&&(nn=clearInterval(nn))):(nn||(fr=In.now(),nn=setInterval(VL,ml)),Ht=1,Dl(RE))}}function SE(e,t,n){var r=new hr;return t=t==null?0:+t,r.restart(o=>{r.stop(),e(o+t)},t,n),r}var kL=Ur("start","end","cancel","interrupt"),jL=[],Ml=0,AE=1,ss=2,sr=3,dE=4,is=5,ir=6;function Br(e,t,n,r,o,s){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;XL(e,n,{name:t,index:r,group:o,on:kL,tween:jL,time:s.time,delay:s.delay,duration:s.duration,ease:s.ease,timer:null,state:Ml})}function Ds(e,t){var n=Ge(e,t);if(n.state>Ml)throw new Error("too late; already scheduled");return n}function We(e,t){var n=Ge(e,t);if(n.state>sr)throw new Error("too late; already running");return n}function Ge(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function XL(e,t,n){var r=e.__transition,o;r[t]=n,n.timer=gl(s,0,n.time);function s(l){n.state=AE,n.timer.restart(i,n.delay,n.time),n.delay<=l&&i(l-n.delay)}function i(l){var R,c,S,A;if(n.state!==AE)return T();for(R in r)if(A=r[R],A.name===n.name){if(A.state===sr)return SE(i);A.state===dE?(A.state=ir,A.timer.stop(),A.on.call("interrupt",e,e.__data__,A.index,A.group),delete r[R]):+R<t&&(A.state=ir,A.timer.stop(),A.on.call("cancel",e,e.__data__,A.index,A.group),delete r[R])}if(SE(function(){n.state===sr&&(n.state=dE,n.timer.restart(a,n.delay,n.time),a(l))}),n.state=ss,n.on.call("start",e,e.__data__,n.index,n.group),n.state===ss){for(n.state=sr,o=new Array(S=n.tween.length),R=0,c=-1;R<S;++R)(A=n.tween[R].value.call(e,e.__data__,n.index,n.group))&&(o[++c]=A);o.length=c+1}}function a(l){for(var R=l<n.duration?n.ease.call(null,l/n.duration):(n.timer.restart(T),n.state=is,1),c=-1,S=o.length;++c<S;)o[c].call(e,R);n.state===is&&(n.on.call("end",e,e.__data__,n.index,n.group),T())}function T(){n.state=ir,n.timer.stop(),delete r[t];for(var l in r)return;delete e.__transition}}function Er(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>ss&&r.state<is,r.state=ir,r.timer.stop(),r.on.call(o?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}s&&delete e.__transition}}function $L(e){return this.each(function(){Er(this,e)})}function KL(e,t){var n,r;return function(){var o=We(this,e),s=o.tween;if(s!==n){r=n=s;for(var i=0,a=r.length;i<a;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}o.tween=r}}function zL(e,t,n){var r,o;if(typeof n!="function")throw new Error;return function(){var s=We(this,e),i=s.tween;if(i!==r){o=(r=i).slice();for(var a={name:t,value:n},T=0,l=o.length;T<l;++T)if(o[T].name===t){o[T]=a;break}T===l&&o.push(a)}s.tween=o}}function JL(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Ge(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?KL:zL)(n,e,t))}function gs(e,t,n){var r=e._id;return e.each(function(){var o=We(this,r);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return Ge(o,r).value[t]}}function xl(e,t){var n;return(typeof t=="number"?Fe:t instanceof ut?Nr:(n=ut(t))?(t=n,Nr):Ll)(e,t)}function qL(e){return function(){this.removeAttribute(e)}}function ZL(e){return function(){this.removeAttributeNS(e.space,e.local)}}function QL(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 ep(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 tp(e,t,n){var r,o,s;return function(){var i,a=n(this),T;return a==null?void this.removeAttribute(e):(i=this.getAttribute(e),T=a+"",i===T?null:i===r&&T===o?s:(o=T,s=t(r=i,a)))}}function np(e,t,n){var r,o,s;return function(){var i,a=n(this),T;return a==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),T=a+"",i===T?null:i===r&&T===o?s:(o=T,s=t(r=i,a)))}}function rp(e,t){var n=br(e),r=n==="transform"?BL:xl;return this.attrTween(e,typeof t=="function"?(n.local?np:tp)(n,r,gs(this,"attr."+e,t)):t==null?(n.local?ZL:qL)(n):(n.local?ep:QL)(n,r,t))}function op(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function sp(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function ip(e,t){var n,r;function o(){var s=t.apply(this,arguments);return s!==r&&(n=(r=s)&&sp(e,s)),n}return o._value=t,o}function Ep(e,t){var n,r;function o(){var s=t.apply(this,arguments);return s!==r&&(n=(r=s)&&op(e,s)),n}return o._value=t,o}function ap(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=br(e);return this.tween(n,(r.local?ip:Ep)(r,t))}function lp(e,t){return function(){Ds(this,e).delay=+t.apply(this,arguments)}}function Tp(e,t){return t=+t,function(){Ds(this,e).delay=t}}function cp(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?lp:Tp)(t,e)):Ge(this.node(),t).delay}function Rp(e,t){return function(){We(this,e).duration=+t.apply(this,arguments)}}function Sp(e,t){return t=+t,function(){We(this,e).duration=t}}function Ap(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Rp:Sp)(t,e)):Ge(this.node(),t).duration}function dp(e,t){if(typeof t!="function")throw new Error;return function(){We(this,e).ease=t}}function up(e){var t=this._id;return arguments.length?this.each(dp(t,e)):Ge(this.node(),t).ease}function Ip(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;We(this,e).ease=n}}function Np(e){if(typeof e!="function")throw new Error;return this.each(Ip(this._id,e))}function Op(e){typeof e!="function"&&(e=El(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,a=r[o]=[],T,l=0;l<i;++l)(T=s[l])&&e.call(T,T.__data__,l,s)&&a.push(T);return new qe(r,this._parents,this._name,this._id)}function fp(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),a=0;a<s;++a)for(var T=t[a],l=n[a],R=T.length,c=i[a]=new Array(R),S,A=0;A<R;++A)(S=T[A]||l[A])&&(c[A]=S);for(;a<r;++a)i[a]=t[a];return new qe(i,this._parents,this._name,this._id)}function hp(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 Cp(e,t,n){var r,o,s=hp(t)?Ds:We;return function(){var i=s(this,e),a=i.on;a!==r&&(o=(r=a).copy()).on(t,n),i.on=o}}function Lp(e,t){var n=this._id;return arguments.length<2?Ge(this.node(),n).on.on(e):this.each(Cp(n,e,t))}function pp(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function _p(){return this.on("end.remove",pp(this._id))}function mp(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Cs(e));for(var r=this._groups,o=r.length,s=new Array(o),i=0;i<o;++i)for(var a=r[i],T=a.length,l=s[i]=new Array(T),R,c,S=0;S<T;++S)(R=a[S])&&(c=e.call(R,R.__data__,S,a))&&("__data__"in R&&(c.__data__=R.__data__),l[S]=c,Br(l[S],t,n,S,l,Ge(R,n)));return new qe(s,this._parents,t,n)}function Dp(e){var t=this._name,n=this._id;typeof e!="function"&&(e=il(e));for(var r=this._groups,o=r.length,s=[],i=[],a=0;a<o;++a)for(var T=r[a],l=T.length,R,c=0;c<l;++c)if(R=T[c]){for(var S=e.call(R,R.__data__,c,T),A,d=Ge(R,n),N=0,I=S.length;N<I;++N)(A=S[N])&&Br(A,t,n,N,S,d);s.push(S),i.push(R)}return new qe(s,i,t,n)}var gp=mn.prototype.constructor;function Mp(){return new gp(this._groups,this._parents)}function xp(e,t){var n,r,o;return function(){var s=Gt(this,e),i=(this.style.removeProperty(e),Gt(this,e));return s===i?null:s===n&&i===r?o:o=t(n=s,r=i)}}function Pl(e){return function(){this.style.removeProperty(e)}}function Pp(e,t,n){var r,o=n+"",s;return function(){var i=Gt(this,e);return i===o?null:i===r?s:s=t(r=i,n)}}function yp(e,t,n){var r,o,s;return function(){var i=Gt(this,e),a=n(this),T=a+"";return a==null&&(T=a=(this.style.removeProperty(e),Gt(this,e))),i===T?null:i===r&&T===o?s:(o=T,s=t(r=i,a))}}function Up(e,t){var n,r,o,s="style."+t,i="end."+s,a;return function(){var T=We(this,e),l=T.on,R=T.value[s]==null?a||(a=Pl(t)):void 0;(l!==n||o!==R)&&(r=(n=l).copy()).on(i,o=R),T.on=r}}function bp(e,t,n){var r=(e+="")=="transform"?vL:xl;return t==null?this.styleTween(e,xp(e,r)).on("end.style."+e,Pl(e)):typeof t=="function"?this.styleTween(e,yp(e,r,gs(this,"style."+e,t))).each(Up(this._id,e)):this.styleTween(e,Pp(e,r,t),n).on("end.style."+e,null)}function vp(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function Bp(e,t,n){var r,o;function s(){var i=t.apply(this,arguments);return i!==o&&(r=(o=i)&&vp(e,i,n)),r}return s._value=t,s}function Gp(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,Bp(e,t,n??""))}function Hp(e){return function(){this.textContent=e}}function Fp(e){return function(){var t=e(this);this.textContent=t??""}}function wp(e){return this.tween("text",typeof e=="function"?Fp(gs(this,"text",e)):Hp(e==null?"":e+""))}function Yp(e){return function(t){this.textContent=e.call(this,t)}}function Vp(e){var t,n;function r(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&Yp(o)),t}return r._value=e,r}function Wp(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,Vp(e))}function kp(){for(var e=this._name,t=this._id,n=yl(),r=this._groups,o=r.length,s=0;s<o;++s)for(var i=r[s],a=i.length,T,l=0;l<a;++l)if(T=i[l]){var R=Ge(T,t);Br(T,e,n,l,i,{time:R.time+R.delay+R.duration,delay:0,duration:R.duration,ease:R.ease})}return new qe(r,this._parents,e,n)}function jp(){var e,t,n=this,r=n._id,o=n.size();return new Promise(function(s,i){var a={value:i},T={value:function(){--o===0&&s()}};n.each(function(){var l=We(this,r),R=l.on;R!==e&&(t=(e=R).copy(),t._.cancel.push(a),t._.interrupt.push(a),t._.end.push(T)),l.on=t}),o===0&&s()})}var Xp=0;function qe(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function yl(){return++Xp}var Ke=mn.prototype;qe.prototype={constructor:qe,select:mp,selectAll:Dp,selectChild:Ke.selectChild,selectChildren:Ke.selectChildren,filter:Op,merge:fp,selection:Mp,transition:kp,call:Ke.call,nodes:Ke.nodes,node:Ke.node,size:Ke.size,empty:Ke.empty,each:Ke.each,on:Lp,attr:rp,attrTween:ap,style:bp,styleTween:Gp,text:wp,textTween:Wp,remove:_p,tween:JL,delay:cp,duration:Ap,ease:up,easeVarying:Np,end:jp,[Symbol.iterator]:Ke[Symbol.iterator]};function $p(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var Kp={time:null,delay:0,duration:250,ease:$p};function zp(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 Jp(e){var t,n;e instanceof qe?(t=e._id,e=e._name):(t=yl(),(n=Kp).time=ms(),e=e==null?null:e+"");for(var r=this._groups,o=r.length,s=0;s<o;++s)for(var i=r[s],a=i.length,T,l=0;l<a;++l)(T=i[l])&&Br(T,e,t,l,i,n||zp(T,t));return new qe(r,this._parents,e,t)}mn.prototype.interrupt=$L;mn.prototype.transition=Jp;const Xn=e=>()=>e;function qp(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 Je(e,t,n){this.k=e,this.x=t,this.y=n}Je.prototype={constructor:Je,scale:function(e){return e===1?this:new Je(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Je(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 Gr=new Je(1,0,0);Ul.prototype=Je.prototype;function Ul(e){for(;!e.__zoom;)if(!(e=e.parentNode))return Gr;return e.__zoom}function xo(e){e.stopImmediatePropagation()}function rn(e){e.preventDefault(),e.stopImmediatePropagation()}function Zp(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function Qp(){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 uE(){return this.__zoom||Gr}function e_(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function t_(){return navigator.maxTouchPoints||"ontouchstart"in this}function n_(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 bl(){var e=Zp,t=Qp,n=n_,r=e_,o=t_,s=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],a=250,T=or,l=Ur("start","zoom","end"),R,c,S,A=500,d=150,N=0,I=10;function u(_){_.property("__zoom",uE).on("wheel.zoom",M,{passive:!1}).on("mousedown.zoom",x).on("dblclick.zoom",B).filter(o).on("touchstart.zoom",g).on("touchmove.zoom",p).on("touchend.zoom touchcancel.zoom",F).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}u.transform=function(_,U,P,v){var b=_.selection?_.selection():_;b.property("__zoom",uE),_!==b?m(_,U,P,v):b.interrupt().each(function(){L(this,arguments).event(v).start().zoom(null,typeof U=="function"?U.apply(this,arguments):U).end()})},u.scaleBy=function(_,U,P,v){u.scaleTo(_,function(){var b=this.__zoom.k,y=typeof U=="function"?U.apply(this,arguments):U;return b*y},P,v)},u.scaleTo=function(_,U,P,v){u.transform(_,function(){var b=t.apply(this,arguments),y=this.__zoom,w=P==null?C(b):typeof P=="function"?P.apply(this,arguments):P,H=y.invert(w),Y=typeof U=="function"?U.apply(this,arguments):U;return n(O(f(y,Y),w,H),b,i)},P,v)},u.translateBy=function(_,U,P,v){u.transform(_,function(){return n(this.__zoom.translate(typeof U=="function"?U.apply(this,arguments):U,typeof P=="function"?P.apply(this,arguments):P),t.apply(this,arguments),i)},null,v)},u.translateTo=function(_,U,P,v,b){u.transform(_,function(){var y=t.apply(this,arguments),w=this.__zoom,H=v==null?C(y):typeof v=="function"?v.apply(this,arguments):v;return n(Gr.translate(H[0],H[1]).scale(w.k).translate(typeof U=="function"?-U.apply(this,arguments):-U,typeof P=="function"?-P.apply(this,arguments):-P),y,i)},v,b)};function f(_,U){return U=Math.max(s[0],Math.min(s[1],U)),U===_.k?_:new Je(U,_.x,_.y)}function O(_,U,P){var v=U[0]-P[0]*_.k,b=U[1]-P[1]*_.k;return v===_.x&&b===_.y?_:new Je(_.k,v,b)}function C(_){return[(+_[0][0]+ +_[1][0])/2,(+_[0][1]+ +_[1][1])/2]}function m(_,U,P,v){_.on("start.zoom",function(){L(this,arguments).event(v).start()}).on("interrupt.zoom end.zoom",function(){L(this,arguments).event(v).end()}).tween("zoom",function(){var b=this,y=arguments,w=L(b,y).event(v),H=t.apply(b,y),Y=P==null?C(H):typeof P=="function"?P.apply(b,y):P,k=Math.max(H[1][0]-H[0][0],H[1][1]-H[0][1]),j=b.__zoom,K=typeof U=="function"?U.apply(b,y):U,Q=T(j.invert(Y).concat(k/j.k),K.invert(Y).concat(k/K.k));return function(X){if(X===1)X=K;else{var $=Q(X),ee=k/$[2];X=new Je(ee,Y[0]-$[0]*ee,Y[1]-$[1]*ee)}w.zoom(null,X)}})}function L(_,U,P){return!P&&_.__zooming||new D(_,U)}function D(_,U){this.that=_,this.args=U,this.active=0,this.sourceEvent=null,this.extent=t.apply(_,U),this.taps=0}D.prototype={event:function(_){return _&&(this.sourceEvent=_),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(_,U){return this.mouse&&_!=="mouse"&&(this.mouse[1]=U.invert(this.mouse[0])),this.touch0&&_!=="touch"&&(this.touch0[1]=U.invert(this.touch0[0])),this.touch1&&_!=="touch"&&(this.touch1[1]=U.invert(this.touch1[0])),this.that.__zoom=U,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(_){var U=De(this.that).datum();l.call(_,this.that,new qp(_,{sourceEvent:this.sourceEvent,target:u,transform:this.that.__zoom,dispatch:l}),U)}};function M(_,...U){if(!e.apply(this,arguments))return;var P=L(this,U).event(_),v=this.__zoom,b=Math.max(s[0],Math.min(s[1],v.k*Math.pow(2,r.apply(this,arguments)))),y=Pe(_);if(P.wheel)(P.mouse[0][0]!==y[0]||P.mouse[0][1]!==y[1])&&(P.mouse[1]=v.invert(P.mouse[0]=y)),clearTimeout(P.wheel);else{if(v.k===b)return;P.mouse=[y,v.invert(y)],Er(this),P.start()}rn(_),P.wheel=setTimeout(w,d),P.zoom("mouse",n(O(f(v,b),P.mouse[0],P.mouse[1]),P.extent,i));function w(){P.wheel=null,P.end()}}function x(_,...U){if(S||!e.apply(this,arguments))return;var P=_.currentTarget,v=L(this,U,!0).event(_),b=De(_.view).on("mousemove.zoom",Y,!0).on("mouseup.zoom",k,!0),y=Pe(_,P),w=_.clientX,H=_.clientY;Il(_.view),xo(_),v.mouse=[y,this.__zoom.invert(y)],Er(this),v.start();function Y(j){if(rn(j),!v.moved){var K=j.clientX-w,Q=j.clientY-H;v.moved=K*K+Q*Q>N}v.event(j).zoom("mouse",n(O(v.that.__zoom,v.mouse[0]=Pe(j,P),v.mouse[1]),v.extent,i))}function k(j){b.on("mousemove.zoom mouseup.zoom",null),Nl(j.view,v.moved),rn(j),v.event(j).end()}}function B(_,...U){if(e.apply(this,arguments)){var P=this.__zoom,v=Pe(_.changedTouches?_.changedTouches[0]:_,this),b=P.invert(v),y=P.k*(_.shiftKey?.5:2),w=n(O(f(P,y),v,b),t.apply(this,U),i);rn(_),a>0?De(this).transition().duration(a).call(m,w,v,_):De(this).call(u.transform,w,v,_)}}function g(_,...U){if(e.apply(this,arguments)){var P=_.touches,v=P.length,b=L(this,U,_.changedTouches.length===v).event(_),y,w,H,Y;for(xo(_),w=0;w<v;++w)H=P[w],Y=Pe(H,this),Y=[Y,this.__zoom.invert(Y),H.identifier],b.touch0?!b.touch1&&b.touch0[2]!==Y[2]&&(b.touch1=Y,b.taps=0):(b.touch0=Y,y=!0,b.taps=1+!!R);R&&(R=clearTimeout(R)),y&&(b.taps<2&&(c=Y[0],R=setTimeout(function(){R=null},A)),Er(this),b.start())}}function p(_,...U){if(this.__zooming){var P=L(this,U).event(_),v=_.changedTouches,b=v.length,y,w,H,Y;for(rn(_),y=0;y<b;++y)w=v[y],H=Pe(w,this),P.touch0&&P.touch0[2]===w.identifier?P.touch0[0]=H:P.touch1&&P.touch1[2]===w.identifier&&(P.touch1[0]=H);if(w=P.that.__zoom,P.touch1){var k=P.touch0[0],j=P.touch0[1],K=P.touch1[0],Q=P.touch1[1],X=(X=K[0]-k[0])*X+(X=K[1]-k[1])*X,$=($=Q[0]-j[0])*$+($=Q[1]-j[1])*$;w=f(w,Math.sqrt(X/$)),H=[(k[0]+K[0])/2,(k[1]+K[1])/2],Y=[(j[0]+Q[0])/2,(j[1]+Q[1])/2]}else if(P.touch0)H=P.touch0[0],Y=P.touch0[1];else return;P.zoom("touch",n(O(w,H,Y),P.extent,i))}}function F(_,...U){if(this.__zooming){var P=L(this,U).event(_),v=_.changedTouches,b=v.length,y,w;for(xo(_),S&&clearTimeout(S),S=setTimeout(function(){S=null},A),y=0;y<b;++y)w=v[y],P.touch0&&P.touch0[2]===w.identifier?delete P.touch0:P.touch1&&P.touch1[2]===w.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&&(w=Pe(w,this),Math.hypot(c[0]-w[0],c[1]-w[1])<I)){var H=De(this).on("dblclick.zoom");H&&H.apply(this,arguments)}}}return u.wheelDelta=function(_){return arguments.length?(r=typeof _=="function"?_:Xn(+_),u):r},u.filter=function(_){return arguments.length?(e=typeof _=="function"?_:Xn(!!_),u):e},u.touchable=function(_){return arguments.length?(o=typeof _=="function"?_:Xn(!!_),u):o},u.extent=function(_){return arguments.length?(t=typeof _=="function"?_:Xn([[+_[0][0],+_[0][1]],[+_[1][0],+_[1][1]]]),u):t},u.scaleExtent=function(_){return arguments.length?(s[0]=+_[0],s[1]=+_[1],u):[s[0],s[1]]},u.translateExtent=function(_){return arguments.length?(i[0][0]=+_[0][0],i[1][0]=+_[1][0],i[0][1]=+_[0][1],i[1][1]=+_[1][1],u):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},u.constrain=function(_){return arguments.length?(n=_,u):n},u.duration=function(_){return arguments.length?(a=+_,u):a},u.interpolate=function(_){return arguments.length?(T=_,u):T},u.on=function(){var _=l.on.apply(l,arguments);return _===l?u:_},u.clickDistance=function(_){return arguments.length?(N=(_=+_)*_,u):Math.sqrt(N)},u.tapDistance=function(_){return arguments.length?(I=+_,u):I},u}const Ve={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."},Nn=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],vl=["Enter"," ","Escape"],Bl={"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 Ft;(function(e){e.Strict="strict",e.Loose="loose"})(Ft||(Ft={}));var dt;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(dt||(dt={}));var On;(function(e){e.Partial="partial",e.Full="full"})(On||(On={}));const Gl={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var nt;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(nt||(nt={}));var fn;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(fn||(fn={}));var Z;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(Z||(Z={}));const IE={[Z.Left]:Z.Right,[Z.Right]:Z.Left,[Z.Top]:Z.Bottom,[Z.Bottom]:Z.Top};function Hl(e){return e===null?null:e?"valid":"invalid"}const Fl=e=>"id"in e&&"source"in e&&"target"in e,r_=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),Ms=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),gn=(e,t=[0,0])=>{const{width:n,height:r}=Ze(e),o=e.origin??t,s=n*o[0],i=r*o[1];return{x:e.position.x-s,y:e.position.y-i}},o_=(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):Ms(o)?o:t.nodeLookup.get(o.id));const a=i?Cr(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return Hr(r,a)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return Fr(n)},Mn=(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=Hr(n,Cr(o)),r=!0)}),r?Fr(n):{x:0,y:0,width:0,height:0}},xs=(e,t,[n,r,o]=[0,0,1],s=!1,i=!1)=>{const a={...Pn(t,[n,r,o]),width:t.width/o,height:t.height/o},T=[];for(const l of e.values()){const{measured:R,selectable:c=!0,hidden:S=!1}=l;if(i&&!c||S)continue;const A=R.width??l.width??l.initialWidth??null,d=R.height??l.height??l.initialHeight??null,N=hn(a,Yt(l)),I=(A??0)*(d??0),u=s&&N>0;(!l.internals.handleBounds||u||N>=I||l.dragging)&&T.push(l)}return T},s_=(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 i_(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 E_({nodes:e,width:t,height:n,panZoom:r,minZoom:o,maxZoom:s},i){if(e.size===0)return Promise.resolve(!0);const a=i_(e,i),T=Mn(a),l=Ps(T,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(l,{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 wl({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:o,onError:s}){const i=n.get(e),a=i.parentId?n.get(i.parentId):void 0,{x:T,y:l}=a?a.internals.positionAbsolute:{x:0,y:0},R=i.origin??r;let c=i.extent||o;if(i.extent==="parent"&&!i.expandParent)if(!a)s==null||s("005",Ve.error005());else{const A=a.measured.width,d=a.measured.height;A&&d&&(c=[[T,l],[T+A,l+d]])}else a&&Vt(i.extent)&&(c=[[i.extent[0][0]+T,i.extent[0][1]+l],[i.extent[1][0]+T,i.extent[1][1]+l]]);const S=Vt(c)?Nt(t,c,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&(s==null||s("015",Ve.error015())),{position:{x:S.x-T+(i.measured.width??0)*R[0],y:S.y-l+(i.measured.height??0)*R[1]},positionAbsolute:S}}async function a_({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:o}){const s=new Set(e.map(S=>S.id)),i=[];for(const S of n){if(S.deletable===!1)continue;const A=s.has(S.id),d=!A&&S.parentId&&i.find(N=>N.id===S.parentId);(A||d)&&i.push(S)}const a=new Set(t.map(S=>S.id)),T=r.filter(S=>S.deletable!==!1),R=s_(i,T);for(const S of T)a.has(S.id)&&!R.find(d=>d.id===S.id)&&R.push(S);if(!o)return{edges:R,nodes:i};const c=await o({nodes:i,edges:R});return typeof c=="boolean"?c?{edges:R,nodes:i}:{edges:[],nodes:[]}:c}const wt=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Nt=(e={x:0,y:0},t,n)=>({x:wt(e.x,t[0][0],t[1][0]-((n==null?void 0:n.width)??0)),y:wt(e.y,t[0][1],t[1][1]-((n==null?void 0:n.height)??0))});function Yl(e,t,n){const{width:r,height:o}=Ze(n),{x:s,y:i}=n.internals.positionAbsolute;return Nt(e,[[s,i],[s+r,i+o]],t)}const NE=(e,t,n)=>e<t?wt(Math.abs(e-t),1,t)/t:e>n?-wt(Math.abs(e-n),1,t)/t:0,Vl=(e,t,n=15,r=40)=>{const o=NE(e.x,r,t.width-r)*n,s=NE(e.y,r,t.height-r)*n;return[o,s]},Hr=(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)}),Es=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Fr=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),Yt=(e,t=[0,0])=>{var o,s;const{x:n,y:r}=Ms(e)?e.internals.positionAbsolute:gn(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}},Cr=(e,t=[0,0])=>{var o,s;const{x:n,y:r}=Ms(e)?e.internals.positionAbsolute:gn(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)}},Wl=(e,t)=>Fr(Hr(Es(e),Es(t))),hn=(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)},OE=e=>Ue(e.width)&&Ue(e.height)&&Ue(e.x)&&Ue(e.y),Ue=e=>!isNaN(e)&&isFinite(e),l_=(e,t)=>{},xn=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),Pn=({x:e,y:t},[n,r,o],s=!1,i=[1,1])=>{const a={x:(e-n)/o,y:(t-r)/o};return s?xn(a,i):a},Lr=({x:e,y:t},[n,r,o])=>({x:e*o+n,y:t*o+r});function Dt(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 T_(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=Dt(e,n),o=Dt(e,t);return{top:r,right:o,bottom:r,left:o,x:o*2,y:r*2}}if(typeof e=="object"){const r=Dt(e.top??e.y??0,n),o=Dt(e.bottom??e.y??0,n),s=Dt(e.left??e.x??0,t),i=Dt(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 c_(e,t,n,r,o,s){const{x:i,y:a}=Lr(e,[t,n,r]),{x:T,y:l}=Lr({x:e.x+e.width,y:e.y+e.height},[t,n,r]),R=o-T,c=s-l;return{left:Math.floor(i),top:Math.floor(a),right:Math.floor(R),bottom:Math.floor(c)}}const Ps=(e,t,n,r,o,s)=>{const i=T_(s,t,n),a=(t-i.x)/e.width,T=(n-i.y)/e.height,l=Math.min(a,T),R=wt(l,r,o),c=e.x+e.width/2,S=e.y+e.height/2,A=t/2-c*R,d=n/2-S*R,N=c_(e,A,d,R,t,n),I={left:Math.min(N.left-i.left,0),top:Math.min(N.top-i.top,0),right:Math.min(N.right-i.right,0),bottom:Math.min(N.bottom-i.bottom,0)};return{x:A-I.left+I.right,y:d-I.top+I.bottom,zoom:R}},Cn=()=>{var e;return typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)==null?void 0:e.indexOf("Mac"))>=0};function Vt(e){return e!=null&&e!=="parent"}function Ze(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 kl(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 jl(e,t={width:0,height:0},n,r,o){const s={...e},i=r.get(n);if(i){const a=i.origin||o;s.x+=i.internals.positionAbsolute.x-(t.width??0)*a[0],s.y+=i.internals.positionAbsolute.y-(t.height??0)*a[1]}return s}function fE(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function R_(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function S_(e){return{...Bl,...e||{}}}function cn(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:o}){const{x:s,y:i}=be(e),a=Pn({x:s-((o==null?void 0:o.left)??0),y:i-((o==null?void 0:o.top)??0)},r),{x:T,y:l}=n?xn(a,t):a;return{xSnapped:T,ySnapped:l,...a}}const ys=e=>({width:e.offsetWidth,height:e.offsetHeight}),Xl=e=>{var t;return((t=e==null?void 0:e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},A_=["INPUT","SELECT","TEXTAREA"];function $l(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:A_.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const Kl=e=>"clientX"in e,be=(e,t)=>{var s,i;const n=Kl(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)}},hE=(e,t,n,r,o)=>{const s=t.querySelectorAll(`.${e}`);return!s||!s.length?null:Array.from(s).map(i=>{const a=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:o,position:i.getAttribute("data-handlepos"),x:(a.left-n.left)/r,y:(a.top-n.top)/r,...ys(i)}})};function zl({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:o,sourceControlY:s,targetControlX:i,targetControlY:a}){const T=e*.125+o*.375+i*.375+n*.125,l=t*.125+s*.375+a*.375+r*.125,R=Math.abs(T-e),c=Math.abs(l-t);return[T,l,R,c]}function $n(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function CE({pos:e,x1:t,y1:n,x2:r,y2:o,c:s}){switch(e){case Z.Left:return[t-$n(t-r,s),n];case Z.Right:return[t+$n(r-t,s),n];case Z.Top:return[t,n-$n(n-o,s)];case Z.Bottom:return[t,n+$n(o-n,s)]}}function Jl({sourceX:e,sourceY:t,sourcePosition:n=Z.Bottom,targetX:r,targetY:o,targetPosition:s=Z.Top,curvature:i=.25}){const[a,T]=CE({pos:n,x1:e,y1:t,x2:r,y2:o,c:i}),[l,R]=CE({pos:s,x1:r,y1:o,x2:e,y2:t,c:i}),[c,S,A,d]=zl({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:a,sourceControlY:T,targetControlX:l,targetControlY:R});return[`M${e},${t} C${a},${T} ${l},${R} ${r},${o}`,c,S,A,d]}function ql({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,a=r<t?r+i:r-i;return[s,a,o,i]}function d_({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,a=Math.max(e.parentId||o&&e.selected?e.internals.z:0,t.parentId||o&&t.selected?t.internals.z:0);return i+a}function u_({sourceNode:e,targetNode:t,width:n,height:r,transform:o}){const s=Hr(Cr(e),Cr(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 hn(i,Fr(s))>0}const I_=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,N_=(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)),O_=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||I_;let o;return Fl(e)?o={...e}:o={...e,id:r(e)},N_(o,t)?t:(o.sourceHandle===null&&delete o.sourceHandle,o.targetHandle===null&&delete o.targetHandle,t.concat(o))};function Zl({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[o,s,i,a]=ql({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,o,s,i,a]}const LE={[Z.Left]:{x:-1,y:0},[Z.Right]:{x:1,y:0},[Z.Top]:{x:0,y:-1},[Z.Bottom]:{x:0,y:1}},f_=({source:e,sourcePosition:t=Z.Bottom,target:n})=>t===Z.Left||t===Z.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},pE=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function h_({source:e,sourcePosition:t=Z.Bottom,target:n,targetPosition:r=Z.Top,center:o,offset:s,stepPosition:i}){const a=LE[t],T=LE[r],l={x:e.x+a.x*s,y:e.y+a.y*s},R={x:n.x+T.x*s,y:n.y+T.y*s},c=f_({source:l,sourcePosition:t,target:R}),S=c.x!==0?"x":"y",A=c[S];let d=[],N,I;const u={x:0,y:0},f={x:0,y:0},[,,O,C]=ql({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(a[S]*T[S]===-1){S==="x"?(N=o.x??l.x+(R.x-l.x)*i,I=o.y??(l.y+R.y)/2):(N=o.x??(l.x+R.x)/2,I=o.y??l.y+(R.y-l.y)*i);const L=[{x:N,y:l.y},{x:N,y:R.y}],D=[{x:l.x,y:I},{x:R.x,y:I}];a[S]===A?d=S==="x"?L:D:d=S==="x"?D:L}else{const L=[{x:l.x,y:R.y}],D=[{x:R.x,y:l.y}];if(S==="x"?d=a.x===A?D:L:d=a.y===A?L:D,t===r){const p=Math.abs(e[S]-n[S]);if(p<=s){const F=Math.min(s-1,s-p);a[S]===A?u[S]=(l[S]>e[S]?-1:1)*F:f[S]=(R[S]>n[S]?-1:1)*F}}if(t!==r){const p=S==="x"?"y":"x",F=a[S]===T[p],_=l[p]>R[p],U=l[p]<R[p];(a[S]===1&&(!F&&_||F&&U)||a[S]!==1&&(!F&&U||F&&_))&&(d=S==="x"?L:D)}const M={x:l.x+u.x,y:l.y+u.y},x={x:R.x+f.x,y:R.y+f.y},B=Math.max(Math.abs(M.x-d[0].x),Math.abs(x.x-d[0].x)),g=Math.max(Math.abs(M.y-d[0].y),Math.abs(x.y-d[0].y));B>=g?(N=(M.x+x.x)/2,I=d[0].y):(N=d[0].x,I=(M.y+x.y)/2)}return[[e,{x:l.x+u.x,y:l.y+u.y},...d,{x:R.x+f.x,y:R.y+f.y},n],N,I,O,C]}function C_(e,t,n,r){const o=Math.min(pE(e,t)/2,pE(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 l=e.x<n.x?-1:1,R=e.y<n.y?1:-1;return`L ${s+o*l},${i}Q ${s},${i} ${s},${i+o*R}`}const a=e.x<n.x?1:-1,T=e.y<n.y?-1:1;return`L ${s},${i+o*T}Q ${s},${i} ${s+o*a},${i}`}function as({sourceX:e,sourceY:t,sourcePosition:n=Z.Bottom,targetX:r,targetY:o,targetPosition:s=Z.Top,borderRadius:i=5,centerX:a,centerY:T,offset:l=20,stepPosition:R=.5}){const[c,S,A,d,N]=h_({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:o},targetPosition:s,center:{x:a,y:T},offset:l,stepPosition:R});return[c.reduce((u,f,O)=>{let C="";return O>0&&O<c.length-1?C=C_(c[O-1],f,c[O+1],i):C=`${O===0?"M":"L"}${f.x} ${f.y}`,u+=C,u},""),S,A,d,N]}function _E(e){var t;return e&&!!(e.internals.handleBounds||(t=e.handles)!=null&&t.length)&&!!(e.measured.width||e.width||e.initialWidth)}function L_(e){var c;const{sourceNode:t,targetNode:n}=e;if(!_E(t)||!_E(n))return null;const r=t.internals.handleBounds||mE(t.handles),o=n.internals.handleBounds||mE(n.handles),s=DE((r==null?void 0:r.source)??[],e.sourceHandle),i=DE(e.connectionMode===Ft.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(c=e.onError)==null||c.call(e,"008",Ve.error008(s?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const a=(s==null?void 0:s.position)||Z.Bottom,T=(i==null?void 0:i.position)||Z.Top,l=Ot(t,s,a),R=Ot(n,i,T);return{sourceX:l.x,sourceY:l.y,targetX:R.x,targetY:R.y,sourcePosition:a,targetPosition:T}}function mE(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 Ot(e,t,n=Z.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:a}=t??Ze(e);if(r)return{x:o+i/2,y:s+a/2};switch((t==null?void 0:t.position)??n){case Z.Top:return{x:o+i/2,y:s};case Z.Right:return{x:o+i,y:s+a/2};case Z.Bottom:return{x:o+i/2,y:s+a};case Z.Left:return{x:o,y:s+a/2}}}function DE(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function ls(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function p_(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:o}){const s=new Set;return e.reduce((i,a)=>([a.markerStart||r,a.markerEnd||o].forEach(T=>{if(T&&typeof T=="object"){const l=ls(T,t);s.has(l)||(i.push({id:l,color:T.color||n,...T}),s.add(l))}}),i),[]).sort((i,a)=>i.id.localeCompare(a.id))}const Ql=1e3,__=10,Us={nodeOrigin:[0,0],nodeExtent:Nn,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},m_={...Us,checkEquality:!0};function bs(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function D_(e,t,n){const r=bs(Us,n);for(const o of e.values())if(o.parentId)Bs(o,e,t,r);else{const s=gn(o,r.nodeOrigin),i=Vt(o.extent)?o.extent:r.nodeExtent,a=Nt(s,i,Ze(o));o.internals.positionAbsolute=a}}function g_(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 vs(e){return e==="manual"}function Ts(e,t,n,r={}){var l,R;const o=bs(m_,r),s={i:0},i=new Map(t),a=o!=null&&o.elevateNodesOnSelect&&!vs(o.zIndexMode)?Ql:0;let T=e.length>0;t.clear(),n.clear();for(const c of e){let S=i.get(c.id);if(o.checkEquality&&c===(S==null?void 0:S.internals.userNode))t.set(c.id,S);else{const A=gn(c,o.nodeOrigin),d=Vt(c.extent)?c.extent:o.nodeExtent,N=Nt(A,d,Ze(c));S={...o.defaults,...c,measured:{width:(l=c.measured)==null?void 0:l.width,height:(R=c.measured)==null?void 0:R.height},internals:{positionAbsolute:N,handleBounds:g_(c,S),z:eT(c,a,o.zIndexMode),userNode:c}},t.set(c.id,S)}(S.measured===void 0||S.measured.width===void 0||S.measured.height===void 0)&&!S.hidden&&(T=!1),c.parentId&&Bs(S,t,n,r,s)}return T}function M_(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 Bs(e,t,n,r,o){const{elevateNodesOnSelect:s,nodeOrigin:i,nodeExtent:a,zIndexMode:T}=bs(Us,r),l=e.parentId,R=t.get(l);if(!R){console.warn(`Parent node ${l} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}M_(e,n),o&&!R.parentId&&R.internals.rootParentIndex===void 0&&T==="auto"&&(R.internals.rootParentIndex=++o.i,R.internals.z=R.internals.z+o.i*__),o&&R.internals.rootParentIndex!==void 0&&(o.i=R.internals.rootParentIndex);const c=s&&!vs(T)?Ql:0,{x:S,y:A,z:d}=x_(e,R,i,a,c,T),{positionAbsolute:N}=e.internals,I=S!==N.x||A!==N.y;(I||d!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:I?{x:S,y:A}:N,z:d}})}function eT(e,t,n){const r=Ue(e.zIndex)?e.zIndex:0;return vs(n)?r:r+(e.selected?t:0)}function x_(e,t,n,r,o,s){const{x:i,y:a}=t.internals.positionAbsolute,T=Ze(e),l=gn(e,n),R=Vt(e.extent)?Nt(l,e.extent,T):l;let c=Nt({x:i+R.x,y:a+R.y},r,T);e.extent==="parent"&&(c=Yl(c,T,t));const S=eT(e,o,s),A=t.internals.z??0;return{x:c.x,y:c.y,z:A>=S?A+1:S}}function Gs(e,t,n,r=[0,0]){var i;const o=[],s=new Map;for(const a of e){const T=t.get(a.parentId);if(!T)continue;const l=((i=s.get(a.parentId))==null?void 0:i.expandedRect)??Yt(T),R=Wl(l,a.rect);s.set(a.parentId,{expandedRect:R,parent:T})}return s.size>0&&s.forEach(({expandedRect:a,parent:T},l)=>{var O;const R=T.internals.positionAbsolute,c=Ze(T),S=T.origin??r,A=a.x<R.x?Math.round(Math.abs(R.x-a.x)):0,d=a.y<R.y?Math.round(Math.abs(R.y-a.y)):0,N=Math.max(c.width,Math.round(a.width)),I=Math.max(c.height,Math.round(a.height)),u=(N-c.width)*S[0],f=(I-c.height)*S[1];(A>0||d>0||u||f)&&(o.push({id:l,type:"position",position:{x:T.position.x-A+u,y:T.position.y-d+f}}),(O=n.get(l))==null||O.forEach(C=>{e.some(m=>m.id===C.id)||o.push({id:C.id,type:"position",position:{x:C.position.x+A,y:C.position.y+d}})})),(c.width<a.width||c.height<a.height||A||d)&&o.push({id:l,type:"dimensions",setAttributes:!0,dimensions:{width:N+(A?S[0]*A-u:0),height:I+(d?S[1]*d-f:0)}})}),o}function P_(e,t,n,r,o,s,i){const a=r==null?void 0:r.querySelector(".xyflow__viewport");let T=!1;if(!a)return{changes:[],updatedInternals:T};const l=[],R=window.getComputedStyle(a),{m22:c}=new window.DOMMatrixReadOnly(R.transform),S=[];for(const A of e.values()){const d=t.get(A.id);if(!d)continue;if(d.hidden){t.set(d.id,{...d,internals:{...d.internals,handleBounds:void 0}}),T=!0;continue}const N=ys(A.nodeElement),I=d.measured.width!==N.width||d.measured.height!==N.height;if(!!(N.width&&N.height&&(I||!d.internals.handleBounds||A.force))){const f=A.nodeElement.getBoundingClientRect(),O=Vt(d.extent)?d.extent:s;let{positionAbsolute:C}=d.internals;d.parentId&&d.extent==="parent"?C=Yl(C,N,t.get(d.parentId)):O&&(C=Nt(C,O,N));const m={...d,measured:N,internals:{...d.internals,positionAbsolute:C,handleBounds:{source:hE("source",A.nodeElement,f,c,d.id),target:hE("target",A.nodeElement,f,c,d.id)}}};t.set(d.id,m),d.parentId&&Bs(m,t,n,{nodeOrigin:o,zIndexMode:i}),T=!0,I&&(l.push({id:d.id,type:"dimensions",dimensions:N}),d.expandParent&&d.parentId&&S.push({id:d.id,parentId:d.parentId,rect:Yt(m,o)}))}}if(S.length>0){const A=Gs(S,t,n,o);l.push(...A)}return{changes:l,updatedInternals:T}}async function y_({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),a=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(a)}function gE(e,t,n,r,o,s){let i=o;const a=r.get(i)||new Map;r.set(i,a.set(n,t)),i=`${o}-${e}`;const T=r.get(i)||new Map;if(r.set(i,T.set(n,t)),s){i=`${o}-${e}-${s}`;const l=r.get(i)||new Map;r.set(i,l.set(n,t))}}function tT(e,t,n){e.clear(),t.clear();for(const r of n){const{source:o,target:s,sourceHandle:i=null,targetHandle:a=null}=r,T={edgeId:r.id,source:o,target:s,sourceHandle:i,targetHandle:a},l=`${o}-${i}--${s}-${a}`,R=`${s}-${a}--${o}-${i}`;gE("source",T,R,e,o,i),gE("target",T,l,e,s,a),t.set(r.id,r)}}function nT(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:nT(n,t):!1}function ME(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 U_(e,t,n,r){const o=new Map;for(const[s,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!nT(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const a=e.get(s);a&&o.set(s,{id:s,position:a.position||{x:0,y:0},distance:{x:n.x-a.internals.positionAbsolute.x,y:n.y-a.internals.positionAbsolute.y},extent:a.extent,parentId:a.parentId,origin:a.origin,expandParent:a.expandParent,internals:{positionAbsolute:a.internals.positionAbsolute||{x:0,y:0}},measured:{width:a.measured.width??0,height:a.measured.height??0}})}return o}function Po({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){var i,a,T;const o=[];for(const[l,R]of t){const c=(i=n.get(l))==null?void 0:i.internals.userNode;c&&o.push({...c,position:R.position,dragging:r})}if(!e)return[o[0],o];const s=(a=n.get(e))==null?void 0:a.internals.userNode;return[s?{...s,position:((T=t.get(e))==null?void 0:T.position)||s.position,dragging:r}:o[0],o]}function b_({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=xn(s,t);return{x:i.x-s.x,y:i.y-s.y}}function v_({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:o}){let s={x:null,y:null},i=0,a=new Map,T=!1,l={x:0,y:0},R=null,c=!1,S=null,A=!1,d=!1,N=null;function I({noDragClassName:f,handleSelector:O,domNode:C,isSelectable:m,nodeId:L,nodeClickDistance:D=0}){S=De(C);function M({x:p,y:F}){const{nodeLookup:_,nodeExtent:U,snapGrid:P,snapToGrid:v,nodeOrigin:b,onNodeDrag:y,onSelectionDrag:w,onError:H,updateNodePositions:Y}=t();s={x:p,y:F};let k=!1;const j=a.size>1,K=j&&U?Es(Mn(a)):null,Q=j&&v?b_({dragItems:a,snapGrid:P,x:p,y:F}):null;for(const[X,$]of a){if(!_.has(X))continue;let ee={x:p-$.distance.x,y:F-$.distance.y};v&&(ee=Q?{x:Math.round(ee.x+Q.x),y:Math.round(ee.y+Q.y)}:xn(ee,P));let oe=null;if(j&&U&&!$.extent&&K){const{positionAbsolute:te}=$.internals,Ee=te.x-K.x+U[0][0],Te=te.x+$.measured.width-K.x2+U[1][0],ie=te.y-K.y+U[0][1],fe=te.y+$.measured.height-K.y2+U[1][1];oe=[[Ee,ie],[Te,fe]]}const{position:q,positionAbsolute:J}=wl({nodeId:X,nextPosition:ee,nodeLookup:_,nodeExtent:oe||U,nodeOrigin:b,onError:H});k=k||$.position.x!==q.x||$.position.y!==q.y,$.position=q,$.internals.positionAbsolute=J}if(d=d||k,!!k&&(Y(a,!0),N&&(r||y||!L&&w))){const[X,$]=Po({nodeId:L,dragItems:a,nodeLookup:_});r==null||r(N,a,X,$),y==null||y(N,X,$),L||w==null||w(N,$)}}async function x(){if(!R)return;const{transform:p,panBy:F,autoPanSpeed:_,autoPanOnNodeDrag:U}=t();if(!U){T=!1,cancelAnimationFrame(i);return}const[P,v]=Vl(l,R,_);(P!==0||v!==0)&&(s.x=(s.x??0)-P/p[2],s.y=(s.y??0)-v/p[2],await F({x:P,y:v})&&M(s)),i=requestAnimationFrame(x)}function B(p){var j;const{nodeLookup:F,multiSelectionActive:_,nodesDraggable:U,transform:P,snapGrid:v,snapToGrid:b,selectNodesOnDrag:y,onNodeDragStart:w,onSelectionDragStart:H,unselectNodesAndEdges:Y}=t();c=!0,(!y||!m)&&!_&&L&&((j=F.get(L))!=null&&j.selected||Y()),m&&y&&L&&(e==null||e(L));const k=cn(p.sourceEvent,{transform:P,snapGrid:v,snapToGrid:b,containerBounds:R});if(s=k,a=U_(F,U,k,L),a.size>0&&(n||w||!L&&H)){const[K,Q]=Po({nodeId:L,dragItems:a,nodeLookup:F});n==null||n(p.sourceEvent,a,K,Q),w==null||w(p.sourceEvent,K,Q),L||H==null||H(p.sourceEvent,Q)}}const g=Ol().clickDistance(D).on("start",p=>{const{domNode:F,nodeDragThreshold:_,transform:U,snapGrid:P,snapToGrid:v}=t();R=(F==null?void 0:F.getBoundingClientRect())||null,A=!1,d=!1,N=p.sourceEvent,_===0&&B(p),s=cn(p.sourceEvent,{transform:U,snapGrid:P,snapToGrid:v,containerBounds:R}),l=be(p.sourceEvent,R)}).on("drag",p=>{const{autoPanOnNodeDrag:F,transform:_,snapGrid:U,snapToGrid:P,nodeDragThreshold:v,nodeLookup:b}=t(),y=cn(p.sourceEvent,{transform:_,snapGrid:U,snapToGrid:P,containerBounds:R});if(N=p.sourceEvent,(p.sourceEvent.type==="touchmove"&&p.sourceEvent.touches.length>1||L&&!b.has(L))&&(A=!0),!A){if(!T&&F&&c&&(T=!0,x()),!c){const w=be(p.sourceEvent,R),H=w.x-l.x,Y=w.y-l.y;Math.sqrt(H*H+Y*Y)>v&&B(p)}(s.x!==y.xSnapped||s.y!==y.ySnapped)&&a&&c&&(l=be(p.sourceEvent,R),M(y))}}).on("end",p=>{if(!(!c||A)&&(T=!1,c=!1,cancelAnimationFrame(i),a.size>0)){const{nodeLookup:F,updateNodePositions:_,onNodeDragStop:U,onSelectionDragStop:P}=t();if(d&&(_(a,!1),d=!1),o||U||!L&&P){const[v,b]=Po({nodeId:L,dragItems:a,nodeLookup:F,dragging:!1});o==null||o(p.sourceEvent,a,v,b),U==null||U(p.sourceEvent,v,b),L||P==null||P(p.sourceEvent,b)}}}).filter(p=>{const F=p.target;return!p.button&&(!f||!ME(F,`.${f}`,C))&&(!O||ME(F,O,C))});S.call(g)}function u(){S==null||S.on(".drag",null)}return{update:I,destroy:u}}function B_(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())hn(o,Yt(s))>0&&r.push(s);return r}const G_=250;function H_(e,t,n,r){var a,T;let o=[],s=1/0;const i=B_(e,n,t+G_);for(const l of i){const R=[...((a=l.internals.handleBounds)==null?void 0:a.source)??[],...((T=l.internals.handleBounds)==null?void 0:T.target)??[]];for(const c of R){if(r.nodeId===c.nodeId&&r.type===c.type&&r.id===c.id)continue;const{x:S,y:A}=Ot(l,c,c.position,!0),d=Math.sqrt(Math.pow(S-e.x,2)+Math.pow(A-e.y,2));d>t||(d<s?(o=[{...c,x:S,y:A}],s=d):d===s&&o.push({...c,x:S,y:A}))}}if(!o.length)return null;if(o.length>1){const l=r.type==="source"?"target":"source";return o.find(R=>R.type===l)??o[0]}return o[0]}function rT(e,t,n,r,o,s=!1){var l,R,c;const i=r.get(e);if(!i)return null;const a=o==="strict"?(l=i.internals.handleBounds)==null?void 0:l[t]:[...((R=i.internals.handleBounds)==null?void 0:R.source)??[],...((c=i.internals.handleBounds)==null?void 0:c.target)??[]],T=(n?a==null?void 0:a.find(S=>S.id===n):a==null?void 0:a[0])??null;return T&&s?{...T,...Ot(i,T,T.position,!0)}:T}function oT(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function F_(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const sT=()=>!0;function w_(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:o,edgeUpdaterType:s,isTarget:i,domNode:a,nodeLookup:T,lib:l,autoPanOnConnect:R,flowId:c,panBy:S,cancelConnection:A,onConnectStart:d,onConnect:N,onConnectEnd:I,isValidConnection:u=sT,onReconnectEnd:f,updateConnection:O,getTransform:C,getFromHandle:m,autoPanSpeed:L,dragThreshold:D=1,handleDomNode:M}){const x=Xl(e.target);let B=0,g;const{x:p,y:F}=be(e),_=oT(s,M),U=a==null?void 0:a.getBoundingClientRect();let P=!1;if(!U||!_)return;const v=rT(o,_,r,T,t);if(!v)return;let b=be(e,U),y=!1,w=null,H=!1,Y=null;function k(){if(!R||!U)return;const[q,J]=Vl(b,U,L);S({x:q,y:J}),B=requestAnimationFrame(k)}const j={...v,nodeId:o,type:_,position:v.position},K=T.get(o);let X={inProgress:!0,isValid:null,from:Ot(K,j,Z.Left,!0),fromHandle:j,fromPosition:j.position,fromNode:K,to:b,toHandle:null,toPosition:IE[j.position],toNode:null,pointer:b};function $(){P=!0,O(X),d==null||d(e,{nodeId:o,handleId:r,handleType:_})}D===0&&$();function ee(q){if(!P){const{x:fe,y:Qe}=be(q),ke=fe-p,lt=Qe-F;if(!(ke*ke+lt*lt>D*D))return;$()}if(!m()||!j){oe(q);return}const J=C();b=be(q,U),g=H_(Pn(b,J,!1,[1,1]),n,T,j),y||(k(),y=!0);const te=iT(q,{handle:g,connectionMode:t,fromNodeId:o,fromHandleId:r,fromType:i?"target":"source",isValidConnection:u,doc:x,lib:l,flowId:c,nodeLookup:T});Y=te.handleDomNode,w=te.connection,H=F_(!!g,te.isValid);const Ee=T.get(o),Te=Ee?Ot(Ee,j,Z.Left,!0):X.from,ie={...X,from:Te,isValid:H,to:te.toHandle&&H?Lr({x:te.toHandle.x,y:te.toHandle.y},J):b,toHandle:te.toHandle,toPosition:H&&te.toHandle?te.toHandle.position:IE[j.position],toNode:te.toHandle?T.get(te.toHandle.nodeId):null,pointer:b};O(ie),X=ie}function oe(q){if(!("touches"in q&&q.touches.length>0)){if(P){(g||Y)&&w&&H&&(N==null||N(w));const{inProgress:J,...te}=X,Ee={...te,toPosition:X.toHandle?X.toPosition:null};I==null||I(q,Ee),s&&(f==null||f(q,Ee))}A(),cancelAnimationFrame(B),y=!1,H=!1,w=null,Y=null,x.removeEventListener("mousemove",ee),x.removeEventListener("mouseup",oe),x.removeEventListener("touchmove",ee),x.removeEventListener("touchend",oe)}}x.addEventListener("mousemove",ee),x.addEventListener("mouseup",oe),x.addEventListener("touchmove",ee),x.addEventListener("touchend",oe)}function iT(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:o,fromType:s,doc:i,lib:a,flowId:T,isValidConnection:l=sT,nodeLookup:R}){const c=s==="target",S=t?i.querySelector(`.${a}-flow__handle[data-id="${T}-${t==null?void 0:t.nodeId}-${t==null?void 0:t.id}-${t==null?void 0:t.type}"]`):null,{x:A,y:d}=be(e),N=i.elementFromPoint(A,d),I=N!=null&&N.classList.contains(`${a}-flow__handle`)?N:S,u={handleDomNode:I,isValid:!1,connection:null,toHandle:null};if(I){const f=oT(void 0,I),O=I.getAttribute("data-nodeid"),C=I.getAttribute("data-handleid"),m=I.classList.contains("connectable"),L=I.classList.contains("connectableend");if(!O||!f)return u;const D={source:c?O:r,sourceHandle:c?C:o,target:c?r:O,targetHandle:c?o:C};u.connection=D;const x=m&&L&&(n===Ft.Strict?c&&f==="source"||!c&&f==="target":O!==r||C!==o);u.isValid=x&&l(D),u.toHandle=rT(O,f,C,R,n,!0)}return u}const cs={onPointerDown:w_,isValid:iT};function Y_({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const o=De(e);function s({translateExtent:a,width:T,height:l,zoomStep:R=1,pannable:c=!0,zoomable:S=!0,inversePan:A=!1}){const d=O=>{if(O.sourceEvent.type!=="wheel"||!t)return;const C=n(),m=O.sourceEvent.ctrlKey&&Cn()?10:1,L=-O.sourceEvent.deltaY*(O.sourceEvent.deltaMode===1?.05:O.sourceEvent.deltaMode?1:.002)*R,D=C[2]*Math.pow(2,L*m);t.scaleTo(D)};let N=[0,0];const I=O=>{(O.sourceEvent.type==="mousedown"||O.sourceEvent.type==="touchstart")&&(N=[O.sourceEvent.clientX??O.sourceEvent.touches[0].clientX,O.sourceEvent.clientY??O.sourceEvent.touches[0].clientY])},u=O=>{const C=n();if(O.sourceEvent.type!=="mousemove"&&O.sourceEvent.type!=="touchmove"||!t)return;const m=[O.sourceEvent.clientX??O.sourceEvent.touches[0].clientX,O.sourceEvent.clientY??O.sourceEvent.touches[0].clientY],L=[m[0]-N[0],m[1]-N[1]];N=m;const D=r()*Math.max(C[2],Math.log(C[2]))*(A?-1:1),M={x:C[0]-L[0]*D,y:C[1]-L[1]*D},x=[[0,0],[T,l]];t.setViewportConstrained({x:M.x,y:M.y,zoom:C[2]},x,a)},f=bl().on("start",I).on("zoom",c?u:null).on("zoom.wheel",S?d:null);o.call(f,{})}function i(){o.on("zoom",null)}return{update:s,destroy:i,pointer:Pe}}const wr=e=>({x:e.x,y:e.y,zoom:e.k}),yo=({x:e,y:t,zoom:n})=>Gr.translate(e,t).scale(n),xt=(e,t)=>e.target.closest(`.${t}`),ET=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),V_=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Uo=(e,t=0,n=V_,r=()=>{})=>{const o=typeof t=="number"&&t>0;return o||r(),o?e.transition().duration(t).ease(n).on("end",r):e},aT=e=>{const t=e.ctrlKey&&Cn()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function W_({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:o,panOnScrollSpeed:s,zoomOnPinch:i,onPanZoomStart:a,onPanZoom:T,onPanZoomEnd:l}){return R=>{if(xt(R,t))return R.ctrlKey&&R.preventDefault(),!1;R.preventDefault(),R.stopImmediatePropagation();const c=n.property("__zoom").k||1;if(R.ctrlKey&&i){const I=Pe(R),u=aT(R),f=c*Math.pow(2,u);r.scaleTo(n,f,I,R);return}const S=R.deltaMode===1?20:1;let A=o===dt.Vertical?0:R.deltaX*S,d=o===dt.Horizontal?0:R.deltaY*S;!Cn()&&R.shiftKey&&o!==dt.Vertical&&(A=R.deltaY*S,d=0),r.translateBy(n,-(A/c)*s,-(d/c)*s,{internal:!0});const N=wr(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(T==null||T(R,N),e.panScrollTimeout=setTimeout(()=>{l==null||l(R,N),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,a==null||a(R,N))}}function k_({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,o){const s=r.type==="wheel",i=!t&&s&&!r.ctrlKey,a=xt(r,e);if(r.ctrlKey&&s&&a&&r.preventDefault(),i||a)return null;r.preventDefault(),n.call(this,r,o)}}function j_({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{var s,i,a;if((s=r.sourceEvent)!=null&&s.internal)return;const o=wr(r.transform);e.mouseButton=((i=r.sourceEvent)==null?void 0:i.button)||0,e.isZoomingOrPanning=!0,e.prevViewport=o,((a=r.sourceEvent)==null?void 0:a.type)==="mousedown"&&t(!0),n&&(n==null||n(r.sourceEvent,o))}}function X_({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:o}){return s=>{var i,a;e.usedRightMouseButton=!!(n&&ET(t,e.mouseButton??0)),(i=s.sourceEvent)!=null&&i.sync||r([s.transform.x,s.transform.y,s.transform.k]),o&&!((a=s.sourceEvent)!=null&&a.internal)&&(o==null||o(s.sourceEvent,wr(s.transform)))}}function $_({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:o,onPaneContextMenu:s}){return i=>{var a;if(!((a=i.sourceEvent)!=null&&a.internal)&&(e.isZoomingOrPanning=!1,s&&ET(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&s(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),o)){const T=wr(i.transform);e.prevViewport=T,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{o==null||o(i.sourceEvent,T)},n?150:0)}}}function K_({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:o,zoomOnDoubleClick:s,userSelectionActive:i,noWheelClassName:a,noPanClassName:T,lib:l,connectionInProgress:R}){return c=>{var I;const S=e||t,A=n&&c.ctrlKey,d=c.type==="wheel";if(c.button===1&&c.type==="mousedown"&&(xt(c,`${l}-flow__node`)||xt(c,`${l}-flow__edge`)))return!0;if(!r&&!S&&!o&&!s&&!n||i||R&&!d||xt(c,a)&&d||xt(c,T)&&(!d||o&&d&&!e)||!n&&c.ctrlKey&&d)return!1;if(!n&&c.type==="touchstart"&&((I=c.touches)==null?void 0:I.length)>1)return c.preventDefault(),!1;if(!S&&!o&&!A&&d||!r&&(c.type==="mousedown"||c.type==="touchstart")||Array.isArray(r)&&!r.includes(c.button)&&c.type==="mousedown")return!1;const N=Array.isArray(r)&&r.includes(c.button)||!c.button||c.button<=1;return(!c.ctrlKey||d)&&N}}function z_({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:o,onPanZoom:s,onPanZoomStart:i,onPanZoomEnd:a,onDraggingChange:T}){const l={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},R=e.getBoundingClientRect(),c=bl().scaleExtent([t,n]).translateExtent(r),S=De(e).call(c);f({x:o.x,y:o.y,zoom:wt(o.zoom,t,n)},[[0,0],[R.width,R.height]],r);const A=S.on("wheel.zoom"),d=S.on("dblclick.zoom");c.wheelDelta(aT);function N(g,p){return S?new Promise(F=>{c==null||c.interpolate((p==null?void 0:p.interpolate)==="linear"?Tn:or).transform(Uo(S,p==null?void 0:p.duration,p==null?void 0:p.ease,()=>F(!0)),g)}):Promise.resolve(!1)}function I({noWheelClassName:g,noPanClassName:p,onPaneContextMenu:F,userSelectionActive:_,panOnScroll:U,panOnDrag:P,panOnScrollMode:v,panOnScrollSpeed:b,preventScrolling:y,zoomOnPinch:w,zoomOnScroll:H,zoomOnDoubleClick:Y,zoomActivationKeyPressed:k,lib:j,onTransformChange:K,connectionInProgress:Q,paneClickDistance:X,selectionOnDrag:$}){_&&!l.isZoomingOrPanning&&u();const ee=U&&!k&&!_;c.clickDistance($?1/0:!Ue(X)||X<0?0:X);const oe=ee?W_({zoomPanValues:l,noWheelClassName:g,d3Selection:S,d3Zoom:c,panOnScrollMode:v,panOnScrollSpeed:b,zoomOnPinch:w,onPanZoomStart:i,onPanZoom:s,onPanZoomEnd:a}):k_({noWheelClassName:g,preventScrolling:y,d3ZoomHandler:A});if(S.on("wheel.zoom",oe,{passive:!1}),!_){const J=j_({zoomPanValues:l,onDraggingChange:T,onPanZoomStart:i});c.on("start",J);const te=X_({zoomPanValues:l,panOnDrag:P,onPaneContextMenu:!!F,onPanZoom:s,onTransformChange:K});c.on("zoom",te);const Ee=$_({zoomPanValues:l,panOnDrag:P,panOnScroll:U,onPaneContextMenu:F,onPanZoomEnd:a,onDraggingChange:T});c.on("end",Ee)}const q=K_({zoomActivationKeyPressed:k,panOnDrag:P,zoomOnScroll:H,panOnScroll:U,zoomOnDoubleClick:Y,zoomOnPinch:w,userSelectionActive:_,noPanClassName:p,noWheelClassName:g,lib:j,connectionInProgress:Q});c.filter(q),Y?S.on("dblclick.zoom",d):S.on("dblclick.zoom",null)}function u(){c.on("zoom",null)}async function f(g,p,F){const _=yo(g),U=c==null?void 0:c.constrain()(_,p,F);return U&&await N(U),new Promise(P=>P(U))}async function O(g,p){const F=yo(g);return await N(F,p),new Promise(_=>_(F))}function C(g){if(S){const p=yo(g),F=S.property("__zoom");(F.k!==g.zoom||F.x!==g.x||F.y!==g.y)&&(c==null||c.transform(S,p,null,{sync:!0}))}}function m(){const g=S?Ul(S.node()):{x:0,y:0,k:1};return{x:g.x,y:g.y,zoom:g.k}}function L(g,p){return S?new Promise(F=>{c==null||c.interpolate((p==null?void 0:p.interpolate)==="linear"?Tn:or).scaleTo(Uo(S,p==null?void 0:p.duration,p==null?void 0:p.ease,()=>F(!0)),g)}):Promise.resolve(!1)}function D(g,p){return S?new Promise(F=>{c==null||c.interpolate((p==null?void 0:p.interpolate)==="linear"?Tn:or).scaleBy(Uo(S,p==null?void 0:p.duration,p==null?void 0:p.ease,()=>F(!0)),g)}):Promise.resolve(!1)}function M(g){c==null||c.scaleExtent(g)}function x(g){c==null||c.translateExtent(g)}function B(g){const p=!Ue(g)||g<0?0:g;c==null||c.clickDistance(p)}return{update:I,destroy:u,setViewport:O,setViewportConstrained:f,getViewport:m,scaleTo:L,scaleBy:D,setScaleExtent:M,setTranslateExtent:x,syncViewport:C,setClickDistance:B}}var Wt;(function(e){e.Line="line",e.Handle="handle"})(Wt||(Wt={}));function J_({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:o,affectsY:s}){const i=e-t,a=n-r,T=[i>0?1:i<0?-1:0,a>0?1:a<0?-1:0];return i&&o&&(T[0]=T[0]*-1),a&&s&&(T[1]=T[1]*-1),T}function xE(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 et(e,t){return Math.max(0,t-e)}function tt(e,t){return Math.max(0,e-t)}function Kn(e,t,n){return Math.max(0,t-e,e-n)}function PE(e,t){return e?!t:t}function q_(e,t,n,r,o,s,i,a){let{affectsX:T,affectsY:l}=t;const{isHorizontal:R,isVertical:c}=t,S=R&&c,{xSnapped:A,ySnapped:d}=n,{minWidth:N,maxWidth:I,minHeight:u,maxHeight:f}=r,{x:O,y:C,width:m,height:L,aspectRatio:D}=e;let M=Math.floor(R?A-e.pointerX:0),x=Math.floor(c?d-e.pointerY:0);const B=m+(T?-M:M),g=L+(l?-x:x),p=-s[0]*m,F=-s[1]*L;let _=Kn(B,N,I),U=Kn(g,u,f);if(i){let b=0,y=0;T&&M<0?b=et(O+M+p,i[0][0]):!T&&M>0&&(b=tt(O+B+p,i[1][0])),l&&x<0?y=et(C+x+F,i[0][1]):!l&&x>0&&(y=tt(C+g+F,i[1][1])),_=Math.max(_,b),U=Math.max(U,y)}if(a){let b=0,y=0;T&&M>0?b=tt(O+M,a[0][0]):!T&&M<0&&(b=et(O+B,a[1][0])),l&&x>0?y=tt(C+x,a[0][1]):!l&&x<0&&(y=et(C+g,a[1][1])),_=Math.max(_,b),U=Math.max(U,y)}if(o){if(R){const b=Kn(B/D,u,f)*D;if(_=Math.max(_,b),i){let y=0;!T&&!l||T&&!l&&S?y=tt(C+F+B/D,i[1][1])*D:y=et(C+F+(T?M:-M)/D,i[0][1])*D,_=Math.max(_,y)}if(a){let y=0;!T&&!l||T&&!l&&S?y=et(C+B/D,a[1][1])*D:y=tt(C+(T?M:-M)/D,a[0][1])*D,_=Math.max(_,y)}}if(c){const b=Kn(g*D,N,I)/D;if(U=Math.max(U,b),i){let y=0;!T&&!l||l&&!T&&S?y=tt(O+g*D+p,i[1][0])/D:y=et(O+(l?x:-x)*D+p,i[0][0])/D,U=Math.max(U,y)}if(a){let y=0;!T&&!l||l&&!T&&S?y=et(O+g*D,a[1][0])/D:y=tt(O+(l?x:-x)*D,a[0][0])/D,U=Math.max(U,y)}}}x=x+(x<0?U:-U),M=M+(M<0?_:-_),o&&(S?B>g*D?x=(PE(T,l)?-M:M)/D:M=(PE(T,l)?-x:x)*D:R?(x=M/D,l=T):(M=x*D,T=l));const P=T?O+M:O,v=l?C+x:C;return{width:m+(T?-M:M),height:L+(l?-x:x),x:s[0]*M*(T?-1:1)+P,y:s[1]*x*(l?-1:1)+v}}const lT={width:0,height:0,x:0,y:0},Z_={...lT,pointerX:0,pointerY:0,aspectRatio:1};function Q_(e){return[[0,0],[e.measured.width,e.measured.height]]}function em(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,a=n[0]*s,T=n[1]*i;return[[r-a,o-T],[r+s-a,o+i-T]]}function tm({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:o}){const s=De(e);let i={controlDirection:xE("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function a({controlPosition:l,boundaries:R,keepAspectRatio:c,resizeDirection:S,onResizeStart:A,onResize:d,onResizeEnd:N,shouldResize:I}){let u={...lT},f={...Z_};i={boundaries:R,resizeDirection:S,keepAspectRatio:c,controlDirection:xE(l)};let O,C=null,m=[],L,D,M,x=!1;const B=Ol().on("start",g=>{const{nodeLookup:p,transform:F,snapGrid:_,snapToGrid:U,nodeOrigin:P,paneDomNode:v}=n();if(O=p.get(t),!O)return;C=(v==null?void 0:v.getBoundingClientRect())??null;const{xSnapped:b,ySnapped:y}=cn(g.sourceEvent,{transform:F,snapGrid:_,snapToGrid:U,containerBounds:C});u={width:O.measured.width??0,height:O.measured.height??0,x:O.position.x??0,y:O.position.y??0},f={...u,pointerX:b,pointerY:y,aspectRatio:u.width/u.height},L=void 0,O.parentId&&(O.extent==="parent"||O.expandParent)&&(L=p.get(O.parentId),D=L&&O.extent==="parent"?Q_(L):void 0),m=[],M=void 0;for(const[w,H]of p)if(H.parentId===t&&(m.push({id:w,position:{...H.position},extent:H.extent}),H.extent==="parent"||H.expandParent)){const Y=em(H,O,H.origin??P);M?M=[[Math.min(Y[0][0],M[0][0]),Math.min(Y[0][1],M[0][1])],[Math.max(Y[1][0],M[1][0]),Math.max(Y[1][1],M[1][1])]]:M=Y}A==null||A(g,{...u})}).on("drag",g=>{const{transform:p,snapGrid:F,snapToGrid:_,nodeOrigin:U}=n(),P=cn(g.sourceEvent,{transform:p,snapGrid:F,snapToGrid:_,containerBounds:C}),v=[];if(!O)return;const{x:b,y,width:w,height:H}=u,Y={},k=O.origin??U,{width:j,height:K,x:Q,y:X}=q_(f,i.controlDirection,P,i.boundaries,i.keepAspectRatio,k,D,M),$=j!==w,ee=K!==H,oe=Q!==b&&$,q=X!==y&ⅇif(!oe&&!q&&!$&&!ee)return;if((oe||q||k[0]===1||k[1]===1)&&(Y.x=oe?Q:u.x,Y.y=q?X:u.y,u.x=Y.x,u.y=Y.y,m.length>0)){const Te=Q-b,ie=X-y;for(const fe of m)fe.position={x:fe.position.x-Te+k[0]*(j-w),y:fe.position.y-ie+k[1]*(K-H)},v.push(fe)}if(($||ee)&&(Y.width=$&&(!i.resizeDirection||i.resizeDirection==="horizontal")?j:u.width,Y.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?K:u.height,u.width=Y.width,u.height=Y.height),L&&O.expandParent){const Te=k[0]*(Y.width??0);Y.x&&Y.x<Te&&(u.x=Te,f.x=f.x-(Y.x-Te));const ie=k[1]*(Y.height??0);Y.y&&Y.y<ie&&(u.y=ie,f.y=f.y-(Y.y-ie))}const J=J_({width:u.width,prevWidth:w,height:u.height,prevHeight:H,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),te={...u,direction:J};(I==null?void 0:I(g,te))!==!1&&(x=!0,d==null||d(g,te),r(Y,v))}).on("end",g=>{x&&(N==null||N(g,{...u}),o==null||o({...u}),x=!1)});s.call(B)}function T(){s.on(".drag",null)}return{update:a,destroy:T}}var bo={exports:{}},vo={},Bo={exports:{}},Go={};/**
|
|
482
|
-
* @license React
|
|
483
|
-
* use-sync-external-store-shim.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 yE;function nm(){if(yE)return Go;yE=1;var e=gr();function t(c,S){return c===S&&(c!==0||1/c===1/S)||c!==c&&S!==S}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,s=e.useLayoutEffect,i=e.useDebugValue;function a(c,S){var A=S(),d=r({inst:{value:A,getSnapshot:S}}),N=d[0].inst,I=d[1];return s(function(){N.value=A,N.getSnapshot=S,T(N)&&I({inst:N})},[c,A,S]),o(function(){return T(N)&&I({inst:N}),c(function(){T(N)&&I({inst:N})})},[c]),i(A),A}function T(c){var S=c.getSnapshot;c=c.value;try{var A=S();return!n(c,A)}catch{return!0}}function l(c,S){return S()}var R=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l:a;return Go.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:R,Go}var UE;function rm(){return UE||(UE=1,Bo.exports=nm()),Bo.exports}/**
|
|
490
|
-
* @license React
|
|
491
|
-
* use-sync-external-store-shim/with-selector.production.js
|
|
492
|
-
*
|
|
493
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
494
|
-
*
|
|
495
|
-
* This source code is licensed under the MIT license found in the
|
|
496
|
-
* LICENSE file in the root directory of this source tree.
|
|
497
|
-
*/var bE;function om(){if(bE)return vo;bE=1;var e=gr(),t=rm();function n(l,R){return l===R&&(l!==0||1/l===1/R)||l!==l&&R!==R}var r=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,s=e.useRef,i=e.useEffect,a=e.useMemo,T=e.useDebugValue;return vo.useSyncExternalStoreWithSelector=function(l,R,c,S,A){var d=s(null);if(d.current===null){var N={hasValue:!1,value:null};d.current=N}else N=d.current;d=a(function(){function u(L){if(!f){if(f=!0,O=L,L=S(L),A!==void 0&&N.hasValue){var D=N.value;if(A(D,L))return C=D}return C=L}if(D=C,r(O,L))return D;var M=S(L);return A!==void 0&&A(D,M)?(O=L,D):(O=L,C=M)}var f=!1,O,C,m=c===void 0?null:c;return[function(){return u(R())},m===null?void 0:function(){return u(m())}]},[R,c,S,A]);var I=o(l,d[0],d[1]);return i(function(){N.hasValue=!0,N.value=I},[I]),T(I),I},vo}var vE;function sm(){return vE||(vE=1,bo.exports=om()),bo.exports}var im=sm();const Em=As(im),am={},BE=e=>{let t;const n=new Set,r=(R,c)=>{const S=typeof R=="function"?R(t):R;if(!Object.is(S,t)){const A=t;t=c??(typeof S!="object"||S===null)?S:Object.assign({},t,S),n.forEach(d=>d(t,A))}},o=()=>t,T={setState:r,getState:o,getInitialState:()=>l,subscribe:R=>(n.add(R),()=>n.delete(R)),destroy:()=>{(am?"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()}},l=t=e(r,o,T);return T},lm=e=>e?BE(e):BE,{useDebugValue:Tm}=Bt,{useSyncExternalStoreWithSelector:cm}=Em,Rm=e=>e;function TT(e,t=Rm,n){const r=cm(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return Tm(r),r}const GE=(e,t)=>{const n=lm(e),r=(o,s=t)=>TT(n,o,s);return Object.assign(r,n),r},Sm=(e,t)=>e?GE(e,t):GE;function ce(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}fa();const Yr=h.createContext(null),Am=Yr.Provider,cT=Ve.error001();function se(e,t){const n=h.useContext(Yr);if(n===null)throw new Error(cT);return TT(n,e,t)}function Re(){const e=h.useContext(Yr);if(e===null)throw new Error(cT);return h.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const HE={display:"none"},dm={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},RT="react-flow__node-desc",ST="react-flow__edge-desc",um="react-flow__aria-live",Im=e=>e.ariaLiveMessage,Nm=e=>e.ariaLabelConfig;function Om({rfId:e}){const t=se(Im);return E.jsx("div",{id:`${um}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:dm,children:t})}function fm({rfId:e,disableKeyboardA11y:t}){const n=se(Nm);return E.jsxs(E.Fragment,{children:[E.jsx("div",{id:`${RT}-${e}`,style:HE,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),E.jsx("div",{id:`${ST}-${e}`,style:HE,children:n["edge.a11yDescription.default"]}),!t&&E.jsx(Om,{rfId:e})]})}const yn=h.forwardRef(({position:e="top-left",children:t,className:n,style:r,...o},s)=>{const i=`${e}`.split("-");return E.jsx("div",{className:Se(["react-flow__panel",n,...i]),style:r,ref:s,...o,children:t})});yn.displayName="Panel";function hm({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:E.jsx(yn,{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:E.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const Cm=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}},zn=e=>e.id;function Lm(e,t){return ce(e.selectedNodes.map(zn),t.selectedNodes.map(zn))&&ce(e.selectedEdges.map(zn),t.selectedEdges.map(zn))}function pm({onSelectionChange:e}){const t=Re(),{selectedNodes:n,selectedEdges:r}=se(Cm,Lm);return h.useEffect(()=>{const o={nodes:n,edges:r};e==null||e(o),t.getState().onSelectionChangeHandlers.forEach(s=>s(o))},[n,r,e]),null}const _m=e=>!!e.onSelectionChangeHandlers;function mm({onSelectionChange:e}){const t=se(_m);return e||t?E.jsx(pm,{onSelectionChange:e}):null}const AT=[0,0],Dm={x:0,y:0,zoom:1},gm=["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"],FE=[...gm,"rfId"],Mm=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}),wE={translateExtent:Nn,nodeOrigin:AT,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function xm(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:o,setTranslateExtent:s,setNodeExtent:i,reset:a,setDefaultNodesAndEdges:T}=se(Mm,ce),l=Re();h.useEffect(()=>(T(e.defaultNodes,e.defaultEdges),()=>{R.current=wE,a()}),[]);const R=h.useRef(wE);return h.useEffect(()=>{for(const c of FE){const S=e[c],A=R.current[c];S!==A&&(typeof e[c]>"u"||(c==="nodes"?t(S):c==="edges"?n(S):c==="minZoom"?r(S):c==="maxZoom"?o(S):c==="translateExtent"?s(S):c==="nodeExtent"?i(S):c==="ariaLabelConfig"?l.setState({ariaLabelConfig:S_(S)}):c==="fitView"?l.setState({fitViewQueued:S}):c==="fitViewOptions"?l.setState({fitViewOptions:S}):l.setState({[c]:S})))}R.current=e},FE.map(c=>e[c])),null}function YE(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function Pm(e){var r;const[t,n]=h.useState(e==="system"?null:e);return h.useEffect(()=>{if(e!=="system"){n(e);return}const o=YE(),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=YE())!=null&&r.matches?"dark":"light"}const VE=typeof document<"u"?document:null;function Ln(e=null,t={target:VE,actInsideInputWithModifier:!0}){const[n,r]=h.useState(!1),o=h.useRef(!1),s=h.useRef(new Set([])),[i,a]=h.useMemo(()=>{if(e!==null){const l=(Array.isArray(e)?e:[e]).filter(c=>typeof c=="string").map(c=>c.replace("+",`
|
|
498
|
-
`).replace(`
|
|
499
|
-
|
|
500
|
-
`,`
|
|
501
|
-
+`).split(`
|
|
502
|
-
`)),R=l.reduce((c,S)=>c.concat(...S),[]);return[l,R]}return[[],[]]},[e]);return h.useEffect(()=>{const T=(t==null?void 0:t.target)??VE,l=(t==null?void 0:t.actInsideInputWithModifier)??!0;if(e!==null){const R=A=>{var I,u;if(o.current=A.ctrlKey||A.metaKey||A.shiftKey||A.altKey,(!o.current||o.current&&!l)&&$l(A))return!1;const N=kE(A.code,a);if(s.current.add(A[N]),WE(i,s.current,!1)){const f=((u=(I=A.composedPath)==null?void 0:I.call(A))==null?void 0:u[0])||A.target,O=(f==null?void 0:f.nodeName)==="BUTTON"||(f==null?void 0:f.nodeName)==="A";t.preventDefault!==!1&&(o.current||!O)&&A.preventDefault(),r(!0)}},c=A=>{const d=kE(A.code,a);WE(i,s.current,!0)?(r(!1),s.current.clear()):s.current.delete(A[d]),A.key==="Meta"&&s.current.clear(),o.current=!1},S=()=>{s.current.clear(),r(!1)};return T==null||T.addEventListener("keydown",R),T==null||T.addEventListener("keyup",c),window.addEventListener("blur",S),window.addEventListener("contextmenu",S),()=>{T==null||T.removeEventListener("keydown",R),T==null||T.removeEventListener("keyup",c),window.removeEventListener("blur",S),window.removeEventListener("contextmenu",S)}}},[e,r]),n}function WE(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(o=>t.has(o)))}function kE(e,t){return t.includes(e)?"code":"key"}const ym=()=>{const e=Re();return h.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:a}=e.getState(),T=Ps(t,r,o,s,i,(n==null?void 0:n.padding)??.1);return a?(await a.setViewport(T,{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:a,y:T}=i.getBoundingClientRect(),l={x:t.x-a,y:t.y-T},R=n.snapGrid??o,c=n.snapToGrid??s;return Pn(l,r,c,R)},flowToScreenPosition:t=>{const{transform:n,domNode:r}=e.getState();if(!r)return t;const{x:o,y:s}=r.getBoundingClientRect(),i=Lr(t,n);return{x:i.x+o,y:i.y+s}}}),[])};function dT(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 a={...s};for(const T of i)Um(T,a);n.push(a)}return o.length&&o.forEach(s=>{s.index!==void 0?n.splice(s.index,0,{...s.item}):n.push({...s.item})}),n}function Um(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 uT(e,t){return dT(e,t)}function IT(e,t){return dT(e,t)}function ct(e,t){return{id:e,type:"select",selected:t}}function Pt(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(ct(s.id,i)))}return r}function jE({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 a=t.get(i.id),T=((o=a==null?void 0:a.internals)==null?void 0:o.userNode)??a;T!==void 0&&T!==i&&n.push({id:i.id,item:i,type:"replace"}),T===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 XE(e){return{id:e.id,type:"remove"}}const $E=e=>r_(e),bm=e=>Fl(e);function NT(e){return h.forwardRef(e)}const vm=typeof window<"u"?h.useLayoutEffect:h.useEffect;function KE(e){const[t,n]=h.useState(BigInt(0)),[r]=h.useState(()=>Bm(()=>n(o=>o+BigInt(1))));return vm(()=>{const o=r.get();o.length&&(e(o),r.reset())},[t]),r}function Bm(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}const OT=h.createContext(null);function Gm({children:e}){const t=Re(),n=h.useCallback(a=>{const{nodes:T=[],setNodes:l,hasDefaultNodes:R,onNodesChange:c,nodeLookup:S,fitViewQueued:A,onNodesChangeMiddlewareMap:d}=t.getState();let N=T;for(const u of a)N=typeof u=="function"?u(N):u;let I=jE({items:N,lookup:S});for(const u of d.values())I=u(I);R&&l(N),I.length>0?c==null||c(I):A&&window.requestAnimationFrame(()=>{const{fitViewQueued:u,nodes:f,setNodes:O}=t.getState();u&&O(f)})},[]),r=KE(n),o=h.useCallback(a=>{const{edges:T=[],setEdges:l,hasDefaultEdges:R,onEdgesChange:c,edgeLookup:S}=t.getState();let A=T;for(const d of a)A=typeof d=="function"?d(A):d;R?l(A):c&&c(jE({items:A,lookup:S}))},[]),s=KE(o),i=h.useMemo(()=>({nodeQueue:r,edgeQueue:s}),[]);return E.jsx(OT.Provider,{value:i,children:e})}function Hm(){const e=h.useContext(OT);if(!e)throw new Error("useBatchContext must be used within a BatchProvider");return e}const Fm=e=>!!e.panZoom;function Hs(){const e=ym(),t=Re(),n=Hm(),r=se(Fm),o=h.useMemo(()=>{const s=c=>t.getState().nodeLookup.get(c),i=c=>{n.nodeQueue.push(c)},a=c=>{n.edgeQueue.push(c)},T=c=>{var u,f;const{nodeLookup:S,nodeOrigin:A}=t.getState(),d=$E(c)?c:S.get(c.id),N=d.parentId?jl(d.position,d.measured,d.parentId,S,A):d.position,I={...d,position:N,width:((u=d.measured)==null?void 0:u.width)??d.width,height:((f=d.measured)==null?void 0:f.height)??d.height};return Yt(I)},l=(c,S,A={replace:!1})=>{i(d=>d.map(N=>{if(N.id===c){const I=typeof S=="function"?S(N):S;return A.replace&&$E(I)?I:{...N,...I}}return N}))},R=(c,S,A={replace:!1})=>{a(d=>d.map(N=>{if(N.id===c){const I=typeof S=="function"?S(N):S;return A.replace&&bm(I)?I:{...N,...I}}return N}))};return{getNodes:()=>t.getState().nodes.map(c=>({...c})),getNode:c=>{var S;return(S=s(c))==null?void 0:S.internals.userNode},getInternalNode:s,getEdges:()=>{const{edges:c=[]}=t.getState();return c.map(S=>({...S}))},getEdge:c=>t.getState().edgeLookup.get(c),setNodes:i,setEdges:a,addNodes:c=>{const S=Array.isArray(c)?c:[c];n.nodeQueue.push(A=>[...A,...S])},addEdges:c=>{const S=Array.isArray(c)?c:[c];n.edgeQueue.push(A=>[...A,...S])},toObject:()=>{const{nodes:c=[],edges:S=[],transform:A}=t.getState(),[d,N,I]=A;return{nodes:c.map(u=>({...u})),edges:S.map(u=>({...u})),viewport:{x:d,y:N,zoom:I}}},deleteElements:async({nodes:c=[],edges:S=[]})=>{const{nodes:A,edges:d,onNodesDelete:N,onEdgesDelete:I,triggerNodeChanges:u,triggerEdgeChanges:f,onDelete:O,onBeforeDelete:C}=t.getState(),{nodes:m,edges:L}=await a_({nodesToRemove:c,edgesToRemove:S,nodes:A,edges:d,onBeforeDelete:C}),D=L.length>0,M=m.length>0;if(D){const x=L.map(XE);I==null||I(L),f(x)}if(M){const x=m.map(XE);N==null||N(m),u(x)}return(M||D)&&(O==null||O({nodes:m,edges:L})),{deletedNodes:m,deletedEdges:L}},getIntersectingNodes:(c,S=!0,A)=>{const d=OE(c),N=d?c:T(c),I=A!==void 0;return N?(A||t.getState().nodes).filter(u=>{const f=t.getState().nodeLookup.get(u.id);if(f&&!d&&(u.id===c.id||!f.internals.positionAbsolute))return!1;const O=Yt(I?u:f),C=hn(O,N);return S&&C>0||C>=O.width*O.height||C>=N.width*N.height}):[]},isNodeIntersecting:(c,S,A=!0)=>{const N=OE(c)?c:T(c);if(!N)return!1;const I=hn(N,S);return A&&I>0||I>=S.width*S.height||I>=N.width*N.height},updateNode:l,updateNodeData:(c,S,A={replace:!1})=>{l(c,d=>{const N=typeof S=="function"?S(d):S;return A.replace?{...d,data:N}:{...d,data:{...d.data,...N}}},A)},updateEdge:R,updateEdgeData:(c,S,A={replace:!1})=>{R(c,d=>{const N=typeof S=="function"?S(d):S;return A.replace?{...d,data:N}:{...d,data:{...d.data,...N}}},A)},getNodesBounds:c=>{const{nodeLookup:S,nodeOrigin:A}=t.getState();return o_(c,{nodeLookup:S,nodeOrigin:A})},getHandleConnections:({type:c,id:S,nodeId:A})=>{var d;return Array.from(((d=t.getState().connectionLookup.get(`${A}-${c}${S?`-${S}`:""}`))==null?void 0:d.values())??[])},getNodeConnections:({type:c,handleId:S,nodeId:A})=>{var d;return Array.from(((d=t.getState().connectionLookup.get(`${A}${c?S?`-${c}-${S}`:`-${c}`:""}`))==null?void 0:d.values())??[])},fitView:async c=>{const S=t.getState().fitViewResolver??R_();return t.setState({fitViewQueued:!0,fitViewOptions:c,fitViewResolver:S}),n.nodeQueue.push(A=>[...A]),S.promise}}},[]);return h.useMemo(()=>({...o,...e,viewportInitialized:r}),[r])}const zE=e=>e.selected,wm=typeof window<"u"?window:void 0;function Ym({deleteKeyCode:e,multiSelectionKeyCode:t}){const n=Re(),{deleteElements:r}=Hs(),o=Ln(e,{actInsideInputWithModifier:!1}),s=Ln(t,{target:wm});h.useEffect(()=>{if(o){const{edges:i,nodes:a}=n.getState();r({nodes:a.filter(zE),edges:i.filter(zE)}),n.setState({nodesSelectionActive:!1})}},[o]),h.useEffect(()=>{n.setState({multiSelectionActive:s})},[s])}function Vm(e){const t=Re();h.useEffect(()=>{const n=()=>{var o,s,i,a;if(!e.current||!(((s=(o=e.current).checkVisibility)==null?void 0:s.call(o))??!0))return!1;const r=ys(e.current);(r.height===0||r.width===0)&&((a=(i=t.getState()).onError)==null||a.call(i,"004",Ve.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 Vr={position:"absolute",width:"100%",height:"100%",top:0,left:0},Wm=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function km({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panOnScrollSpeed:o=.5,panOnScrollMode:s=dt.Free,zoomOnDoubleClick:i=!0,panOnDrag:a=!0,defaultViewport:T,translateExtent:l,minZoom:R,maxZoom:c,zoomActivationKeyCode:S,preventScrolling:A=!0,children:d,noWheelClassName:N,noPanClassName:I,onViewportChange:u,isControlledViewport:f,paneClickDistance:O,selectionOnDrag:C}){const m=Re(),L=h.useRef(null),{userSelectionActive:D,lib:M,connectionInProgress:x}=se(Wm,ce),B=Ln(S),g=h.useRef();Vm(L);const p=h.useCallback(F=>{u==null||u({x:F[0],y:F[1],zoom:F[2]}),f||m.setState({transform:F})},[u,f]);return h.useEffect(()=>{if(L.current){g.current=z_({domNode:L.current,minZoom:R,maxZoom:c,translateExtent:l,viewport:T,onDraggingChange:P=>m.setState(v=>v.paneDragging===P?v:{paneDragging:P}),onPanZoomStart:(P,v)=>{const{onViewportChangeStart:b,onMoveStart:y}=m.getState();y==null||y(P,v),b==null||b(v)},onPanZoom:(P,v)=>{const{onViewportChange:b,onMove:y}=m.getState();y==null||y(P,v),b==null||b(v)},onPanZoomEnd:(P,v)=>{const{onViewportChangeEnd:b,onMoveEnd:y}=m.getState();y==null||y(P,v),b==null||b(v)}});const{x:F,y:_,zoom:U}=g.current.getViewport();return m.setState({panZoom:g.current,transform:[F,_,U],domNode:L.current.closest(".react-flow")}),()=>{var P;(P=g.current)==null||P.destroy()}}},[]),h.useEffect(()=>{var F;(F=g.current)==null||F.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panOnScrollSpeed:o,panOnScrollMode:s,zoomOnDoubleClick:i,panOnDrag:a,zoomActivationKeyPressed:B,preventScrolling:A,noPanClassName:I,userSelectionActive:D,noWheelClassName:N,lib:M,onTransformChange:p,connectionInProgress:x,selectionOnDrag:C,paneClickDistance:O})},[e,t,n,r,o,s,i,a,B,A,I,D,N,M,p,x,C,O]),E.jsx("div",{className:"react-flow__renderer",ref:L,style:Vr,children:d})}const jm=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function Xm(){const{userSelectionActive:e,userSelectionRect:t}=se(jm,ce);return e&&t?E.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 Ho=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},$m=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging});function Km({isSelecting:e,selectionKeyPressed:t,selectionMode:n=On.Full,panOnDrag:r,paneClickDistance:o,selectionOnDrag:s,onSelectionStart:i,onSelectionEnd:a,onPaneClick:T,onPaneContextMenu:l,onPaneScroll:R,onPaneMouseEnter:c,onPaneMouseMove:S,onPaneMouseLeave:A,children:d}){const N=Re(),{userSelectionActive:I,elementsSelectable:u,dragging:f,connectionInProgress:O}=se($m,ce),C=u&&(e||I),m=h.useRef(null),L=h.useRef(),D=h.useRef(new Set),M=h.useRef(new Set),x=h.useRef(!1),B=b=>{if(x.current||O){x.current=!1;return}T==null||T(b),N.getState().resetSelectedElements(),N.setState({nodesSelectionActive:!1})},g=b=>{if(Array.isArray(r)&&(r!=null&&r.includes(2))){b.preventDefault();return}l==null||l(b)},p=R?b=>R(b):void 0,F=b=>{x.current&&(b.stopPropagation(),x.current=!1)},_=b=>{var K,Q;const{domNode:y}=N.getState();if(L.current=y==null?void 0:y.getBoundingClientRect(),!L.current)return;const w=b.target===m.current;if(!w&&!!b.target.closest(".nokey")||!e||!(s&&w||t)||b.button!==0||!b.isPrimary)return;(Q=(K=b.target)==null?void 0:K.setPointerCapture)==null||Q.call(K,b.pointerId),x.current=!1;const{x:k,y:j}=be(b.nativeEvent,L.current);N.setState({userSelectionRect:{width:0,height:0,startX:k,startY:j,x:k,y:j}}),w||(b.stopPropagation(),b.preventDefault())},U=b=>{const{userSelectionRect:y,transform:w,nodeLookup:H,edgeLookup:Y,connectionLookup:k,triggerNodeChanges:j,triggerEdgeChanges:K,defaultEdgeOptions:Q,resetSelectedElements:X}=N.getState();if(!L.current||!y)return;const{x:$,y:ee}=be(b.nativeEvent,L.current),{startX:oe,startY:q}=y;if(!x.current){const ie=t?0:o;if(Math.hypot($-oe,ee-q)<=ie)return;X(),i==null||i(b)}x.current=!0;const J={startX:oe,startY:q,x:$<oe?$:oe,y:ee<q?ee:q,width:Math.abs($-oe),height:Math.abs(ee-q)},te=D.current,Ee=M.current;D.current=new Set(xs(H,J,w,n===On.Partial,!0).map(ie=>ie.id)),M.current=new Set;const Te=(Q==null?void 0:Q.selectable)??!0;for(const ie of D.current){const fe=k.get(ie);if(fe)for(const{edgeId:Qe}of fe.values()){const ke=Y.get(Qe);ke&&(ke.selectable??Te)&&M.current.add(Qe)}}if(!fE(te,D.current)){const ie=Pt(H,D.current,!0);j(ie)}if(!fE(Ee,M.current)){const ie=Pt(Y,M.current);K(ie)}N.setState({userSelectionRect:J,userSelectionActive:!0,nodesSelectionActive:!1})},P=b=>{var y,w;b.button===0&&((w=(y=b.target)==null?void 0:y.releasePointerCapture)==null||w.call(y,b.pointerId),!I&&b.target===m.current&&N.getState().userSelectionRect&&(B==null||B(b)),N.setState({userSelectionActive:!1,userSelectionRect:null}),x.current&&(a==null||a(b),N.setState({nodesSelectionActive:D.current.size>0})))},v=r===!0||Array.isArray(r)&&r.includes(0);return E.jsxs("div",{className:Se(["react-flow__pane",{draggable:v,dragging:f,selection:e}]),onClick:C?void 0:Ho(B,m),onContextMenu:Ho(g,m),onWheel:Ho(p,m),onPointerEnter:C?void 0:c,onPointerMove:C?U:S,onPointerUp:C?P:void 0,onPointerDownCapture:C?_:void 0,onClickCapture:C?F:void 0,onPointerLeave:A,ref:m,style:Vr,children:[d,E.jsx(Xm,{})]})}function Rs({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:o,unselectNodesAndEdges:s,multiSelectionActive:i,nodeLookup:a,onError:T}=t.getState(),l=a.get(e);if(!l){T==null||T("012",Ve.error012(e));return}t.setState({nodesSelectionActive:!1}),l.selected?(n||l.selected&&i)&&(s({nodes:[l],edges:[]}),requestAnimationFrame(()=>{var R;return(R=r==null?void 0:r.current)==null?void 0:R.blur()})):o([e])}function fT({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:o,isSelectable:s,nodeClickDistance:i}){const a=Re(),[T,l]=h.useState(!1),R=h.useRef();return h.useEffect(()=>{R.current=v_({getStoreItems:()=>a.getState(),onNodeMouseDown:c=>{Rs({id:c,store:a,nodeRef:e})},onDragStart:()=>{l(!0)},onDragStop:()=>{l(!1)}})},[]),h.useEffect(()=>{if(!(t||!e.current||!R.current))return R.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:s,nodeId:o,nodeClickDistance:i}),()=>{var c;(c=R.current)==null||c.destroy()}},[n,r,t,s,e,o,i]),T}const zm=e=>t=>t.selected&&(t.draggable||e&&typeof t.draggable>"u");function hT(){const e=Re();return h.useCallback(n=>{const{nodeExtent:r,snapToGrid:o,snapGrid:s,nodesDraggable:i,onError:a,updateNodePositions:T,nodeLookup:l,nodeOrigin:R}=e.getState(),c=new Map,S=zm(i),A=o?s[0]:5,d=o?s[1]:5,N=n.direction.x*A*n.factor,I=n.direction.y*d*n.factor;for(const[,u]of l){if(!S(u))continue;let f={x:u.internals.positionAbsolute.x+N,y:u.internals.positionAbsolute.y+I};o&&(f=xn(f,s));const{position:O,positionAbsolute:C}=wl({nodeId:u.id,nextPosition:f,nodeLookup:l,nodeExtent:r,nodeOrigin:R,onError:a});u.position=O,u.internals.positionAbsolute=C,c.set(u.id,u)}T(c)},[])}const Fs=h.createContext(null),Jm=Fs.Provider;Fs.Consumer;const CT=()=>h.useContext(Fs),qm=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),Zm=(e,t,n)=>r=>{const{connectionClickStartHandle:o,connectionMode:s,connection:i}=r,{fromHandle:a,toHandle:T,isValid:l}=i,R=(T==null?void 0:T.nodeId)===e&&(T==null?void 0:T.id)===t&&(T==null?void 0:T.type)===n;return{connectingFrom:(a==null?void 0:a.nodeId)===e&&(a==null?void 0:a.id)===t&&(a==null?void 0:a.type)===n,connectingTo:R,clickConnecting:(o==null?void 0:o.nodeId)===e&&(o==null?void 0:o.id)===t&&(o==null?void 0:o.type)===n,isPossibleEndHandle:s===Ft.Strict?(a==null?void 0:a.type)!==n:e!==(a==null?void 0:a.nodeId)||t!==(a==null?void 0:a.id),connectionInProcess:!!a,clickConnectionInProcess:!!o,valid:R&&l}};function Qm({type:e="source",position:t=Z.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:o=!0,isConnectableEnd:s=!0,id:i,onConnect:a,children:T,className:l,onMouseDown:R,onTouchStart:c,...S},A){var U,P;const d=i||null,N=e==="target",I=Re(),u=CT(),{connectOnClick:f,noPanClassName:O,rfId:C}=se(qm,ce),{connectingFrom:m,connectingTo:L,clickConnecting:D,isPossibleEndHandle:M,connectionInProcess:x,clickConnectionInProcess:B,valid:g}=se(Zm(u,d,e),ce);u||(P=(U=I.getState()).onError)==null||P.call(U,"010",Ve.error010());const p=v=>{const{defaultEdgeOptions:b,onConnect:y,hasDefaultEdges:w}=I.getState(),H={...b,...v};if(w){const{edges:Y,setEdges:k}=I.getState();k(O_(H,Y))}y==null||y(H),a==null||a(H)},F=v=>{if(!u)return;const b=Kl(v.nativeEvent);if(o&&(b&&v.button===0||!b)){const y=I.getState();cs.onPointerDown(v.nativeEvent,{handleDomNode:v.currentTarget,autoPanOnConnect:y.autoPanOnConnect,connectionMode:y.connectionMode,connectionRadius:y.connectionRadius,domNode:y.domNode,nodeLookup:y.nodeLookup,lib:y.lib,isTarget:N,handleId:d,nodeId:u,flowId:y.rfId,panBy:y.panBy,cancelConnection:y.cancelConnection,onConnectStart:y.onConnectStart,onConnectEnd:(...w)=>{var H,Y;return(Y=(H=I.getState()).onConnectEnd)==null?void 0:Y.call(H,...w)},updateConnection:y.updateConnection,onConnect:p,isValidConnection:n||((...w)=>{var H,Y;return((Y=(H=I.getState()).isValidConnection)==null?void 0:Y.call(H,...w))??!0}),getTransform:()=>I.getState().transform,getFromHandle:()=>I.getState().connection.fromHandle,autoPanSpeed:y.autoPanSpeed,dragThreshold:y.connectionDragThreshold})}b?R==null||R(v):c==null||c(v)},_=v=>{const{onClickConnectStart:b,onClickConnectEnd:y,connectionClickStartHandle:w,connectionMode:H,isValidConnection:Y,lib:k,rfId:j,nodeLookup:K,connection:Q}=I.getState();if(!u||!w&&!o)return;if(!w){b==null||b(v.nativeEvent,{nodeId:u,handleId:d,handleType:e}),I.setState({connectionClickStartHandle:{nodeId:u,type:e,id:d}});return}const X=Xl(v.target),$=n||Y,{connection:ee,isValid:oe}=cs.isValid(v.nativeEvent,{handle:{nodeId:u,id:d,type:e},connectionMode:H,fromNodeId:w.nodeId,fromHandleId:w.id||null,fromType:w.type,isValidConnection:$,flowId:j,doc:X,lib:k,nodeLookup:K});oe&&ee&&p(ee);const q=structuredClone(Q);delete q.inProgress,q.toPosition=q.toHandle?q.toHandle.position:null,y==null||y(v,q),I.setState({connectionClickStartHandle:null})};return E.jsx("div",{"data-handleid":d,"data-nodeid":u,"data-handlepos":t,"data-id":`${C}-${u}-${d}-${e}`,className:Se(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",O,l,{source:!N,target:N,connectable:r,connectablestart:o,connectableend:s,clickconnecting:D,connectingfrom:m,connectingto:L,valid:g,connectionindicator:r&&(!x||M)&&(x||B?s:o)}]),onMouseDown:F,onTouchStart:F,onClick:f?_:void 0,ref:A,...S,children:T})}const kt=h.memo(NT(Qm));function eD({data:e,isConnectable:t,sourcePosition:n=Z.Bottom}){return E.jsxs(E.Fragment,{children:[e==null?void 0:e.label,E.jsx(kt,{type:"source",position:n,isConnectable:t})]})}function tD({data:e,isConnectable:t,targetPosition:n=Z.Top,sourcePosition:r=Z.Bottom}){return E.jsxs(E.Fragment,{children:[E.jsx(kt,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,E.jsx(kt,{type:"source",position:r,isConnectable:t})]})}function nD(){return null}function rD({data:e,isConnectable:t,targetPosition:n=Z.Top}){return E.jsxs(E.Fragment,{children:[E.jsx(kt,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label]})}const pr={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},JE={input:eD,default:tD,output:rD,group:nD};function oD(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 sD=e=>{const{width:t,height:n,x:r,y:o}=Mn(e.nodeLookup,{filter:s=>!!s.selected});return{width:Ue(t)?t:null,height:Ue(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 iD({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=Re(),{width:o,height:s,transformString:i,userSelectionActive:a}=se(sD,ce),T=hT(),l=h.useRef(null);h.useEffect(()=>{var A;n||(A=l.current)==null||A.focus({preventScroll:!0})},[n]);const R=!a&&o!==null&&s!==null;if(fT({nodeRef:l,disabled:!R}),!R)return null;const c=e?A=>{const d=r.getState().nodes.filter(N=>N.selected);e(A,d)}:void 0,S=A=>{Object.prototype.hasOwnProperty.call(pr,A.key)&&(A.preventDefault(),T({direction:pr[A.key],factor:A.shiftKey?4:1}))};return E.jsx("div",{className:Se(["react-flow__nodesselection","react-flow__container",t]),style:{transform:i},children:E.jsx("div",{ref:l,className:"react-flow__nodesselection-rect",onContextMenu:c,tabIndex:n?void 0:-1,onKeyDown:n?void 0:S,style:{width:o,height:s}})})}const qE=typeof window<"u"?window:void 0,ED=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function LT({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:s,onPaneScroll:i,paneClickDistance:a,deleteKeyCode:T,selectionKeyCode:l,selectionOnDrag:R,selectionMode:c,onSelectionStart:S,onSelectionEnd:A,multiSelectionKeyCode:d,panActivationKeyCode:N,zoomActivationKeyCode:I,elementsSelectable:u,zoomOnScroll:f,zoomOnPinch:O,panOnScroll:C,panOnScrollSpeed:m,panOnScrollMode:L,zoomOnDoubleClick:D,panOnDrag:M,defaultViewport:x,translateExtent:B,minZoom:g,maxZoom:p,preventScrolling:F,onSelectionContextMenu:_,noWheelClassName:U,noPanClassName:P,disableKeyboardA11y:v,onViewportChange:b,isControlledViewport:y}){const{nodesSelectionActive:w,userSelectionActive:H}=se(ED,ce),Y=Ln(l,{target:qE}),k=Ln(N,{target:qE}),j=k||M,K=k||C,Q=R&&j!==!0,X=Y||H||Q;return Ym({deleteKeyCode:T,multiSelectionKeyCode:d}),E.jsx(km,{onPaneContextMenu:s,elementsSelectable:u,zoomOnScroll:f,zoomOnPinch:O,panOnScroll:K,panOnScrollSpeed:m,panOnScrollMode:L,zoomOnDoubleClick:D,panOnDrag:!Y&&j,defaultViewport:x,translateExtent:B,minZoom:g,maxZoom:p,zoomActivationKeyCode:I,preventScrolling:F,noWheelClassName:U,noPanClassName:P,onViewportChange:b,isControlledViewport:y,paneClickDistance:a,selectionOnDrag:Q,children:E.jsxs(Km,{onSelectionStart:S,onSelectionEnd:A,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:s,onPaneScroll:i,panOnDrag:j,isSelecting:!!X,selectionMode:c,selectionKeyPressed:Y,paneClickDistance:a,selectionOnDrag:Q,children:[e,w&&E.jsx(iD,{onSelectionContextMenu:_,noPanClassName:P,disableKeyboardA11y:v})]})})}LT.displayName="FlowRenderer";const aD=h.memo(LT),lD=e=>t=>e?xs(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 TD(e){return se(h.useCallback(lD(e),[e]),ce)}const cD=e=>e.updateNodeInternals;function RD(){const e=se(cD),[t]=h.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 h.useEffect(()=>()=>{t==null||t.disconnect()},[t]),t}function SD({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){const o=Re(),s=h.useRef(null),i=h.useRef(null),a=h.useRef(e.sourcePosition),T=h.useRef(e.targetPosition),l=h.useRef(t),R=n&&!!e.internals.handleBounds;return h.useEffect(()=>{s.current&&!e.hidden&&(!R||i.current!==s.current)&&(i.current&&(r==null||r.unobserve(i.current)),r==null||r.observe(s.current),i.current=s.current)},[R,e.hidden]),h.useEffect(()=>()=>{i.current&&(r==null||r.unobserve(i.current),i.current=null)},[]),h.useEffect(()=>{if(s.current){const c=l.current!==t,S=a.current!==e.sourcePosition,A=T.current!==e.targetPosition;(c||S||A)&&(l.current=t,a.current=e.sourcePosition,T.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 AD({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:o,onContextMenu:s,onDoubleClick:i,nodesDraggable:a,elementsSelectable:T,nodesConnectable:l,nodesFocusable:R,resizeObserver:c,noDragClassName:S,noPanClassName:A,disableKeyboardA11y:d,rfId:N,nodeTypes:I,nodeClickDistance:u,onError:f}){const{node:O,internals:C,isParent:m}=se($=>{const ee=$.nodeLookup.get(e),oe=$.parentLookup.has(e);return{node:ee,internals:ee.internals,isParent:oe}},ce);let L=O.type||"default",D=(I==null?void 0:I[L])||JE[L];D===void 0&&(f==null||f("003",Ve.error003(L)),L="default",D=(I==null?void 0:I.default)||JE.default);const M=!!(O.draggable||a&&typeof O.draggable>"u"),x=!!(O.selectable||T&&typeof O.selectable>"u"),B=!!(O.connectable||l&&typeof O.connectable>"u"),g=!!(O.focusable||R&&typeof O.focusable>"u"),p=Re(),F=kl(O),_=SD({node:O,nodeType:L,hasDimensions:F,resizeObserver:c}),U=fT({nodeRef:_,disabled:O.hidden||!M,noDragClassName:S,handleSelector:O.dragHandle,nodeId:e,isSelectable:x,nodeClickDistance:u}),P=hT();if(O.hidden)return null;const v=Ze(O),b=oD(O),y=x||M||t||n||r||o,w=n?$=>n($,{...C.userNode}):void 0,H=r?$=>r($,{...C.userNode}):void 0,Y=o?$=>o($,{...C.userNode}):void 0,k=s?$=>s($,{...C.userNode}):void 0,j=i?$=>i($,{...C.userNode}):void 0,K=$=>{const{selectNodesOnDrag:ee,nodeDragThreshold:oe}=p.getState();x&&(!ee||!M||oe>0)&&Rs({id:e,store:p,nodeRef:_}),t&&t($,{...C.userNode})},Q=$=>{if(!($l($.nativeEvent)||d)){if(vl.includes($.key)&&x){const ee=$.key==="Escape";Rs({id:e,store:p,unselect:ee,nodeRef:_})}else if(M&&O.selected&&Object.prototype.hasOwnProperty.call(pr,$.key)){$.preventDefault();const{ariaLabelConfig:ee}=p.getState();p.setState({ariaLiveMessage:ee["node.a11yDescription.ariaLiveMessage"]({direction:$.key.replace("Arrow","").toLowerCase(),x:~~C.positionAbsolute.x,y:~~C.positionAbsolute.y})}),P({direction:pr[$.key],factor:$.shiftKey?4:1})}}},X=()=>{var Ee;if(d||!((Ee=_.current)!=null&&Ee.matches(":focus-visible")))return;const{transform:$,width:ee,height:oe,autoPanOnNodeFocus:q,setCenter:J}=p.getState();if(!q)return;xs(new Map([[e,O]]),{x:0,y:0,width:ee,height:oe},$,!0).length>0||J(O.position.x+v.width/2,O.position.y+v.height/2,{zoom:$[2]})};return E.jsx("div",{className:Se(["react-flow__node",`react-flow__node-${L}`,{[A]:M},O.className,{selected:O.selected,selectable:x,parent:m,draggable:M,dragging:U}]),ref:_,style:{zIndex:C.z,transform:`translate(${C.positionAbsolute.x}px,${C.positionAbsolute.y}px)`,pointerEvents:y?"all":"none",visibility:F?"visible":"hidden",...O.style,...b},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:w,onMouseMove:H,onMouseLeave:Y,onContextMenu:k,onClick:K,onDoubleClick:j,onKeyDown:g?Q:void 0,tabIndex:g?0:void 0,onFocus:g?X:void 0,role:O.ariaRole??(g?"group":void 0),"aria-roledescription":"node","aria-describedby":d?void 0:`${RT}-${N}`,"aria-label":O.ariaLabel,...O.domAttributes,children:E.jsx(Jm,{value:e,children:E.jsx(D,{id:e,data:O.data,type:L,positionAbsoluteX:C.positionAbsolute.x,positionAbsoluteY:C.positionAbsolute.y,selected:O.selected??!1,selectable:x,draggable:M,deletable:O.deletable??!0,isConnectable:B,sourcePosition:O.sourcePosition,targetPosition:O.targetPosition,dragging:U,dragHandle:O.dragHandle,zIndex:C.z,parentId:O.parentId,...v})})})}var dD=h.memo(AD);const uD=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function pT(e){const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,onError:s}=se(uD,ce),i=TD(e.onlyRenderVisibleElements),a=RD();return E.jsx("div",{className:"react-flow__nodes",style:Vr,children:i.map(T=>E.jsx(dD,{id:T,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:a,nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,nodeClickDistance:e.nodeClickDistance,onError:s},T))})}pT.displayName="NodeRenderer";const ID=h.memo(pT);function ND(e){return se(h.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&&u_({sourceNode:s,targetNode:i,width:n.width,height:n.height,transform:n.transform})&&r.push(o.id)}return r},[e]),ce)}const OD=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e}};return E.jsx("polyline",{className:"arrow",style:n,strokeLinecap:"round",fill:"none",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4"})},fD=({color:e="none",strokeWidth:t=1})=>{const n={strokeWidth:t,...e&&{stroke:e,fill:e}};return E.jsx("polyline",{className:"arrowclosed",style:n,strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},ZE={[fn.Arrow]:OD,[fn.ArrowClosed]:fD};function hD(e){const t=Re();return h.useMemo(()=>{var o,s;return Object.prototype.hasOwnProperty.call(ZE,e)?ZE[e]:((s=(o=t.getState()).onError)==null||s.call(o,"009",Ve.error009(e)),null)},[e])}const CD=({id:e,type:t,color:n,width:r=12.5,height:o=12.5,markerUnits:s="strokeWidth",strokeWidth:i,orient:a="auto-start-reverse"})=>{const T=hD(t);return T?E.jsx("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${o}`,viewBox:"-10 -10 20 20",markerUnits:s,orient:a,refX:"0",refY:"0",children:E.jsx(T,{color:n,strokeWidth:i})}):null},_T=({defaultColor:e,rfId:t})=>{const n=se(s=>s.edges),r=se(s=>s.defaultEdgeOptions),o=h.useMemo(()=>p_(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?E.jsx("svg",{className:"react-flow__marker","aria-hidden":"true",children:E.jsx("defs",{children:o.map(s=>E.jsx(CD,{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};_T.displayName="MarkerDefinitions";var LD=h.memo(_T);function mT({x:e,y:t,label:n,labelStyle:r,labelShowBg:o=!0,labelBgStyle:s,labelBgPadding:i=[2,4],labelBgBorderRadius:a=2,children:T,className:l,...R}){const[c,S]=h.useState({x:1,y:0,width:0,height:0}),A=Se(["react-flow__edge-textwrapper",l]),d=h.useRef(null);return h.useEffect(()=>{if(d.current){const N=d.current.getBBox();S({x:N.x,y:N.y,width:N.width,height:N.height})}},[n]),n?E.jsxs("g",{transform:`translate(${e-c.width/2} ${t-c.height/2})`,className:A,visibility:c.width?"visible":"hidden",...R,children:[o&&E.jsx("rect",{width:c.width+2*i[0],x:-i[0],y:-i[1],height:c.height+2*i[1],className:"react-flow__edge-textbg",style:s,rx:a,ry:a}),E.jsx("text",{className:"react-flow__edge-text",y:c.height/2,dy:"0.3em",ref:d,style:r,children:n}),T]}):null}mT.displayName="EdgeText";const pD=h.memo(mT);function Wr({path:e,labelX:t,labelY:n,label:r,labelStyle:o,labelShowBg:s,labelBgStyle:i,labelBgPadding:a,labelBgBorderRadius:T,interactionWidth:l=20,...R}){return E.jsxs(E.Fragment,{children:[E.jsx("path",{...R,d:e,fill:"none",className:Se(["react-flow__edge-path",R.className])}),l?E.jsx("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:l,className:"react-flow__edge-interaction"}):null,r&&Ue(t)&&Ue(n)?E.jsx(pD,{x:t,y:n,label:r,labelStyle:o,labelShowBg:s,labelBgStyle:i,labelBgPadding:a,labelBgBorderRadius:T}):null]})}function QE({pos:e,x1:t,y1:n,x2:r,y2:o}){return e===Z.Left||e===Z.Right?[.5*(t+r),n]:[t,.5*(n+o)]}function DT({sourceX:e,sourceY:t,sourcePosition:n=Z.Bottom,targetX:r,targetY:o,targetPosition:s=Z.Top}){const[i,a]=QE({pos:n,x1:e,y1:t,x2:r,y2:o}),[T,l]=QE({pos:s,x1:r,y1:o,x2:e,y2:t}),[R,c,S,A]=zl({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:i,sourceControlY:a,targetControlX:T,targetControlY:l});return[`M${e},${t} C${i},${a} ${T},${l} ${r},${o}`,R,c,S,A]}function gT(e){return h.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,sourcePosition:i,targetPosition:a,label:T,labelStyle:l,labelShowBg:R,labelBgStyle:c,labelBgPadding:S,labelBgBorderRadius:A,style:d,markerEnd:N,markerStart:I,interactionWidth:u})=>{const[f,O,C]=DT({sourceX:n,sourceY:r,sourcePosition:i,targetX:o,targetY:s,targetPosition:a}),m=e.isInternal?void 0:t;return E.jsx(Wr,{id:m,path:f,labelX:O,labelY:C,label:T,labelStyle:l,labelShowBg:R,labelBgStyle:c,labelBgPadding:S,labelBgBorderRadius:A,style:d,markerEnd:N,markerStart:I,interactionWidth:u})})}const _D=gT({isInternal:!1}),MT=gT({isInternal:!0});_D.displayName="SimpleBezierEdge";MT.displayName="SimpleBezierEdgeInternal";function xT(e){return h.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,label:i,labelStyle:a,labelShowBg:T,labelBgStyle:l,labelBgPadding:R,labelBgBorderRadius:c,style:S,sourcePosition:A=Z.Bottom,targetPosition:d=Z.Top,markerEnd:N,markerStart:I,pathOptions:u,interactionWidth:f})=>{const[O,C,m]=as({sourceX:n,sourceY:r,sourcePosition:A,targetX:o,targetY:s,targetPosition:d,borderRadius:u==null?void 0:u.borderRadius,offset:u==null?void 0:u.offset,stepPosition:u==null?void 0:u.stepPosition}),L=e.isInternal?void 0:t;return E.jsx(Wr,{id:L,path:O,labelX:C,labelY:m,label:i,labelStyle:a,labelShowBg:T,labelBgStyle:l,labelBgPadding:R,labelBgBorderRadius:c,style:S,markerEnd:N,markerStart:I,interactionWidth:f})})}const PT=xT({isInternal:!1}),yT=xT({isInternal:!0});PT.displayName="SmoothStepEdge";yT.displayName="SmoothStepEdgeInternal";function UT(e){return h.memo(({id:t,...n})=>{var o;const r=e.isInternal?void 0:t;return E.jsx(PT,{...n,id:r,pathOptions:h.useMemo(()=>{var s;return{borderRadius:0,offset:(s=n.pathOptions)==null?void 0:s.offset}},[(o=n.pathOptions)==null?void 0:o.offset])})})}const mD=UT({isInternal:!1}),bT=UT({isInternal:!0});mD.displayName="StepEdge";bT.displayName="StepEdgeInternal";function vT(e){return h.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,label:i,labelStyle:a,labelShowBg:T,labelBgStyle:l,labelBgPadding:R,labelBgBorderRadius:c,style:S,markerEnd:A,markerStart:d,interactionWidth:N})=>{const[I,u,f]=Zl({sourceX:n,sourceY:r,targetX:o,targetY:s}),O=e.isInternal?void 0:t;return E.jsx(Wr,{id:O,path:I,labelX:u,labelY:f,label:i,labelStyle:a,labelShowBg:T,labelBgStyle:l,labelBgPadding:R,labelBgBorderRadius:c,style:S,markerEnd:A,markerStart:d,interactionWidth:N})})}const DD=vT({isInternal:!1}),BT=vT({isInternal:!0});DD.displayName="StraightEdge";BT.displayName="StraightEdgeInternal";function GT(e){return h.memo(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:s,sourcePosition:i=Z.Bottom,targetPosition:a=Z.Top,label:T,labelStyle:l,labelShowBg:R,labelBgStyle:c,labelBgPadding:S,labelBgBorderRadius:A,style:d,markerEnd:N,markerStart:I,pathOptions:u,interactionWidth:f})=>{const[O,C,m]=Jl({sourceX:n,sourceY:r,sourcePosition:i,targetX:o,targetY:s,targetPosition:a,curvature:u==null?void 0:u.curvature}),L=e.isInternal?void 0:t;return E.jsx(Wr,{id:L,path:O,labelX:C,labelY:m,label:T,labelStyle:l,labelShowBg:R,labelBgStyle:c,labelBgPadding:S,labelBgBorderRadius:A,style:d,markerEnd:N,markerStart:I,interactionWidth:f})})}const gD=GT({isInternal:!1}),HT=GT({isInternal:!0});gD.displayName="BezierEdge";HT.displayName="BezierEdgeInternal";const ea={default:HT,straight:BT,step:bT,smoothstep:yT,simplebezier:MT},ta={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},MD=(e,t,n)=>n===Z.Left?e-t:n===Z.Right?e+t:e,xD=(e,t,n)=>n===Z.Top?e-t:n===Z.Bottom?e+t:e,na="react-flow__edgeupdater";function ra({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:o,onMouseEnter:s,onMouseOut:i,type:a}){return E.jsx("circle",{onMouseDown:o,onMouseEnter:s,onMouseOut:i,className:Se([na,`${na}-${a}`]),cx:MD(t,r,e),cy:xD(n,r,e),r,stroke:"transparent",fill:"transparent"})}function PD({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:o,targetX:s,targetY:i,sourcePosition:a,targetPosition:T,onReconnect:l,onReconnectStart:R,onReconnectEnd:c,setReconnecting:S,setUpdateHover:A}){const d=Re(),N=(C,m)=>{if(C.button!==0)return;const{autoPanOnConnect:L,domNode:D,connectionMode:M,connectionRadius:x,lib:B,onConnectStart:g,cancelConnection:p,nodeLookup:F,rfId:_,panBy:U,updateConnection:P}=d.getState(),v=m.type==="target",b=(H,Y)=>{S(!1),c==null||c(H,n,m.type,Y)},y=H=>l==null?void 0:l(n,H),w=(H,Y)=>{S(!0),R==null||R(C,n,m.type),g==null||g(H,Y)};cs.onPointerDown(C.nativeEvent,{autoPanOnConnect:L,connectionMode:M,connectionRadius:x,domNode:D,handleId:m.id,nodeId:m.nodeId,nodeLookup:F,isTarget:v,edgeUpdaterType:m.type,lib:B,flowId:_,cancelConnection:p,panBy:U,isValidConnection:(...H)=>{var Y,k;return((k=(Y=d.getState()).isValidConnection)==null?void 0:k.call(Y,...H))??!0},onConnect:y,onConnectStart:w,onConnectEnd:(...H)=>{var Y,k;return(k=(Y=d.getState()).onConnectEnd)==null?void 0:k.call(Y,...H)},onReconnectEnd:b,updateConnection:P,getTransform:()=>d.getState().transform,getFromHandle:()=>d.getState().connection.fromHandle,dragThreshold:d.getState().connectionDragThreshold,handleDomNode:C.currentTarget})},I=C=>N(C,{nodeId:n.target,id:n.targetHandle??null,type:"target"}),u=C=>N(C,{nodeId:n.source,id:n.sourceHandle??null,type:"source"}),f=()=>A(!0),O=()=>A(!1);return E.jsxs(E.Fragment,{children:[(e===!0||e==="source")&&E.jsx(ra,{position:a,centerX:r,centerY:o,radius:t,onMouseDown:I,onMouseEnter:f,onMouseOut:O,type:"source"}),(e===!0||e==="target")&&E.jsx(ra,{position:T,centerX:s,centerY:i,radius:t,onMouseDown:u,onMouseEnter:f,onMouseOut:O,type:"target"})]})}function yD({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:o,onDoubleClick:s,onContextMenu:i,onMouseEnter:a,onMouseMove:T,onMouseLeave:l,reconnectRadius:R,onReconnect:c,onReconnectStart:S,onReconnectEnd:A,rfId:d,edgeTypes:N,noPanClassName:I,onError:u,disableKeyboardA11y:f}){let O=se(J=>J.edgeLookup.get(e));const C=se(J=>J.defaultEdgeOptions);O=C?{...C,...O}:O;let m=O.type||"default",L=(N==null?void 0:N[m])||ea[m];L===void 0&&(u==null||u("011",Ve.error011(m)),m="default",L=(N==null?void 0:N.default)||ea.default);const D=!!(O.focusable||t&&typeof O.focusable>"u"),M=typeof c<"u"&&(O.reconnectable||n&&typeof O.reconnectable>"u"),x=!!(O.selectable||r&&typeof O.selectable>"u"),B=h.useRef(null),[g,p]=h.useState(!1),[F,_]=h.useState(!1),U=Re(),{zIndex:P,sourceX:v,sourceY:b,targetX:y,targetY:w,sourcePosition:H,targetPosition:Y}=se(h.useCallback(J=>{const te=J.nodeLookup.get(O.source),Ee=J.nodeLookup.get(O.target);if(!te||!Ee)return{zIndex:O.zIndex,...ta};const Te=L_({id:e,sourceNode:te,targetNode:Ee,sourceHandle:O.sourceHandle||null,targetHandle:O.targetHandle||null,connectionMode:J.connectionMode,onError:u});return{zIndex:d_({selected:O.selected,zIndex:O.zIndex,sourceNode:te,targetNode:Ee,elevateOnSelect:J.elevateEdgesOnSelect,zIndexMode:J.zIndexMode}),...Te||ta}},[O.source,O.target,O.sourceHandle,O.targetHandle,O.selected,O.zIndex]),ce),k=h.useMemo(()=>O.markerStart?`url('#${ls(O.markerStart,d)}')`:void 0,[O.markerStart,d]),j=h.useMemo(()=>O.markerEnd?`url('#${ls(O.markerEnd,d)}')`:void 0,[O.markerEnd,d]);if(O.hidden||v===null||b===null||y===null||w===null)return null;const K=J=>{var ie;const{addSelectedEdges:te,unselectNodesAndEdges:Ee,multiSelectionActive:Te}=U.getState();x&&(U.setState({nodesSelectionActive:!1}),O.selected&&Te?(Ee({nodes:[],edges:[O]}),(ie=B.current)==null||ie.blur()):te([e])),o&&o(J,O)},Q=s?J=>{s(J,{...O})}:void 0,X=i?J=>{i(J,{...O})}:void 0,$=a?J=>{a(J,{...O})}:void 0,ee=T?J=>{T(J,{...O})}:void 0,oe=l?J=>{l(J,{...O})}:void 0,q=J=>{var te;if(!f&&vl.includes(J.key)&&x){const{unselectNodesAndEdges:Ee,addSelectedEdges:Te}=U.getState();J.key==="Escape"?((te=B.current)==null||te.blur(),Ee({edges:[O]})):Te([e])}};return E.jsx("svg",{style:{zIndex:P},children:E.jsxs("g",{className:Se(["react-flow__edge",`react-flow__edge-${m}`,O.className,I,{selected:O.selected,animated:O.animated,inactive:!x&&!o,updating:g,selectable:x}]),onClick:K,onDoubleClick:Q,onContextMenu:X,onMouseEnter:$,onMouseMove:ee,onMouseLeave:oe,onKeyDown:D?q:void 0,tabIndex:D?0:void 0,role:O.ariaRole??(D?"group":"img"),"aria-roledescription":"edge","data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":O.ariaLabel===null?void 0:O.ariaLabel||`Edge from ${O.source} to ${O.target}`,"aria-describedby":D?`${ST}-${d}`:void 0,ref:B,...O.domAttributes,children:[!F&&E.jsx(L,{id:e,source:O.source,target:O.target,type:O.type,selected:O.selected,animated:O.animated,selectable:x,deletable:O.deletable??!0,label:O.label,labelStyle:O.labelStyle,labelShowBg:O.labelShowBg,labelBgStyle:O.labelBgStyle,labelBgPadding:O.labelBgPadding,labelBgBorderRadius:O.labelBgBorderRadius,sourceX:v,sourceY:b,targetX:y,targetY:w,sourcePosition:H,targetPosition:Y,data:O.data,style:O.style,sourceHandleId:O.sourceHandle,targetHandleId:O.targetHandle,markerStart:k,markerEnd:j,pathOptions:"pathOptions"in O?O.pathOptions:void 0,interactionWidth:O.interactionWidth}),M&&E.jsx(PD,{edge:O,isReconnectable:M,reconnectRadius:R,onReconnect:c,onReconnectStart:S,onReconnectEnd:A,sourceX:v,sourceY:b,targetX:y,targetY:w,sourcePosition:H,targetPosition:Y,setUpdateHover:p,setReconnecting:_})]})})}var UD=h.memo(yD);const bD=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function FT({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:o,onReconnect:s,onEdgeContextMenu:i,onEdgeMouseEnter:a,onEdgeMouseMove:T,onEdgeMouseLeave:l,onEdgeClick:R,reconnectRadius:c,onEdgeDoubleClick:S,onReconnectStart:A,onReconnectEnd:d,disableKeyboardA11y:N}){const{edgesFocusable:I,edgesReconnectable:u,elementsSelectable:f,onError:O}=se(bD,ce),C=ND(t);return E.jsxs("div",{className:"react-flow__edges",children:[E.jsx(LD,{defaultColor:e,rfId:n}),C.map(m=>E.jsx(UD,{id:m,edgesFocusable:I,edgesReconnectable:u,elementsSelectable:f,noPanClassName:o,onReconnect:s,onContextMenu:i,onMouseEnter:a,onMouseMove:T,onMouseLeave:l,onClick:R,reconnectRadius:c,onDoubleClick:S,onReconnectStart:A,onReconnectEnd:d,rfId:n,onError:O,edgeTypes:r,disableKeyboardA11y:N},m))]})}FT.displayName="EdgeRenderer";const vD=h.memo(FT),BD=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function GD({children:e}){const t=se(BD);return E.jsx("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:t},children:e})}function HD(e){const t=Hs(),n=h.useRef(!1);h.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const FD=e=>{var t;return(t=e.panZoom)==null?void 0:t.syncViewport};function wD(e){const t=se(FD),n=Re();return h.useEffect(()=>{e&&(t==null||t(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function YD(e){return e.connection.inProgress?{...e.connection,to:Pn(e.connection.to,e.transform)}:{...e.connection}}function VD(e){return YD}function WD(e){const t=VD();return se(t,ce)}const kD=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function jD({containerStyle:e,style:t,type:n,component:r}){const{nodesConnectable:o,width:s,height:i,isValid:a,inProgress:T}=se(kD,ce);return!(s&&o&&T)?null:E.jsx("svg",{style:e,width:s,height:i,className:"react-flow__connectionline react-flow__container",children:E.jsx("g",{className:Se(["react-flow__connection",Hl(a)]),children:E.jsx(wT,{style:t,type:n,CustomComponent:r,isValid:a})})})}const wT=({style:e,type:t=nt.Bezier,CustomComponent:n,isValid:r})=>{const{inProgress:o,from:s,fromNode:i,fromHandle:a,fromPosition:T,to:l,toNode:R,toHandle:c,toPosition:S,pointer:A}=WD();if(!o)return;if(n)return E.jsx(n,{connectionLineType:t,connectionLineStyle:e,fromNode:i,fromHandle:a,fromX:s.x,fromY:s.y,toX:l.x,toY:l.y,fromPosition:T,toPosition:S,connectionStatus:Hl(r),toNode:R,toHandle:c,pointer:A});let d="";const N={sourceX:s.x,sourceY:s.y,sourcePosition:T,targetX:l.x,targetY:l.y,targetPosition:S};switch(t){case nt.Bezier:[d]=Jl(N);break;case nt.SimpleBezier:[d]=DT(N);break;case nt.Step:[d]=as({...N,borderRadius:0});break;case nt.SmoothStep:[d]=as(N);break;default:[d]=Zl(N)}return E.jsx("path",{d,fill:"none",className:"react-flow__connection-path",style:e})};wT.displayName="ConnectionLine";const XD={};function oa(e=XD){h.useRef(e),Re(),h.useEffect(()=>{},[e])}function $D(){Re(),h.useRef(!1),h.useEffect(()=>{},[])}function YT({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:o,onNodeDoubleClick:s,onEdgeDoubleClick:i,onNodeMouseEnter:a,onNodeMouseMove:T,onNodeMouseLeave:l,onNodeContextMenu:R,onSelectionContextMenu:c,onSelectionStart:S,onSelectionEnd:A,connectionLineType:d,connectionLineStyle:N,connectionLineComponent:I,connectionLineContainerStyle:u,selectionKeyCode:f,selectionOnDrag:O,selectionMode:C,multiSelectionKeyCode:m,panActivationKeyCode:L,zoomActivationKeyCode:D,deleteKeyCode:M,onlyRenderVisibleElements:x,elementsSelectable:B,defaultViewport:g,translateExtent:p,minZoom:F,maxZoom:_,preventScrolling:U,defaultMarkerColor:P,zoomOnScroll:v,zoomOnPinch:b,panOnScroll:y,panOnScrollSpeed:w,panOnScrollMode:H,zoomOnDoubleClick:Y,panOnDrag:k,onPaneClick:j,onPaneMouseEnter:K,onPaneMouseMove:Q,onPaneMouseLeave:X,onPaneScroll:$,onPaneContextMenu:ee,paneClickDistance:oe,nodeClickDistance:q,onEdgeContextMenu:J,onEdgeMouseEnter:te,onEdgeMouseMove:Ee,onEdgeMouseLeave:Te,reconnectRadius:ie,onReconnect:fe,onReconnectStart:Qe,onReconnectEnd:ke,noDragClassName:lt,noWheelClassName:Kt,noPanClassName:zt,disableKeyboardA11y:Jt,nodeExtent:Xr,rfId:bn,viewport:Lt,onViewportChange:qt}){return oa(e),oa(t),$D(),HD(n),wD(Lt),E.jsx(aD,{onPaneClick:j,onPaneMouseEnter:K,onPaneMouseMove:Q,onPaneMouseLeave:X,onPaneContextMenu:ee,onPaneScroll:$,paneClickDistance:oe,deleteKeyCode:M,selectionKeyCode:f,selectionOnDrag:O,selectionMode:C,onSelectionStart:S,onSelectionEnd:A,multiSelectionKeyCode:m,panActivationKeyCode:L,zoomActivationKeyCode:D,elementsSelectable:B,zoomOnScroll:v,zoomOnPinch:b,zoomOnDoubleClick:Y,panOnScroll:y,panOnScrollSpeed:w,panOnScrollMode:H,panOnDrag:k,defaultViewport:g,translateExtent:p,minZoom:F,maxZoom:_,onSelectionContextMenu:c,preventScrolling:U,noDragClassName:lt,noWheelClassName:Kt,noPanClassName:zt,disableKeyboardA11y:Jt,onViewportChange:qt,isControlledViewport:!!Lt,children:E.jsxs(GD,{children:[E.jsx(vD,{edgeTypes:t,onEdgeClick:o,onEdgeDoubleClick:i,onReconnect:fe,onReconnectStart:Qe,onReconnectEnd:ke,onlyRenderVisibleElements:x,onEdgeContextMenu:J,onEdgeMouseEnter:te,onEdgeMouseMove:Ee,onEdgeMouseLeave:Te,reconnectRadius:ie,defaultMarkerColor:P,noPanClassName:zt,disableKeyboardA11y:Jt,rfId:bn}),E.jsx(jD,{style:N,type:d,component:I,containerStyle:u}),E.jsx("div",{className:"react-flow__edgelabel-renderer"}),E.jsx(ID,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:s,onNodeMouseEnter:a,onNodeMouseMove:T,onNodeMouseLeave:l,onNodeContextMenu:R,nodeClickDistance:q,onlyRenderVisibleElements:x,noPanClassName:zt,noDragClassName:lt,disableKeyboardA11y:Jt,nodeExtent:Xr,rfId:bn}),E.jsx("div",{className:"react-flow__viewport-portal"})]})})}YT.displayName="GraphView";const KD=h.memo(YT),sa=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:i,fitViewOptions:a,minZoom:T=.5,maxZoom:l=2,nodeOrigin:R,nodeExtent:c,zIndexMode:S="basic"}={})=>{const A=new Map,d=new Map,N=new Map,I=new Map,u=r??t??[],f=n??e??[],O=R??[0,0],C=c??Nn;tT(N,I,u);const m=Ts(f,A,d,{nodeOrigin:O,nodeExtent:C,zIndexMode:S});let L=[0,0,1];if(i&&o&&s){const D=Mn(A,{filter:g=>!!((g.width||g.initialWidth)&&(g.height||g.initialHeight))}),{x:M,y:x,zoom:B}=Ps(D,o,s,T,l,(a==null?void 0:a.padding)??.1);L=[M,x,B]}return{rfId:"1",width:o??0,height:s??0,transform:L,nodes:f,nodesInitialized:m,nodeLookup:A,parentLookup:d,edges:u,edgeLookup:I,connectionLookup:N,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:n!==void 0,hasDefaultEdges:r!==void 0,panZoom:null,minZoom:T,maxZoom:l,translateExtent:Nn,nodeExtent:C,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:Ft.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:O,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:a,fitViewResolver:null,connection:{...Gl},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:l_,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:Bl,zIndexMode:S,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}},zD=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:i,fitViewOptions:a,minZoom:T,maxZoom:l,nodeOrigin:R,nodeExtent:c,zIndexMode:S})=>Sm((A,d)=>{async function N(){const{nodeLookup:I,panZoom:u,fitViewOptions:f,fitViewResolver:O,width:C,height:m,minZoom:L,maxZoom:D}=d();u&&(await E_({nodes:I,width:C,height:m,panZoom:u,minZoom:L,maxZoom:D},f),O==null||O.resolve(!0),A({fitViewResolver:null}))}return{...sa({nodes:e,edges:t,width:o,height:s,fitView:i,fitViewOptions:a,minZoom:T,maxZoom:l,nodeOrigin:R,nodeExtent:c,defaultNodes:n,defaultEdges:r,zIndexMode:S}),setNodes:I=>{const{nodeLookup:u,parentLookup:f,nodeOrigin:O,elevateNodesOnSelect:C,fitViewQueued:m,zIndexMode:L}=d(),D=Ts(I,u,f,{nodeOrigin:O,nodeExtent:c,elevateNodesOnSelect:C,checkEquality:!0,zIndexMode:L});m&&D?(N(),A({nodes:I,nodesInitialized:D,fitViewQueued:!1,fitViewOptions:void 0})):A({nodes:I,nodesInitialized:D})},setEdges:I=>{const{connectionLookup:u,edgeLookup:f}=d();tT(u,f,I),A({edges:I})},setDefaultNodesAndEdges:(I,u)=>{if(I){const{setNodes:f}=d();f(I),A({hasDefaultNodes:!0})}if(u){const{setEdges:f}=d();f(u),A({hasDefaultEdges:!0})}},updateNodeInternals:I=>{const{triggerNodeChanges:u,nodeLookup:f,parentLookup:O,domNode:C,nodeOrigin:m,nodeExtent:L,debug:D,fitViewQueued:M,zIndexMode:x}=d(),{changes:B,updatedInternals:g}=P_(I,f,O,C,m,L,x);g&&(D_(f,O,{nodeOrigin:m,nodeExtent:L,zIndexMode:x}),M?(N(),A({fitViewQueued:!1,fitViewOptions:void 0})):A({}),(B==null?void 0:B.length)>0&&(D&&console.log("React Flow: trigger node changes",B),u==null||u(B)))},updateNodePositions:(I,u=!1)=>{const f=[];let O=[];const{nodeLookup:C,triggerNodeChanges:m,connection:L,updateConnection:D,onNodesChangeMiddlewareMap:M}=d();for(const[x,B]of I){const g=C.get(x),p=!!(g!=null&&g.expandParent&&(g!=null&&g.parentId)&&(B!=null&&B.position)),F={id:x,type:"position",position:p?{x:Math.max(0,B.position.x),y:Math.max(0,B.position.y)}:B.position,dragging:u};if(g&&L.inProgress&&L.fromNode.id===g.id){const _=Ot(g,L.fromHandle,Z.Left,!0);D({...L,from:_})}p&&g.parentId&&f.push({id:x,parentId:g.parentId,rect:{...B.internals.positionAbsolute,width:B.measured.width??0,height:B.measured.height??0}}),O.push(F)}if(f.length>0){const{parentLookup:x,nodeOrigin:B}=d(),g=Gs(f,C,x,B);O.push(...g)}for(const x of M.values())O=x(O);m(O)},triggerNodeChanges:I=>{const{onNodesChange:u,setNodes:f,nodes:O,hasDefaultNodes:C,debug:m}=d();if(I!=null&&I.length){if(C){const L=uT(I,O);f(L)}m&&console.log("React Flow: trigger node changes",I),u==null||u(I)}},triggerEdgeChanges:I=>{const{onEdgesChange:u,setEdges:f,edges:O,hasDefaultEdges:C,debug:m}=d();if(I!=null&&I.length){if(C){const L=IT(I,O);f(L)}m&&console.log("React Flow: trigger edge changes",I),u==null||u(I)}},addSelectedNodes:I=>{const{multiSelectionActive:u,edgeLookup:f,nodeLookup:O,triggerNodeChanges:C,triggerEdgeChanges:m}=d();if(u){const L=I.map(D=>ct(D,!0));C(L);return}C(Pt(O,new Set([...I]),!0)),m(Pt(f))},addSelectedEdges:I=>{const{multiSelectionActive:u,edgeLookup:f,nodeLookup:O,triggerNodeChanges:C,triggerEdgeChanges:m}=d();if(u){const L=I.map(D=>ct(D,!0));m(L);return}m(Pt(f,new Set([...I]))),C(Pt(O,new Set,!0))},unselectNodesAndEdges:({nodes:I,edges:u}={})=>{const{edges:f,nodes:O,nodeLookup:C,triggerNodeChanges:m,triggerEdgeChanges:L}=d(),D=I||O,M=u||f,x=[];for(const g of D){if(!g.selected)continue;const p=C.get(g.id);p&&(p.selected=!1),x.push(ct(g.id,!1))}const B=[];for(const g of M)g.selected&&B.push(ct(g.id,!1));m(x),L(B)},setMinZoom:I=>{const{panZoom:u,maxZoom:f}=d();u==null||u.setScaleExtent([I,f]),A({minZoom:I})},setMaxZoom:I=>{const{panZoom:u,minZoom:f}=d();u==null||u.setScaleExtent([f,I]),A({maxZoom:I})},setTranslateExtent:I=>{var u;(u=d().panZoom)==null||u.setTranslateExtent(I),A({translateExtent:I})},resetSelectedElements:()=>{const{edges:I,nodes:u,triggerNodeChanges:f,triggerEdgeChanges:O,elementsSelectable:C}=d();if(!C)return;const m=u.reduce((D,M)=>M.selected?[...D,ct(M.id,!1)]:D,[]),L=I.reduce((D,M)=>M.selected?[...D,ct(M.id,!1)]:D,[]);f(m),O(L)},setNodeExtent:I=>{const{nodes:u,nodeLookup:f,parentLookup:O,nodeOrigin:C,elevateNodesOnSelect:m,nodeExtent:L,zIndexMode:D}=d();I[0][0]===L[0][0]&&I[0][1]===L[0][1]&&I[1][0]===L[1][0]&&I[1][1]===L[1][1]||(Ts(u,f,O,{nodeOrigin:C,nodeExtent:I,elevateNodesOnSelect:m,checkEquality:!1,zIndexMode:D}),A({nodeExtent:I}))},panBy:I=>{const{transform:u,width:f,height:O,panZoom:C,translateExtent:m}=d();return y_({delta:I,panZoom:C,transform:u,translateExtent:m,width:f,height:O})},setCenter:async(I,u,f)=>{const{width:O,height:C,maxZoom:m,panZoom:L}=d();if(!L)return Promise.resolve(!1);const D=typeof(f==null?void 0:f.zoom)<"u"?f.zoom:m;return await L.setViewport({x:O/2-I*D,y:C/2-u*D,zoom:D},{duration:f==null?void 0:f.duration,ease:f==null?void 0:f.ease,interpolate:f==null?void 0:f.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{A({connection:{...Gl}})},updateConnection:I=>{A({connection:I})},reset:()=>A({...sa()})}},Object.is);function JD({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:o,initialHeight:s,initialMinZoom:i,initialMaxZoom:a,initialFitViewOptions:T,fitView:l,nodeOrigin:R,nodeExtent:c,zIndexMode:S,children:A}){const[d]=h.useState(()=>zD({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:s,fitView:l,minZoom:i,maxZoom:a,fitViewOptions:T,nodeOrigin:R,nodeExtent:c,zIndexMode:S}));return E.jsx(Am,{value:d,children:E.jsx(Gm,{children:A})})}function qD({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:o,width:s,height:i,fitView:a,fitViewOptions:T,minZoom:l,maxZoom:R,nodeOrigin:c,nodeExtent:S,zIndexMode:A}){return h.useContext(Yr)?E.jsx(E.Fragment,{children:e}):E.jsx(JD,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:o,initialWidth:s,initialHeight:i,fitView:a,initialFitViewOptions:T,initialMinZoom:l,initialMaxZoom:R,nodeOrigin:c,nodeExtent:S,zIndexMode:A,children:e})}const ZD={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};function QD({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:o,nodeTypes:s,edgeTypes:i,onNodeClick:a,onEdgeClick:T,onInit:l,onMove:R,onMoveStart:c,onMoveEnd:S,onConnect:A,onConnectStart:d,onConnectEnd:N,onClickConnectStart:I,onClickConnectEnd:u,onNodeMouseEnter:f,onNodeMouseMove:O,onNodeMouseLeave:C,onNodeContextMenu:m,onNodeDoubleClick:L,onNodeDragStart:D,onNodeDrag:M,onNodeDragStop:x,onNodesDelete:B,onEdgesDelete:g,onDelete:p,onSelectionChange:F,onSelectionDragStart:_,onSelectionDrag:U,onSelectionDragStop:P,onSelectionContextMenu:v,onSelectionStart:b,onSelectionEnd:y,onBeforeDelete:w,connectionMode:H,connectionLineType:Y=nt.Bezier,connectionLineStyle:k,connectionLineComponent:j,connectionLineContainerStyle:K,deleteKeyCode:Q="Backspace",selectionKeyCode:X="Shift",selectionOnDrag:$=!1,selectionMode:ee=On.Full,panActivationKeyCode:oe="Space",multiSelectionKeyCode:q=Cn()?"Meta":"Control",zoomActivationKeyCode:J=Cn()?"Meta":"Control",snapToGrid:te,snapGrid:Ee,onlyRenderVisibleElements:Te=!1,selectNodesOnDrag:ie,nodesDraggable:fe,autoPanOnNodeFocus:Qe,nodesConnectable:ke,nodesFocusable:lt,nodeOrigin:Kt=AT,edgesFocusable:zt,edgesReconnectable:Jt,elementsSelectable:Xr=!0,defaultViewport:bn=Dm,minZoom:Lt=.5,maxZoom:qt=2,translateExtent:js=Nn,preventScrolling:Nc=!0,nodeExtent:$r,defaultMarkerColor:Oc="#b1b1b7",zoomOnScroll:fc=!0,zoomOnPinch:hc=!0,panOnScroll:Cc=!1,panOnScrollSpeed:Lc=.5,panOnScrollMode:pc=dt.Free,zoomOnDoubleClick:_c=!0,panOnDrag:mc=!0,onPaneClick:Dc,onPaneMouseEnter:gc,onPaneMouseMove:Mc,onPaneMouseLeave:xc,onPaneScroll:Pc,onPaneContextMenu:yc,paneClickDistance:Uc=1,nodeClickDistance:bc=0,children:vc,onReconnect:Bc,onReconnectStart:Gc,onReconnectEnd:Hc,onEdgeContextMenu:Fc,onEdgeDoubleClick:wc,onEdgeMouseEnter:Yc,onEdgeMouseMove:Vc,onEdgeMouseLeave:Wc,reconnectRadius:kc=10,onNodesChange:jc,onEdgesChange:Xc,noDragClassName:$c="nodrag",noWheelClassName:Kc="nowheel",noPanClassName:Xs="nopan",fitView:$s,fitViewOptions:Ks,connectOnClick:zc,attributionPosition:Jc,proOptions:qc,defaultEdgeOptions:Zc,elevateNodesOnSelect:Qc=!0,elevateEdgesOnSelect:eR=!1,disableKeyboardA11y:zs=!1,autoPanOnConnect:tR,autoPanOnNodeDrag:nR,autoPanSpeed:rR,connectionRadius:oR,isValidConnection:sR,onError:iR,style:ER,id:Js,nodeDragThreshold:aR,connectionDragThreshold:lR,viewport:TR,onViewportChange:cR,width:RR,height:SR,colorMode:AR="light",debug:dR,onScroll:vn,ariaLabelConfig:uR,zIndexMode:qs="basic",...IR},NR){const Kr=Js||"1",fR=Pm(AR),hR=h.useCallback(Zs=>{Zs.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),vn==null||vn(Zs)},[vn]);return E.jsx("div",{"data-testid":"rf__wrapper",...IR,onScroll:hR,style:{...ER,...ZD},ref:NR,className:Se(["react-flow",o,fR]),id:Js,role:"application",children:E.jsxs(qD,{nodes:e,edges:t,width:RR,height:SR,fitView:$s,fitViewOptions:Ks,minZoom:Lt,maxZoom:qt,nodeOrigin:Kt,nodeExtent:$r,zIndexMode:qs,children:[E.jsx(KD,{onInit:l,onNodeClick:a,onEdgeClick:T,onNodeMouseEnter:f,onNodeMouseMove:O,onNodeMouseLeave:C,onNodeContextMenu:m,onNodeDoubleClick:L,nodeTypes:s,edgeTypes:i,connectionLineType:Y,connectionLineStyle:k,connectionLineComponent:j,connectionLineContainerStyle:K,selectionKeyCode:X,selectionOnDrag:$,selectionMode:ee,deleteKeyCode:Q,multiSelectionKeyCode:q,panActivationKeyCode:oe,zoomActivationKeyCode:J,onlyRenderVisibleElements:Te,defaultViewport:bn,translateExtent:js,minZoom:Lt,maxZoom:qt,preventScrolling:Nc,zoomOnScroll:fc,zoomOnPinch:hc,zoomOnDoubleClick:_c,panOnScroll:Cc,panOnScrollSpeed:Lc,panOnScrollMode:pc,panOnDrag:mc,onPaneClick:Dc,onPaneMouseEnter:gc,onPaneMouseMove:Mc,onPaneMouseLeave:xc,onPaneScroll:Pc,onPaneContextMenu:yc,paneClickDistance:Uc,nodeClickDistance:bc,onSelectionContextMenu:v,onSelectionStart:b,onSelectionEnd:y,onReconnect:Bc,onReconnectStart:Gc,onReconnectEnd:Hc,onEdgeContextMenu:Fc,onEdgeDoubleClick:wc,onEdgeMouseEnter:Yc,onEdgeMouseMove:Vc,onEdgeMouseLeave:Wc,reconnectRadius:kc,defaultMarkerColor:Oc,noDragClassName:$c,noWheelClassName:Kc,noPanClassName:Xs,rfId:Kr,disableKeyboardA11y:zs,nodeExtent:$r,viewport:TR,onViewportChange:cR}),E.jsx(xm,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:A,onConnectStart:d,onConnectEnd:N,onClickConnectStart:I,onClickConnectEnd:u,nodesDraggable:fe,autoPanOnNodeFocus:Qe,nodesConnectable:ke,nodesFocusable:lt,edgesFocusable:zt,edgesReconnectable:Jt,elementsSelectable:Xr,elevateNodesOnSelect:Qc,elevateEdgesOnSelect:eR,minZoom:Lt,maxZoom:qt,nodeExtent:$r,onNodesChange:jc,onEdgesChange:Xc,snapToGrid:te,snapGrid:Ee,connectionMode:H,translateExtent:js,connectOnClick:zc,defaultEdgeOptions:Zc,fitView:$s,fitViewOptions:Ks,onNodesDelete:B,onEdgesDelete:g,onDelete:p,onNodeDragStart:D,onNodeDrag:M,onNodeDragStop:x,onSelectionDrag:U,onSelectionDragStart:_,onSelectionDragStop:P,onMove:R,onMoveStart:c,onMoveEnd:S,noPanClassName:Xs,nodeOrigin:Kt,rfId:Kr,autoPanOnConnect:tR,autoPanOnNodeDrag:nR,autoPanSpeed:rR,onError:iR,connectionRadius:oR,isValidConnection:sR,selectNodesOnDrag:ie,nodeDragThreshold:aR,connectionDragThreshold:lR,onBeforeDelete:w,debug:dR,ariaLabelConfig:uR,zIndexMode:qs}),E.jsx(mm,{onSelectionChange:F}),vc,E.jsx(hm,{proOptions:qc,position:Jc}),E.jsx(fm,{rfId:Kr,disableKeyboardA11y:zs})]})})}var eg=NT(QD);function tg(e){const[t,n]=h.useState(e),r=h.useCallback(o=>n(s=>uT(o,s)),[]);return[t,n,r]}function ng(e){const[t,n]=h.useState(e),r=h.useCallback(o=>n(s=>IT(o,s)),[]);return[t,n,r]}function rg({dimensions:e,lineWidth:t,variant:n,className:r}){return E.jsx("path",{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:Se(["react-flow__background-pattern",n,r])})}function og({radius:e,className:t}){return E.jsx("circle",{cx:e,cy:e,r:e,className:Se(["react-flow__background-pattern","dots",t])})}var it;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(it||(it={}));const sg={[it.Dots]:1,[it.Lines]:1,[it.Cross]:6},ig=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function VT({id:e,variant:t=it.Dots,gap:n=20,size:r,lineWidth:o=1,offset:s=0,color:i,bgColor:a,style:T,className:l,patternClassName:R}){const c=h.useRef(null),{transform:S,patternId:A}=se(ig,ce),d=r||sg[t],N=t===it.Dots,I=t===it.Cross,u=Array.isArray(n)?n:[n,n],f=[u[0]*S[2]||1,u[1]*S[2]||1],O=d*S[2],C=Array.isArray(s)?s:[s,s],m=I?[O,O]:f,L=[C[0]*S[2]||1+m[0]/2,C[1]*S[2]||1+m[1]/2],D=`${A}${e||""}`;return E.jsxs("svg",{className:Se(["react-flow__background",l]),style:{...T,...Vr,"--xy-background-color-props":a,"--xy-background-pattern-color-props":i},ref:c,"data-testid":"rf__background",children:[E.jsx("pattern",{id:D,x:S[0]%f[0],y:S[1]%f[1],width:f[0],height:f[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${L[0]},-${L[1]})`,children:N?E.jsx(og,{radius:O/2,className:R}):E.jsx(rg,{dimensions:m,lineWidth:o,variant:t,className:R})}),E.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${D})`})]})}VT.displayName="Background";const Eg=h.memo(VT);function ag(){return E.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:E.jsx("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function lg(){return E.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:E.jsx("path",{d:"M0 0h32v4.2H0z"})})}function Tg(){return E.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:E.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 cg(){return E.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:E.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 Rg(){return E.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:E.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 Jn({children:e,className:t,...n}){return E.jsx("button",{type:"button",className:Se(["react-flow__controls-button",t]),...n,children:e})}const Sg=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function WT({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:o,onZoomIn:s,onZoomOut:i,onFitView:a,onInteractiveChange:T,className:l,children:R,position:c="bottom-left",orientation:S="vertical","aria-label":A}){const d=Re(),{isInteractive:N,minZoomReached:I,maxZoomReached:u,ariaLabelConfig:f}=se(Sg,ce),{zoomIn:O,zoomOut:C,fitView:m}=Hs(),L=()=>{O(),s==null||s()},D=()=>{C(),i==null||i()},M=()=>{m(o),a==null||a()},x=()=>{d.setState({nodesDraggable:!N,nodesConnectable:!N,elementsSelectable:!N}),T==null||T(!N)},B=S==="horizontal"?"horizontal":"vertical";return E.jsxs(yn,{className:Se(["react-flow__controls",B,l]),position:c,style:e,"data-testid":"rf__controls","aria-label":A??f["controls.ariaLabel"],children:[t&&E.jsxs(E.Fragment,{children:[E.jsx(Jn,{onClick:L,className:"react-flow__controls-zoomin",title:f["controls.zoomIn.ariaLabel"],"aria-label":f["controls.zoomIn.ariaLabel"],disabled:u,children:E.jsx(ag,{})}),E.jsx(Jn,{onClick:D,className:"react-flow__controls-zoomout",title:f["controls.zoomOut.ariaLabel"],"aria-label":f["controls.zoomOut.ariaLabel"],disabled:I,children:E.jsx(lg,{})})]}),n&&E.jsx(Jn,{className:"react-flow__controls-fitview",onClick:M,title:f["controls.fitView.ariaLabel"],"aria-label":f["controls.fitView.ariaLabel"],children:E.jsx(Tg,{})}),r&&E.jsx(Jn,{className:"react-flow__controls-interactive",onClick:x,title:f["controls.interactive.ariaLabel"],"aria-label":f["controls.interactive.ariaLabel"],children:N?E.jsx(Rg,{}):E.jsx(cg,{})}),R]})}WT.displayName="Controls";const Ag=h.memo(WT);function dg({id:e,x:t,y:n,width:r,height:o,style:s,color:i,strokeColor:a,strokeWidth:T,className:l,borderRadius:R,shapeRendering:c,selected:S,onClick:A}){const{background:d,backgroundColor:N}=s||{},I=i||d||N;return E.jsx("rect",{className:Se(["react-flow__minimap-node",{selected:S},l]),x:t,y:n,rx:R,ry:R,width:r,height:o,style:{fill:I,stroke:a,strokeWidth:T},shapeRendering:c,onClick:A?u=>A(u,e):void 0})}const ug=h.memo(dg),Ig=e=>e.nodes.map(t=>t.id),Fo=e=>e instanceof Function?e:()=>e;function Ng({nodeStrokeColor:e,nodeColor:t,nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:o,nodeComponent:s=ug,onClick:i}){const a=se(Ig,ce),T=Fo(t),l=Fo(e),R=Fo(n),c=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return E.jsx(E.Fragment,{children:a.map(S=>E.jsx(fg,{id:S,nodeColorFunc:T,nodeStrokeColorFunc:l,nodeClassNameFunc:R,nodeBorderRadius:r,nodeStrokeWidth:o,NodeComponent:s,onClick:i,shapeRendering:c},S))})}function Og({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:o,nodeStrokeWidth:s,shapeRendering:i,NodeComponent:a,onClick:T}){const{node:l,x:R,y:c,width:S,height:A}=se(d=>{const N=d.nodeLookup.get(e);if(!N)return{node:void 0,x:0,y:0,width:0,height:0};const I=N.internals.userNode,{x:u,y:f}=N.internals.positionAbsolute,{width:O,height:C}=Ze(I);return{node:I,x:u,y:f,width:O,height:C}},ce);return!l||l.hidden||!kl(l)?null:E.jsx(a,{x:R,y:c,width:S,height:A,style:l.style,selected:!!l.selected,className:r(l),color:t(l),borderRadius:o,strokeColor:n(l),strokeWidth:s,shapeRendering:i,onClick:T,id:l.id})}const fg=h.memo(Og);var hg=h.memo(Ng);const Cg=200,Lg=150,pg=e=>!e.hidden,_g=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?Wl(Mn(e.nodeLookup,{filter:pg}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}},mg="react-flow__minimap-desc";function kT({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:o="",nodeBorderRadius:s=5,nodeStrokeWidth:i,nodeComponent:a,bgColor:T,maskColor:l,maskStrokeColor:R,maskStrokeWidth:c,position:S="bottom-right",onClick:A,onNodeClick:d,pannable:N=!1,zoomable:I=!1,ariaLabel:u,inversePan:f,zoomStep:O=1,offsetScale:C=5}){const m=Re(),L=h.useRef(null),{boundingRect:D,viewBB:M,rfId:x,panZoom:B,translateExtent:g,flowWidth:p,flowHeight:F,ariaLabelConfig:_}=se(_g,ce),U=(e==null?void 0:e.width)??Cg,P=(e==null?void 0:e.height)??Lg,v=D.width/U,b=D.height/P,y=Math.max(v,b),w=y*U,H=y*P,Y=C*y,k=D.x-(w-D.width)/2-Y,j=D.y-(H-D.height)/2-Y,K=w+Y*2,Q=H+Y*2,X=`${mg}-${x}`,$=h.useRef(0),ee=h.useRef();$.current=y,h.useEffect(()=>{if(L.current&&B)return ee.current=Y_({domNode:L.current,panZoom:B,getTransform:()=>m.getState().transform,getViewScale:()=>$.current}),()=>{var te;(te=ee.current)==null||te.destroy()}},[B]),h.useEffect(()=>{var te;(te=ee.current)==null||te.update({translateExtent:g,width:p,height:F,inversePan:f,pannable:N,zoomStep:O,zoomable:I})},[N,I,f,O,g,p,F]);const oe=A?te=>{var ie;const[Ee,Te]=((ie=ee.current)==null?void 0:ie.pointer(te))||[0,0];A(te,{x:Ee,y:Te})}:void 0,q=d?h.useCallback((te,Ee)=>{const Te=m.getState().nodeLookup.get(Ee).internals.userNode;d(te,Te)},[]):void 0,J=u??_["minimap.ariaLabel"];return E.jsx(yn,{position:S,style:{...e,"--xy-minimap-background-color-props":typeof T=="string"?T:void 0,"--xy-minimap-mask-background-color-props":typeof l=="string"?l:void 0,"--xy-minimap-mask-stroke-color-props":typeof R=="string"?R:void 0,"--xy-minimap-mask-stroke-width-props":typeof c=="number"?c*y: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:Se(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:E.jsxs("svg",{width:U,height:P,viewBox:`${k} ${j} ${K} ${Q}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":X,ref:L,onClick:oe,children:[J&&E.jsx("title",{id:X,children:J}),E.jsx(hg,{onClick:q,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:s,nodeClassName:o,nodeStrokeWidth:i,nodeComponent:a}),E.jsx("path",{className:"react-flow__minimap-mask",d:`M${k-Y},${j-Y}h${K+Y*2}v${Q+Y*2}h${-K-Y*2}z
|
|
503
|
-
M${M.x},${M.y}h${M.width}v${M.height}h${-M.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}kT.displayName="MiniMap";const Dg=h.memo(kT),gg=e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0,Mg={[Wt.Line]:"right",[Wt.Handle]:"bottom-right"};function xg({nodeId:e,position:t,variant:n=Wt.Handle,className:r,style:o=void 0,children:s,color:i,minWidth:a=10,minHeight:T=10,maxWidth:l=Number.MAX_VALUE,maxHeight:R=Number.MAX_VALUE,keepAspectRatio:c=!1,resizeDirection:S,autoScale:A=!0,shouldResize:d,onResizeStart:N,onResize:I,onResizeEnd:u}){const f=CT(),O=typeof e=="string"?e:f,C=Re(),m=h.useRef(null),L=n===Wt.Handle,D=se(h.useCallback(gg(L&&A),[L,A]),ce),M=h.useRef(null),x=t??Mg[n];h.useEffect(()=>{if(!(!m.current||!O))return M.current||(M.current=tm({domNode:m.current,nodeId:O,getStoreItems:()=>{const{nodeLookup:g,transform:p,snapGrid:F,snapToGrid:_,nodeOrigin:U,domNode:P}=C.getState();return{nodeLookup:g,transform:p,snapGrid:F,snapToGrid:_,nodeOrigin:U,paneDomNode:P}},onChange:(g,p)=>{const{triggerNodeChanges:F,nodeLookup:_,parentLookup:U,nodeOrigin:P}=C.getState(),v=[],b={x:g.x,y:g.y},y=_.get(O);if(y&&y.expandParent&&y.parentId){const w=y.origin??P,H=g.width??y.measured.width??0,Y=g.height??y.measured.height??0,k={id:y.id,parentId:y.parentId,rect:{width:H,height:Y,...jl({x:g.x??y.position.x,y:g.y??y.position.y},{width:H,height:Y},y.parentId,_,w)}},j=Gs([k],_,U,P);v.push(...j),b.x=g.x?Math.max(w[0]*H,g.x):void 0,b.y=g.y?Math.max(w[1]*Y,g.y):void 0}if(b.x!==void 0&&b.y!==void 0){const w={id:O,type:"position",position:{...b}};v.push(w)}if(g.width!==void 0&&g.height!==void 0){const H={id:O,type:"dimensions",resizing:!0,setAttributes:S?S==="horizontal"?"width":"height":!0,dimensions:{width:g.width,height:g.height}};v.push(H)}for(const w of p){const H={...w,type:"position"};v.push(H)}F(v)},onEnd:({width:g,height:p})=>{const F={id:O,type:"dimensions",resizing:!1,dimensions:{width:g,height:p}};C.getState().triggerNodeChanges([F])}})),M.current.update({controlPosition:x,boundaries:{minWidth:a,minHeight:T,maxWidth:l,maxHeight:R},keepAspectRatio:c,resizeDirection:S,onResizeStart:N,onResize:I,onResizeEnd:u,shouldResize:d}),()=>{var g;(g=M.current)==null||g.destroy()}},[x,a,T,l,R,c,N,I,u,d]);const B=x.split("-");return E.jsx("div",{className:Se(["react-flow__resize-control","nodrag",...B,n,r]),ref:m,style:{...o,scale:D,...i&&{[L?"backgroundColor":"borderColor"]:i}},children:s})}h.memo(xg);var jT=Object.defineProperty,Pg=(e,t,n)=>t in e?jT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,yg=(e,t)=>{for(var n in t)jT(e,n,{get:t[n],enumerable:!0})},Ug=(e,t,n)=>Pg(e,t+"",n),XT={};yg(XT,{Graph:()=>xe,alg:()=>ws,json:()=>KT,version:()=>Bg});var bg=Object.defineProperty,$T=(e,t)=>{for(var n in t)bg(e,n,{get:t[n],enumerable:!0})},xe=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,a,T=!1;typeof e=="object"&&e!==null&&"v"in e?(o=e.v,s=e.w,i=e.name,arguments.length===2&&(a=t,T=!0)):(o=e,s=t,i=r,arguments.length>2&&(a=n,T=!0)),o=""+o,s=""+s,i!==void 0&&(i=""+i);let l=an(this._isDirected,o,s,i);if(l in this._edgeLabels)return T&&(this._edgeLabels[l]=a),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[l]=T?a:this._defaultEdgeLabelFn(o,s,i);let R=vg(this._isDirected,o,s,i);return o=R.v,s=R.w,Object.freeze(R),this._edgeObjs[l]=R,ia(this._preds[s],o),ia(this._sucs[o],s),this._in[s][l]=R,this._out[o][l]=R,this._edgeCount++,this}edge(e,t,n){let r=arguments.length===1?wo(this._isDirected,e):an(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?wo(this._isDirected,e):an(this._isDirected,e,t,n))in this._edgeLabels}removeEdge(e,t,n){let r=arguments.length===1?wo(this._isDirected,e):an(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],Ea(this._preds[i],s),Ea(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 ia(e,t){e[t]?e[t]++:e[t]=1}function Ea(e,t){e[t]!==void 0&&!--e[t]&&delete e[t]}function an(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 vg(e,t,n,r){let o=""+t,s=""+n;if(!e&&o>s){let a=o;o=s,s=a}let i={v:o,w:s};return r&&(i.name=r),i}function wo(e,t){return an(e,t.v,t.w,t.name)}var Bg="4.0.1",KT={};$T(KT,{read:()=>wg,write:()=>Gg});function Gg(e){let t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:Hg(e),edges:Fg(e)},n=e.graph();return n!==void 0&&(t.value=structuredClone(n)),t}function Hg(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 Fg(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 wg(e){let t=new xe(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 ws={};$T(ws,{CycleException:()=>mr,bellmanFord:()=>zT,components:()=>Wg,dijkstra:()=>_r,dijkstraAll:()=>Xg,findCycles:()=>$g,floydWarshall:()=>zg,isAcyclic:()=>qg,postorder:()=>Qg,preorder:()=>e0,prim:()=>t0,shortestPaths:()=>n0,tarjan:()=>qT,topsort:()=>ZT});var Yg=()=>1;function zT(e,t,n,r){return Vg(e,String(t),n||Yg,r||function(o){return e.outEdges(o)})}function Vg(e,t,n,r){let o={},s,i=0,a=e.nodes(),T=function(c){let S=n(c);o[c.v].distance+S<o[c.w].distance&&(o[c.w]={distance:o[c.v].distance+S,predecessor:c.v},s=!0)},l=function(){a.forEach(function(c){r(c).forEach(function(S){let A=S.v===c?S.v:S.w,d=A===S.v?S.w:S.v;T({v:A,w:d})})})};a.forEach(function(c){let S=c===t?0:Number.POSITIVE_INFINITY;o[c]={distance:S,predecessor:""}});let R=a.length;for(let c=1;c<R&&(s=!1,i++,l(),!!s);c++);if(i===R-1&&(s=!1,l(),s))throw new Error("The graph contains a negative weight cycle");return o}function Wg(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 JT=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}},kg=()=>1;function _r(e,t,n,r){let o=function(s){return e.outEdges(s)};return jg(e,String(t),n||kg,r||o)}function jg(e,t,n,r){let o={},s=new JT,i,a,T=function(l){let R=l.v!==i?l.v:l.w,c=o[R],S=n(l),A=a.distance+S;if(S<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+l+" Weight: "+S);A<c.distance&&(c.distance=A,c.predecessor=i,s.decrease(R,A))};for(e.nodes().forEach(function(l){let R=l===t?0:Number.POSITIVE_INFINITY;o[l]={distance:R,predecessor:""},s.add(l,R)});s.size()>0&&(i=s.removeMin(),a=o[i],a.distance!==Number.POSITIVE_INFINITY);)r(i).forEach(T);return o}function Xg(e,t,n){return e.nodes().reduce(function(r,o){return r[o]=_r(e,o,t,n),r},{})}function qT(e){let t=0,n=[],r={},o=[];function s(i){let a=r[i]={onStack:!0,lowlink:t,index:t++};if(n.push(i),e.successors(i).forEach(function(T){T in r?r[T].onStack&&(a.lowlink=Math.min(a.lowlink,r[T].index)):(s(T),a.lowlink=Math.min(a.lowlink,r[T].lowlink))}),a.lowlink===a.index){let T=[],l;do l=n.pop(),r[l].onStack=!1,T.push(l);while(i!==l);o.push(T)}}return e.nodes().forEach(function(i){i in r||s(i)}),o}function $g(e){return qT(e).filter(function(t){return t.length>1||t.length===1&&e.hasEdge(t[0],t[0])})}var Kg=()=>1;function zg(e,t,n){return Jg(e,t||Kg,n||function(r){return e.outEdges(r)})}function Jg(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 a=i.v===s?i.w:i.v,T=t(i);r[s][a]={distance:T,predecessor:s}})}),o.forEach(function(s){let i=r[s];o.forEach(function(a){let T=r[a];o.forEach(function(l){let R=T[s],c=i[l],S=T[l],A=R.distance+c.distance;A<S.distance&&(S.distance=A,S.predecessor=c.predecessor)})})}),r}var mr=class extends Error{constructor(...e){super(...e)}};function ZT(e){let t={},n={},r=[];function o(s){if(s in n)throw new mr;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 mr;return r}function qg(e){try{ZT(e)}catch(t){if(t instanceof mr)return!1;throw t}return!0}function Zg(e,t,n,r,o){Array.isArray(t)||(t=[t]);let s=(a=>{var T;return(T=e.isDirected()?e.successors(a):e.neighbors(a))!=null?T:[]}),i={};return t.forEach(function(a){if(!e.hasNode(a))throw new Error("Graph does not have node: "+a);o=QT(e,a,n==="post",i,s,r,o)}),o}function QT(e,t,n,r,o,s,i){return t in r||(r[t]=!0,n||(i=s(i,t)),o(t).forEach(function(a){i=QT(e,a,n,r,o,s,i)}),n&&(i=s(i,t))),i}function ec(e,t,n){return Zg(e,t,n,function(r,o){return r.push(o),r},[])}function Qg(e,t){return ec(e,t,"post")}function e0(e,t){return ec(e,t,"pre")}function t0(e,t){let n=new xe,r={},o=new JT,s;function i(T){let l=T.v===s?T.w:T.v,R=o.priority(l);if(R!==void 0){let c=t(T);c<R&&(r[l]=s,o.decrease(l,c))}}if(e.nodeCount()===0)return n;e.nodes().forEach(function(T){o.add(T,Number.POSITIVE_INFINITY),n.setNode(T)}),o.decrease(e.nodes()[0],0);let a=!1;for(;o.size()>0;){if(s=o.removeMin(),s in r)n.setEdge(s,r[s]);else{if(a)throw new Error("Input graph is not connected: "+e);a=!0}e.nodeEdges(s).forEach(i)}return n}function n0(e,t,n,r){return r0(e,t,n,r??(o=>{let s=e.outEdges(o);return s??[]}))}function r0(e,t,n,r){if(n===void 0)return _r(e,t,n,r);let o=!1,s=e.nodes();for(let i=0;i<s.length;i++){let a=r(s[i]);for(let T=0;T<a.length;T++){let l=a[T],R=l.v===s[i]?l.v:l.w,c=R===l.v?l.w:l.v;n({v:R,w:c})<0&&(o=!0)}if(o)return zT(e,t,n,r)}return _r(e,t,n,r)}function $t(e,t,n,r){let o=r;for(;e.hasNode(o);)o=Ys(r);return n.dummy=t,e.setNode(o,n),o}function o0(e){let t=new xe().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 tc(e){let t=new xe({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 aa(e,t){let n=e.x,r=e.y,o=t.x-n,s=t.y-r,i=e.width/2,a=e.height/2;if(!o&&!s)throw new Error("Not possible to find intersection inside of the rectangle");let T,l;return Math.abs(s)*i>Math.abs(o)*a?(s<0&&(a=-a),T=a*o/s,l=a):(o<0&&(i=-i),T=i,l=i*s/o),{x:n+T,y:r+l}}function Un(e){let t=pn(rc(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 s0(e){let t=e.nodes().map(r=>{let o=e.node(r).rank;return o===void 0?Number.MAX_VALUE:o}),n=we(Math.min,t);e.nodes().forEach(r=>{let o=e.node(r);Object.hasOwn(o,"rank")&&(o.rank-=n)})}function i0(e){let t=e.nodes().map(i=>e.node(i).rank).filter(i=>i!==void 0),n=we(Math.min,t),r=[];e.nodes().forEach(i=>{let a=e.node(i).rank-n;r[a]||(r[a]=[]),r[a].push(i)});let o=0,s=e.graph().nodeRankFactor;Array.from(r).forEach((i,a)=>{i===void 0&&a%s!==0?--o:i!==void 0&&o&&i.forEach(T=>e.node(T).rank+=o)})}function la(e,t,n,r){let o={width:0,height:0};return arguments.length>=4&&(o.rank=n,o.order=r),$t(e,"border",o,t)}function E0(e,t=nc){let n=[];for(let r=0;r<e.length;r+=t){let o=e.slice(r,r+t);n.push(o)}return n}var nc=65535;function we(e,t){if(t.length>nc){let n=E0(t);return e(...n.map(r=>e(...r)))}else return e(...t)}function rc(e){let t=e.nodes().map(n=>{let r=e.node(n).rank;return r===void 0?Number.MIN_VALUE:r});return we(Math.max,t)}function a0(e,t){let n={lhs:[],rhs:[]};return e.forEach(r=>{t(r)?n.lhs.push(r):n.rhs.push(r)}),n}function oc(e,t){let n=Date.now();try{return t()}finally{console.log(e+" time: "+(Date.now()-n)+"ms")}}function sc(e,t){return t()}var l0=0;function Ys(e){let t=++l0;return e+(""+t)}function pn(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 Dr(e,t){let n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return n}function kr(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 T0(e,t){return e.reduce((n,r,o)=>(n[r]=t[o],n),{})}var jr="\0",c0="3.0.0",R0=class{constructor(){Ug(this,"_sentinel");let e={};e._next=e._prev=e,this._sentinel=e}dequeue(){let e=this._sentinel,t=e._prev;if(t!==e)return Ta(t),t}enqueue(e){let t=this._sentinel;e._prev&&e._next&&Ta(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,S0)),n=n._prev;return"["+e.join(", ")+"]"}};function Ta(e){e._prev._next=e._next,e._next._prev=e._prev,delete e._next,delete e._prev}function S0(e,t){if(e!=="_next"&&e!=="_prev")return t}var A0=R0,d0=()=>1;function u0(e,t){if(e.nodeCount()<=1)return[];let n=N0(e,t||d0);return I0(n.graph,n.buckets,n.zeroIdx).flatMap(r=>e.outEdges(r.v,r.w)||[])}function I0(e,t,n){var r;let o=[],s=t[t.length-1],i=t[0],a;for(;e.nodeCount();){for(;a=i.dequeue();)Yo(e,t,n,a);for(;a=s.dequeue();)Yo(e,t,n,a);if(e.nodeCount()){for(let T=t.length-2;T>0;--T)if(a=(r=t[T])==null?void 0:r.dequeue(),a){o=o.concat(Yo(e,t,n,a,!0)||[]);break}}}return o}function Yo(e,t,n,r,o){let s=[],i=o?s:void 0;return(e.inEdges(r.v)||[]).forEach(a=>{let T=e.edge(a),l=e.node(a.v);o&&s.push({v:a.v,w:a.w}),l.out-=T,Ss(t,n,l)}),(e.outEdges(r.v)||[]).forEach(a=>{let T=e.edge(a),l=a.w,R=e.node(l);R.in-=T,Ss(t,n,R)}),e.removeNode(r.v),i}function N0(e,t){let n=new xe,r=0,o=0;e.nodes().forEach(a=>{n.setNode(a,{v:a,in:0,out:0})}),e.edges().forEach(a=>{let T=n.edge(a.v,a.w)||0,l=t(a),R=T+l;n.setEdge(a.v,a.w,R);let c=n.node(a.v),S=n.node(a.w);o=Math.max(o,c.out+=l),r=Math.max(r,S.in+=l)});let s=O0(o+r+3).map(()=>new A0),i=r+1;return n.nodes().forEach(a=>{Ss(s,i,n.node(a))}),{graph:n,buckets:s,zeroIdx:i}}function Ss(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 O0(e){let t=[];for(let n=0;n<e;n++)t.push(n);return t}function f0(e){(e.graph().acyclicer==="greedy"?u0(e,t(e)):h0(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,Ys("rev"))});function t(n){return r=>n.edge(r).weight}}function h0(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 C0(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 L0(e){e.graph().dummyChains=[],e.edges().forEach(t=>p0(e,t))}function p0(e,t){let n=t.v,r=e.node(n).rank,o=t.w,s=e.node(o).rank,i=t.name,a=e.edge(t),T=a.labelRank;if(s===r+1)return;e.removeEdge(t);let l,R,c;for(c=0,++r;r<s;++c,++r)a.points=[],R={width:0,height:0,edgeLabel:a,edgeObj:t,rank:r},l=$t(e,"edge",R,"_d"),r===T&&(R.width=a.width,R.height=a.height,R.dummy="edge-label",R.labelpos=a.labelpos),e.setEdge(n,l,{weight:a.weight},i),c===0&&e.graph().dummyChains.push(l),n=l;e.setEdge(n,o,{weight:a.weight},i)}function _0(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 Vs(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(T=>T==null?Number.POSITIVE_INFINITY:n(T.w)-e.edge(T).minlen):[],a=we(Math.min,i);return a===Number.POSITIVE_INFINITY&&(a=0),o.rank=a}e.sources().forEach(n)}function jt(e,t){return e.node(t.w).rank-e.node(t.v).rank-e.edge(t).minlen}var ic=m0;function m0(e){let t=new xe({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(;D0(t,e)<o&&(s=g0(t,e),!!s);)i=t.hasNode(s.v)?jt(e,s):-jt(e,s),M0(t,e,i);return t}function D0(e,t){function n(r){let o=t.nodeEdges(r);o&&o.forEach(s=>{let i=s.v,a=r===i?s.w:i;!e.hasNode(a)&&!jt(t,s)&&(e.setNode(a,{}),e.setEdge(r,a,{}),n(a))})}return e.nodes().forEach(n),e.nodeCount()}function g0(e,t){return t.edges().reduce((n,r)=>{let o=Number.POSITIVE_INFINITY;return e.hasNode(r.v)!==e.hasNode(r.w)&&(o=jt(t,r)),o<n[0]?[o,r]:n},[Number.POSITIVE_INFINITY,null])[1]}function M0(e,t,n){e.nodes().forEach(r=>t.node(r).rank+=n)}var{preorder:x0,postorder:P0}=ws,y0=Ct;Ct.initLowLimValues=ks;Ct.initCutValues=Ws;Ct.calcCutValue=Ec;Ct.leaveEdge=lc;Ct.enterEdge=Tc;Ct.exchangeEdges=cc;function Ct(e){e=o0(e),Vs(e);let t=ic(e);ks(t),Ws(t,e);let n,r;for(;n=lc(t);)r=Tc(t,e,n),cc(t,e,n,r)}function Ws(e,t){let n=P0(e,e.nodes());n=n.slice(0,n.length-1),n.forEach(r=>U0(e,t,r))}function U0(e,t,n){let r=e.node(n).parent,o=e.edge(n,r);o.cutvalue=Ec(e,t,n)}function Ec(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 a=t.nodeEdges(n);return a&&a.forEach(T=>{let l=T.v===n,R=l?T.w:T.v;if(R!==r){let c=l===o,S=t.edge(T).weight;if(i+=c?S:-S,v0(e,n,R)){let A=e.edge(n,R).cutvalue;i+=c?-A:A}}}),i}function ks(e,t){arguments.length<2&&(t=e.nodes()[0]),ac(e,{},1,t)}function ac(e,t,n,r,o){let s=n,i=e.node(r);t[r]=!0;let a=e.neighbors(r);return a&&a.forEach(T=>{Object.hasOwn(t,T)||(n=ac(e,t,n,T,r))}),i.low=s,i.lim=n++,o?i.parent=o:delete i.parent,n}function lc(e){return e.edges().find(t=>e.edge(t).cutvalue<0)}function Tc(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),a=s,T=!1;return s.lim>i.lim&&(a=i,T=!0),t.edges().filter(l=>T===ca(e,e.node(l.v),a)&&T!==ca(e,e.node(l.w),a)).reduce((l,R)=>jt(t,R)<jt(t,l)?R:l)}function cc(e,t,n,r){let o=n.v,s=n.w;e.removeEdge(o,s),e.setEdge(r.v,r.w,{}),ks(e),Ws(e,t),b0(e,t)}function b0(e,t){let n=e.nodes().find(o=>!e.node(o).parent);if(!n)return;let r=x0(e,[n]);r=r.slice(1),r.forEach(o=>{let s=e.node(o).parent,i=t.edge(o,s),a=!1;i||(i=t.edge(s,o),a=!0),t.node(o).rank=t.node(s).rank+(a?i.minlen:-i.minlen)})}function v0(e,t,n){return e.hasEdge(t,n)}function ca(e,t,n){return n.low<=t.lim&&t.lim<=n.lim}var B0=G0;function G0(e){let t=e.graph().ranker;if(typeof t=="function")return t(e);switch(t){case"network-simplex":Ra(e);break;case"tight-tree":F0(e);break;case"longest-path":H0(e);break;case"none":break;default:Ra(e)}}var H0=Vs;function F0(e){Vs(e),ic(e)}function Ra(e){y0(e)}var w0=Y0;function Y0(e){let t=W0(e);e.graph().dummyChains.forEach(n=>{let r=e.node(n),o=r.edgeObj,s=V0(e,t,o.v,o.w),i=s.path,a=s.lca,T=0,l=i[T],R=!0;for(;n!==o.w;){if(r=e.node(n),R){for(;(l=i[T])!==a&&e.node(l).maxRank<r.rank;)T++;l===a&&(R=!1)}if(!R){for(;T<i.length-1&&e.node(i[T+1]).minRank<=r.rank;)T++;l=i[T]}l!==void 0&&e.setParent(n,l),n=e.successors(n)[0]}})}function V0(e,t,n,r){let o=[],s=[],i=Math.min(t[n].low,t[r].low),a=Math.max(t[n].lim,t[r].lim),T;T=n;do T=e.parent(T),o.push(T);while(T&&(t[T].low>i||a>t[T].lim));let l=T,R=r;for(;(R=e.parent(R))!==l;)s.push(R);return{path:o.concat(s.reverse()),lca:l}}function W0(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(jr).forEach(r),t}function k0(e){let t=$t(e,"root",{},"_root"),n=j0(e),r=Object.values(n),o=we(Math.max,r)-1,s=2*o+1;e.graph().nestingRoot=t,e.edges().forEach(a=>e.edge(a).minlen*=s);let i=X0(e)+1;e.children(jr).forEach(a=>Rc(e,t,s,i,o,n,a)),e.graph().nodeRankFactor=s}function Rc(e,t,n,r,o,s,i){var a;let T=e.children(i);if(!T.length){i!==t&&e.setEdge(t,i,{weight:0,minlen:n});return}let l=la(e,"_bt"),R=la(e,"_bb"),c=e.node(i);e.setParent(l,i),c.borderTop=l,e.setParent(R,i),c.borderBottom=R,T.forEach(S=>{var A;Rc(e,t,n,r,o,s,S);let d=e.node(S),N=d.borderTop?d.borderTop:S,I=d.borderBottom?d.borderBottom:S,u=d.borderTop?r:2*r,f=N!==I?1:o-((A=s[i])!=null?A:0)+1;e.setEdge(l,N,{weight:u,minlen:f,nestingEdge:!0}),e.setEdge(I,R,{weight:u,minlen:f,nestingEdge:!0})}),e.parent(i)||e.setEdge(t,l,{weight:0,minlen:o+((a=s[i])!=null?a:0)})}function j0(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(jr).forEach(r=>n(r,1)),t}function X0(e){return e.edges().reduce((t,n)=>t+e.edge(n).weight,0)}function $0(e){let t=e.graph();e.removeNode(t.nestingRoot),delete t.nestingRoot,e.edges().forEach(n=>{e.edge(n).nestingEdge&&e.removeEdge(n)})}var K0=z0;function z0(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)Sa(e,"borderLeft","_bl",n,o,s),Sa(e,"borderRight","_br",n,o,s)}}e.children(jr).forEach(t)}function Sa(e,t,n,r,o,s){let i={width:0,height:0,rank:s,borderType:t},a=o[t][s-1],T=$t(e,"border",i,n);o[t][s]=T,e.setParent(T,r),a&&e.setEdge(a,T,{weight:1})}function J0(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="lr"||n==="rl")&&Sc(e)}function q0(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n==="bt"||n==="rl")&&Z0(e),(n==="lr"||n==="rl")&&(Q0(e),Sc(e))}function Sc(e){e.nodes().forEach(t=>Aa(e.node(t))),e.edges().forEach(t=>Aa(e.edge(t)))}function Aa(e){let t=e.width;e.width=e.height,e.height=t}function Z0(e){e.nodes().forEach(t=>Vo(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(Vo),Object.hasOwn(r,"y")&&Vo(r)})}function Vo(e){e.y=-e.y}function Q0(e){e.nodes().forEach(t=>Wo(e.node(t))),e.edges().forEach(t=>{var n;let r=e.edge(t);(n=r.points)==null||n.forEach(Wo),Object.hasOwn(r,"x")&&Wo(r)})}function Wo(e){let t=e.x;e.x=e.y,e.y=t}function eM(e){let t={},n=e.nodes().filter(a=>!e.children(a).length),r=n.map(a=>e.node(a).rank),o=we(Math.max,r),s=pn(o+1).map(()=>[]);function i(a){if(t[a])return;t[a]=!0;let T=e.node(a);s[T.rank].push(a);let l=e.successors(a);l&&l.forEach(i)}return n.sort((a,T)=>e.node(a).rank-e.node(T).rank).forEach(i),s}function tM(e,t){let n=0;for(let r=1;r<t.length;++r)n+=nM(e,t[r-1],t[r]);return n}function nM(e,t,n){let r=T0(n,n.map((l,R)=>R)),o=t.flatMap(l=>{let R=e.outEdges(l);return R?R.map(c=>({pos:r[c.w],weight:e.edge(c).weight})).sort((c,S)=>c.pos-S.pos):[]}),s=1;for(;s<n.length;)s<<=1;let i=2*s-1;s-=1;let a=new Array(i).fill(0),T=0;return o.forEach(l=>{let R=l.pos+s;a[R]+=l.weight;let c=0;for(;R>0;)R%2&&(c+=a[R+1]),R=R-1>>1,a[R]+=l.weight;T+=l.weight*c}),T}function rM(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 a=e.edge(i),T=e.node(i.v);return{sum:s.sum+a.weight*T.order,weight:s.weight+a.weight}},{sum:0,weight:0});return{v:n,barycenter:o.sum/o.weight,weight:o.weight}}})}function oM(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 sM(r)}function sM(e){let t=[];function n(o){return s=>{s.merged||(s.barycenter===void 0||o.barycenter===void 0||s.barycenter>=o.barycenter)&&iM(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=>Dr(o,["vs","i","barycenter","weight"]))}function iM(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 EM(e,t){let n=a0(e,R=>Object.hasOwn(R,"barycenter")),r=n.lhs,o=n.rhs.sort((R,c)=>c.i-R.i),s=[],i=0,a=0,T=0;r.sort(aM(!!t)),T=da(s,o,T),r.forEach(R=>{T+=R.vs.length,s.push(R.vs),i+=R.barycenter*R.weight,a+=R.weight,T=da(s,o,T)});let l={vs:s.flat(1)};return a&&(l.barycenter=i/a,l.weight=a),l}function da(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 aM(e){return(t,n)=>t.barycenter<n.barycenter?-1:t.barycenter>n.barycenter?1:e?n.i-t.i:t.i-n.i}function Ac(e,t,n,r){let o=e.children(t),s=e.node(t),i=s?s.borderLeft:void 0,a=s?s.borderRight:void 0,T={};i&&(o=o.filter(S=>S!==i&&S!==a));let l=rM(e,o);l.forEach(S=>{if(e.children(S.v).length){let A=Ac(e,S.v,n,r);T[S.v]=A,Object.hasOwn(A,"barycenter")&&TM(S,A)}});let R=oM(l,n);lM(R,T);let c=EM(R,r);if(i&&a){c.vs=[i,c.vs,a].flat(1);let S=e.predecessors(i);if(S&&S.length){let A=e.node(S[0]),d=e.predecessors(a),N=e.node(d[0]);Object.hasOwn(c,"barycenter")||(c.barycenter=0,c.weight=0),c.barycenter=(c.barycenter*c.weight+A.order+N.order)/(c.weight+2),c.weight+=2}}return c}function lM(e,t){e.forEach(n=>{n.vs=n.vs.flatMap(r=>t[r]?t[r].vs:r)})}function TM(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 cM(e,t,n,r){r||(r=e.nodes());let o=RM(e),s=new xe({compound:!0}).setGraph({root:o}).setDefaultNodeLabel(i=>e.node(i));return r.forEach(i=>{let a=e.node(i),T=e.parent(i);if(a.rank===t||a.minRank<=t&&t<=a.maxRank){s.setNode(i),s.setParent(i,T||o);let l=e[n](i);l&&l.forEach(R=>{let c=R.v===i?R.w:R.v,S=s.edge(c,i),A=S!==void 0?S.weight:0;s.setEdge(c,i,{weight:e.edge(R).weight+A})}),Object.hasOwn(a,"minRank")&&s.setNode(i,{borderLeft:a.borderLeft[t],borderRight:a.borderRight[t]})}}),s}function RM(e){let t;for(;e.hasNode(t=Ys("_root")););return t}function SM(e,t,n){let r={},o;n.forEach(s=>{let i=e.parent(s),a,T;for(;i;){if(a=e.parent(i),a?(T=r[a],r[a]=i):(T=o,o=i),T&&T!==i){t.setEdge(T,i);return}i=a}})}function dc(e,t={}){if(typeof t.customOrder=="function"){t.customOrder(e,dc);return}let n=rc(e),r=ua(e,pn(1,n+1),"inEdges"),o=ua(e,pn(n-1,-1,-1),"outEdges"),s=eM(e);if(Ia(e,s),t.disableOptimalOrderHeuristic)return;let i=Number.POSITIVE_INFINITY,a,T=t.constraints||[];for(let l=0,R=0;R<4;++l,++R){AM(l%2?r:o,l%4>=2,T),s=Un(e);let c=tM(e,s);c<i?(R=0,a=Object.assign({},s),i=c):c===i&&(a=structuredClone(s))}Ia(e,a)}function ua(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 a=i.minRank;a<=i.maxRank;a++)a!==i.rank&&o(a,s)}return t.map(function(s){return cM(e,s,n,r.get(s)||[])})}function AM(e,t,n){let r=new xe;e.forEach(function(o){n.forEach(a=>r.setEdge(a.left,a.right));let s=o.graph().root,i=Ac(o,s,r,t);i.vs.forEach((a,T)=>o.node(a).order=T),SM(o,r,i.vs)})}function Ia(e,t){Object.values(t).forEach(n=>n.forEach((r,o)=>e.node(r).order=o))}function dM(e,t){let n={};function r(o,s){let i=0,a=0,T=o.length,l=s[s.length-1];return s.forEach((R,c)=>{let S=IM(e,R),A=S?e.node(S).order:T;(S||R===l)&&(s.slice(a,c+1).forEach(d=>{let N=e.predecessors(d);N&&N.forEach(I=>{let u=e.node(I),f=u.order;(f<i||A<f)&&!(u.dummy&&e.node(d).dummy)&&uc(n,I,d)})}),a=c+1,i=A)}),s}return t.length&&t.reduce(r),n}function uM(e,t){let n={};function r(s,i,a,T,l){pn(i,a).forEach(R=>{let c=s[R];if(c!==void 0&&e.node(c).dummy){let S=e.predecessors(c);S&&S.forEach(A=>{if(A===void 0)return;let d=e.node(A);d.dummy&&(d.order<T||d.order>l)&&uc(n,A,c)})}})}function o(s,i){let a=-1,T=-1,l=0;return i.forEach((R,c)=>{if(e.node(R).dummy==="border"){let S=e.predecessors(R);if(S&&S.length){let A=S[0];if(A===void 0)return;T=e.node(A).order,r(i,l,c,a,T),l=c,a=T}}r(i,l,i.length,T,s.length)}),i}return t.length&&t.reduce(o),n}function IM(e,t){if(e.node(t).dummy){let n=e.predecessors(t);if(n)return n.find(r=>e.node(r).dummy)}}function uc(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 NM(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 OM(e,t,n,r){let o={},s={},i={};return t.forEach(a=>{a.forEach((T,l)=>{o[T]=T,s[T]=T,i[T]=l})}),t.forEach(a=>{let T=-1;a.forEach(l=>{let R=r(l);if(R&&R.length){let c=R.sort((A,d)=>{let N=i[A],I=i[d];return(N!==void 0?N:0)-(I!==void 0?I:0)}),S=(c.length-1)/2;for(let A=Math.floor(S),d=Math.ceil(S);A<=d;++A){let N=c[A];if(N===void 0)continue;let I=i[N];if(I!==void 0&&s[l]===l&&T<I&&!NM(n,l,N)){let u=o[N];u!==void 0&&(s[N]=l,s[l]=o[l]=u,T=I)}}}})}),{root:o,align:s}}function fM(e,t,n,r,o=!1){let s={},i=hM(e,t,n,o),a=o?"borderLeft":"borderRight";function T(A,d){let N=i.nodes().slice(),I={},u=N.pop();for(;u;){if(I[u])A(u);else{I[u]=!0,N.push(u);for(let f of d(u))N.push(f)}u=N.pop()}}function l(A){let d=i.inEdges(A);d?s[A]=d.reduce((N,I)=>{var u;let f=(u=s[I.v])!=null?u:0,O=i.edge(I);return Math.max(N,f+(O!==void 0?O:0))},0):s[A]=0}function R(A){let d=i.outEdges(A),N=Number.POSITIVE_INFINITY;d&&(N=d.reduce((u,f)=>{let O=s[f.w],C=i.edge(f);return Math.min(u,(O!==void 0?O:0)-(C!==void 0?C:0))},Number.POSITIVE_INFINITY));let I=e.node(A);N!==Number.POSITIVE_INFINITY&&I.borderType!==a&&(s[A]=Math.max(s[A]!==void 0?s[A]:0,N))}function c(A){return i.predecessors(A)||[]}function S(A){return i.successors(A)||[]}return T(l,c),T(R,S),Object.keys(r).forEach(A=>{var d;let N=n[A];N!==void 0&&(s[A]=(d=s[N])!=null?d:0)}),s}function hM(e,t,n,r){let o=new xe,s=e.graph(),i=mM(s.nodesep,s.edgesep,r);return t.forEach(a=>{let T;a.forEach(l=>{let R=n[l];if(R!==void 0){if(o.setNode(R),T!==void 0){let c=n[T];if(c!==void 0){let S=o.edge(c,R);o.setEdge(c,R,Math.max(i(e,l,T),S||0))}}T=l}})}),o}function CM(e,t){return Object.values(t).reduce((n,r)=>{let o=Number.NEGATIVE_INFINITY,s=Number.POSITIVE_INFINITY;Object.entries(r).forEach(([a,T])=>{let l=DM(e,a)/2;o=Math.max(T+l,o),s=Math.min(T-l,s)});let i=o-s;return i<n[0]&&(n=[i,r]),n},[Number.POSITIVE_INFINITY,null])[1]}function LM(e,t){let n=Object.values(t),r=we(Math.min,n),o=we(Math.max,n);["u","d"].forEach(s=>{["l","r"].forEach(i=>{let a=s+i,T=e[a];if(!T||T===t)return;let l=Object.values(T),R=r-we(Math.min,l);i!=="l"&&(R=o-we(Math.max,l)),R&&(e[a]=kr(T,c=>c+R))})})}function pM(e,t=void 0){let n=e.ul;return n?kr(n,(r,o)=>{var s,i;if(t){let T=t.toLowerCase(),l=e[T];if(l&&l[o]!==void 0)return l[o]}let a=Object.values(e).map(T=>{let l=T[o];return l!==void 0?l:0}).sort((T,l)=>T-l);return(((s=a[1])!=null?s:0)+((i=a[2])!=null?i:0))/2}):{}}function _M(e){let t=Un(e),n=Object.assign(dM(e,t),uM(e,t)),r={},o;["u","d"].forEach(i=>{o=i==="u"?t:Object.values(t).reverse(),["l","r"].forEach(a=>{a==="r"&&(o=o.map(R=>Object.values(R).reverse()));let T=OM(e,o,n,R=>(i==="u"?e.predecessors(R):e.successors(R))||[]),l=fM(e,o,T.root,T.align,a==="r");a==="r"&&(l=kr(l,R=>-R)),r[i+a]=l})});let s=CM(e,r);return LM(r,s),pM(r,e.graph().align)}function mM(e,t,n){return(r,o,s)=>{let i=r.node(o),a=r.node(s),T=0,l;if(T+=i.width/2,Object.hasOwn(i,"labelpos"))switch(i.labelpos.toLowerCase()){case"l":l=-i.width/2;break;case"r":l=i.width/2;break}if(l&&(T+=n?l:-l),l=void 0,T+=(i.dummy?t:e)/2,T+=(a.dummy?t:e)/2,T+=a.width/2,Object.hasOwn(a,"labelpos"))switch(a.labelpos.toLowerCase()){case"l":l=a.width/2;break;case"r":l=-a.width/2;break}return l&&(T+=n?l:-l),T}}function DM(e,t){return e.node(t).width}function gM(e){e=tc(e),MM(e),Object.entries(_M(e)).forEach(([t,n])=>e.node(t).x=n)}function MM(e){let t=Un(e),n=e.graph(),r=n.ranksep,o=n.rankalign,s=0;t.forEach(i=>{let a=i.reduce((T,l)=>{var R;let c=(R=e.node(l).height)!=null?R:0;return T>c?T:c},0);i.forEach(T=>{let l=e.node(T);o==="top"?l.y=s+l.height/2:o==="bottom"?l.y=s+a-l.height/2:l.y=s+a/2}),s+=a+r})}function xM(e,t={}){let n=t.debugTiming?oc:sc;return n("layout",()=>{let r=n(" buildLayoutGraph",()=>wM(e));return n(" runLayout",()=>PM(r,n,t)),n(" updateInputGraph",()=>yM(e,r)),r})}function PM(e,t,n){t(" makeSpaceForEdgeLabels",()=>YM(e)),t(" removeSelfEdges",()=>JM(e)),t(" acyclic",()=>f0(e)),t(" nestingGraph.run",()=>k0(e)),t(" rank",()=>B0(tc(e))),t(" injectEdgeLabelProxies",()=>VM(e)),t(" removeEmptyRanks",()=>i0(e)),t(" nestingGraph.cleanup",()=>$0(e)),t(" normalizeRanks",()=>s0(e)),t(" assignRankMinMax",()=>WM(e)),t(" removeEdgeLabelProxies",()=>kM(e)),t(" normalize.run",()=>L0(e)),t(" parentDummyChains",()=>w0(e)),t(" addBorderSegments",()=>K0(e)),t(" order",()=>dc(e,n)),t(" insertSelfEdges",()=>qM(e)),t(" adjustCoordinateSystem",()=>J0(e)),t(" position",()=>gM(e)),t(" positionSelfEdges",()=>ZM(e)),t(" removeBorderNodes",()=>zM(e)),t(" normalize.undo",()=>_0(e)),t(" fixupEdgeLabelCoords",()=>$M(e)),t(" undoCoordinateSystem",()=>q0(e)),t(" translateGraph",()=>jM(e)),t(" assignNodeIntersects",()=>XM(e)),t(" reversePoints",()=>KM(e)),t(" acyclic.undo",()=>C0(e))}function yM(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 UM=["nodesep","edgesep","ranksep","marginx","marginy"],bM={ranksep:50,edgesep:20,nodesep:50,rankdir:"TB",rankalign:"center"},vM=["acyclicer","ranker","rankdir","align","rankalign"],BM=["width","height","rank"],Na={width:0,height:0},GM=["minlen","weight","width","height","labeloffset"],HM={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},FM=["labelpos"];function wM(e){let t=new xe({multigraph:!0,compound:!0}),n=jo(e.graph());return t.setGraph(Object.assign({},bM,ko(n,UM),Dr(n,vM))),e.nodes().forEach(r=>{let o=jo(e.node(r)),s=ko(o,BM);Object.keys(Na).forEach(a=>{s[a]===void 0&&(s[a]=Na[a])}),t.setNode(r,s);let i=e.parent(r);i!==void 0&&t.setParent(r,i)}),e.edges().forEach(r=>{let o=jo(e.edge(r));t.setEdge(r,Object.assign({},HM,ko(o,GM),Dr(o,FM)))}),t}function YM(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 VM(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};$t(e,"edge-proxy",o,"_ep")}})}function WM(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 kM(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 jM(e){let t=Number.POSITIVE_INFINITY,n=0,r=Number.POSITIVE_INFINITY,o=0,s=e.graph(),i=s.marginx||0,a=s.marginy||0;function T(l){let R=l.x,c=l.y,S=l.width,A=l.height;t=Math.min(t,R-S/2),n=Math.max(n,R+S/2),r=Math.min(r,c-A/2),o=Math.max(o,c+A/2)}e.nodes().forEach(l=>T(e.node(l))),e.edges().forEach(l=>{let R=e.edge(l);Object.hasOwn(R,"x")&&T(R)}),t-=i,r-=a,e.nodes().forEach(l=>{let R=e.node(l);R.x-=t,R.y-=r}),e.edges().forEach(l=>{let R=e.edge(l);R.points.forEach(c=>{c.x-=t,c.y-=r}),Object.hasOwn(R,"x")&&(R.x-=t),Object.hasOwn(R,"y")&&(R.y-=r)}),s.width=n-t+i,s.height=o-r+a}function XM(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(aa(r,s)),n.points.push(aa(o,i))})}function $M(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 KM(e){e.edges().forEach(t=>{let n=e.edge(t);n.reversed&&n.points.reverse()})}function zM(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 JM(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 qM(e){Un(e).forEach(t=>{let n=0;t.forEach((r,o)=>{let s=e.node(r);s.order=o+n,(s.selfEdges||[]).forEach(i=>{$t(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 ZM(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,a=n.x-s,T=o.height/2;e.setEdge(r.e,r.label),e.removeNode(t),r.label.points=[{x:s+2*a/3,y:i-T},{x:s+5*a/6,y:i-T},{x:s+a,y:i},{x:s+5*a/6,y:i+T},{x:s+2*a/3,y:i+T}],r.label.x=n.x,r.label.y=n.y}})}function ko(e,t){return kr(Dr(e,t),Number)}function jo(e){let t={};return e&&Object.entries(e).forEach(([n,r])=>{typeof n=="string"&&(n=n.toLowerCase()),t[n]=r}),t}function QM(e){let t=Un(e),n=new xe({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,a)=>(n.setEdge(i,a,{style:"invis"}),a))}),n}var ex={graphlib:XT,version:c0,layout:xM,debug:QM,util:{time:oc,notime:sc}},Oa=ex;/*! For license information please see dagre.esm.js.LEGAL.txt */const He={source_table:"#8b949e",block:"#56d364",metric:"#388bfd",dimension:"#e3b341",domain:"#d2a8ff",chart:"#f778ba"},ar={source_table:"TABLE",block:"BLOCK",metric:"METRIC",dimension:"DIM",domain:"DOMAIN",chart:"CHART"},Ic={certified:"#56d364",draft:"#8b949e",review:"#e3b341",deprecated:"#f85149",pending_recertification:"#d29922"},Xo={reads_from:"#8b949e",feeds_into:"#56d364",aggregates:"#388bfd",visualizes:"#f778ba",crosses_domain:"#d2a8ff"};function tx(e,t,n="LR"){const r=new Oa.graphlib.Graph().setDefaultEdgeLabel(()=>({}));r.setGraph({rankdir:n,ranksep:80,nodesep:40,marginx:40,marginy:40});for(const s of e){const i=s.type==="domainGroup"?200:180,a=s.type==="domainGroup"?60:56;r.setNode(s.id,{width:i,height:a})}for(const s of t)r.setEdge(s.source,s.target);return Oa.layout(r),{nodes:e.map(s=>{const i=r.node(s.id),a=s.type==="domainGroup"?200:180,T=s.type==="domainGroup"?60:56;return{...s,position:{x:i.x-a/2,y:i.y-T/2}}}),edges:t}}function nx({data:e,selected:t}){const n=e.nodeType,r=He[n]??"#8b949e",o=ar[n]??n.slice(0,5).toUpperCase(),s=e.label,i=e.domain,a=e.status,T=a?Ic[a]:void 0,l=e.highlighted,R=e.dimmed;return E.jsxs("div",{style:{background:"#161b22",border:`2px solid ${t?"#58a6ff":l?r:"#30363d"}`,borderRadius:8,padding:"6px 10px",minWidth:140,maxWidth:200,opacity:R?.3:1,transition:"opacity 0.2s, border-color 0.2s",cursor:"pointer"},children:[E.jsx(kt,{type:"target",position:Z.Left,style:{background:r,width:6,height:6,border:"none"}}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginBottom:3},children:[E.jsx("span",{style:{fontSize:9,fontWeight:700,color:"#0d1117",background:r,borderRadius:3,padding:"1px 5px",letterSpacing:"0.5px"},children:o}),i&&E.jsx("span",{style:{fontSize:9,color:"#8b949e"},children:i}),T&&E.jsx("span",{style:{marginLeft:"auto",width:7,height:7,borderRadius:"50%",background:T,flexShrink:0},title:a})]}),E.jsx("div",{style:{fontSize:11,fontWeight:600,color:"#e6edf3",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:s,children:s}),E.jsx(kt,{type:"source",position:Z.Right,style:{background:r,width:6,height:6,border:"none"}})]})}const rx={dagNode:nx};function on({label:e,color:t,active:n,count:r,onClick:o}){return E.jsxs("button",{onClick:o,style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:9,fontWeight:600,padding:"2px 6px",borderRadius:4,border:`1px solid ${n?t:"#30363d"}`,background:n?`${t}20`:"transparent",color:n?t:"#8b949e",cursor:"pointer",transition:"all 0.15s"},children:[E.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:n?t:"#484f58"}}),e,E.jsx("span",{style:{fontWeight:400,opacity:.7},children:r})]})}function ox(){const{state:e}=ae(),t=re[e.themeMode],[n,r]=h.useState(!0),[o,s]=h.useState([]),[i,a]=h.useState([]),[T,l,R]=tg([]),[c,S,A]=ng([]),[d,N]=h.useState(!0),[I,u]=h.useState(!0),[f,O]=h.useState(!0),[C,m]=h.useState(!0),[L,D]=h.useState(!0),[M,x]=h.useState(null),[B,g]=h.useState(new Set),[p,F]=h.useState(null),[_,U]=h.useState([]),[P,v]=h.useState([]),b=h.useCallback(async()=>{r(!0);const k=await le.fetchLineage();s(k.nodes??[]),a(k.edges??[]),r(!1)},[]);h.useEffect(()=>{b()},[b]);const y=h.useMemo(()=>{const k=new Set;return d&&k.add("source_table"),I&&k.add("block"),f&&k.add("metric"),C&&k.add("dimension"),L&&k.add("chart"),k.add("domain"),k},[d,I,f,C,L]);h.useEffect(()=>{const k=o.filter(X=>y.has(X.type)),j=new Set(k.map(X=>X.id)),K=k.map(X=>({id:X.id,type:"dagNode",position:{x:0,y:0},data:{label:X.name,nodeType:X.type,domain:X.domain,status:X.status,owner:X.owner,highlighted:B.has(X.id),dimmed:B.size>0&&!B.has(X.id)}})),Q=i.filter(X=>j.has(X.source)&&j.has(X.target)&&X.type!=="crosses_domain").map((X,$)=>({id:`e-${$}`,source:X.source,target:X.target,type:"default",animated:X.type==="feeds_into",style:{stroke:Xo[X.type]??"#30363d",strokeWidth:B.size>0?B.has(X.source)&&B.has(X.target)?2.5:.5:1.5,opacity:B.size>0?B.has(X.source)&&B.has(X.target)?1:.15:.7},markerEnd:{type:fn.ArrowClosed,width:12,height:12,color:Xo[X.type]??"#30363d"}}));if(K.length>0){const X=tx(K,Q,"LR");l(X.nodes),S(X.edges)}else l([]),S([])},[o,i,y,B,l,S]);const w=h.useCallback(async(k,j)=>{if(M===j.id){x(null),g(new Set),F(null),U([]),v([]);return}x(j.id);const K=o.find(q=>q.id===j.id);F(K??null);const Q=new Set,X=new Set;function $(q){for(const J of i)J.target===q&&J.type!=="crosses_domain"&&!Q.has(J.source)&&(Q.add(J.source),$(J.source))}function ee(q){for(const J of i)J.source===q&&J.type!=="crosses_domain"&&!X.has(J.target)&&(X.add(J.target),ee(J.target))}$(j.id),ee(j.id);const oe=new Set([j.id,...Q,...X]);if(g(oe),U(o.filter(q=>Q.has(q.id))),v(o.filter(q=>X.has(q.id))),(K==null?void 0:K.type)==="block"){const q=await le.fetchBlockLineage(K.name);q&&(U(q.ancestors??[]),v(q.descendants??[]))}},[M,o,i]),H=h.useCallback(()=>{x(null),g(new Set),F(null),U([]),v([])},[]),Y=h.useMemo(()=>{const k={};for(const j of o)k[j.type]=(k[j.type]??0)+1;return k},[o]);return n?E.jsx("div",{style:{padding:16,color:t.textMuted,fontSize:12,height:"100%"},children:"Loading lineage graph..."}):o.length===0?E.jsxs("div",{style:{padding:16,color:t.textMuted,fontSize:12,height:"100%"},children:["No lineage data. Add DQL blocks or run ",E.jsx("code",{children:"dql compile"})," to generate lineage."]}):E.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",background:"#0d1117"},children:[E.jsxs("div",{style:{display:"flex",gap:4,padding:"6px 8px",flexWrap:"wrap",borderBottom:`1px solid ${t.headerBorder}`,background:t.sidebarBg,flexShrink:0},children:[E.jsx(on,{label:"Tables",color:He.source_table,active:d,count:Y.source_table??0,onClick:()=>N(!d)}),E.jsx(on,{label:"Blocks",color:He.block,active:I,count:Y.block??0,onClick:()=>u(!I)}),E.jsx(on,{label:"Metrics",color:He.metric,active:f,count:Y.metric??0,onClick:()=>O(!f)}),E.jsx(on,{label:"Dims",color:He.dimension,active:C,count:Y.dimension??0,onClick:()=>m(!C)}),E.jsx(on,{label:"Charts",color:He.chart,active:L,count:Y.chart??0,onClick:()=>D(!L)})]}),E.jsx("div",{style:{flex:1,position:"relative"},children:E.jsxs(eg,{nodes:T,edges:c,onNodesChange:R,onEdgesChange:A,onNodeClick:w,onPaneClick:H,nodeTypes:rx,fitView:!0,fitViewOptions:{padding:.2},minZoom:.1,maxZoom:2,proOptions:{hideAttribution:!0},style:{background:"#0d1117"},children:[E.jsx(Eg,{color:"#21262d",gap:24,size:1}),E.jsx(Ag,{showInteractive:!1,style:{button:{background:"#161b22",color:"#e6edf3",border:"1px solid #30363d"}}}),E.jsx(Dg,{nodeColor:k=>{var K;const j=(K=k.data)==null?void 0:K.nodeType;return He[j]??"#8b949e"},maskColor:"rgba(0,0,0,0.6)",style:{background:"#0d1117",border:"1px solid #30363d"}}),E.jsx(yn,{position:"bottom-left",children:E.jsx("div",{style:{display:"flex",gap:10,background:"rgba(22,27,34,0.9)",padding:"4px 10px",borderRadius:6,border:"1px solid #30363d",fontSize:9,color:"#8b949e"},children:Object.entries(Xo).map(([k,j])=>E.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3},children:[E.jsx("span",{style:{width:12,height:2,background:j,borderRadius:1}}),k.replace(/_/g," ")]},k))})})]})}),p&&E.jsxs("div",{style:{flexShrink:0,maxHeight:180,overflow:"auto",borderTop:`1px solid ${t.headerBorder}`,background:t.sidebarBg,padding:8,fontSize:11},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginBottom:6},children:[E.jsx("span",{style:{fontSize:9,fontWeight:700,color:"#0d1117",background:He[p.type]??"#8b949e",borderRadius:3,padding:"1px 5px"},children:ar[p.type]??p.type}),E.jsx("span",{style:{fontWeight:600,color:t.textPrimary,flex:1},children:p.name}),E.jsx("button",{onClick:()=>{x(null),g(new Set),F(null)},style:{background:"transparent",border:"none",color:t.textMuted,cursor:"pointer",fontSize:14},children:"×"})]}),p.domain&&E.jsxs("div",{style:{color:t.textMuted,marginBottom:2},children:["Domain: ",E.jsx("span",{style:{color:"#d2a8ff"},children:p.domain})]}),p.owner&&E.jsxs("div",{style:{color:t.textMuted,marginBottom:2},children:["Owner: ",E.jsx("span",{style:{color:t.textSecondary},children:p.owner})]}),p.status&&E.jsxs("div",{style:{color:t.textMuted,marginBottom:4},children:["Status: ",E.jsx("span",{style:{color:Ic[p.status]??t.textSecondary},children:p.status})]}),_.length>0&&E.jsxs("div",{style:{marginTop:4},children:[E.jsxs("div",{style:{color:t.textMuted,fontSize:9,fontWeight:600,textTransform:"uppercase",marginBottom:2},children:["Upstream (",_.length,")"]}),_.slice(0,8).map(k=>{var j;return E.jsxs("div",{style:{padding:"1px 0",color:t.textSecondary,display:"flex",alignItems:"center",gap:3},children:[E.jsx("span",{style:{color:He[k.type],fontSize:8,fontWeight:700},children:((j=ar[k.type])==null?void 0:j.slice(0,3))??"???"}),k.name]},k.id)}),_.length>8&&E.jsxs("div",{style:{color:t.textMuted,fontSize:10},children:["+",_.length-8," more"]})]}),P.length>0&&E.jsxs("div",{style:{marginTop:4},children:[E.jsxs("div",{style:{color:t.textMuted,fontSize:9,fontWeight:600,textTransform:"uppercase",marginBottom:2},children:["Downstream (",P.length,")"]}),P.slice(0,8).map(k=>{var j;return E.jsxs("div",{style:{padding:"1px 0",color:t.textSecondary,display:"flex",alignItems:"center",gap:3},children:[E.jsx("span",{style:{color:He[k.type],fontSize:8,fontWeight:700},children:((j=ar[k.type])==null?void 0:j.slice(0,3))??"???"}),k.name]},k.id)}),P.length>8&&E.jsxs("div",{style:{color:t.textMuted,fontSize:10},children:["+",P.length-8," more"]})]})]})]})}function sx(){const{state:e,dispatch:t}=ae(),{executeAll:n}=xr();h.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 ix(){const{state:e,dispatch:t}=ae(),n=re[e.themeMode],r=h.useRef({});sx();const o=h.useCallback(async a=>{try{const{content:T}=await le.readNotebook(a.path),{title:l,cells:R}=OA(a.path,T);t({type:"OPEN_FILE",file:a,cells:R,title:l}),e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"})}catch(T){console.error("Failed to open file:",T),t({type:"OPEN_FILE",file:a,cells:[Le("sql")],title:a.name})}},[t,e.sidebarPanel]),s=h.useCallback(a=>{const T=r.current[a];T&&T.scrollIntoView({behavior:"smooth",block:"start"})},[]),i=h.useCallback((a,T)=>{T?r.current[a]=T:delete r.current[a]},[]);return E.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100vh",width:"100vw",background:n.appBg,fontFamily:n.font,color:n.textPrimary,overflow:"hidden"},children:[E.jsx(GA,{}),E.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[E.jsx(IS,{}),e.sidebarOpen&&E.jsx(dA,{onOpenFile:o,onNavigateToCell:s}),E.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:e.lineageFullscreen?E.jsx(ox,{}):E.jsxs(E.Fragment,{children:[E.jsx(Ah,{onOpenFile:o,registerCellRef:i}),E.jsx(YA,{})]})})]}),e.newNotebookModalOpen&&E.jsx(fh,{onFileOpened:o}),e.newBlockModalOpen&&E.jsx(Lh,{onFileOpened:o})]})}function Ex(){const{state:e,dispatch:t}=ae(),n=h.useRef(null),r=h.useRef(null);h.useEffect(()=>{var o;n.current=((o=e.activeFile)==null?void 0:o.path)??null},[e.activeFile]),h.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 a=JSON.parse(i.data);(a.type==="file-added"||a.type==="file-deleted")&&le.listNotebooks().then(T=>{t({type:"SET_FILES",files:T})}),a.type==="file-changed"&&le.listNotebooks().then(T=>{t({type:"SET_FILES",files:T})}),a.type==="semantic-reload"&&(t({type:"SET_SEMANTIC_LOADING",loading:!0}),le.getSemanticLayer().then(T=>{t({type:"SET_SEMANTIC_LAYER",layer:T})}))}catch{}}),s.addEventListener("error",()=>{s.close(),setTimeout(o,5e3)})};return o(),()=>{var s;(s=r.current)==null||s.close(),r.current=null}},[t])}function ax(){const{state:e,dispatch:t}=ae(),n=re[e.themeMode];return h.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=`
|
|
504
|
-
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
505
|
-
body {
|
|
506
|
-
font-family: ${n.font};
|
|
507
|
-
overflow: hidden;
|
|
508
|
-
background: ${n.appBg};
|
|
509
|
-
color: ${n.textPrimary};
|
|
510
|
-
}
|
|
511
|
-
::-webkit-scrollbar { width: 6px; height: 6px; }
|
|
512
|
-
::-webkit-scrollbar-track { background: transparent; }
|
|
513
|
-
::-webkit-scrollbar-thumb {
|
|
514
|
-
background: ${n.scrollbarThumb};
|
|
515
|
-
border-radius: 3px;
|
|
516
|
-
}
|
|
517
|
-
::-webkit-scrollbar-thumb:hover {
|
|
518
|
-
background: ${n.textMuted};
|
|
519
|
-
}
|
|
520
|
-
::selection {
|
|
521
|
-
background: ${n.accent}40;
|
|
522
|
-
color: ${n.textPrimary};
|
|
523
|
-
}
|
|
524
|
-
`},[n]),h.useEffect(()=>{t({type:"SET_FILES_LOADING",loading:!0}),le.listNotebooks().then(r=>{t({type:"SET_FILES",files:r}),t({type:"SET_FILES_LOADING",loading:!1})})},[t]),h.useEffect(()=>{t({type:"SET_SCHEMA_LOADING",loading:!0}),le.getSchema().then(r=>{t({type:"SET_SCHEMA",tables:r}),t({type:"SET_SCHEMA_LOADING",loading:!1})})},[t]),Ex(),E.jsx(ix,{})}function lx(){return E.jsx(sS,{children:E.jsx(ax,{})})}nS.createRoot(document.getElementById("root")).render(E.jsx(lx,{}));
|