diff --git a/plugins/sidemantic/skills/webapp-builder/assets/ui-dist/sidemantic-ui.js b/plugins/sidemantic/skills/webapp-builder/assets/ui-dist/sidemantic-ui.js index 4c5455d8..b1c5bb6e 100644 --- a/plugins/sidemantic/skills/webapp-builder/assets/ui-dist/sidemantic-ui.js +++ b/plugins/sidemantic/skills/webapp-builder/assets/ui-dist/sidemantic-ui.js @@ -1265,7 +1265,7 @@ class ErrorBoundary extends Component { import { useState as useState9 } from "react"; // webapp/src/components/FilterEditor.tsx -import { useEffect as useEffect8, useId, useMemo as useMemo3, useRef as useRef6, useState as useState8 } from "react"; +import { useEffect as useEffect8, useId, useMemo as useMemo3, useRef as useRef7, useState as useState8 } from "react"; // webapp/src/lib/catalog.ts function graphMetricsForModel(catalog, modelName) { @@ -1479,7 +1479,7 @@ function distinctValues(dimRef, filters, limit = 50, segments, usePreaggregation } // webapp/src/state/ExplorerContext.tsx -import { createContext, useContext, useEffect as useEffect6, useMemo as useMemo2, useReducer } from "react"; +import { createContext, useContext, useEffect as useEffect6, useMemo as useMemo2, useReducer, useRef as useRef5 } from "react"; // webapp/src/state/url.ts var GRAINS2 = new Set(ALL_GRAINS); @@ -1498,7 +1498,7 @@ function useExplorer() { } // webapp/src/state/useQueryResult.ts -import { useEffect as useEffect7, useRef as useRef5, useState as useState7 } from "react"; +import { useEffect as useEffect7, useRef as useRef6, useState as useState7 } from "react"; // webapp/src/state/queryActivity.ts import { useSyncExternalStore } from "react"; @@ -1520,7 +1520,7 @@ function endQuery() { var DEBOUNCE_MS = 80; function useQueryResult(backend, query) { const [state, setState] = useState7({ loading: false }); - const token = useRef5(0); + const token = useRef6(0); const key = query ? JSON.stringify(query) : null; useEffect7(() => { if (!query) { @@ -1572,8 +1572,8 @@ function FilterEditor({ const filter = state.filters[dim.ref]; const [mode, setModeState] = useState8(filter?.mode ?? "include"); const selected = useMemo3(() => new Set(filter?.mode !== "contains" ? filter?.values ?? [] : []), [filter]); - const panelRef = useRef6(null); - const searchRef = useRef6(null); + const panelRef = useRef7(null); + const searchRef = useRef7(null); const labelId = useId(); const [search, setSearch] = useState8(""); const debouncedSearch = useDebounced(search, SEARCH_DEBOUNCE_MS); @@ -1849,7 +1849,7 @@ function FilterPill(props) { }); } // webapp/src/components/HeatmapChart.tsx -import { useEffect as useEffect9, useRef as useRef7, useState as useState10 } from "react"; +import { useEffect as useEffect9, useRef as useRef8, useState as useState10 } from "react"; import { jsx as jsx13, jsxs as jsxs11, Fragment as Fragment4 } from "react/jsx-runtime"; var MARGIN3 = { top: 8, right: 8, bottom: 26, left: 76 }; function orderedLabels(cells, key, explicit) { @@ -1862,7 +1862,7 @@ function orderedLabels(cells, key, explicit) { return seen; } function HeatmapChart({ cells, xLabels, yLabels, height = 240, format = formatValue, ariaLabel }) { - const ref = useRef7(null); + const ref = useRef8(null); const [width, setWidth] = useState10(640); const { tip, handlers } = useChartTooltip(); useEffect9(() => observeWidth(ref.current, 240, setWidth), []); @@ -1936,7 +1936,7 @@ function HeatmapChart({ cells, xLabels, yLabels, height = 240, format = formatVa }); } // webapp/src/components/HistogramChart.tsx -import { useEffect as useEffect10, useRef as useRef8, useState as useState11 } from "react"; +import { useEffect as useEffect10, useRef as useRef9, useState as useState11 } from "react"; import { jsx as jsx14, jsxs as jsxs12, Fragment as Fragment5 } from "react/jsx-runtime"; function binValues(values, bins) { const finite = values.filter(Number.isFinite); @@ -1961,7 +1961,7 @@ function binValues(values, bins) { } var MARGIN4 = { top: 12, right: 14, bottom: 26, left: 44 }; function HistogramChart({ values, bins, height = 200, format = formatCompact, ariaLabel }) { - const ref = useRef8(null); + const ref = useRef9(null); const [width, setWidth] = useState11(640); const { tip, handlers } = useChartTooltip(); useEffect10(() => observeWidth(ref.current, 160, setWidth), []); @@ -2181,7 +2181,7 @@ function Leaderboard({ import { useState as useState13 } from "react"; // webapp/src/components/Sparkline.tsx -import { useEffect as useEffect11, useId as useId2, useRef as useRef9, useState as useState12 } from "react"; +import { useEffect as useEffect11, useId as useId2, useRef as useRef10, useState as useState12 } from "react"; import { jsx as jsx16, jsxs as jsxs14, Fragment as Fragment6 } from "react/jsx-runtime"; function Sparkline({ values, @@ -2192,10 +2192,10 @@ function Sparkline({ onHover, onBrush }) { - const containerRef = useRef9(null); + const containerRef = useRef10(null); const gradientId = useId2(); - const svgRef = useRef9(null); - const dragStart = useRef9(null); + const svgRef = useRef10(null); + const dragStart = useRef10(null); const [width, setWidth] = useState12(200); const [hover, setHover] = useState12(null); const [brush, setBrush] = useState12(null); @@ -2488,7 +2488,7 @@ function MetricCard({ }); } // webapp/src/components/NetworkChart.tsx -import { useEffect as useEffect12, useMemo as useMemo4, useRef as useRef10, useState as useState14 } from "react"; +import { useEffect as useEffect12, useMemo as useMemo4, useRef as useRef11, useState as useState14 } from "react"; import { jsx as jsx18, jsxs as jsxs16, Fragment as Fragment8 } from "react/jsx-runtime"; function hashSeed(text) { let hash = 2166136261; @@ -2585,7 +2585,7 @@ function layoutNetwork(nodes, links, { width = 640, height = 320, iterations = 1 })); } function NetworkChart({ nodes, links, height = 320, ariaLabel }) { - const ref = useRef10(null); + const ref = useRef11(null); const [width, setWidth] = useState14(640); const { tip, handlers } = useChartTooltip(); useEffect12(() => observeWidth(ref.current, 240, setWidth), []); @@ -2801,7 +2801,7 @@ ${sql}`).join(` }); } // webapp/src/components/ScatterChart.tsx -import { useEffect as useEffect13, useRef as useRef11, useState as useState15 } from "react"; +import { useEffect as useEffect13, useRef as useRef12, useState as useState15 } from "react"; import { jsx as jsx20, jsxs as jsxs18, Fragment as Fragment9 } from "react/jsx-runtime"; var MARGIN5 = { top: 12, right: 14, bottom: 30, left: 48 }; function ScatterChart({ @@ -2813,7 +2813,7 @@ function ScatterChart({ formatY = formatCompact, ariaLabel }) { - const ref = useRef11(null); + const ref = useRef12(null); const [width, setWidth] = useState15(640); const { tip, handlers } = useChartTooltip(); useEffect13(() => observeWidth(ref.current, 200, setWidth), []); @@ -2945,7 +2945,7 @@ function ScatterChart({ }); } // webapp/src/components/StackedAreaChart.tsx -import { useEffect as useEffect14, useRef as useRef12, useState as useState16 } from "react"; +import { useEffect as useEffect14, useRef as useRef13, useState as useState16 } from "react"; import { jsx as jsx21, jsxs as jsxs19 } from "react/jsx-runtime"; var MARGIN6 = { top: 12, right: 14, bottom: 26, left: 48 }; function clamp2(value, min, max) { @@ -2959,7 +2959,7 @@ function StackedAreaChart({ formatLabel = (label) => label, ariaLabel }) { - const container = useRef12(null); + const container = useRef13(null); const [width, setWidth] = useState16(640); const [hover, setHover] = useState16(null); useEffect14(() => observeWidth(container.current, 240, setWidth), []); @@ -3166,7 +3166,7 @@ function StatusDot({ status }) { }); } // webapp/src/components/WaterfallChart.tsx -import { useEffect as useEffect15, useRef as useRef13, useState as useState17 } from "react"; +import { useEffect as useEffect15, useRef as useRef14, useState as useState17 } from "react"; import { jsx as jsx23, jsxs as jsxs21, Fragment as Fragment10 } from "react/jsx-runtime"; function waterfallSteps(data) { let running = 0; @@ -3183,7 +3183,7 @@ function waterfallSteps(data) { } var MARGIN7 = { top: 12, right: 14, bottom: 26, left: 48 }; function WaterfallChart({ data, height = 220, format = formatValue, ariaLabel }) { - const ref = useRef13(null); + const ref = useRef14(null); const [width, setWidth] = useState17(640); const { tip, handlers } = useChartTooltip(); useEffect15(() => observeWidth(ref.current, 200, setWidth), []); @@ -3313,7 +3313,7 @@ function Button({ variant = "secondary", size = "md", type = "button", className }); } // webapp/src/components/Combobox.tsx -import { useEffect as useEffect16, useId as useId3, useMemo as useMemo5, useRef as useRef14, useState as useState18 } from "react"; +import { useEffect as useEffect16, useId as useId3, useMemo as useMemo5, useRef as useRef15, useState as useState18 } from "react"; import { jsx as jsx25, jsxs as jsxs22 } from "react/jsx-runtime"; function filterOptions(options, query) { const needle = query.trim().toLowerCase(); @@ -3324,7 +3324,7 @@ function filterOptions(options, query) { function Combobox(props) { const { options, placeholder = "Search…", ariaLabel, disabled, maxVisible = 50 } = props; const listId = useId3(); - const rootRef = useRef14(null); + const rootRef = useRef15(null); const [open, setOpen] = useState18(false); const [query, setQuery] = useState18(""); const [activeIndex, setActiveIndex] = useState18(0); @@ -3470,7 +3470,7 @@ function Combobox(props) { }); } // webapp/src/components/DatePicker.tsx -import { useRef as useRef15, useState as useState19 } from "react"; +import { useRef as useRef16, useState as useState19 } from "react"; import { jsx as jsx26, jsxs as jsxs23 } from "react/jsx-runtime"; var WEEKDAYS = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]; var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; @@ -3508,7 +3508,7 @@ function DatePicker(props) { const [year, setYear] = useState19(() => Number((anchor ?? todayIso()).slice(0, 4))); const [monthIndex, setMonthIndex] = useState19(() => Number((anchor ?? todayIso()).slice(5, 7)) - 1); const [pending, setPending] = useState19(null); - const details = useRef15(null); + const details = useRef16(null); function shiftMonth(delta) { const next = new Date(Date.UTC(year, monthIndex + delta, 1)); setYear(next.getUTCFullYear()); @@ -3649,7 +3649,7 @@ function DatePicker(props) { }); } // webapp/src/components/DateRangeControl.tsx -import { useRef as useRef16, useState as useState20 } from "react"; +import { useRef as useRef17, useState as useState20 } from "react"; import { jsx as jsx27, jsxs as jsxs24 } from "react/jsx-runtime"; var COMPARISON_OPTIONS = [ { key: "off", label: "Off" }, @@ -3665,7 +3665,7 @@ function DateRangeControl({ comparisonRange, onComparisonChange }) { - const details = useRef16(null); + const details = useRef17(null); const [from, setFrom] = useState20(range?.from ?? ""); const [to, setTo] = useState20(range?.to ?? ""); const [cmpFrom, setCmpFrom] = useState20(comparisonRange?.from ?? ""); @@ -4112,14 +4112,14 @@ function Tooltip({ content, children, className }) { }); } // webapp/src/components/ViewSwitcher.tsx -import { useRef as useRef17 } from "react"; +import { useRef as useRef18 } from "react"; import { jsx as jsx34 } from "react/jsx-runtime"; var SEGMENTS = [ { key: "explore", label: "Explore" }, { key: "pivot", label: "Pivot" } ]; function ViewSwitcher({ view, onChange }) { - const list = useRef17(null); + const list = useRef18(null); function move(direction) { const current = Math.max(0, SEGMENTS.findIndex((segment) => segment.key === view)); const next = SEGMENTS[(current + direction + SEGMENTS.length) % SEGMENTS.length]; diff --git a/sidemantic-rs/ui/assets/index-iemRTgYP.js b/sidemantic-rs/ui/assets/index-D-e4ps_P.js similarity index 77% rename from sidemantic-rs/ui/assets/index-iemRTgYP.js rename to sidemantic-rs/ui/assets/index-D-e4ps_P.js index 873cbd34..212baf71 100644 --- a/sidemantic-rs/ui/assets/index-iemRTgYP.js +++ b/sidemantic-rs/ui/assets/index-D-e4ps_P.js @@ -1,4 +1,4 @@ -var Xx=Object.defineProperty;var eb=(n,e,t)=>e in n?Xx(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Mn=(n,e,t)=>eb(n,typeof e!="symbol"?e+"":e,t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))i(a);new MutationObserver(a=>{for(const u of a)if(u.type==="childList")for(const f of u.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&i(f)}).observe(document,{childList:!0,subtree:!0});function t(a){const u={};return a.integrity&&(u.integrity=a.integrity),a.referrerPolicy&&(u.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?u.credentials="include":a.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function i(a){if(a.ep)return;a.ep=!0;const u=t(a);fetch(a.href,u)}})();var Jc={exports:{}},wo={},qc={exports:{}},Be={};/** +var nb=Object.defineProperty;var rb=(n,e,t)=>e in n?nb(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Mn=(n,e,t)=>rb(n,typeof e!="symbol"?e+"":e,t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))i(a);new MutationObserver(a=>{for(const u of a)if(u.type==="childList")for(const f of u.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&i(f)}).observe(document,{childList:!0,subtree:!0});function t(a){const u={};return a.integrity&&(u.integrity=a.integrity),a.referrerPolicy&&(u.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?u.credentials="include":a.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function i(a){if(a.ep)return;a.ep=!0;const u=t(a);fetch(a.href,u)}})();var Jc={exports:{}},wo={},qc={exports:{}},Be={};/** * @license React * react.production.min.js * @@ -6,7 +6,7 @@ var Xx=Object.defineProperty;var eb=(n,e,t)=>e in n?Xx(n,e,{enumerable:!0,config * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var Xp;function tb(){if(Xp)return Be;Xp=1;var n=Symbol.for("react.element"),e=Symbol.for("react.portal"),t=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),u=Symbol.for("react.provider"),f=Symbol.for("react.context"),h=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),g=Symbol.for("react.memo"),v=Symbol.for("react.lazy"),x=Symbol.iterator;function b(_){return _===null||typeof _!="object"?null:(_=x&&_[x]||_["@@iterator"],typeof _=="function"?_:null)}var w={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},j=Object.assign,C={};function O(_,F,te){this.props=_,this.context=F,this.refs=C,this.updater=te||w}O.prototype.isReactComponent={},O.prototype.setState=function(_,F){if(typeof _!="object"&&typeof _!="function"&&_!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,_,F,"setState")},O.prototype.forceUpdate=function(_){this.updater.enqueueForceUpdate(this,_,"forceUpdate")};function H(){}H.prototype=O.prototype;function L(_,F,te){this.props=_,this.context=F,this.refs=C,this.updater=te||w}var R=L.prototype=new H;R.constructor=L,j(R,O.prototype),R.isPureReactComponent=!0;var T=Array.isArray,E=Object.prototype.hasOwnProperty,I={current:null},U={key:!0,ref:!0,__self:!0,__source:!0};function G(_,F,te){var pe,ne={},fe=null,Ce=null;if(F!=null)for(pe in F.ref!==void 0&&(Ce=F.ref),F.key!==void 0&&(fe=""+F.key),F)E.call(F,pe)&&!U.hasOwnProperty(pe)&&(ne[pe]=F[pe]);var Te=arguments.length-2;if(Te===1)ne.children=te;else if(1e in n?Xx(n,e,{enumerable:!0,config * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var tm;function nb(){if(tm)return wo;tm=1;var n=Ad(),e=Symbol.for("react.element"),t=Symbol.for("react.fragment"),i=Object.prototype.hasOwnProperty,a=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,u={key:!0,ref:!0,__self:!0,__source:!0};function f(h,m,g){var v,x={},b=null,w=null;g!==void 0&&(b=""+g),m.key!==void 0&&(b=""+m.key),m.ref!==void 0&&(w=m.ref);for(v in m)i.call(m,v)&&!u.hasOwnProperty(v)&&(x[v]=m[v]);if(h&&h.defaultProps)for(v in m=h.defaultProps,m)x[v]===void 0&&(x[v]=m[v]);return{$$typeof:e,type:h,key:b,ref:w,props:x,_owner:a.current}}return wo.Fragment=t,wo.jsx=f,wo.jsxs=f,wo}var nm;function rb(){return nm||(nm=1,Jc.exports=nb()),Jc.exports}var c=rb(),D=Ad(),tl={},Zc={exports:{}},$t={},Xc={exports:{}},ed={};/** + */var tm;function ib(){if(tm)return wo;tm=1;var n=Ad(),e=Symbol.for("react.element"),t=Symbol.for("react.fragment"),i=Object.prototype.hasOwnProperty,a=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,u={key:!0,ref:!0,__self:!0,__source:!0};function f(h,m,g){var v,x={},b=null,w=null;g!==void 0&&(b=""+g),m.key!==void 0&&(b=""+m.key),m.ref!==void 0&&(w=m.ref);for(v in m)i.call(m,v)&&!u.hasOwnProperty(v)&&(x[v]=m[v]);if(h&&h.defaultProps)for(v in m=h.defaultProps,m)x[v]===void 0&&(x[v]=m[v]);return{$$typeof:e,type:h,key:b,ref:w,props:x,_owner:a.current}}return wo.Fragment=t,wo.jsx=f,wo.jsxs=f,wo}var nm;function ob(){return nm||(nm=1,Jc.exports=ib()),Jc.exports}var c=ob(),M=Ad(),tl={},Zc={exports:{}},$t={},Xc={exports:{}},ed={};/** * @license React * scheduler.production.min.js * @@ -22,7 +22,7 @@ var Xx=Object.defineProperty;var eb=(n,e,t)=>e in n?Xx(n,e,{enumerable:!0,config * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var rm;function sb(){return rm||(rm=1,(function(n){function e(A,Y){var W=A.length;A.push(Y);e:for(;0>>1,F=A[_];if(0>>1;_a(ne,W))fea(Ce,ne)?(A[_]=Ce,A[fe]=W,_=fe):(A[_]=ne,A[pe]=W,_=pe);else if(fea(Ce,W))A[_]=Ce,A[fe]=W,_=fe;else break e}}return Y}function a(A,Y){var W=A.sortIndex-Y.sortIndex;return W!==0?W:A.id-Y.id}if(typeof performance=="object"&&typeof performance.now=="function"){var u=performance;n.unstable_now=function(){return u.now()}}else{var f=Date,h=f.now();n.unstable_now=function(){return f.now()-h}}var m=[],g=[],v=1,x=null,b=3,w=!1,j=!1,C=!1,O=typeof setTimeout=="function"?setTimeout:null,H=typeof clearTimeout=="function"?clearTimeout:null,L=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function R(A){for(var Y=t(g);Y!==null;){if(Y.callback===null)i(g);else if(Y.startTime<=A)i(g),Y.sortIndex=Y.expirationTime,e(m,Y);else break;Y=t(g)}}function T(A){if(C=!1,R(A),!j)if(t(m)!==null)j=!0,re(E);else{var Y=t(g);Y!==null&&se(T,Y.startTime-A)}}function E(A,Y){j=!1,C&&(C=!1,H(G),G=-1),w=!0;var W=b;try{for(R(Y),x=t(m);x!==null&&(!(x.expirationTime>Y)||A&&!z());){var _=x.callback;if(typeof _=="function"){x.callback=null,b=x.priorityLevel;var F=_(x.expirationTime<=Y);Y=n.unstable_now(),typeof F=="function"?x.callback=F:x===t(m)&&i(m),R(Y)}else i(m);x=t(m)}if(x!==null)var te=!0;else{var pe=t(g);pe!==null&&se(T,pe.startTime-Y),te=!1}return te}finally{x=null,b=W,w=!1}}var I=!1,U=null,G=-1,V=5,Q=-1;function z(){return!(n.unstable_now()-QA||125_?(A.sortIndex=W,e(g,A),t(m)===null&&A===t(g)&&(C?(H(G),G=-1):C=!0,se(T,W-_))):(A.sortIndex=F,e(m,A),j||w||(j=!0,re(E))),A},n.unstable_shouldYield=z,n.unstable_wrapCallback=function(A){var Y=b;return function(){var W=b;b=Y;try{return A.apply(this,arguments)}finally{b=W}}}})(ed)),ed}var sm;function ib(){return sm||(sm=1,Xc.exports=sb()),Xc.exports}/** + */var rm;function ab(){return rm||(rm=1,(function(n){function e(A,Y){var W=A.length;A.push(Y);e:for(;0>>1,F=A[_];if(0>>1;_a(ne,W))fea(Ce,ne)?(A[_]=Ce,A[fe]=W,_=fe):(A[_]=ne,A[pe]=W,_=pe);else if(fea(Ce,W))A[_]=Ce,A[fe]=W,_=fe;else break e}}return Y}function a(A,Y){var W=A.sortIndex-Y.sortIndex;return W!==0?W:A.id-Y.id}if(typeof performance=="object"&&typeof performance.now=="function"){var u=performance;n.unstable_now=function(){return u.now()}}else{var f=Date,h=f.now();n.unstable_now=function(){return f.now()-h}}var m=[],g=[],v=1,x=null,b=3,w=!1,j=!1,C=!1,O=typeof setTimeout=="function"?setTimeout:null,H=typeof clearTimeout=="function"?clearTimeout:null,L=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function R(A){for(var Y=t(g);Y!==null;){if(Y.callback===null)i(g);else if(Y.startTime<=A)i(g),Y.sortIndex=Y.expirationTime,e(m,Y);else break;Y=t(g)}}function T(A){if(C=!1,R(A),!j)if(t(m)!==null)j=!0,re(E);else{var Y=t(g);Y!==null&&se(T,Y.startTime-A)}}function E(A,Y){j=!1,C&&(C=!1,H(G),G=-1),w=!0;var W=b;try{for(R(Y),x=t(m);x!==null&&(!(x.expirationTime>Y)||A&&!z());){var _=x.callback;if(typeof _=="function"){x.callback=null,b=x.priorityLevel;var F=_(x.expirationTime<=Y);Y=n.unstable_now(),typeof F=="function"?x.callback=F:x===t(m)&&i(m),R(Y)}else i(m);x=t(m)}if(x!==null)var te=!0;else{var pe=t(g);pe!==null&&se(T,pe.startTime-Y),te=!1}return te}finally{x=null,b=W,w=!1}}var I=!1,U=null,G=-1,V=5,Q=-1;function z(){return!(n.unstable_now()-QA||125_?(A.sortIndex=W,e(g,A),t(m)===null&&A===t(g)&&(C?(H(G),G=-1):C=!0,se(T,W-_))):(A.sortIndex=F,e(m,A),j||w||(j=!0,re(E))),A},n.unstable_shouldYield=z,n.unstable_wrapCallback=function(A){var Y=b;return function(){var W=b;b=Y;try{return A.apply(this,arguments)}finally{b=W}}}})(ed)),ed}var sm;function lb(){return sm||(sm=1,Xc.exports=ab()),Xc.exports}/** * @license React * react-dom.production.min.js * @@ -30,26 +30,26 @@ var Xx=Object.defineProperty;var eb=(n,e,t)=>e in n?Xx(n,e,{enumerable:!0,config * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var im;function ob(){if(im)return $t;im=1;var n=Ad(),e=ib();function t(r){for(var s="https://reactjs.org/docs/error-decoder.html?invariant="+r,o=1;o"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),m=Object.prototype.hasOwnProperty,g=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,v={},x={};function b(r){return m.call(x,r)?!0:m.call(v,r)?!1:g.test(r)?x[r]=!0:(v[r]=!0,!1)}function w(r,s,o,l){if(o!==null&&o.type===0)return!1;switch(typeof s){case"function":case"symbol":return!0;case"boolean":return l?!1:o!==null?!o.acceptsBooleans:(r=r.toLowerCase().slice(0,5),r!=="data-"&&r!=="aria-");default:return!1}}function j(r,s,o,l){if(s===null||typeof s>"u"||w(r,s,o,l))return!0;if(l)return!1;if(o!==null)switch(o.type){case 3:return!s;case 4:return s===!1;case 5:return isNaN(s);case 6:return isNaN(s)||1>s}return!1}function C(r,s,o,l,d,p,y){this.acceptsBooleans=s===2||s===3||s===4,this.attributeName=l,this.attributeNamespace=d,this.mustUseProperty=o,this.propertyName=r,this.type=s,this.sanitizeURL=p,this.removeEmptyString=y}var O={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(r){O[r]=new C(r,0,!1,r,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(r){var s=r[0];O[s]=new C(s,1,!1,r[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(r){O[r]=new C(r,2,!1,r.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(r){O[r]=new C(r,2,!1,r,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(r){O[r]=new C(r,3,!1,r.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(r){O[r]=new C(r,3,!0,r,null,!1,!1)}),["capture","download"].forEach(function(r){O[r]=new C(r,4,!1,r,null,!1,!1)}),["cols","rows","size","span"].forEach(function(r){O[r]=new C(r,6,!1,r,null,!1,!1)}),["rowSpan","start"].forEach(function(r){O[r]=new C(r,5,!1,r.toLowerCase(),null,!1,!1)});var H=/[\-:]([a-z])/g;function L(r){return r[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(r){var s=r.replace(H,L);O[s]=new C(s,1,!1,r,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(r){var s=r.replace(H,L);O[s]=new C(s,1,!1,r,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(r){var s=r.replace(H,L);O[s]=new C(s,1,!1,r,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(r){O[r]=new C(r,1,!1,r.toLowerCase(),null,!1,!1)}),O.xlinkHref=new C("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(r){O[r]=new C(r,1,!1,r.toLowerCase(),null,!0,!0)});function R(r,s,o,l){var d=O.hasOwnProperty(s)?O[s]:null;(d!==null?d.type!==0:l||!(2"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),m=Object.prototype.hasOwnProperty,g=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,v={},x={};function b(r){return m.call(x,r)?!0:m.call(v,r)?!1:g.test(r)?x[r]=!0:(v[r]=!0,!1)}function w(r,s,o,l){if(o!==null&&o.type===0)return!1;switch(typeof s){case"function":case"symbol":return!0;case"boolean":return l?!1:o!==null?!o.acceptsBooleans:(r=r.toLowerCase().slice(0,5),r!=="data-"&&r!=="aria-");default:return!1}}function j(r,s,o,l){if(s===null||typeof s>"u"||w(r,s,o,l))return!0;if(l)return!1;if(o!==null)switch(o.type){case 3:return!s;case 4:return s===!1;case 5:return isNaN(s);case 6:return isNaN(s)||1>s}return!1}function C(r,s,o,l,d,p,y){this.acceptsBooleans=s===2||s===3||s===4,this.attributeName=l,this.attributeNamespace=d,this.mustUseProperty=o,this.propertyName=r,this.type=s,this.sanitizeURL=p,this.removeEmptyString=y}var O={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(r){O[r]=new C(r,0,!1,r,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(r){var s=r[0];O[s]=new C(s,1,!1,r[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(r){O[r]=new C(r,2,!1,r.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(r){O[r]=new C(r,2,!1,r,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(r){O[r]=new C(r,3,!1,r.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(r){O[r]=new C(r,3,!0,r,null,!1,!1)}),["capture","download"].forEach(function(r){O[r]=new C(r,4,!1,r,null,!1,!1)}),["cols","rows","size","span"].forEach(function(r){O[r]=new C(r,6,!1,r,null,!1,!1)}),["rowSpan","start"].forEach(function(r){O[r]=new C(r,5,!1,r.toLowerCase(),null,!1,!1)});var H=/[\-:]([a-z])/g;function L(r){return r[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(r){var s=r.replace(H,L);O[s]=new C(s,1,!1,r,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(r){var s=r.replace(H,L);O[s]=new C(s,1,!1,r,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(r){var s=r.replace(H,L);O[s]=new C(s,1,!1,r,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(r){O[r]=new C(r,1,!1,r.toLowerCase(),null,!1,!1)}),O.xlinkHref=new C("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(r){O[r]=new C(r,1,!1,r.toLowerCase(),null,!0,!0)});function R(r,s,o,l){var d=O.hasOwnProperty(s)?O[s]:null;(d!==null?d.type!==0:l||!(2S||d[y]!==p[S]){var N=` -`+d[y].replace(" at new "," at ");return r.displayName&&N.includes("")&&(N=N.replace("",r.displayName)),N}while(1<=y&&0<=S);break}}}finally{te=!1,Error.prepareStackTrace=o}return(r=r?r.displayName||r.name:"")?F(r):""}function ne(r){switch(r.tag){case 5:return F(r.type);case 16:return F("Lazy");case 13:return F("Suspense");case 19:return F("SuspenseList");case 0:case 2:case 15:return r=pe(r.type,!1),r;case 11:return r=pe(r.type.render,!1),r;case 1:return r=pe(r.type,!0),r;default:return""}}function fe(r){if(r==null)return null;if(typeof r=="function")return r.displayName||r.name||null;if(typeof r=="string")return r;switch(r){case U:return"Fragment";case I:return"Portal";case V:return"Profiler";case G:return"StrictMode";case X:return"Suspense";case ie:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case z:return(r.displayName||"Context")+".Consumer";case Q:return(r._context.displayName||"Context")+".Provider";case ee:var s=r.render;return r=r.displayName,r||(r=s.displayName||s.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case ae:return s=r.displayName||null,s!==null?s:fe(r.type)||"Memo";case re:s=r._payload,r=r._init;try{return fe(r(s))}catch{}}return null}function Ce(r){var s=r.type;switch(r.tag){case 24:return"Cache";case 9:return(s.displayName||"Context")+".Consumer";case 10:return(s._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return r=s.render,r=r.displayName||r.name||"",s.displayName||(r!==""?"ForwardRef("+r+")":"ForwardRef");case 7:return"Fragment";case 5:return s;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return fe(s);case 8:return s===G?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof s=="function")return s.displayName||s.name||null;if(typeof s=="string")return s}return null}function Te(r){switch(typeof r){case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function Ue(r){var s=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(s==="checkbox"||s==="radio")}function lt(r){var s=Ue(r)?"checked":"value",o=Object.getOwnPropertyDescriptor(r.constructor.prototype,s),l=""+r[s];if(!r.hasOwnProperty(s)&&typeof o<"u"&&typeof o.get=="function"&&typeof o.set=="function"){var d=o.get,p=o.set;return Object.defineProperty(r,s,{configurable:!0,get:function(){return d.call(this)},set:function(y){l=""+y,p.call(this,y)}}),Object.defineProperty(r,s,{enumerable:o.enumerable}),{getValue:function(){return l},setValue:function(y){l=""+y},stopTracking:function(){r._valueTracker=null,delete r[s]}}}}function wt(r){r._valueTracker||(r._valueTracker=lt(r))}function Bs(r){if(!r)return!1;var s=r._valueTracker;if(!s)return!0;var o=s.getValue(),l="";return r&&(l=Ue(r)?r.checked?"true":"false":r.value),r=l,r!==o?(s.setValue(r),!0):!1}function xn(r){if(r=r||(typeof document<"u"?document:void 0),typeof r>"u")return null;try{return r.activeElement||r.body}catch{return r.body}}function Cr(r,s){var o=s.checked;return W({},s,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:o??r._wrapperState.initialChecked})}function Fr(r,s){var o=s.defaultValue==null?"":s.defaultValue,l=s.checked!=null?s.checked:s.defaultChecked;o=Te(s.value!=null?s.value:o),r._wrapperState={initialChecked:l,initialValue:o,controlled:s.type==="checkbox"||s.type==="radio"?s.checked!=null:s.value!=null}}function ue(r,s){s=s.checked,s!=null&&R(r,"checked",s,!1)}function Oe(r,s){ue(r,s);var o=Te(s.value),l=s.type;if(o!=null)l==="number"?(o===0&&r.value===""||r.value!=o)&&(r.value=""+o):r.value!==""+o&&(r.value=""+o);else if(l==="submit"||l==="reset"){r.removeAttribute("value");return}s.hasOwnProperty("value")?Nt(r,s.type,o):s.hasOwnProperty("defaultValue")&&Nt(r,s.type,Te(s.defaultValue)),s.checked==null&&s.defaultChecked!=null&&(r.defaultChecked=!!s.defaultChecked)}function rt(r,s,o){if(s.hasOwnProperty("value")||s.hasOwnProperty("defaultValue")){var l=s.type;if(!(l!=="submit"&&l!=="reset"||s.value!==void 0&&s.value!==null))return;s=""+r._wrapperState.initialValue,o||s===r.value||(r.value=s),r.defaultValue=s}o=r.name,o!==""&&(r.name=""),r.defaultChecked=!!r._wrapperState.initialChecked,o!==""&&(r.name=o)}function Nt(r,s,o){(s!=="number"||xn(r.ownerDocument)!==r)&&(o==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+o&&(r.defaultValue=""+o))}var Un=Array.isArray;function sr(r,s,o,l){if(r=r.options,s){s={};for(var d=0;d"+s.valueOf().toString()+"",s=ds.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;s.firstChild;)r.appendChild(s.firstChild)}});function ir(r,s){if(s){var o=r.firstChild;if(o&&o===r.lastChild&&o.nodeType===3){o.nodeValue=s;return}}r.textContent=s}var Ri={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},r0=["Webkit","ms","Moz","O"];Object.keys(Ri).forEach(function(r){r0.forEach(function(s){s=s+r.charAt(0).toUpperCase()+r.substring(1),Ri[s]=Ri[r]})});function pf(r,s,o){return s==null||typeof s=="boolean"||s===""?"":o||typeof s!="number"||s===0||Ri.hasOwnProperty(r)&&Ri[r]?(""+s).trim():s+"px"}function mf(r,s){r=r.style;for(var o in s)if(s.hasOwnProperty(o)){var l=o.indexOf("--")===0,d=pf(o,s[o],l);o==="float"&&(o="cssFloat"),l?r.setProperty(o,d):r[o]=d}}var s0=W({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function lu(r,s){if(s){if(s0[r]&&(s.children!=null||s.dangerouslySetInnerHTML!=null))throw Error(t(137,r));if(s.dangerouslySetInnerHTML!=null){if(s.children!=null)throw Error(t(60));if(typeof s.dangerouslySetInnerHTML!="object"||!("__html"in s.dangerouslySetInnerHTML))throw Error(t(61))}if(s.style!=null&&typeof s.style!="object")throw Error(t(62))}}function uu(r,s){if(r.indexOf("-")===-1)return typeof s.is=="string";switch(r){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var cu=null;function du(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var fu=null,Rs=null,Ls=null;function yf(r){if(r=io(r)){if(typeof fu!="function")throw Error(t(280));var s=r.stateNode;s&&(s=ya(s),fu(r.stateNode,r.type,s))}}function gf(r){Rs?Ls?Ls.push(r):Ls=[r]:Rs=r}function vf(){if(Rs){var r=Rs,s=Ls;if(Ls=Rs=null,yf(r),s)for(r=0;r>>=0,r===0?32:31-(m0(r)/y0|0)|0}var Zo=64,Xo=4194304;function Pi(r){switch(r&-r){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return r&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return r}}function ea(r,s){var o=r.pendingLanes;if(o===0)return 0;var l=0,d=r.suspendedLanes,p=r.pingedLanes,y=o&268435455;if(y!==0){var S=y&~d;S!==0?l=Pi(S):(p&=y,p!==0&&(l=Pi(p)))}else y=o&~d,y!==0?l=Pi(y):p!==0&&(l=Pi(p));if(l===0)return 0;if(s!==0&&s!==l&&(s&d)===0&&(d=l&-l,p=s&-s,d>=p||d===16&&(p&4194240)!==0))return s;if((l&4)!==0&&(l|=o&16),s=r.entangledLanes,s!==0)for(r=r.entanglements,s&=l;0o;o++)s.push(r);return s}function zi(r,s,o){r.pendingLanes|=s,s!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,s=31-wn(s),r[s]=o}function b0(r,s){var o=r.pendingLanes&~s;r.pendingLanes=s,r.suspendedLanes=0,r.pingedLanes=0,r.expiredLanes&=s,r.mutableReadLanes&=s,r.entangledLanes&=s,s=r.entanglements;var l=r.eventTimes;for(r=r.expirationTimes;0=Ji),Gf=" ",Yf=!1;function Qf(r,s){switch(r){case"keyup":return Q0.indexOf(s.keyCode)!==-1;case"keydown":return s.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Kf(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var Ps=!1;function J0(r,s){switch(r){case"compositionend":return Kf(s);case"keypress":return s.which!==32?null:(Yf=!0,Gf);case"textInput":return r=s.data,r===Gf&&Yf?null:r;default:return null}}function q0(r,s){if(Ps)return r==="compositionend"||!Cu&&Qf(r,s)?(r=$f(),ia=Nu=Er=null,Ps=!1,r):null;switch(r){case"paste":return null;case"keypress":if(!(s.ctrlKey||s.altKey||s.metaKey)||s.ctrlKey&&s.altKey){if(s.char&&1=s)return{node:o,offset:s-r};r=l}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=nh(o)}}function sh(r,s){return r&&s?r===s?!0:r&&r.nodeType===3?!1:s&&s.nodeType===3?sh(r,s.parentNode):"contains"in r?r.contains(s):r.compareDocumentPosition?!!(r.compareDocumentPosition(s)&16):!1:!1}function ih(){for(var r=window,s=xn();s instanceof r.HTMLIFrameElement;){try{var o=typeof s.contentWindow.location.href=="string"}catch{o=!1}if(o)r=s.contentWindow;else break;s=xn(r.document)}return s}function Tu(r){var s=r&&r.nodeName&&r.nodeName.toLowerCase();return s&&(s==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||s==="textarea"||r.contentEditable==="true")}function ox(r){var s=ih(),o=r.focusedElem,l=r.selectionRange;if(s!==o&&o&&o.ownerDocument&&sh(o.ownerDocument.documentElement,o)){if(l!==null&&Tu(o)){if(s=l.start,r=l.end,r===void 0&&(r=s),"selectionStart"in o)o.selectionStart=s,o.selectionEnd=Math.min(r,o.value.length);else if(r=(s=o.ownerDocument||document)&&s.defaultView||window,r.getSelection){r=r.getSelection();var d=o.textContent.length,p=Math.min(l.start,d);l=l.end===void 0?p:Math.min(l.end,d),!r.extend&&p>l&&(d=l,l=p,p=d),d=rh(o,p);var y=rh(o,l);d&&y&&(r.rangeCount!==1||r.anchorNode!==d.node||r.anchorOffset!==d.offset||r.focusNode!==y.node||r.focusOffset!==y.offset)&&(s=s.createRange(),s.setStart(d.node,d.offset),r.removeAllRanges(),p>l?(r.addRange(s),r.extend(y.node,y.offset)):(s.setEnd(y.node,y.offset),r.addRange(s)))}}for(s=[],r=o;r=r.parentNode;)r.nodeType===1&&s.push({element:r,left:r.scrollLeft,top:r.scrollTop});for(typeof o.focus=="function"&&o.focus(),o=0;o=document.documentMode,zs=null,Au=null,eo=null,Bu=!1;function oh(r,s,o){var l=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;Bu||zs==null||zs!==xn(l)||(l=zs,"selectionStart"in l&&Tu(l)?l={start:l.selectionStart,end:l.selectionEnd}:(l=(l.ownerDocument&&l.ownerDocument.defaultView||window).getSelection(),l={anchorNode:l.anchorNode,anchorOffset:l.anchorOffset,focusNode:l.focusNode,focusOffset:l.focusOffset}),eo&&Xi(eo,l)||(eo=l,l=ha(Au,"onSelect"),0Ys||(r.current=Yu[Ys],Yu[Ys]=null,Ys--)}function qe(r,s){Ys++,Yu[Ys]=r.current,r.current=s}var $r={},jt=Ur($r),Bt=Ur(!1),ps=$r;function Qs(r,s){var o=r.type.contextTypes;if(!o)return $r;var l=r.stateNode;if(l&&l.__reactInternalMemoizedUnmaskedChildContext===s)return l.__reactInternalMemoizedMaskedChildContext;var d={},p;for(p in o)d[p]=s[p];return l&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=s,r.__reactInternalMemoizedMaskedChildContext=d),d}function Et(r){return r=r.childContextTypes,r!=null}function ga(){et(Bt),et(jt)}function wh(r,s,o){if(jt.current!==$r)throw Error(t(168));qe(jt,s),qe(Bt,o)}function Sh(r,s,o){var l=r.stateNode;if(s=s.childContextTypes,typeof l.getChildContext!="function")return o;l=l.getChildContext();for(var d in l)if(!(d in s))throw Error(t(108,Ce(r)||"Unknown",d));return W({},o,l)}function va(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||$r,ps=jt.current,qe(jt,r),qe(Bt,Bt.current),!0}function _h(r,s,o){var l=r.stateNode;if(!l)throw Error(t(169));o?(r=Sh(r,s,ps),l.__reactInternalMemoizedMergedChildContext=r,et(Bt),et(jt),qe(jt,r)):et(Bt),qe(Bt,o)}var ar=null,xa=!1,Qu=!1;function Nh(r){ar===null?ar=[r]:ar.push(r)}function vx(r){xa=!0,Nh(r)}function Pr(){if(!Qu&&ar!==null){Qu=!0;var r=0,s=Ge;try{var o=ar;for(Ge=1;r>=y,d-=y,lr=1<<32-wn(s)+d|o<Me?(bt=ge,ge=null):bt=ge.sibling;var ze=K(B,ge,$[Me],Z);if(ze===null){ge===null&&(ge=bt);break}r&&ge&&ze.alternate===null&&s(B,ge),k=p(ze,k,Me),ye===null?he=ze:ye.sibling=ze,ye=ze,ge=bt}if(Me===$.length)return o(B,ge),st&&ys(B,Me),he;if(ge===null){for(;Me<$.length;Me++)ge=q(B,$[Me],Z),ge!==null&&(k=p(ge,k,Me),ye===null?he=ge:ye.sibling=ge,ye=ge);return st&&ys(B,Me),he}for(ge=l(B,ge);Me<$.length;Me++)bt=oe(ge,B,Me,$[Me],Z),bt!==null&&(r&&bt.alternate!==null&&ge.delete(bt.key===null?Me:bt.key),k=p(bt,k,Me),ye===null?he=bt:ye.sibling=bt,ye=bt);return r&&ge.forEach(function(Jr){return s(B,Jr)}),st&&ys(B,Me),he}function de(B,k,$,Z){var he=Y($);if(typeof he!="function")throw Error(t(150));if($=he.call($),$==null)throw Error(t(151));for(var ye=he=null,ge=k,Me=k=0,bt=null,ze=$.next();ge!==null&&!ze.done;Me++,ze=$.next()){ge.index>Me?(bt=ge,ge=null):bt=ge.sibling;var Jr=K(B,ge,ze.value,Z);if(Jr===null){ge===null&&(ge=bt);break}r&&ge&&Jr.alternate===null&&s(B,ge),k=p(Jr,k,Me),ye===null?he=Jr:ye.sibling=Jr,ye=Jr,ge=bt}if(ze.done)return o(B,ge),st&&ys(B,Me),he;if(ge===null){for(;!ze.done;Me++,ze=$.next())ze=q(B,ze.value,Z),ze!==null&&(k=p(ze,k,Me),ye===null?he=ze:ye.sibling=ze,ye=ze);return st&&ys(B,Me),he}for(ge=l(B,ge);!ze.done;Me++,ze=$.next())ze=oe(ge,B,Me,ze.value,Z),ze!==null&&(r&&ze.alternate!==null&&ge.delete(ze.key===null?Me:ze.key),k=p(ze,k,Me),ye===null?he=ze:ye.sibling=ze,ye=ze);return r&&ge.forEach(function(Zx){return s(B,Zx)}),st&&ys(B,Me),he}function dt(B,k,$,Z){if(typeof $=="object"&&$!==null&&$.type===U&&$.key===null&&($=$.props.children),typeof $=="object"&&$!==null){switch($.$$typeof){case E:e:{for(var he=$.key,ye=k;ye!==null;){if(ye.key===he){if(he=$.type,he===U){if(ye.tag===7){o(B,ye.sibling),k=d(ye,$.props.children),k.return=B,B=k;break e}}else if(ye.elementType===he||typeof he=="object"&&he!==null&&he.$$typeof===re&&Ch(he)===ye.type){o(B,ye.sibling),k=d(ye,$.props),k.ref=oo(B,ye,$),k.return=B,B=k;break e}o(B,ye);break}else s(B,ye);ye=ye.sibling}$.type===U?(k=Ns($.props.children,B.mode,Z,$.key),k.return=B,B=k):(Z=Ya($.type,$.key,$.props,null,B.mode,Z),Z.ref=oo(B,k,$),Z.return=B,B=Z)}return y(B);case I:e:{for(ye=$.key;k!==null;){if(k.key===ye)if(k.tag===4&&k.stateNode.containerInfo===$.containerInfo&&k.stateNode.implementation===$.implementation){o(B,k.sibling),k=d(k,$.children||[]),k.return=B,B=k;break e}else{o(B,k);break}else s(B,k);k=k.sibling}k=Hc($,B.mode,Z),k.return=B,B=k}return y(B);case re:return ye=$._init,dt(B,k,ye($._payload),Z)}if(Un($))return ce(B,k,$,Z);if(Y($))return de(B,k,$,Z);_a(B,$)}return typeof $=="string"&&$!==""||typeof $=="number"?($=""+$,k!==null&&k.tag===6?(o(B,k.sibling),k=d(k,$),k.return=B,B=k):(o(B,k),k=Wc($,B.mode,Z),k.return=B,B=k),y(B)):o(B,k)}return dt}var Zs=Fh(!0),Oh=Fh(!1),Na=Ur(null),ja=null,Xs=null,ec=null;function tc(){ec=Xs=ja=null}function nc(r){var s=Na.current;et(Na),r._currentValue=s}function rc(r,s,o){for(;r!==null;){var l=r.alternate;if((r.childLanes&s)!==s?(r.childLanes|=s,l!==null&&(l.childLanes|=s)):l!==null&&(l.childLanes&s)!==s&&(l.childLanes|=s),r===o)break;r=r.return}}function ei(r,s){ja=r,ec=Xs=null,r=r.dependencies,r!==null&&r.firstContext!==null&&((r.lanes&s)!==0&&(Rt=!0),r.firstContext=null)}function sn(r){var s=r._currentValue;if(ec!==r)if(r={context:r,memoizedValue:s,next:null},Xs===null){if(ja===null)throw Error(t(308));Xs=r,ja.dependencies={lanes:0,firstContext:r}}else Xs=Xs.next=r;return s}var gs=null;function sc(r){gs===null?gs=[r]:gs.push(r)}function Th(r,s,o,l){var d=s.interleaved;return d===null?(o.next=o,sc(s)):(o.next=d.next,d.next=o),s.interleaved=o,cr(r,l)}function cr(r,s){r.lanes|=s;var o=r.alternate;for(o!==null&&(o.lanes|=s),o=r,r=r.return;r!==null;)r.childLanes|=s,o=r.alternate,o!==null&&(o.childLanes|=s),o=r,r=r.return;return o.tag===3?o.stateNode:null}var zr=!1;function ic(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ah(r,s){r=r.updateQueue,s.updateQueue===r&&(s.updateQueue={baseState:r.baseState,firstBaseUpdate:r.firstBaseUpdate,lastBaseUpdate:r.lastBaseUpdate,shared:r.shared,effects:r.effects})}function dr(r,s){return{eventTime:r,lane:s,tag:0,payload:null,callback:null,next:null}}function Vr(r,s,o){var l=r.updateQueue;if(l===null)return null;if(l=l.shared,(Pe&2)!==0){var d=l.pending;return d===null?s.next=s:(s.next=d.next,d.next=s),l.pending=s,cr(r,o)}return d=l.interleaved,d===null?(s.next=s,sc(l)):(s.next=d.next,d.next=s),l.interleaved=s,cr(r,o)}function ka(r,s,o){if(s=s.updateQueue,s!==null&&(s=s.shared,(o&4194240)!==0)){var l=s.lanes;l&=r.pendingLanes,o|=l,s.lanes=o,xu(r,o)}}function Bh(r,s){var o=r.updateQueue,l=r.alternate;if(l!==null&&(l=l.updateQueue,o===l)){var d=null,p=null;if(o=o.firstBaseUpdate,o!==null){do{var y={eventTime:o.eventTime,lane:o.lane,tag:o.tag,payload:o.payload,callback:o.callback,next:null};p===null?d=p=y:p=p.next=y,o=o.next}while(o!==null);p===null?d=p=s:p=p.next=s}else d=p=s;o={baseState:l.baseState,firstBaseUpdate:d,lastBaseUpdate:p,shared:l.shared,effects:l.effects},r.updateQueue=o;return}r=o.lastBaseUpdate,r===null?o.firstBaseUpdate=s:r.next=s,o.lastBaseUpdate=s}function Ia(r,s,o,l){var d=r.updateQueue;zr=!1;var p=d.firstBaseUpdate,y=d.lastBaseUpdate,S=d.shared.pending;if(S!==null){d.shared.pending=null;var N=S,P=N.next;N.next=null,y===null?p=P:y.next=P,y=N;var J=r.alternate;J!==null&&(J=J.updateQueue,S=J.lastBaseUpdate,S!==y&&(S===null?J.firstBaseUpdate=P:S.next=P,J.lastBaseUpdate=N))}if(p!==null){var q=d.baseState;y=0,J=P=N=null,S=p;do{var K=S.lane,oe=S.eventTime;if((l&K)===K){J!==null&&(J=J.next={eventTime:oe,lane:0,tag:S.tag,payload:S.payload,callback:S.callback,next:null});e:{var ce=r,de=S;switch(K=s,oe=o,de.tag){case 1:if(ce=de.payload,typeof ce=="function"){q=ce.call(oe,q,K);break e}q=ce;break e;case 3:ce.flags=ce.flags&-65537|128;case 0:if(ce=de.payload,K=typeof ce=="function"?ce.call(oe,q,K):ce,K==null)break e;q=W({},q,K);break e;case 2:zr=!0}}S.callback!==null&&S.lane!==0&&(r.flags|=64,K=d.effects,K===null?d.effects=[S]:K.push(S))}else oe={eventTime:oe,lane:K,tag:S.tag,payload:S.payload,callback:S.callback,next:null},J===null?(P=J=oe,N=q):J=J.next=oe,y|=K;if(S=S.next,S===null){if(S=d.shared.pending,S===null)break;K=S,S=K.next,K.next=null,d.lastBaseUpdate=K,d.shared.pending=null}}while(!0);if(J===null&&(N=q),d.baseState=N,d.firstBaseUpdate=P,d.lastBaseUpdate=J,s=d.shared.interleaved,s!==null){d=s;do y|=d.lane,d=d.next;while(d!==s)}else p===null&&(d.shared.lanes=0);bs|=y,r.lanes=y,r.memoizedState=q}}function Eh(r,s,o){if(r=s.effects,s.effects=null,r!==null)for(s=0;so?o:4,r(!0);var l=cc.transition;cc.transition={};try{r(!1),s()}finally{Ge=o,cc.transition=l}}function tp(){return on().memoizedState}function Sx(r,s,o){var l=Yr(r);if(o={lane:l,action:o,hasEagerState:!1,eagerState:null,next:null},np(r))rp(s,o);else if(o=Th(r,s,o,l),o!==null){var d=Ft();In(o,r,l,d),sp(o,s,l)}}function _x(r,s,o){var l=Yr(r),d={lane:l,action:o,hasEagerState:!1,eagerState:null,next:null};if(np(r))rp(s,d);else{var p=r.alternate;if(r.lanes===0&&(p===null||p.lanes===0)&&(p=s.lastRenderedReducer,p!==null))try{var y=s.lastRenderedState,S=p(y,o);if(d.hasEagerState=!0,d.eagerState=S,Sn(S,y)){var N=s.interleaved;N===null?(d.next=d,sc(s)):(d.next=N.next,N.next=d),s.interleaved=d;return}}catch{}finally{}o=Th(r,s,d,l),o!==null&&(d=Ft(),In(o,r,l,d),sp(o,s,l))}}function np(r){var s=r.alternate;return r===ot||s!==null&&s===ot}function rp(r,s){co=Ca=!0;var o=r.pending;o===null?s.next=s:(s.next=o.next,o.next=s),r.pending=s}function sp(r,s,o){if((o&4194240)!==0){var l=s.lanes;l&=r.pendingLanes,o|=l,s.lanes=o,xu(r,o)}}var Ta={readContext:sn,useCallback:kt,useContext:kt,useEffect:kt,useImperativeHandle:kt,useInsertionEffect:kt,useLayoutEffect:kt,useMemo:kt,useReducer:kt,useRef:kt,useState:kt,useDebugValue:kt,useDeferredValue:kt,useTransition:kt,useMutableSource:kt,useSyncExternalStore:kt,useId:kt,unstable_isNewReconciler:!1},Nx={readContext:sn,useCallback:function(r,s){return Vn().memoizedState=[r,s===void 0?null:s],r},useContext:sn,useEffect:Yh,useImperativeHandle:function(r,s,o){return o=o!=null?o.concat([r]):null,Fa(4194308,4,Jh.bind(null,s,r),o)},useLayoutEffect:function(r,s){return Fa(4194308,4,r,s)},useInsertionEffect:function(r,s){return Fa(4,2,r,s)},useMemo:function(r,s){var o=Vn();return s=s===void 0?null:s,r=r(),o.memoizedState=[r,s],r},useReducer:function(r,s,o){var l=Vn();return s=o!==void 0?o(s):s,l.memoizedState=l.baseState=s,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:s},l.queue=r,r=r.dispatch=Sx.bind(null,ot,r),[l.memoizedState,r]},useRef:function(r){var s=Vn();return r={current:r},s.memoizedState=r},useState:Hh,useDebugValue:gc,useDeferredValue:function(r){return Vn().memoizedState=r},useTransition:function(){var r=Hh(!1),s=r[0];return r=wx.bind(null,r[1]),Vn().memoizedState=r,[s,r]},useMutableSource:function(){},useSyncExternalStore:function(r,s,o){var l=ot,d=Vn();if(st){if(o===void 0)throw Error(t(407));o=o()}else{if(o=s(),xt===null)throw Error(t(349));(xs&30)!==0||$h(l,s,o)}d.memoizedState=o;var p={value:o,getSnapshot:s};return d.queue=p,Yh(zh.bind(null,l,p,r),[r]),l.flags|=2048,po(9,Ph.bind(null,l,p,o,s),void 0,null),o},useId:function(){var r=Vn(),s=xt.identifierPrefix;if(st){var o=ur,l=lr;o=(l&~(1<<32-wn(l)-1)).toString(32)+o,s=":"+s+"R"+o,o=fo++,0")&&(N=N.replace("",r.displayName)),N}while(1<=y&&0<=S);break}}}finally{te=!1,Error.prepareStackTrace=o}return(r=r?r.displayName||r.name:"")?F(r):""}function ne(r){switch(r.tag){case 5:return F(r.type);case 16:return F("Lazy");case 13:return F("Suspense");case 19:return F("SuspenseList");case 0:case 2:case 15:return r=pe(r.type,!1),r;case 11:return r=pe(r.type.render,!1),r;case 1:return r=pe(r.type,!0),r;default:return""}}function fe(r){if(r==null)return null;if(typeof r=="function")return r.displayName||r.name||null;if(typeof r=="string")return r;switch(r){case U:return"Fragment";case I:return"Portal";case V:return"Profiler";case G:return"StrictMode";case X:return"Suspense";case ie:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case z:return(r.displayName||"Context")+".Consumer";case Q:return(r._context.displayName||"Context")+".Provider";case ee:var s=r.render;return r=r.displayName,r||(r=s.displayName||s.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case ae:return s=r.displayName||null,s!==null?s:fe(r.type)||"Memo";case re:s=r._payload,r=r._init;try{return fe(r(s))}catch{}}return null}function Ce(r){var s=r.type;switch(r.tag){case 24:return"Cache";case 9:return(s.displayName||"Context")+".Consumer";case 10:return(s._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return r=s.render,r=r.displayName||r.name||"",s.displayName||(r!==""?"ForwardRef("+r+")":"ForwardRef");case 7:return"Fragment";case 5:return s;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return fe(s);case 8:return s===G?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof s=="function")return s.displayName||s.name||null;if(typeof s=="string")return s}return null}function Te(r){switch(typeof r){case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function Ue(r){var s=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(s==="checkbox"||s==="radio")}function lt(r){var s=Ue(r)?"checked":"value",o=Object.getOwnPropertyDescriptor(r.constructor.prototype,s),l=""+r[s];if(!r.hasOwnProperty(s)&&typeof o<"u"&&typeof o.get=="function"&&typeof o.set=="function"){var d=o.get,p=o.set;return Object.defineProperty(r,s,{configurable:!0,get:function(){return d.call(this)},set:function(y){l=""+y,p.call(this,y)}}),Object.defineProperty(r,s,{enumerable:o.enumerable}),{getValue:function(){return l},setValue:function(y){l=""+y},stopTracking:function(){r._valueTracker=null,delete r[s]}}}}function wt(r){r._valueTracker||(r._valueTracker=lt(r))}function Bs(r){if(!r)return!1;var s=r._valueTracker;if(!s)return!0;var o=s.getValue(),l="";return r&&(l=Ue(r)?r.checked?"true":"false":r.value),r=l,r!==o?(s.setValue(r),!0):!1}function xn(r){if(r=r||(typeof document<"u"?document:void 0),typeof r>"u")return null;try{return r.activeElement||r.body}catch{return r.body}}function Cr(r,s){var o=s.checked;return W({},s,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:o??r._wrapperState.initialChecked})}function Fr(r,s){var o=s.defaultValue==null?"":s.defaultValue,l=s.checked!=null?s.checked:s.defaultChecked;o=Te(s.value!=null?s.value:o),r._wrapperState={initialChecked:l,initialValue:o,controlled:s.type==="checkbox"||s.type==="radio"?s.checked!=null:s.value!=null}}function ue(r,s){s=s.checked,s!=null&&R(r,"checked",s,!1)}function Oe(r,s){ue(r,s);var o=Te(s.value),l=s.type;if(o!=null)l==="number"?(o===0&&r.value===""||r.value!=o)&&(r.value=""+o):r.value!==""+o&&(r.value=""+o);else if(l==="submit"||l==="reset"){r.removeAttribute("value");return}s.hasOwnProperty("value")?Nt(r,s.type,o):s.hasOwnProperty("defaultValue")&&Nt(r,s.type,Te(s.defaultValue)),s.checked==null&&s.defaultChecked!=null&&(r.defaultChecked=!!s.defaultChecked)}function rt(r,s,o){if(s.hasOwnProperty("value")||s.hasOwnProperty("defaultValue")){var l=s.type;if(!(l!=="submit"&&l!=="reset"||s.value!==void 0&&s.value!==null))return;s=""+r._wrapperState.initialValue,o||s===r.value||(r.value=s),r.defaultValue=s}o=r.name,o!==""&&(r.name=""),r.defaultChecked=!!r._wrapperState.initialChecked,o!==""&&(r.name=o)}function Nt(r,s,o){(s!=="number"||xn(r.ownerDocument)!==r)&&(o==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+o&&(r.defaultValue=""+o))}var Un=Array.isArray;function sr(r,s,o,l){if(r=r.options,s){s={};for(var d=0;d"+s.valueOf().toString()+"",s=ds.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;s.firstChild;)r.appendChild(s.firstChild)}});function ir(r,s){if(s){var o=r.firstChild;if(o&&o===r.lastChild&&o.nodeType===3){o.nodeValue=s;return}}r.textContent=s}var Ri={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},o0=["Webkit","ms","Moz","O"];Object.keys(Ri).forEach(function(r){o0.forEach(function(s){s=s+r.charAt(0).toUpperCase()+r.substring(1),Ri[s]=Ri[r]})});function pf(r,s,o){return s==null||typeof s=="boolean"||s===""?"":o||typeof s!="number"||s===0||Ri.hasOwnProperty(r)&&Ri[r]?(""+s).trim():s+"px"}function mf(r,s){r=r.style;for(var o in s)if(s.hasOwnProperty(o)){var l=o.indexOf("--")===0,d=pf(o,s[o],l);o==="float"&&(o="cssFloat"),l?r.setProperty(o,d):r[o]=d}}var a0=W({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function lu(r,s){if(s){if(a0[r]&&(s.children!=null||s.dangerouslySetInnerHTML!=null))throw Error(t(137,r));if(s.dangerouslySetInnerHTML!=null){if(s.children!=null)throw Error(t(60));if(typeof s.dangerouslySetInnerHTML!="object"||!("__html"in s.dangerouslySetInnerHTML))throw Error(t(61))}if(s.style!=null&&typeof s.style!="object")throw Error(t(62))}}function uu(r,s){if(r.indexOf("-")===-1)return typeof s.is=="string";switch(r){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var cu=null;function du(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var fu=null,Rs=null,Ls=null;function yf(r){if(r=io(r)){if(typeof fu!="function")throw Error(t(280));var s=r.stateNode;s&&(s=ya(s),fu(r.stateNode,r.type,s))}}function gf(r){Rs?Ls?Ls.push(r):Ls=[r]:Rs=r}function vf(){if(Rs){var r=Rs,s=Ls;if(Ls=Rs=null,yf(r),s)for(r=0;r>>=0,r===0?32:31-(v0(r)/x0|0)|0}var Zo=64,Xo=4194304;function Pi(r){switch(r&-r){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return r&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return r}}function ea(r,s){var o=r.pendingLanes;if(o===0)return 0;var l=0,d=r.suspendedLanes,p=r.pingedLanes,y=o&268435455;if(y!==0){var S=y&~d;S!==0?l=Pi(S):(p&=y,p!==0&&(l=Pi(p)))}else y=o&~d,y!==0?l=Pi(y):p!==0&&(l=Pi(p));if(l===0)return 0;if(s!==0&&s!==l&&(s&d)===0&&(d=l&-l,p=s&-s,d>=p||d===16&&(p&4194240)!==0))return s;if((l&4)!==0&&(l|=o&16),s=r.entangledLanes,s!==0)for(r=r.entanglements,s&=l;0o;o++)s.push(r);return s}function zi(r,s,o){r.pendingLanes|=s,s!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,s=31-wn(s),r[s]=o}function _0(r,s){var o=r.pendingLanes&~s;r.pendingLanes=s,r.suspendedLanes=0,r.pingedLanes=0,r.expiredLanes&=s,r.mutableReadLanes&=s,r.entangledLanes&=s,s=r.entanglements;var l=r.eventTimes;for(r=r.expirationTimes;0=Ji),Gf=" ",Yf=!1;function Qf(r,s){switch(r){case"keyup":return q0.indexOf(s.keyCode)!==-1;case"keydown":return s.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Kf(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var Ps=!1;function X0(r,s){switch(r){case"compositionend":return Kf(s);case"keypress":return s.which!==32?null:(Yf=!0,Gf);case"textInput":return r=s.data,r===Gf&&Yf?null:r;default:return null}}function ex(r,s){if(Ps)return r==="compositionend"||!Cu&&Qf(r,s)?(r=$f(),ia=Nu=Er=null,Ps=!1,r):null;switch(r){case"paste":return null;case"keypress":if(!(s.ctrlKey||s.altKey||s.metaKey)||s.ctrlKey&&s.altKey){if(s.char&&1=s)return{node:o,offset:s-r};r=l}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=nh(o)}}function sh(r,s){return r&&s?r===s?!0:r&&r.nodeType===3?!1:s&&s.nodeType===3?sh(r,s.parentNode):"contains"in r?r.contains(s):r.compareDocumentPosition?!!(r.compareDocumentPosition(s)&16):!1:!1}function ih(){for(var r=window,s=xn();s instanceof r.HTMLIFrameElement;){try{var o=typeof s.contentWindow.location.href=="string"}catch{o=!1}if(o)r=s.contentWindow;else break;s=xn(r.document)}return s}function Tu(r){var s=r&&r.nodeName&&r.nodeName.toLowerCase();return s&&(s==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||s==="textarea"||r.contentEditable==="true")}function ux(r){var s=ih(),o=r.focusedElem,l=r.selectionRange;if(s!==o&&o&&o.ownerDocument&&sh(o.ownerDocument.documentElement,o)){if(l!==null&&Tu(o)){if(s=l.start,r=l.end,r===void 0&&(r=s),"selectionStart"in o)o.selectionStart=s,o.selectionEnd=Math.min(r,o.value.length);else if(r=(s=o.ownerDocument||document)&&s.defaultView||window,r.getSelection){r=r.getSelection();var d=o.textContent.length,p=Math.min(l.start,d);l=l.end===void 0?p:Math.min(l.end,d),!r.extend&&p>l&&(d=l,l=p,p=d),d=rh(o,p);var y=rh(o,l);d&&y&&(r.rangeCount!==1||r.anchorNode!==d.node||r.anchorOffset!==d.offset||r.focusNode!==y.node||r.focusOffset!==y.offset)&&(s=s.createRange(),s.setStart(d.node,d.offset),r.removeAllRanges(),p>l?(r.addRange(s),r.extend(y.node,y.offset)):(s.setEnd(y.node,y.offset),r.addRange(s)))}}for(s=[],r=o;r=r.parentNode;)r.nodeType===1&&s.push({element:r,left:r.scrollLeft,top:r.scrollTop});for(typeof o.focus=="function"&&o.focus(),o=0;o=document.documentMode,zs=null,Au=null,eo=null,Bu=!1;function oh(r,s,o){var l=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;Bu||zs==null||zs!==xn(l)||(l=zs,"selectionStart"in l&&Tu(l)?l={start:l.selectionStart,end:l.selectionEnd}:(l=(l.ownerDocument&&l.ownerDocument.defaultView||window).getSelection(),l={anchorNode:l.anchorNode,anchorOffset:l.anchorOffset,focusNode:l.focusNode,focusOffset:l.focusOffset}),eo&&Xi(eo,l)||(eo=l,l=ha(Au,"onSelect"),0Ys||(r.current=Yu[Ys],Yu[Ys]=null,Ys--)}function qe(r,s){Ys++,Yu[Ys]=r.current,r.current=s}var $r={},jt=Ur($r),Bt=Ur(!1),ps=$r;function Qs(r,s){var o=r.type.contextTypes;if(!o)return $r;var l=r.stateNode;if(l&&l.__reactInternalMemoizedUnmaskedChildContext===s)return l.__reactInternalMemoizedMaskedChildContext;var d={},p;for(p in o)d[p]=s[p];return l&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=s,r.__reactInternalMemoizedMaskedChildContext=d),d}function Et(r){return r=r.childContextTypes,r!=null}function ga(){et(Bt),et(jt)}function wh(r,s,o){if(jt.current!==$r)throw Error(t(168));qe(jt,s),qe(Bt,o)}function Sh(r,s,o){var l=r.stateNode;if(s=s.childContextTypes,typeof l.getChildContext!="function")return o;l=l.getChildContext();for(var d in l)if(!(d in s))throw Error(t(108,Ce(r)||"Unknown",d));return W({},o,l)}function va(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||$r,ps=jt.current,qe(jt,r),qe(Bt,Bt.current),!0}function _h(r,s,o){var l=r.stateNode;if(!l)throw Error(t(169));o?(r=Sh(r,s,ps),l.__reactInternalMemoizedMergedChildContext=r,et(Bt),et(jt),qe(jt,r)):et(Bt),qe(Bt,o)}var ar=null,xa=!1,Qu=!1;function Nh(r){ar===null?ar=[r]:ar.push(r)}function wx(r){xa=!0,Nh(r)}function Pr(){if(!Qu&&ar!==null){Qu=!0;var r=0,s=Ge;try{var o=ar;for(Ge=1;r>=y,d-=y,lr=1<<32-wn(s)+d|o<Me?(bt=ge,ge=null):bt=ge.sibling;var ze=K(B,ge,$[Me],Z);if(ze===null){ge===null&&(ge=bt);break}r&&ge&&ze.alternate===null&&s(B,ge),k=p(ze,k,Me),ye===null?he=ze:ye.sibling=ze,ye=ze,ge=bt}if(Me===$.length)return o(B,ge),st&&ys(B,Me),he;if(ge===null){for(;Me<$.length;Me++)ge=q(B,$[Me],Z),ge!==null&&(k=p(ge,k,Me),ye===null?he=ge:ye.sibling=ge,ye=ge);return st&&ys(B,Me),he}for(ge=l(B,ge);Me<$.length;Me++)bt=oe(ge,B,Me,$[Me],Z),bt!==null&&(r&&bt.alternate!==null&&ge.delete(bt.key===null?Me:bt.key),k=p(bt,k,Me),ye===null?he=bt:ye.sibling=bt,ye=bt);return r&&ge.forEach(function(Jr){return s(B,Jr)}),st&&ys(B,Me),he}function de(B,k,$,Z){var he=Y($);if(typeof he!="function")throw Error(t(150));if($=he.call($),$==null)throw Error(t(151));for(var ye=he=null,ge=k,Me=k=0,bt=null,ze=$.next();ge!==null&&!ze.done;Me++,ze=$.next()){ge.index>Me?(bt=ge,ge=null):bt=ge.sibling;var Jr=K(B,ge,ze.value,Z);if(Jr===null){ge===null&&(ge=bt);break}r&&ge&&Jr.alternate===null&&s(B,ge),k=p(Jr,k,Me),ye===null?he=Jr:ye.sibling=Jr,ye=Jr,ge=bt}if(ze.done)return o(B,ge),st&&ys(B,Me),he;if(ge===null){for(;!ze.done;Me++,ze=$.next())ze=q(B,ze.value,Z),ze!==null&&(k=p(ze,k,Me),ye===null?he=ze:ye.sibling=ze,ye=ze);return st&&ys(B,Me),he}for(ge=l(B,ge);!ze.done;Me++,ze=$.next())ze=oe(ge,B,Me,ze.value,Z),ze!==null&&(r&&ze.alternate!==null&&ge.delete(ze.key===null?Me:ze.key),k=p(ze,k,Me),ye===null?he=ze:ye.sibling=ze,ye=ze);return r&&ge.forEach(function(tb){return s(B,tb)}),st&&ys(B,Me),he}function dt(B,k,$,Z){if(typeof $=="object"&&$!==null&&$.type===U&&$.key===null&&($=$.props.children),typeof $=="object"&&$!==null){switch($.$$typeof){case E:e:{for(var he=$.key,ye=k;ye!==null;){if(ye.key===he){if(he=$.type,he===U){if(ye.tag===7){o(B,ye.sibling),k=d(ye,$.props.children),k.return=B,B=k;break e}}else if(ye.elementType===he||typeof he=="object"&&he!==null&&he.$$typeof===re&&Ch(he)===ye.type){o(B,ye.sibling),k=d(ye,$.props),k.ref=oo(B,ye,$),k.return=B,B=k;break e}o(B,ye);break}else s(B,ye);ye=ye.sibling}$.type===U?(k=Ns($.props.children,B.mode,Z,$.key),k.return=B,B=k):(Z=Ya($.type,$.key,$.props,null,B.mode,Z),Z.ref=oo(B,k,$),Z.return=B,B=Z)}return y(B);case I:e:{for(ye=$.key;k!==null;){if(k.key===ye)if(k.tag===4&&k.stateNode.containerInfo===$.containerInfo&&k.stateNode.implementation===$.implementation){o(B,k.sibling),k=d(k,$.children||[]),k.return=B,B=k;break e}else{o(B,k);break}else s(B,k);k=k.sibling}k=Hc($,B.mode,Z),k.return=B,B=k}return y(B);case re:return ye=$._init,dt(B,k,ye($._payload),Z)}if(Un($))return ce(B,k,$,Z);if(Y($))return de(B,k,$,Z);_a(B,$)}return typeof $=="string"&&$!==""||typeof $=="number"?($=""+$,k!==null&&k.tag===6?(o(B,k.sibling),k=d(k,$),k.return=B,B=k):(o(B,k),k=Wc($,B.mode,Z),k.return=B,B=k),y(B)):o(B,k)}return dt}var Zs=Fh(!0),Oh=Fh(!1),Na=Ur(null),ja=null,Xs=null,ec=null;function tc(){ec=Xs=ja=null}function nc(r){var s=Na.current;et(Na),r._currentValue=s}function rc(r,s,o){for(;r!==null;){var l=r.alternate;if((r.childLanes&s)!==s?(r.childLanes|=s,l!==null&&(l.childLanes|=s)):l!==null&&(l.childLanes&s)!==s&&(l.childLanes|=s),r===o)break;r=r.return}}function ei(r,s){ja=r,ec=Xs=null,r=r.dependencies,r!==null&&r.firstContext!==null&&((r.lanes&s)!==0&&(Rt=!0),r.firstContext=null)}function sn(r){var s=r._currentValue;if(ec!==r)if(r={context:r,memoizedValue:s,next:null},Xs===null){if(ja===null)throw Error(t(308));Xs=r,ja.dependencies={lanes:0,firstContext:r}}else Xs=Xs.next=r;return s}var gs=null;function sc(r){gs===null?gs=[r]:gs.push(r)}function Th(r,s,o,l){var d=s.interleaved;return d===null?(o.next=o,sc(s)):(o.next=d.next,d.next=o),s.interleaved=o,cr(r,l)}function cr(r,s){r.lanes|=s;var o=r.alternate;for(o!==null&&(o.lanes|=s),o=r,r=r.return;r!==null;)r.childLanes|=s,o=r.alternate,o!==null&&(o.childLanes|=s),o=r,r=r.return;return o.tag===3?o.stateNode:null}var zr=!1;function ic(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ah(r,s){r=r.updateQueue,s.updateQueue===r&&(s.updateQueue={baseState:r.baseState,firstBaseUpdate:r.firstBaseUpdate,lastBaseUpdate:r.lastBaseUpdate,shared:r.shared,effects:r.effects})}function dr(r,s){return{eventTime:r,lane:s,tag:0,payload:null,callback:null,next:null}}function Vr(r,s,o){var l=r.updateQueue;if(l===null)return null;if(l=l.shared,(Pe&2)!==0){var d=l.pending;return d===null?s.next=s:(s.next=d.next,d.next=s),l.pending=s,cr(r,o)}return d=l.interleaved,d===null?(s.next=s,sc(l)):(s.next=d.next,d.next=s),l.interleaved=s,cr(r,o)}function ka(r,s,o){if(s=s.updateQueue,s!==null&&(s=s.shared,(o&4194240)!==0)){var l=s.lanes;l&=r.pendingLanes,o|=l,s.lanes=o,xu(r,o)}}function Bh(r,s){var o=r.updateQueue,l=r.alternate;if(l!==null&&(l=l.updateQueue,o===l)){var d=null,p=null;if(o=o.firstBaseUpdate,o!==null){do{var y={eventTime:o.eventTime,lane:o.lane,tag:o.tag,payload:o.payload,callback:o.callback,next:null};p===null?d=p=y:p=p.next=y,o=o.next}while(o!==null);p===null?d=p=s:p=p.next=s}else d=p=s;o={baseState:l.baseState,firstBaseUpdate:d,lastBaseUpdate:p,shared:l.shared,effects:l.effects},r.updateQueue=o;return}r=o.lastBaseUpdate,r===null?o.firstBaseUpdate=s:r.next=s,o.lastBaseUpdate=s}function Ia(r,s,o,l){var d=r.updateQueue;zr=!1;var p=d.firstBaseUpdate,y=d.lastBaseUpdate,S=d.shared.pending;if(S!==null){d.shared.pending=null;var N=S,P=N.next;N.next=null,y===null?p=P:y.next=P,y=N;var J=r.alternate;J!==null&&(J=J.updateQueue,S=J.lastBaseUpdate,S!==y&&(S===null?J.firstBaseUpdate=P:S.next=P,J.lastBaseUpdate=N))}if(p!==null){var q=d.baseState;y=0,J=P=N=null,S=p;do{var K=S.lane,oe=S.eventTime;if((l&K)===K){J!==null&&(J=J.next={eventTime:oe,lane:0,tag:S.tag,payload:S.payload,callback:S.callback,next:null});e:{var ce=r,de=S;switch(K=s,oe=o,de.tag){case 1:if(ce=de.payload,typeof ce=="function"){q=ce.call(oe,q,K);break e}q=ce;break e;case 3:ce.flags=ce.flags&-65537|128;case 0:if(ce=de.payload,K=typeof ce=="function"?ce.call(oe,q,K):ce,K==null)break e;q=W({},q,K);break e;case 2:zr=!0}}S.callback!==null&&S.lane!==0&&(r.flags|=64,K=d.effects,K===null?d.effects=[S]:K.push(S))}else oe={eventTime:oe,lane:K,tag:S.tag,payload:S.payload,callback:S.callback,next:null},J===null?(P=J=oe,N=q):J=J.next=oe,y|=K;if(S=S.next,S===null){if(S=d.shared.pending,S===null)break;K=S,S=K.next,K.next=null,d.lastBaseUpdate=K,d.shared.pending=null}}while(!0);if(J===null&&(N=q),d.baseState=N,d.firstBaseUpdate=P,d.lastBaseUpdate=J,s=d.shared.interleaved,s!==null){d=s;do y|=d.lane,d=d.next;while(d!==s)}else p===null&&(d.shared.lanes=0);bs|=y,r.lanes=y,r.memoizedState=q}}function Eh(r,s,o){if(r=s.effects,s.effects=null,r!==null)for(s=0;so?o:4,r(!0);var l=cc.transition;cc.transition={};try{r(!1),s()}finally{Ge=o,cc.transition=l}}function tp(){return on().memoizedState}function jx(r,s,o){var l=Yr(r);if(o={lane:l,action:o,hasEagerState:!1,eagerState:null,next:null},np(r))rp(s,o);else if(o=Th(r,s,o,l),o!==null){var d=Ft();In(o,r,l,d),sp(o,s,l)}}function kx(r,s,o){var l=Yr(r),d={lane:l,action:o,hasEagerState:!1,eagerState:null,next:null};if(np(r))rp(s,d);else{var p=r.alternate;if(r.lanes===0&&(p===null||p.lanes===0)&&(p=s.lastRenderedReducer,p!==null))try{var y=s.lastRenderedState,S=p(y,o);if(d.hasEagerState=!0,d.eagerState=S,Sn(S,y)){var N=s.interleaved;N===null?(d.next=d,sc(s)):(d.next=N.next,N.next=d),s.interleaved=d;return}}catch{}finally{}o=Th(r,s,d,l),o!==null&&(d=Ft(),In(o,r,l,d),sp(o,s,l))}}function np(r){var s=r.alternate;return r===ot||s!==null&&s===ot}function rp(r,s){co=Ca=!0;var o=r.pending;o===null?s.next=s:(s.next=o.next,o.next=s),r.pending=s}function sp(r,s,o){if((o&4194240)!==0){var l=s.lanes;l&=r.pendingLanes,o|=l,s.lanes=o,xu(r,o)}}var Ta={readContext:sn,useCallback:kt,useContext:kt,useEffect:kt,useImperativeHandle:kt,useInsertionEffect:kt,useLayoutEffect:kt,useMemo:kt,useReducer:kt,useRef:kt,useState:kt,useDebugValue:kt,useDeferredValue:kt,useTransition:kt,useMutableSource:kt,useSyncExternalStore:kt,useId:kt,unstable_isNewReconciler:!1},Ix={readContext:sn,useCallback:function(r,s){return Vn().memoizedState=[r,s===void 0?null:s],r},useContext:sn,useEffect:Yh,useImperativeHandle:function(r,s,o){return o=o!=null?o.concat([r]):null,Fa(4194308,4,Jh.bind(null,s,r),o)},useLayoutEffect:function(r,s){return Fa(4194308,4,r,s)},useInsertionEffect:function(r,s){return Fa(4,2,r,s)},useMemo:function(r,s){var o=Vn();return s=s===void 0?null:s,r=r(),o.memoizedState=[r,s],r},useReducer:function(r,s,o){var l=Vn();return s=o!==void 0?o(s):s,l.memoizedState=l.baseState=s,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:s},l.queue=r,r=r.dispatch=jx.bind(null,ot,r),[l.memoizedState,r]},useRef:function(r){var s=Vn();return r={current:r},s.memoizedState=r},useState:Hh,useDebugValue:gc,useDeferredValue:function(r){return Vn().memoizedState=r},useTransition:function(){var r=Hh(!1),s=r[0];return r=Nx.bind(null,r[1]),Vn().memoizedState=r,[s,r]},useMutableSource:function(){},useSyncExternalStore:function(r,s,o){var l=ot,d=Vn();if(st){if(o===void 0)throw Error(t(407));o=o()}else{if(o=s(),xt===null)throw Error(t(349));(xs&30)!==0||$h(l,s,o)}d.memoizedState=o;var p={value:o,getSnapshot:s};return d.queue=p,Yh(zh.bind(null,l,p,r),[r]),l.flags|=2048,po(9,Ph.bind(null,l,p,o,s),void 0,null),o},useId:function(){var r=Vn(),s=xt.identifierPrefix;if(st){var o=ur,l=lr;o=(l&~(1<<32-wn(l)-1)).toString(32)+o,s=":"+s+"R"+o,o=fo++,0<\/script>",r=r.removeChild(r.firstChild)):typeof l.is=="string"?r=y.createElement(o,{is:l.is}):(r=y.createElement(o),o==="select"&&(y=r,l.multiple?y.multiple=!0:l.size&&(y.size=l.size))):r=y.createElementNS(r,o),r[Pn]=s,r[so]=l,Np(r,s,!1,!1),s.stateNode=r;e:{switch(y=uu(o,l),o){case"dialog":Xe("cancel",r),Xe("close",r),d=l;break;case"iframe":case"object":case"embed":Xe("load",r),d=l;break;case"video":case"audio":for(d=0;dii&&(s.flags|=128,l=!0,mo(p,!1),s.lanes=4194304)}else{if(!l)if(r=Ma(y),r!==null){if(s.flags|=128,l=!0,o=r.updateQueue,o!==null&&(s.updateQueue=o,s.flags|=4),mo(p,!0),p.tail===null&&p.tailMode==="hidden"&&!y.alternate&&!st)return It(s),null}else 2*ct()-p.renderingStartTime>ii&&o!==1073741824&&(s.flags|=128,l=!0,mo(p,!1),s.lanes=4194304);p.isBackwards?(y.sibling=s.child,s.child=y):(o=p.last,o!==null?o.sibling=y:s.child=y,p.last=y)}return p.tail!==null?(s=p.tail,p.rendering=s,p.tail=s.sibling,p.renderingStartTime=ct(),s.sibling=null,o=it.current,qe(it,l?o&1|2:o&1),s):(It(s),null);case 22:case 23:return Pc(),l=s.memoizedState!==null,r!==null&&r.memoizedState!==null!==l&&(s.flags|=8192),l&&(s.mode&1)!==0?(Jt&1073741824)!==0&&(It(s),s.subtreeFlags&6&&(s.flags|=8192)):It(s),null;case 24:return null;case 25:return null}throw Error(t(156,s.tag))}function Ox(r,s){switch(Ju(s),s.tag){case 1:return Et(s.type)&&ga(),r=s.flags,r&65536?(s.flags=r&-65537|128,s):null;case 3:return ti(),et(Bt),et(jt),uc(),r=s.flags,(r&65536)!==0&&(r&128)===0?(s.flags=r&-65537|128,s):null;case 5:return ac(s),null;case 13:if(et(it),r=s.memoizedState,r!==null&&r.dehydrated!==null){if(s.alternate===null)throw Error(t(340));qs()}return r=s.flags,r&65536?(s.flags=r&-65537|128,s):null;case 19:return et(it),null;case 4:return ti(),null;case 10:return nc(s.type._context),null;case 22:case 23:return Pc(),null;case 24:return null;default:return null}}var Ra=!1,Mt=!1,Tx=typeof WeakSet=="function"?WeakSet:Set,le=null;function ri(r,s){var o=r.ref;if(o!==null)if(typeof o=="function")try{o(null)}catch(l){ut(r,s,l)}else o.current=null}function Dc(r,s,o){try{o()}catch(l){ut(r,s,l)}}var Ip=!1;function Ax(r,s){if(Pu=ra,r=ih(),Tu(r)){if("selectionStart"in r)var o={start:r.selectionStart,end:r.selectionEnd};else e:{o=(o=r.ownerDocument)&&o.defaultView||window;var l=o.getSelection&&o.getSelection();if(l&&l.rangeCount!==0){o=l.anchorNode;var d=l.anchorOffset,p=l.focusNode;l=l.focusOffset;try{o.nodeType,p.nodeType}catch{o=null;break e}var y=0,S=-1,N=-1,P=0,J=0,q=r,K=null;t:for(;;){for(var oe;q!==o||d!==0&&q.nodeType!==3||(S=y+d),q!==p||l!==0&&q.nodeType!==3||(N=y+l),q.nodeType===3&&(y+=q.nodeValue.length),(oe=q.firstChild)!==null;)K=q,q=oe;for(;;){if(q===r)break t;if(K===o&&++P===d&&(S=y),K===p&&++J===l&&(N=y),(oe=q.nextSibling)!==null)break;q=K,K=q.parentNode}q=oe}o=S===-1||N===-1?null:{start:S,end:N}}else o=null}o=o||{start:0,end:0}}else o=null;for(zu={focusedElem:r,selectionRange:o},ra=!1,le=s;le!==null;)if(s=le,r=s.child,(s.subtreeFlags&1028)!==0&&r!==null)r.return=s,le=r;else for(;le!==null;){s=le;try{var ce=s.alternate;if((s.flags&1024)!==0)switch(s.tag){case 0:case 11:case 15:break;case 1:if(ce!==null){var de=ce.memoizedProps,dt=ce.memoizedState,B=s.stateNode,k=B.getSnapshotBeforeUpdate(s.elementType===s.type?de:Nn(s.type,de),dt);B.__reactInternalSnapshotBeforeUpdate=k}break;case 3:var $=s.stateNode.containerInfo;$.nodeType===1?$.textContent="":$.nodeType===9&&$.documentElement&&$.removeChild($.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(t(163))}}catch(Z){ut(s,s.return,Z)}if(r=s.sibling,r!==null){r.return=s.return,le=r;break}le=s.return}return ce=Ip,Ip=!1,ce}function yo(r,s,o){var l=s.updateQueue;if(l=l!==null?l.lastEffect:null,l!==null){var d=l=l.next;do{if((d.tag&r)===r){var p=d.destroy;d.destroy=void 0,p!==void 0&&Dc(s,o,p)}d=d.next}while(d!==l)}}function La(r,s){if(s=s.updateQueue,s=s!==null?s.lastEffect:null,s!==null){var o=s=s.next;do{if((o.tag&r)===r){var l=o.create;o.destroy=l()}o=o.next}while(o!==s)}}function Cc(r){var s=r.ref;if(s!==null){var o=r.stateNode;switch(r.tag){case 5:r=o;break;default:r=o}typeof s=="function"?s(r):s.current=r}}function Mp(r){var s=r.alternate;s!==null&&(r.alternate=null,Mp(s)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(s=r.stateNode,s!==null&&(delete s[Pn],delete s[so],delete s[Gu],delete s[yx],delete s[gx])),r.stateNode=null,r.return=null,r.dependencies=null,r.memoizedProps=null,r.memoizedState=null,r.pendingProps=null,r.stateNode=null,r.updateQueue=null}function Dp(r){return r.tag===5||r.tag===3||r.tag===4}function Cp(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||Dp(r.return))return null;r=r.return}for(r.sibling.return=r.return,r=r.sibling;r.tag!==5&&r.tag!==6&&r.tag!==18;){if(r.flags&2||r.child===null||r.tag===4)continue e;r.child.return=r,r=r.child}if(!(r.flags&2))return r.stateNode}}function Fc(r,s,o){var l=r.tag;if(l===5||l===6)r=r.stateNode,s?o.nodeType===8?o.parentNode.insertBefore(r,s):o.insertBefore(r,s):(o.nodeType===8?(s=o.parentNode,s.insertBefore(r,o)):(s=o,s.appendChild(r)),o=o._reactRootContainer,o!=null||s.onclick!==null||(s.onclick=ma));else if(l!==4&&(r=r.child,r!==null))for(Fc(r,s,o),r=r.sibling;r!==null;)Fc(r,s,o),r=r.sibling}function Oc(r,s,o){var l=r.tag;if(l===5||l===6)r=r.stateNode,s?o.insertBefore(r,s):o.appendChild(r);else if(l!==4&&(r=r.child,r!==null))for(Oc(r,s,o),r=r.sibling;r!==null;)Oc(r,s,o),r=r.sibling}var St=null,jn=!1;function Wr(r,s,o){for(o=o.child;o!==null;)Fp(r,s,o),o=o.sibling}function Fp(r,s,o){if($n&&typeof $n.onCommitFiberUnmount=="function")try{$n.onCommitFiberUnmount(qo,o)}catch{}switch(o.tag){case 5:Mt||ri(o,s);case 6:var l=St,d=jn;St=null,Wr(r,s,o),St=l,jn=d,St!==null&&(jn?(r=St,o=o.stateNode,r.nodeType===8?r.parentNode.removeChild(o):r.removeChild(o)):St.removeChild(o.stateNode));break;case 18:St!==null&&(jn?(r=St,o=o.stateNode,r.nodeType===8?Hu(r.parentNode,o):r.nodeType===1&&Hu(r,o),Yi(r)):Hu(St,o.stateNode));break;case 4:l=St,d=jn,St=o.stateNode.containerInfo,jn=!0,Wr(r,s,o),St=l,jn=d;break;case 0:case 11:case 14:case 15:if(!Mt&&(l=o.updateQueue,l!==null&&(l=l.lastEffect,l!==null))){d=l=l.next;do{var p=d,y=p.destroy;p=p.tag,y!==void 0&&((p&2)!==0||(p&4)!==0)&&Dc(o,s,y),d=d.next}while(d!==l)}Wr(r,s,o);break;case 1:if(!Mt&&(ri(o,s),l=o.stateNode,typeof l.componentWillUnmount=="function"))try{l.props=o.memoizedProps,l.state=o.memoizedState,l.componentWillUnmount()}catch(S){ut(o,s,S)}Wr(r,s,o);break;case 21:Wr(r,s,o);break;case 22:o.mode&1?(Mt=(l=Mt)||o.memoizedState!==null,Wr(r,s,o),Mt=l):Wr(r,s,o);break;default:Wr(r,s,o)}}function Op(r){var s=r.updateQueue;if(s!==null){r.updateQueue=null;var o=r.stateNode;o===null&&(o=r.stateNode=new Tx),s.forEach(function(l){var d=Vx.bind(null,r,l);o.has(l)||(o.add(l),l.then(d,d))})}}function kn(r,s){var o=s.deletions;if(o!==null)for(var l=0;ld&&(d=y),l&=~p}if(l=d,l=ct()-l,l=(120>l?120:480>l?480:1080>l?1080:1920>l?1920:3e3>l?3e3:4320>l?4320:1960*Ex(l/1960))-l,10r?16:r,Gr===null)var l=!1;else{if(r=Gr,Gr=null,Va=0,(Pe&6)!==0)throw Error(t(331));var d=Pe;for(Pe|=4,le=r.current;le!==null;){var p=le,y=p.child;if((le.flags&16)!==0){var S=p.deletions;if(S!==null){for(var N=0;Nct()-Bc?Ss(r,0):Ac|=o),Ut(r,s)}function Hp(r,s){s===0&&((r.mode&1)===0?s=1:(s=Xo,Xo<<=1,(Xo&130023424)===0&&(Xo=4194304)));var o=Ft();r=cr(r,s),r!==null&&(zi(r,s,o),Ut(r,o))}function zx(r){var s=r.memoizedState,o=0;s!==null&&(o=s.retryLane),Hp(r,o)}function Vx(r,s){var o=0;switch(r.tag){case 13:var l=r.stateNode,d=r.memoizedState;d!==null&&(o=d.retryLane);break;case 19:l=r.stateNode;break;default:throw Error(t(314))}l!==null&&l.delete(s),Hp(r,o)}var Gp;Gp=function(r,s,o){if(r!==null)if(r.memoizedProps!==s.pendingProps||Bt.current)Rt=!0;else{if((r.lanes&o)===0&&(s.flags&128)===0)return Rt=!1,Cx(r,s,o);Rt=(r.flags&131072)!==0}else Rt=!1,st&&(s.flags&1048576)!==0&&jh(s,wa,s.index);switch(s.lanes=0,s.tag){case 2:var l=s.type;Ea(r,s),r=s.pendingProps;var d=Qs(s,jt.current);ei(s,o),d=fc(null,s,l,r,d,o);var p=hc();return s.flags|=1,typeof d=="object"&&d!==null&&typeof d.render=="function"&&d.$$typeof===void 0?(s.tag=1,s.memoizedState=null,s.updateQueue=null,Et(l)?(p=!0,va(s)):p=!1,s.memoizedState=d.state!==null&&d.state!==void 0?d.state:null,ic(s),d.updater=Aa,s.stateNode=d,d._reactInternals=s,xc(s,l,r,o),s=_c(null,s,l,!0,p,o)):(s.tag=0,st&&p&&Ku(s),Ct(null,s,d,o),s=s.child),s;case 16:l=s.elementType;e:{switch(Ea(r,s),r=s.pendingProps,d=l._init,l=d(l._payload),s.type=l,d=s.tag=Hx(l),r=Nn(l,r),d){case 0:s=Sc(null,s,l,r,o);break e;case 1:s=vp(null,s,l,r,o);break e;case 11:s=hp(null,s,l,r,o);break e;case 14:s=pp(null,s,l,Nn(l.type,r),o);break e}throw Error(t(306,l,""))}return s;case 0:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),Sc(r,s,l,d,o);case 1:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),vp(r,s,l,d,o);case 3:e:{if(xp(s),r===null)throw Error(t(387));l=s.pendingProps,p=s.memoizedState,d=p.element,Ah(r,s),Ia(s,l,null,o);var y=s.memoizedState;if(l=y.element,p.isDehydrated)if(p={element:l,isDehydrated:!1,cache:y.cache,pendingSuspenseBoundaries:y.pendingSuspenseBoundaries,transitions:y.transitions},s.updateQueue.baseState=p,s.memoizedState=p,s.flags&256){d=ni(Error(t(423)),s),s=bp(r,s,l,o,d);break e}else if(l!==d){d=ni(Error(t(424)),s),s=bp(r,s,l,o,d);break e}else for(Kt=Lr(s.stateNode.containerInfo.firstChild),Qt=s,st=!0,_n=null,o=Oh(s,null,l,o),s.child=o;o;)o.flags=o.flags&-3|4096,o=o.sibling;else{if(qs(),l===d){s=fr(r,s,o);break e}Ct(r,s,l,o)}s=s.child}return s;case 5:return Rh(s),r===null&&Zu(s),l=s.type,d=s.pendingProps,p=r!==null?r.memoizedProps:null,y=d.children,Vu(l,d)?y=null:p!==null&&Vu(l,p)&&(s.flags|=32),gp(r,s),Ct(r,s,y,o),s.child;case 6:return r===null&&Zu(s),null;case 13:return wp(r,s,o);case 4:return oc(s,s.stateNode.containerInfo),l=s.pendingProps,r===null?s.child=Zs(s,null,l,o):Ct(r,s,l,o),s.child;case 11:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),hp(r,s,l,d,o);case 7:return Ct(r,s,s.pendingProps,o),s.child;case 8:return Ct(r,s,s.pendingProps.children,o),s.child;case 12:return Ct(r,s,s.pendingProps.children,o),s.child;case 10:e:{if(l=s.type._context,d=s.pendingProps,p=s.memoizedProps,y=d.value,qe(Na,l._currentValue),l._currentValue=y,p!==null)if(Sn(p.value,y)){if(p.children===d.children&&!Bt.current){s=fr(r,s,o);break e}}else for(p=s.child,p!==null&&(p.return=s);p!==null;){var S=p.dependencies;if(S!==null){y=p.child;for(var N=S.firstContext;N!==null;){if(N.context===l){if(p.tag===1){N=dr(-1,o&-o),N.tag=2;var P=p.updateQueue;if(P!==null){P=P.shared;var J=P.pending;J===null?N.next=N:(N.next=J.next,J.next=N),P.pending=N}}p.lanes|=o,N=p.alternate,N!==null&&(N.lanes|=o),rc(p.return,o,s),S.lanes|=o;break}N=N.next}}else if(p.tag===10)y=p.type===s.type?null:p.child;else if(p.tag===18){if(y=p.return,y===null)throw Error(t(341));y.lanes|=o,S=y.alternate,S!==null&&(S.lanes|=o),rc(y,o,s),y=p.sibling}else y=p.child;if(y!==null)y.return=p;else for(y=p;y!==null;){if(y===s){y=null;break}if(p=y.sibling,p!==null){p.return=y.return,y=p;break}y=y.return}p=y}Ct(r,s,d.children,o),s=s.child}return s;case 9:return d=s.type,l=s.pendingProps.children,ei(s,o),d=sn(d),l=l(d),s.flags|=1,Ct(r,s,l,o),s.child;case 14:return l=s.type,d=Nn(l,s.pendingProps),d=Nn(l.type,d),pp(r,s,l,d,o);case 15:return mp(r,s,s.type,s.pendingProps,o);case 17:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),Ea(r,s),s.tag=1,Et(l)?(r=!0,va(s)):r=!1,ei(s,o),op(s,l,d),xc(s,l,d,o),_c(null,s,l,!0,r,o);case 19:return _p(r,s,o);case 22:return yp(r,s,o)}throw Error(t(156,s.tag))};function Yp(r,s){return kf(r,s)}function Wx(r,s,o,l){this.tag=r,this.key=o,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=s,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=l,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ln(r,s,o,l){return new Wx(r,s,o,l)}function Vc(r){return r=r.prototype,!(!r||!r.isReactComponent)}function Hx(r){if(typeof r=="function")return Vc(r)?1:0;if(r!=null){if(r=r.$$typeof,r===ee)return 11;if(r===ae)return 14}return 2}function Kr(r,s){var o=r.alternate;return o===null?(o=ln(r.tag,s,r.key,r.mode),o.elementType=r.elementType,o.type=r.type,o.stateNode=r.stateNode,o.alternate=r,r.alternate=o):(o.pendingProps=s,o.type=r.type,o.flags=0,o.subtreeFlags=0,o.deletions=null),o.flags=r.flags&14680064,o.childLanes=r.childLanes,o.lanes=r.lanes,o.child=r.child,o.memoizedProps=r.memoizedProps,o.memoizedState=r.memoizedState,o.updateQueue=r.updateQueue,s=r.dependencies,o.dependencies=s===null?null:{lanes:s.lanes,firstContext:s.firstContext},o.sibling=r.sibling,o.index=r.index,o.ref=r.ref,o}function Ya(r,s,o,l,d,p){var y=2;if(l=r,typeof r=="function")Vc(r)&&(y=1);else if(typeof r=="string")y=5;else e:switch(r){case U:return Ns(o.children,d,p,s);case G:y=8,d|=8;break;case V:return r=ln(12,o,s,d|2),r.elementType=V,r.lanes=p,r;case X:return r=ln(13,o,s,d),r.elementType=X,r.lanes=p,r;case ie:return r=ln(19,o,s,d),r.elementType=ie,r.lanes=p,r;case se:return Qa(o,d,p,s);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case Q:y=10;break e;case z:y=9;break e;case ee:y=11;break e;case ae:y=14;break e;case re:y=16,l=null;break e}throw Error(t(130,r==null?r:typeof r,""))}return s=ln(y,o,s,d),s.elementType=r,s.type=l,s.lanes=p,s}function Ns(r,s,o,l){return r=ln(7,r,l,s),r.lanes=o,r}function Qa(r,s,o,l){return r=ln(22,r,l,s),r.elementType=se,r.lanes=o,r.stateNode={isHidden:!1},r}function Wc(r,s,o){return r=ln(6,r,null,s),r.lanes=o,r}function Hc(r,s,o){return s=ln(4,r.children!==null?r.children:[],r.key,s),s.lanes=o,s.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},s}function Gx(r,s,o,l,d){this.tag=s,this.containerInfo=r,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=vu(0),this.expirationTimes=vu(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=vu(0),this.identifierPrefix=l,this.onRecoverableError=d,this.mutableSourceEagerHydrationData=null}function Gc(r,s,o,l,d,p,y,S,N){return r=new Gx(r,s,o,S,N),s===1?(s=1,p===!0&&(s|=8)):s=0,p=ln(3,null,null,s),r.current=p,p.stateNode=r,p.memoizedState={element:l,isDehydrated:o,cache:null,transitions:null,pendingSuspenseBoundaries:null},ic(p),r}function Yx(r,s,o){var l=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),Zc.exports=ob(),Zc.exports}var am;function lb(){if(am)return tl;am=1;var n=ab();return tl.createRoot=n.createRoot,tl.hydrateRoot=n.hydrateRoot,tl}var ub=lb();function Sr(n){return n.split(".").at(-1)||n}function Fn(n,e){const t=Sr(n);if(e.filter(a=>Sr(a)===t).length<2)return t;const i=n.indexOf(".");return i>0?`${n.slice(0,i)}_${t}`:t}const er="\0__null__";function cb(n){return String(n||"").replaceAll("_"," ").replaceAll("."," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}function py(n,e={}){if(n==null||n==="")return"—";const t=typeof n=="number"?n:Number(n);if(!Number.isFinite(t))return String(n);const i=String(e.format||"").toLowerCase();if(e.style==="percent"||i.includes("%")||i.includes("percent")||i.includes("pct")||e.type==="ratio")return(e.style==="percent"?t:Math.abs(t)<=1?t*100:t).toLocaleString(void 0,{maximumFractionDigits:e.maximumFractionDigits??1,style:e.style==="percent"?"percent":"decimal"})+(e.style==="percent"?"":"%");const u=e.style==="currency"||e.currency||i.includes("$")||i.includes("usd")||i.includes("currency")||i.includes("dollar");return t.toLocaleString(void 0,{currency:u?e.currency||"USD":void 0,maximumFractionDigits:e.maximumFractionDigits??2,notation:e.compact?"compact":"standard",style:u?"currency":"decimal"})}function db(n,e={}){return py(n,{...e,compact:!0,maximumFractionDigits:e.maximumFractionDigits??1})}function fb(n,e,t){const i=t>0&&n.length>t,a=i?Math.ceil(n.length/t):1,u=Math.max(0,Math.min(e,a-1)),f=i?u*t:0;return{paginate:i,pageCount:a,safePage:u,start:f,visibleRows:i?n.slice(f,f+t):n}}function rs(n){return n===er||n===""?"—":n}function Le(n){return cb(n)}function pt(n,e={}){return py(n,e)}function Wt(n,e={}){return db(n,e)}function my(n){return!Number.isFinite(n)||n===0?"neutral":n>0?"positive":"negative"}function hb(n,e){return!Number.isFinite(n)||!Number.isFinite(e)||e<=0?{label:"—",tone:"neutral"}:{label:`${(n/e*100).toLocaleString(void 0,{maximumFractionDigits:1})}%`,tone:"neutral"}}function pb(n,e,t={}){if(e==null||!Number.isFinite(e)||!Number.isFinite(n))return{label:"—",tone:"neutral"};const i=n-e;return{label:`${i>0?"+":i<0?"−":""}${Wt(Math.abs(i),t)}`,tone:my(i)}}function mb(n,e){if(e==null||!Number.isFinite(e)||e===0||!Number.isFinite(n))return{label:"—",tone:"neutral"};const t=(n-e)/Math.abs(e);return{label:`${(t*100).toLocaleString(void 0,{maximumFractionDigits:1,signDisplay:"exceptZero"})}%`,tone:my(t)}}function yy(n,e){if(e==null||!Number.isFinite(e)||e===0||!Number.isFinite(n))return null;const t=(n-e)/Math.abs(e),i=(t*100).toLocaleString(void 0,{maximumFractionDigits:1,signDisplay:"exceptZero"}),a=t>0?"positive":t<0?"negative":"neutral";return{label:`${i}%`,tone:a}}function Tn(n){return`'${n.replaceAll("'","''")}'`}function yb(n){if(n.mode==="contains")return`contains ${Tn(n.pattern??"")}`;const{values:e}=n,t=n.mode==="exclude"?"is not":"is";return e.length===0?t:e.length===1?`${t} ${rs(e[0])}`:e.length<=2?`${t} ${e.map(rs).join(", ")}`:`${t} ${e.length} values`}const td=n=>n.public!==!1,gy=/(^|_)(date|time|day|month|week|year|quarter|created|updated|timestamp|_at|_on)($|_)/i;function vy(n,e){if(e){const t=n.find(i=>i.name===e);if(t)return t}return n.find(t=>t.type==="time")??n.find(t=>gy.test(t.name))}function gb(n,e){var f;const t=new Set;if(!n)return t;const i=new Set(e.map(h=>h.name)),a=n.match(/[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*/g)??[];for(const h of a){const[m]=h.split(".");i.has(m)&&t.add(m)}if(t.size)return t;const u=(f=n.match(/^[A-Za-z_][A-Za-z0-9_]*$/))==null?void 0:f[0];if(!u)return t;for(const h of e)h.metrics.some(m=>m.name===u)&&t.add(h.name);return t}function xy(n,e){const t=new Set;for(const i of[n.base_metric,n.numerator,n.denominator,n.sql])for(const a of gb(i,e))t.add(a);return t.size===1?[...t][0]:void 0}function vb(n){const e=(n.models??[]).map(i=>{const a=(i.dimensions??[]).filter(td).map(h=>({ref:`${i.name}.${h.name}`,name:h.name,model:i.name,label:h.label||Le(h.name),description:h.description,type:h.type||"categorical",granularity:h.granularity,supportedGranularities:h.supported_granularities,format:h.format})),u=(i.metrics??[]).filter(td).map(h=>({ref:`${i.name}.${h.name}`,name:h.name,model:i.name,label:h.label||Le(h.name),description:h.description,agg:h.agg,type:h.type,format:h.format})),f=vy(a,i.default_time_dimension);return{name:i.name,label:Le(i.name),description:i.description,table:i.table,dimensions:a,metrics:u,timeDimension:f,defaultGrain:i.default_grain||(f==null?void 0:f.granularity)||"day"}}),t=(n.metrics??[]).filter(td).map(i=>({ref:i.name,name:i.name,ownerModel:xy(i,e),baseMetric:i.base_metric,label:i.label||Le(i.name),description:i.description,type:i.type,format:i.format}));return{models:e,graphMetrics:t,dialect:n.dialect}}function xb(n){const e=n??{},t=(e.models??[]).map(a=>{const u=(a.dimensions??[]).map(m=>({ref:`${a.name}.${m}`,name:m,model:a.name,label:Le(m),type:gy.test(m)?"time":"categorical"})),f=(a.metrics??[]).map(m=>({ref:`${a.name}.${m}`,name:m,model:a.name,label:Le(m)})),h=vy(u);return{name:a.name,label:Le(a.name),table:a.table,dimensions:u,metrics:f,timeDimension:h,defaultGrain:(h==null?void 0:h.granularity)||"day"}}),i=(e.graph_metrics??[]).map(a=>({ref:a.name,name:a.name,ownerModel:xy(a,t),baseMetric:a.base_metric,label:Le(a.name),type:a.type,description:a.description}));return{models:t,graphMetrics:i,joinablePairs:e.joinable_pairs??[]}}function bb(n,e){return{...n,joinablePairs:(e??{}).joinable_pairs??n.joinablePairs??[]}}function ji(n,e){const t=new Set;for(const i of n.joinablePairs??[])i.from===e&&t.add(i.to),i.to===e&&t.add(i.from);return n.graphMetrics.filter(i=>i.ownerModel?i.ownerModel===e||t.has(i.ownerModel):!0)}function Fe(n,e,t,i){function a(u){return u instanceof t?u:new t(function(f){f(u)})}return new(t||(t=Promise))(function(u,f){function h(v){try{g(i.next(v))}catch(x){f(x)}}function m(v){try{g(i.throw(v))}catch(x){f(x)}}function g(v){v.done?u(v.value):a(v.value).then(h,m)}g((i=i.apply(n,e||[])).next())})}function lm(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ae(n){return this instanceof Ae?(this.v=n,this):new Ae(n)}function qn(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),a,u=[];return a=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),h("next"),h("throw"),h("return",f),a[Symbol.asyncIterator]=function(){return this},a;function f(w){return function(j){return Promise.resolve(j).then(w,x)}}function h(w,j){i[w]&&(a[w]=function(C){return new Promise(function(O,H){u.push([w,C,O,H])>1||m(w,C)})},j&&(a[w]=j(a[w])))}function m(w,j){try{g(i[w](j))}catch(C){b(u[0][3],C)}}function g(w){w.value instanceof Ae?Promise.resolve(w.value.v).then(v,x):b(u[0][2],w)}function v(w){m("next",w)}function x(w){m("throw",w)}function b(w,j){w(j),u.shift(),u.length&&m(u[0][0],u[0][1])}}function fl(n){var e,t;return e={},i("next"),i("throw",function(a){throw a}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(a,u){e[a]=n[a]?function(f){return(t=!t)?{value:Ae(n[a](f)),done:!1}:u?u(f):f}:u}}function xi(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof lm=="function"?lm(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(u){t[u]=n[u]&&function(f){return new Promise(function(h,m){f=n[u](f),a(h,m,f.done,f.value)})}}function a(u,f,h,m){Promise.resolve(m).then(function(g){u({value:g,done:h})},f)}}const wb=new TextDecoder("utf-8"),xd=n=>wb.decode(n),Sb=new TextEncoder,Bd=n=>Sb.encode(n),_b=n=>typeof n=="number",Nb=n=>typeof n=="boolean",Ot=n=>typeof n=="function",En=n=>n!=null&&Object(n)===n,Ao=n=>En(n)&&Ot(n.then),nu=n=>En(n)&&Ot(n[Symbol.iterator]),Ed=n=>En(n)&&Ot(n[Symbol.asyncIterator]),bd=n=>En(n)&&En(n.schema),by=n=>En(n)&&"done"in n&&"value"in n,wy=n=>En(n)&&Ot(n.stat)&&_b(n.fd),Sy=n=>En(n)&&Rd(n.body),_y=n=>"_getDOMStream"in n&&"_getNodeStream"in n,Rd=n=>En(n)&&Ot(n.cancel)&&Ot(n.getReader)&&!_y(n),Ny=n=>En(n)&&Ot(n.read)&&Ot(n.pipe)&&Nb(n.readable)&&!_y(n),jb=n=>En(n)&&Ot(n.clear)&&Ot(n.bytes)&&Ot(n.position)&&Ot(n.setPosition)&&Ot(n.capacity)&&Ot(n.getBufferIdentifier)&&Ot(n.createLong),Ld=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function kb(n){const e=n[0]?[n[0]]:[];let t,i,a,u;for(let f,h,m=0,g=0,v=n.length;++mv+x.byteLength,0);let a,u,f,h=0,m=-1;const g=Math.min(e||Number.POSITIVE_INFINITY,i);for(const v=t.length;++mKe(Int32Array,n),cm=n=>Ke(BigInt64Array,n),$e=n=>Ke(Uint8Array,n),wd=n=>(n.next(),n);function*Ib(n,e){const t=function*(a){yield a},i=typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof Ld?t(e):nu(e)?e:t(e);return yield*wd((function*(a){let u=null;do u=a.next(yield Ke(n,u));while(!u.done)})(i[Symbol.iterator]())),new n}const Mb=n=>Ib(Uint8Array,n);function jy(n,e){return qn(this,arguments,function*(){if(Ao(e))return yield Ae(yield Ae(yield*fl(xi(jy(n,yield Ae(e))))));const i=function(f){return qn(this,arguments,function*(){yield yield Ae(yield Ae(f))})},a=function(f){return qn(this,arguments,function*(){yield Ae(yield*fl(xi(wd((function*(h){let m=null;do m=h.next(yield m==null?void 0:m.value);while(!m.done)})(f[Symbol.iterator]())))))})},u=typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof Ld?i(e):nu(e)?a(e):Ed(e)?e:i(e);return yield Ae(yield*fl(xi(wd((function(f){return qn(this,arguments,function*(){let h=null;do h=yield Ae(f.next(yield yield Ae(Ke(n,h))));while(!h.done)})})(u[Symbol.asyncIterator]()))))),yield Ae(new n)})}const Db=n=>jy(Uint8Array,n);function Cb(n,e){let t=0;const i=n.length;if(i!==e.length)return!1;if(i>0)do if(n[t]!==e[t])return!1;while(++t(n.next(),n);function*Fb(n){let e,t=!1,i=[],a,u,f,h=0;function m(){return u==="peek"?tr(i,f)[0]:([a,i,h]=tr(i,f),a)}({cmd:u,size:f}=(yield null)||{cmd:"read",size:0});const g=Mb(n)[Symbol.iterator]();try{do if({done:e,value:a}=Number.isNaN(f-h)?g.next():g.next(f-h),!e&&a.byteLength>0&&(i.push(a),h+=a.byteLength),e||f<=h)do({cmd:u,size:f}=yield m());while(f0&&(a.push(u),m+=u.byteLength),t||h<=m)do({cmd:f,size:h}=yield yield Ae(g()));while(h0&&(a.push($e(u)),m+=u.byteLength),t||h<=m)do({cmd:f,size:h}=yield yield Ae(g()));while(h{})}get closed(){return this.reader?this.reader.closed.catch(()=>{}):Promise.resolve()}releaseLock(){this.reader&&this.reader.releaseLock(),this.reader=null}cancel(e){return Fe(this,void 0,void 0,function*(){const{reader:t,source:i}=this;t&&(yield t.cancel(e).catch(()=>{})),i&&i.locked&&this.releaseLock()})}read(e){return Fe(this,void 0,void 0,function*(){if(e===0)return{done:this.reader==null,value:new Uint8Array(0)};const t=yield this.reader.read();return!t.done&&(t.value=$e(t)),t})}}const nd=(n,e)=>{const t=a=>i([e,a]);let i;return[e,t,new Promise(a=>(i=a)&&n.once(e,t))]};function Bb(n){return qn(this,arguments,function*(){const t=[];let i="error",a=!1,u=null,f,h,m=0,g=[],v;function x(){return f==="peek"?tr(g,h)[0]:([v,g,m]=tr(g,h),v)}if({cmd:f,size:h}=(yield yield Ae(null))||{cmd:"read",size:0},n.isTTY)return yield yield Ae(new Uint8Array(0)),yield Ae(null);try{t[0]=nd(n,"end"),t[1]=nd(n,"error");do{if(t[2]=nd(n,"readable"),[i,u]=yield Ae(Promise.race(t.map(w=>w[2]))),i==="error")break;if((a=i==="end")||(Number.isFinite(h-m)?(v=$e(n.read(h-m)),v.byteLength0&&(g.push(v),m+=v.byteLength)),a||h<=m)do({cmd:f,size:h}=yield yield Ae(x()));while(h{for(const[H,L]of w)n.off(H,L);try{const H=n.destroy;H&&H.call(n,j),j=void 0}catch(H){j=H||j}finally{j!=null?O(j):C()}})}})}var ht;(function(n){n[n.V1=0]="V1",n[n.V2=1]="V2",n[n.V3=2]="V3",n[n.V4=3]="V4",n[n.V5=4]="V5"})(ht||(ht={}));var Ht;(function(n){n[n.Sparse=0]="Sparse",n[n.Dense=1]="Dense"})(Ht||(Ht={}));var Dt;(function(n){n[n.HALF=0]="HALF",n[n.SINGLE=1]="SINGLE",n[n.DOUBLE=2]="DOUBLE"})(Dt||(Dt={}));var gn;(function(n){n[n.DAY=0]="DAY",n[n.MILLISECOND=1]="MILLISECOND"})(gn||(gn={}));var _e;(function(n){n[n.SECOND=0]="SECOND",n[n.MILLISECOND=1]="MILLISECOND",n[n.MICROSECOND=2]="MICROSECOND",n[n.NANOSECOND=3]="NANOSECOND"})(_e||(_e={}));var nr;(function(n){n[n.YEAR_MONTH=0]="YEAR_MONTH",n[n.DAY_TIME=1]="DAY_TIME",n[n.MONTH_DAY_NANO=2]="MONTH_DAY_NANO"})(nr||(nr={}));const rd=2,Qn=4,br=4,He=4,es=new Int32Array(2),dm=new Float32Array(es.buffer),fm=new Float64Array(es.buffer),rl=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Sd;(function(n){n[n.UTF8_BYTES=1]="UTF8_BYTES",n[n.UTF16_STRING=2]="UTF16_STRING"})(Sd||(Sd={}));let ki=class ky{constructor(e){this.bytes_=e,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(e){return new ky(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return BigInt.asIntN(64,BigInt(this.readUint32(e))+(BigInt(this.readUint32(e+4))<>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,Number(BigInt.asIntN(32,t))),this.writeInt32(e+4,Number(BigInt.asIntN(32,t>>BigInt(32))))}writeUint64(e,t){this.writeUint32(e,Number(BigInt.asUintN(32,t))),this.writeUint32(e+4,Number(BigInt.asUintN(32,t>>BigInt(32))))}writeFloat32(e,t){dm[0]=t,this.writeInt32(e,es[0])}writeFloat64(e,t){fm[0]=t,this.writeInt32(e,es[rl?0:1]),this.writeInt32(e+4,es[rl?1:0])}getBufferIdentifier(){if(this.bytes_.lengththis.minalign&&(this.minalign=e);const i=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space=0&&this.vtable[t]==0;t--);const i=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);const a=2;this.addInt16(e-this.object_start);const u=(i+a)*rd;this.addInt16(u);let f=0;const h=this.space;e:for(t=0;t=0;f--)this.writeInt8(u.charCodeAt(f))}this.prep(this.minalign,Qn+a),this.addOffset(e),a&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){const i=this.bb.capacity()-e,a=i-this.bb.readInt32(i);if(!(t=0;i--)e.addInt32(t[i]);return e.endVector()}static startTypeIdsVector(e,t){e.startVector(4,t,4)}static endUnion(e){return e.endObject()}static createUnion(e,t,i){return Vt.startUnion(e),Vt.addMode(e,t),Vt.addTypeIds(e,i),Vt.endUnion(e)}}let xm=class Fo{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsUtf8(e,t){return(t||new Fo).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsUtf8(e,t){return e.setPosition(e.position()+He),(t||new Fo).__init(e.readInt32(e.position())+e.position(),e)}static startUtf8(e){e.startObject(0)}static endUtf8(e){return e.endObject()}static createUtf8(e){return Fo.startUtf8(e),Fo.endUtf8(e)}};var Ze;(function(n){n[n.NONE=0]="NONE",n[n.Null=1]="Null",n[n.Int=2]="Int",n[n.FloatingPoint=3]="FloatingPoint",n[n.Binary=4]="Binary",n[n.Utf8=5]="Utf8",n[n.Bool=6]="Bool",n[n.Decimal=7]="Decimal",n[n.Date=8]="Date",n[n.Time=9]="Time",n[n.Timestamp=10]="Timestamp",n[n.Interval=11]="Interval",n[n.List=12]="List",n[n.Struct_=13]="Struct_",n[n.Union=14]="Union",n[n.FixedSizeBinary=15]="FixedSizeBinary",n[n.FixedSizeList=16]="FixedSizeList",n[n.Map=17]="Map",n[n.Duration=18]="Duration",n[n.LargeBinary=19]="LargeBinary",n[n.LargeUtf8=20]="LargeUtf8",n[n.LargeList=21]="LargeList",n[n.RunEndEncoded=22]="RunEndEncoded"})(Ze||(Ze={}));let dn=class vl{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsField(e,t){return(t||new vl).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsField(e,t){return e.setPosition(e.position()+He),(t||new vl).__init(e.readInt32(e.position())+e.position(),e)}name(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}nullable(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}typeType(){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readUint8(this.bb_pos+e):Ze.NONE}type(e){const t=this.bb.__offset(this.bb_pos,10);return t?this.bb.__union(e,this.bb_pos+t):null}dictionary(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new wr).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}children(e,t){const i=this.bb.__offset(this.bb_pos,14);return i?(t||new vl).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}childrenLength(){const e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,16);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__vector_len(this.bb_pos+e):0}static startField(e){e.startObject(7)}static addName(e,t){e.addFieldOffset(0,t,0)}static addNullable(e,t){e.addFieldInt8(1,+t,0)}static addTypeType(e,t){e.addFieldInt8(2,t,Ze.NONE)}static addType(e,t){e.addFieldOffset(3,t,0)}static addDictionary(e,t){e.addFieldOffset(4,t,0)}static addChildren(e,t){e.addFieldOffset(5,t,0)}static createChildrenVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startChildrenVector(e,t){e.startVector(4,t,4)}static addCustomMetadata(e,t){e.addFieldOffset(6,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endField(e){return e.endObject()}},Gn=class mr{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSchema(e,t){return(t||new mr).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSchema(e,t){return e.setPosition(e.position()+He),(t||new mr).__init(e.readInt32(e.position())+e.position(),e)}endianness(){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):Ii.Little}fields(e,t){const i=this.bb.__offset(this.bb_pos,6);return i?(t||new dn).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}fieldsLength(){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,8);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}features(e){const t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+e*8):BigInt(0)}featuresLength(){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__vector_len(this.bb_pos+e):0}static startSchema(e){e.startObject(4)}static addEndianness(e,t){e.addFieldInt16(0,t,Ii.Little)}static addFields(e,t){e.addFieldOffset(1,t,0)}static createFieldsVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startFieldsVector(e,t){e.startVector(4,t,4)}static addCustomMetadata(e,t){e.addFieldOffset(2,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static addFeatures(e,t){e.addFieldOffset(3,t,0)}static createFeaturesVector(e,t){e.startVector(8,t.length,8);for(let i=t.length-1;i>=0;i--)e.addInt64(t[i]);return e.endVector()}static startFeaturesVector(e,t){e.startVector(8,t,8)}static endSchema(e){return e.endObject()}static finishSchemaBuffer(e,t){e.finish(t)}static finishSizePrefixedSchemaBuffer(e,t){e.finish(t,void 0,!0)}static createSchema(e,t,i,a,u){return mr.startSchema(e),mr.addEndianness(e,t),mr.addFields(e,i),mr.addCustomMetadata(e,a),mr.addFeatures(e,u),mr.endSchema(e)}};var Ve;(function(n){n[n.NONE=0]="NONE",n[n.Schema=1]="Schema",n[n.DictionaryBatch=2]="DictionaryBatch",n[n.RecordBatch=3]="RecordBatch",n[n.Tensor=4]="Tensor",n[n.SparseTensor=5]="SparseTensor"})(Ve||(Ve={}));var M;(function(n){n[n.NONE=0]="NONE",n[n.Null=1]="Null",n[n.Int=2]="Int",n[n.Float=3]="Float",n[n.Binary=4]="Binary",n[n.Utf8=5]="Utf8",n[n.Bool=6]="Bool",n[n.Decimal=7]="Decimal",n[n.Date=8]="Date",n[n.Time=9]="Time",n[n.Timestamp=10]="Timestamp",n[n.Interval=11]="Interval",n[n.List=12]="List",n[n.Struct=13]="Struct",n[n.Union=14]="Union",n[n.FixedSizeBinary=15]="FixedSizeBinary",n[n.FixedSizeList=16]="FixedSizeList",n[n.Map=17]="Map",n[n.Duration=18]="Duration",n[n.LargeBinary=19]="LargeBinary",n[n.LargeUtf8=20]="LargeUtf8",n[n.Dictionary=-1]="Dictionary",n[n.Int8=-2]="Int8",n[n.Int16=-3]="Int16",n[n.Int32=-4]="Int32",n[n.Int64=-5]="Int64",n[n.Uint8=-6]="Uint8",n[n.Uint16=-7]="Uint16",n[n.Uint32=-8]="Uint32",n[n.Uint64=-9]="Uint64",n[n.Float16=-10]="Float16",n[n.Float32=-11]="Float32",n[n.Float64=-12]="Float64",n[n.DateDay=-13]="DateDay",n[n.DateMillisecond=-14]="DateMillisecond",n[n.TimestampSecond=-15]="TimestampSecond",n[n.TimestampMillisecond=-16]="TimestampMillisecond",n[n.TimestampMicrosecond=-17]="TimestampMicrosecond",n[n.TimestampNanosecond=-18]="TimestampNanosecond",n[n.TimeSecond=-19]="TimeSecond",n[n.TimeMillisecond=-20]="TimeMillisecond",n[n.TimeMicrosecond=-21]="TimeMicrosecond",n[n.TimeNanosecond=-22]="TimeNanosecond",n[n.DenseUnion=-23]="DenseUnion",n[n.SparseUnion=-24]="SparseUnion",n[n.IntervalDayTime=-25]="IntervalDayTime",n[n.IntervalYearMonth=-26]="IntervalYearMonth",n[n.DurationSecond=-27]="DurationSecond",n[n.DurationMillisecond=-28]="DurationMillisecond",n[n.DurationMicrosecond=-29]="DurationMicrosecond",n[n.DurationNanosecond=-30]="DurationNanosecond"})(M||(M={}));var gr;(function(n){n[n.OFFSET=0]="OFFSET",n[n.DATA=1]="DATA",n[n.VALIDITY=2]="VALIDITY",n[n.TYPE=3]="TYPE"})(gr||(gr={}));const Eb=void 0;function Bo(n){if(n===null)return"null";if(n===Eb)return"undefined";switch(typeof n){case"number":return`${n}`;case"bigint":return`${n}`;case"string":return`"${n}"`}return typeof n[Symbol.toPrimitive]=="function"?n[Symbol.toPrimitive]("string"):ArrayBuffer.isView(n)?n instanceof BigInt64Array||n instanceof BigUint64Array?`[${[...n].map(e=>Bo(e))}]`:`[${n}]`:ArrayBuffer.isView(n)?`[${n}]`:JSON.stringify(n,(e,t)=>typeof t=="bigint"?`${t}`:t)}function tt(n){if(typeof n=="bigint"&&(nNumber.MAX_SAFE_INTEGER))throw new TypeError(`${n} is not safe to convert to a number.`);return Number(n)}function Fy(n,e){return tt(n/e)+tt(n%e)/tt(e)}const Rb=Symbol.for("isArrowBigNum");function Ln(n,...e){return e.length===0?Object.setPrototypeOf(Ke(this.TypedArray,n),this.constructor.prototype):Object.setPrototypeOf(new this.TypedArray(n,...e),this.constructor.prototype)}Ln.prototype[Rb]=!0;Ln.prototype.toJSON=function(){return`"${Ro(this)}"`};Ln.prototype.valueOf=function(n){return Oy(this,n)};Ln.prototype.toString=function(){return Ro(this)};Ln.prototype[Symbol.toPrimitive]=function(n="default"){switch(n){case"number":return Oy(this);case"string":return Ro(this);case"default":return $b(this)}return Ro(this)};function bi(...n){return Ln.apply(this,n)}function wi(...n){return Ln.apply(this,n)}function Eo(...n){return Ln.apply(this,n)}Object.setPrototypeOf(bi.prototype,Object.create(Int32Array.prototype));Object.setPrototypeOf(wi.prototype,Object.create(Uint32Array.prototype));Object.setPrototypeOf(Eo.prototype,Object.create(Uint32Array.prototype));Object.assign(bi.prototype,Ln.prototype,{constructor:bi,signed:!0,TypedArray:Int32Array,BigIntArray:BigInt64Array});Object.assign(wi.prototype,Ln.prototype,{constructor:wi,signed:!1,TypedArray:Uint32Array,BigIntArray:BigUint64Array});Object.assign(Eo.prototype,Ln.prototype,{constructor:Eo,signed:!0,TypedArray:Uint32Array,BigIntArray:BigUint64Array});const Lb=BigInt(4294967296)*BigInt(4294967296),Ub=Lb-BigInt(1);function Oy(n,e){const{buffer:t,byteOffset:i,byteLength:a,signed:u}=n,f=new BigUint64Array(t,i,a/8),h=u&&f.at(-1)&BigInt(1)<=0)return sd(n);e=e.slice();let i=1;for(let u=0;u(n.children=null,n.ArrayType=Array,n.OffsetArrayType=Int32Array,n[Symbol.toStringTag]="DataType"))(me.prototype);class ss extends me{constructor(){super(M.Null)}toString(){return"Null"}}Ay=Symbol.toStringTag;ss[Ay]=(n=>n[Symbol.toStringTag]="Null")(ss.prototype);class Ds extends me{constructor(e,t){super(M.Int),this.isSigned=e,this.bitWidth=t}get ArrayType(){switch(this.bitWidth){case 8:return this.isSigned?Int8Array:Uint8Array;case 16:return this.isSigned?Int16Array:Uint16Array;case 32:return this.isSigned?Int32Array:Uint32Array;case 64:return this.isSigned?BigInt64Array:BigUint64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`${this.isSigned?"I":"Ui"}nt${this.bitWidth}`}}By=Symbol.toStringTag;Ds[By]=(n=>(n.isSigned=null,n.bitWidth=null,n[Symbol.toStringTag]="Int"))(Ds.prototype);class Lo extends Ds{constructor(){super(!0,32)}get ArrayType(){return Int32Array}}Object.defineProperty(Lo.prototype,"ArrayType",{value:Int32Array});class jl extends me{constructor(e){super(M.Float),this.precision=e}get ArrayType(){switch(this.precision){case Dt.HALF:return Uint16Array;case Dt.SINGLE:return Float32Array;case Dt.DOUBLE:return Float64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`Float${this.precision<<5||16}`}}Ey=Symbol.toStringTag;jl[Ey]=(n=>(n.precision=null,n[Symbol.toStringTag]="Float"))(jl.prototype);class kl extends me{constructor(){super(M.Binary)}toString(){return"Binary"}}Ry=Symbol.toStringTag;kl[Ry]=(n=>(n.ArrayType=Uint8Array,n[Symbol.toStringTag]="Binary"))(kl.prototype);class Il extends me{constructor(){super(M.LargeBinary)}toString(){return"LargeBinary"}}Ly=Symbol.toStringTag;Il[Ly]=(n=>(n.ArrayType=Uint8Array,n.OffsetArrayType=BigInt64Array,n[Symbol.toStringTag]="LargeBinary"))(Il.prototype);class Ml extends me{constructor(){super(M.Utf8)}toString(){return"Utf8"}}Uy=Symbol.toStringTag;Ml[Uy]=(n=>(n.ArrayType=Uint8Array,n[Symbol.toStringTag]="Utf8"))(Ml.prototype);class Dl extends me{constructor(){super(M.LargeUtf8)}toString(){return"LargeUtf8"}}$y=Symbol.toStringTag;Dl[$y]=(n=>(n.ArrayType=Uint8Array,n.OffsetArrayType=BigInt64Array,n[Symbol.toStringTag]="LargeUtf8"))(Dl.prototype);class Cl extends me{constructor(){super(M.Bool)}toString(){return"Bool"}}Py=Symbol.toStringTag;Cl[Py]=(n=>(n.ArrayType=Uint8Array,n[Symbol.toStringTag]="Bool"))(Cl.prototype);class Fl extends me{constructor(e,t,i=128){super(M.Decimal),this.scale=e,this.precision=t,this.bitWidth=i}toString(){return`Decimal[${this.precision}e${this.scale>0?"+":""}${this.scale}]`}}zy=Symbol.toStringTag;Fl[zy]=(n=>(n.scale=null,n.precision=null,n.ArrayType=Uint32Array,n[Symbol.toStringTag]="Decimal"))(Fl.prototype);class Ol extends me{constructor(e){super(M.Date),this.unit=e}toString(){return`Date${(this.unit+1)*32}<${gn[this.unit]}>`}get ArrayType(){return this.unit===gn.DAY?Int32Array:BigInt64Array}}Vy=Symbol.toStringTag;Ol[Vy]=(n=>(n.unit=null,n[Symbol.toStringTag]="Date"))(Ol.prototype);class Tl extends me{constructor(e,t){super(M.Time),this.unit=e,this.bitWidth=t}toString(){return`Time${this.bitWidth}<${_e[this.unit]}>`}get ArrayType(){switch(this.bitWidth){case 32:return Int32Array;case 64:return BigInt64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}}Wy=Symbol.toStringTag;Tl[Wy]=(n=>(n.unit=null,n.bitWidth=null,n[Symbol.toStringTag]="Time"))(Tl.prototype);class Al extends me{constructor(e,t){super(M.Timestamp),this.unit=e,this.timezone=t}toString(){return`Timestamp<${_e[this.unit]}${this.timezone?`, ${this.timezone}`:""}>`}}Hy=Symbol.toStringTag;Al[Hy]=(n=>(n.unit=null,n.timezone=null,n.ArrayType=BigInt64Array,n[Symbol.toStringTag]="Timestamp"))(Al.prototype);class Bl extends me{constructor(e){super(M.Interval),this.unit=e}toString(){return`Interval<${nr[this.unit]}>`}}Gy=Symbol.toStringTag;Bl[Gy]=(n=>(n.unit=null,n.ArrayType=Int32Array,n[Symbol.toStringTag]="Interval"))(Bl.prototype);class El extends me{constructor(e){super(M.Duration),this.unit=e}toString(){return`Duration<${_e[this.unit]}>`}}Yy=Symbol.toStringTag;El[Yy]=(n=>(n.unit=null,n.ArrayType=BigInt64Array,n[Symbol.toStringTag]="Duration"))(El.prototype);class Rl extends me{constructor(e){super(M.List),this.children=[e]}toString(){return`List<${this.valueType}>`}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}}Qy=Symbol.toStringTag;Rl[Qy]=(n=>(n.children=null,n[Symbol.toStringTag]="List"))(Rl.prototype);class Tt extends me{constructor(e){super(M.Struct),this.children=e}toString(){return`Struct<{${this.children.map(e=>`${e.name}:${e.type}`).join(", ")}}>`}}Ky=Symbol.toStringTag;Tt[Ky]=(n=>(n.children=null,n[Symbol.toStringTag]="Struct"))(Tt.prototype);class Ll extends me{constructor(e,t,i){super(M.Union),this.mode=e,this.children=i,this.typeIds=t=Int32Array.from(t),this.typeIdToChildIndex=t.reduce((a,u,f)=>(a[u]=f)&&a||a,Object.create(null))}toString(){return`${this[Symbol.toStringTag]}<${this.children.map(e=>`${e.type}`).join(" | ")}>`}}Jy=Symbol.toStringTag;Ll[Jy]=(n=>(n.mode=null,n.typeIds=null,n.children=null,n.typeIdToChildIndex=null,n.ArrayType=Int8Array,n[Symbol.toStringTag]="Union"))(Ll.prototype);class Ul extends me{constructor(e){super(M.FixedSizeBinary),this.byteWidth=e}toString(){return`FixedSizeBinary[${this.byteWidth}]`}}qy=Symbol.toStringTag;Ul[qy]=(n=>(n.byteWidth=null,n.ArrayType=Uint8Array,n[Symbol.toStringTag]="FixedSizeBinary"))(Ul.prototype);class $l extends me{constructor(e,t){super(M.FixedSizeList),this.listSize=e,this.children=[t]}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}toString(){return`FixedSizeList[${this.listSize}]<${this.valueType}>`}}Zy=Symbol.toStringTag;$l[Zy]=(n=>(n.children=null,n.listSize=null,n[Symbol.toStringTag]="FixedSizeList"))($l.prototype);class Pl extends me{constructor(e,t=!1){var i,a,u;if(super(M.Map),this.children=[e],this.keysSorted=t,e&&(e.name="entries",!((i=e==null?void 0:e.type)===null||i===void 0)&&i.children)){const f=(a=e==null?void 0:e.type)===null||a===void 0?void 0:a.children[0];f&&(f.name="key");const h=(u=e==null?void 0:e.type)===null||u===void 0?void 0:u.children[1];h&&(h.name="value")}}get keyType(){return this.children[0].type.children[0].type}get valueType(){return this.children[0].type.children[1].type}get childType(){return this.children[0].type}toString(){return`Map<{${this.children[0].type.children.map(e=>`${e.name}:${e.type}`).join(", ")}}>`}}Xy=Symbol.toStringTag;Pl[Xy]=(n=>(n.children=null,n.keysSorted=null,n[Symbol.toStringTag]="Map_"))(Pl.prototype);const Pb=(n=>()=>++n)(-1);class Mi extends me{constructor(e,t,i,a){super(M.Dictionary),this.indices=t,this.dictionary=e,this.isOrdered=a||!1,this.id=i==null?Pb():tt(i)}get children(){return this.dictionary.children}get valueType(){return this.dictionary}get ArrayType(){return this.dictionary.ArrayType}toString(){return`Dictionary<${this.indices}, ${this.dictionary}>`}}eg=Symbol.toStringTag;Mi[eg]=(n=>(n.id=null,n.indices=null,n.isOrdered=null,n.dictionary=null,n[Symbol.toStringTag]="Dictionary"))(Mi.prototype);function vr(n){const e=n;switch(n.typeId){case M.Decimal:return n.bitWidth/32;case M.Interval:return 1+e.unit;case M.FixedSizeList:return e.listSize;case M.FixedSizeBinary:return e.byteWidth;default:return 1}}class Re{visitMany(e,...t){return e.map((i,a)=>this.visit(i,...t.map(u=>u[a])))}visit(...e){return this.getVisitFn(e[0],!1).apply(this,e)}getVisitFn(e,t=!0){return zb(this,e,t)}getVisitFnByTypeId(e,t=!0){return mi(this,e,t)}visitNull(e,...t){return null}visitBool(e,...t){return null}visitInt(e,...t){return null}visitFloat(e,...t){return null}visitUtf8(e,...t){return null}visitLargeUtf8(e,...t){return null}visitBinary(e,...t){return null}visitLargeBinary(e,...t){return null}visitFixedSizeBinary(e,...t){return null}visitDate(e,...t){return null}visitTimestamp(e,...t){return null}visitTime(e,...t){return null}visitDecimal(e,...t){return null}visitList(e,...t){return null}visitStruct(e,...t){return null}visitUnion(e,...t){return null}visitDictionary(e,...t){return null}visitInterval(e,...t){return null}visitDuration(e,...t){return null}visitFixedSizeList(e,...t){return null}visitMap(e,...t){return null}}function zb(n,e,t=!0){return typeof e=="number"?mi(n,e,t):typeof e=="string"&&e in M?mi(n,M[e],t):e&&e instanceof me?mi(n,bm(e),t):e!=null&&e.type&&e.type instanceof me?mi(n,bm(e.type),t):mi(n,M.NONE,t)}function mi(n,e,t=!0){let i=null;switch(e){case M.Null:i=n.visitNull;break;case M.Bool:i=n.visitBool;break;case M.Int:i=n.visitInt;break;case M.Int8:i=n.visitInt8||n.visitInt;break;case M.Int16:i=n.visitInt16||n.visitInt;break;case M.Int32:i=n.visitInt32||n.visitInt;break;case M.Int64:i=n.visitInt64||n.visitInt;break;case M.Uint8:i=n.visitUint8||n.visitInt;break;case M.Uint16:i=n.visitUint16||n.visitInt;break;case M.Uint32:i=n.visitUint32||n.visitInt;break;case M.Uint64:i=n.visitUint64||n.visitInt;break;case M.Float:i=n.visitFloat;break;case M.Float16:i=n.visitFloat16||n.visitFloat;break;case M.Float32:i=n.visitFloat32||n.visitFloat;break;case M.Float64:i=n.visitFloat64||n.visitFloat;break;case M.Utf8:i=n.visitUtf8;break;case M.LargeUtf8:i=n.visitLargeUtf8;break;case M.Binary:i=n.visitBinary;break;case M.LargeBinary:i=n.visitLargeBinary;break;case M.FixedSizeBinary:i=n.visitFixedSizeBinary;break;case M.Date:i=n.visitDate;break;case M.DateDay:i=n.visitDateDay||n.visitDate;break;case M.DateMillisecond:i=n.visitDateMillisecond||n.visitDate;break;case M.Timestamp:i=n.visitTimestamp;break;case M.TimestampSecond:i=n.visitTimestampSecond||n.visitTimestamp;break;case M.TimestampMillisecond:i=n.visitTimestampMillisecond||n.visitTimestamp;break;case M.TimestampMicrosecond:i=n.visitTimestampMicrosecond||n.visitTimestamp;break;case M.TimestampNanosecond:i=n.visitTimestampNanosecond||n.visitTimestamp;break;case M.Time:i=n.visitTime;break;case M.TimeSecond:i=n.visitTimeSecond||n.visitTime;break;case M.TimeMillisecond:i=n.visitTimeMillisecond||n.visitTime;break;case M.TimeMicrosecond:i=n.visitTimeMicrosecond||n.visitTime;break;case M.TimeNanosecond:i=n.visitTimeNanosecond||n.visitTime;break;case M.Decimal:i=n.visitDecimal;break;case M.List:i=n.visitList;break;case M.Struct:i=n.visitStruct;break;case M.Union:i=n.visitUnion;break;case M.DenseUnion:i=n.visitDenseUnion||n.visitUnion;break;case M.SparseUnion:i=n.visitSparseUnion||n.visitUnion;break;case M.Dictionary:i=n.visitDictionary;break;case M.Interval:i=n.visitInterval;break;case M.IntervalDayTime:i=n.visitIntervalDayTime||n.visitInterval;break;case M.IntervalYearMonth:i=n.visitIntervalYearMonth||n.visitInterval;break;case M.Duration:i=n.visitDuration;break;case M.DurationSecond:i=n.visitDurationSecond||n.visitDuration;break;case M.DurationMillisecond:i=n.visitDurationMillisecond||n.visitDuration;break;case M.DurationMicrosecond:i=n.visitDurationMicrosecond||n.visitDuration;break;case M.DurationNanosecond:i=n.visitDurationNanosecond||n.visitDuration;break;case M.FixedSizeList:i=n.visitFixedSizeList;break;case M.Map:i=n.visitMap;break}if(typeof i=="function")return i;if(!t)return()=>null;throw new Error(`Unrecognized type '${M[e]}'`)}function bm(n){switch(n.typeId){case M.Null:return M.Null;case M.Int:{const{bitWidth:e,isSigned:t}=n;switch(e){case 8:return t?M.Int8:M.Uint8;case 16:return t?M.Int16:M.Uint16;case 32:return t?M.Int32:M.Uint32;case 64:return t?M.Int64:M.Uint64}return M.Int}case M.Float:switch(n.precision){case Dt.HALF:return M.Float16;case Dt.SINGLE:return M.Float32;case Dt.DOUBLE:return M.Float64}return M.Float;case M.Binary:return M.Binary;case M.LargeBinary:return M.LargeBinary;case M.Utf8:return M.Utf8;case M.LargeUtf8:return M.LargeUtf8;case M.Bool:return M.Bool;case M.Decimal:return M.Decimal;case M.Time:switch(n.unit){case _e.SECOND:return M.TimeSecond;case _e.MILLISECOND:return M.TimeMillisecond;case _e.MICROSECOND:return M.TimeMicrosecond;case _e.NANOSECOND:return M.TimeNanosecond}return M.Time;case M.Timestamp:switch(n.unit){case _e.SECOND:return M.TimestampSecond;case _e.MILLISECOND:return M.TimestampMillisecond;case _e.MICROSECOND:return M.TimestampMicrosecond;case _e.NANOSECOND:return M.TimestampNanosecond}return M.Timestamp;case M.Date:switch(n.unit){case gn.DAY:return M.DateDay;case gn.MILLISECOND:return M.DateMillisecond}return M.Date;case M.Interval:switch(n.unit){case nr.DAY_TIME:return M.IntervalDayTime;case nr.YEAR_MONTH:return M.IntervalYearMonth}return M.Interval;case M.Duration:switch(n.unit){case _e.SECOND:return M.DurationSecond;case _e.MILLISECOND:return M.DurationMillisecond;case _e.MICROSECOND:return M.DurationMicrosecond;case _e.NANOSECOND:return M.DurationNanosecond}return M.Duration;case M.Map:return M.Map;case M.List:return M.List;case M.Struct:return M.Struct;case M.Union:switch(n.mode){case Ht.Dense:return M.DenseUnion;case Ht.Sparse:return M.SparseUnion}return M.Union;case M.FixedSizeBinary:return M.FixedSizeBinary;case M.FixedSizeList:return M.FixedSizeList;case M.Dictionary:return M.Dictionary}throw new Error(`Unrecognized type '${M[n.typeId]}'`)}Re.prototype.visitInt8=null;Re.prototype.visitInt16=null;Re.prototype.visitInt32=null;Re.prototype.visitInt64=null;Re.prototype.visitUint8=null;Re.prototype.visitUint16=null;Re.prototype.visitUint32=null;Re.prototype.visitUint64=null;Re.prototype.visitFloat16=null;Re.prototype.visitFloat32=null;Re.prototype.visitFloat64=null;Re.prototype.visitDateDay=null;Re.prototype.visitDateMillisecond=null;Re.prototype.visitTimestampSecond=null;Re.prototype.visitTimestampMillisecond=null;Re.prototype.visitTimestampMicrosecond=null;Re.prototype.visitTimestampNanosecond=null;Re.prototype.visitTimeSecond=null;Re.prototype.visitTimeMillisecond=null;Re.prototype.visitTimeMicrosecond=null;Re.prototype.visitTimeNanosecond=null;Re.prototype.visitDenseUnion=null;Re.prototype.visitSparseUnion=null;Re.prototype.visitIntervalDayTime=null;Re.prototype.visitIntervalYearMonth=null;Re.prototype.visitDuration=null;Re.prototype.visitDurationSecond=null;Re.prototype.visitDurationMillisecond=null;Re.prototype.visitDurationMicrosecond=null;Re.prototype.visitDurationNanosecond=null;const tg=new Float64Array(1),ai=new Uint32Array(tg.buffer);function ng(n){const e=(n&31744)>>10,t=(n&1023)/1024,i=Math.pow(-1,(n&32768)>>15);switch(e){case 31:return i*(t?Number.NaN:1/0);case 0:return i*(t?6103515625e-14*t:0)}return i*Math.pow(2,e-15)*(1+t)}function Vb(n){if(n!==n)return 32256;tg[0]=n;const e=(ai[1]&2147483648)>>16&65535;let t=ai[1]&2146435072,i=0;return t>=1089470464?ai[0]>0?t=31744:(t=(t&2080374784)>>16,i=(ai[1]&1048575)>>10):t<=1056964608?(i=1048576+(ai[1]&1048575),i=1048576+(i<<(t>>20)-998)>>21,t=0):(t=t-1056964608>>10,i=(ai[1]&1048575)+512>>10),e|t|i&65535}class Ne extends Re{}function Ie(n){return(e,t,i)=>{if(e.setValid(t,i!=null))return n(e,t,i)}}const Wb=(n,e,t)=>{n[e]=Math.floor(t/864e5)},rg=(n,e,t,i)=>{if(t+1{const a=n+t;i?e[a>>3]|=1<>3]&=~(1<{n[e]=t},$d=({values:n},e,t)=>{n[e]=t},sg=({values:n},e,t)=>{n[e]=Vb(t)},Gb=(n,e,t)=>{switch(n.type.precision){case Dt.HALF:return sg(n,e,t);case Dt.SINGLE:case Dt.DOUBLE:return $d(n,e,t)}},ig=({values:n},e,t)=>{Wb(n,e,t.valueOf())},og=({values:n},e,t)=>{n[e]=BigInt(t)},Yb=({stride:n,values:e},t,i)=>{e.set(i.subarray(0,n),n*t)},ag=({values:n,valueOffsets:e},t,i)=>rg(n,e,t,i),lg=({values:n,valueOffsets:e},t,i)=>rg(n,e,t,Bd(i)),Qb=(n,e,t)=>{n.type.unit===gn.DAY?ig(n,e,t):og(n,e,t)},ug=({values:n},e,t)=>{n[e]=BigInt(t/1e3)},cg=({values:n},e,t)=>{n[e]=BigInt(t)},dg=({values:n},e,t)=>{n[e]=BigInt(t*1e3)},fg=({values:n},e,t)=>{n[e]=BigInt(t*1e6)},Kb=(n,e,t)=>{switch(n.type.unit){case _e.SECOND:return ug(n,e,t);case _e.MILLISECOND:return cg(n,e,t);case _e.MICROSECOND:return dg(n,e,t);case _e.NANOSECOND:return fg(n,e,t)}},hg=({values:n},e,t)=>{n[e]=t},pg=({values:n},e,t)=>{n[e]=t},mg=({values:n},e,t)=>{n[e]=t},yg=({values:n},e,t)=>{n[e]=t},Jb=(n,e,t)=>{switch(n.type.unit){case _e.SECOND:return hg(n,e,t);case _e.MILLISECOND:return pg(n,e,t);case _e.MICROSECOND:return mg(n,e,t);case _e.NANOSECOND:return yg(n,e,t)}},qb=({values:n,stride:e},t,i)=>{n.set(i.subarray(0,e),e*t)},Zb=(n,e,t)=>{const i=n.children[0],a=n.valueOffsets,u=vn.getVisitFn(i);if(Array.isArray(t))for(let f=-1,h=a[e],m=a[e+1];h{const i=n.children[0],{valueOffsets:a}=n,u=vn.getVisitFn(i);let{[e]:f,[e+1]:h}=a;const m=t instanceof Map?t.entries():Object.entries(t);for(const g of m)if(u(i,f,g),++f>=h)break},ew=(n,e)=>(t,i,a,u)=>i&&t(i,n,e[u]),tw=(n,e)=>(t,i,a,u)=>i&&t(i,n,e.get(u)),nw=(n,e)=>(t,i,a,u)=>i&&t(i,n,e.get(a.name)),rw=(n,e)=>(t,i,a,u)=>i&&t(i,n,e[a.name]),sw=(n,e,t)=>{const i=n.type.children.map(u=>vn.getVisitFn(u.type)),a=t instanceof Map?nw(e,t):t instanceof Je?tw(e,t):Array.isArray(t)?ew(e,t):rw(e,t);n.type.children.forEach((u,f)=>a(i[f],n.children[f],u,f))},iw=(n,e,t)=>{n.type.mode===Ht.Dense?gg(n,e,t):vg(n,e,t)},gg=(n,e,t)=>{const i=n.type.typeIdToChildIndex[n.typeIds[e]],a=n.children[i];vn.visit(a,n.valueOffsets[e],t)},vg=(n,e,t)=>{const i=n.type.typeIdToChildIndex[n.typeIds[e]],a=n.children[i];vn.visit(a,e,t)},ow=(n,e,t)=>{var i;(i=n.dictionary)===null||i===void 0||i.set(n.values[e],t)},aw=(n,e,t)=>{n.type.unit===nr.DAY_TIME?xg(n,e,t):bg(n,e,t)},xg=({values:n},e,t)=>{n.set(t.subarray(0,2),2*e)},bg=({values:n},e,t)=>{n[e]=t[0]*12+t[1]%12},wg=({values:n},e,t)=>{n[e]=t},Sg=({values:n},e,t)=>{n[e]=t},_g=({values:n},e,t)=>{n[e]=t},Ng=({values:n},e,t)=>{n[e]=t},lw=(n,e,t)=>{switch(n.type.unit){case _e.SECOND:return wg(n,e,t);case _e.MILLISECOND:return Sg(n,e,t);case _e.MICROSECOND:return _g(n,e,t);case _e.NANOSECOND:return Ng(n,e,t)}},uw=(n,e,t)=>{const{stride:i}=n,a=n.children[0],u=vn.getVisitFn(a);if(Array.isArray(t))for(let f=-1,h=e*i;++f`${Bo(e)}: ${Bo(t)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}[Symbol.iterator](){return new cw(this[On],this[Si])}}class cw{constructor(e,t){this.childIndex=0,this.children=e.children,this.rowIndex=t,this.childFields=e.type.children,this.numChildren=this.childFields.length}[Symbol.iterator](){return this}next(){const e=this.childIndex;return et.name)}has(e,t){return e[On].type.children.findIndex(i=>i.name===t)!==-1}getOwnPropertyDescriptor(e,t){if(e[On].type.children.findIndex(i=>i.name===t)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(e,t){if(Reflect.has(e,t))return e[t];const i=e[On].type.children.findIndex(a=>a.name===t);if(i!==-1){const a=Gt.visit(e[On].children[i],e[Si]);return Reflect.set(e,t,a),a}}set(e,t,i){const a=e[On].type.children.findIndex(u=>u.name===t);return a!==-1?(vn.visit(e[On].children[a],e[Si],i),Reflect.set(e,t,i)):Reflect.has(e,t)||typeof t=="symbol"?Reflect.set(e,t,i):!1}}class ve extends Re{}function je(n){return(e,t)=>e.getValid(t)?n(e,t):null}const fw=(n,e)=>864e5*n[e],hw=(n,e)=>null,jg=(n,e,t)=>{if(t+1>=e.length)return null;const i=tt(e[t]),a=tt(e[t+1]);return n.subarray(i,a)},pw=({offset:n,values:e},t)=>{const i=n+t;return(e[i>>3]&1<fw(n,e),Ig=({values:n},e)=>tt(n[e]),as=({stride:n,values:e},t)=>e[n*t],mw=({stride:n,values:e},t)=>ng(e[n*t]),Mg=({values:n},e)=>n[e],yw=({stride:n,values:e},t)=>e.subarray(n*t,n*(t+1)),Dg=({values:n,valueOffsets:e},t)=>jg(n,e,t),Cg=({values:n,valueOffsets:e},t)=>{const i=jg(n,e,t);return i!==null?xd(i):null},gw=({values:n},e)=>n[e],vw=({type:n,values:e},t)=>n.precision!==Dt.HALF?e[t]:ng(e[t]),xw=(n,e)=>n.type.unit===gn.DAY?kg(n,e):Ig(n,e),Fg=({values:n},e)=>1e3*tt(n[e]),Og=({values:n},e)=>tt(n[e]),Tg=({values:n},e)=>Fy(n[e],BigInt(1e3)),Ag=({values:n},e)=>Fy(n[e],BigInt(1e6)),bw=(n,e)=>{switch(n.type.unit){case _e.SECOND:return Fg(n,e);case _e.MILLISECOND:return Og(n,e);case _e.MICROSECOND:return Tg(n,e);case _e.NANOSECOND:return Ag(n,e)}},Bg=({values:n},e)=>n[e],Eg=({values:n},e)=>n[e],Rg=({values:n},e)=>n[e],Lg=({values:n},e)=>n[e],ww=(n,e)=>{switch(n.type.unit){case _e.SECOND:return Bg(n,e);case _e.MILLISECOND:return Eg(n,e);case _e.MICROSECOND:return Rg(n,e);case _e.NANOSECOND:return Lg(n,e)}},Sw=({values:n,stride:e},t)=>Ud.decimal(n.subarray(e*t,e*(t+1))),_w=(n,e)=>{const{valueOffsets:t,stride:i,children:a}=n,{[e*i]:u,[e*i+1]:f}=t,m=a[0].slice(u,f-u);return new Je([m])},Nw=(n,e)=>{const{valueOffsets:t,children:i}=n,{[e]:a,[e+1]:u}=t,f=i[0];return new zd(f.slice(a,u-a))},jw=(n,e)=>new Pd(n,e),kw=(n,e)=>n.type.mode===Ht.Dense?Ug(n,e):$g(n,e),Ug=(n,e)=>{const t=n.type.typeIdToChildIndex[n.typeIds[e]],i=n.children[t];return Gt.visit(i,n.valueOffsets[e])},$g=(n,e)=>{const t=n.type.typeIdToChildIndex[n.typeIds[e]],i=n.children[t];return Gt.visit(i,e)},Iw=(n,e)=>{var t;return(t=n.dictionary)===null||t===void 0?void 0:t.get(n.values[e])},Mw=(n,e)=>n.type.unit===nr.DAY_TIME?Pg(n,e):zg(n,e),Pg=({values:n},e)=>n.subarray(2*e,2*(e+1)),zg=({values:n},e)=>{const t=n[e],i=new Int32Array(2);return i[0]=Math.trunc(t/12),i[1]=Math.trunc(t%12),i},Vg=({values:n},e)=>n[e],Wg=({values:n},e)=>n[e],Hg=({values:n},e)=>n[e],Gg=({values:n},e)=>n[e],Dw=(n,e)=>{switch(n.type.unit){case _e.SECOND:return Vg(n,e);case _e.MILLISECOND:return Wg(n,e);case _e.MICROSECOND:return Hg(n,e);case _e.NANOSECOND:return Gg(n,e)}},Cw=(n,e)=>{const{stride:t,children:i}=n,u=i[0].slice(e*t,t);return new Je([u])};ve.prototype.visitNull=je(hw);ve.prototype.visitBool=je(pw);ve.prototype.visitInt=je(gw);ve.prototype.visitInt8=je(as);ve.prototype.visitInt16=je(as);ve.prototype.visitInt32=je(as);ve.prototype.visitInt64=je(Mg);ve.prototype.visitUint8=je(as);ve.prototype.visitUint16=je(as);ve.prototype.visitUint32=je(as);ve.prototype.visitUint64=je(Mg);ve.prototype.visitFloat=je(vw);ve.prototype.visitFloat16=je(mw);ve.prototype.visitFloat32=je(as);ve.prototype.visitFloat64=je(as);ve.prototype.visitUtf8=je(Cg);ve.prototype.visitLargeUtf8=je(Cg);ve.prototype.visitBinary=je(Dg);ve.prototype.visitLargeBinary=je(Dg);ve.prototype.visitFixedSizeBinary=je(yw);ve.prototype.visitDate=je(xw);ve.prototype.visitDateDay=je(kg);ve.prototype.visitDateMillisecond=je(Ig);ve.prototype.visitTimestamp=je(bw);ve.prototype.visitTimestampSecond=je(Fg);ve.prototype.visitTimestampMillisecond=je(Og);ve.prototype.visitTimestampMicrosecond=je(Tg);ve.prototype.visitTimestampNanosecond=je(Ag);ve.prototype.visitTime=je(ww);ve.prototype.visitTimeSecond=je(Bg);ve.prototype.visitTimeMillisecond=je(Eg);ve.prototype.visitTimeMicrosecond=je(Rg);ve.prototype.visitTimeNanosecond=je(Lg);ve.prototype.visitDecimal=je(Sw);ve.prototype.visitList=je(_w);ve.prototype.visitStruct=je(jw);ve.prototype.visitUnion=je(kw);ve.prototype.visitDenseUnion=je(Ug);ve.prototype.visitSparseUnion=je($g);ve.prototype.visitDictionary=je(Iw);ve.prototype.visitInterval=je(Mw);ve.prototype.visitIntervalDayTime=je(Pg);ve.prototype.visitIntervalYearMonth=je(zg);ve.prototype.visitDuration=je(Dw);ve.prototype.visitDurationSecond=je(Vg);ve.prototype.visitDurationMillisecond=je(Wg);ve.prototype.visitDurationMicrosecond=je(Hg);ve.prototype.visitDurationNanosecond=je(Gg);ve.prototype.visitFixedSizeList=je(Cw);ve.prototype.visitMap=je(Nw);const Gt=new ve,yi=Symbol.for("keys"),_i=Symbol.for("vals"),gi=Symbol.for("kKeysAsStrings"),jd=Symbol.for("_kKeysAsStrings");class zd{constructor(e){return this[yi]=new Je([e.children[0]]).memoize(),this[_i]=e.children[1],new Proxy(this,new Ow)}get[gi](){return this[jd]||(this[jd]=Array.from(this[yi].toArray(),String))}[Symbol.iterator](){return new Fw(this[yi],this[_i])}get size(){return this[yi].length}toArray(){return Object.values(this.toJSON())}toJSON(){const e=this[yi],t=this[_i],i={};for(let a=-1,u=e.length;++a`${Bo(e)}: ${Bo(t)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}class Fw{constructor(e,t){this.keys=e,this.vals=t,this.keyIndex=0,this.numKeys=e.length}[Symbol.iterator](){return this}next(){const e=this.keyIndex;return e===this.numKeys?{done:!0,value:null}:(this.keyIndex++,{done:!1,value:[this.keys.get(e),Gt.visit(this.vals,e)]})}}class Ow{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(e){return e[gi]}has(e,t){return e[gi].includes(t)}getOwnPropertyDescriptor(e,t){if(e[gi].indexOf(t)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(e,t){if(Reflect.has(e,t))return e[t];const i=e[gi].indexOf(t);if(i!==-1){const a=Gt.visit(Reflect.get(e,_i),i);return Reflect.set(e,t,a),a}}set(e,t,i){const a=e[gi].indexOf(t);return a!==-1?(vn.visit(Reflect.get(e,_i),a,i),Reflect.set(e,t,i)):Reflect.has(e,t)?Reflect.set(e,t,i):!1}}Object.defineProperties(zd.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:"Row"},[yi]:{writable:!0,enumerable:!1,configurable:!1,value:null},[_i]:{writable:!0,enumerable:!1,configurable:!1,value:null},[jd]:{writable:!0,enumerable:!1,configurable:!1,value:null}});let wm;function Yg(n,e,t,i){const{length:a=0}=n;let u=typeof e!="number"?0:e,f=typeof t!="number"?a:t;return u<0&&(u=(u%a+a)%a),f<0&&(f=(f%a+a)%a),fa&&(f=a),i?i(n,u,f):[u,f]}const Vd=(n,e)=>n<0?e+n:n,Sm=n=>n!==n;function Ti(n){if(typeof n!=="object"||n===null)return Sm(n)?Sm:t=>t===n;if(n instanceof Date){const t=n.valueOf();return i=>i instanceof Date?i.valueOf()===t:!1}return ArrayBuffer.isView(n)?t=>t?Cb(n,t):!1:n instanceof Map?Aw(n):Array.isArray(n)?Tw(n):n instanceof Je?Bw(n):Ew(n,!0)}function Tw(n){const e=[];for(let t=-1,i=n.length;++t!1;const i=[];for(let a=-1,u=t.length;++a{if(!t||typeof t!="object")return!1;switch(t.constructor){case Array:return Rw(n,t);case Map:return _m(n,t,t.keys());case zd:case Pd:case Object:case void 0:return _m(n,t,e||Object.keys(t))}return t instanceof Je?Lw(n,t):!1}}function Rw(n,e){const t=n.length;if(e.length!==t)return!1;for(let i=-1;++i>i}function Nm(n,e,t){const i=t.byteLength+7&-8;if(n>0||t.byteLength>3):kd(new Wd(t,n,e,null,Qg)).subarray(0,i)),a}return t}function kd(n){const e=[];let t=0,i=0,a=0;for(const f of n)f&&(a|=1<0)&&(e[t++]=a);const u=new Uint8Array(e.length+7&-8);return u.set(e),u}class Wd{constructor(e,t,i,a,u){this.bytes=e,this.length=i,this.context=a,this.get=u,this.bit=t%8,this.byteIndex=t>>3,this.byte=e[this.byteIndex++],this.index=0}next(){return this.index>3<<3,a=e+(e%8===0?0:8-e%8);return Id(n,e,a)+Id(n,i,t)+$w(n,a>>3,i-a>>3)}function $w(n,e,t){let i=0,a=Math.trunc(e);const u=new DataView(n.buffer,n.byteOffset,n.byteLength),f=t===void 0?n.byteLength:a+t;for(;f-a>=4;)i+=id(u.getUint32(a)),a+=4;for(;f-a>=2;)i+=id(u.getUint16(a)),a+=2;for(;f-a>=1;)i+=id(u.getUint8(a)),a+=1;return i}function id(n){let e=Math.trunc(n);return e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),(e+(e>>>4)&252645135)*16843009>>>24}const Pw=-1;class Ye{get typeId(){return this.type.typeId}get ArrayType(){return this.type.ArrayType}get buffers(){return[this.valueOffsets,this.values,this.nullBitmap,this.typeIds]}get nullable(){if(this._nullCount!==0){const{type:e}=this;return me.isSparseUnion(e)?this.children.some(t=>t.nullable):me.isDenseUnion(e)?this.children.some(t=>t.nullable):this.nullBitmap&&this.nullBitmap.byteLength>0}return!0}get byteLength(){let e=0;const{valueOffsets:t,values:i,nullBitmap:a,typeIds:u}=this;return t&&(e+=t.byteLength),i&&(e+=i.byteLength),a&&(e+=a.byteLength),u&&(e+=u.byteLength),this.children.reduce((f,h)=>f+h.byteLength,e)}get nullCount(){if(me.isUnion(this.type))return this.children.reduce((i,a)=>i+a.nullCount,0);let e=this._nullCount,t;return e<=Pw&&(t=this.nullBitmap)&&(this._nullCount=e=t.length===0?0:this.length-Id(t,this.offset,this.offset+this.length)),e}constructor(e,t,i,a,u,f=[],h){this.type=e,this.children=f,this.dictionary=h,this.offset=Math.floor(Math.max(t||0,0)),this.length=Math.floor(Math.max(i||0,0)),this._nullCount=Math.floor(Math.max(a||0,-1));let m;u instanceof Ye?(this.stride=u.stride,this.values=u.values,this.typeIds=u.typeIds,this.nullBitmap=u.nullBitmap,this.valueOffsets=u.valueOffsets):(this.stride=vr(e),u&&((m=u[0])&&(this.valueOffsets=m),(m=u[1])&&(this.values=m),(m=u[2])&&(this.nullBitmap=m),(m=u[3])&&(this.typeIds=m)))}getValid(e){const{type:t}=this;if(me.isUnion(t)){const i=t,a=this.children[i.typeIdToChildIndex[this.typeIds[e]]],u=i.mode===Ht.Dense?this.valueOffsets[e]:e;return a.getValid(u)}if(this.nullable&&this.nullCount>0){const i=this.offset+e;return(this.nullBitmap[i>>3]&1<>3;(!u||u.byteLength<=v)&&(u=new Uint8Array((f+h+63&-64)>>3).fill(255),this.nullCount>0?(u.set(Nm(f,h,this.nullBitmap),0),Object.assign(this,{nullBitmap:u})):Object.assign(this,{nullBitmap:u,_nullCount:0}));const x=u[v];i=(x&g)!==0,u[v]=t?x|g:x&~g}return i!==!!t&&(this._nullCount=this.nullCount+(t?-1:1)),t}clone(e=this.type,t=this.offset,i=this.length,a=this._nullCount,u=this,f=this.children){return new Ye(e,t,i,a,u,f,this.dictionary)}slice(e,t){const{stride:i,typeId:a,children:u}=this,f=+(this._nullCount===0)-1,h=a===16?i:1,m=this._sliceBuffers(e,t,i,a);return this.clone(this.type,this.offset+e,t,f,m,u.length===0||this.valueOffsets?u:this._sliceChildren(u,h*e,h*t))}_changeLengthAndBackfillNullBitmap(e){if(this.typeId===M.Null)return this.clone(this.type,0,e,0);const{length:t,nullCount:i}=this,a=new Uint8Array((e+63&-64)>>3).fill(255,0,t>>3);a[t>>3]=(1<0&&a.set(Nm(this.offset,t,this.nullBitmap),0);const u=this.buffers;return u[gr.VALIDITY]=a,this.clone(this.type,0,e,i+(e-t),u)}_sliceBuffers(e,t,i,a){let u;const{buffers:f}=this;return(u=f[gr.TYPE])&&(f[gr.TYPE]=u.subarray(e,e+t)),(u=f[gr.OFFSET])&&(f[gr.OFFSET]=u.subarray(e,e+t+1))||(u=f[gr.DATA])&&(f[gr.DATA]=a===6?u:u.subarray(i*e,i*(e+t))),f}_sliceChildren(e,t,i){return e.map(a=>a.slice(t,i))}}Ye.prototype.children=Object.freeze([]);class To extends Re{visit(e){return this.getVisitFn(e.type).call(this,e)}visitNull(e){const{["type"]:t,["offset"]:i=0,["length"]:a=0}=e;return new Ye(t,i,a,a)}visitBool(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length>>3,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitInt(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitFloat(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitUtf8(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitLargeUtf8(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=cm(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitBinary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitLargeBinary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=cm(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitFixedSizeBinary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitDate(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitTimestamp(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitTime(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitDecimal(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitList(e){const{["type"]:t,["offset"]:i=0,["child"]:a}=e,u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,void 0,u],[a])}visitStruct(e){const{["type"]:t,["offset"]:i=0,["children"]:a=[]}=e,u=$e(e.nullBitmap),{length:f=a.reduce((m,{length:g})=>Math.max(m,g),0),nullCount:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,void 0,u],a)}visitUnion(e){const{["type"]:t,["offset"]:i=0,["children"]:a=[]}=e,u=Ke(t.ArrayType,e.typeIds),{["length"]:f=u.length,["nullCount"]:h=-1}=e;if(me.isSparseUnion(t))return new Ye(t,i,f,h,[void 0,void 0,void 0,u],a);const m=So(e.valueOffsets);return new Ye(t,i,f,h,[m,void 0,void 0,u],a)}visitDictionary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.indices.ArrayType,e.data),{["dictionary"]:f=new Je([new To().visit({type:t.dictionary})])}=e,{["length"]:h=u.length,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[void 0,u,a],[],f)}visitInterval(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitDuration(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitFixedSizeList(e){const{["type"]:t,["offset"]:i=0,["child"]:a=new To().visit({type:t.valueType})}=e,u=$e(e.nullBitmap),{["length"]:f=a.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,void 0,u],[a])}visitMap(e){const{["type"]:t,["offset"]:i=0,["child"]:a=new To().visit({type:t.childType})}=e,u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,void 0,u],[a])}}const zw=new To;function Ee(n){return zw.visit(n)}class jm{constructor(e=0,t){this.numChunks=e,this.getChunkIterator=t,this.chunkIndex=0,this.chunkIterator=this.getChunkIterator(0)}next(){for(;this.chunkIndexe.nullable)}function Kg(n){return n.reduce((e,t)=>e+t.nullCount,0)}function Jg(n){return n.reduce((e,t,i)=>(e[i+1]=e[i]+t.length,e),new Uint32Array(n.length+1))}function qg(n,e,t,i){const a=[];for(let u=-1,f=n.length;++u=i)break;if(t>=m+g)continue;if(m>=t&&m+g<=i){a.push(h);continue}const v=Math.max(0,t-m),x=Math.min(i-m,g);a.push(h.slice(v,x-v))}return a.length===0&&a.push(n[0].slice(0,0)),a}function Hd(n,e,t,i){let a=0,u=0,f=e.length-1;do{if(a>=f-1)return t0?0:-1}function Hw(n,e){const{nullBitmap:t}=n;if(!t||n.nullCount<=0)return-1;let i=0;for(const a of new Wd(t,n.offset+(e||0),n.length,t,Qg)){if(!a)return i;++i}return-1}function De(n,e,t){if(e===void 0)return-1;if(e===null)switch(n.typeId){case M.Union:break;case M.Dictionary:break;default:return Hw(n,t)}const i=Gt.getVisitFn(n),a=Ti(e);for(let u=(t||0)-1,f=n.length;++u{const a=n.data[i];return a.values.subarray(0,a.length)[Symbol.iterator]()});let t=0;return new jm(n.data.length,i=>{const u=n.data[i].length,f=n.slice(t,t+u);return t+=u,new Gw(f)})}class Gw{constructor(e){this.vector=e,this.index=0}next(){return this.indexh.data):e;if(u.length===0||u.some(h=>!(h instanceof Ye)))throw new TypeError("Vector constructor expects an Array of Data instances.");const f=(t=u[0])===null||t===void 0?void 0:t.type;switch(u.length){case 0:this._offsets=[0];break;case 1:{const{get:h,set:m,indexOf:g}=nv[f.typeId],v=u[0];this.isValid=x=>Gd(v,x),this.get=x=>h(v,x),this.set=(x,b)=>m(v,x,b),this.indexOf=x=>g(v,x),this._offsets=[0,v.length];break}default:Object.setPrototypeOf(this,rv[f.typeId]),this._offsets=Jg(u);break}this.data=u,this.type=f,this.stride=vr(f),this.numChildren=(a=(i=f.children)===null||i===void 0?void 0:i.length)!==null&&a!==void 0?a:0,this.length=this._offsets.at(-1)}get byteLength(){return this.data.reduce((e,t)=>e+t.byteLength,0)}get nullable(){return Vw(this.data)}get nullCount(){return Kg(this.data)}get ArrayType(){return this.type.ArrayType}get[Symbol.toStringTag](){return`${this.VectorName}<${this.type[Symbol.toStringTag]}>`}get VectorName(){return`${M[this.type.typeId]}Vector`}isValid(e){return!1}get(e){return null}at(e){return this.get(Vd(e,this.length))}set(e,t){}indexOf(e,t){return-1}includes(e,t){return this.indexOf(e,t)>-1}[Symbol.iterator](){return Yd.visit(this)}concat(...e){return new Je(this.data.concat(e.flatMap(t=>t.data).flat(Number.POSITIVE_INFINITY)))}slice(e,t){return new Je(Yg(this,e,t,({data:i,_offsets:a},u,f)=>qg(i,a,u,f)))}toJSON(){return[...this]}toArray(){const{type:e,data:t,length:i,stride:a,ArrayType:u}=this;switch(e.typeId){case M.Int:case M.Float:case M.Decimal:case M.Time:case M.Timestamp:switch(t.length){case 0:return new u;case 1:return t[0].values.subarray(0,i*a);default:return t.reduce((f,{values:h,length:m})=>(f.array.set(h.subarray(0,m*a),f.offset),f.offset+=m*a,f),{array:new u(i*a),offset:0}).array}}return[...this]}toString(){return`[${[...this].join(",")}]`}getChild(e){var t;return this.getChildAt((t=this.type.children)===null||t===void 0?void 0:t.findIndex(i=>i.name===e))}getChildAt(e){return e>-1&&et[e])):null}get isMemoized(){return me.isDictionary(this.type)?this.data[0].dictionary.isMemoized:!1}memoize(){if(me.isDictionary(this.type)){const e=new Wl(this.data[0].dictionary),t=this.data.map(i=>{const a=i.clone();return a.dictionary=e,a});return new Je(t)}return new Wl(this)}unmemoize(){if(me.isDictionary(this.type)&&this.isMemoized){const e=this.data[0].dictionary.unmemoize(),t=this.data.map(i=>{const a=i.clone();return a.dictionary=e,a});return new Je(t)}return this}}tv=Symbol.toStringTag;Je[tv]=(n=>{n.type=me.prototype,n.data=[],n.length=0,n.stride=1,n.numChildren=0,n._offsets=new Uint32Array([0]),n[Symbol.isConcatSpreadable]=!0;const e=Object.keys(M).map(t=>M[t]).filter(t=>typeof t=="number"&&t!==M.NONE);for(const t of e){const i=Gt.getVisitFnByTypeId(t),a=vn.getVisitFnByTypeId(t),u=Vl.getVisitFnByTypeId(t);nv[t]={get:i,set:a,indexOf:u},rv[t]=Object.create(n,{isValid:{value:zl(Gd)},get:{value:zl(Gt.getVisitFnByTypeId(t))},set:{value:Zg(vn.getVisitFnByTypeId(t))},indexOf:{value:Xg(Vl.getVisitFnByTypeId(t))}})}return"Vector"})(Je.prototype);class Wl extends Je{constructor(e){super(e.data);const t=this.get,i=this.set,a=this.slice,u=new Array(this.length);Object.defineProperty(this,"get",{value(f){const h=u[f];if(h!==void 0)return h;const m=t.call(this,f);return u[f]=m,m}}),Object.defineProperty(this,"set",{value(f,h){i.call(this,f,h),u[f]=h}}),Object.defineProperty(this,"slice",{value:(f,h)=>new Wl(a.call(this,f,h))}),Object.defineProperty(this,"isMemoized",{value:!0}),Object.defineProperty(this,"unmemoize",{value:()=>new Je(this.data)}),Object.defineProperty(this,"memoize",{value:()=>this})}}class Md{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}offset(){return this.bb.readInt64(this.bb_pos)}metaDataLength(){return this.bb.readInt32(this.bb_pos+8)}bodyLength(){return this.bb.readInt64(this.bb_pos+16)}static sizeOf(){return 24}static createBlock(e,t,i,a){return e.prep(8,24),e.writeInt64(BigInt(a??0)),e.pad(4),e.writeInt32(i),e.writeInt64(BigInt(t??0)),e.offset()}}class Xt{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsFooter(e,t){return(t||new Xt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsFooter(e,t){return e.setPosition(e.position()+He),(t||new Xt).__init(e.readInt32(e.position())+e.position(),e)}version(){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):ht.V1}schema(e){const t=this.bb.__offset(this.bb_pos,6);return t?(e||new Gn).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}dictionaries(e,t){const i=this.bb.__offset(this.bb_pos,8);return i?(t||new Md).__init(this.bb.__vector(this.bb_pos+i)+e*24,this.bb):null}dictionariesLength(){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}recordBatches(e,t){const i=this.bb.__offset(this.bb_pos,10);return i?(t||new Md).__init(this.bb.__vector(this.bb_pos+i)+e*24,this.bb):null}recordBatchesLength(){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,12);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}static startFooter(e){e.startObject(5)}static addVersion(e,t){e.addFieldInt16(0,t,ht.V1)}static addSchema(e,t){e.addFieldOffset(1,t,0)}static addDictionaries(e,t){e.addFieldOffset(2,t,0)}static startDictionariesVector(e,t){e.startVector(24,t,8)}static addRecordBatches(e,t){e.addFieldOffset(3,t,0)}static startRecordBatchesVector(e,t){e.startVector(24,t,8)}static addCustomMetadata(e,t){e.addFieldOffset(4,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endFooter(e){return e.endObject()}static finishFooterBuffer(e,t){e.finish(t)}static finishSizePrefixedFooterBuffer(e,t){e.finish(t,void 0,!0)}}class We{constructor(e=[],t,i,a=ht.V5){this.fields=e||[],this.metadata=t||new Map,i||(i=Dd(this.fields)),this.dictionaries=i,this.metadataVersion=a}get[Symbol.toStringTag](){return"Schema"}get names(){return this.fields.map(e=>e.name)}toString(){return`Schema<{ ${this.fields.map((e,t)=>`${t}: ${e}`).join(", ")} }>`}select(e){const t=new Set(e),i=this.fields.filter(a=>t.has(a.name));return new We(i,this.metadata)}selectAt(e){const t=e.map(i=>this.fields[i]).filter(Boolean);return new We(t,this.metadata)}assign(...e){const t=e[0]instanceof We?e[0]:Array.isArray(e[0])?new We(e[0]):new We(e),i=[...this.fields],a=sl(sl(new Map,this.metadata),t.metadata),u=t.fields.filter(h=>{const m=i.findIndex(g=>g.name===h.name);return~m?(i[m]=h.clone({metadata:sl(sl(new Map,i[m].metadata),h.metadata)}))&&!1:!0}),f=Dd(u,new Map);return new We([...i,...u],a,new Map([...this.dictionaries,...f]))}}We.prototype.fields=null;We.prototype.metadata=null;We.prototype.dictionaries=null;class nt{static new(...e){let[t,i,a,u]=e;return e[0]&&typeof e[0]=="object"&&({name:t}=e[0],i===void 0&&(i=e[0].type),a===void 0&&(a=e[0].nullable),u===void 0&&(u=e[0].metadata)),new nt(`${t}`,i,a,u)}constructor(e,t,i=!1,a){this.name=e,this.type=t,this.nullable=i,this.metadata=a||new Map}get typeId(){return this.type.typeId}get[Symbol.toStringTag](){return"Field"}toString(){return`${this.name}: ${this.type}`}clone(...e){let[t,i,a,u]=e;return!e[0]||typeof e[0]!="object"?[t=this.name,i=this.type,a=this.nullable,u=this.metadata]=e:{name:t=this.name,type:i=this.type,nullable:a=this.nullable,metadata:u=this.metadata}=e[0],nt.new(t,i,a,u)}}nt.prototype.type=null;nt.prototype.name=null;nt.prototype.nullable=null;nt.prototype.metadata=null;function sl(n,e){return new Map([...n||new Map,...e||new Map])}function Dd(n,e=new Map){for(let t=-1,i=n.length;++t0&&Dd(u.children,e)}return e}var Yw=Iy,Qw=ki;class Qd{static decode(e){e=new Qw($e(e));const t=Xt.getRootAsFooter(e),i=We.decode(t.schema(),new Map,t.version());return new Kw(i,t)}static encode(e){const t=new Yw,i=We.encode(t,e.schema);Xt.startRecordBatchesVector(t,e.numRecordBatches);for(const f of[...e.recordBatches()].slice().reverse())Di.encode(t,f);const a=t.endVector();Xt.startDictionariesVector(t,e.numDictionaries);for(const f of[...e.dictionaryBatches()].slice().reverse())Di.encode(t,f);const u=t.endVector();return Xt.startFooter(t),Xt.addSchema(t,i),Xt.addVersion(t,ht.V5),Xt.addRecordBatches(t,a),Xt.addDictionaries(t,u),Xt.finishFooterBuffer(t,Xt.endFooter(t)),t.asUint8Array()}get numRecordBatches(){return this._recordBatches.length}get numDictionaries(){return this._dictionaryBatches.length}constructor(e,t=ht.V5,i,a){this.schema=e,this.version=t,i&&(this._recordBatches=i),a&&(this._dictionaryBatches=a)}*recordBatches(){for(let e,t=-1,i=this.numRecordBatches;++t=0&&e=0&&e=0&&e=0&&ethis._closedPromiseResolve=e)}get closed(){return this._closedPromise}cancel(e){return Fe(this,void 0,void 0,function*(){yield this.return(e)})}write(e){this._ensureOpen()&&(this.resolvers.length<=0?this._values.push(e):this.resolvers.shift().resolve({done:!1,value:e}))}abort(e){this._closedPromiseResolve&&(this.resolvers.length<=0?this._error={error:e}:this.resolvers.shift().reject({done:!0,value:e}))}close(){if(this._closedPromiseResolve){const{resolvers:e}=this;for(;e.length>0;)e.shift().resolve(at);this._closedPromiseResolve(),this._closedPromiseResolve=void 0}}[Symbol.asyncIterator](){return this}toDOMStream(e){return fn.toDOMStream(this._closedPromiseResolve||this._error?this:this._values,e)}toNodeStream(e){return fn.toNodeStream(this._closedPromiseResolve||this._error?this:this._values,e)}throw(e){return Fe(this,void 0,void 0,function*(){return yield this.abort(e),at})}return(e){return Fe(this,void 0,void 0,function*(){return yield this.close(),at})}read(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"read")).value})}peek(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"peek")).value})}next(...e){return this._values.length>0?Promise.resolve({done:!1,value:this._values.shift()}):this._error?Promise.reject({done:!0,value:this._error.error}):this._closedPromiseResolve?new Promise((t,i)=>{this.resolvers.push({resolve:t,reject:i})}):Promise.resolve(at)}_ensureOpen(){if(this._closedPromiseResolve)return!0;throw new Error("AsyncQueue is closed")}}class qw extends Jw{write(e){if((e=$e(e)).byteLength>0)return super.write(e)}toString(e=!1){return e?xd(this.toUint8Array(!0)):this.toUint8Array(!1).then(xd)}toUint8Array(e=!1){return e?tr(this._values)[0]:Fe(this,void 0,void 0,function*(){var t,i,a,u;const f=[];let h=0;try{for(var m=!0,g=xi(this),v;v=yield g.next(),t=v.done,!t;m=!0){u=v.value,m=!1;const x=u;f.push(x),h+=x.byteLength}}catch(x){i={error:x}}finally{try{!m&&!t&&(a=g.return)&&(yield a.call(g))}finally{if(i)throw i.error}}return tr(f,h)[0]})}}class Hl{constructor(e){e&&(this.source=new Zw(fn.fromIterable(e)))}[Symbol.iterator](){return this}next(e){return this.source.next(e)}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}peek(e){return this.source.peek(e)}read(e){return this.source.read(e)}}class Ci{constructor(e){e instanceof Ci?this.source=e.source:e instanceof qw?this.source=new js(fn.fromAsyncIterable(e)):Ny(e)?this.source=new js(fn.fromNodeStream(e)):Rd(e)?this.source=new js(fn.fromDOMStream(e)):Sy(e)?this.source=new js(fn.fromDOMStream(e.body)):nu(e)?this.source=new js(fn.fromIterable(e)):Ao(e)?this.source=new js(fn.fromAsyncIterable(e)):Ed(e)&&(this.source=new js(fn.fromAsyncIterable(e)))}[Symbol.asyncIterator](){return this}next(e){return this.source.next(e)}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}get closed(){return this.source.closed}cancel(e){return this.source.cancel(e)}peek(e){return this.source.peek(e)}read(e){return this.source.read(e)}}class Zw{constructor(e){this.source=e}cancel(e){this.return(e)}peek(e){return this.next(e,"peek").value}read(e){return this.next(e,"read").value}next(e,t="read"){return this.source.next({cmd:t,size:e})}throw(e){return Object.create(this.source.throw&&this.source.throw(e)||at)}return(e){return Object.create(this.source.return&&this.source.return(e)||at)}}class js{constructor(e){this.source=e,this._closedPromise=new Promise(t=>this._closedPromiseResolve=t)}cancel(e){return Fe(this,void 0,void 0,function*(){yield this.return(e)})}get closed(){return this._closedPromise}read(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"read")).value})}peek(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"peek")).value})}next(e){return Fe(this,arguments,void 0,function*(t,i="read"){return yield this.source.next({cmd:i,size:t})})}throw(e){return Fe(this,void 0,void 0,function*(){const t=this.source.throw&&(yield this.source.throw(e))||at;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(t)})}return(e){return Fe(this,void 0,void 0,function*(){const t=this.source.return&&(yield this.source.return(e))||at;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(t)})}}class Im extends Hl{constructor(e,t){super(),this.position=0,this.buffer=$e(e),this.size=t===void 0?this.buffer.byteLength:t}readInt32(e){const{buffer:t,byteOffset:i}=this.readAt(e,4);return new DataView(t,i).getInt32(0,!0)}seek(e){return this.position=Math.min(e,this.size),e>>16,this.buffer[1]&65535,this.buffer[0]>>>16,this.buffer[0]&65535]),i=new Uint32Array([e.buffer[1]>>>16,e.buffer[1]&65535,e.buffer[0]>>>16,e.buffer[0]&65535]);let a=t[3]*i[3];this.buffer[0]=a&65535;let u=a>>>16;return a=t[2]*i[3],u+=a,a=t[3]*i[2]>>>0,u+=a,this.buffer[0]+=u<<16,this.buffer[1]=u>>>0>>16,this.buffer[1]+=t[1]*i[3]+t[2]*i[2]+t[3]*i[1],this.buffer[1]+=t[0]*i[3]+t[1]*i[2]+t[2]*i[1]+t[3]*i[0]<<16,this}_plus(e){const t=this.buffer[0]+e.buffer[0]>>>0;this.buffer[1]+=e.buffer[1],t>>0&&++this.buffer[1],this.buffer[0]=t}lessThan(e){return this.buffer[1]>>0,t[2]=this.buffer[2]+e.buffer[2]>>>0,t[1]=this.buffer[1]+e.buffer[1]>>>0,t[0]=this.buffer[0]+e.buffer[0]>>>0,t[0]>>0&&++t[1],t[1]>>0&&++t[2],t[2]>>0&&++t[3],this.buffer[3]=t[3],this.buffer[2]=t[2],this.buffer[1]=t[1],this.buffer[0]=t[0],this}hex(){return`${vi(this.buffer[3])} ${vi(this.buffer[2])} ${vi(this.buffer[1])} ${vi(this.buffer[0])}`}static multiply(e,t){return new Yn(new Uint32Array(e.buffer)).times(t)}static add(e,t){return new Yn(new Uint32Array(e.buffer)).plus(t)}static from(e,t=new Uint32Array(4)){return Yn.fromString(typeof e=="string"?e:e.toString(),t)}static fromNumber(e,t=new Uint32Array(4)){return Yn.fromString(e.toString(),t)}static fromString(e,t=new Uint32Array(4)){const i=e.startsWith("-"),a=e.length,u=new Yn(t);for(let f=i?1:0;f0&&this.readData(e,i)||new Uint8Array(0)}readOffsets(e,t){return this.readData(e,t)}readTypeIds(e,t){return this.readData(e,t)}readData(e,{length:t,offset:i}=this.nextBufferRange()){return this.bytes.subarray(i,i+t)}readDictionary(e){return this.dictionaries.get(e.id)}}class e1 extends ov{constructor(e,t,i,a,u){super(new Uint8Array(0),t,i,a,u),this.sources=e}readNullBitmap(e,t,{offset:i}=this.nextBufferRange()){return t<=0?new Uint8Array(0):kd(this.sources[i])}readOffsets(e,{offset:t}=this.nextBufferRange()){return Ke(Uint8Array,Ke(e.OffsetArrayType,this.sources[t]))}readTypeIds(e,{offset:t}=this.nextBufferRange()){return Ke(Uint8Array,Ke(e.ArrayType,this.sources[t]))}readData(e,{offset:t}=this.nextBufferRange()){const{sources:i}=this;return me.isTimestamp(e)||(me.isInt(e)||me.isTime(e))&&e.bitWidth===64||me.isDuration(e)||me.isDate(e)&&e.unit===gn.MILLISECOND?Ke(Uint8Array,zt.convertArray(i[t])):me.isDecimal(e)?Ke(Uint8Array,Yn.convertArray(i[t])):me.isBinary(e)||me.isLargeBinary(e)||me.isFixedSizeBinary(e)?t1(i[t]):me.isBool(e)?kd(i[t]):me.isUtf8(e)||me.isLargeUtf8(e)?Bd(i[t].join("")):Ke(Uint8Array,Ke(e.ArrayType,i[t].map(a=>+a)))}}function t1(n){const e=n.join(""),t=new Uint8Array(e.length/2);for(let i=0;i>1]=Number.parseInt(e.slice(i,i+2),16);return t}class we extends Re{compareSchemas(e,t){return e===t||t instanceof e.constructor&&this.compareManyFields(e.fields,t.fields)}compareManyFields(e,t){return e===t||Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>this.compareFields(i,t[a]))}compareFields(e,t){return e===t||t instanceof e.constructor&&e.name===t.name&&e.nullable===t.nullable&&this.visit(e.type,t.type)}}function At(n,e){return e instanceof n.constructor}function As(n,e){return n===e||At(n,e)}function Mr(n,e){return n===e||At(n,e)&&n.bitWidth===e.bitWidth&&n.isSigned===e.isSigned}function su(n,e){return n===e||At(n,e)&&n.precision===e.precision}function n1(n,e){return n===e||At(n,e)&&n.byteWidth===e.byteWidth}function Jd(n,e){return n===e||At(n,e)&&n.unit===e.unit}function Po(n,e){return n===e||At(n,e)&&n.unit===e.unit&&n.timezone===e.timezone}function zo(n,e){return n===e||At(n,e)&&n.unit===e.unit&&n.bitWidth===e.bitWidth}function r1(n,e){return n===e||At(n,e)&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}function s1(n,e){return n===e||At(n,e)&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}function qd(n,e){return n===e||At(n,e)&&n.mode===e.mode&&n.typeIds.every((t,i)=>t===e.typeIds[i])&&is.compareManyFields(n.children,e.children)}function i1(n,e){return n===e||At(n,e)&&n.id===e.id&&n.isOrdered===e.isOrdered&&is.visit(n.indices,e.indices)&&is.visit(n.dictionary,e.dictionary)}function Zd(n,e){return n===e||At(n,e)&&n.unit===e.unit}function Vo(n,e){return n===e||At(n,e)&&n.unit===e.unit}function o1(n,e){return n===e||At(n,e)&&n.listSize===e.listSize&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}function a1(n,e){return n===e||At(n,e)&&n.keysSorted===e.keysSorted&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}we.prototype.visitNull=As;we.prototype.visitBool=As;we.prototype.visitInt=Mr;we.prototype.visitInt8=Mr;we.prototype.visitInt16=Mr;we.prototype.visitInt32=Mr;we.prototype.visitInt64=Mr;we.prototype.visitUint8=Mr;we.prototype.visitUint16=Mr;we.prototype.visitUint32=Mr;we.prototype.visitUint64=Mr;we.prototype.visitFloat=su;we.prototype.visitFloat16=su;we.prototype.visitFloat32=su;we.prototype.visitFloat64=su;we.prototype.visitUtf8=As;we.prototype.visitLargeUtf8=As;we.prototype.visitBinary=As;we.prototype.visitLargeBinary=As;we.prototype.visitFixedSizeBinary=n1;we.prototype.visitDate=Jd;we.prototype.visitDateDay=Jd;we.prototype.visitDateMillisecond=Jd;we.prototype.visitTimestamp=Po;we.prototype.visitTimestampSecond=Po;we.prototype.visitTimestampMillisecond=Po;we.prototype.visitTimestampMicrosecond=Po;we.prototype.visitTimestampNanosecond=Po;we.prototype.visitTime=zo;we.prototype.visitTimeSecond=zo;we.prototype.visitTimeMillisecond=zo;we.prototype.visitTimeMicrosecond=zo;we.prototype.visitTimeNanosecond=zo;we.prototype.visitDecimal=As;we.prototype.visitList=r1;we.prototype.visitStruct=s1;we.prototype.visitUnion=qd;we.prototype.visitDenseUnion=qd;we.prototype.visitSparseUnion=qd;we.prototype.visitDictionary=i1;we.prototype.visitInterval=Zd;we.prototype.visitIntervalDayTime=Zd;we.prototype.visitIntervalYearMonth=Zd;we.prototype.visitDuration=Vo;we.prototype.visitDurationSecond=Vo;we.prototype.visitDurationMillisecond=Vo;we.prototype.visitDurationMicrosecond=Vo;we.prototype.visitDurationNanosecond=Vo;we.prototype.visitFixedSizeList=o1;we.prototype.visitMap=a1;const is=new we;function l1(n,e){return is.compareSchemas(n,e)}function od(n,e){return u1(n,e.map(t=>t.data.concat()))}function u1(n,e){const t=[...n.fields],i=[],a={numBatches:e.reduce((x,b)=>Math.max(x,b.length),0)};let u=0,f=0,h=-1;const m=e.length;let g,v=[];for(;a.numBatches-- >0;){for(f=Number.POSITIVE_INFINITY,h=-1;++h0&&(i[u++]=Ee({type:new Tt(t),length:f,nullCount:0,children:v.slice()})))}return[n=n.assign(t),i.map(x=>new An(n,x))]}function c1(n,e,t,i,a){var u;const f=(e+63&-64)>>3;for(let h=-1,m=i.length;++h=e)v===e?t[h]=g:(t[h]=g.slice(0,e),a.numBatches=Math.max(a.numBatches,i[h].unshift(g.slice(e,v-e))));else{const x=n[h];n[h]=x.clone({nullable:!0}),t[h]=(u=g==null?void 0:g._changeLengthAndBackfillNullBitmap(e))!==null&&u!==void 0?u:Ee({type:x.type,length:e,nullCount:e,nullBitmap:new Uint8Array(f)})}}return t}var av;class mn{constructor(...e){var t,i;if(e.length===0)return this.batches=[],this.schema=new We([]),this._offsets=[0],this;let a,u;e[0]instanceof We&&(a=e.shift()),e.at(-1)instanceof Uint32Array&&(u=e.pop());const f=m=>{if(m){if(m instanceof An)return[m];if(m instanceof mn)return m.batches;if(m instanceof Ye){if(m.type instanceof Tt)return[new An(new We(m.type.children),m)]}else{if(Array.isArray(m))return m.flatMap(g=>f(g));if(typeof m[Symbol.iterator]=="function")return[...m].flatMap(g=>f(g));if(typeof m=="object"){const g=Object.keys(m),v=g.map(w=>new Je([m[w]])),x=a??new We(g.map((w,j)=>new nt(String(w),v[j].type,v[j].nullable))),[,b]=od(x,v);return b.length===0?[new An(m)]:b}}}return[]},h=e.flatMap(m=>f(m));if(a=(i=a??((t=h[0])===null||t===void 0?void 0:t.schema))!==null&&i!==void 0?i:new We([]),!(a instanceof We))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");for(const m of h){if(!(m instanceof An))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");if(!l1(a,m.schema))throw new TypeError("Table and inner RecordBatch schemas must be equivalent.")}this.schema=a,this.batches=h,this._offsets=u??Jg(this.data)}get data(){return this.batches.map(({data:e})=>e)}get numCols(){return this.schema.fields.length}get numRows(){return this.data.reduce((e,t)=>e+t.length,0)}get nullCount(){return this._nullCount===-1&&(this._nullCount=Kg(this.data)),this._nullCount}isValid(e){return!1}get(e){return null}at(e){return this.get(Vd(e,this.numRows))}set(e,t){}indexOf(e,t){return-1}[Symbol.iterator](){return this.batches.length>0?Yd.visit(new Je(this.data)):new Array(0)[Symbol.iterator]()}toArray(){return[...this]}toString(){return`[ +`+p.stack}return{value:r,source:s,stack:d,digest:null}}function bc(r,s,o){return{value:r,source:null,stack:o??null,digest:s??null}}function wc(r,s){try{console.error(s.value)}catch(o){setTimeout(function(){throw o})}}var Cx=typeof WeakMap=="function"?WeakMap:Map;function lp(r,s,o){o=dr(-1,o),o.tag=3,o.payload={element:null};var l=s.value;return o.callback=function(){Pa||(Pa=!0,Ec=l),wc(r,s)},o}function up(r,s,o){o=dr(-1,o),o.tag=3;var l=r.type.getDerivedStateFromError;if(typeof l=="function"){var d=s.value;o.payload=function(){return l(d)},o.callback=function(){wc(r,s)}}var p=r.stateNode;return p!==null&&typeof p.componentDidCatch=="function"&&(o.callback=function(){wc(r,s),typeof l!="function"&&(Hr===null?Hr=new Set([this]):Hr.add(this));var y=s.stack;this.componentDidCatch(s.value,{componentStack:y!==null?y:""})}),o}function cp(r,s,o){var l=r.pingCache;if(l===null){l=r.pingCache=new Cx;var d=new Set;l.set(s,d)}else d=l.get(s),d===void 0&&(d=new Set,l.set(s,d));d.has(o)||(d.add(o),r=Wx.bind(null,r,s,o),s.then(r,r))}function dp(r){do{var s;if((s=r.tag===13)&&(s=r.memoizedState,s=s!==null?s.dehydrated!==null:!0),s)return r;r=r.return}while(r!==null);return null}function fp(r,s,o,l,d){return(r.mode&1)===0?(r===s?r.flags|=65536:(r.flags|=128,o.flags|=131072,o.flags&=-52805,o.tag===1&&(o.alternate===null?o.tag=17:(s=dr(-1,1),s.tag=2,Vr(o,s,1))),o.lanes|=1),r):(r.flags|=65536,r.lanes=d,r)}var Fx=T.ReactCurrentOwner,Rt=!1;function Ct(r,s,o,l){s.child=r===null?Oh(s,null,o,l):Zs(s,r.child,o,l)}function hp(r,s,o,l,d){o=o.render;var p=s.ref;return ei(s,d),l=fc(r,s,o,l,p,d),o=hc(),r!==null&&!Rt?(s.updateQueue=r.updateQueue,s.flags&=-2053,r.lanes&=~d,fr(r,s,d)):(st&&o&&Ku(s),s.flags|=1,Ct(r,s,l,d),s.child)}function pp(r,s,o,l,d){if(r===null){var p=o.type;return typeof p=="function"&&!Vc(p)&&p.defaultProps===void 0&&o.compare===null&&o.defaultProps===void 0?(s.tag=15,s.type=p,mp(r,s,p,l,d)):(r=Ya(o.type,null,l,s,s.mode,d),r.ref=s.ref,r.return=s,s.child=r)}if(p=r.child,(r.lanes&d)===0){var y=p.memoizedProps;if(o=o.compare,o=o!==null?o:Xi,o(y,l)&&r.ref===s.ref)return fr(r,s,d)}return s.flags|=1,r=Kr(p,l),r.ref=s.ref,r.return=s,s.child=r}function mp(r,s,o,l,d){if(r!==null){var p=r.memoizedProps;if(Xi(p,l)&&r.ref===s.ref)if(Rt=!1,s.pendingProps=l=p,(r.lanes&d)!==0)(r.flags&131072)!==0&&(Rt=!0);else return s.lanes=r.lanes,fr(r,s,d)}return Sc(r,s,o,l,d)}function yp(r,s,o){var l=s.pendingProps,d=l.children,p=r!==null?r.memoizedState:null;if(l.mode==="hidden")if((s.mode&1)===0)s.memoizedState={baseLanes:0,cachePool:null,transitions:null},qe(si,Jt),Jt|=o;else{if((o&1073741824)===0)return r=p!==null?p.baseLanes|o:o,s.lanes=s.childLanes=1073741824,s.memoizedState={baseLanes:r,cachePool:null,transitions:null},s.updateQueue=null,qe(si,Jt),Jt|=r,null;s.memoizedState={baseLanes:0,cachePool:null,transitions:null},l=p!==null?p.baseLanes:o,qe(si,Jt),Jt|=l}else p!==null?(l=p.baseLanes|o,s.memoizedState=null):l=o,qe(si,Jt),Jt|=l;return Ct(r,s,d,o),s.child}function gp(r,s){var o=s.ref;(r===null&&o!==null||r!==null&&r.ref!==o)&&(s.flags|=512,s.flags|=2097152)}function Sc(r,s,o,l,d){var p=Et(o)?ps:jt.current;return p=Qs(s,p),ei(s,d),o=fc(r,s,o,l,p,d),l=hc(),r!==null&&!Rt?(s.updateQueue=r.updateQueue,s.flags&=-2053,r.lanes&=~d,fr(r,s,d)):(st&&l&&Ku(s),s.flags|=1,Ct(r,s,o,d),s.child)}function vp(r,s,o,l,d){if(Et(o)){var p=!0;va(s)}else p=!1;if(ei(s,d),s.stateNode===null)Ea(r,s),op(s,o,l),xc(s,o,l,d),l=!0;else if(r===null){var y=s.stateNode,S=s.memoizedProps;y.props=S;var N=y.context,P=o.contextType;typeof P=="object"&&P!==null?P=sn(P):(P=Et(o)?ps:jt.current,P=Qs(s,P));var J=o.getDerivedStateFromProps,q=typeof J=="function"||typeof y.getSnapshotBeforeUpdate=="function";q||typeof y.UNSAFE_componentWillReceiveProps!="function"&&typeof y.componentWillReceiveProps!="function"||(S!==l||N!==P)&&ap(s,y,l,P),zr=!1;var K=s.memoizedState;y.state=K,Ia(s,l,y,d),N=s.memoizedState,S!==l||K!==N||Bt.current||zr?(typeof J=="function"&&(vc(s,o,J,l),N=s.memoizedState),(S=zr||ip(s,o,S,l,K,N,P))?(q||typeof y.UNSAFE_componentWillMount!="function"&&typeof y.componentWillMount!="function"||(typeof y.componentWillMount=="function"&&y.componentWillMount(),typeof y.UNSAFE_componentWillMount=="function"&&y.UNSAFE_componentWillMount()),typeof y.componentDidMount=="function"&&(s.flags|=4194308)):(typeof y.componentDidMount=="function"&&(s.flags|=4194308),s.memoizedProps=l,s.memoizedState=N),y.props=l,y.state=N,y.context=P,l=S):(typeof y.componentDidMount=="function"&&(s.flags|=4194308),l=!1)}else{y=s.stateNode,Ah(r,s),S=s.memoizedProps,P=s.type===s.elementType?S:Nn(s.type,S),y.props=P,q=s.pendingProps,K=y.context,N=o.contextType,typeof N=="object"&&N!==null?N=sn(N):(N=Et(o)?ps:jt.current,N=Qs(s,N));var oe=o.getDerivedStateFromProps;(J=typeof oe=="function"||typeof y.getSnapshotBeforeUpdate=="function")||typeof y.UNSAFE_componentWillReceiveProps!="function"&&typeof y.componentWillReceiveProps!="function"||(S!==q||K!==N)&&ap(s,y,l,N),zr=!1,K=s.memoizedState,y.state=K,Ia(s,l,y,d);var ce=s.memoizedState;S!==q||K!==ce||Bt.current||zr?(typeof oe=="function"&&(vc(s,o,oe,l),ce=s.memoizedState),(P=zr||ip(s,o,P,l,K,ce,N)||!1)?(J||typeof y.UNSAFE_componentWillUpdate!="function"&&typeof y.componentWillUpdate!="function"||(typeof y.componentWillUpdate=="function"&&y.componentWillUpdate(l,ce,N),typeof y.UNSAFE_componentWillUpdate=="function"&&y.UNSAFE_componentWillUpdate(l,ce,N)),typeof y.componentDidUpdate=="function"&&(s.flags|=4),typeof y.getSnapshotBeforeUpdate=="function"&&(s.flags|=1024)):(typeof y.componentDidUpdate!="function"||S===r.memoizedProps&&K===r.memoizedState||(s.flags|=4),typeof y.getSnapshotBeforeUpdate!="function"||S===r.memoizedProps&&K===r.memoizedState||(s.flags|=1024),s.memoizedProps=l,s.memoizedState=ce),y.props=l,y.state=ce,y.context=N,l=P):(typeof y.componentDidUpdate!="function"||S===r.memoizedProps&&K===r.memoizedState||(s.flags|=4),typeof y.getSnapshotBeforeUpdate!="function"||S===r.memoizedProps&&K===r.memoizedState||(s.flags|=1024),l=!1)}return _c(r,s,o,l,p,d)}function _c(r,s,o,l,d,p){gp(r,s);var y=(s.flags&128)!==0;if(!l&&!y)return d&&_h(s,o,!1),fr(r,s,p);l=s.stateNode,Fx.current=s;var S=y&&typeof o.getDerivedStateFromError!="function"?null:l.render();return s.flags|=1,r!==null&&y?(s.child=Zs(s,r.child,null,p),s.child=Zs(s,null,S,p)):Ct(r,s,S,p),s.memoizedState=l.state,d&&_h(s,o,!0),s.child}function xp(r){var s=r.stateNode;s.pendingContext?wh(r,s.pendingContext,s.pendingContext!==s.context):s.context&&wh(r,s.context,!1),oc(r,s.containerInfo)}function bp(r,s,o,l,d){return qs(),Xu(d),s.flags|=256,Ct(r,s,o,l),s.child}var Nc={dehydrated:null,treeContext:null,retryLane:0};function jc(r){return{baseLanes:r,cachePool:null,transitions:null}}function wp(r,s,o){var l=s.pendingProps,d=it.current,p=!1,y=(s.flags&128)!==0,S;if((S=y)||(S=r!==null&&r.memoizedState===null?!1:(d&2)!==0),S?(p=!0,s.flags&=-129):(r===null||r.memoizedState!==null)&&(d|=1),qe(it,d&1),r===null)return Zu(s),r=s.memoizedState,r!==null&&(r=r.dehydrated,r!==null)?((s.mode&1)===0?s.lanes=1:r.data==="$!"?s.lanes=8:s.lanes=1073741824,null):(y=l.children,r=l.fallback,p?(l=s.mode,p=s.child,y={mode:"hidden",children:y},(l&1)===0&&p!==null?(p.childLanes=0,p.pendingProps=y):p=Qa(y,l,0,null),r=Ns(r,l,o,null),p.return=s,r.return=s,p.sibling=r,s.child=p,s.child.memoizedState=jc(o),s.memoizedState=Nc,r):kc(s,y));if(d=r.memoizedState,d!==null&&(S=d.dehydrated,S!==null))return Ox(r,s,y,l,S,d,o);if(p){p=l.fallback,y=s.mode,d=r.child,S=d.sibling;var N={mode:"hidden",children:l.children};return(y&1)===0&&s.child!==d?(l=s.child,l.childLanes=0,l.pendingProps=N,s.deletions=null):(l=Kr(d,N),l.subtreeFlags=d.subtreeFlags&14680064),S!==null?p=Kr(S,p):(p=Ns(p,y,o,null),p.flags|=2),p.return=s,l.return=s,l.sibling=p,s.child=l,l=p,p=s.child,y=r.child.memoizedState,y=y===null?jc(o):{baseLanes:y.baseLanes|o,cachePool:null,transitions:y.transitions},p.memoizedState=y,p.childLanes=r.childLanes&~o,s.memoizedState=Nc,l}return p=r.child,r=p.sibling,l=Kr(p,{mode:"visible",children:l.children}),(s.mode&1)===0&&(l.lanes=o),l.return=s,l.sibling=null,r!==null&&(o=s.deletions,o===null?(s.deletions=[r],s.flags|=16):o.push(r)),s.child=l,s.memoizedState=null,l}function kc(r,s){return s=Qa({mode:"visible",children:s},r.mode,0,null),s.return=r,r.child=s}function Ba(r,s,o,l){return l!==null&&Xu(l),Zs(s,r.child,null,o),r=kc(s,s.pendingProps.children),r.flags|=2,s.memoizedState=null,r}function Ox(r,s,o,l,d,p,y){if(o)return s.flags&256?(s.flags&=-257,l=bc(Error(t(422))),Ba(r,s,y,l)):s.memoizedState!==null?(s.child=r.child,s.flags|=128,null):(p=l.fallback,d=s.mode,l=Qa({mode:"visible",children:l.children},d,0,null),p=Ns(p,d,y,null),p.flags|=2,l.return=s,p.return=s,l.sibling=p,s.child=l,(s.mode&1)!==0&&Zs(s,r.child,null,y),s.child.memoizedState=jc(y),s.memoizedState=Nc,p);if((s.mode&1)===0)return Ba(r,s,y,null);if(d.data==="$!"){if(l=d.nextSibling&&d.nextSibling.dataset,l)var S=l.dgst;return l=S,p=Error(t(419)),l=bc(p,l,void 0),Ba(r,s,y,l)}if(S=(y&r.childLanes)!==0,Rt||S){if(l=xt,l!==null){switch(y&-y){case 4:d=2;break;case 16:d=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:d=32;break;case 536870912:d=268435456;break;default:d=0}d=(d&(l.suspendedLanes|y))!==0?0:d,d!==0&&d!==p.retryLane&&(p.retryLane=d,cr(r,d),In(l,r,d,-1))}return zc(),l=bc(Error(t(421))),Ba(r,s,y,l)}return d.data==="$?"?(s.flags|=128,s.child=r.child,s=Hx.bind(null,r),d._reactRetry=s,null):(r=p.treeContext,Kt=Lr(d.nextSibling),Qt=s,st=!0,_n=null,r!==null&&(nn[rn++]=lr,nn[rn++]=ur,nn[rn++]=ms,lr=r.id,ur=r.overflow,ms=s),s=kc(s,l.children),s.flags|=4096,s)}function Sp(r,s,o){r.lanes|=s;var l=r.alternate;l!==null&&(l.lanes|=s),rc(r.return,s,o)}function Ic(r,s,o,l,d){var p=r.memoizedState;p===null?r.memoizedState={isBackwards:s,rendering:null,renderingStartTime:0,last:l,tail:o,tailMode:d}:(p.isBackwards=s,p.rendering=null,p.renderingStartTime=0,p.last=l,p.tail=o,p.tailMode=d)}function _p(r,s,o){var l=s.pendingProps,d=l.revealOrder,p=l.tail;if(Ct(r,s,l.children,o),l=it.current,(l&2)!==0)l=l&1|2,s.flags|=128;else{if(r!==null&&(r.flags&128)!==0)e:for(r=s.child;r!==null;){if(r.tag===13)r.memoizedState!==null&&Sp(r,o,s);else if(r.tag===19)Sp(r,o,s);else if(r.child!==null){r.child.return=r,r=r.child;continue}if(r===s)break e;for(;r.sibling===null;){if(r.return===null||r.return===s)break e;r=r.return}r.sibling.return=r.return,r=r.sibling}l&=1}if(qe(it,l),(s.mode&1)===0)s.memoizedState=null;else switch(d){case"forwards":for(o=s.child,d=null;o!==null;)r=o.alternate,r!==null&&Ma(r)===null&&(d=o),o=o.sibling;o=d,o===null?(d=s.child,s.child=null):(d=o.sibling,o.sibling=null),Ic(s,!1,d,o,p);break;case"backwards":for(o=null,d=s.child,s.child=null;d!==null;){if(r=d.alternate,r!==null&&Ma(r)===null){s.child=d;break}r=d.sibling,d.sibling=o,o=d,d=r}Ic(s,!0,o,null,p);break;case"together":Ic(s,!1,null,null,void 0);break;default:s.memoizedState=null}return s.child}function Ea(r,s){(s.mode&1)===0&&r!==null&&(r.alternate=null,s.alternate=null,s.flags|=2)}function fr(r,s,o){if(r!==null&&(s.dependencies=r.dependencies),bs|=s.lanes,(o&s.childLanes)===0)return null;if(r!==null&&s.child!==r.child)throw Error(t(153));if(s.child!==null){for(r=s.child,o=Kr(r,r.pendingProps),s.child=o,o.return=s;r.sibling!==null;)r=r.sibling,o=o.sibling=Kr(r,r.pendingProps),o.return=s;o.sibling=null}return s.child}function Tx(r,s,o){switch(s.tag){case 3:xp(s),qs();break;case 5:Rh(s);break;case 1:Et(s.type)&&va(s);break;case 4:oc(s,s.stateNode.containerInfo);break;case 10:var l=s.type._context,d=s.memoizedProps.value;qe(Na,l._currentValue),l._currentValue=d;break;case 13:if(l=s.memoizedState,l!==null)return l.dehydrated!==null?(qe(it,it.current&1),s.flags|=128,null):(o&s.child.childLanes)!==0?wp(r,s,o):(qe(it,it.current&1),r=fr(r,s,o),r!==null?r.sibling:null);qe(it,it.current&1);break;case 19:if(l=(o&s.childLanes)!==0,(r.flags&128)!==0){if(l)return _p(r,s,o);s.flags|=128}if(d=s.memoizedState,d!==null&&(d.rendering=null,d.tail=null,d.lastEffect=null),qe(it,it.current),l)break;return null;case 22:case 23:return s.lanes=0,yp(r,s,o)}return fr(r,s,o)}var Np,Mc,jp,kp;Np=function(r,s){for(var o=s.child;o!==null;){if(o.tag===5||o.tag===6)r.appendChild(o.stateNode);else if(o.tag!==4&&o.child!==null){o.child.return=o,o=o.child;continue}if(o===s)break;for(;o.sibling===null;){if(o.return===null||o.return===s)return;o=o.return}o.sibling.return=o.return,o=o.sibling}},Mc=function(){},jp=function(r,s,o,l){var d=r.memoizedProps;if(d!==l){r=s.stateNode,vs(zn.current);var p=null;switch(o){case"input":d=Cr(r,d),l=Cr(r,l),p=[];break;case"select":d=W({},d,{value:void 0}),l=W({},l,{value:void 0}),p=[];break;case"textarea":d=Es(r,d),l=Es(r,l),p=[];break;default:typeof d.onClick!="function"&&typeof l.onClick=="function"&&(r.onclick=ma)}lu(o,l);var y;o=null;for(P in d)if(!l.hasOwnProperty(P)&&d.hasOwnProperty(P)&&d[P]!=null)if(P==="style"){var S=d[P];for(y in S)S.hasOwnProperty(y)&&(o||(o={}),o[y]="")}else P!=="dangerouslySetInnerHTML"&&P!=="children"&&P!=="suppressContentEditableWarning"&&P!=="suppressHydrationWarning"&&P!=="autoFocus"&&(a.hasOwnProperty(P)?p||(p=[]):(p=p||[]).push(P,null));for(P in l){var N=l[P];if(S=d!=null?d[P]:void 0,l.hasOwnProperty(P)&&N!==S&&(N!=null||S!=null))if(P==="style")if(S){for(y in S)!S.hasOwnProperty(y)||N&&N.hasOwnProperty(y)||(o||(o={}),o[y]="");for(y in N)N.hasOwnProperty(y)&&S[y]!==N[y]&&(o||(o={}),o[y]=N[y])}else o||(p||(p=[]),p.push(P,o)),o=N;else P==="dangerouslySetInnerHTML"?(N=N?N.__html:void 0,S=S?S.__html:void 0,N!=null&&S!==N&&(p=p||[]).push(P,N)):P==="children"?typeof N!="string"&&typeof N!="number"||(p=p||[]).push(P,""+N):P!=="suppressContentEditableWarning"&&P!=="suppressHydrationWarning"&&(a.hasOwnProperty(P)?(N!=null&&P==="onScroll"&&Xe("scroll",r),p||S===N||(p=[])):(p=p||[]).push(P,N))}o&&(p=p||[]).push("style",o);var P=p;(s.updateQueue=P)&&(s.flags|=4)}},kp=function(r,s,o,l){o!==l&&(s.flags|=4)};function mo(r,s){if(!st)switch(r.tailMode){case"hidden":s=r.tail;for(var o=null;s!==null;)s.alternate!==null&&(o=s),s=s.sibling;o===null?r.tail=null:o.sibling=null;break;case"collapsed":o=r.tail;for(var l=null;o!==null;)o.alternate!==null&&(l=o),o=o.sibling;l===null?s||r.tail===null?r.tail=null:r.tail.sibling=null:l.sibling=null}}function It(r){var s=r.alternate!==null&&r.alternate.child===r.child,o=0,l=0;if(s)for(var d=r.child;d!==null;)o|=d.lanes|d.childLanes,l|=d.subtreeFlags&14680064,l|=d.flags&14680064,d.return=r,d=d.sibling;else for(d=r.child;d!==null;)o|=d.lanes|d.childLanes,l|=d.subtreeFlags,l|=d.flags,d.return=r,d=d.sibling;return r.subtreeFlags|=l,r.childLanes=o,s}function Ax(r,s,o){var l=s.pendingProps;switch(Ju(s),s.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return It(s),null;case 1:return Et(s.type)&&ga(),It(s),null;case 3:return l=s.stateNode,ti(),et(Bt),et(jt),uc(),l.pendingContext&&(l.context=l.pendingContext,l.pendingContext=null),(r===null||r.child===null)&&(Sa(s)?s.flags|=4:r===null||r.memoizedState.isDehydrated&&(s.flags&256)===0||(s.flags|=1024,_n!==null&&(Uc(_n),_n=null))),Mc(r,s),It(s),null;case 5:ac(s);var d=vs(uo.current);if(o=s.type,r!==null&&s.stateNode!=null)jp(r,s,o,l,d),r.ref!==s.ref&&(s.flags|=512,s.flags|=2097152);else{if(!l){if(s.stateNode===null)throw Error(t(166));return It(s),null}if(r=vs(zn.current),Sa(s)){l=s.stateNode,o=s.type;var p=s.memoizedProps;switch(l[Pn]=s,l[so]=p,r=(s.mode&1)!==0,o){case"dialog":Xe("cancel",l),Xe("close",l);break;case"iframe":case"object":case"embed":Xe("load",l);break;case"video":case"audio":for(d=0;d<\/script>",r=r.removeChild(r.firstChild)):typeof l.is=="string"?r=y.createElement(o,{is:l.is}):(r=y.createElement(o),o==="select"&&(y=r,l.multiple?y.multiple=!0:l.size&&(y.size=l.size))):r=y.createElementNS(r,o),r[Pn]=s,r[so]=l,Np(r,s,!1,!1),s.stateNode=r;e:{switch(y=uu(o,l),o){case"dialog":Xe("cancel",r),Xe("close",r),d=l;break;case"iframe":case"object":case"embed":Xe("load",r),d=l;break;case"video":case"audio":for(d=0;dii&&(s.flags|=128,l=!0,mo(p,!1),s.lanes=4194304)}else{if(!l)if(r=Ma(y),r!==null){if(s.flags|=128,l=!0,o=r.updateQueue,o!==null&&(s.updateQueue=o,s.flags|=4),mo(p,!0),p.tail===null&&p.tailMode==="hidden"&&!y.alternate&&!st)return It(s),null}else 2*ct()-p.renderingStartTime>ii&&o!==1073741824&&(s.flags|=128,l=!0,mo(p,!1),s.lanes=4194304);p.isBackwards?(y.sibling=s.child,s.child=y):(o=p.last,o!==null?o.sibling=y:s.child=y,p.last=y)}return p.tail!==null?(s=p.tail,p.rendering=s,p.tail=s.sibling,p.renderingStartTime=ct(),s.sibling=null,o=it.current,qe(it,l?o&1|2:o&1),s):(It(s),null);case 22:case 23:return Pc(),l=s.memoizedState!==null,r!==null&&r.memoizedState!==null!==l&&(s.flags|=8192),l&&(s.mode&1)!==0?(Jt&1073741824)!==0&&(It(s),s.subtreeFlags&6&&(s.flags|=8192)):It(s),null;case 24:return null;case 25:return null}throw Error(t(156,s.tag))}function Bx(r,s){switch(Ju(s),s.tag){case 1:return Et(s.type)&&ga(),r=s.flags,r&65536?(s.flags=r&-65537|128,s):null;case 3:return ti(),et(Bt),et(jt),uc(),r=s.flags,(r&65536)!==0&&(r&128)===0?(s.flags=r&-65537|128,s):null;case 5:return ac(s),null;case 13:if(et(it),r=s.memoizedState,r!==null&&r.dehydrated!==null){if(s.alternate===null)throw Error(t(340));qs()}return r=s.flags,r&65536?(s.flags=r&-65537|128,s):null;case 19:return et(it),null;case 4:return ti(),null;case 10:return nc(s.type._context),null;case 22:case 23:return Pc(),null;case 24:return null;default:return null}}var Ra=!1,Mt=!1,Ex=typeof WeakSet=="function"?WeakSet:Set,le=null;function ri(r,s){var o=r.ref;if(o!==null)if(typeof o=="function")try{o(null)}catch(l){ut(r,s,l)}else o.current=null}function Dc(r,s,o){try{o()}catch(l){ut(r,s,l)}}var Ip=!1;function Rx(r,s){if(Pu=ra,r=ih(),Tu(r)){if("selectionStart"in r)var o={start:r.selectionStart,end:r.selectionEnd};else e:{o=(o=r.ownerDocument)&&o.defaultView||window;var l=o.getSelection&&o.getSelection();if(l&&l.rangeCount!==0){o=l.anchorNode;var d=l.anchorOffset,p=l.focusNode;l=l.focusOffset;try{o.nodeType,p.nodeType}catch{o=null;break e}var y=0,S=-1,N=-1,P=0,J=0,q=r,K=null;t:for(;;){for(var oe;q!==o||d!==0&&q.nodeType!==3||(S=y+d),q!==p||l!==0&&q.nodeType!==3||(N=y+l),q.nodeType===3&&(y+=q.nodeValue.length),(oe=q.firstChild)!==null;)K=q,q=oe;for(;;){if(q===r)break t;if(K===o&&++P===d&&(S=y),K===p&&++J===l&&(N=y),(oe=q.nextSibling)!==null)break;q=K,K=q.parentNode}q=oe}o=S===-1||N===-1?null:{start:S,end:N}}else o=null}o=o||{start:0,end:0}}else o=null;for(zu={focusedElem:r,selectionRange:o},ra=!1,le=s;le!==null;)if(s=le,r=s.child,(s.subtreeFlags&1028)!==0&&r!==null)r.return=s,le=r;else for(;le!==null;){s=le;try{var ce=s.alternate;if((s.flags&1024)!==0)switch(s.tag){case 0:case 11:case 15:break;case 1:if(ce!==null){var de=ce.memoizedProps,dt=ce.memoizedState,B=s.stateNode,k=B.getSnapshotBeforeUpdate(s.elementType===s.type?de:Nn(s.type,de),dt);B.__reactInternalSnapshotBeforeUpdate=k}break;case 3:var $=s.stateNode.containerInfo;$.nodeType===1?$.textContent="":$.nodeType===9&&$.documentElement&&$.removeChild($.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(t(163))}}catch(Z){ut(s,s.return,Z)}if(r=s.sibling,r!==null){r.return=s.return,le=r;break}le=s.return}return ce=Ip,Ip=!1,ce}function yo(r,s,o){var l=s.updateQueue;if(l=l!==null?l.lastEffect:null,l!==null){var d=l=l.next;do{if((d.tag&r)===r){var p=d.destroy;d.destroy=void 0,p!==void 0&&Dc(s,o,p)}d=d.next}while(d!==l)}}function La(r,s){if(s=s.updateQueue,s=s!==null?s.lastEffect:null,s!==null){var o=s=s.next;do{if((o.tag&r)===r){var l=o.create;o.destroy=l()}o=o.next}while(o!==s)}}function Cc(r){var s=r.ref;if(s!==null){var o=r.stateNode;switch(r.tag){case 5:r=o;break;default:r=o}typeof s=="function"?s(r):s.current=r}}function Mp(r){var s=r.alternate;s!==null&&(r.alternate=null,Mp(s)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(s=r.stateNode,s!==null&&(delete s[Pn],delete s[so],delete s[Gu],delete s[xx],delete s[bx])),r.stateNode=null,r.return=null,r.dependencies=null,r.memoizedProps=null,r.memoizedState=null,r.pendingProps=null,r.stateNode=null,r.updateQueue=null}function Dp(r){return r.tag===5||r.tag===3||r.tag===4}function Cp(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||Dp(r.return))return null;r=r.return}for(r.sibling.return=r.return,r=r.sibling;r.tag!==5&&r.tag!==6&&r.tag!==18;){if(r.flags&2||r.child===null||r.tag===4)continue e;r.child.return=r,r=r.child}if(!(r.flags&2))return r.stateNode}}function Fc(r,s,o){var l=r.tag;if(l===5||l===6)r=r.stateNode,s?o.nodeType===8?o.parentNode.insertBefore(r,s):o.insertBefore(r,s):(o.nodeType===8?(s=o.parentNode,s.insertBefore(r,o)):(s=o,s.appendChild(r)),o=o._reactRootContainer,o!=null||s.onclick!==null||(s.onclick=ma));else if(l!==4&&(r=r.child,r!==null))for(Fc(r,s,o),r=r.sibling;r!==null;)Fc(r,s,o),r=r.sibling}function Oc(r,s,o){var l=r.tag;if(l===5||l===6)r=r.stateNode,s?o.insertBefore(r,s):o.appendChild(r);else if(l!==4&&(r=r.child,r!==null))for(Oc(r,s,o),r=r.sibling;r!==null;)Oc(r,s,o),r=r.sibling}var St=null,jn=!1;function Wr(r,s,o){for(o=o.child;o!==null;)Fp(r,s,o),o=o.sibling}function Fp(r,s,o){if($n&&typeof $n.onCommitFiberUnmount=="function")try{$n.onCommitFiberUnmount(qo,o)}catch{}switch(o.tag){case 5:Mt||ri(o,s);case 6:var l=St,d=jn;St=null,Wr(r,s,o),St=l,jn=d,St!==null&&(jn?(r=St,o=o.stateNode,r.nodeType===8?r.parentNode.removeChild(o):r.removeChild(o)):St.removeChild(o.stateNode));break;case 18:St!==null&&(jn?(r=St,o=o.stateNode,r.nodeType===8?Hu(r.parentNode,o):r.nodeType===1&&Hu(r,o),Yi(r)):Hu(St,o.stateNode));break;case 4:l=St,d=jn,St=o.stateNode.containerInfo,jn=!0,Wr(r,s,o),St=l,jn=d;break;case 0:case 11:case 14:case 15:if(!Mt&&(l=o.updateQueue,l!==null&&(l=l.lastEffect,l!==null))){d=l=l.next;do{var p=d,y=p.destroy;p=p.tag,y!==void 0&&((p&2)!==0||(p&4)!==0)&&Dc(o,s,y),d=d.next}while(d!==l)}Wr(r,s,o);break;case 1:if(!Mt&&(ri(o,s),l=o.stateNode,typeof l.componentWillUnmount=="function"))try{l.props=o.memoizedProps,l.state=o.memoizedState,l.componentWillUnmount()}catch(S){ut(o,s,S)}Wr(r,s,o);break;case 21:Wr(r,s,o);break;case 22:o.mode&1?(Mt=(l=Mt)||o.memoizedState!==null,Wr(r,s,o),Mt=l):Wr(r,s,o);break;default:Wr(r,s,o)}}function Op(r){var s=r.updateQueue;if(s!==null){r.updateQueue=null;var o=r.stateNode;o===null&&(o=r.stateNode=new Ex),s.forEach(function(l){var d=Gx.bind(null,r,l);o.has(l)||(o.add(l),l.then(d,d))})}}function kn(r,s){var o=s.deletions;if(o!==null)for(var l=0;ld&&(d=y),l&=~p}if(l=d,l=ct()-l,l=(120>l?120:480>l?480:1080>l?1080:1920>l?1920:3e3>l?3e3:4320>l?4320:1960*Ux(l/1960))-l,10r?16:r,Gr===null)var l=!1;else{if(r=Gr,Gr=null,Va=0,(Pe&6)!==0)throw Error(t(331));var d=Pe;for(Pe|=4,le=r.current;le!==null;){var p=le,y=p.child;if((le.flags&16)!==0){var S=p.deletions;if(S!==null){for(var N=0;Nct()-Bc?Ss(r,0):Ac|=o),Ut(r,s)}function Hp(r,s){s===0&&((r.mode&1)===0?s=1:(s=Xo,Xo<<=1,(Xo&130023424)===0&&(Xo=4194304)));var o=Ft();r=cr(r,s),r!==null&&(zi(r,s,o),Ut(r,o))}function Hx(r){var s=r.memoizedState,o=0;s!==null&&(o=s.retryLane),Hp(r,o)}function Gx(r,s){var o=0;switch(r.tag){case 13:var l=r.stateNode,d=r.memoizedState;d!==null&&(o=d.retryLane);break;case 19:l=r.stateNode;break;default:throw Error(t(314))}l!==null&&l.delete(s),Hp(r,o)}var Gp;Gp=function(r,s,o){if(r!==null)if(r.memoizedProps!==s.pendingProps||Bt.current)Rt=!0;else{if((r.lanes&o)===0&&(s.flags&128)===0)return Rt=!1,Tx(r,s,o);Rt=(r.flags&131072)!==0}else Rt=!1,st&&(s.flags&1048576)!==0&&jh(s,wa,s.index);switch(s.lanes=0,s.tag){case 2:var l=s.type;Ea(r,s),r=s.pendingProps;var d=Qs(s,jt.current);ei(s,o),d=fc(null,s,l,r,d,o);var p=hc();return s.flags|=1,typeof d=="object"&&d!==null&&typeof d.render=="function"&&d.$$typeof===void 0?(s.tag=1,s.memoizedState=null,s.updateQueue=null,Et(l)?(p=!0,va(s)):p=!1,s.memoizedState=d.state!==null&&d.state!==void 0?d.state:null,ic(s),d.updater=Aa,s.stateNode=d,d._reactInternals=s,xc(s,l,r,o),s=_c(null,s,l,!0,p,o)):(s.tag=0,st&&p&&Ku(s),Ct(null,s,d,o),s=s.child),s;case 16:l=s.elementType;e:{switch(Ea(r,s),r=s.pendingProps,d=l._init,l=d(l._payload),s.type=l,d=s.tag=Qx(l),r=Nn(l,r),d){case 0:s=Sc(null,s,l,r,o);break e;case 1:s=vp(null,s,l,r,o);break e;case 11:s=hp(null,s,l,r,o);break e;case 14:s=pp(null,s,l,Nn(l.type,r),o);break e}throw Error(t(306,l,""))}return s;case 0:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),Sc(r,s,l,d,o);case 1:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),vp(r,s,l,d,o);case 3:e:{if(xp(s),r===null)throw Error(t(387));l=s.pendingProps,p=s.memoizedState,d=p.element,Ah(r,s),Ia(s,l,null,o);var y=s.memoizedState;if(l=y.element,p.isDehydrated)if(p={element:l,isDehydrated:!1,cache:y.cache,pendingSuspenseBoundaries:y.pendingSuspenseBoundaries,transitions:y.transitions},s.updateQueue.baseState=p,s.memoizedState=p,s.flags&256){d=ni(Error(t(423)),s),s=bp(r,s,l,o,d);break e}else if(l!==d){d=ni(Error(t(424)),s),s=bp(r,s,l,o,d);break e}else for(Kt=Lr(s.stateNode.containerInfo.firstChild),Qt=s,st=!0,_n=null,o=Oh(s,null,l,o),s.child=o;o;)o.flags=o.flags&-3|4096,o=o.sibling;else{if(qs(),l===d){s=fr(r,s,o);break e}Ct(r,s,l,o)}s=s.child}return s;case 5:return Rh(s),r===null&&Zu(s),l=s.type,d=s.pendingProps,p=r!==null?r.memoizedProps:null,y=d.children,Vu(l,d)?y=null:p!==null&&Vu(l,p)&&(s.flags|=32),gp(r,s),Ct(r,s,y,o),s.child;case 6:return r===null&&Zu(s),null;case 13:return wp(r,s,o);case 4:return oc(s,s.stateNode.containerInfo),l=s.pendingProps,r===null?s.child=Zs(s,null,l,o):Ct(r,s,l,o),s.child;case 11:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),hp(r,s,l,d,o);case 7:return Ct(r,s,s.pendingProps,o),s.child;case 8:return Ct(r,s,s.pendingProps.children,o),s.child;case 12:return Ct(r,s,s.pendingProps.children,o),s.child;case 10:e:{if(l=s.type._context,d=s.pendingProps,p=s.memoizedProps,y=d.value,qe(Na,l._currentValue),l._currentValue=y,p!==null)if(Sn(p.value,y)){if(p.children===d.children&&!Bt.current){s=fr(r,s,o);break e}}else for(p=s.child,p!==null&&(p.return=s);p!==null;){var S=p.dependencies;if(S!==null){y=p.child;for(var N=S.firstContext;N!==null;){if(N.context===l){if(p.tag===1){N=dr(-1,o&-o),N.tag=2;var P=p.updateQueue;if(P!==null){P=P.shared;var J=P.pending;J===null?N.next=N:(N.next=J.next,J.next=N),P.pending=N}}p.lanes|=o,N=p.alternate,N!==null&&(N.lanes|=o),rc(p.return,o,s),S.lanes|=o;break}N=N.next}}else if(p.tag===10)y=p.type===s.type?null:p.child;else if(p.tag===18){if(y=p.return,y===null)throw Error(t(341));y.lanes|=o,S=y.alternate,S!==null&&(S.lanes|=o),rc(y,o,s),y=p.sibling}else y=p.child;if(y!==null)y.return=p;else for(y=p;y!==null;){if(y===s){y=null;break}if(p=y.sibling,p!==null){p.return=y.return,y=p;break}y=y.return}p=y}Ct(r,s,d.children,o),s=s.child}return s;case 9:return d=s.type,l=s.pendingProps.children,ei(s,o),d=sn(d),l=l(d),s.flags|=1,Ct(r,s,l,o),s.child;case 14:return l=s.type,d=Nn(l,s.pendingProps),d=Nn(l.type,d),pp(r,s,l,d,o);case 15:return mp(r,s,s.type,s.pendingProps,o);case 17:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),Ea(r,s),s.tag=1,Et(l)?(r=!0,va(s)):r=!1,ei(s,o),op(s,l,d),xc(s,l,d,o),_c(null,s,l,!0,r,o);case 19:return _p(r,s,o);case 22:return yp(r,s,o)}throw Error(t(156,s.tag))};function Yp(r,s){return kf(r,s)}function Yx(r,s,o,l){this.tag=r,this.key=o,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=s,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=l,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ln(r,s,o,l){return new Yx(r,s,o,l)}function Vc(r){return r=r.prototype,!(!r||!r.isReactComponent)}function Qx(r){if(typeof r=="function")return Vc(r)?1:0;if(r!=null){if(r=r.$$typeof,r===ee)return 11;if(r===ae)return 14}return 2}function Kr(r,s){var o=r.alternate;return o===null?(o=ln(r.tag,s,r.key,r.mode),o.elementType=r.elementType,o.type=r.type,o.stateNode=r.stateNode,o.alternate=r,r.alternate=o):(o.pendingProps=s,o.type=r.type,o.flags=0,o.subtreeFlags=0,o.deletions=null),o.flags=r.flags&14680064,o.childLanes=r.childLanes,o.lanes=r.lanes,o.child=r.child,o.memoizedProps=r.memoizedProps,o.memoizedState=r.memoizedState,o.updateQueue=r.updateQueue,s=r.dependencies,o.dependencies=s===null?null:{lanes:s.lanes,firstContext:s.firstContext},o.sibling=r.sibling,o.index=r.index,o.ref=r.ref,o}function Ya(r,s,o,l,d,p){var y=2;if(l=r,typeof r=="function")Vc(r)&&(y=1);else if(typeof r=="string")y=5;else e:switch(r){case U:return Ns(o.children,d,p,s);case G:y=8,d|=8;break;case V:return r=ln(12,o,s,d|2),r.elementType=V,r.lanes=p,r;case X:return r=ln(13,o,s,d),r.elementType=X,r.lanes=p,r;case ie:return r=ln(19,o,s,d),r.elementType=ie,r.lanes=p,r;case se:return Qa(o,d,p,s);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case Q:y=10;break e;case z:y=9;break e;case ee:y=11;break e;case ae:y=14;break e;case re:y=16,l=null;break e}throw Error(t(130,r==null?r:typeof r,""))}return s=ln(y,o,s,d),s.elementType=r,s.type=l,s.lanes=p,s}function Ns(r,s,o,l){return r=ln(7,r,l,s),r.lanes=o,r}function Qa(r,s,o,l){return r=ln(22,r,l,s),r.elementType=se,r.lanes=o,r.stateNode={isHidden:!1},r}function Wc(r,s,o){return r=ln(6,r,null,s),r.lanes=o,r}function Hc(r,s,o){return s=ln(4,r.children!==null?r.children:[],r.key,s),s.lanes=o,s.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},s}function Kx(r,s,o,l,d){this.tag=s,this.containerInfo=r,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=vu(0),this.expirationTimes=vu(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=vu(0),this.identifierPrefix=l,this.onRecoverableError=d,this.mutableSourceEagerHydrationData=null}function Gc(r,s,o,l,d,p,y,S,N){return r=new Kx(r,s,o,S,N),s===1?(s=1,p===!0&&(s|=8)):s=0,p=ln(3,null,null,s),r.current=p,p.stateNode=r,p.memoizedState={element:l,isDehydrated:o,cache:null,transitions:null,pendingSuspenseBoundaries:null},ic(p),r}function Jx(r,s,o){var l=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),Zc.exports=ub(),Zc.exports}var am;function db(){if(am)return tl;am=1;var n=cb();return tl.createRoot=n.createRoot,tl.hydrateRoot=n.hydrateRoot,tl}var fb=db();function Sr(n){return n.split(".").at(-1)||n}function Fn(n,e){const t=Sr(n);if(e.filter(a=>Sr(a)===t).length<2)return t;const i=n.indexOf(".");return i>0?`${n.slice(0,i)}_${t}`:t}const er="\0__null__";function hb(n){return String(n||"").replaceAll("_"," ").replaceAll("."," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}function gy(n,e={}){if(n==null||n==="")return"—";const t=typeof n=="number"?n:Number(n);if(!Number.isFinite(t))return String(n);const i=String(e.format||"").toLowerCase();if(e.style==="percent"||i.includes("%")||i.includes("percent")||i.includes("pct")||e.type==="ratio")return(e.style==="percent"?t:Math.abs(t)<=1?t*100:t).toLocaleString(void 0,{maximumFractionDigits:e.maximumFractionDigits??1,style:e.style==="percent"?"percent":"decimal"})+(e.style==="percent"?"":"%");const u=e.style==="currency"||e.currency||i.includes("$")||i.includes("usd")||i.includes("currency")||i.includes("dollar");return t.toLocaleString(void 0,{currency:u?e.currency||"USD":void 0,maximumFractionDigits:e.maximumFractionDigits??2,notation:e.compact?"compact":"standard",style:u?"currency":"decimal"})}function pb(n,e={}){return gy(n,{...e,compact:!0,maximumFractionDigits:e.maximumFractionDigits??1})}function mb(n,e,t){const i=t>0&&n.length>t,a=i?Math.ceil(n.length/t):1,u=Math.max(0,Math.min(e,a-1)),f=i?u*t:0;return{paginate:i,pageCount:a,safePage:u,start:f,visibleRows:i?n.slice(f,f+t):n}}function rs(n){return n===er||n===""?"—":n}function Le(n){return hb(n)}function pt(n,e={}){return gy(n,e)}function Wt(n,e={}){return pb(n,e)}function vy(n){return!Number.isFinite(n)||n===0?"neutral":n>0?"positive":"negative"}function yb(n,e){return!Number.isFinite(n)||!Number.isFinite(e)||e<=0?{label:"—",tone:"neutral"}:{label:`${(n/e*100).toLocaleString(void 0,{maximumFractionDigits:1})}%`,tone:"neutral"}}function gb(n,e,t={}){if(e==null||!Number.isFinite(e)||!Number.isFinite(n))return{label:"—",tone:"neutral"};const i=n-e;return{label:`${i>0?"+":i<0?"−":""}${Wt(Math.abs(i),t)}`,tone:vy(i)}}function vb(n,e){if(e==null||!Number.isFinite(e)||e===0||!Number.isFinite(n))return{label:"—",tone:"neutral"};const t=(n-e)/Math.abs(e);return{label:`${(t*100).toLocaleString(void 0,{maximumFractionDigits:1,signDisplay:"exceptZero"})}%`,tone:vy(t)}}function xy(n,e){if(e==null||!Number.isFinite(e)||e===0||!Number.isFinite(n))return null;const t=(n-e)/Math.abs(e),i=(t*100).toLocaleString(void 0,{maximumFractionDigits:1,signDisplay:"exceptZero"}),a=t>0?"positive":t<0?"negative":"neutral";return{label:`${i}%`,tone:a}}function Tn(n){return`'${n.replaceAll("'","''")}'`}function xb(n){if(n.mode==="contains")return`contains ${Tn(n.pattern??"")}`;const{values:e}=n,t=n.mode==="exclude"?"is not":"is";return e.length===0?t:e.length===1?`${t} ${rs(e[0])}`:e.length<=2?`${t} ${e.map(rs).join(", ")}`:`${t} ${e.length} values`}const td=n=>n.public!==!1,by=/(^|_)(date|time|day|month|week|year|quarter|created|updated|timestamp|_at|_on)($|_)/i;function wy(n,e){if(e){const t=n.find(i=>i.name===e);if(t)return t}return n.find(t=>t.type==="time")??n.find(t=>by.test(t.name))}function bb(n,e){var f;const t=new Set;if(!n)return t;const i=new Set(e.map(h=>h.name)),a=n.match(/[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*/g)??[];for(const h of a){const[m]=h.split(".");i.has(m)&&t.add(m)}if(t.size)return t;const u=(f=n.match(/^[A-Za-z_][A-Za-z0-9_]*$/))==null?void 0:f[0];if(!u)return t;for(const h of e)h.metrics.some(m=>m.name===u)&&t.add(h.name);return t}function Sy(n,e){const t=new Set;for(const i of[n.base_metric,n.numerator,n.denominator,n.sql])for(const a of bb(i,e))t.add(a);return t.size===1?[...t][0]:void 0}function wb(n){const e=(n.models??[]).map(i=>{const a=(i.dimensions??[]).filter(td).map(h=>({ref:`${i.name}.${h.name}`,name:h.name,model:i.name,label:h.label||Le(h.name),description:h.description,type:h.type||"categorical",granularity:h.granularity,supportedGranularities:h.supported_granularities,format:h.format})),u=(i.metrics??[]).filter(td).map(h=>({ref:`${i.name}.${h.name}`,name:h.name,model:i.name,label:h.label||Le(h.name),description:h.description,agg:h.agg,type:h.type,format:h.format})),f=wy(a,i.default_time_dimension);return{name:i.name,label:Le(i.name),description:i.description,table:i.table,dimensions:a,metrics:u,timeDimension:f,defaultGrain:i.default_grain||(f==null?void 0:f.granularity)||"day"}}),t=(n.metrics??[]).filter(td).map(i=>({ref:i.name,name:i.name,ownerModel:Sy(i,e),baseMetric:i.base_metric,label:i.label||Le(i.name),description:i.description,type:i.type,format:i.format}));return{models:e,graphMetrics:t,dialect:n.dialect}}function Sb(n){const e=n??{},t=(e.models??[]).map(a=>{const u=(a.dimensions??[]).map(m=>({ref:`${a.name}.${m}`,name:m,model:a.name,label:Le(m),type:by.test(m)?"time":"categorical"})),f=(a.metrics??[]).map(m=>({ref:`${a.name}.${m}`,name:m,model:a.name,label:Le(m)})),h=wy(u);return{name:a.name,label:Le(a.name),table:a.table,dimensions:u,metrics:f,timeDimension:h,defaultGrain:(h==null?void 0:h.granularity)||"day"}}),i=(e.graph_metrics??[]).map(a=>({ref:a.name,name:a.name,ownerModel:Sy(a,t),baseMetric:a.base_metric,label:Le(a.name),type:a.type,description:a.description}));return{models:t,graphMetrics:i,joinablePairs:e.joinable_pairs??[]}}function _b(n,e){return{...n,joinablePairs:(e??{}).joinable_pairs??n.joinablePairs??[]}}function ji(n,e){const t=new Set;for(const i of n.joinablePairs??[])i.from===e&&t.add(i.to),i.to===e&&t.add(i.from);return n.graphMetrics.filter(i=>i.ownerModel?i.ownerModel===e||t.has(i.ownerModel):!0)}function Fe(n,e,t,i){function a(u){return u instanceof t?u:new t(function(f){f(u)})}return new(t||(t=Promise))(function(u,f){function h(v){try{g(i.next(v))}catch(x){f(x)}}function m(v){try{g(i.throw(v))}catch(x){f(x)}}function g(v){v.done?u(v.value):a(v.value).then(h,m)}g((i=i.apply(n,e||[])).next())})}function lm(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ae(n){return this instanceof Ae?(this.v=n,this):new Ae(n)}function qn(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),a,u=[];return a=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),h("next"),h("throw"),h("return",f),a[Symbol.asyncIterator]=function(){return this},a;function f(w){return function(j){return Promise.resolve(j).then(w,x)}}function h(w,j){i[w]&&(a[w]=function(C){return new Promise(function(O,H){u.push([w,C,O,H])>1||m(w,C)})},j&&(a[w]=j(a[w])))}function m(w,j){try{g(i[w](j))}catch(C){b(u[0][3],C)}}function g(w){w.value instanceof Ae?Promise.resolve(w.value.v).then(v,x):b(u[0][2],w)}function v(w){m("next",w)}function x(w){m("throw",w)}function b(w,j){w(j),u.shift(),u.length&&m(u[0][0],u[0][1])}}function fl(n){var e,t;return e={},i("next"),i("throw",function(a){throw a}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(a,u){e[a]=n[a]?function(f){return(t=!t)?{value:Ae(n[a](f)),done:!1}:u?u(f):f}:u}}function xi(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof lm=="function"?lm(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(u){t[u]=n[u]&&function(f){return new Promise(function(h,m){f=n[u](f),a(h,m,f.done,f.value)})}}function a(u,f,h,m){Promise.resolve(m).then(function(g){u({value:g,done:h})},f)}}const Nb=new TextDecoder("utf-8"),xd=n=>Nb.decode(n),jb=new TextEncoder,Bd=n=>jb.encode(n),kb=n=>typeof n=="number",Ib=n=>typeof n=="boolean",Ot=n=>typeof n=="function",En=n=>n!=null&&Object(n)===n,Ao=n=>En(n)&&Ot(n.then),nu=n=>En(n)&&Ot(n[Symbol.iterator]),Ed=n=>En(n)&&Ot(n[Symbol.asyncIterator]),bd=n=>En(n)&&En(n.schema),_y=n=>En(n)&&"done"in n&&"value"in n,Ny=n=>En(n)&&Ot(n.stat)&&kb(n.fd),jy=n=>En(n)&&Rd(n.body),ky=n=>"_getDOMStream"in n&&"_getNodeStream"in n,Rd=n=>En(n)&&Ot(n.cancel)&&Ot(n.getReader)&&!ky(n),Iy=n=>En(n)&&Ot(n.read)&&Ot(n.pipe)&&Ib(n.readable)&&!ky(n),Mb=n=>En(n)&&Ot(n.clear)&&Ot(n.bytes)&&Ot(n.position)&&Ot(n.setPosition)&&Ot(n.capacity)&&Ot(n.getBufferIdentifier)&&Ot(n.createLong),Ld=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function Db(n){const e=n[0]?[n[0]]:[];let t,i,a,u;for(let f,h,m=0,g=0,v=n.length;++mv+x.byteLength,0);let a,u,f,h=0,m=-1;const g=Math.min(e||Number.POSITIVE_INFINITY,i);for(const v=t.length;++mKe(Int32Array,n),cm=n=>Ke(BigInt64Array,n),$e=n=>Ke(Uint8Array,n),wd=n=>(n.next(),n);function*Cb(n,e){const t=function*(a){yield a},i=typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof Ld?t(e):nu(e)?e:t(e);return yield*wd((function*(a){let u=null;do u=a.next(yield Ke(n,u));while(!u.done)})(i[Symbol.iterator]())),new n}const Fb=n=>Cb(Uint8Array,n);function My(n,e){return qn(this,arguments,function*(){if(Ao(e))return yield Ae(yield Ae(yield*fl(xi(My(n,yield Ae(e))))));const i=function(f){return qn(this,arguments,function*(){yield yield Ae(yield Ae(f))})},a=function(f){return qn(this,arguments,function*(){yield Ae(yield*fl(xi(wd((function*(h){let m=null;do m=h.next(yield m==null?void 0:m.value);while(!m.done)})(f[Symbol.iterator]())))))})},u=typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof Ld?i(e):nu(e)?a(e):Ed(e)?e:i(e);return yield Ae(yield*fl(xi(wd((function(f){return qn(this,arguments,function*(){let h=null;do h=yield Ae(f.next(yield yield Ae(Ke(n,h))));while(!h.done)})})(u[Symbol.asyncIterator]()))))),yield Ae(new n)})}const Ob=n=>My(Uint8Array,n);function Tb(n,e){let t=0;const i=n.length;if(i!==e.length)return!1;if(i>0)do if(n[t]!==e[t])return!1;while(++t(n.next(),n);function*Ab(n){let e,t=!1,i=[],a,u,f,h=0;function m(){return u==="peek"?tr(i,f)[0]:([a,i,h]=tr(i,f),a)}({cmd:u,size:f}=(yield null)||{cmd:"read",size:0});const g=Fb(n)[Symbol.iterator]();try{do if({done:e,value:a}=Number.isNaN(f-h)?g.next():g.next(f-h),!e&&a.byteLength>0&&(i.push(a),h+=a.byteLength),e||f<=h)do({cmd:u,size:f}=yield m());while(f0&&(a.push(u),m+=u.byteLength),t||h<=m)do({cmd:f,size:h}=yield yield Ae(g()));while(h0&&(a.push($e(u)),m+=u.byteLength),t||h<=m)do({cmd:f,size:h}=yield yield Ae(g()));while(h{})}get closed(){return this.reader?this.reader.closed.catch(()=>{}):Promise.resolve()}releaseLock(){this.reader&&this.reader.releaseLock(),this.reader=null}cancel(e){return Fe(this,void 0,void 0,function*(){const{reader:t,source:i}=this;t&&(yield t.cancel(e).catch(()=>{})),i&&i.locked&&this.releaseLock()})}read(e){return Fe(this,void 0,void 0,function*(){if(e===0)return{done:this.reader==null,value:new Uint8Array(0)};const t=yield this.reader.read();return!t.done&&(t.value=$e(t)),t})}}const nd=(n,e)=>{const t=a=>i([e,a]);let i;return[e,t,new Promise(a=>(i=a)&&n.once(e,t))]};function Lb(n){return qn(this,arguments,function*(){const t=[];let i="error",a=!1,u=null,f,h,m=0,g=[],v;function x(){return f==="peek"?tr(g,h)[0]:([v,g,m]=tr(g,h),v)}if({cmd:f,size:h}=(yield yield Ae(null))||{cmd:"read",size:0},n.isTTY)return yield yield Ae(new Uint8Array(0)),yield Ae(null);try{t[0]=nd(n,"end"),t[1]=nd(n,"error");do{if(t[2]=nd(n,"readable"),[i,u]=yield Ae(Promise.race(t.map(w=>w[2]))),i==="error")break;if((a=i==="end")||(Number.isFinite(h-m)?(v=$e(n.read(h-m)),v.byteLength0&&(g.push(v),m+=v.byteLength)),a||h<=m)do({cmd:f,size:h}=yield yield Ae(x()));while(h{for(const[H,L]of w)n.off(H,L);try{const H=n.destroy;H&&H.call(n,j),j=void 0}catch(H){j=H||j}finally{j!=null?O(j):C()}})}})}var ht;(function(n){n[n.V1=0]="V1",n[n.V2=1]="V2",n[n.V3=2]="V3",n[n.V4=3]="V4",n[n.V5=4]="V5"})(ht||(ht={}));var Ht;(function(n){n[n.Sparse=0]="Sparse",n[n.Dense=1]="Dense"})(Ht||(Ht={}));var Dt;(function(n){n[n.HALF=0]="HALF",n[n.SINGLE=1]="SINGLE",n[n.DOUBLE=2]="DOUBLE"})(Dt||(Dt={}));var gn;(function(n){n[n.DAY=0]="DAY",n[n.MILLISECOND=1]="MILLISECOND"})(gn||(gn={}));var _e;(function(n){n[n.SECOND=0]="SECOND",n[n.MILLISECOND=1]="MILLISECOND",n[n.MICROSECOND=2]="MICROSECOND",n[n.NANOSECOND=3]="NANOSECOND"})(_e||(_e={}));var nr;(function(n){n[n.YEAR_MONTH=0]="YEAR_MONTH",n[n.DAY_TIME=1]="DAY_TIME",n[n.MONTH_DAY_NANO=2]="MONTH_DAY_NANO"})(nr||(nr={}));const rd=2,Qn=4,br=4,He=4,es=new Int32Array(2),dm=new Float32Array(es.buffer),fm=new Float64Array(es.buffer),rl=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Sd;(function(n){n[n.UTF8_BYTES=1]="UTF8_BYTES",n[n.UTF16_STRING=2]="UTF16_STRING"})(Sd||(Sd={}));let ki=class Dy{constructor(e){this.bytes_=e,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(e){return new Dy(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return BigInt.asIntN(64,BigInt(this.readUint32(e))+(BigInt(this.readUint32(e+4))<>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,Number(BigInt.asIntN(32,t))),this.writeInt32(e+4,Number(BigInt.asIntN(32,t>>BigInt(32))))}writeUint64(e,t){this.writeUint32(e,Number(BigInt.asUintN(32,t))),this.writeUint32(e+4,Number(BigInt.asUintN(32,t>>BigInt(32))))}writeFloat32(e,t){dm[0]=t,this.writeInt32(e,es[0])}writeFloat64(e,t){fm[0]=t,this.writeInt32(e,es[rl?0:1]),this.writeInt32(e+4,es[rl?1:0])}getBufferIdentifier(){if(this.bytes_.lengththis.minalign&&(this.minalign=e);const i=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space=0&&this.vtable[t]==0;t--);const i=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);const a=2;this.addInt16(e-this.object_start);const u=(i+a)*rd;this.addInt16(u);let f=0;const h=this.space;e:for(t=0;t=0;f--)this.writeInt8(u.charCodeAt(f))}this.prep(this.minalign,Qn+a),this.addOffset(e),a&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){const i=this.bb.capacity()-e,a=i-this.bb.readInt32(i);if(!(t=0;i--)e.addInt32(t[i]);return e.endVector()}static startTypeIdsVector(e,t){e.startVector(4,t,4)}static endUnion(e){return e.endObject()}static createUnion(e,t,i){return Vt.startUnion(e),Vt.addMode(e,t),Vt.addTypeIds(e,i),Vt.endUnion(e)}}let xm=class Fo{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsUtf8(e,t){return(t||new Fo).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsUtf8(e,t){return e.setPosition(e.position()+He),(t||new Fo).__init(e.readInt32(e.position())+e.position(),e)}static startUtf8(e){e.startObject(0)}static endUtf8(e){return e.endObject()}static createUtf8(e){return Fo.startUtf8(e),Fo.endUtf8(e)}};var Ze;(function(n){n[n.NONE=0]="NONE",n[n.Null=1]="Null",n[n.Int=2]="Int",n[n.FloatingPoint=3]="FloatingPoint",n[n.Binary=4]="Binary",n[n.Utf8=5]="Utf8",n[n.Bool=6]="Bool",n[n.Decimal=7]="Decimal",n[n.Date=8]="Date",n[n.Time=9]="Time",n[n.Timestamp=10]="Timestamp",n[n.Interval=11]="Interval",n[n.List=12]="List",n[n.Struct_=13]="Struct_",n[n.Union=14]="Union",n[n.FixedSizeBinary=15]="FixedSizeBinary",n[n.FixedSizeList=16]="FixedSizeList",n[n.Map=17]="Map",n[n.Duration=18]="Duration",n[n.LargeBinary=19]="LargeBinary",n[n.LargeUtf8=20]="LargeUtf8",n[n.LargeList=21]="LargeList",n[n.RunEndEncoded=22]="RunEndEncoded"})(Ze||(Ze={}));let dn=class vl{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsField(e,t){return(t||new vl).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsField(e,t){return e.setPosition(e.position()+He),(t||new vl).__init(e.readInt32(e.position())+e.position(),e)}name(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}nullable(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}typeType(){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readUint8(this.bb_pos+e):Ze.NONE}type(e){const t=this.bb.__offset(this.bb_pos,10);return t?this.bb.__union(e,this.bb_pos+t):null}dictionary(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new wr).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}children(e,t){const i=this.bb.__offset(this.bb_pos,14);return i?(t||new vl).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}childrenLength(){const e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,16);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__vector_len(this.bb_pos+e):0}static startField(e){e.startObject(7)}static addName(e,t){e.addFieldOffset(0,t,0)}static addNullable(e,t){e.addFieldInt8(1,+t,0)}static addTypeType(e,t){e.addFieldInt8(2,t,Ze.NONE)}static addType(e,t){e.addFieldOffset(3,t,0)}static addDictionary(e,t){e.addFieldOffset(4,t,0)}static addChildren(e,t){e.addFieldOffset(5,t,0)}static createChildrenVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startChildrenVector(e,t){e.startVector(4,t,4)}static addCustomMetadata(e,t){e.addFieldOffset(6,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endField(e){return e.endObject()}},Gn=class mr{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSchema(e,t){return(t||new mr).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSchema(e,t){return e.setPosition(e.position()+He),(t||new mr).__init(e.readInt32(e.position())+e.position(),e)}endianness(){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):Ii.Little}fields(e,t){const i=this.bb.__offset(this.bb_pos,6);return i?(t||new dn).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}fieldsLength(){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,8);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}features(e){const t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+e*8):BigInt(0)}featuresLength(){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__vector_len(this.bb_pos+e):0}static startSchema(e){e.startObject(4)}static addEndianness(e,t){e.addFieldInt16(0,t,Ii.Little)}static addFields(e,t){e.addFieldOffset(1,t,0)}static createFieldsVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startFieldsVector(e,t){e.startVector(4,t,4)}static addCustomMetadata(e,t){e.addFieldOffset(2,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static addFeatures(e,t){e.addFieldOffset(3,t,0)}static createFeaturesVector(e,t){e.startVector(8,t.length,8);for(let i=t.length-1;i>=0;i--)e.addInt64(t[i]);return e.endVector()}static startFeaturesVector(e,t){e.startVector(8,t,8)}static endSchema(e){return e.endObject()}static finishSchemaBuffer(e,t){e.finish(t)}static finishSizePrefixedSchemaBuffer(e,t){e.finish(t,void 0,!0)}static createSchema(e,t,i,a,u){return mr.startSchema(e),mr.addEndianness(e,t),mr.addFields(e,i),mr.addCustomMetadata(e,a),mr.addFeatures(e,u),mr.endSchema(e)}};var Ve;(function(n){n[n.NONE=0]="NONE",n[n.Schema=1]="Schema",n[n.DictionaryBatch=2]="DictionaryBatch",n[n.RecordBatch=3]="RecordBatch",n[n.Tensor=4]="Tensor",n[n.SparseTensor=5]="SparseTensor"})(Ve||(Ve={}));var D;(function(n){n[n.NONE=0]="NONE",n[n.Null=1]="Null",n[n.Int=2]="Int",n[n.Float=3]="Float",n[n.Binary=4]="Binary",n[n.Utf8=5]="Utf8",n[n.Bool=6]="Bool",n[n.Decimal=7]="Decimal",n[n.Date=8]="Date",n[n.Time=9]="Time",n[n.Timestamp=10]="Timestamp",n[n.Interval=11]="Interval",n[n.List=12]="List",n[n.Struct=13]="Struct",n[n.Union=14]="Union",n[n.FixedSizeBinary=15]="FixedSizeBinary",n[n.FixedSizeList=16]="FixedSizeList",n[n.Map=17]="Map",n[n.Duration=18]="Duration",n[n.LargeBinary=19]="LargeBinary",n[n.LargeUtf8=20]="LargeUtf8",n[n.Dictionary=-1]="Dictionary",n[n.Int8=-2]="Int8",n[n.Int16=-3]="Int16",n[n.Int32=-4]="Int32",n[n.Int64=-5]="Int64",n[n.Uint8=-6]="Uint8",n[n.Uint16=-7]="Uint16",n[n.Uint32=-8]="Uint32",n[n.Uint64=-9]="Uint64",n[n.Float16=-10]="Float16",n[n.Float32=-11]="Float32",n[n.Float64=-12]="Float64",n[n.DateDay=-13]="DateDay",n[n.DateMillisecond=-14]="DateMillisecond",n[n.TimestampSecond=-15]="TimestampSecond",n[n.TimestampMillisecond=-16]="TimestampMillisecond",n[n.TimestampMicrosecond=-17]="TimestampMicrosecond",n[n.TimestampNanosecond=-18]="TimestampNanosecond",n[n.TimeSecond=-19]="TimeSecond",n[n.TimeMillisecond=-20]="TimeMillisecond",n[n.TimeMicrosecond=-21]="TimeMicrosecond",n[n.TimeNanosecond=-22]="TimeNanosecond",n[n.DenseUnion=-23]="DenseUnion",n[n.SparseUnion=-24]="SparseUnion",n[n.IntervalDayTime=-25]="IntervalDayTime",n[n.IntervalYearMonth=-26]="IntervalYearMonth",n[n.DurationSecond=-27]="DurationSecond",n[n.DurationMillisecond=-28]="DurationMillisecond",n[n.DurationMicrosecond=-29]="DurationMicrosecond",n[n.DurationNanosecond=-30]="DurationNanosecond"})(D||(D={}));var gr;(function(n){n[n.OFFSET=0]="OFFSET",n[n.DATA=1]="DATA",n[n.VALIDITY=2]="VALIDITY",n[n.TYPE=3]="TYPE"})(gr||(gr={}));const Ub=void 0;function Bo(n){if(n===null)return"null";if(n===Ub)return"undefined";switch(typeof n){case"number":return`${n}`;case"bigint":return`${n}`;case"string":return`"${n}"`}return typeof n[Symbol.toPrimitive]=="function"?n[Symbol.toPrimitive]("string"):ArrayBuffer.isView(n)?n instanceof BigInt64Array||n instanceof BigUint64Array?`[${[...n].map(e=>Bo(e))}]`:`[${n}]`:ArrayBuffer.isView(n)?`[${n}]`:JSON.stringify(n,(e,t)=>typeof t=="bigint"?`${t}`:t)}function tt(n){if(typeof n=="bigint"&&(nNumber.MAX_SAFE_INTEGER))throw new TypeError(`${n} is not safe to convert to a number.`);return Number(n)}function Ay(n,e){return tt(n/e)+tt(n%e)/tt(e)}const $b=Symbol.for("isArrowBigNum");function Ln(n,...e){return e.length===0?Object.setPrototypeOf(Ke(this.TypedArray,n),this.constructor.prototype):Object.setPrototypeOf(new this.TypedArray(n,...e),this.constructor.prototype)}Ln.prototype[$b]=!0;Ln.prototype.toJSON=function(){return`"${Ro(this)}"`};Ln.prototype.valueOf=function(n){return By(this,n)};Ln.prototype.toString=function(){return Ro(this)};Ln.prototype[Symbol.toPrimitive]=function(n="default"){switch(n){case"number":return By(this);case"string":return Ro(this);case"default":return Vb(this)}return Ro(this)};function bi(...n){return Ln.apply(this,n)}function wi(...n){return Ln.apply(this,n)}function Eo(...n){return Ln.apply(this,n)}Object.setPrototypeOf(bi.prototype,Object.create(Int32Array.prototype));Object.setPrototypeOf(wi.prototype,Object.create(Uint32Array.prototype));Object.setPrototypeOf(Eo.prototype,Object.create(Uint32Array.prototype));Object.assign(bi.prototype,Ln.prototype,{constructor:bi,signed:!0,TypedArray:Int32Array,BigIntArray:BigInt64Array});Object.assign(wi.prototype,Ln.prototype,{constructor:wi,signed:!1,TypedArray:Uint32Array,BigIntArray:BigUint64Array});Object.assign(Eo.prototype,Ln.prototype,{constructor:Eo,signed:!0,TypedArray:Uint32Array,BigIntArray:BigUint64Array});const Pb=BigInt(4294967296)*BigInt(4294967296),zb=Pb-BigInt(1);function By(n,e){const{buffer:t,byteOffset:i,byteLength:a,signed:u}=n,f=new BigUint64Array(t,i,a/8),h=u&&f.at(-1)&BigInt(1)<=0)return sd(n);e=e.slice();let i=1;for(let u=0;u(n.children=null,n.ArrayType=Array,n.OffsetArrayType=Int32Array,n[Symbol.toStringTag]="DataType"))(me.prototype);class ss extends me{constructor(){super(D.Null)}toString(){return"Null"}}Ry=Symbol.toStringTag;ss[Ry]=(n=>n[Symbol.toStringTag]="Null")(ss.prototype);class Ds extends me{constructor(e,t){super(D.Int),this.isSigned=e,this.bitWidth=t}get ArrayType(){switch(this.bitWidth){case 8:return this.isSigned?Int8Array:Uint8Array;case 16:return this.isSigned?Int16Array:Uint16Array;case 32:return this.isSigned?Int32Array:Uint32Array;case 64:return this.isSigned?BigInt64Array:BigUint64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`${this.isSigned?"I":"Ui"}nt${this.bitWidth}`}}Ly=Symbol.toStringTag;Ds[Ly]=(n=>(n.isSigned=null,n.bitWidth=null,n[Symbol.toStringTag]="Int"))(Ds.prototype);class Lo extends Ds{constructor(){super(!0,32)}get ArrayType(){return Int32Array}}Object.defineProperty(Lo.prototype,"ArrayType",{value:Int32Array});class jl extends me{constructor(e){super(D.Float),this.precision=e}get ArrayType(){switch(this.precision){case Dt.HALF:return Uint16Array;case Dt.SINGLE:return Float32Array;case Dt.DOUBLE:return Float64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`Float${this.precision<<5||16}`}}Uy=Symbol.toStringTag;jl[Uy]=(n=>(n.precision=null,n[Symbol.toStringTag]="Float"))(jl.prototype);class kl extends me{constructor(){super(D.Binary)}toString(){return"Binary"}}$y=Symbol.toStringTag;kl[$y]=(n=>(n.ArrayType=Uint8Array,n[Symbol.toStringTag]="Binary"))(kl.prototype);class Il extends me{constructor(){super(D.LargeBinary)}toString(){return"LargeBinary"}}Py=Symbol.toStringTag;Il[Py]=(n=>(n.ArrayType=Uint8Array,n.OffsetArrayType=BigInt64Array,n[Symbol.toStringTag]="LargeBinary"))(Il.prototype);class Ml extends me{constructor(){super(D.Utf8)}toString(){return"Utf8"}}zy=Symbol.toStringTag;Ml[zy]=(n=>(n.ArrayType=Uint8Array,n[Symbol.toStringTag]="Utf8"))(Ml.prototype);class Dl extends me{constructor(){super(D.LargeUtf8)}toString(){return"LargeUtf8"}}Vy=Symbol.toStringTag;Dl[Vy]=(n=>(n.ArrayType=Uint8Array,n.OffsetArrayType=BigInt64Array,n[Symbol.toStringTag]="LargeUtf8"))(Dl.prototype);class Cl extends me{constructor(){super(D.Bool)}toString(){return"Bool"}}Wy=Symbol.toStringTag;Cl[Wy]=(n=>(n.ArrayType=Uint8Array,n[Symbol.toStringTag]="Bool"))(Cl.prototype);class Fl extends me{constructor(e,t,i=128){super(D.Decimal),this.scale=e,this.precision=t,this.bitWidth=i}toString(){return`Decimal[${this.precision}e${this.scale>0?"+":""}${this.scale}]`}}Hy=Symbol.toStringTag;Fl[Hy]=(n=>(n.scale=null,n.precision=null,n.ArrayType=Uint32Array,n[Symbol.toStringTag]="Decimal"))(Fl.prototype);class Ol extends me{constructor(e){super(D.Date),this.unit=e}toString(){return`Date${(this.unit+1)*32}<${gn[this.unit]}>`}get ArrayType(){return this.unit===gn.DAY?Int32Array:BigInt64Array}}Gy=Symbol.toStringTag;Ol[Gy]=(n=>(n.unit=null,n[Symbol.toStringTag]="Date"))(Ol.prototype);class Tl extends me{constructor(e,t){super(D.Time),this.unit=e,this.bitWidth=t}toString(){return`Time${this.bitWidth}<${_e[this.unit]}>`}get ArrayType(){switch(this.bitWidth){case 32:return Int32Array;case 64:return BigInt64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}}Yy=Symbol.toStringTag;Tl[Yy]=(n=>(n.unit=null,n.bitWidth=null,n[Symbol.toStringTag]="Time"))(Tl.prototype);class Al extends me{constructor(e,t){super(D.Timestamp),this.unit=e,this.timezone=t}toString(){return`Timestamp<${_e[this.unit]}${this.timezone?`, ${this.timezone}`:""}>`}}Qy=Symbol.toStringTag;Al[Qy]=(n=>(n.unit=null,n.timezone=null,n.ArrayType=BigInt64Array,n[Symbol.toStringTag]="Timestamp"))(Al.prototype);class Bl extends me{constructor(e){super(D.Interval),this.unit=e}toString(){return`Interval<${nr[this.unit]}>`}}Ky=Symbol.toStringTag;Bl[Ky]=(n=>(n.unit=null,n.ArrayType=Int32Array,n[Symbol.toStringTag]="Interval"))(Bl.prototype);class El extends me{constructor(e){super(D.Duration),this.unit=e}toString(){return`Duration<${_e[this.unit]}>`}}Jy=Symbol.toStringTag;El[Jy]=(n=>(n.unit=null,n.ArrayType=BigInt64Array,n[Symbol.toStringTag]="Duration"))(El.prototype);class Rl extends me{constructor(e){super(D.List),this.children=[e]}toString(){return`List<${this.valueType}>`}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}}qy=Symbol.toStringTag;Rl[qy]=(n=>(n.children=null,n[Symbol.toStringTag]="List"))(Rl.prototype);class Tt extends me{constructor(e){super(D.Struct),this.children=e}toString(){return`Struct<{${this.children.map(e=>`${e.name}:${e.type}`).join(", ")}}>`}}Zy=Symbol.toStringTag;Tt[Zy]=(n=>(n.children=null,n[Symbol.toStringTag]="Struct"))(Tt.prototype);class Ll extends me{constructor(e,t,i){super(D.Union),this.mode=e,this.children=i,this.typeIds=t=Int32Array.from(t),this.typeIdToChildIndex=t.reduce((a,u,f)=>(a[u]=f)&&a||a,Object.create(null))}toString(){return`${this[Symbol.toStringTag]}<${this.children.map(e=>`${e.type}`).join(" | ")}>`}}Xy=Symbol.toStringTag;Ll[Xy]=(n=>(n.mode=null,n.typeIds=null,n.children=null,n.typeIdToChildIndex=null,n.ArrayType=Int8Array,n[Symbol.toStringTag]="Union"))(Ll.prototype);class Ul extends me{constructor(e){super(D.FixedSizeBinary),this.byteWidth=e}toString(){return`FixedSizeBinary[${this.byteWidth}]`}}eg=Symbol.toStringTag;Ul[eg]=(n=>(n.byteWidth=null,n.ArrayType=Uint8Array,n[Symbol.toStringTag]="FixedSizeBinary"))(Ul.prototype);class $l extends me{constructor(e,t){super(D.FixedSizeList),this.listSize=e,this.children=[t]}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}toString(){return`FixedSizeList[${this.listSize}]<${this.valueType}>`}}tg=Symbol.toStringTag;$l[tg]=(n=>(n.children=null,n.listSize=null,n[Symbol.toStringTag]="FixedSizeList"))($l.prototype);class Pl extends me{constructor(e,t=!1){var i,a,u;if(super(D.Map),this.children=[e],this.keysSorted=t,e&&(e.name="entries",!((i=e==null?void 0:e.type)===null||i===void 0)&&i.children)){const f=(a=e==null?void 0:e.type)===null||a===void 0?void 0:a.children[0];f&&(f.name="key");const h=(u=e==null?void 0:e.type)===null||u===void 0?void 0:u.children[1];h&&(h.name="value")}}get keyType(){return this.children[0].type.children[0].type}get valueType(){return this.children[0].type.children[1].type}get childType(){return this.children[0].type}toString(){return`Map<{${this.children[0].type.children.map(e=>`${e.name}:${e.type}`).join(", ")}}>`}}ng=Symbol.toStringTag;Pl[ng]=(n=>(n.children=null,n.keysSorted=null,n[Symbol.toStringTag]="Map_"))(Pl.prototype);const Wb=(n=>()=>++n)(-1);class Mi extends me{constructor(e,t,i,a){super(D.Dictionary),this.indices=t,this.dictionary=e,this.isOrdered=a||!1,this.id=i==null?Wb():tt(i)}get children(){return this.dictionary.children}get valueType(){return this.dictionary}get ArrayType(){return this.dictionary.ArrayType}toString(){return`Dictionary<${this.indices}, ${this.dictionary}>`}}rg=Symbol.toStringTag;Mi[rg]=(n=>(n.id=null,n.indices=null,n.isOrdered=null,n.dictionary=null,n[Symbol.toStringTag]="Dictionary"))(Mi.prototype);function vr(n){const e=n;switch(n.typeId){case D.Decimal:return n.bitWidth/32;case D.Interval:return 1+e.unit;case D.FixedSizeList:return e.listSize;case D.FixedSizeBinary:return e.byteWidth;default:return 1}}class Re{visitMany(e,...t){return e.map((i,a)=>this.visit(i,...t.map(u=>u[a])))}visit(...e){return this.getVisitFn(e[0],!1).apply(this,e)}getVisitFn(e,t=!0){return Hb(this,e,t)}getVisitFnByTypeId(e,t=!0){return mi(this,e,t)}visitNull(e,...t){return null}visitBool(e,...t){return null}visitInt(e,...t){return null}visitFloat(e,...t){return null}visitUtf8(e,...t){return null}visitLargeUtf8(e,...t){return null}visitBinary(e,...t){return null}visitLargeBinary(e,...t){return null}visitFixedSizeBinary(e,...t){return null}visitDate(e,...t){return null}visitTimestamp(e,...t){return null}visitTime(e,...t){return null}visitDecimal(e,...t){return null}visitList(e,...t){return null}visitStruct(e,...t){return null}visitUnion(e,...t){return null}visitDictionary(e,...t){return null}visitInterval(e,...t){return null}visitDuration(e,...t){return null}visitFixedSizeList(e,...t){return null}visitMap(e,...t){return null}}function Hb(n,e,t=!0){return typeof e=="number"?mi(n,e,t):typeof e=="string"&&e in D?mi(n,D[e],t):e&&e instanceof me?mi(n,bm(e),t):e!=null&&e.type&&e.type instanceof me?mi(n,bm(e.type),t):mi(n,D.NONE,t)}function mi(n,e,t=!0){let i=null;switch(e){case D.Null:i=n.visitNull;break;case D.Bool:i=n.visitBool;break;case D.Int:i=n.visitInt;break;case D.Int8:i=n.visitInt8||n.visitInt;break;case D.Int16:i=n.visitInt16||n.visitInt;break;case D.Int32:i=n.visitInt32||n.visitInt;break;case D.Int64:i=n.visitInt64||n.visitInt;break;case D.Uint8:i=n.visitUint8||n.visitInt;break;case D.Uint16:i=n.visitUint16||n.visitInt;break;case D.Uint32:i=n.visitUint32||n.visitInt;break;case D.Uint64:i=n.visitUint64||n.visitInt;break;case D.Float:i=n.visitFloat;break;case D.Float16:i=n.visitFloat16||n.visitFloat;break;case D.Float32:i=n.visitFloat32||n.visitFloat;break;case D.Float64:i=n.visitFloat64||n.visitFloat;break;case D.Utf8:i=n.visitUtf8;break;case D.LargeUtf8:i=n.visitLargeUtf8;break;case D.Binary:i=n.visitBinary;break;case D.LargeBinary:i=n.visitLargeBinary;break;case D.FixedSizeBinary:i=n.visitFixedSizeBinary;break;case D.Date:i=n.visitDate;break;case D.DateDay:i=n.visitDateDay||n.visitDate;break;case D.DateMillisecond:i=n.visitDateMillisecond||n.visitDate;break;case D.Timestamp:i=n.visitTimestamp;break;case D.TimestampSecond:i=n.visitTimestampSecond||n.visitTimestamp;break;case D.TimestampMillisecond:i=n.visitTimestampMillisecond||n.visitTimestamp;break;case D.TimestampMicrosecond:i=n.visitTimestampMicrosecond||n.visitTimestamp;break;case D.TimestampNanosecond:i=n.visitTimestampNanosecond||n.visitTimestamp;break;case D.Time:i=n.visitTime;break;case D.TimeSecond:i=n.visitTimeSecond||n.visitTime;break;case D.TimeMillisecond:i=n.visitTimeMillisecond||n.visitTime;break;case D.TimeMicrosecond:i=n.visitTimeMicrosecond||n.visitTime;break;case D.TimeNanosecond:i=n.visitTimeNanosecond||n.visitTime;break;case D.Decimal:i=n.visitDecimal;break;case D.List:i=n.visitList;break;case D.Struct:i=n.visitStruct;break;case D.Union:i=n.visitUnion;break;case D.DenseUnion:i=n.visitDenseUnion||n.visitUnion;break;case D.SparseUnion:i=n.visitSparseUnion||n.visitUnion;break;case D.Dictionary:i=n.visitDictionary;break;case D.Interval:i=n.visitInterval;break;case D.IntervalDayTime:i=n.visitIntervalDayTime||n.visitInterval;break;case D.IntervalYearMonth:i=n.visitIntervalYearMonth||n.visitInterval;break;case D.Duration:i=n.visitDuration;break;case D.DurationSecond:i=n.visitDurationSecond||n.visitDuration;break;case D.DurationMillisecond:i=n.visitDurationMillisecond||n.visitDuration;break;case D.DurationMicrosecond:i=n.visitDurationMicrosecond||n.visitDuration;break;case D.DurationNanosecond:i=n.visitDurationNanosecond||n.visitDuration;break;case D.FixedSizeList:i=n.visitFixedSizeList;break;case D.Map:i=n.visitMap;break}if(typeof i=="function")return i;if(!t)return()=>null;throw new Error(`Unrecognized type '${D[e]}'`)}function bm(n){switch(n.typeId){case D.Null:return D.Null;case D.Int:{const{bitWidth:e,isSigned:t}=n;switch(e){case 8:return t?D.Int8:D.Uint8;case 16:return t?D.Int16:D.Uint16;case 32:return t?D.Int32:D.Uint32;case 64:return t?D.Int64:D.Uint64}return D.Int}case D.Float:switch(n.precision){case Dt.HALF:return D.Float16;case Dt.SINGLE:return D.Float32;case Dt.DOUBLE:return D.Float64}return D.Float;case D.Binary:return D.Binary;case D.LargeBinary:return D.LargeBinary;case D.Utf8:return D.Utf8;case D.LargeUtf8:return D.LargeUtf8;case D.Bool:return D.Bool;case D.Decimal:return D.Decimal;case D.Time:switch(n.unit){case _e.SECOND:return D.TimeSecond;case _e.MILLISECOND:return D.TimeMillisecond;case _e.MICROSECOND:return D.TimeMicrosecond;case _e.NANOSECOND:return D.TimeNanosecond}return D.Time;case D.Timestamp:switch(n.unit){case _e.SECOND:return D.TimestampSecond;case _e.MILLISECOND:return D.TimestampMillisecond;case _e.MICROSECOND:return D.TimestampMicrosecond;case _e.NANOSECOND:return D.TimestampNanosecond}return D.Timestamp;case D.Date:switch(n.unit){case gn.DAY:return D.DateDay;case gn.MILLISECOND:return D.DateMillisecond}return D.Date;case D.Interval:switch(n.unit){case nr.DAY_TIME:return D.IntervalDayTime;case nr.YEAR_MONTH:return D.IntervalYearMonth}return D.Interval;case D.Duration:switch(n.unit){case _e.SECOND:return D.DurationSecond;case _e.MILLISECOND:return D.DurationMillisecond;case _e.MICROSECOND:return D.DurationMicrosecond;case _e.NANOSECOND:return D.DurationNanosecond}return D.Duration;case D.Map:return D.Map;case D.List:return D.List;case D.Struct:return D.Struct;case D.Union:switch(n.mode){case Ht.Dense:return D.DenseUnion;case Ht.Sparse:return D.SparseUnion}return D.Union;case D.FixedSizeBinary:return D.FixedSizeBinary;case D.FixedSizeList:return D.FixedSizeList;case D.Dictionary:return D.Dictionary}throw new Error(`Unrecognized type '${D[n.typeId]}'`)}Re.prototype.visitInt8=null;Re.prototype.visitInt16=null;Re.prototype.visitInt32=null;Re.prototype.visitInt64=null;Re.prototype.visitUint8=null;Re.prototype.visitUint16=null;Re.prototype.visitUint32=null;Re.prototype.visitUint64=null;Re.prototype.visitFloat16=null;Re.prototype.visitFloat32=null;Re.prototype.visitFloat64=null;Re.prototype.visitDateDay=null;Re.prototype.visitDateMillisecond=null;Re.prototype.visitTimestampSecond=null;Re.prototype.visitTimestampMillisecond=null;Re.prototype.visitTimestampMicrosecond=null;Re.prototype.visitTimestampNanosecond=null;Re.prototype.visitTimeSecond=null;Re.prototype.visitTimeMillisecond=null;Re.prototype.visitTimeMicrosecond=null;Re.prototype.visitTimeNanosecond=null;Re.prototype.visitDenseUnion=null;Re.prototype.visitSparseUnion=null;Re.prototype.visitIntervalDayTime=null;Re.prototype.visitIntervalYearMonth=null;Re.prototype.visitDuration=null;Re.prototype.visitDurationSecond=null;Re.prototype.visitDurationMillisecond=null;Re.prototype.visitDurationMicrosecond=null;Re.prototype.visitDurationNanosecond=null;const sg=new Float64Array(1),ai=new Uint32Array(sg.buffer);function ig(n){const e=(n&31744)>>10,t=(n&1023)/1024,i=Math.pow(-1,(n&32768)>>15);switch(e){case 31:return i*(t?Number.NaN:1/0);case 0:return i*(t?6103515625e-14*t:0)}return i*Math.pow(2,e-15)*(1+t)}function Gb(n){if(n!==n)return 32256;sg[0]=n;const e=(ai[1]&2147483648)>>16&65535;let t=ai[1]&2146435072,i=0;return t>=1089470464?ai[0]>0?t=31744:(t=(t&2080374784)>>16,i=(ai[1]&1048575)>>10):t<=1056964608?(i=1048576+(ai[1]&1048575),i=1048576+(i<<(t>>20)-998)>>21,t=0):(t=t-1056964608>>10,i=(ai[1]&1048575)+512>>10),e|t|i&65535}class Ne extends Re{}function Ie(n){return(e,t,i)=>{if(e.setValid(t,i!=null))return n(e,t,i)}}const Yb=(n,e,t)=>{n[e]=Math.floor(t/864e5)},og=(n,e,t,i)=>{if(t+1{const a=n+t;i?e[a>>3]|=1<>3]&=~(1<{n[e]=t},$d=({values:n},e,t)=>{n[e]=t},ag=({values:n},e,t)=>{n[e]=Gb(t)},Kb=(n,e,t)=>{switch(n.type.precision){case Dt.HALF:return ag(n,e,t);case Dt.SINGLE:case Dt.DOUBLE:return $d(n,e,t)}},lg=({values:n},e,t)=>{Yb(n,e,t.valueOf())},ug=({values:n},e,t)=>{n[e]=BigInt(t)},Jb=({stride:n,values:e},t,i)=>{e.set(i.subarray(0,n),n*t)},cg=({values:n,valueOffsets:e},t,i)=>og(n,e,t,i),dg=({values:n,valueOffsets:e},t,i)=>og(n,e,t,Bd(i)),qb=(n,e,t)=>{n.type.unit===gn.DAY?lg(n,e,t):ug(n,e,t)},fg=({values:n},e,t)=>{n[e]=BigInt(t/1e3)},hg=({values:n},e,t)=>{n[e]=BigInt(t)},pg=({values:n},e,t)=>{n[e]=BigInt(t*1e3)},mg=({values:n},e,t)=>{n[e]=BigInt(t*1e6)},Zb=(n,e,t)=>{switch(n.type.unit){case _e.SECOND:return fg(n,e,t);case _e.MILLISECOND:return hg(n,e,t);case _e.MICROSECOND:return pg(n,e,t);case _e.NANOSECOND:return mg(n,e,t)}},yg=({values:n},e,t)=>{n[e]=t},gg=({values:n},e,t)=>{n[e]=t},vg=({values:n},e,t)=>{n[e]=t},xg=({values:n},e,t)=>{n[e]=t},Xb=(n,e,t)=>{switch(n.type.unit){case _e.SECOND:return yg(n,e,t);case _e.MILLISECOND:return gg(n,e,t);case _e.MICROSECOND:return vg(n,e,t);case _e.NANOSECOND:return xg(n,e,t)}},ew=({values:n,stride:e},t,i)=>{n.set(i.subarray(0,e),e*t)},tw=(n,e,t)=>{const i=n.children[0],a=n.valueOffsets,u=vn.getVisitFn(i);if(Array.isArray(t))for(let f=-1,h=a[e],m=a[e+1];h{const i=n.children[0],{valueOffsets:a}=n,u=vn.getVisitFn(i);let{[e]:f,[e+1]:h}=a;const m=t instanceof Map?t.entries():Object.entries(t);for(const g of m)if(u(i,f,g),++f>=h)break},rw=(n,e)=>(t,i,a,u)=>i&&t(i,n,e[u]),sw=(n,e)=>(t,i,a,u)=>i&&t(i,n,e.get(u)),iw=(n,e)=>(t,i,a,u)=>i&&t(i,n,e.get(a.name)),ow=(n,e)=>(t,i,a,u)=>i&&t(i,n,e[a.name]),aw=(n,e,t)=>{const i=n.type.children.map(u=>vn.getVisitFn(u.type)),a=t instanceof Map?iw(e,t):t instanceof Je?sw(e,t):Array.isArray(t)?rw(e,t):ow(e,t);n.type.children.forEach((u,f)=>a(i[f],n.children[f],u,f))},lw=(n,e,t)=>{n.type.mode===Ht.Dense?bg(n,e,t):wg(n,e,t)},bg=(n,e,t)=>{const i=n.type.typeIdToChildIndex[n.typeIds[e]],a=n.children[i];vn.visit(a,n.valueOffsets[e],t)},wg=(n,e,t)=>{const i=n.type.typeIdToChildIndex[n.typeIds[e]],a=n.children[i];vn.visit(a,e,t)},uw=(n,e,t)=>{var i;(i=n.dictionary)===null||i===void 0||i.set(n.values[e],t)},cw=(n,e,t)=>{n.type.unit===nr.DAY_TIME?Sg(n,e,t):_g(n,e,t)},Sg=({values:n},e,t)=>{n.set(t.subarray(0,2),2*e)},_g=({values:n},e,t)=>{n[e]=t[0]*12+t[1]%12},Ng=({values:n},e,t)=>{n[e]=t},jg=({values:n},e,t)=>{n[e]=t},kg=({values:n},e,t)=>{n[e]=t},Ig=({values:n},e,t)=>{n[e]=t},dw=(n,e,t)=>{switch(n.type.unit){case _e.SECOND:return Ng(n,e,t);case _e.MILLISECOND:return jg(n,e,t);case _e.MICROSECOND:return kg(n,e,t);case _e.NANOSECOND:return Ig(n,e,t)}},fw=(n,e,t)=>{const{stride:i}=n,a=n.children[0],u=vn.getVisitFn(a);if(Array.isArray(t))for(let f=-1,h=e*i;++f`${Bo(e)}: ${Bo(t)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}[Symbol.iterator](){return new hw(this[On],this[Si])}}class hw{constructor(e,t){this.childIndex=0,this.children=e.children,this.rowIndex=t,this.childFields=e.type.children,this.numChildren=this.childFields.length}[Symbol.iterator](){return this}next(){const e=this.childIndex;return et.name)}has(e,t){return e[On].type.children.findIndex(i=>i.name===t)!==-1}getOwnPropertyDescriptor(e,t){if(e[On].type.children.findIndex(i=>i.name===t)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(e,t){if(Reflect.has(e,t))return e[t];const i=e[On].type.children.findIndex(a=>a.name===t);if(i!==-1){const a=Gt.visit(e[On].children[i],e[Si]);return Reflect.set(e,t,a),a}}set(e,t,i){const a=e[On].type.children.findIndex(u=>u.name===t);return a!==-1?(vn.visit(e[On].children[a],e[Si],i),Reflect.set(e,t,i)):Reflect.has(e,t)||typeof t=="symbol"?Reflect.set(e,t,i):!1}}class ve extends Re{}function je(n){return(e,t)=>e.getValid(t)?n(e,t):null}const mw=(n,e)=>864e5*n[e],yw=(n,e)=>null,Mg=(n,e,t)=>{if(t+1>=e.length)return null;const i=tt(e[t]),a=tt(e[t+1]);return n.subarray(i,a)},gw=({offset:n,values:e},t)=>{const i=n+t;return(e[i>>3]&1<mw(n,e),Cg=({values:n},e)=>tt(n[e]),as=({stride:n,values:e},t)=>e[n*t],vw=({stride:n,values:e},t)=>ig(e[n*t]),Fg=({values:n},e)=>n[e],xw=({stride:n,values:e},t)=>e.subarray(n*t,n*(t+1)),Og=({values:n,valueOffsets:e},t)=>Mg(n,e,t),Tg=({values:n,valueOffsets:e},t)=>{const i=Mg(n,e,t);return i!==null?xd(i):null},bw=({values:n},e)=>n[e],ww=({type:n,values:e},t)=>n.precision!==Dt.HALF?e[t]:ig(e[t]),Sw=(n,e)=>n.type.unit===gn.DAY?Dg(n,e):Cg(n,e),Ag=({values:n},e)=>1e3*tt(n[e]),Bg=({values:n},e)=>tt(n[e]),Eg=({values:n},e)=>Ay(n[e],BigInt(1e3)),Rg=({values:n},e)=>Ay(n[e],BigInt(1e6)),_w=(n,e)=>{switch(n.type.unit){case _e.SECOND:return Ag(n,e);case _e.MILLISECOND:return Bg(n,e);case _e.MICROSECOND:return Eg(n,e);case _e.NANOSECOND:return Rg(n,e)}},Lg=({values:n},e)=>n[e],Ug=({values:n},e)=>n[e],$g=({values:n},e)=>n[e],Pg=({values:n},e)=>n[e],Nw=(n,e)=>{switch(n.type.unit){case _e.SECOND:return Lg(n,e);case _e.MILLISECOND:return Ug(n,e);case _e.MICROSECOND:return $g(n,e);case _e.NANOSECOND:return Pg(n,e)}},jw=({values:n,stride:e},t)=>Ud.decimal(n.subarray(e*t,e*(t+1))),kw=(n,e)=>{const{valueOffsets:t,stride:i,children:a}=n,{[e*i]:u,[e*i+1]:f}=t,m=a[0].slice(u,f-u);return new Je([m])},Iw=(n,e)=>{const{valueOffsets:t,children:i}=n,{[e]:a,[e+1]:u}=t,f=i[0];return new zd(f.slice(a,u-a))},Mw=(n,e)=>new Pd(n,e),Dw=(n,e)=>n.type.mode===Ht.Dense?zg(n,e):Vg(n,e),zg=(n,e)=>{const t=n.type.typeIdToChildIndex[n.typeIds[e]],i=n.children[t];return Gt.visit(i,n.valueOffsets[e])},Vg=(n,e)=>{const t=n.type.typeIdToChildIndex[n.typeIds[e]],i=n.children[t];return Gt.visit(i,e)},Cw=(n,e)=>{var t;return(t=n.dictionary)===null||t===void 0?void 0:t.get(n.values[e])},Fw=(n,e)=>n.type.unit===nr.DAY_TIME?Wg(n,e):Hg(n,e),Wg=({values:n},e)=>n.subarray(2*e,2*(e+1)),Hg=({values:n},e)=>{const t=n[e],i=new Int32Array(2);return i[0]=Math.trunc(t/12),i[1]=Math.trunc(t%12),i},Gg=({values:n},e)=>n[e],Yg=({values:n},e)=>n[e],Qg=({values:n},e)=>n[e],Kg=({values:n},e)=>n[e],Ow=(n,e)=>{switch(n.type.unit){case _e.SECOND:return Gg(n,e);case _e.MILLISECOND:return Yg(n,e);case _e.MICROSECOND:return Qg(n,e);case _e.NANOSECOND:return Kg(n,e)}},Tw=(n,e)=>{const{stride:t,children:i}=n,u=i[0].slice(e*t,t);return new Je([u])};ve.prototype.visitNull=je(yw);ve.prototype.visitBool=je(gw);ve.prototype.visitInt=je(bw);ve.prototype.visitInt8=je(as);ve.prototype.visitInt16=je(as);ve.prototype.visitInt32=je(as);ve.prototype.visitInt64=je(Fg);ve.prototype.visitUint8=je(as);ve.prototype.visitUint16=je(as);ve.prototype.visitUint32=je(as);ve.prototype.visitUint64=je(Fg);ve.prototype.visitFloat=je(ww);ve.prototype.visitFloat16=je(vw);ve.prototype.visitFloat32=je(as);ve.prototype.visitFloat64=je(as);ve.prototype.visitUtf8=je(Tg);ve.prototype.visitLargeUtf8=je(Tg);ve.prototype.visitBinary=je(Og);ve.prototype.visitLargeBinary=je(Og);ve.prototype.visitFixedSizeBinary=je(xw);ve.prototype.visitDate=je(Sw);ve.prototype.visitDateDay=je(Dg);ve.prototype.visitDateMillisecond=je(Cg);ve.prototype.visitTimestamp=je(_w);ve.prototype.visitTimestampSecond=je(Ag);ve.prototype.visitTimestampMillisecond=je(Bg);ve.prototype.visitTimestampMicrosecond=je(Eg);ve.prototype.visitTimestampNanosecond=je(Rg);ve.prototype.visitTime=je(Nw);ve.prototype.visitTimeSecond=je(Lg);ve.prototype.visitTimeMillisecond=je(Ug);ve.prototype.visitTimeMicrosecond=je($g);ve.prototype.visitTimeNanosecond=je(Pg);ve.prototype.visitDecimal=je(jw);ve.prototype.visitList=je(kw);ve.prototype.visitStruct=je(Mw);ve.prototype.visitUnion=je(Dw);ve.prototype.visitDenseUnion=je(zg);ve.prototype.visitSparseUnion=je(Vg);ve.prototype.visitDictionary=je(Cw);ve.prototype.visitInterval=je(Fw);ve.prototype.visitIntervalDayTime=je(Wg);ve.prototype.visitIntervalYearMonth=je(Hg);ve.prototype.visitDuration=je(Ow);ve.prototype.visitDurationSecond=je(Gg);ve.prototype.visitDurationMillisecond=je(Yg);ve.prototype.visitDurationMicrosecond=je(Qg);ve.prototype.visitDurationNanosecond=je(Kg);ve.prototype.visitFixedSizeList=je(Tw);ve.prototype.visitMap=je(Iw);const Gt=new ve,yi=Symbol.for("keys"),_i=Symbol.for("vals"),gi=Symbol.for("kKeysAsStrings"),jd=Symbol.for("_kKeysAsStrings");class zd{constructor(e){return this[yi]=new Je([e.children[0]]).memoize(),this[_i]=e.children[1],new Proxy(this,new Bw)}get[gi](){return this[jd]||(this[jd]=Array.from(this[yi].toArray(),String))}[Symbol.iterator](){return new Aw(this[yi],this[_i])}get size(){return this[yi].length}toArray(){return Object.values(this.toJSON())}toJSON(){const e=this[yi],t=this[_i],i={};for(let a=-1,u=e.length;++a`${Bo(e)}: ${Bo(t)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}class Aw{constructor(e,t){this.keys=e,this.vals=t,this.keyIndex=0,this.numKeys=e.length}[Symbol.iterator](){return this}next(){const e=this.keyIndex;return e===this.numKeys?{done:!0,value:null}:(this.keyIndex++,{done:!1,value:[this.keys.get(e),Gt.visit(this.vals,e)]})}}class Bw{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(e){return e[gi]}has(e,t){return e[gi].includes(t)}getOwnPropertyDescriptor(e,t){if(e[gi].indexOf(t)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(e,t){if(Reflect.has(e,t))return e[t];const i=e[gi].indexOf(t);if(i!==-1){const a=Gt.visit(Reflect.get(e,_i),i);return Reflect.set(e,t,a),a}}set(e,t,i){const a=e[gi].indexOf(t);return a!==-1?(vn.visit(Reflect.get(e,_i),a,i),Reflect.set(e,t,i)):Reflect.has(e,t)?Reflect.set(e,t,i):!1}}Object.defineProperties(zd.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:"Row"},[yi]:{writable:!0,enumerable:!1,configurable:!1,value:null},[_i]:{writable:!0,enumerable:!1,configurable:!1,value:null},[jd]:{writable:!0,enumerable:!1,configurable:!1,value:null}});let wm;function Jg(n,e,t,i){const{length:a=0}=n;let u=typeof e!="number"?0:e,f=typeof t!="number"?a:t;return u<0&&(u=(u%a+a)%a),f<0&&(f=(f%a+a)%a),fa&&(f=a),i?i(n,u,f):[u,f]}const Vd=(n,e)=>n<0?e+n:n,Sm=n=>n!==n;function Ti(n){if(typeof n!=="object"||n===null)return Sm(n)?Sm:t=>t===n;if(n instanceof Date){const t=n.valueOf();return i=>i instanceof Date?i.valueOf()===t:!1}return ArrayBuffer.isView(n)?t=>t?Tb(n,t):!1:n instanceof Map?Rw(n):Array.isArray(n)?Ew(n):n instanceof Je?Lw(n):Uw(n,!0)}function Ew(n){const e=[];for(let t=-1,i=n.length;++t!1;const i=[];for(let a=-1,u=t.length;++a{if(!t||typeof t!="object")return!1;switch(t.constructor){case Array:return $w(n,t);case Map:return _m(n,t,t.keys());case zd:case Pd:case Object:case void 0:return _m(n,t,e||Object.keys(t))}return t instanceof Je?Pw(n,t):!1}}function $w(n,e){const t=n.length;if(e.length!==t)return!1;for(let i=-1;++i>i}function Nm(n,e,t){const i=t.byteLength+7&-8;if(n>0||t.byteLength>3):kd(new Wd(t,n,e,null,qg)).subarray(0,i)),a}return t}function kd(n){const e=[];let t=0,i=0,a=0;for(const f of n)f&&(a|=1<0)&&(e[t++]=a);const u=new Uint8Array(e.length+7&-8);return u.set(e),u}class Wd{constructor(e,t,i,a,u){this.bytes=e,this.length=i,this.context=a,this.get=u,this.bit=t%8,this.byteIndex=t>>3,this.byte=e[this.byteIndex++],this.index=0}next(){return this.index>3<<3,a=e+(e%8===0?0:8-e%8);return Id(n,e,a)+Id(n,i,t)+Vw(n,a>>3,i-a>>3)}function Vw(n,e,t){let i=0,a=Math.trunc(e);const u=new DataView(n.buffer,n.byteOffset,n.byteLength),f=t===void 0?n.byteLength:a+t;for(;f-a>=4;)i+=id(u.getUint32(a)),a+=4;for(;f-a>=2;)i+=id(u.getUint16(a)),a+=2;for(;f-a>=1;)i+=id(u.getUint8(a)),a+=1;return i}function id(n){let e=Math.trunc(n);return e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),(e+(e>>>4)&252645135)*16843009>>>24}const Ww=-1;class Ye{get typeId(){return this.type.typeId}get ArrayType(){return this.type.ArrayType}get buffers(){return[this.valueOffsets,this.values,this.nullBitmap,this.typeIds]}get nullable(){if(this._nullCount!==0){const{type:e}=this;return me.isSparseUnion(e)?this.children.some(t=>t.nullable):me.isDenseUnion(e)?this.children.some(t=>t.nullable):this.nullBitmap&&this.nullBitmap.byteLength>0}return!0}get byteLength(){let e=0;const{valueOffsets:t,values:i,nullBitmap:a,typeIds:u}=this;return t&&(e+=t.byteLength),i&&(e+=i.byteLength),a&&(e+=a.byteLength),u&&(e+=u.byteLength),this.children.reduce((f,h)=>f+h.byteLength,e)}get nullCount(){if(me.isUnion(this.type))return this.children.reduce((i,a)=>i+a.nullCount,0);let e=this._nullCount,t;return e<=Ww&&(t=this.nullBitmap)&&(this._nullCount=e=t.length===0?0:this.length-Id(t,this.offset,this.offset+this.length)),e}constructor(e,t,i,a,u,f=[],h){this.type=e,this.children=f,this.dictionary=h,this.offset=Math.floor(Math.max(t||0,0)),this.length=Math.floor(Math.max(i||0,0)),this._nullCount=Math.floor(Math.max(a||0,-1));let m;u instanceof Ye?(this.stride=u.stride,this.values=u.values,this.typeIds=u.typeIds,this.nullBitmap=u.nullBitmap,this.valueOffsets=u.valueOffsets):(this.stride=vr(e),u&&((m=u[0])&&(this.valueOffsets=m),(m=u[1])&&(this.values=m),(m=u[2])&&(this.nullBitmap=m),(m=u[3])&&(this.typeIds=m)))}getValid(e){const{type:t}=this;if(me.isUnion(t)){const i=t,a=this.children[i.typeIdToChildIndex[this.typeIds[e]]],u=i.mode===Ht.Dense?this.valueOffsets[e]:e;return a.getValid(u)}if(this.nullable&&this.nullCount>0){const i=this.offset+e;return(this.nullBitmap[i>>3]&1<>3;(!u||u.byteLength<=v)&&(u=new Uint8Array((f+h+63&-64)>>3).fill(255),this.nullCount>0?(u.set(Nm(f,h,this.nullBitmap),0),Object.assign(this,{nullBitmap:u})):Object.assign(this,{nullBitmap:u,_nullCount:0}));const x=u[v];i=(x&g)!==0,u[v]=t?x|g:x&~g}return i!==!!t&&(this._nullCount=this.nullCount+(t?-1:1)),t}clone(e=this.type,t=this.offset,i=this.length,a=this._nullCount,u=this,f=this.children){return new Ye(e,t,i,a,u,f,this.dictionary)}slice(e,t){const{stride:i,typeId:a,children:u}=this,f=+(this._nullCount===0)-1,h=a===16?i:1,m=this._sliceBuffers(e,t,i,a);return this.clone(this.type,this.offset+e,t,f,m,u.length===0||this.valueOffsets?u:this._sliceChildren(u,h*e,h*t))}_changeLengthAndBackfillNullBitmap(e){if(this.typeId===D.Null)return this.clone(this.type,0,e,0);const{length:t,nullCount:i}=this,a=new Uint8Array((e+63&-64)>>3).fill(255,0,t>>3);a[t>>3]=(1<0&&a.set(Nm(this.offset,t,this.nullBitmap),0);const u=this.buffers;return u[gr.VALIDITY]=a,this.clone(this.type,0,e,i+(e-t),u)}_sliceBuffers(e,t,i,a){let u;const{buffers:f}=this;return(u=f[gr.TYPE])&&(f[gr.TYPE]=u.subarray(e,e+t)),(u=f[gr.OFFSET])&&(f[gr.OFFSET]=u.subarray(e,e+t+1))||(u=f[gr.DATA])&&(f[gr.DATA]=a===6?u:u.subarray(i*e,i*(e+t))),f}_sliceChildren(e,t,i){return e.map(a=>a.slice(t,i))}}Ye.prototype.children=Object.freeze([]);class To extends Re{visit(e){return this.getVisitFn(e.type).call(this,e)}visitNull(e){const{["type"]:t,["offset"]:i=0,["length"]:a=0}=e;return new Ye(t,i,a,a)}visitBool(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length>>3,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitInt(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitFloat(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitUtf8(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitLargeUtf8(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=cm(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitBinary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitLargeBinary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=cm(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitFixedSizeBinary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitDate(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitTimestamp(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitTime(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitDecimal(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitList(e){const{["type"]:t,["offset"]:i=0,["child"]:a}=e,u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,void 0,u],[a])}visitStruct(e){const{["type"]:t,["offset"]:i=0,["children"]:a=[]}=e,u=$e(e.nullBitmap),{length:f=a.reduce((m,{length:g})=>Math.max(m,g),0),nullCount:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,void 0,u],a)}visitUnion(e){const{["type"]:t,["offset"]:i=0,["children"]:a=[]}=e,u=Ke(t.ArrayType,e.typeIds),{["length"]:f=u.length,["nullCount"]:h=-1}=e;if(me.isSparseUnion(t))return new Ye(t,i,f,h,[void 0,void 0,void 0,u],a);const m=So(e.valueOffsets);return new Ye(t,i,f,h,[m,void 0,void 0,u],a)}visitDictionary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.indices.ArrayType,e.data),{["dictionary"]:f=new Je([new To().visit({type:t.dictionary})])}=e,{["length"]:h=u.length,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[void 0,u,a],[],f)}visitInterval(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitDuration(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitFixedSizeList(e){const{["type"]:t,["offset"]:i=0,["child"]:a=new To().visit({type:t.valueType})}=e,u=$e(e.nullBitmap),{["length"]:f=a.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,void 0,u],[a])}visitMap(e){const{["type"]:t,["offset"]:i=0,["child"]:a=new To().visit({type:t.childType})}=e,u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,void 0,u],[a])}}const Hw=new To;function Ee(n){return Hw.visit(n)}class jm{constructor(e=0,t){this.numChunks=e,this.getChunkIterator=t,this.chunkIndex=0,this.chunkIterator=this.getChunkIterator(0)}next(){for(;this.chunkIndexe.nullable)}function Zg(n){return n.reduce((e,t)=>e+t.nullCount,0)}function Xg(n){return n.reduce((e,t,i)=>(e[i+1]=e[i]+t.length,e),new Uint32Array(n.length+1))}function ev(n,e,t,i){const a=[];for(let u=-1,f=n.length;++u=i)break;if(t>=m+g)continue;if(m>=t&&m+g<=i){a.push(h);continue}const v=Math.max(0,t-m),x=Math.min(i-m,g);a.push(h.slice(v,x-v))}return a.length===0&&a.push(n[0].slice(0,0)),a}function Hd(n,e,t,i){let a=0,u=0,f=e.length-1;do{if(a>=f-1)return t0?0:-1}function Qw(n,e){const{nullBitmap:t}=n;if(!t||n.nullCount<=0)return-1;let i=0;for(const a of new Wd(t,n.offset+(e||0),n.length,t,qg)){if(!a)return i;++i}return-1}function De(n,e,t){if(e===void 0)return-1;if(e===null)switch(n.typeId){case D.Union:break;case D.Dictionary:break;default:return Qw(n,t)}const i=Gt.getVisitFn(n),a=Ti(e);for(let u=(t||0)-1,f=n.length;++u{const a=n.data[i];return a.values.subarray(0,a.length)[Symbol.iterator]()});let t=0;return new jm(n.data.length,i=>{const u=n.data[i].length,f=n.slice(t,t+u);return t+=u,new Kw(f)})}class Kw{constructor(e){this.vector=e,this.index=0}next(){return this.indexh.data):e;if(u.length===0||u.some(h=>!(h instanceof Ye)))throw new TypeError("Vector constructor expects an Array of Data instances.");const f=(t=u[0])===null||t===void 0?void 0:t.type;switch(u.length){case 0:this._offsets=[0];break;case 1:{const{get:h,set:m,indexOf:g}=iv[f.typeId],v=u[0];this.isValid=x=>Gd(v,x),this.get=x=>h(v,x),this.set=(x,b)=>m(v,x,b),this.indexOf=x=>g(v,x),this._offsets=[0,v.length];break}default:Object.setPrototypeOf(this,ov[f.typeId]),this._offsets=Xg(u);break}this.data=u,this.type=f,this.stride=vr(f),this.numChildren=(a=(i=f.children)===null||i===void 0?void 0:i.length)!==null&&a!==void 0?a:0,this.length=this._offsets.at(-1)}get byteLength(){return this.data.reduce((e,t)=>e+t.byteLength,0)}get nullable(){return Gw(this.data)}get nullCount(){return Zg(this.data)}get ArrayType(){return this.type.ArrayType}get[Symbol.toStringTag](){return`${this.VectorName}<${this.type[Symbol.toStringTag]}>`}get VectorName(){return`${D[this.type.typeId]}Vector`}isValid(e){return!1}get(e){return null}at(e){return this.get(Vd(e,this.length))}set(e,t){}indexOf(e,t){return-1}includes(e,t){return this.indexOf(e,t)>-1}[Symbol.iterator](){return Yd.visit(this)}concat(...e){return new Je(this.data.concat(e.flatMap(t=>t.data).flat(Number.POSITIVE_INFINITY)))}slice(e,t){return new Je(Jg(this,e,t,({data:i,_offsets:a},u,f)=>ev(i,a,u,f)))}toJSON(){return[...this]}toArray(){const{type:e,data:t,length:i,stride:a,ArrayType:u}=this;switch(e.typeId){case D.Int:case D.Float:case D.Decimal:case D.Time:case D.Timestamp:switch(t.length){case 0:return new u;case 1:return t[0].values.subarray(0,i*a);default:return t.reduce((f,{values:h,length:m})=>(f.array.set(h.subarray(0,m*a),f.offset),f.offset+=m*a,f),{array:new u(i*a),offset:0}).array}}return[...this]}toString(){return`[${[...this].join(",")}]`}getChild(e){var t;return this.getChildAt((t=this.type.children)===null||t===void 0?void 0:t.findIndex(i=>i.name===e))}getChildAt(e){return e>-1&&et[e])):null}get isMemoized(){return me.isDictionary(this.type)?this.data[0].dictionary.isMemoized:!1}memoize(){if(me.isDictionary(this.type)){const e=new Wl(this.data[0].dictionary),t=this.data.map(i=>{const a=i.clone();return a.dictionary=e,a});return new Je(t)}return new Wl(this)}unmemoize(){if(me.isDictionary(this.type)&&this.isMemoized){const e=this.data[0].dictionary.unmemoize(),t=this.data.map(i=>{const a=i.clone();return a.dictionary=e,a});return new Je(t)}return this}}sv=Symbol.toStringTag;Je[sv]=(n=>{n.type=me.prototype,n.data=[],n.length=0,n.stride=1,n.numChildren=0,n._offsets=new Uint32Array([0]),n[Symbol.isConcatSpreadable]=!0;const e=Object.keys(D).map(t=>D[t]).filter(t=>typeof t=="number"&&t!==D.NONE);for(const t of e){const i=Gt.getVisitFnByTypeId(t),a=vn.getVisitFnByTypeId(t),u=Vl.getVisitFnByTypeId(t);iv[t]={get:i,set:a,indexOf:u},ov[t]=Object.create(n,{isValid:{value:zl(Gd)},get:{value:zl(Gt.getVisitFnByTypeId(t))},set:{value:tv(vn.getVisitFnByTypeId(t))},indexOf:{value:nv(Vl.getVisitFnByTypeId(t))}})}return"Vector"})(Je.prototype);class Wl extends Je{constructor(e){super(e.data);const t=this.get,i=this.set,a=this.slice,u=new Array(this.length);Object.defineProperty(this,"get",{value(f){const h=u[f];if(h!==void 0)return h;const m=t.call(this,f);return u[f]=m,m}}),Object.defineProperty(this,"set",{value(f,h){i.call(this,f,h),u[f]=h}}),Object.defineProperty(this,"slice",{value:(f,h)=>new Wl(a.call(this,f,h))}),Object.defineProperty(this,"isMemoized",{value:!0}),Object.defineProperty(this,"unmemoize",{value:()=>new Je(this.data)}),Object.defineProperty(this,"memoize",{value:()=>this})}}class Md{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}offset(){return this.bb.readInt64(this.bb_pos)}metaDataLength(){return this.bb.readInt32(this.bb_pos+8)}bodyLength(){return this.bb.readInt64(this.bb_pos+16)}static sizeOf(){return 24}static createBlock(e,t,i,a){return e.prep(8,24),e.writeInt64(BigInt(a??0)),e.pad(4),e.writeInt32(i),e.writeInt64(BigInt(t??0)),e.offset()}}class Xt{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsFooter(e,t){return(t||new Xt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsFooter(e,t){return e.setPosition(e.position()+He),(t||new Xt).__init(e.readInt32(e.position())+e.position(),e)}version(){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):ht.V1}schema(e){const t=this.bb.__offset(this.bb_pos,6);return t?(e||new Gn).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}dictionaries(e,t){const i=this.bb.__offset(this.bb_pos,8);return i?(t||new Md).__init(this.bb.__vector(this.bb_pos+i)+e*24,this.bb):null}dictionariesLength(){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}recordBatches(e,t){const i=this.bb.__offset(this.bb_pos,10);return i?(t||new Md).__init(this.bb.__vector(this.bb_pos+i)+e*24,this.bb):null}recordBatchesLength(){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,12);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}static startFooter(e){e.startObject(5)}static addVersion(e,t){e.addFieldInt16(0,t,ht.V1)}static addSchema(e,t){e.addFieldOffset(1,t,0)}static addDictionaries(e,t){e.addFieldOffset(2,t,0)}static startDictionariesVector(e,t){e.startVector(24,t,8)}static addRecordBatches(e,t){e.addFieldOffset(3,t,0)}static startRecordBatchesVector(e,t){e.startVector(24,t,8)}static addCustomMetadata(e,t){e.addFieldOffset(4,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endFooter(e){return e.endObject()}static finishFooterBuffer(e,t){e.finish(t)}static finishSizePrefixedFooterBuffer(e,t){e.finish(t,void 0,!0)}}class We{constructor(e=[],t,i,a=ht.V5){this.fields=e||[],this.metadata=t||new Map,i||(i=Dd(this.fields)),this.dictionaries=i,this.metadataVersion=a}get[Symbol.toStringTag](){return"Schema"}get names(){return this.fields.map(e=>e.name)}toString(){return`Schema<{ ${this.fields.map((e,t)=>`${t}: ${e}`).join(", ")} }>`}select(e){const t=new Set(e),i=this.fields.filter(a=>t.has(a.name));return new We(i,this.metadata)}selectAt(e){const t=e.map(i=>this.fields[i]).filter(Boolean);return new We(t,this.metadata)}assign(...e){const t=e[0]instanceof We?e[0]:Array.isArray(e[0])?new We(e[0]):new We(e),i=[...this.fields],a=sl(sl(new Map,this.metadata),t.metadata),u=t.fields.filter(h=>{const m=i.findIndex(g=>g.name===h.name);return~m?(i[m]=h.clone({metadata:sl(sl(new Map,i[m].metadata),h.metadata)}))&&!1:!0}),f=Dd(u,new Map);return new We([...i,...u],a,new Map([...this.dictionaries,...f]))}}We.prototype.fields=null;We.prototype.metadata=null;We.prototype.dictionaries=null;class nt{static new(...e){let[t,i,a,u]=e;return e[0]&&typeof e[0]=="object"&&({name:t}=e[0],i===void 0&&(i=e[0].type),a===void 0&&(a=e[0].nullable),u===void 0&&(u=e[0].metadata)),new nt(`${t}`,i,a,u)}constructor(e,t,i=!1,a){this.name=e,this.type=t,this.nullable=i,this.metadata=a||new Map}get typeId(){return this.type.typeId}get[Symbol.toStringTag](){return"Field"}toString(){return`${this.name}: ${this.type}`}clone(...e){let[t,i,a,u]=e;return!e[0]||typeof e[0]!="object"?[t=this.name,i=this.type,a=this.nullable,u=this.metadata]=e:{name:t=this.name,type:i=this.type,nullable:a=this.nullable,metadata:u=this.metadata}=e[0],nt.new(t,i,a,u)}}nt.prototype.type=null;nt.prototype.name=null;nt.prototype.nullable=null;nt.prototype.metadata=null;function sl(n,e){return new Map([...n||new Map,...e||new Map])}function Dd(n,e=new Map){for(let t=-1,i=n.length;++t0&&Dd(u.children,e)}return e}var Jw=Cy,qw=ki;class Qd{static decode(e){e=new qw($e(e));const t=Xt.getRootAsFooter(e),i=We.decode(t.schema(),new Map,t.version());return new Zw(i,t)}static encode(e){const t=new Jw,i=We.encode(t,e.schema);Xt.startRecordBatchesVector(t,e.numRecordBatches);for(const f of[...e.recordBatches()].slice().reverse())Di.encode(t,f);const a=t.endVector();Xt.startDictionariesVector(t,e.numDictionaries);for(const f of[...e.dictionaryBatches()].slice().reverse())Di.encode(t,f);const u=t.endVector();return Xt.startFooter(t),Xt.addSchema(t,i),Xt.addVersion(t,ht.V5),Xt.addRecordBatches(t,a),Xt.addDictionaries(t,u),Xt.finishFooterBuffer(t,Xt.endFooter(t)),t.asUint8Array()}get numRecordBatches(){return this._recordBatches.length}get numDictionaries(){return this._dictionaryBatches.length}constructor(e,t=ht.V5,i,a){this.schema=e,this.version=t,i&&(this._recordBatches=i),a&&(this._dictionaryBatches=a)}*recordBatches(){for(let e,t=-1,i=this.numRecordBatches;++t=0&&e=0&&e=0&&e=0&&ethis._closedPromiseResolve=e)}get closed(){return this._closedPromise}cancel(e){return Fe(this,void 0,void 0,function*(){yield this.return(e)})}write(e){this._ensureOpen()&&(this.resolvers.length<=0?this._values.push(e):this.resolvers.shift().resolve({done:!1,value:e}))}abort(e){this._closedPromiseResolve&&(this.resolvers.length<=0?this._error={error:e}:this.resolvers.shift().reject({done:!0,value:e}))}close(){if(this._closedPromiseResolve){const{resolvers:e}=this;for(;e.length>0;)e.shift().resolve(at);this._closedPromiseResolve(),this._closedPromiseResolve=void 0}}[Symbol.asyncIterator](){return this}toDOMStream(e){return fn.toDOMStream(this._closedPromiseResolve||this._error?this:this._values,e)}toNodeStream(e){return fn.toNodeStream(this._closedPromiseResolve||this._error?this:this._values,e)}throw(e){return Fe(this,void 0,void 0,function*(){return yield this.abort(e),at})}return(e){return Fe(this,void 0,void 0,function*(){return yield this.close(),at})}read(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"read")).value})}peek(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"peek")).value})}next(...e){return this._values.length>0?Promise.resolve({done:!1,value:this._values.shift()}):this._error?Promise.reject({done:!0,value:this._error.error}):this._closedPromiseResolve?new Promise((t,i)=>{this.resolvers.push({resolve:t,reject:i})}):Promise.resolve(at)}_ensureOpen(){if(this._closedPromiseResolve)return!0;throw new Error("AsyncQueue is closed")}}class e1 extends Xw{write(e){if((e=$e(e)).byteLength>0)return super.write(e)}toString(e=!1){return e?xd(this.toUint8Array(!0)):this.toUint8Array(!1).then(xd)}toUint8Array(e=!1){return e?tr(this._values)[0]:Fe(this,void 0,void 0,function*(){var t,i,a,u;const f=[];let h=0;try{for(var m=!0,g=xi(this),v;v=yield g.next(),t=v.done,!t;m=!0){u=v.value,m=!1;const x=u;f.push(x),h+=x.byteLength}}catch(x){i={error:x}}finally{try{!m&&!t&&(a=g.return)&&(yield a.call(g))}finally{if(i)throw i.error}}return tr(f,h)[0]})}}class Hl{constructor(e){e&&(this.source=new t1(fn.fromIterable(e)))}[Symbol.iterator](){return this}next(e){return this.source.next(e)}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}peek(e){return this.source.peek(e)}read(e){return this.source.read(e)}}class Ci{constructor(e){e instanceof Ci?this.source=e.source:e instanceof e1?this.source=new js(fn.fromAsyncIterable(e)):Iy(e)?this.source=new js(fn.fromNodeStream(e)):Rd(e)?this.source=new js(fn.fromDOMStream(e)):jy(e)?this.source=new js(fn.fromDOMStream(e.body)):nu(e)?this.source=new js(fn.fromIterable(e)):Ao(e)?this.source=new js(fn.fromAsyncIterable(e)):Ed(e)&&(this.source=new js(fn.fromAsyncIterable(e)))}[Symbol.asyncIterator](){return this}next(e){return this.source.next(e)}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}get closed(){return this.source.closed}cancel(e){return this.source.cancel(e)}peek(e){return this.source.peek(e)}read(e){return this.source.read(e)}}class t1{constructor(e){this.source=e}cancel(e){this.return(e)}peek(e){return this.next(e,"peek").value}read(e){return this.next(e,"read").value}next(e,t="read"){return this.source.next({cmd:t,size:e})}throw(e){return Object.create(this.source.throw&&this.source.throw(e)||at)}return(e){return Object.create(this.source.return&&this.source.return(e)||at)}}class js{constructor(e){this.source=e,this._closedPromise=new Promise(t=>this._closedPromiseResolve=t)}cancel(e){return Fe(this,void 0,void 0,function*(){yield this.return(e)})}get closed(){return this._closedPromise}read(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"read")).value})}peek(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"peek")).value})}next(e){return Fe(this,arguments,void 0,function*(t,i="read"){return yield this.source.next({cmd:i,size:t})})}throw(e){return Fe(this,void 0,void 0,function*(){const t=this.source.throw&&(yield this.source.throw(e))||at;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(t)})}return(e){return Fe(this,void 0,void 0,function*(){const t=this.source.return&&(yield this.source.return(e))||at;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(t)})}}class Im extends Hl{constructor(e,t){super(),this.position=0,this.buffer=$e(e),this.size=t===void 0?this.buffer.byteLength:t}readInt32(e){const{buffer:t,byteOffset:i}=this.readAt(e,4);return new DataView(t,i).getInt32(0,!0)}seek(e){return this.position=Math.min(e,this.size),e>>16,this.buffer[1]&65535,this.buffer[0]>>>16,this.buffer[0]&65535]),i=new Uint32Array([e.buffer[1]>>>16,e.buffer[1]&65535,e.buffer[0]>>>16,e.buffer[0]&65535]);let a=t[3]*i[3];this.buffer[0]=a&65535;let u=a>>>16;return a=t[2]*i[3],u+=a,a=t[3]*i[2]>>>0,u+=a,this.buffer[0]+=u<<16,this.buffer[1]=u>>>0>>16,this.buffer[1]+=t[1]*i[3]+t[2]*i[2]+t[3]*i[1],this.buffer[1]+=t[0]*i[3]+t[1]*i[2]+t[2]*i[1]+t[3]*i[0]<<16,this}_plus(e){const t=this.buffer[0]+e.buffer[0]>>>0;this.buffer[1]+=e.buffer[1],t>>0&&++this.buffer[1],this.buffer[0]=t}lessThan(e){return this.buffer[1]>>0,t[2]=this.buffer[2]+e.buffer[2]>>>0,t[1]=this.buffer[1]+e.buffer[1]>>>0,t[0]=this.buffer[0]+e.buffer[0]>>>0,t[0]>>0&&++t[1],t[1]>>0&&++t[2],t[2]>>0&&++t[3],this.buffer[3]=t[3],this.buffer[2]=t[2],this.buffer[1]=t[1],this.buffer[0]=t[0],this}hex(){return`${vi(this.buffer[3])} ${vi(this.buffer[2])} ${vi(this.buffer[1])} ${vi(this.buffer[0])}`}static multiply(e,t){return new Yn(new Uint32Array(e.buffer)).times(t)}static add(e,t){return new Yn(new Uint32Array(e.buffer)).plus(t)}static from(e,t=new Uint32Array(4)){return Yn.fromString(typeof e=="string"?e:e.toString(),t)}static fromNumber(e,t=new Uint32Array(4)){return Yn.fromString(e.toString(),t)}static fromString(e,t=new Uint32Array(4)){const i=e.startsWith("-"),a=e.length,u=new Yn(t);for(let f=i?1:0;f0&&this.readData(e,i)||new Uint8Array(0)}readOffsets(e,t){return this.readData(e,t)}readTypeIds(e,t){return this.readData(e,t)}readData(e,{length:t,offset:i}=this.nextBufferRange()){return this.bytes.subarray(i,i+t)}readDictionary(e){return this.dictionaries.get(e.id)}}class r1 extends uv{constructor(e,t,i,a,u){super(new Uint8Array(0),t,i,a,u),this.sources=e}readNullBitmap(e,t,{offset:i}=this.nextBufferRange()){return t<=0?new Uint8Array(0):kd(this.sources[i])}readOffsets(e,{offset:t}=this.nextBufferRange()){return Ke(Uint8Array,Ke(e.OffsetArrayType,this.sources[t]))}readTypeIds(e,{offset:t}=this.nextBufferRange()){return Ke(Uint8Array,Ke(e.ArrayType,this.sources[t]))}readData(e,{offset:t}=this.nextBufferRange()){const{sources:i}=this;return me.isTimestamp(e)||(me.isInt(e)||me.isTime(e))&&e.bitWidth===64||me.isDuration(e)||me.isDate(e)&&e.unit===gn.MILLISECOND?Ke(Uint8Array,zt.convertArray(i[t])):me.isDecimal(e)?Ke(Uint8Array,Yn.convertArray(i[t])):me.isBinary(e)||me.isLargeBinary(e)||me.isFixedSizeBinary(e)?s1(i[t]):me.isBool(e)?kd(i[t]):me.isUtf8(e)||me.isLargeUtf8(e)?Bd(i[t].join("")):Ke(Uint8Array,Ke(e.ArrayType,i[t].map(a=>+a)))}}function s1(n){const e=n.join(""),t=new Uint8Array(e.length/2);for(let i=0;i>1]=Number.parseInt(e.slice(i,i+2),16);return t}class we extends Re{compareSchemas(e,t){return e===t||t instanceof e.constructor&&this.compareManyFields(e.fields,t.fields)}compareManyFields(e,t){return e===t||Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>this.compareFields(i,t[a]))}compareFields(e,t){return e===t||t instanceof e.constructor&&e.name===t.name&&e.nullable===t.nullable&&this.visit(e.type,t.type)}}function At(n,e){return e instanceof n.constructor}function As(n,e){return n===e||At(n,e)}function Mr(n,e){return n===e||At(n,e)&&n.bitWidth===e.bitWidth&&n.isSigned===e.isSigned}function su(n,e){return n===e||At(n,e)&&n.precision===e.precision}function i1(n,e){return n===e||At(n,e)&&n.byteWidth===e.byteWidth}function Jd(n,e){return n===e||At(n,e)&&n.unit===e.unit}function Po(n,e){return n===e||At(n,e)&&n.unit===e.unit&&n.timezone===e.timezone}function zo(n,e){return n===e||At(n,e)&&n.unit===e.unit&&n.bitWidth===e.bitWidth}function o1(n,e){return n===e||At(n,e)&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}function a1(n,e){return n===e||At(n,e)&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}function qd(n,e){return n===e||At(n,e)&&n.mode===e.mode&&n.typeIds.every((t,i)=>t===e.typeIds[i])&&is.compareManyFields(n.children,e.children)}function l1(n,e){return n===e||At(n,e)&&n.id===e.id&&n.isOrdered===e.isOrdered&&is.visit(n.indices,e.indices)&&is.visit(n.dictionary,e.dictionary)}function Zd(n,e){return n===e||At(n,e)&&n.unit===e.unit}function Vo(n,e){return n===e||At(n,e)&&n.unit===e.unit}function u1(n,e){return n===e||At(n,e)&&n.listSize===e.listSize&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}function c1(n,e){return n===e||At(n,e)&&n.keysSorted===e.keysSorted&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}we.prototype.visitNull=As;we.prototype.visitBool=As;we.prototype.visitInt=Mr;we.prototype.visitInt8=Mr;we.prototype.visitInt16=Mr;we.prototype.visitInt32=Mr;we.prototype.visitInt64=Mr;we.prototype.visitUint8=Mr;we.prototype.visitUint16=Mr;we.prototype.visitUint32=Mr;we.prototype.visitUint64=Mr;we.prototype.visitFloat=su;we.prototype.visitFloat16=su;we.prototype.visitFloat32=su;we.prototype.visitFloat64=su;we.prototype.visitUtf8=As;we.prototype.visitLargeUtf8=As;we.prototype.visitBinary=As;we.prototype.visitLargeBinary=As;we.prototype.visitFixedSizeBinary=i1;we.prototype.visitDate=Jd;we.prototype.visitDateDay=Jd;we.prototype.visitDateMillisecond=Jd;we.prototype.visitTimestamp=Po;we.prototype.visitTimestampSecond=Po;we.prototype.visitTimestampMillisecond=Po;we.prototype.visitTimestampMicrosecond=Po;we.prototype.visitTimestampNanosecond=Po;we.prototype.visitTime=zo;we.prototype.visitTimeSecond=zo;we.prototype.visitTimeMillisecond=zo;we.prototype.visitTimeMicrosecond=zo;we.prototype.visitTimeNanosecond=zo;we.prototype.visitDecimal=As;we.prototype.visitList=o1;we.prototype.visitStruct=a1;we.prototype.visitUnion=qd;we.prototype.visitDenseUnion=qd;we.prototype.visitSparseUnion=qd;we.prototype.visitDictionary=l1;we.prototype.visitInterval=Zd;we.prototype.visitIntervalDayTime=Zd;we.prototype.visitIntervalYearMonth=Zd;we.prototype.visitDuration=Vo;we.prototype.visitDurationSecond=Vo;we.prototype.visitDurationMillisecond=Vo;we.prototype.visitDurationMicrosecond=Vo;we.prototype.visitDurationNanosecond=Vo;we.prototype.visitFixedSizeList=u1;we.prototype.visitMap=c1;const is=new we;function d1(n,e){return is.compareSchemas(n,e)}function od(n,e){return f1(n,e.map(t=>t.data.concat()))}function f1(n,e){const t=[...n.fields],i=[],a={numBatches:e.reduce((x,b)=>Math.max(x,b.length),0)};let u=0,f=0,h=-1;const m=e.length;let g,v=[];for(;a.numBatches-- >0;){for(f=Number.POSITIVE_INFINITY,h=-1;++h0&&(i[u++]=Ee({type:new Tt(t),length:f,nullCount:0,children:v.slice()})))}return[n=n.assign(t),i.map(x=>new An(n,x))]}function h1(n,e,t,i,a){var u;const f=(e+63&-64)>>3;for(let h=-1,m=i.length;++h=e)v===e?t[h]=g:(t[h]=g.slice(0,e),a.numBatches=Math.max(a.numBatches,i[h].unshift(g.slice(e,v-e))));else{const x=n[h];n[h]=x.clone({nullable:!0}),t[h]=(u=g==null?void 0:g._changeLengthAndBackfillNullBitmap(e))!==null&&u!==void 0?u:Ee({type:x.type,length:e,nullCount:e,nullBitmap:new Uint8Array(f)})}}return t}var cv;class mn{constructor(...e){var t,i;if(e.length===0)return this.batches=[],this.schema=new We([]),this._offsets=[0],this;let a,u;e[0]instanceof We&&(a=e.shift()),e.at(-1)instanceof Uint32Array&&(u=e.pop());const f=m=>{if(m){if(m instanceof An)return[m];if(m instanceof mn)return m.batches;if(m instanceof Ye){if(m.type instanceof Tt)return[new An(new We(m.type.children),m)]}else{if(Array.isArray(m))return m.flatMap(g=>f(g));if(typeof m[Symbol.iterator]=="function")return[...m].flatMap(g=>f(g));if(typeof m=="object"){const g=Object.keys(m),v=g.map(w=>new Je([m[w]])),x=a??new We(g.map((w,j)=>new nt(String(w),v[j].type,v[j].nullable))),[,b]=od(x,v);return b.length===0?[new An(m)]:b}}}return[]},h=e.flatMap(m=>f(m));if(a=(i=a??((t=h[0])===null||t===void 0?void 0:t.schema))!==null&&i!==void 0?i:new We([]),!(a instanceof We))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");for(const m of h){if(!(m instanceof An))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");if(!d1(a,m.schema))throw new TypeError("Table and inner RecordBatch schemas must be equivalent.")}this.schema=a,this.batches=h,this._offsets=u??Xg(this.data)}get data(){return this.batches.map(({data:e})=>e)}get numCols(){return this.schema.fields.length}get numRows(){return this.data.reduce((e,t)=>e+t.length,0)}get nullCount(){return this._nullCount===-1&&(this._nullCount=Zg(this.data)),this._nullCount}isValid(e){return!1}get(e){return null}at(e){return this.get(Vd(e,this.numRows))}set(e,t){}indexOf(e,t){return-1}[Symbol.iterator](){return this.batches.length>0?Yd.visit(new Je(this.data)):new Array(0)[Symbol.iterator]()}toArray(){return[...this]}toString(){return`[ ${this.toArray().join(`, `)} -]`}concat(...e){const t=this.schema,i=this.data.concat(e.flatMap(({data:a})=>a));return new mn(t,i.map(a=>new An(t,a)))}slice(e,t){const i=this.schema;[e,t]=Yg({length:this.numRows},e,t);const a=qg(this.data,this._offsets,e,t);return new mn(i,a.map(u=>new An(i,u)))}getChild(e){return this.getChildAt(this.schema.fields.findIndex(t=>t.name===e))}getChildAt(e){if(e>-1&&ei.children[e]);if(t.length===0){const{type:i}=this.schema.fields[e],a=Ee({type:i,length:0,nullCount:0});t.push(a._changeLengthAndBackfillNullBitmap(this.numRows))}return new Je(t)}return null}setChild(e,t){var i;return this.setChildAt((i=this.schema.fields)===null||i===void 0?void 0:i.findIndex(a=>a.name===e),t)}setChildAt(e,t){let i=this.schema,a=[...this.batches];if(e>-1&&ethis.getChildAt(g));[u[e],h[e]]=[f,t],[i,a]=od(i,h)}return new mn(i,a)}select(e){const t=this.schema.fields.reduce((i,a,u)=>i.set(a.name,u),new Map);return this.selectAt(e.map(i=>t.get(i)).filter(i=>i>-1))}selectAt(e){const t=this.schema.selectAt(e),i=this.batches.map(a=>a.selectAt(e));return new mn(t,i)}assign(e){const t=this.schema.fields,[i,a]=e.schema.fields.reduce((h,m,g)=>{const[v,x]=h,b=t.findIndex(w=>w.name===m.name);return~b?x[b]=g:v.push(g),h},[[],[]]),u=this.schema.assign(e.schema),f=[...t.map((h,m)=>[m,a[m]]).map(([h,m])=>m===void 0?this.getChildAt(h):e.getChildAt(m)),...i.map(h=>e.getChildAt(h))].filter(Boolean);return new mn(...od(u,f))}}av=Symbol.toStringTag;mn[av]=(n=>(n.schema=null,n.batches=[],n._offsets=new Uint32Array([0]),n._nullCount=-1,n[Symbol.isConcatSpreadable]=!0,n.isValid=zl(Gd),n.get=zl(Gt.getVisitFn(M.Struct)),n.set=Zg(vn.getVisitFn(M.Struct)),n.indexOf=Xg(Vl.getVisitFn(M.Struct)),"Table"))(mn.prototype);var lv;let An=class Oo{constructor(...e){switch(e.length){case 2:{if([this.schema]=e,!(this.schema instanceof We))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");if([,this.data=Ee({nullCount:0,type:new Tt(this.schema.fields),children:this.schema.fields.map(t=>Ee({type:t.type,nullCount:0}))})]=e,!(this.data instanceof Ye))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");[this.schema,this.data]=Mm(this.schema,this.data.children);break}case 1:{const[t]=e,{fields:i,children:a,length:u}=Object.keys(t).reduce((m,g,v)=>(m.children[v]=t[g],m.length=Math.max(m.length,t[g].length),m.fields[v]=nt.new({name:g,type:t[g].type,nullable:!0}),m),{length:0,fields:new Array,children:new Array}),f=new We(i),h=Ee({type:new Tt(i),length:u,children:a,nullCount:0});[this.schema,this.data]=Mm(f,h.children,u);break}default:throw new TypeError("RecordBatch constructor expects an Object mapping names to child Data, or a [Schema, Data] pair.")}}get dictionaries(){return this._dictionaries||(this._dictionaries=uv(this.schema.fields,this.data.children))}get numCols(){return this.schema.fields.length}get numRows(){return this.data.length}get nullCount(){return this.data.nullCount}isValid(e){return this.data.getValid(e)}get(e){return Gt.visit(this.data,e)}at(e){return this.get(Vd(e,this.numRows))}set(e,t){return vn.visit(this.data,e,t)}indexOf(e,t){return Vl.visit(this.data,e,t)}[Symbol.iterator](){return Yd.visit(new Je([this.data]))}toArray(){return[...this]}concat(...e){return new mn(this.schema,[this,...e])}slice(e,t){const[i]=new Je([this.data]).slice(e,t).data;return new Oo(this.schema,i)}getChild(e){var t;return this.getChildAt((t=this.schema.fields)===null||t===void 0?void 0:t.findIndex(i=>i.name===e))}getChildAt(e){return e>-1&&ea.name===e),t)}setChildAt(e,t){let i=this.schema,a=this.data;if(e>-1&&eh.name===u);~f&&(a[f]=this.data.children[f])}return new Oo(t,Ee({type:i,length:this.numRows,children:a}))}selectAt(e){const t=this.schema.selectAt(e),i=e.map(u=>this.data.children[u]).filter(Boolean),a=Ee({type:new Tt(t.fields),length:this.numRows,children:i});return new Oo(t,a)}};lv=Symbol.toStringTag;An[lv]=(n=>(n._nullCount=-1,n[Symbol.isConcatSpreadable]=!0,"RecordBatch"))(An.prototype);function Mm(n,e,t=e.reduce((i,a)=>Math.max(i,a.length),0)){var i;const a=[...n.fields],u=[...e],f=(t+63&-64)>>3;for(const[h,m]of n.fields.entries()){const g=e[h];(!g||g.length!==t)&&(a[h]=m.clone({nullable:!0}),u[h]=(i=g==null?void 0:g._changeLengthAndBackfillNullBitmap(t))!==null&&i!==void 0?i:Ee({type:m.type,length:t,nullCount:t,nullBitmap:new Uint8Array(f)}))}return[n.assign(a),Ee({type:new Tt(a),length:t,children:u})]}function uv(n,e,t=new Map){var i,a;if(((i=n==null?void 0:n.length)!==null&&i!==void 0?i:0)>0&&(n==null?void 0:n.length)===(e==null?void 0:e.length))for(let u=-1,f=n.length;++uEe({type:a.type})),i=Ee({type:new Tt(e.fields),nullCount:0,children:t});super(e,i)}}let qr=class Hn{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsMessage(e,t){return(t||new Hn).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsMessage(e,t){return e.setPosition(e.position()+He),(t||new Hn).__init(e.readInt32(e.position())+e.position(),e)}version(){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):ht.V1}headerType(){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb_pos+e):Ve.NONE}header(e){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__union(e,this.bb_pos+t):null}bodyLength(){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt64(this.bb_pos+e):BigInt("0")}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,12);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}static startMessage(e){e.startObject(5)}static addVersion(e,t){e.addFieldInt16(0,t,ht.V1)}static addHeaderType(e,t){e.addFieldInt8(1,t,Ve.NONE)}static addHeader(e,t){e.addFieldOffset(2,t,0)}static addBodyLength(e,t){e.addFieldInt64(3,t,BigInt("0"))}static addCustomMetadata(e,t){e.addFieldOffset(4,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endMessage(e){return e.endObject()}static finishMessageBuffer(e,t){e.finish(t)}static finishSizePrefixedMessageBuffer(e,t){e.finish(t,void 0,!0)}static createMessage(e,t,i,a,u,f){return Hn.startMessage(e),Hn.addVersion(e,t),Hn.addHeaderType(e,i),Hn.addHeader(e,a),Hn.addBodyLength(e,u),Hn.addCustomMetadata(e,f),Hn.endMessage(e)}};class d1 extends Re{visit(e,t){return e==null||t==null?void 0:super.visit(e,t)}visitNull(e,t){return vm.startNull(t),vm.endNull(t)}visitInt(e,t){return en.startInt(t),en.addBitWidth(t,e.bitWidth),en.addIsSigned(t,e.isSigned),en.endInt(t)}visitFloat(e,t){return Kn.startFloatingPoint(t),Kn.addPrecision(t,e.precision),Kn.endFloatingPoint(t)}visitBinary(e,t){return hm.startBinary(t),hm.endBinary(t)}visitLargeBinary(e,t){return mm.startLargeBinary(t),mm.endLargeBinary(t)}visitBool(e,t){return pm.startBool(t),pm.endBool(t)}visitUtf8(e,t){return xm.startUtf8(t),xm.endUtf8(t)}visitLargeUtf8(e,t){return ym.startLargeUtf8(t),ym.endLargeUtf8(t)}visitDecimal(e,t){return ci.startDecimal(t),ci.addScale(t,e.scale),ci.addPrecision(t,e.precision),ci.addBitWidth(t,e.bitWidth),ci.endDecimal(t)}visitDate(e,t){return hl.startDate(t),hl.addUnit(t,e.unit),hl.endDate(t)}visitTime(e,t){return hn.startTime(t),hn.addUnit(t,e.unit),hn.addBitWidth(t,e.bitWidth),hn.endTime(t)}visitTimestamp(e,t){const i=e.timezone&&t.createString(e.timezone)||void 0;return pn.startTimestamp(t),pn.addUnit(t,e.unit),i!==void 0&&pn.addTimezone(t,i),pn.endTimestamp(t)}visitInterval(e,t){return Jn.startInterval(t),Jn.addUnit(t,e.unit),Jn.endInterval(t)}visitDuration(e,t){return pl.startDuration(t),pl.addUnit(t,e.unit),pl.endDuration(t)}visitList(e,t){return gm.startList(t),gm.endList(t)}visitStruct(e,t){return ks.startStruct_(t),ks.endStruct_(t)}visitUnion(e,t){Vt.startTypeIdsVector(t,e.typeIds.length);const i=Vt.createTypeIdsVector(t,e.typeIds);return Vt.startUnion(t),Vt.addMode(t,e.mode),Vt.addTypeIds(t,i),Vt.endUnion(t)}visitDictionary(e,t){const i=this.visit(e.indices,t);return wr.startDictionaryEncoding(t),wr.addId(t,BigInt(e.id)),wr.addIsOrdered(t,e.isOrdered),i!==void 0&&wr.addIndexType(t,i),wr.endDictionaryEncoding(t)}visitFixedSizeBinary(e,t){return ml.startFixedSizeBinary(t),ml.addByteWidth(t,e.byteWidth),ml.endFixedSizeBinary(t)}visitFixedSizeList(e,t){return yl.startFixedSizeList(t),yl.addListSize(t,e.listSize),yl.endFixedSizeList(t)}visitMap(e,t){return gl.startMap(t),gl.addKeysSorted(t,e.keysSorted),gl.endMap(t)}}const ad=new d1;function f1(n,e=new Map){return new We(p1(n,e),xl(n.metadata),e)}function dv(n){return new Rn(n.count,fv(n.columns),hv(n.columns))}function h1(n){return new kr(dv(n.data),n.id,n.isDelta)}function p1(n,e){return(n.fields||[]).filter(Boolean).map(t=>nt.fromJSON(t,e))}function Dm(n,e){return(n.children||[]).filter(Boolean).map(t=>nt.fromJSON(t,e))}function fv(n){return(n||[]).reduce((e,t)=>[...e,new Ai(t.count,m1(t.VALIDITY)),...fv(t.children)],[])}function hv(n,e=[]){for(let t=-1,i=(n||[]).length;++te+ +(t===0),0)}function y1(n,e){let t,i,a,u,f,h;return!e||!(u=n.dictionary)?(f=Fm(n,Dm(n,e)),a=new nt(n.name,f,n.nullable,xl(n.metadata))):e.has(t=u.id)?(i=(i=u.indexType)?Cm(i):new Lo,h=new Mi(e.get(t),i,t,u.isOrdered),a=new nt(n.name,h,n.nullable,xl(n.metadata))):(i=(i=u.indexType)?Cm(i):new Lo,e.set(t,f=Fm(n,Dm(n,e))),h=new Mi(f,i,t,u.isOrdered),a=new nt(n.name,h,n.nullable,xl(n.metadata))),a||null}function xl(n=[]){return new Map(n.map(({key:e,value:t})=>[e,t]))}function Cm(n){return new Ds(n.isSigned,n.bitWidth)}function Fm(n,e){const t=n.type.name;switch(t){case"NONE":return new ss;case"null":return new ss;case"binary":return new kl;case"largebinary":return new Il;case"utf8":return new Ml;case"largeutf8":return new Dl;case"bool":return new Cl;case"list":return new Rl((e||[])[0]);case"struct":return new Tt(e||[]);case"struct_":return new Tt(e||[])}switch(t){case"int":{const i=n.type;return new Ds(i.isSigned,i.bitWidth)}case"floatingpoint":{const i=n.type;return new jl(Dt[i.precision])}case"decimal":{const i=n.type;return new Fl(i.scale,i.precision,i.bitWidth)}case"date":{const i=n.type;return new Ol(gn[i.unit])}case"time":{const i=n.type;return new Tl(_e[i.unit],i.bitWidth)}case"timestamp":{const i=n.type;return new Al(_e[i.unit],i.timezone)}case"interval":{const i=n.type;return new Bl(nr[i.unit])}case"duration":{const i=n.type;return new El(_e[i.unit])}case"union":{const i=n.type,[a,...u]=(i.mode+"").toLowerCase(),f=a.toUpperCase()+u.join("");return new Ll(Ht[f],i.typeIds||[],e||[])}case"fixedsizebinary":{const i=n.type;return new Ul(i.byteWidth)}case"fixedsizelist":{const i=n.type;return new $l(i.listSize,(e||[])[0])}case"map":{const i=n.type;return new Pl((e||[])[0],i.keysSorted)}}throw new Error(`Unrecognized type: "${t}"`)}var g1=Iy,v1=ki;class Bn{static fromJSON(e,t){const i=new Bn(0,ht.V5,t);return i._createHeader=x1(e,t),i}static decode(e){e=new v1($e(e));const t=qr.getRootAsMessage(e),i=t.bodyLength(),a=t.version(),u=t.headerType(),f=new Bn(i,a,u);return f._createHeader=b1(t,u),f}static encode(e){const t=new g1;let i=-1;return e.isSchema()?i=We.encode(t,e.header()):e.isRecordBatch()?i=Rn.encode(t,e.header()):e.isDictionaryBatch()&&(i=kr.encode(t,e.header())),qr.startMessage(t),qr.addVersion(t,ht.V5),qr.addHeader(t,i),qr.addHeaderType(t,e.headerType),qr.addBodyLength(t,BigInt(e.bodyLength)),qr.finishMessageBuffer(t,qr.endMessage(t)),t.asUint8Array()}static from(e,t=0){if(e instanceof We)return new Bn(0,ht.V5,Ve.Schema,e);if(e instanceof Rn)return new Bn(t,ht.V5,Ve.RecordBatch,e);if(e instanceof kr)return new Bn(t,ht.V5,Ve.DictionaryBatch,e);throw new Error(`Unrecognized Message header: ${e}`)}get type(){return this.headerType}get version(){return this._version}get headerType(){return this._headerType}get bodyLength(){return this._bodyLength}header(){return this._createHeader()}isSchema(){return this.headerType===Ve.Schema}isRecordBatch(){return this.headerType===Ve.RecordBatch}isDictionaryBatch(){return this.headerType===Ve.DictionaryBatch}constructor(e,t,i,a){this._version=t,this._headerType=i,this.body=new Uint8Array(0),a&&(this._createHeader=()=>a),this._bodyLength=tt(e)}}class Rn{get nodes(){return this._nodes}get length(){return this._length}get buffers(){return this._buffers}constructor(e,t,i){this._nodes=t,this._buffers=i,this._length=tt(e)}}class kr{get id(){return this._id}get data(){return this._data}get isDelta(){return this._isDelta}get length(){return this.data.length}get nodes(){return this.data.nodes}get buffers(){return this.data.buffers}constructor(e,t,i=!1){this._data=e,this._isDelta=i,this._id=tt(t)}}class _r{constructor(e,t){this.offset=tt(e),this.length=tt(t)}}class Ai{constructor(e,t){this.length=tt(e),this.nullCount=tt(t)}}function x1(n,e){return(()=>{switch(e){case Ve.Schema:return We.fromJSON(n);case Ve.RecordBatch:return Rn.fromJSON(n);case Ve.DictionaryBatch:return kr.fromJSON(n)}throw new Error(`Unrecognized Message type: { name: ${Ve[e]}, type: ${e} }`)})}function b1(n,e){return(()=>{switch(e){case Ve.Schema:return We.decode(n.header(new Gn),new Map,n.version());case Ve.RecordBatch:return Rn.decode(n.header(new yr),n.version());case Ve.DictionaryBatch:return kr.decode(n.header(new li),n.version())}throw new Error(`Unrecognized Message type: { name: ${Ve[e]}, type: ${e} }`)})}nt.encode=F1;nt.decode=D1;nt.fromJSON=y1;We.encode=C1;We.decode=w1;We.fromJSON=f1;Rn.encode=O1;Rn.decode=S1;Rn.fromJSON=dv;kr.encode=T1;kr.decode=_1;kr.fromJSON=h1;Ai.encode=A1;Ai.decode=j1;_r.encode=B1;_r.decode=N1;function w1(n,e=new Map,t=ht.V5){const i=M1(n,e);return new We(i,bl(n),e,t)}function S1(n,e=ht.V5){if(n.compression()!==null)throw new Error("Record batch compression not implemented");return new Rn(n.length(),k1(n),I1(n,e))}function _1(n,e=ht.V5){return new kr(Rn.decode(n.data(),e),n.id(),n.isDelta())}function N1(n){return new _r(n.offset(),n.length())}function j1(n){return new Ai(n.length(),n.nullCount())}function k1(n){const e=[];for(let t,i=-1,a=-1,u=n.nodesLength();++int.encode(n,u));Gn.startFieldsVector(n,t.length);const i=Gn.createFieldsVector(n,t),a=e.metadata&&e.metadata.size>0?Gn.createCustomMetadataVector(n,[...e.metadata].map(([u,f])=>{const h=n.createString(`${u}`),m=n.createString(`${f}`);return gt.startKeyValue(n),gt.addKey(n,h),gt.addValue(n,m),gt.endKeyValue(n)})):-1;return Gn.startSchema(n),Gn.addFields(n,i),Gn.addEndianness(n,E1?Ii.Little:Ii.Big),a!==-1&&Gn.addCustomMetadata(n,a),Gn.endSchema(n)}function F1(n,e){let t=-1,i=-1,a=-1;const u=e.type;let f=e.typeId;me.isDictionary(u)?(f=u.dictionary.typeId,a=ad.visit(u,n),i=ad.visit(u.dictionary,n)):i=ad.visit(u,n);const h=(u.children||[]).map(v=>nt.encode(n,v)),m=dn.createChildrenVector(n,h),g=e.metadata&&e.metadata.size>0?dn.createCustomMetadataVector(n,[...e.metadata].map(([v,x])=>{const b=n.createString(`${v}`),w=n.createString(`${x}`);return gt.startKeyValue(n),gt.addKey(n,b),gt.addValue(n,w),gt.endKeyValue(n)})):-1;return e.name&&(t=n.createString(e.name)),dn.startField(n),dn.addType(n,i),dn.addTypeType(n,f),dn.addChildren(n,m),dn.addNullable(n,!!e.nullable),t!==-1&&dn.addName(n,t),a!==-1&&dn.addDictionary(n,a),g!==-1&&dn.addCustomMetadata(n,g),dn.endField(n)}function O1(n,e){const t=e.nodes||[],i=e.buffers||[];yr.startNodesVector(n,t.length);for(const f of t.slice().reverse())Ai.encode(n,f);const a=n.endVector();yr.startBuffersVector(n,i.length);for(const f of i.slice().reverse())_r.encode(n,f);const u=n.endVector();return yr.startRecordBatch(n),yr.addLength(n,BigInt(e.length)),yr.addNodes(n,a),yr.addBuffers(n,u),yr.endRecordBatch(n)}function T1(n,e){const t=Rn.encode(n,e.data);return li.startDictionaryBatch(n),li.addId(n,BigInt(e.id)),li.addIsDelta(n,e.isDelta),li.addData(n,t),li.endDictionaryBatch(n)}function A1(n,e){return Cy.createFieldNode(n,BigInt(e.length),BigInt(e.nullCount))}function B1(n,e){return Dy.createBuffer(n,BigInt(e.offset),BigInt(e.length))}const E1=(()=>{const n=new ArrayBuffer(2);return new DataView(n).setInt16(0,256,!0),new Int16Array(n)[0]===256})(),Xd=n=>`Expected ${Ve[n]} Message in stream, but was null or length 0.`,ef=n=>`Header pointer of flatbuffer-encoded ${Ve[n]} Message is null or length 0.`,pv=(n,e)=>`Expected to read ${n} metadata bytes, but only read ${e}.`,mv=(n,e)=>`Expected to read ${n} bytes for message body, but only read ${e}.`;class yv{constructor(e){this.source=e instanceof Hl?e:new Hl(e)}[Symbol.iterator](){return this}next(){let e;return(e=this.readMetadataLength()).done||e.value===-1&&(e=this.readMetadataLength()).done||(e=this.readMetadata(e.value)).done?at:e}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}readMessage(e){let t;if((t=this.next()).done)return null;if(e!=null&&t.value.headerType!==e)throw new Error(Xd(e));return t.value}readMessageBody(e){if(e<=0)return new Uint8Array(0);const t=$e(this.source.read(e));if(t.byteLength[...a,...u.VALIDITY&&[u.VALIDITY]||[],...u.TYPE_ID&&[u.TYPE_ID]||[],...u.OFFSET&&[u.OFFSET]||[],...u.DATA&&[u.DATA]||[],...t(u.children)],[])}}readMessage(e){let t;if((t=this.next()).done)return null;if(e!=null&&t.value.headerType!==e)throw new Error(Xd(e));return t.value}readSchema(){const e=Ve.Schema,t=this.readMessage(e),i=t==null?void 0:t.header();if(!t||!i)throw new Error(ef(e));return i}}const iu=4,Cd="ARROW1",Yl=new Uint8Array(Cd.length);for(let n=0;nthis):this}readRecordBatch(e){return this._impl.isFile()?this._impl.readRecordBatch(e):null}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}toDOMStream(){return fn.toDOMStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this})}toNodeStream(){return fn.toNodeStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this},{objectMode:!0})}static throughNode(e){throw new Error('"throughNode" not available in this environment')}static throughDOM(e,t){throw new Error('"throughDOM" not available in this environment')}static from(e){return e instanceof jr?e:bd(e)?V1(e):wy(e)?G1(e):Ao(e)?Fe(this,void 0,void 0,function*(){return yield jr.from(yield e)}):Sy(e)||Rd(e)||Ny(e)||Ed(e)?H1(new Ci(e)):W1(new Hl(e))}static readAll(e){return e instanceof jr?e.isSync()?Bm(e):Em(e):bd(e)||ArrayBuffer.isView(e)||nu(e)||by(e)?Bm(e):Em(e)}}class Ql extends jr{constructor(e){super(e),this._impl=e}readAll(){return[...this]}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return qn(this,arguments,function*(){yield Ae(yield*fl(xi(this[Symbol.iterator]())))})}}class Kl extends jr{constructor(e){super(e),this._impl=e}readAll(){return Fe(this,void 0,void 0,function*(){var e,t,i,a;const u=new Array;try{for(var f=!0,h=xi(this),m;m=yield h.next(),e=m.done,!e;f=!0){a=m.value,f=!1;const g=a;u.push(g)}}catch(g){t={error:g}}finally{try{!f&&!e&&(i=h.return)&&(yield i.call(h))}finally{if(t)throw t.error}}return u})}[Symbol.iterator](){throw new Error("AsyncRecordBatchStreamReader is not Iterable")}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}}class vv extends Ql{constructor(e){super(e),this._impl=e}}class $1 extends Kl{constructor(e){super(e),this._impl=e}}class xv{get numDictionaries(){return this._dictionaryIndex}get numRecordBatches(){return this._recordBatchIndex}constructor(e=new Map){this.closed=!1,this.autoDestroy=!0,this._dictionaryIndex=0,this._recordBatchIndex=0,this.dictionaries=e}isSync(){return!1}isAsync(){return!1}isFile(){return!1}isStream(){return!1}reset(e){return this._dictionaryIndex=0,this._recordBatchIndex=0,this.schema=e,this.dictionaries=new Map,this}_loadRecordBatch(e,t){const i=this._loadVectors(e,t,this.schema.fields),a=Ee({type:new Tt(this.schema.fields),length:e.length,children:i});return new An(this.schema,a)}_loadDictionaryBatch(e,t){const{id:i,isDelta:a}=e,{dictionaries:u,schema:f}=this,h=u.get(i),m=f.dictionaries.get(i),g=this._loadVectors(e.data,t,[m]);return(h&&a?h.concat(new Je(g)):new Je(g)).memoize()}_loadVectors(e,t,i){return new ov(t,e.nodes,e.buffers,this.dictionaries,this.schema.metadataVersion).visitMany(i)}}class Jl extends xv{constructor(e,t){super(t),this._reader=bd(e)?new L1(this._handle=e):new yv(this._handle=e)}isSync(){return!0}isStream(){return!0}[Symbol.iterator](){return this}cancel(){!this.closed&&(this.closed=!0)&&(this.reset()._reader.return(),this._reader=null,this.dictionaries=null)}open(e){return this.closed||(this.autoDestroy=wv(this,e),this.schema||(this.schema=this._reader.readSchema())||this.cancel()),this}throw(e){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.throw(e):at}return(e){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.return(e):at}next(){if(this.closed)return at;let e;const{_reader:t}=this;for(;e=this._readNextMessageAndValidate();)if(e.isSchema())this.reset(e.header());else if(e.isRecordBatch()){this._recordBatchIndex++;const i=e.header(),a=t.readMessageBody(e.bodyLength);return{done:!1,value:this._loadRecordBatch(i,a)}}else if(e.isDictionaryBatch()){this._dictionaryIndex++;const i=e.header(),a=t.readMessageBody(e.bodyLength),u=this._loadDictionaryBatch(i,a);this.dictionaries.set(i.id,u)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new cv(this.schema)}):this.return()}_readNextMessageAndValidate(e){return this._reader.readMessage(e)}}class ql extends xv{constructor(e,t){super(t),this._reader=new R1(this._handle=e)}isAsync(){return!0}isStream(){return!0}[Symbol.asyncIterator](){return this}cancel(){return Fe(this,void 0,void 0,function*(){!this.closed&&(this.closed=!0)&&(yield this.reset()._reader.return(),this._reader=null,this.dictionaries=null)})}open(e){return Fe(this,void 0,void 0,function*(){return this.closed||(this.autoDestroy=wv(this,e),this.schema||(this.schema=yield this._reader.readSchema())||(yield this.cancel())),this})}throw(e){return Fe(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.throw(e):at})}return(e){return Fe(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.return(e):at})}next(){return Fe(this,void 0,void 0,function*(){if(this.closed)return at;let e;const{_reader:t}=this;for(;e=yield this._readNextMessageAndValidate();)if(e.isSchema())yield this.reset(e.header());else if(e.isRecordBatch()){this._recordBatchIndex++;const i=e.header(),a=yield t.readMessageBody(e.bodyLength);return{done:!1,value:this._loadRecordBatch(i,a)}}else if(e.isDictionaryBatch()){this._dictionaryIndex++;const i=e.header(),a=yield t.readMessageBody(e.bodyLength),u=this._loadDictionaryBatch(i,a);this.dictionaries.set(i.id,u)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new cv(this.schema)}):yield this.return()})}_readNextMessageAndValidate(e){return Fe(this,void 0,void 0,function*(){return yield this._reader.readMessage(e)})}}class bv extends Jl{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(e,t){super(e instanceof Im?e:new Im(e),t)}isSync(){return!0}isFile(){return!0}open(e){if(!this.closed&&!this._footer){this.schema=(this._footer=this._readFooter()).schema;for(const t of this._footer.dictionaryBatches())t&&this._readDictionaryBatch(this._dictionaryIndex++)}return super.open(e)}readRecordBatch(e){var t;if(this.closed)return null;this._footer||this.open();const i=(t=this._footer)===null||t===void 0?void 0:t.getRecordBatch(e);if(i&&this._handle.seek(i.offset)){const a=this._reader.readMessage(Ve.RecordBatch);if(a!=null&&a.isRecordBatch()){const u=a.header(),f=this._reader.readMessageBody(a.bodyLength);return this._loadRecordBatch(u,f)}}return null}_readDictionaryBatch(e){var t;const i=(t=this._footer)===null||t===void 0?void 0:t.getDictionaryBatch(e);if(i&&this._handle.seek(i.offset)){const a=this._reader.readMessage(Ve.DictionaryBatch);if(a!=null&&a.isDictionaryBatch()){const u=a.header(),f=this._reader.readMessageBody(a.bodyLength),h=this._loadDictionaryBatch(u,f);this.dictionaries.set(u.id,h)}}}_readFooter(){const{_handle:e}=this,t=e.size-gv,i=e.readInt32(t),a=e.readAt(t-i,i);return Qd.decode(a)}_readNextMessageAndValidate(e){var t;if(this._footer||this.open(),this._footer&&this._recordBatchIndexsuper.open}});return Fe(this,void 0,void 0,function*(){if(!this.closed&&!this._footer){this.schema=(this._footer=yield this._readFooter()).schema;for(const i of this._footer.dictionaryBatches())i&&(yield this._readDictionaryBatch(this._dictionaryIndex++))}return yield t.open.call(this,e)})}readRecordBatch(e){return Fe(this,void 0,void 0,function*(){var t;if(this.closed)return null;this._footer||(yield this.open());const i=(t=this._footer)===null||t===void 0?void 0:t.getRecordBatch(e);if(i&&(yield this._handle.seek(i.offset))){const a=yield this._reader.readMessage(Ve.RecordBatch);if(a!=null&&a.isRecordBatch()){const u=a.header(),f=yield this._reader.readMessageBody(a.bodyLength);return this._loadRecordBatch(u,f)}}return null})}_readDictionaryBatch(e){return Fe(this,void 0,void 0,function*(){var t;const i=(t=this._footer)===null||t===void 0?void 0:t.getDictionaryBatch(e);if(i&&(yield this._handle.seek(i.offset))){const a=yield this._reader.readMessage(Ve.DictionaryBatch);if(a!=null&&a.isDictionaryBatch()){const u=a.header(),f=yield this._reader.readMessageBody(a.bodyLength),h=this._loadDictionaryBatch(u,f);this.dictionaries.set(u.id,h)}}})}_readFooter(){return Fe(this,void 0,void 0,function*(){const{_handle:e}=this;e._pending&&(yield e._pending);const t=e.size-gv,i=yield e.readInt32(t),a=yield e.readAt(t-i,i);return Qd.decode(a)})}_readNextMessageAndValidate(e){return Fe(this,void 0,void 0,function*(){if(this._footer||(yield this.open()),this._footer&&this._recordBatchIndex=4?tf(e)?new vv(new bv(n.read())):new Ql(new Jl(n)):new Ql(new Jl((function*(){})()))}function H1(n){return Fe(this,void 0,void 0,function*(){const e=yield n.peek(Wo+7&-8);return e&&e.byteLength>=4?tf(e)?new vv(new bv(yield n.read())):new Kl(new ql(n)):new Kl(new ql((function(){return qn(this,arguments,function*(){})})()))})}function G1(n){return Fe(this,void 0,void 0,function*(){const{size:e}=yield n.stat(),t=new Gl(n,e);return e>=U1&&tf(yield t.readAt(0,Wo+7&-8))?new $1(new P1(t)):new Kl(new ql(t))})}function Sv(n){const e=jr.from(n);return Ao(e)?e.then(t=>Sv(t)):e.isAsync()?e.readAll().then(t=>new mn(t)):new mn(e.readAll())}function Y1(n){if(n==null)return null;if(typeof n=="bigint"){const e=Number(n);return Number.isSafeInteger(e)?e:n.toString()}if(n instanceof Date){const e=n.toISOString();return e.endsWith("T00:00:00.000Z")?e.slice(0,10):e}return typeof n=="object"?String(n):n}function Q1(n){const e=Sv(n),t=e.schema.fields.map(a=>a.name),i=new Array(e.numRows);for(let a=0;a({...e,charts:e.charts.map(t=>{var f,h;const i=t.query,a=(f=t.interactions)==null?void 0:f.brush,u=(h=t.interactions)==null?void 0:h.select;return{...t,query:{...i,metrics:Zr(i.metrics)??[],dimensions:Zr(i.dimensions),filters:Zr(i.filters),segments:Zr(i.segments),order_by:Zr(i.order_by),orderBy:Zr(i.orderBy)},interactions:t.interactions?{...t.interactions,brush:typeof a=="object"?{...a,fields:Zr(a.fields)}:a,select:typeof u=="object"?{...u,fields:Zr(u.fields)}:u}:void 0}})}))}}const J1="application/vnd.apache.arrow.stream";class q1{constructor(e){Mn(this,"active",0);Mn(this,"waiters",[]);this.max=e}async run(e){var t;this.active>=this.max&&await new Promise(i=>this.waiters.push(i)),this.active+=1;try{return await e()}finally{this.active-=1,(t=this.waiters.shift())==null||t()}}}function Z1(n){var t,i,a,u,f;const e={};return(t=n.metrics)!=null&&t.length&&(e.metrics=n.metrics),(i=n.dimensions)!=null&&i.length&&(e.dimensions=n.dimensions),(a=n.filters)!=null&&a.length&&(e.filters=n.filters),(u=n.segments)!=null&&u.length&&(e.segments=n.segments),(f=n.orderBy)!=null&&f.length&&(e.order_by=n.orderBy),n.limit!=null&&(e.limit=n.limit),n.offset!=null&&(e.offset=n.offset),n.ungrouped&&(e.ungrouped=!0),n.parameters&&(e.parameters=n.parameters),n.usePreaggregations!=null&&(e.use_preaggregations=n.usePreaggregations),n.timezone&&n.timezone!=="UTC"&&(e.timezone=n.timezone),e}class X1{constructor(e={}){Mn(this,"baseUrl");Mn(this,"token");Mn(this,"sessionToken");Mn(this,"transport");Mn(this,"usePreaggregations");Mn(this,"gate");Mn(this,"onUnauthorized");this.baseUrl=(e.baseUrl??"").replace(/\/$/,""),this.token=e.token,this.transport=e.transport??"json",this.usePreaggregations=e.usePreaggregations??!0,this.gate=new q1(e.maxConcurrency??6),this.onUnauthorized=e.onUnauthorized}body(e){return Z1({usePreaggregations:this.usePreaggregations,...e})}headers(e){const t={...e};return this.sessionToken?t.Authorization=`Sidemantic-Session ${this.sessionToken}`:this.token&&(t.Authorization=`Bearer ${this.token}`),t}isCrossOrigin(){return!this.baseUrl||typeof globalThis.location>"u"?!1:new URL(this.baseUrl,globalThis.location.href).origin!==globalThis.location.origin}url(e){return`${this.baseUrl}${e}`}async getJson(e){const t=await fetch(this.url(e),{headers:this.headers(),credentials:"include"});if(!t.ok)throw new Error(await this.errorText(t,e));return await t.json()}async errorText(e,t){var a;e.status===401&&((a=this.onUnauthorized)==null||a.call(this));let i="";try{const u=await e.json();i=u.error??u.detail??""}catch{}return`${t} failed (${e.status})${i?`: ${i}`:""}`}async health(){try{return(await fetch(this.url("/health"),{headers:this.headers(),credentials:"include"})).ok}catch{return!1}}async getCatalog(){try{const t=await fetch(this.url("/describe"),{headers:this.headers(),credentials:"include"});if(t.ok){const i=vb(await t.json());try{return bb(i,await this.getJson("/graph"))}catch{return i}}}catch{}const e=await this.getJson("/graph");return xb(e)}async getDashboard(){try{const e=await fetch(this.url("/dashboard"),{headers:this.headers()});if(e.status===404)return null;if(!e.ok)throw new Error(await this.errorText(e,"/dashboard"));if(!(e.headers.get("content-type")??"").includes("application/json"))return null;const t=await e.json();return typeof t.title=="string"&&Array.isArray(t.tabs)?K1(t):null}catch{return null}}async compile(e){const t=await fetch(this.url("/compile"),{method:"POST",headers:this.headers({"Content-Type":"application/json"}),credentials:"include",body:JSON.stringify(this.body(e))});if(!t.ok)throw new Error(await this.errorText(t,"/compile"));return(await t.json()).sql}async runQuery(e){return this.gate.run(()=>this.transport==="arrow"?this.runQueryArrow(e):this.runQueryJson(e))}async runQueryJson(e){const t=await fetch(this.url("/query"),{method:"POST",headers:this.headers({"Content-Type":"application/json"}),credentials:"include",body:JSON.stringify(this.body(e))});if(!t.ok)throw new Error(await this.errorText(t,"/query"));const i=await t.json(),a=i.rows??[];return{columns:a.length?Object.keys(a[0]):[],rows:a,rowCount:i.row_count??a.length,sql:i.sql??""}}async runQueryArrow(e){const t=await fetch(this.url("/query?format=arrow"),{method:"POST",headers:this.headers({"Content-Type":"application/json",Accept:J1}),credentials:"include",body:JSON.stringify(this.body(e))});if(!t.ok)throw new Error(await this.errorText(t,"/query"));const i=new Uint8Array(await t.arrayBuffer()),{columns:a,rows:u}=Q1(i),f=t.headers.get("X-Sidemantic-Sql")??"";return{columns:a,rows:u,rowCount:u.length,sql:f}}async createBrowserSession(e){var a;const t=this.isCrossOrigin(),i=await fetch(this.url("/auth/session"),{method:"POST",headers:{Authorization:`Bearer ${e}`,...t?{"X-Sidemantic-Session-Mode":"header"}:{}},credentials:"include"});if(i.status===404||i.ok&&!((a=i.headers.get("content-type"))!=null&&a.includes("application/json"))){this.token=e;return}if(!i.ok)throw new Error(await this.errorText(i,"/auth/session"));if(t){const u=await i.json();if(!u.session_token)throw new Error("/auth/session did not return a cross-origin session token");this.sessionToken=u.session_token}this.token=void 0}}function _v({brand:n,toolbar:e,filters:t,rail:i,children:a,drawer:u,showRail:f=!0,openRailRequest:h}){const[m,g]=D.useState(()=>typeof window<"u"&&window.matchMedia("(max-width: 767px)").matches),[v,x]=D.useState(()=>typeof window>"u"||!window.matchMedia("(max-width: 767px)").matches),b=D.useId(),w=D.useRef(null),j=D.useRef(null),C=f&&v;return D.useEffect(()=>{const O=window.matchMedia("(max-width: 767px)"),H=()=>{g(O.matches),x(!O.matches)};return O.addEventListener("change",H),()=>O.removeEventListener("change",H)},[]),D.useEffect(()=>{h&&!m&&x(!0)},[h,m]),D.useEffect(()=>{if(!m||!v)return;const O=j.current,H=document.body.style.overflow;document.body.style.overflow="hidden",window.requestAnimationFrame(()=>{var R,T;return(T=(R=w.current)==null?void 0:R.querySelector("button"))==null?void 0:T.focus()});function L(R){var U;if(R.key==="Escape"){R.preventDefault(),x(!1);return}if(R.key!=="Tab")return;const T=(U=w.current)==null?void 0:U.querySelectorAll('button:not(:disabled), select:not(:disabled), input:not(:disabled), [href], [tabindex]:not([tabindex="-1"])');if(!(T!=null&&T.length))return;const E=T[0],I=T[T.length-1];R.shiftKey&&document.activeElement===E?(R.preventDefault(),I.focus()):!R.shiftKey&&document.activeElement===I&&(R.preventDefault(),E.focus())}return document.addEventListener("keydown",L,!0),()=>{document.body.style.overflow=H,document.removeEventListener("keydown",L,!0),O==null||O.focus()}},[m,v]),c.jsxs("div",{className:"flex h-[100dvh] min-w-0 flex-col overflow-hidden bg-bg text-ink",children:[c.jsxs("header",{className:"relative z-40 flex shrink-0 flex-col gap-2 border-b border-line bg-surface px-3 py-2 md:flex-row md:items-center md:justify-between md:gap-3",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[f?c.jsx("button",{ref:j,type:"button","aria-label":m?"Open catalog":v?"Collapse sidebar":"Expand sidebar","aria-expanded":v,"aria-controls":b,onClick:()=>x(O=>!O),className:"grid size-7 shrink-0 place-items-center border border-line text-faint hover:border-faint hover:text-ink",children:v?"‹":"›"}):null,n]}),c.jsx("div",{className:"flex w-full min-w-0 flex-wrap items-center gap-2 overflow-visible md:w-auto md:shrink-0 md:flex-nowrap",children:e})]}),t?c.jsx("div",{className:"flex min-h-9 shrink-0 flex-wrap items-center gap-2 overflow-x-auto border-b border-line bg-surface px-3 py-2 md:h-9 md:flex-nowrap md:py-0",children:t}):null,c.jsxs("div",{className:`grid min-h-0 min-w-0 flex-1 grid-cols-1 ${C?"md:grid-cols-[260px_minmax(0,1fr)]":"md:grid-cols-1"}`,children:[f&&C?c.jsxs(c.Fragment,{children:[m?c.jsx("button",{type:"button","aria-label":"Close catalog",className:"fixed inset-0 z-40 bg-black/35 backdrop-blur-[2px]",onClick:()=>x(!1)}):null,c.jsxs("aside",{id:b,ref:w,role:m?"dialog":void 0,"aria-modal":m?"true":void 0,"aria-label":m?"Data catalog":void 0,onClick:O=>{m&&O.target.closest("[data-catalog-metric], [data-catalog-dimension]")&&x(!1)},onChange:()=>m&&x(!1),className:"fixed inset-y-0 left-0 z-50 min-h-0 w-[min(88vw,320px)] overflow-y-auto bg-surface shadow-[var(--shadow)] md:static md:z-auto md:w-auto md:border-r md:border-line md:shadow-none",children:[m?c.jsxs("div",{"data-testid":"catalog-drawer-header",className:"sticky top-0 z-10 flex items-center justify-between border-b border-line bg-surface px-4 py-3",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-sm font-semibold text-ink",children:"Catalog"}),c.jsx("p",{className:"text-xs text-muted",children:"Choose a model and fields"})]}),c.jsx("button",{type:"button","aria-label":"Close catalog",onClick:()=>x(!1),className:"grid size-10 place-items-center rounded-full bg-surface-soft text-muted hover:bg-line hover:text-ink",children:c.jsx("span",{"aria-hidden":"true",className:"text-xl leading-none",children:"×"})})]}):null,i]})]}):null,c.jsxs("main",{className:"relative min-h-0 min-w-0 overflow-hidden",children:[c.jsx("div",{className:`h-full overflow-y-auto ${u?"pb-8":""}`,children:a}),u]})]})]})}function eS({dashboardTitle:n,modelLabel:e,onHome:t}){const i=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-sm font-semibold text-ink",children:n??"Sidemantic"}),n===void 0&&e?c.jsx("span",{className:"truncate text-2xs text-faint",children:e}):null]});return n!==void 0?c.jsx("span",{className:"flex min-w-0 items-baseline gap-2",children:i}):c.jsx("button",{type:"button",onClick:t,"aria-label":"Home",className:"flex min-w-0 items-baseline gap-2",children:i})}const tS=new Set(["second","minute","hour","day","week","month","quarter","year"]);function il(n){return n===void 0?[]:Array.isArray(n)?n:[n]}function ol(n,e){return n.models.flatMap(t=>t.dimensions).find(t=>e===t.ref||e.startsWith(`${t.ref}__`))}function nS(n,e){const t=n.split("__").at(-1);return t&&tS.has(t)?t:e}function rS(n){var a;const e=(a=n.defaults)==null?void 0:a.query;if(!e||typeof e!="object")return;const t=e,i=t.use_preaggregations??t.usePreaggregations;return typeof i=="boolean"?i:void 0}function sS(n,e){var u;const t=(u=n.defaults)==null?void 0:u.query,i=t&&typeof t=="object"?t:{},a=e.query.interaction_preaggregations??e.query.interactionPreaggregations??e.interaction_preaggregations??e.interactionPreaggregations??i.interaction_preaggregations??i.interactionPreaggregations;return typeof a=="boolean"?a:void 0}function Cs(n,e,t){var T,E,I,U,G,V,Q;if(!(e!=null&&e.tabs.length))return null;const i=e.tabs.find(z=>z.id===t)??e.tabs[0],a=i.charts[0];if(!a)return null;const u=il(a.query.dimensions),f=il(a.query.metrics),h=f.map(z=>{var ee;return(ee=n.graphMetrics.find(X=>X.ref===z))==null?void 0:ee.ownerModel}).find(z=>!!z),m=((T=f.find(z=>z.includes(".")))==null?void 0:T.split(".")[0])??h??((E=u.find(z=>z.includes(".")))==null?void 0:E.split(".")[0]),g=n.models.find(z=>z.name===m)??n.models[0];if(!g)return null;const v=[...n.models.flatMap(z=>z.metrics),...ji(n,g.name)],x=f.map(z=>v.find(ee=>ee.ref===z)).filter(z=>!!z),b=u.map(z=>ol(n,z)).filter((z,ee,X)=>!!z&&X.findIndex(ie=>(ie==null?void 0:ie.ref)===(z==null?void 0:z.ref))===ee),w=(I=a.encoding)==null?void 0:I.y,C=(Array.isArray(w)?w:w?[w]:[]).find(z=>x.some(ee=>ee.ref===z))??((U=x[0])==null?void 0:U.ref)??((G=g.metrics[0])==null?void 0:G.ref)??"",O=(V=a.encoding)==null?void 0:V.x,H=(O&&((Q=ol(n,O))==null?void 0:Q.type)==="time"?O:void 0)??u.find(z=>{var ee;return((ee=ol(n,z))==null?void 0:ee.type)==="time"}),L=g.defaultGrain??"month",R=H?ol(n,H):g.timeDimension;return{id:i.id,label:i.label??i.id,title:a.title??e.title,model:g,metrics:x.length?x:g.metrics,dimensions:b.length?b:g.dimensions,timeDimension:R,selectedMetric:C,grain:H?nS(H,L):L,filters:il(a.query.filters),segments:il(a.query.segments),usePreaggregations:sS(e,a)??a.query.use_preaggregations??a.query.usePreaggregations??rS(e)}}const Fd=["second","minute","hour","day","week","month","quarter","year"];function iS(n,e){if(n!=null&&n.length){const i=new Set(n.map(u=>u.toLowerCase())),a=Fd.filter(u=>i.has(u));if(a.length)return a}const t=["day","week","month","quarter","year"];return e&&!t.includes(e)?Fd.filter(i=>i===e||t.includes(i)):t}function Ni(n){return n.toISOString().slice(0,10)}function nf(n){return n.slice(0,10)}function Oi(n){const e=n.trim();return/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:/[zZ]|[+-]\d{2}:?\d{2}$/.test(e)?e:`${e.replace(" ","T")}Z`}function Fs(n){return new Date(`${nf(n)}T00:00:00Z`)}function Uo(n,e){const t=Fs(n);return t.setUTCDate(t.getUTCDate()+e),Ni(t)}function oS(n){return Math.round((Fs(n.to).getTime()-Fs(n.from).getTime())/864e5)+1}function aS(n){if(n.from.includes("T")||n.to.includes("T")){const a=Date.parse(Oi(n.from)),f=Date.parse(Oi(n.to))-a;return{from:new Date(a-f).toISOString().slice(0,19),to:new Date(a).toISOString().slice(0,19)}}const e=oS(n),t=Uo(n.from,-1);return{from:Uo(t,-(e-1)),to:t}}function Rm(n){if(n.includes("T")){const f=new Date(Oi(n)),h=f.getUTCFullYear()-1,m=f.getUTCMonth(),g=new Date(Date.UTC(h,m+1,0)).getUTCDate();return new Date(Date.UTC(h,m,Math.min(f.getUTCDate(),g),f.getUTCHours(),f.getUTCMinutes(),f.getUTCSeconds())).toISOString().slice(0,19)}const e=Fs(n),t=e.getUTCFullYear()-1,i=e.getUTCMonth(),a=e.getUTCDate(),u=new Date(Date.UTC(t,i+1,0)).getUTCDate();return Ni(new Date(Date.UTC(t,i,Math.min(a,u))))}function lS(n){return{from:Rm(n.from),to:Rm(n.to)}}function uS(n,e){const t=n.trim(),i=t.slice(0,10);if(e!=="second"&&e!=="minute"&&e!=="hour")return i||n;const a=t.slice(10).match(/(\d{2}):(\d{2})(?::(\d{2}))?/);if(!a)return i||n;const u=e==="second"&&a[3]?`${a[1]}:${a[2]}:${a[3]}`:`${a[1]}:${a[2]}`;return`${i} ${u}`}const cS=[{key:"7d",label:"Last 7 days",days:7},{key:"28d",label:"Last 28 days",days:28},{key:"90d",label:"Last 90 days",days:90},{key:"180d",label:"Last 180 days",days:180},{key:"365d",label:"Last 12 months",days:365}];function dS(n,e=new Date){const t=Ni(e);return{from:Uo(t,-(n-1)),to:t}}function fS(n,e){return e.from.includes("T")||e.to.includes("T")?[`${n} >= cast('${e.from}' as timestamp)`,`${n} < cast('${e.to}' as timestamp)`]:[`${n} >= cast('${e.from}' as date)`,`${n} < cast('${Uo(e.to,1)}' as date)`]}function Lm(n,e,t){if(t==="second"||t==="minute"||t==="hour"){const f=t==="second"?1e3:t==="minute"?6e4:36e5;return Math.round((Date.parse(Oi(e))-Date.parse(Oi(n)))/f)}const i=Fs(n),a=Fs(e),u=(a.getUTCFullYear()-i.getUTCFullYear())*12+(a.getUTCMonth()-i.getUTCMonth());switch(t){case"week":return Math.round((a.getTime()-i.getTime())/(7*864e5));case"month":return u;case"quarter":return Math.round(u/3);case"year":return a.getUTCFullYear()-i.getUTCFullYear();default:return Math.round((a.getTime()-i.getTime())/864e5)}}function ld(n,e){return new Date(Date.parse(Oi(n))+e).toISOString().slice(0,19)}function hS(n,e){const t=nf(n),i=Fs(t);switch(e){case"second":return ld(n,1e3);case"minute":return ld(n,6e4);case"hour":return ld(n,36e5);case"day":return t;case"week":return Uo(n,6);case"month":return Ni(new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth()+1,0)));case"quarter":{const a=Math.floor(i.getUTCMonth()/3)*3+3;return Ni(new Date(Date.UTC(i.getUTCFullYear(),a,0)))}case"year":return Ni(new Date(Date.UTC(i.getUTCFullYear(),12,0)));default:return n}}function rf(n){return n.mode==="contains"?!n.pattern:n.values.length===0}function sf(n){return Object.fromEntries(n.map(e=>[e.ref,e.type]))}function ou(n){return sf(n.models.flatMap(e=>e.dimensions))}function Um(n,e){if((e==="numeric"||e==="number")&&n.trim()!==""&&Number.isFinite(Number(n)))return n;if(e==="boolean"){const t=n.toLowerCase();if(t==="true"||t==="false")return t}return Tn(n)}function Nv(n){return n.replaceAll("\\","\\\\").replaceAll("%","\\%").replaceAll("_","\\_")}function pS(n,e,t){const i=e.mode==="exclude",a=e.values.includes(er),u=e.values.filter(h=>h!==er);let f=null;if(u.length===1)f=`${n} ${i?"!=":"="} ${Um(u[0],t)}`;else if(u.length>1){const h=u.map(m=>Um(m,t)).join(", ");f=`${n} ${i?"NOT IN":"IN"} (${h})`}if(!i){const h=[];return f&&h.push(f),a&&h.push(`${n} IS NULL`),h.length===0?null:h.length===1?h[0]:`(${h.join(" OR ")})`}if(a){const h=[];return f&&h.push(f),h.push(`${n} IS NOT NULL`),h.length===1?h[0]:`(${h.join(" AND ")})`}return f?`(${f} OR ${n} IS NULL)`:null}function jv(n,e={}){var i;const t=[];for(const[a,u]of Object.entries(n)){if(a===e.excludeDim||rf(u))continue;const f=(i=e.types)==null?void 0:i[a];if(u.mode==="contains"){const m=Tn(`%${Nv(u.pattern??"")}%`);t.push(`CAST(${a} AS VARCHAR) ILIKE ${m} ESCAPE '\\'`);continue}const h=pS(a,u,f);h&&t.push(h)}return t}function Os(n,e={}){const t=jv(n,{types:e.types,excludeDim:e.excludeDim});return e.timeRef&&e.range&&t.push(...fS(e.timeRef,e.range)),t}function $m(n,e,t,i){return{metrics:n,filters:e,...t!=null&&t.length?{segments:t}:{},...i!=null?{usePreaggregations:i}:{}}}const mS={second:2e3,minute:2e3,hour:9600,day:4e3,week:800,month:240,quarter:120,year:60};function Pm(n,e,t,i,a,u,f=!1){const h=`${e}__${t}`,m=t==="second"||t==="minute",g=m&&!f;return{metrics:n,dimensions:[h],filters:i,...a!=null&&a.length?{segments:a}:{},...u!=null?{usePreaggregations:u}:{},orderBy:[`${h} ${g?"DESC":"ASC"}`],...!m||g?{limit:mS[t]??2e3}:{}}}function zm(n,e,t,i=6,a,u){return{metrics:[n],dimensions:[e],filters:t,...a!=null&&a.length?{segments:a}:{},...u!=null?{usePreaggregations:u}:{},orderBy:[`${n} DESC`],limit:i}}function yS(n,e,t=50,i,a){return{dimensions:[n],filters:e,...i!=null&&i.length?{segments:i}:{},...a!=null?{usePreaggregations:a}:{},orderBy:[`${n} ASC`],limit:t}}function gS(n,e,t,i,a=500){return{metrics:n,dimensions:e,filters:t,orderBy:i,limit:a}}function vS(n,e,t=50,i,a){return{dimensions:n.dimensions,metrics:n.metrics,filters:e,...i!=null&&i.length?{segments:i}:{},...a!=null?{usePreaggregations:a}:{},ungrouped:!0,limit:t}}function xS(n,e){const t=n??[];return t.includes(e)?t.filter(i=>i!==e):[...t,e]}function al(n,e,t){const i={...n};return rf(t)?delete i[e]:i[e]=t,i}function bS(n,e){switch(e.type){case"hydrate":return e.state;case"setView":return{...n,view:e.view};case"setDashboardTab":return{...n,view:"explore",dashboardTab:e.tab,model:e.model,selectedMetric:e.metric,grain:e.grain,filters:{},dateRange:void 0,pivotDims:[],pivotMetrics:[]};case"setModel":return{...n,model:e.model,selectedMetric:e.metric,grain:e.grain,filters:{},pivotDims:[],pivotMetrics:[]};case"setMetric":return{...n,selectedMetric:e.metric};case"toggleFilter":{const t=n.filters[e.dim],i=e.mode??(t&&t.mode!=="contains"?t.mode:"include"),a=t&&t.mode===i?t.values:[],u=xS(a,e.value);return{...n,filters:al(n.filters,e.dim,{mode:i,values:u})}}case"setFilterMode":{const t=n.filters[e.dim],i={mode:e.mode,values:(t==null?void 0:t.values)??[],pattern:t==null?void 0:t.pattern};return{...n,filters:al(n.filters,e.dim,i)}}case"setFilterPattern":{const t=n.filters[e.dim],i={mode:"contains",values:(t==null?void 0:t.values)??[],pattern:e.pattern};return{...n,filters:al(n.filters,e.dim,i)}}case"removeFilterValue":{const t=n.filters[e.dim];if(!t)return n;const i=t.values.filter(a=>a!==e.value);return{...n,filters:al(n.filters,e.dim,{...t,values:i})}}case"removeFilterDim":{const t={...n.filters};return delete t[e.dim],{...n,filters:t}}case"clearFilters":return{...n,filters:{}};case"setGrain":return{...n,grain:e.grain};case"setTimezone":return{...n,timezone:e.timezone};case"setDateRange":return{...n,dateRange:e.range};case"setContextColumn":return{...n,contextColumn:e.column};case"setComparison":return{...n,comparison:e.comparison,comparisonRange:e.comparison==="custom"?e.range:void 0};case"setPivotDims":return{...n,pivotDims:e.dims};case"setPivotMetrics":return{...n,pivotMetrics:e.metrics};case"reset":return{...e.initial,view:n.view};default:return n}}function wS(n){return n.models.find(e=>e.timeDimension)??n.models[0]}function kv(n,e){var t,i;return((t=n==null?void 0:n.metrics[0])==null?void 0:t.ref)??(n?(i=ji(e,n.name)[0])==null?void 0:i.ref:void 0)??""}function Iv(n,e,t){const i=Cs(n,e,t),a=(i==null?void 0:i.model)??wS(n),u=(i==null?void 0:i.selectedMetric)??kv(a,n);return{view:i?"explore":"home",dashboardTab:i==null?void 0:i.id,model:(a==null?void 0:a.name)??"",selectedMetric:u,filters:{},grain:(i==null?void 0:i.grain)??(a==null?void 0:a.defaultGrain)??"month",timezone:"UTC",dateRange:void 0,contextColumn:"none",comparison:"previous",comparisonRange:void 0,pivotDims:[],pivotMetrics:[]}}function SS(n,e,t){const i=new URLSearchParams(t),a=i.get("metric"),u=i.get("grain"),f=a===n.selectedMetric&&e.metrics.some(m=>m.ref===a),h=u===n.grain;return{...n,view:"explore",dashboardTab:e.id,model:e.model.name,selectedMetric:f?n.selectedMetric:e.selectedMetric,grain:h?n.grain:e.grain}}const _S=["home","explore","pivot"],NS=new Set(Fd),jS=new Set(["none","pctTotal","delta","deltaPct"]),kS=new Set(["off","previous","year","custom"]),IS="none",MS="previous",DS="UTC";function CS(n){return n!=null&&/^[A-Za-z][A-Za-z0-9/_+-]{0,63}$/.test(n)}function ud(n){if(n)try{return JSON.parse(n)}catch{return}}function Zl(n){return Array.isArray(n)&&n.every(e=>typeof e=="string")}function ll(n){return n!=null&&/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2})?$/.test(n)&&!Number.isNaN(Date.parse(n))}const FS=new Set(["include","exclude","contains"]);function OS(n){if(Zl(n))return{mode:"include",values:n};if(typeof n!="object"||n===null||Array.isArray(n))return null;const e=n;if(!FS.has(e.mode))return null;const t=e.mode,i=Zl(e.values)?e.values:[],a=typeof e.pattern=="string"?e.pattern:void 0,u={mode:t,values:i,pattern:a};return rf(u)?null:u}function TS(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;const e={};for(const[t,i]of Object.entries(n)){const a=OS(i);a&&(e[t]=a)}return e}function AS(n){const e={};for(const[t,i]of Object.entries(n))e[t]=i.mode==="include"?i.values:i;return e}function BS(n){const e=new URLSearchParams;return e.set("view",n.view),n.dashboardTab&&e.set("tab",n.dashboardTab),n.model&&e.set("model",n.model),n.selectedMetric&&e.set("metric",n.selectedMetric),n.grain&&e.set("grain",n.grain),n.timezone&&n.timezone!==DS&&e.set("tz",n.timezone),n.dateRange&&(e.set("from",n.dateRange.from),e.set("to",n.dateRange.to)),n.contextColumn!==IS&&e.set("ctx",n.contextColumn),n.comparison!==MS&&e.set("cmp",n.comparison),n.comparison==="custom"&&n.comparisonRange&&(e.set("cfrom",n.comparisonRange.from),e.set("cto",n.comparisonRange.to)),Object.keys(n.filters).length&&e.set("filters",JSON.stringify(AS(n.filters))),n.pivotDims.length&&e.set("pdims",JSON.stringify(n.pivotDims)),n.pivotMetrics.length&&e.set("pmetrics",JSON.stringify(n.pivotMetrics)),e.toString()}function ES(n,e){const t=new URLSearchParams(n),i={...e},a=t.get("view");a&&_S.includes(a)&&(i.view=a);const u=t.get("tab");u&&(i.dashboardTab=u);const f=t.get("model");f&&(i.model=f);const h=t.get("metric");h&&(i.selectedMetric=h);const m=t.get("grain");m&&NS.has(m)&&(i.grain=m);const g=t.get("tz");CS(g)&&(i.timezone=g);const v=t.get("from"),x=t.get("to");ll(v)&&ll(x)&&Date.parse(v)<=Date.parse(x)&&(i.dateRange={from:v,to:x});const b=t.get("ctx");b&&jS.has(b)&&(i.contextColumn=b);const w=t.get("cmp");w&&kS.has(w)&&(i.comparison=w);const j=t.get("cfrom"),C=t.get("cto");i.comparison==="custom"&&ll(j)&&ll(C)&&Date.parse(j)<=Date.parse(C)&&(i.comparisonRange={from:j,to:C});const O=TS(ud(t.get("filters")));O&&(i.filters=O);const H=ud(t.get("pdims"));Zl(H)&&(i.pivotDims=H);const L=ud(t.get("pmetrics"));return Zl(L)&&(i.pivotMetrics=L),i}const Mv=D.createContext(null);function RS({catalog:n,backend:e,dashboard:t,children:i}){const a=D.useMemo(()=>Iv(n,t),[n,t]),[u,f]=D.useReducer(bS,void 0,()=>{const m=ES(window.location.search,a),g=Cs(n,t,m.dashboardTab);return g?SS(m,g,window.location.search):m});D.useEffect(()=>{const m=BS(u),g=`${window.location.pathname}${m?`?${m}`:""}`;window.history.replaceState(null,"",g)},[u]);const h=D.useMemo(()=>({state:u,dispatch:f,catalog:n,backend:e,initial:a,dashboard:t}),[u,n,e,a,t]);return c.jsx(Mv.Provider,{value:h,children:i})}function ls(){const n=D.useContext(Mv);if(!n)throw new Error("useExplorer must be used within ExplorerProvider");return n}const Is={active:0,listeners:new Set};function Dv(){for(const n of Is.listeners)n()}function LS(){Is.active+=1,Dv()}function US(){Is.active=Math.max(0,Is.active-1),Dv()}function Cv(){return D.useSyncExternalStore(n=>(Is.listeners.add(n),()=>Is.listeners.delete(n)),()=>Is.active>0,()=>!1)}const $S=80;function Zn(n,e){const[t,i]=D.useState({loading:!1}),a=D.useRef(0),u=e?JSON.stringify(e):null;return D.useEffect(()=>{if(!e){i({loading:!1});return}const f=++a.current;i(m=>({result:m.result,loading:!0}));const h=setTimeout(()=>{LS(),n.runQuery(e).then(m=>{f===a.current&&i({result:m,loading:!1})}).catch(m=>{f===a.current&&i({loading:!1,error:m instanceof Error?m.message:String(m)})}).finally(()=>US())},$S);return()=>clearTimeout(h)},[u,n]),t}const PS=[{mode:"include",label:"Include"},{mode:"exclude",label:"Exclude"},{mode:"contains",label:"Contains"}],zS=50,Vm=200;function Wm(n,e){const[t,i]=D.useState(n);return D.useEffect(()=>{const a=setTimeout(()=>i(n),e);return()=>clearTimeout(a)},[n,e]),t}function Fv({dim:n,model:e,onClose:t}){var W,_;const{state:i,dispatch:a,backend:u,catalog:f,dashboard:h}=ls(),m=D.useMemo(()=>Cs(f,h,i.dashboardTab),[f,h,i.dashboardTab]),g=i.filters[n.ref],[v,x]=D.useState((g==null?void 0:g.mode)??"include"),b=D.useMemo(()=>new Set((g==null?void 0:g.mode)!=="contains"?(g==null?void 0:g.values)??[]:[]),[g]),w=D.useRef(null),j=D.useRef(null),C=D.useId(),[O,H]=D.useState(""),L=Wm(O,Vm),R=(g==null?void 0:g.mode)==="contains"?g.pattern??"":"",[T,E]=D.useState(R),I=Wm(T,Vm);D.useEffect(()=>{var te;const F=document.activeElement;return(te=j.current)==null||te.focus(),()=>{var pe;return(pe=F==null?void 0:F.focus)==null?void 0:pe.call(F)}},[]),D.useEffect(()=>{function F(pe){pe.key==="Escape"&&(pe.stopPropagation(),t())}function te(pe){w.current&&!w.current.contains(pe.target)&&t()}return document.addEventListener("keydown",F,!0),document.addEventListener("mousedown",te,!0),()=>{document.removeEventListener("keydown",F,!0),document.removeEventListener("mousedown",te,!0)}},[t]),D.useEffect(()=>{v==="contains"&&I!==R&&a({type:"setFilterPattern",dim:n.ref,pattern:I})},[I,v,n.ref,a]);const U=((W=m==null?void 0:m.timeDimension)==null?void 0:W.ref)??((_=e.timeDimension)==null?void 0:_.ref),G=D.useMemo(()=>ou(f),[f]),V=D.useMemo(()=>{const F=[...(m==null?void 0:m.filters)??[],...Os(i.filters,{timeRef:U,range:i.dateRange,excludeDim:n.ref,types:G})];if(L.trim()){const te=Tn(`%${Nv(L.trim())}%`);F.push(`CAST(${n.ref} AS VARCHAR) ILIKE ${te} ESCAPE '\\'`)}return F},[m,i.filters,U,i.dateRange,n.ref,L,G]),Q=v!=="contains",{result:z,loading:ee,error:X}=Zn(u,Q?yS(n.ref,V,zS,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations):null),ie=Sr(n.ref),ae=D.useMemo(()=>z?z.rows.map(F=>{const te=F[ie];return te==null?er:String(te)}):[],[z,ie]),re=!!z&&z.rows.length>0&&!z.columns.includes(ie),se=Q&&(ee||re);function A(F){x(F),g&&a({type:"setFilterMode",dim:n.ref,mode:F}),F==="contains"&&E(R)}function Y(F){var fe;if(F.key!=="Tab")return;const te=(fe=w.current)==null?void 0:fe.querySelectorAll('button, input, [href], select, textarea, [tabindex]:not([tabindex="-1"])');if(!te||te.length===0)return;const pe=te[0],ne=te[te.length-1];F.shiftKey&&document.activeElement===pe?(F.preventDefault(),ne.focus()):!F.shiftKey&&document.activeElement===ne&&(F.preventDefault(),pe.focus())}return c.jsxs("div",{ref:w,role:"dialog","aria-modal":"true","aria-labelledby":C,onKeyDown:Y,className:"absolute left-0 z-50 mt-1 w-64 border border-line bg-surface p-2 text-2xs shadow-lg",children:[c.jsxs("div",{id:C,className:"mb-2 flex items-baseline justify-between gap-2",children:[c.jsx("span",{className:"truncate font-semibold text-ink",children:n.label}),c.jsx("button",{type:"button","aria-label":"Close filter editor",onClick:t,className:"grid size-4 place-items-center rounded-full bg-surface-soft text-faint hover:bg-line hover:text-ink",children:"×"})]}),c.jsx("div",{role:"group","aria-label":"Filter mode",className:"mb-2 grid grid-cols-3 gap-px border border-line bg-line",children:PS.map(({mode:F,label:te})=>c.jsx("button",{type:"button","aria-pressed":v===F,onClick:()=>A(F),className:`px-1.5 py-1 text-center ${v===F?"bg-accent-soft font-medium text-accent":"bg-surface text-muted hover:bg-surface-soft"}`,children:te},F))}),v==="contains"?c.jsx("input",{ref:j,type:"text","aria-label":`${n.label} contains`,placeholder:"Substring…",value:T,onChange:F=>E(F.target.value),className:"w-full border border-line bg-surface px-1.5 py-1 text-2xs text-ink placeholder:text-faint"}):c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:j,type:"text","aria-label":`Search ${n.label} values`,placeholder:"Search values…",value:O,onChange:F=>H(F.target.value),className:"w-full border border-line bg-surface px-1.5 py-1 text-2xs text-ink placeholder:text-faint"}),c.jsx("div",{className:"mt-2 max-h-56 overflow-y-auto",role:"group","aria-label":`${n.label} values`,children:X?c.jsx("p",{className:"px-1 py-2 text-danger",children:X}):se?c.jsx("div",{className:"space-y-1.5 p-1",children:[0,1,2,3,4].map(F=>c.jsx("div",{className:"skeleton h-4 w-full"},F))}):ae.length===0?c.jsx("p",{className:"px-1 py-2 text-faint",children:"No values"}):ae.map(F=>{const te=b.has(F);return c.jsxs("label",{className:"flex cursor-pointer items-center gap-2 px-1 py-1 hover:bg-surface-soft",children:[c.jsx("input",{type:"checkbox",checked:te,onChange:()=>a({type:"toggleFilter",dim:n.ref,value:F,mode:v}),className:"size-3 accent-[var(--accent)]"}),c.jsx("span",{className:"min-w-0 truncate text-ink",children:rs(F)})]},F)})})]}),c.jsxs("div",{className:"mt-2 flex items-center justify-between border-t border-line pt-2",children:[c.jsx("button",{type:"button",onClick:()=>a({type:"removeFilterDim",dim:n.ref}),className:"text-muted underline-offset-2 hover:text-ink hover:underline",children:"Clear"}),c.jsx("button",{type:"button",onClick:t,className:"border border-line px-2 py-1 text-muted hover:bg-surface-soft",children:"Done"})]})]})}function VS({model:n}){const e=n.dimensions.filter(m=>m.type!=="time"),[t,i]=D.useState(!1),[a,u]=D.useState(null),f=D.useRef(null);D.useEffect(()=>{if(!t)return;function m(v){v.key==="Escape"&&h()}function g(v){a||f.current&&!f.current.contains(v.target)&&h()}return document.addEventListener("keydown",m,!0),document.addEventListener("mousedown",g,!0),()=>{document.removeEventListener("keydown",m,!0),document.removeEventListener("mousedown",g,!0)}},[t,a]);function h(){i(!1),u(null)}return e.length===0?null:c.jsxs("span",{ref:f,className:"relative inline-flex",children:[c.jsx("button",{type:"button","aria-haspopup":"dialog","aria-expanded":t,onClick:()=>t?h():i(!0),className:"inline-flex h-7 shrink-0 items-center rounded-full border border-dashed border-line px-3 text-xs text-muted hover:border-faint hover:text-ink",children:"+ Filter"}),t&&!a?c.jsx("div",{role:"menu","aria-label":"Add a filter for a dimension",className:"absolute left-0 z-50 mt-1 max-h-64 w-48 overflow-y-auto rounded-xl border border-line bg-surface p-1.5 text-2xs shadow-[var(--shadow)]",children:e.map(m=>c.jsx("button",{type:"button",role:"menuitem",onClick:()=>u(m),className:"block w-full truncate px-1.5 py-1 text-left text-muted hover:bg-surface-soft hover:text-ink",children:m.label},m.ref))}):null,t&&a?c.jsx(Fv,{dim:a,model:n,onClose:h}):null]})}function cd(n,e){return n.includes(e)?n.filter(t=>t!==e):[...n,e]}function Hm({metric:n,selected:e,multiple:t,onSelect:i}){return c.jsxs("button",{type:"button","data-catalog-metric":n.ref,"data-selected":e||void 0,"aria-pressed":e,title:n.description,onClick:i,className:"flex w-full items-center justify-between gap-2 border-l-2 px-3 py-1 text-left text-xs hover:bg-surface-soft data-[selected=true]:border-l-accent data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent border-l-transparent text-muted",children:[c.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[t?c.jsx("span",{"aria-hidden":"true",className:"w-3 shrink-0 text-center text-accent",children:e?"✓":""}):null,c.jsx("span",{className:"truncate",children:n.label})]}),n.agg?c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:n.agg}):null]})}function WS({dimension:n,selected:e,onSelect:t}){return c.jsxs("button",{type:"button","data-catalog-dimension":n.ref,"data-selected":e||void 0,"aria-pressed":e,title:n.description,onClick:t,className:"flex w-full items-center justify-between gap-2 border-l-2 border-l-transparent px-3 py-1 text-left text-xs text-muted hover:bg-surface-soft data-[selected=true]:border-l-accent data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent",children:[c.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[c.jsx("span",{"aria-hidden":"true",className:"w-3 shrink-0 text-center",children:e?"✓":""}),c.jsx("span",{className:"truncate",children:n.label})]}),c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:n.type==="time"?"time":""})]})}function HS(){const{state:n,dispatch:e,catalog:t}=ls(),i=t.models.find(h=>h.name===n.model),a=ji(t,n.model),u=n.view==="pivot",f=n.pivotMetrics.length?n.pivotMetrics:n.selectedMetric?[n.selectedMetric]:[];return c.jsxs("nav",{"aria-label":"Semantic layer catalog",className:"flex flex-col gap-4 py-3 text-sm",children:[c.jsxs("section",{className:"px-3",children:[c.jsx("h2",{className:"mb-1 text-xs font-medium text-muted",children:"Model"}),c.jsx("select",{"aria-label":"Model",value:n.model,onChange:h=>{var v,x;const m=t.models.find(b=>b.name===h.target.value),g=((v=m==null?void 0:m.metrics[0])==null?void 0:v.ref)??((x=ji(t,h.target.value)[0])==null?void 0:x.ref)??"";e({type:"setModel",model:h.target.value,metric:g,grain:(m==null?void 0:m.defaultGrain)??"month"})},className:"w-full border border-line bg-surface px-2 py-1 text-xs text-ink",children:t.models.map(h=>c.jsx("option",{value:h.name,children:h.label},h.name))})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-1 px-3 text-xs font-medium text-muted",children:"Metrics"}),c.jsx("div",{children:((i==null?void 0:i.metrics)??[]).map(h=>c.jsx(Hm,{metric:h,selected:u?f.includes(h.ref):n.selectedMetric===h.ref,multiple:u,onSelect:()=>e(u?{type:"setPivotMetrics",metrics:cd(f,h.ref)}:{type:"setMetric",metric:h.ref})},h.ref))}),a.length?c.jsxs(c.Fragment,{children:[c.jsx("h3",{className:"mb-1 mt-3 px-3 text-xs font-medium text-muted",children:"Shared metrics"}),c.jsx("div",{children:a.map(h=>c.jsx(Hm,{metric:h,selected:u?f.includes(h.ref):n.selectedMetric===h.ref,multiple:u,onSelect:()=>e(u?{type:"setPivotMetrics",metrics:cd(f,h.ref)}:{type:"setMetric",metric:h.ref})},h.ref))})]}):null]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-1 px-3 text-xs font-medium text-muted",children:"Dimensions"}),u?c.jsx("div",{children:((i==null?void 0:i.dimensions)??[]).map(h=>c.jsx(WS,{dimension:h,selected:n.pivotDims.includes(h.ref),onSelect:()=>e({type:"setPivotDims",dims:cd(n.pivotDims,h.ref)})},h.ref))}):c.jsx("ul",{className:"px-3 text-xs text-muted",children:((i==null?void 0:i.dimensions)??[]).map(h=>c.jsxs("li",{className:"flex items-center justify-between gap-2 py-0.5",title:h.description,children:[c.jsx("span",{className:"truncate",children:h.label}),c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:h.type==="time"?"time":""})]},h.ref))})]})]})}class GS extends D.Component{constructor(){super(...arguments);Mn(this,"state",{})}static getDerivedStateFromError(t){return{error:t}}render(){return this.state.error?c.jsx("div",{className:"p-4",children:c.jsxs("div",{className:"border border-danger/40 bg-surface p-4",children:[c.jsx("p",{className:"text-sm font-semibold text-danger",children:"Something went wrong rendering this view."}),c.jsx("p",{className:"mt-1 break-words text-xs text-muted",children:this.state.error.message}),c.jsxs("div",{className:"mt-3 flex gap-2",children:[c.jsx("button",{type:"button",onClick:()=>this.setState({error:void 0}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Retry"}),c.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Reload"})]})]})}):this.props.children}}const YS=[{key:"off",label:"Off"},{key:"previous",label:"Previous period"},{key:"year",label:"Previous year"},{key:"custom",label:"Custom range"}];function Ov({range:n,disabled:e,onChange:t,comparison:i,comparisonRange:a,onComparisonChange:u}){const f=D.useRef(null),[h,m]=D.useState((n==null?void 0:n.from)??""),[g,v]=D.useState((n==null?void 0:n.to)??""),[x,b]=D.useState((a==null?void 0:a.from)??""),[w,j]=D.useState((a==null?void 0:a.to)??"");function C(){f.current&&(f.current.open=!1)}function O(T){t(T),C()}function H(T){T==="custom"?u("custom",x&&w?{from:x,to:w}:void 0):u(T)}const L=n?`${n.from} → ${n.to}`:"All time",R=!n;return c.jsxs("details",{ref:f,className:"relative text-xs",onToggle:T=>{e&&(T.currentTarget.open=!1)},children:[c.jsxs("summary",{"aria-disabled":e||void 0,tabIndex:e?-1:void 0,onClick:T=>e&&T.preventDefault(),onKeyDown:T=>{e&&(T.key==="Enter"||T.key===" ")&&T.preventDefault()},className:`flex h-7 cursor-pointer items-center gap-1.5 rounded-full border border-line bg-surface px-3 text-ink ${e?"cursor-not-allowed opacity-50":""}`,children:[c.jsx("span",{className:"text-faint",children:"Range"}),c.jsx("span",{className:"tnum",children:L}),c.jsx("span",{"aria-hidden":"true",className:"text-faint",children:"▾"})]}),c.jsxs("div",{className:"absolute right-0 z-50 mt-1 w-64 rounded-xl border border-line bg-surface p-1.5 shadow-[var(--shadow)]",children:[c.jsx("button",{type:"button",onClick:()=>O(void 0),className:"w-full rounded-lg px-2.5 py-1.5 text-left text-xs text-muted hover:bg-surface-soft hover:text-ink",children:"All time"}),c.jsx("div",{className:"grid grid-cols-2",children:cS.map(T=>c.jsx("button",{type:"button",onClick:()=>O(dS(T.days)),className:"rounded-lg px-2.5 py-1.5 text-left text-xs text-muted hover:bg-surface-soft hover:text-ink",children:T.label},T.key))}),c.jsxs("div",{className:"mt-2 px-1 pb-1",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("input",{type:"date","aria-label":"From date",value:h,onChange:T=>m(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"}),c.jsx("span",{className:"text-faint",children:"→"}),c.jsx("input",{type:"date","aria-label":"To date",value:g,onChange:T=>v(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"})]}),c.jsx("button",{type:"button",disabled:!h||!g,onClick:()=>O({from:h,to:g}),className:"mt-1.5 inline-flex h-7 w-full items-center justify-center rounded-full border border-accent bg-accent-soft text-xs font-medium text-accent hover:bg-accent hover:text-surface disabled:pointer-events-none disabled:opacity-50",children:"Apply custom range"})]}),c.jsxs("div",{className:"mt-1 px-1 pb-1","data-testid":"comparison-picker",children:[c.jsx("p",{className:"mb-1 px-1.5 text-2xs text-faint",children:"Compare to"}),c.jsx("div",{className:`grid grid-cols-2 ${R?"opacity-50":""}`,children:YS.map(T=>c.jsx("button",{type:"button",disabled:R,"data-comparison":T.key,"data-active":i===T.key||void 0,onClick:()=>H(T.key),className:"rounded-lg px-2.5 py-1.5 text-left text-xs text-muted hover:bg-surface-soft hover:text-ink data-[active=true]:bg-accent-soft data-[active=true]:text-accent",children:T.label},T.key))}),i==="custom"&&!R?c.jsxs("div",{className:"mt-1.5",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("input",{type:"date","aria-label":"Comparison from date",value:x,onChange:T=>b(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"}),c.jsx("span",{className:"text-faint",children:"→"}),c.jsx("input",{type:"date","aria-label":"Comparison to date",value:w,onChange:T=>j(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"})]}),c.jsx("button",{type:"button",disabled:!x||!w,onClick:()=>u("custom",{from:x,to:w}),className:"mt-1.5 inline-flex h-7 w-full items-center justify-center rounded-full border border-accent bg-accent-soft text-xs font-medium text-accent hover:bg-accent hover:text-surface disabled:pointer-events-none disabled:opacity-50",children:"Apply comparison"})]}):null]})]})]})}function Od(n){const[e,t]=D.useState(!1);if(!("dim"in n))return c.jsxs("span",{"data-dimension":n.dimension,"data-value":n.value,className:"inline-flex max-w-full items-center gap-1 rounded-full bg-surface-soft px-2 py-0.5 text-2xs leading-4 text-muted",children:[c.jsxs("span",{className:"truncate",children:[c.jsxs("span",{className:"text-faint",children:[n.dimensionLabel??n.dimension,":"]})," ",n.value]}),n.onRemove?c.jsx("button",{type:"button","aria-label":`Remove filter ${n.value}`,onClick:n.onRemove,className:"-mr-0.5 px-0.5 text-faint hover:text-ink",children:"×"}):null]});const{dim:i,model:a,filter:u,onRemove:f}=n;return c.jsxs("span",{className:"relative inline-flex max-w-full items-center","data-dimension":i.ref,"data-mode":u.mode,children:[c.jsxs("span",{className:"inline-flex max-w-full items-center gap-1 rounded-full bg-surface-soft px-2 py-0.5 text-2xs leading-4 text-muted",children:[c.jsxs("button",{type:"button","aria-label":`Edit filter ${i.label}`,"aria-haspopup":"dialog","aria-expanded":e,onClick:()=>t(h=>!h),className:"min-w-0 truncate text-left hover:text-ink",children:[c.jsx("span",{className:"text-faint",children:i.label})," ",yb(u)]}),c.jsx("button",{type:"button","aria-label":`Remove filter ${i.label}`,onClick:f,className:"grid size-3.5 shrink-0 place-items-center rounded-full bg-surface-soft text-faint hover:bg-line hover:text-ink",children:"×"})]}),e?c.jsx(Fv,{dim:i,model:a,onClose:()=>t(!1)}):null]})}function Td({grain:n,options:e,disabled:t,onChange:i}){return c.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-faint",children:[c.jsx("span",{className:"hidden sm:inline",children:"Grain"}),c.jsx("select",{"aria-label":"Time grain",value:n,disabled:t,onChange:a=>i(a.target.value),className:"h-7 rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50",children:e.map(a=>c.jsx("option",{value:a,children:Le(a)},a))})]})}const QS=["UTC","America/Los_Angeles","America/Denver","America/Chicago","America/New_York","America/Sao_Paulo","Europe/London","Europe/Berlin","Europe/Paris","Europe/Moscow","Asia/Dubai","Asia/Kolkata","Asia/Singapore","Asia/Shanghai","Asia/Tokyo","Australia/Sydney"];let ul=null;function Gm(){if(ul)return ul;const n=typeof Intl.supportedValuesOf=="function"?Intl.supportedValuesOf("timeZone"):[];return ul=[...new Set(["UTC",...n])].sort(),ul}function KS(n){if(!n)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:n}),!0}catch{return!1}}function JS(n,e=new Date){var t;try{const u=(((t=new Intl.DateTimeFormat("en-US",{timeZone:n,timeZoneName:"shortOffset"}).formatToParts(e).find(g=>g.type==="timeZoneName"))==null?void 0:t.value)??"").match(/([+-])(\d{1,2})(?::(\d{2}))?/);if(!u)return n==="UTC"?"+00:00":"";const f=u[1],h=u[2].padStart(2,"0"),m=u[3]??"00";return`${f}${h}:${m}`}catch{return""}}const Ym="__search__";function qS({timezone:n,disabled:e,onChange:t}){const i=D.useId(),[a,u]=D.useState(!1),[f,h]=D.useState(""),m=D.useMemo(()=>{const b=new Set(QS);return n&&b.add(n),[...b]},[n]),g=D.useMemo(()=>a?Gm():[],[a]);function v(b){const w=b.trim();KS(w)&&(t(w),u(!1),h(""))}if(a)return c.jsxs("label",{className:"flex items-center gap-1.5 text-2xs text-faint",children:[c.jsx("span",{className:"hidden sm:inline",children:"Zone"}),c.jsx("input",{type:"text",list:i,autoFocus:!0,"aria-label":"Search timezone",placeholder:"Region/City…",value:f,disabled:e,onChange:b=>{h(b.target.value),Gm().includes(b.target.value)&&v(b.target.value)},onKeyDown:b=>{b.key==="Enter"?v(f):b.key==="Escape"&&(u(!1),h(""))},onBlur:()=>{u(!1),h("")},className:"h-7 w-36 rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50"}),c.jsx("datalist",{id:i,children:g.map(b=>c.jsx("option",{value:b},b))})]});const x=JS(n);return c.jsxs("label",{className:"flex items-center gap-1.5 text-2xs text-faint",children:[c.jsx("span",{className:"hidden sm:inline",children:"Zone"}),c.jsxs("select",{"aria-label":"Timezone",value:n,disabled:e,onChange:b=>{b.target.value===Ym?u(!0):t(b.target.value)},className:"h-7 max-w-[11rem] rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50",children:[m.map(b=>c.jsxs("option",{value:b,children:[b,b==="UTC"?"":x&&b===n?` (${x})`:""]},b)),c.jsx("option",{value:Ym,children:"Search…"})]})]})}function ZS(n,e,t){if(t==="count")return n.length;const i=n.map(u=>typeof u[e]=="number"?u[e]:Number(u[e])).filter(Number.isFinite);if(i.length===0)return Number.NaN;if(t==="min")return Math.min(...i);if(t==="max")return Math.max(...i);const a=i.reduce((u,f)=>u+f,0);return t==="avg"?a/i.length:a}const XS={sum:"Σ",avg:"avg",min:"min",max:"max",count:"n"};function Ho({columns:n,rows:e,loading:t,sortKey:i,sortDir:a,onSort:u,renderCell:f,pageSize:h=50,searchable:m,totals:g,stickyHeader:v=!0}){const[x,b]=D.useState(0),[w,j]=D.useState(""),C=D.useMemo(()=>{const I=w.trim().toLowerCase();return!m||!I?e:e.filter(U=>n.some(G=>String(U[G.key]??"").toLowerCase().includes(I)))},[e,n,w,m]),{paginate:O,pageCount:H,safePage:L,start:R,visibleRows:T}=fb(C,x,h);D.useEffect(()=>{b(0)},[e,h,i,a,w]);const E=g&&n.some(I=>g[I.key]);return c.jsxs("div",{children:[m?c.jsxs("div",{className:"mb-2 flex items-center justify-end gap-2",children:[w?c.jsxs("span",{className:"whitespace-nowrap text-2xs text-faint tnum",children:[C.length.toLocaleString()," of ",e.length.toLocaleString()]}):null,c.jsx("input",{type:"search","aria-label":"Search rows",placeholder:"Search…",value:w,onChange:I=>j(I.target.value),className:"h-7 w-full max-w-64 rounded-full border border-line bg-surface px-2.5 text-xs text-ink placeholder:text-faint"})]}):null,c.jsx("div",{className:"overflow-auto border border-line bg-surface",children:c.jsxs("table",{className:"w-max min-w-full border-collapse text-xs","data-testid":"pivot-table",children:[c.jsx("thead",{children:c.jsx("tr",{className:"bg-surface-soft",children:n.map(I=>{const U=i===I.key;return c.jsx("th",{className:`max-w-80 whitespace-nowrap border-b border-line bg-surface-soft px-3 py-1.5 font-semibold text-faint ${I.numeric?"min-w-32 text-right":"min-w-40 text-left"} ${v?"sticky top-0 z-10":""}`,children:I.sortable&&u?c.jsxs("button",{type:"button",onClick:()=>u(I.key),"aria-label":`Sort by ${I.label}${U?`, currently ${a==="asc"?"ascending":"descending"}`:""}`,className:`table-sort inline-flex max-w-full items-center gap-1 whitespace-nowrap hover:text-ink ${U?"text-ink":""}`,children:[c.jsx("span",{className:"truncate",children:I.label}),c.jsx("span",{"aria-hidden":"true",className:"text-[9px]",children:U?a==="asc"?"▲":"▼":"↕"})]}):c.jsx("span",{className:"block truncate",title:I.label,children:I.label})},I.key)})})}),c.jsx("tbody",{children:t&&C.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:n.length,className:"px-3 py-6 text-center text-faint",children:"Loading…"})}):C.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:n.length,className:"px-3 py-6 text-center text-faint",children:w?"No matching rows":"No rows"})}):T.map((I,U)=>c.jsx("tr",{className:"hover:bg-surface-soft",children:n.map(G=>{const V=f(G,I[G.key]);return c.jsx("td",{className:`max-w-80 whitespace-nowrap border-b border-line px-3 py-1.5 text-muted ${G.numeric?"min-w-32 text-right font-mono tnum text-ink":"min-w-40"}`,children:c.jsx("span",{className:"block max-w-80 truncate",title:V,children:V})},G.key)})},R+U))}),E&&C.length>0?c.jsx("tfoot",{children:c.jsx("tr",{className:"bg-surface-soft","data-testid":"table-totals",children:n.map(I=>{const U=g==null?void 0:g[I.key];if(!U)return c.jsx("td",{className:"border-t border-line px-3 py-1.5"},I.key);const G=ZS(C,I.key,U),V=U==="count"?G.toLocaleString():Number.isFinite(G)?f(I,G):"—";return c.jsxs("td",{"data-total":U,className:`whitespace-nowrap border-t border-line px-3 py-1.5 font-mono tnum font-medium text-ink ${I.numeric?"text-right":"text-left"}`,children:[c.jsx("span",{"aria-hidden":"true",className:"mr-1 text-2xs text-faint",children:XS[U]}),V]},I.key)})})}):null]})}),O?c.jsxs("div",{"data-testid":"pivot-table-pager",className:"mt-1.5 flex items-center justify-between gap-3 text-2xs text-faint",children:[c.jsxs("span",{className:"tnum",children:[R+1,"–",Math.min(R+h,C.length)," of ",C.length.toLocaleString(),t?" · Updating…":""]}),c.jsxs("div",{className:"flex gap-1",children:[c.jsx("button",{type:"button",disabled:L===0,onClick:()=>b(I=>Math.max(0,I-1)),className:"table-pager-button px-2 py-1 text-muted hover:text-ink disabled:cursor-not-allowed disabled:opacity-40",children:"Prev"}),c.jsx("button",{type:"button",disabled:L>=H-1,onClick:()=>b(I=>Math.min(H-1,I+1)),className:"table-pager-button px-2 py-1 text-muted hover:text-ink disabled:cursor-not-allowed disabled:opacity-40",children:"Next"})]})]}):null]})}function e_(n,e){const t=e.filter(i=>n.some(a=>a.ref===i));return t.length?t:n.slice(0,6).map(i=>i.ref)}function t_(){var L,R;const[n,e]=D.useState(!1),{state:t,catalog:i,backend:a,dashboard:u}=ls(),f=i.models.find(T=>T.name===t.model),h=D.useMemo(()=>Cs(i,u,t.dashboardTab),[i,u,t.dashboardTab]),m=(h==null?void 0:h.dimensions)??(f==null?void 0:f.dimensions)??[],g=e_(m,t.pivotDims),v=((L=h==null?void 0:h.timeDimension)==null?void 0:L.ref)??((R=f==null?void 0:f.timeDimension)==null?void 0:R.ref),x=D.useMemo(()=>ou(i),[i]),b=D.useMemo(()=>[...(h==null?void 0:h.filters)??[],...Os(t.filters,{timeRef:v,range:t.dateRange,types:x})],[h,t.filters,v,t.dateRange,x]),w=n&&f?vS({dimensions:g,metrics:[]},b,50,h==null?void 0:h.segments,h==null?void 0:h.usePreaggregations):null,{result:j,loading:C,error:O}=Zn(a,w),H=[...g.map(T=>{var E;return{key:Sr(T),label:((E=m.find(I=>I.ref===T))==null?void 0:E.label)??Le(T)}})];return c.jsxs("section",{"data-testid":"row-preview-drawer","data-open":n||void 0,className:"absolute inset-x-0 bottom-0 z-30 border-t border-line bg-surface shadow-[0_-8px_24px_rgba(0,0,0,0.16)]",children:[c.jsxs("button",{type:"button","aria-expanded":n,onClick:()=>e(T=>!T),className:"flex h-8 w-full items-center justify-between px-3 text-left text-xs font-medium text-muted hover:bg-surface-soft hover:text-ink",children:[c.jsx("span",{children:"Rows preview"}),c.jsx("span",{"aria-hidden":"true",children:n?"▼":"▲"})]}),n?c.jsx("div",{className:"max-h-[45vh] overflow-auto border-t border-line",children:O?c.jsx("p",{role:"alert",className:"p-3 text-xs text-danger",children:O}):H.length===0?c.jsx("p",{className:"p-3 text-xs text-faint",children:"No preview fields are available."}):c.jsx(Ho,{columns:H,rows:(j==null?void 0:j.rows)??[],loading:C,pageSize:10,renderCell:(T,E)=>E==null||E===""?"—":String(E)})}):null]})}function of({tone:n,title:e,message:t}){const i=n==="danger";return c.jsx("div",{className:`grid min-h-[200px] place-items-center border bg-surface p-6 text-center ${i?"border-danger/40":"border-line"}`,"data-state":n,role:i?"alert":"status","aria-live":i?"assertive":"polite",children:c.jsxs("div",{className:"max-w-md",children:[n==="loading"?c.jsx("span",{"aria-hidden":"true",className:"motion-safe:animate-pulse inline-block size-2 rounded-full bg-accent"}):null,e?c.jsx("h3",{className:`text-sm font-semibold ${i?"text-danger":"text-ink"}`,children:e}):null,c.jsx("p",{className:`mt-1 text-xs ${i?"text-danger":"text-muted"}`,children:t})]})})}function af({title:n="Loading",message:e="Loading metrics…"}){return c.jsx(of,{tone:"loading",title:n,message:e})}function Xn({title:n="No results",message:e}){return c.jsx(of,{tone:"muted",title:n,message:e})}function Bi({title:n="Query failed",message:e}){return c.jsx(of,{tone:"danger",title:n,message:e})}function dd({status:n}){const e=n==="ok"?"bg-success":n==="loading"?"bg-faint animate-pulse":"bg-line";return c.jsx("span",{"aria-hidden":"true",className:`inline-block size-2 rounded-full ${e}`})}const Tv="sidemantic-theme";function lf(){var e;const n=localStorage.getItem(Tv);return n==="light"||n==="dark"?n:(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}function Av(n){document.documentElement.dataset.theme=n}function n_(){Av(lf())}function r_(){const n=lf()==="dark"?"light":"dark";return localStorage.setItem(Tv,n),Av(n),n}function $o(){const[n,e]=D.useState(lf());return c.jsx("button",{type:"button","aria-label":n==="dark"?"Switch to light theme":"Switch to dark theme",title:n==="dark"?"Light theme":"Dark theme",onClick:()=>e(r_()),className:"grid size-7 place-items-center border border-line bg-surface text-faint hover:border-faint hover:text-ink",children:n==="dark"?c.jsxs("svg",{viewBox:"0 0 24 24",className:"size-3.5",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[c.jsx("circle",{cx:"12",cy:"12",r:"4"}),c.jsx("path",{d:"M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"})]}):c.jsx("svg",{viewBox:"0 0 24 24",className:"size-3.5",fill:"none",stroke:"currentColor",strokeWidth:"2",children:c.jsx("path",{d:"M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"})})})}const _o=[{key:"explore",label:"Explore"},{key:"pivot",label:"Pivot"}];function Bv({view:n,onChange:e}){const t=D.useRef(null);function i(a){const u=Math.max(0,_o.findIndex(h=>h.key===n)),f=_o[(u+a+_o.length)%_o.length];e(f.key),window.requestAnimationFrame(()=>{var h,m;return(m=(h=t.current)==null?void 0:h.querySelector(`[data-view="${f.key}"]`))==null?void 0:m.focus()})}return c.jsx("div",{ref:t,role:"tablist","aria-label":"View",className:"inline-flex items-center gap-0.5 rounded-full border border-line bg-surface p-px",children:_o.map(a=>c.jsx("button",{role:"tab",type:"button","aria-selected":n===a.key,tabIndex:n===a.key?0:-1,"data-view":a.key,"data-selected":n===a.key||void 0,onClick:()=>e(a.key),onKeyDown:u=>{u.key==="ArrowLeft"?(u.preventDefault(),i(-1)):u.key==="ArrowRight"&&(u.preventDefault(),i(1))},className:"inline-flex h-6 items-center rounded-full px-2.5 text-xs font-medium text-muted hover:bg-surface-soft hover:text-ink data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent",children:a.label},a.key))})}const Ev="dashboard_filters",Rv="dashboard_ranges",Lv="dashboard_filter_sources",Uv="dashboard_range_sources",$v="dashboard_chart_filters",Pv="dashboard_chart_ranges";function s_(n,e){if(n==="/explore")return!0;const t=new URLSearchParams(e).get("view");return t==="explore"||t==="pivot"}function uf(n,e){var i,a;if(!e||!(n.query.dimensions??[]).includes(e))return!1;const t=(i=n.interactions)==null?void 0:i.select;return t===!0?!0:t?!((a=t.fields)!=null&&a.length)||t.fields.includes(e):!1}function i_(n){return(n.query.dimensions??[]).find(e=>uf(n,e))}function o_(n,e){var i,a;if(!e||!(n.query.dimensions??[]).includes(e))return!1;const t=(i=n.interactions)==null?void 0:i.brush;return t===!0?!0:!t||t.channel&&t.channel!=="x"?!1:!((a=t.fields)!=null&&a.length)||t.fields.includes(e)}function Xl(n){return n==null?er:String(n)}function a_(n){let e=n.trim().replaceAll(/[^A-Za-z0-9_]/g,"_").replaceAll(/^_+|_+$/g,"")||"field";return/^\d/.test(e)&&(e=`field_${e}`),e}function xr(n,e){const t=Sr(n),i=a_(n);return i!==t&&e.includes(i)?i:e.includes(t)?t:e.find(a=>a.endsWith(t))??t}function l_(n){var t;const e=(t=n.encoding)==null?void 0:t.y;return Array.isArray(e)&&e.length?e:typeof e=="string"?[e]:n.query.metrics.slice(0,1)}function u_(n,e,t,i,a){return Object.fromEntries([[e,t],...i.map((u,f)=>[u,a[f]])].filter(u=>typeof u[1]=="string"&&uf(n,u[0])))}function c_(n,e,t){return[e,...t].some(i=>uf(n,i))}const d_=new Set(["second","minute","hour","day","week","month","quarter","year"]);function Ms(n){const e=n.lastIndexOf("__");if(e<0)return null;const t=n.slice(e+2);return d_.has(t)?{baseDimension:n.slice(0,e),grain:t}:null}function zv(n,e){var u,f;if(n.type&&n.type!=="auto")return n.type;const t=((u=n.encoding)==null?void 0:u.x)??((f=n.query.dimensions)==null?void 0:f[0])??"",i=Ms(t);return(e[t]??(i?e[i.baseDimension]:void 0))==="time"?"line":"bar"}function Vv(n,e){const t=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/.test(n)?`${n}Z`:n,i=new Date(t);return Number.isFinite(i.getTime())?(e==="second"?i.setUTCSeconds(i.getUTCSeconds()+1):e==="minute"?i.setUTCMinutes(i.getUTCMinutes()+1):e==="hour"?i.setUTCHours(i.getUTCHours()+1):e==="day"?i.setUTCDate(i.getUTCDate()+1):e==="week"?i.setUTCDate(i.getUTCDate()+7):e==="month"?i.setUTCMonth(i.getUTCMonth()+1):e==="quarter"?i.setUTCMonth(i.getUTCMonth()+3):e==="year"&&i.setUTCFullYear(i.getUTCFullYear()+1),/^\d{4}-\d{2}-\d{2}$/.test(n)?i.toISOString().slice(0,10):i.toISOString()):null}function Wv(n,e){const t=Ms(n);if(t){const i=Vv(e.to,t.grain);return i?`${t.baseDimension} >= ${Tn(e.from)} AND ${t.baseDimension} < ${Tn(i)}`:`${t.baseDimension} >= ${Tn(e.from)} AND ${t.baseDimension} <= ${Tn(e.to)}`}return`${n} >= ${Tn(e.from)} AND ${n} <= ${Tn(e.to)}`}function f_(n,e,t){const i=Ms(n);return i?e===er?[`${i.baseDimension} IS NULL`]:[Wv(n,{from:e,to:e})]:jv({[n]:{mode:"include",values:[e]}},{types:t})}function eu(n,e){const t=n.tabs.find(i=>i.charts.includes(e));return`${(t==null?void 0:t.id)??"dashboard"}:${e.id}`}function cf(n,e,t){var f,h,m,g,v;const i=((h=(f=n.defaults)==null?void 0:f.interactions)==null?void 0:h.scope)??"dashboard";if(i==="dashboard")return t;if(i==="chart"){const x=eu(n,e);return{filters:{...Object.fromEntries(Object.entries(t.filters).filter(([b])=>t.filterSources[b]===x)),...((m=t.chartFilters)==null?void 0:m[x])??{}},ranges:{...Object.fromEntries(Object.entries(t.ranges).filter(([b])=>t.rangeSources[b]===x)),...((g=t.chartRanges)==null?void 0:g[x])??{}}}}const a=((v=n.tabs.find(x=>x.charts.includes(e)))==null?void 0:v.charts)??[e],u=new Set(a.flatMap(x=>x.query.dimensions??[]));return{filters:Object.fromEntries(Object.entries(t.filters).filter(([x])=>u.has(x))),ranges:Object.fromEntries(Object.entries(t.ranges).filter(([x])=>u.has(x)))}}function h_(n,e,t,i,a={},u={filterSources:{},rangeSources:{}}){var b,w,j,C,O,H;const f=cf(n,e,{filters:t,ranges:a,...u}),h=((b=e.encoding)==null?void 0:b.x)??((w=e.query.dimensions)==null?void 0:w[0])??"",m=e.query.order_by??e.query.orderBy,g=h&&["line","area"].includes(zv(e,i))?[`${h} ASC`]:void 0,v={metrics:e.query.metrics,dimensions:e.query.dimensions,filters:[...e.query.filters??[],...Object.entries(f.filters).flatMap(([L,R])=>f_(L,R,i)),...Object.entries(f.ranges).map(([L,R])=>Wv(L,R))],segments:e.query.segments,orderBy:m??g,limit:e.query.limit??500},x=e.query.use_preaggregations??e.query.usePreaggregations??((C=(j=n.defaults)==null?void 0:j.query)==null?void 0:C.use_preaggregations)??((H=(O=n.defaults)==null?void 0:O.query)==null?void 0:H.usePreaggregations);return x!==void 0&&(v.usePreaggregations=x),v}function Qm(n){const e=/^(\d{4}-\d{2}-\d{2})/.exec(n);return(e==null?void 0:e[1])??null}function Km(n,e){const t=Qm(e.from);if(!t)return null;const i=Ms(n);if(!i){const f=Qm(e.to);return f?{from:t,to:f}:null}const a=Vv(e.to,i.grain);if(!a)return null;const u=new Date(a);return u.setUTCMilliseconds(u.getUTCMilliseconds()-1),{from:t,to:u.toISOString().slice(0,10)}}function p_(n,e,t,i={},a){var T,E,I;const u=(T=e.encoding)==null?void 0:T.y,f=(Array.isArray(u)?u[0]:u)??e.query.metrics[0]??"",h=e.query.dimensions??[],m=a==null?void 0:a.graphMetrics.find(U=>U.ref===f),g=f.includes(".")?f.split(".")[0]:((E=h[0])==null?void 0:E.split(".")[0])??(m==null?void 0:m.ownerModel)??(m==null?void 0:m.model)??"",v=cf(n,e,t),x=Object.entries(v.filters).flatMap(([U,G])=>{const V=Ms(U);return V?[{dimension:U,value:G,baseDimension:V.baseDimension}]:[]}),b=Object.fromEntries(Object.entries(v.filters).flatMap(([U,G])=>{const V=Ms(U);return V?G===er?[[V.baseDimension,[G]]]:[]:[[U,[G]]]})),w=new URLSearchParams({view:"explore",model:g,metric:f});Object.keys(b).length&&w.set("filters",JSON.stringify(b));const j=((I=e.encoding)==null?void 0:I.x)??h[0],C=x.find(({baseDimension:U,value:G})=>G!==er&&(!g||U.startsWith(`${g}.`))),O=Object.keys(v.ranges),H=[j,...O].find((U,G,V)=>{if(!U||V.indexOf(U)!==G||!v.ranges[U])return!1;const Q=Ms(U);return((i[U]??(Q?i[Q.baseDimension]:void 0))==="time"||!!Q)&&(!g||U.startsWith(`${g}.`))}),L=H?v.ranges[H]:void 0,R=C?Km(C.dimension,{from:C.value,to:C.value}):H&&L?Km(H,L):null;return R&&(w.set("from",R.from),w.set("to",R.to)),`/explore?${w}`}function m_(n,e,t,i){const a=new Map;for(const u of n){const f=Number(u[t]);if(!Number.isFinite(f))continue;const h=i.map(b=>Xl(u[b])),m=JSON.stringify(h),g=h.length?h.map(rs).join(" · "):"Current",v=a.get(m)??{label:g,filterValues:h,data:[]},x=Xl(u[e]);v.data.push({label:rs(x),filterValue:x,value:f}),a.set(m,v)}return[...a.values()]}function y_(n,e,t,i){const a=[],u=new Set,f=new Map;for(const h of n){if(h[e]==null)continue;const m=String(h[e]),g=Number(h[t]);if(!Number.isFinite(g))continue;u.has(m)||(u.add(m),a.push(m));const v=i.map(j=>Xl(h[j])),x=JSON.stringify(v),b=v.length?v.map(rs).join(" · "):"Current",w=f.get(x)??{label:b,values:new Map};w.values.set(m,g),f.set(x,w)}return[...f.values()].map(h=>({label:h.label,points:a.map(m=>({x:m,y:h.values.get(m)??Number.NaN}))}))}function df(n,e){if(typeof n!="object"||n===null||Array.isArray(n))return{};const t={};for(const[i,a]of Object.entries(n))e.has(i)&&typeof a=="string"&&(t[i]=a);return t}function ff(n,e){if(typeof n!="object"||n===null||Array.isArray(n))return{};const t={};for(const[i,a]of Object.entries(n)){if(!e.has(i)||typeof a!="object"||a===null||Array.isArray(a))continue;const u=a;typeof u.from=="string"&&typeof u.to=="string"&&(t[i]={from:u.from,to:u.to})}return t}function tu(n,e){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).filter(t=>e.has(t[0])&&typeof t[1]=="string"))}function Hv(n,e){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).flatMap(([t,i])=>{const a=e.get(t);if(!a)return[];const u=df(i,a);return Object.keys(u).length?[[t,u]]:[]}))}function Gv(n,e){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).flatMap(([t,i])=>{const a=e.get(t);if(!a)return[];const u=ff(i,a);return Object.keys(u).length?[[t,u]]:[]}))}function Yv(n){return new Set(n.tabs.flatMap(e=>e.charts.flatMap(t=>t.query.dimensions??[])))}function Qv(n){return new Map(n.tabs.flatMap(e=>e.charts.map(t=>[eu(n,t),new Set(t.query.dimensions??[])])))}function g_(n,e){var j;const t=new URLSearchParams(n),i=((j=e.tabs[0])==null?void 0:j.id)??"",a=t.get("tab"),u=e.tabs.some(C=>C.id===a)?a??i:i;let f,h,m,g,v,x;try{f=JSON.parse(t.get(Ev)??"{}")}catch{f={}}try{h=JSON.parse(t.get(Rv)??"{}")}catch{h={}}try{m=JSON.parse(t.get(Lv)??"{}")}catch{m={}}try{g=JSON.parse(t.get(Uv)??"{}")}catch{g={}}try{v=JSON.parse(t.get($v)??"{}")}catch{v={}}try{x=JSON.parse(t.get(Pv)??"{}")}catch{x={}}const b=Yv(e),w=Qv(e);return{tab:u,filters:df(f,b),ranges:ff(h,b),filterSources:tu(m,b),rangeSources:tu(g,b),chartFilters:Hv(v,w),chartRanges:Gv(x,w)}}function v_(n,e){var u;const t=new URLSearchParams;n.tab&&n.tab!==((u=e.tabs[0])==null?void 0:u.id)&&t.set("tab",n.tab),Object.keys(n.filters).length&&t.set(Ev,JSON.stringify(n.filters)),Object.keys(n.ranges).length&&t.set(Rv,JSON.stringify(n.ranges));const i=Object.fromEntries(Object.entries(n.filterSources).filter(([f])=>f in n.filters)),a=Object.fromEntries(Object.entries(n.rangeSources).filter(([f])=>f in n.ranges));return Object.keys(i).length&&t.set(Lv,JSON.stringify(i)),Object.keys(a).length&&t.set(Uv,JSON.stringify(a)),Object.keys(n.chartFilters??{}).length&&t.set($v,JSON.stringify(n.chartFilters)),Object.keys(n.chartRanges??{}).length&&t.set(Pv,JSON.stringify(n.chartRanges)),t.toString()}function Kv(n){return`sidemantic-dashboard-views:${`${n.schema??"sidemantic.dashboard.v1"}:${n.title}`}`}function x_(n){try{const e=JSON.parse(localStorage.getItem(Kv(n))??"[]");if(!Array.isArray(e))return[];const t=Yv(n);return e.flatMap(i=>{var m;if(typeof i!="object"||i===null||Array.isArray(i))return[];const a=i;if(typeof a.name!="string"||!a.name.trim())return[];if(typeof a.state!="object"||a.state===null||Array.isArray(a.state))return[];const u=a.state,f=n.tabs.some(g=>g.id===u.tab)?String(u.tab):((m=n.tabs[0])==null?void 0:m.id)??"",h=Qv(n);return[{name:a.name,state:{tab:f,filters:df(u.filters,t),ranges:ff(u.ranges,t),filterSources:tu(u.filterSources,t),rangeSources:tu(u.rangeSources,t),chartFilters:Hv(u.chartFilters,h),chartRanges:Gv(u.chartRanges,h)}}]})}catch{return[]}}function b_(n,e){try{return localStorage.setItem(Kv(n),JSON.stringify(e)),!0}catch{return!1}}function Jm(n){if(n==null)return"";const e=String(n);return/[",\r\n]/.test(e)?`"${e.replaceAll('"','""')}"`:e}function w_(n,e){return[n.map(Jm).join(","),...e.map(t=>n.map(i=>Jm(t[i])).join(","))].join(`\r -`)}function S_(n){var e;return((e=n.label)==null?void 0:e.trim())||n.id}function fd(n,e){return`${n} ${e}${n===1?"":"s"}`}function __(){const{catalog:n,dispatch:e}=ls(),t=i=>{const a=n.models.find(h=>h.name===i),u=kv(a,n),f=(a==null?void 0:a.defaultGrain)??"month";e({type:"setModel",model:i,metric:u,grain:f}),e({type:"setView",view:"explore"})};return c.jsxs("div",{className:"mx-auto w-full max-w-5xl p-6",children:[c.jsxs("div",{className:"mb-4",children:[c.jsx("h1",{className:"text-base font-semibold text-ink",children:"Explore"}),c.jsxs("p",{className:"text-2xs text-muted",children:[fd(n.models.length,"model")," · pick one to explore"]})]}),c.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3",children:n.models.map(i=>c.jsxs("button",{type:"button","data-testid":"explore-card","data-model":i.name,onClick:()=>t(i.name),className:"flex min-h-32 flex-col gap-2 rounded-xl border border-line bg-surface p-4 text-left shadow-[var(--shadow-sm)] transition-colors hover:border-line-strong",children:[c.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[c.jsx("span",{className:"truncate text-sm font-medium text-ink",children:i.label}),i.timeDimension?c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:"time series"}):null]}),i.description?c.jsx("p",{className:"line-clamp-2 text-2xs text-muted",children:i.description}):null,c.jsx("div",{className:"mt-auto flex flex-wrap gap-1 pt-1",children:i.metrics.slice(0,3).map(a=>c.jsx("span",{className:"rounded-full bg-surface-soft px-2 py-0.5 text-2xs text-muted",children:a.label},a.ref))}),c.jsxs("div",{className:"text-2xs text-faint",children:[fd(i.metrics.length,"metric")," · ",fd(i.dimensions.length,"dimension")]})]},i.name))})]})}const N_="600px";function j_(n){for(let e=n.parentElement;e;e=e.parentElement){const t=getComputedStyle(e).overflowY;if(t==="auto"||t==="scroll")return e}return null}function k_(n,e,t=N_){if(typeof IntersectionObserver>"u")return e(),()=>{};const i=new IntersectionObserver(a=>{a.some(u=>u.isIntersecting)&&(i.disconnect(),e())},{root:j_(n),rootMargin:t});return i.observe(n),()=>i.disconnect()}const I_={positive:"text-success",negative:"text-danger",neutral:"text-faint"};function Jv({dimension:n,title:e,metricLabel:t,rows:i,selectedValues:a=[],loading:u,formatMetric:f,onToggle:h,contextColumn:m="none",contextOptions:g,onContextColumn:v,collapsedLimit:x=6,expanded:b=!1,onExpandedChange:w,containerRef:j}){const C=new Set(a),O=b?i:i.slice(0,x),H=Math.max(1,...O.map(E=>Math.abs(E.metric))),L=b||i.length>x,R=m!=="none",T=R?"grid-cols-[minmax(0,1fr)_auto_auto]":"grid-cols-[minmax(0,1fr)_auto]";return c.jsxs("section",{ref:j,"data-testid":"dimension-leaderboard","data-dimension":n,"data-expanded":b||void 0,"aria-label":`${e}, ranked by ${t}`,className:"flex min-h-40 flex-col border-b border-r border-line bg-surface data-[expanded=true]:col-span-full",children:[c.jsxs("header",{className:"flex items-center justify-between gap-3 px-3 pb-2 pt-2.5",children:[c.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[c.jsx("h3",{className:"truncate text-sm font-semibold text-ink",children:e}),c.jsxs("p",{className:"sr-only",children:["Ranked by ",t]})]}),g&&v?c.jsx("div",{role:"group","aria-label":"Context column","data-testid":"leaderboard-context-toggle",className:"flex shrink-0 overflow-hidden border border-line text-2xs",children:g.map(E=>c.jsx("button",{type:"button",title:E.title,"aria-pressed":m===E.key,"data-context":E.key,"data-active":m===E.key||void 0,onClick:()=>v(E.key),className:"border-l border-line px-1.5 py-0.5 font-mono text-faint first:border-l-0 hover:bg-surface-soft data-[active=true]:bg-accent-soft data-[active=true]:text-accent",children:E.label},E.key))}):null]}),c.jsx("div",{"data-testid":"leaderboard-rows",children:u&&i.length===0?c.jsx("div",{className:"space-y-2 p-3",children:[0,1,2,3].map(E=>c.jsx("div",{className:"skeleton h-5 w-full"},E))}):i.length===0?c.jsx("p",{className:"px-3 py-4 text-xs text-faint",children:"No values"}):O.map(E=>{var V,Q,z;const I=E.metric<0?"negative":"positive",U=C.has(E.value),G=`${Math.round(Math.abs(E.metric)/H*100)}%`;return c.jsxs("button",{type:"button","data-dimension":n,"data-value":E.value,"data-selected":U||void 0,"data-tone":I,onClick:()=>h==null?void 0:h(E.value),"aria-pressed":U,className:`leaderboard-row relative grid w-full ${T} items-center gap-3 overflow-hidden border-0 bg-transparent px-3 py-1 text-left text-xs text-ink data-[selected=true]:bg-chart-primary-selected`,children:[c.jsx("span",{"aria-hidden":"true",className:`absolute inset-y-0 left-0 ${I==="negative"?"bg-danger-soft":"bg-chart-primary-soft"}`,style:{width:G}}),c.jsx("span",{className:"relative min-w-0 truncate text-muted",children:rs(E.value)}),c.jsx("strong",{className:"relative tnum font-semibold text-ink",children:f(E.metric)}),R?c.jsx("span",{"data-testid":"leaderboard-context","data-tone":((V=E.context)==null?void 0:V.tone)??"neutral",className:`relative w-14 text-right font-mono tnum text-2xs ${I_[((Q=E.context)==null?void 0:Q.tone)??"neutral"]}`,children:((z=E.context)==null?void 0:z.label)??"—"}):null]},`${n}:${E.value}`)})}),L&&!u?c.jsx("button",{type:"button","data-action":b?"leaderboard-back":"leaderboard-expand","aria-expanded":b,onClick:()=>w==null?void 0:w(!b),className:"leaderboard-expand border-0 border-t border-line bg-transparent px-3 py-1 text-left text-xs font-normal text-faint hover:text-accent",children:b?"← All dimensions":`Expand table (${i.length})`}):null]})}const M_=[{key:"none",label:"—",title:"No context column"},{key:"pctTotal",label:"%",title:"Share of total"},{key:"delta",label:"Δ",title:"Absolute change vs comparison period"},{key:"deltaPct",label:"Δ%",title:"Percent change vs comparison period"}],D_=[],C_=[];function F_({dim:n,model:e,timeDimensionRef:t,rankMetric:i,contextColumn:a,metricTotal:u,comparisonRange:f,baseFilters:h=D_,baseSegments:m=C_,usePreaggregations:g,limit:v=6,expanded:x=!1,onExpandedChange:b}){var pe;const{state:w,dispatch:j,backend:C,catalog:O}=ls(),H=D.useRef(null),[L,R]=D.useState(!1);D.useEffect(()=>{if(!(L||!H.current))return k_(H.current,()=>R(!0))},[L]);const T=t??((pe=e.timeDimension)==null?void 0:pe.ref),E=D.useMemo(()=>ou(O),[O]),I=D.useMemo(()=>[...h,...Os(w.filters,{timeRef:T,range:w.dateRange,excludeDim:n.ref,types:E})],[h,w.filters,T,w.dateRange,n.ref,E]),{result:U,loading:G,error:V}=Zn(C,L?zm(i.ref,n.ref,I,v,m,g):null),Q=w.filters[n.ref],z=(Q==null?void 0:Q.mode)==="include"?Q.values:void 0,ee=[i.ref,n.ref],X=Fn(n.ref,ee),ie=a==="delta"||a==="deltaPct",ae=D.useMemo(()=>{if(!U||!U.columns.includes(X))return null;const ne=[];let fe=!1;for(const Te of U.rows){const Ue=Te[X];Ue==null?fe=!0:ne.push(String(Ue))}const Ce=[];return ne.length&&Ce.push(`CAST(${n.ref} AS VARCHAR) IN (${ne.map(Tn).join(", ")})`),fe&&Ce.push(`${n.ref} IS NULL`),Ce.length?Ce.length===1?Ce[0]:`(${Ce.join(" OR ")})`:null},[U,X,n.ref]),re=D.useMemo(()=>ie&&f&&T&&ae?[...h,...Os(w.filters,{timeRef:T,range:f,excludeDim:n.ref,types:E}),ae]:null,[ie,f,T,w.filters,n.ref,E,ae,h]),se=Zn(C,re?zm(i.ref,n.ref,re,v,m,g):null),A=Fn(i.ref,ee),Y=!!U&&U.rows.length>0&&!U.columns.includes(A),W=D.useMemo(()=>{const ne=new Map;if(!se.result||!se.result.columns.includes(A))return ne;for(const fe of se.result.rows){const Ce=fe[X],Te=Ce==null?er:String(Ce);ne.set(Te,Number(fe[A]))}return ne},[se.result,X,A]),_={format:i.format,type:i.type};function F(ne,fe){switch(a){case"pctTotal":return u===void 0?void 0:hb(fe,u);case"delta":return pb(fe,W.get(ne),_);case"deltaPct":return mb(fe,W.get(ne));default:return}}const te=U&&!Y?U.rows.map(ne=>{const fe=ne[X],Ce=fe==null?er:String(fe),Te=Number(ne[A]??0);return{value:Ce,metric:Te,context:F(Ce,Te)}}):[];return V?c.jsx(Bi,{title:n.label,message:V}):c.jsx(Jv,{dimension:n.ref,title:n.label,metricLabel:i.label,rows:te,containerRef:H,loading:!L||G||Y,selectedValues:z,formatMetric:ne=>Wt(ne,_),onToggle:ne=>j({type:"toggleFilter",dim:n.ref,value:ne}),contextColumn:a,contextOptions:M_,onContextColumn:ne=>j({type:"setContextColumn",column:ne}),collapsedLimit:v,expanded:x,onExpandedChange:b})}function Dr(){const[n,e]=D.useState(null);return{tip:n,handlers:i=>({onMouseEnter:a=>e({content:i,x:a.clientX,y:a.clientY}),onMouseMove:a=>e({content:i,x:a.clientX,y:a.clientY}),onMouseLeave:()=>e(null)})}}function rr({tip:n,position:e="fixed",offset:t=12,className:i,style:a}){return n?c.jsx("div",{role:"tooltip",style:{position:e,left:n.x+t,top:n.y+t,pointerEvents:"none",zIndex:50,...a},className:i||"rounded-lg border border-line bg-surface px-2.5 py-1.5 text-xs text-ink shadow-[var(--shadow)]",children:n.content}):null}function os({title:n,rows:e}){return c.jsxs("div",{className:"min-w-28",children:[n?c.jsx("div",{className:"mb-0.5 font-mono text-faint",children:n}):null,e.map((t,i)=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs("span",{className:"flex items-center gap-1 text-muted",children:[t.swatch?c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-sm",style:{background:t.swatch}}):null,t.label]}),c.jsx("span",{className:"font-mono tnum font-medium text-ink",children:t.value})]},i))]})}function qv({values:n,labels:e,height:t=44,ariaLabel:i,formatValue:a=h=>h.toLocaleString(void 0,{maximumFractionDigits:2}),onHover:u,onBrush:f}){const h=D.useRef(null),m=D.useId(),g=D.useRef(null),v=D.useRef(null),[x,b]=D.useState(200),[w,j]=D.useState(null),[C,O]=D.useState(null),[H,L]=D.useState(null);D.useEffect(()=>{const W=h.current;if(!W||typeof ResizeObserver>"u")return;const _=new ResizeObserver(F=>{for(const te of F)b(Math.max(40,te.contentRect.width))});return _.observe(W),()=>_.disconnect()},[]);const R=n.map((W,_)=>({index:_,value:W})).filter(W=>Number.isFinite(W.value));if(R.length<2)return c.jsx("svg",{ref:g,role:"img","aria-label":i||"No trend data",className:"h-11 w-full",viewBox:`0 0 ${x} ${t}`});const T=3,E=Math.min(...R.map(W=>W.value)),U=Math.max(...R.map(W=>W.value))-E||1,G=R.map((W,_)=>({...W,x:T+_/(R.length-1)*(x-T*2),y:T+(1-(W.value-E)/U)*(t-T*2)})),V=G.map(({x:W,y:_})=>`${W.toFixed(1)},${_.toFixed(1)}`).join(" L "),Q=`M ${G[0].x.toFixed(1)},${t-T} L ${V} L ${G.at(-1).x.toFixed(1)},${t-T} Z`,z=G.at(-1),ee=i||`Trend of ${R.length} points, latest ${a(z.value)}`;function X(W){var F;const _=(F=g.current)==null?void 0:F.getBoundingClientRect();return _?Math.max(T,Math.min(x-T,(W.clientX-_.left)/_.width*x)):T}function ie(W){return Math.max(0,Math.min(G.length-1,Math.round((W-T)/(x-T*2)*(G.length-1))))}function ae(W){const _=X(W),F=ie(_),te=G[F];j(F),L({content:`${e!=null&&e[te.index]?`${e[te.index]}: `:""}${a(te.value)}`,x:W.clientX,y:W.clientY}),u==null||u({index:te.index,label:e==null?void 0:e[te.index],value:te.value}),v.current!==null&&O({a:v.current,b:_})}function re(W){if(!f||!(e!=null&&e.length))return;W.currentTarget.setPointerCapture(W.pointerId);const _=X(W);v.current=_,O({a:_,b:_})}function se(W){if(v.current===null||!f||!(e!=null&&e.length))return;W.currentTarget.hasPointerCapture(W.pointerId)&&W.currentTarget.releasePointerCapture(W.pointerId);const _=X(W);if(Math.abs(_-v.current)>6){const F=G[ie(Math.min(v.current,_))],te=G[ie(Math.max(v.current,_))];f({from:e[F.index],to:e[te.index]})}v.current=null,O(null)}function A(){j(null),L(null),u==null||u(null),v.current===null&&O(null)}const Y=w===null?null:G[w];return c.jsxs("span",{ref:h,className:"relative block w-full",children:[c.jsxs("svg",{ref:g,role:"img","aria-label":ee,className:`h-11 w-full overflow-hidden text-chart-primary ${f?"touch-none select-none":""}`,viewBox:`0 0 ${x} ${t}`,preserveAspectRatio:"none",onPointerMove:ae,onPointerDown:re,onPointerUp:se,onPointerCancel:A,onPointerLeave:A,onDoubleClick:()=>f==null?void 0:f(null),children:[c.jsx("defs",{children:c.jsxs("linearGradient",{id:m,x1:"0",y1:"0",x2:"0",y2:"1",children:[c.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:.16}),c.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:0})]})}),c.jsx("path",{d:Q,fill:`url(#${m})`}),c.jsx("path",{d:`M ${V}`,fill:"none",stroke:"currentColor",strokeWidth:1.5,vectorEffect:"non-scaling-stroke"}),C?c.jsx("rect",{x:Math.min(C.a,C.b),y:0,width:Math.abs(C.b-C.a),height:t,fill:"currentColor",opacity:.12}):null,Y?c.jsxs(c.Fragment,{children:[c.jsx("line",{x1:Y.x,x2:Y.x,y1:0,y2:t,stroke:"currentColor",strokeWidth:1,opacity:.45}),c.jsx("circle",{cx:Y.x,cy:Y.y,r:2.5,fill:"currentColor"})]}):c.jsx("circle",{cx:z.x,cy:z.y,r:2.25,fill:"currentColor"})]}),c.jsx(rr,{tip:H})]})}const O_={positive:"text-success",negative:"text-danger",neutral:"text-faint"},T_={positive:"▲",negative:"▼",neutral:"·"};function Nr({metric:n,label:e,value:t,valueText:i,format:a,delta:u,comparison:f,sparkValues:h=[],sparkLabels:m,selected:g,loading:v,onSelect:x,onSparkHover:b,onSparkBrush:w}){const[j,C]=D.useState(null),O=c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[c.jsx("span",{className:"truncate text-xs font-medium text-muted",children:e}),j!=null&&j.label?c.jsx("span",{className:"shrink-0 font-mono text-2xs text-faint",children:j.label}):null]}),c.jsx("div",{className:"font-mono tnum text-[19px] font-semibold leading-tight tracking-tight text-ink",children:v?c.jsx("span",{className:"skeleton inline-block h-6 w-24 align-middle"}):j?pt(j.value,a):i??pt(t,a)}),u||f?c.jsxs("div",{className:"flex items-baseline gap-1 text-2xs",children:[u?c.jsxs("span",{"data-tone":u.tone,className:`font-mono tnum font-medium ${O_[u.tone]}`,children:[c.jsx("span",{"aria-hidden":"true",className:"mr-0.5 text-[8px]",children:T_[u.tone]}),u.label]}):null,f?c.jsx("span",{className:"truncate text-faint",children:f}):null]}):null]}),H="group flex w-full flex-col gap-1.5 overflow-hidden rounded-xl border border-line bg-surface px-3.5 pt-3 text-left shadow-[var(--shadow-sm)] transition-colors hover:border-line-strong data-[selected=true]:border-accent",L=c.jsx("div",{className:"-mx-3.5 mt-auto",children:c.jsx(qv,{values:h,labels:m,onHover:R=>{C(R),b==null||b(R)},onBrush:w,formatValue:R=>pt(R,a)})});return x?c.jsxs("article",{"data-metric":n,"data-selected":g||void 0,className:H,children:[c.jsx("button",{type:"button","data-metric":n,"aria-pressed":!!g,onClick:()=>x(n),className:"-m-1 flex flex-col gap-1 border-0 bg-transparent p-1 text-left transition hover:opacity-75",children:O}),L]}):c.jsxs("article",{"data-metric":n,"data-selected":g||void 0,className:H,children:[O,L]})}const cl=280,qt={top:14,right:18,bottom:26,left:60},qm=["var(--accent)","var(--danger)","#0f9f8f","#d98921","#a66dd4","#3b82c4"];function hd(n){return qm[n%qm.length]}function Zm(n,e,t){return Math.min(Math.max(n,e),t)}function Go({points:n,seriesLabel:e="Current",additionalSeries:t=[],comparison:i,formatValue:a,formatAxis:u=a,formatLabel:f=v=>v,comparisonLabel:h="Previous",ariaLabel:m,onBrush:g}){var Fr;const v=D.useRef(null),x=D.useRef(null),b=D.useRef(!1),w=D.useRef(null),[j,C]=D.useState(820),[O,H]=D.useState(null),[L,R]=D.useState(null);D.useEffect(()=>{const ue=v.current;if(!ue)return;const Oe=new ResizeObserver(rt=>{for(const Nt of rt)C(Math.max(320,Nt.contentRect.width))});return Oe.observe(ue),()=>Oe.disconnect()},[]);const T=n.length,E=[{label:e,points:n},...t],I=[...E.flatMap(ue=>ue.points),...i??[]].map(ue=>ue.y).filter(Number.isFinite),U=T<2||I.length===0,G=U?0:Math.min(0,...I),V=U?1:Math.max(...I),Q=V-G||1,z=j-qt.left-qt.right,ee=cl-qt.top-qt.bottom,X=ue=>qt.left+(T<=1?0:ue/(T-1)*z),ie=ue=>qt.top+(1-(ue-G)/Q)*ee,ae=ue=>Zm(Math.round((ue-qt.left)/z*(T-1)),0,T-1),re=ue=>{const Oe=[];let rt=[];return ue.forEach((Nt,Un)=>{Number.isFinite(Nt.y)?rt.push(`${X(Un).toFixed(1)},${ie(Nt.y).toFixed(1)}`):rt.length&&(Oe.push(rt.join(" L ")),rt=[])}),rt.length&&Oe.push(rt.join(" L ")),Oe.map(Nt=>`M ${Nt}`).join(" ")},se=U||n.some(ue=>!Number.isFinite(ue.y))?"":`M ${X(0).toFixed(1)},${ie(G).toFixed(1)} L ${n.map((ue,Oe)=>`${X(Oe).toFixed(1)},${ie(ue.y).toFixed(1)}`).join(" L ")} L ${X(T-1).toFixed(1)},${ie(G).toFixed(1)} Z`;function A(ue){var rt;const Oe=(rt=x.current)==null?void 0:rt.getBoundingClientRect();return Oe?ue.clientX-Oe.left:0}function Y(ue){if(U)return;const Oe=A(ue);H(ae(Oe)),b.current&&w.current&&(w.current={a:w.current.a,b:Oe},R({...w.current}))}function W(ue){if(U||!g)return;ue.currentTarget.setPointerCapture(ue.pointerId),b.current=!0;const Oe=A(ue);w.current={a:Oe,b:Oe},R({...w.current})}function _(ue){ue.currentTarget.hasPointerCapture(ue.pointerId)&&ue.currentTarget.releasePointerCapture(ue.pointerId);const Oe=w.current;if(b.current&&Oe&&g){const rt=ae(Math.min(Oe.a,Oe.b)),Nt=ae(Math.max(Oe.a,Oe.b));Nt>rt&&g({from:n[rt].x,to:n[Nt].x})}b.current=!1,w.current=null,R(null)}function F(){H(null),b.current=!1,w.current=null,R(null)}const te=Math.max(1,Math.ceil(T/8)),pe=[V,G+Q*.66,G+Q*.33,G],ne=O!=null&&O>=0&&O{const rt=ue.points[ne];return rt&&Number.isFinite(rt.y)?[{...ue,point:rt,index:Oe}]:[]}),lt=ne!=null?(i==null?void 0:i[ne])??null:null,wt=lt&&Number.isFinite(lt.y)?lt:null,Bs=ne!=null?Zm(X(ne),80,j-80):0,xn=Ce&&wt&&wt.y!==0?(Ce.y-wt.y)/Math.abs(wt.y)*100:null,Cr=m??(U?"Time series chart: not enough data to plot.":`Time series chart, ${T} points from ${f(n[0].x)} to ${f(n[T-1].x)}.`);return c.jsxs("div",{className:"relative text-chart-primary",children:[c.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-x-3 gap-y-0.5 px-3 pt-2 text-2xs text-faint",children:[E.map((ue,Oe)=>c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"inline-block h-0.5 w-3",style:{backgroundColor:hd(Oe)}})," ",ue.label]},`${ue.label}-${Oe}`)),i!=null&&i.length?c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"inline-block h-0 w-3 border-t border-dashed border-faint"})," ",h]}):null]}),c.jsx("div",{ref:v,className:"w-full",children:U?c.jsx("div",{className:"grid h-[280px] place-items-center text-xs text-faint",children:"Not enough data to chart."}):c.jsxs("svg",{ref:x,width:j,height:cl,role:"img","aria-label":Cr,className:"block touch-none select-none",onPointerMove:Y,onPointerDown:W,onPointerUp:_,onPointerLeave:F,onPointerCancel:F,onDoubleClick:()=>g==null?void 0:g(null),children:[c.jsx("defs",{children:c.jsxs("linearGradient",{id:"ts-fill",x1:"0",y1:"0",x2:"0",y2:"1",children:[c.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:.18}),c.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:0})]})}),pe.map((ue,Oe)=>c.jsxs("g",{children:[c.jsx("line",{x1:qt.left,x2:j-qt.right,y1:ie(ue),y2:ie(ue),className:"stroke-line"}),c.jsx("text",{x:qt.left-8,y:ie(ue)+3,textAnchor:"end",className:"fill-faint font-mono text-[10px]",children:u(ue)})]},Oe)),i&&i.length>=2?c.jsx("path",{d:re(i),fill:"none",className:"stroke-faint",strokeWidth:1.25,strokeDasharray:"4 3"}):null,se?c.jsx("path",{d:se,fill:"url(#ts-fill)"}):null,E.map((ue,Oe)=>c.jsx("path",{d:re(ue.points),fill:"none",stroke:hd(Oe),strokeWidth:1.75},`${ue.label}-${Oe}`)),L?c.jsx("rect",{x:Math.min(L.a,L.b),y:qt.top,width:Math.abs(L.b-L.a),height:ee,className:"fill-chart-primary",opacity:.12}):null,ne!=null&&Ue.length?c.jsxs("g",{children:[c.jsx("line",{x1:X(ne),x2:X(ne),y1:qt.top,y2:cl-qt.bottom,className:"stroke-faint",strokeDasharray:"3 3"}),wt?c.jsx("circle",{cx:X(ne),cy:ie(wt.y),r:3,className:"fill-faint"}):null,Ue.map(ue=>c.jsx("circle",{cx:X(ne),cy:ie(ue.point.y),r:3.5,fill:hd(ue.index)},`${ue.label}-${ue.index}`))]}):null,n.map((ue,Oe)=>Oe%te===0||Oe===T-1?c.jsx("text",{x:X(Oe),y:cl-8,textAnchor:"middle",className:"fill-faint font-mono text-[10px]",children:f(ue.x)},ue.x):null)]})}),Ue.length&&Te?c.jsxs("div",{className:"pointer-events-none absolute top-8 z-20 -translate-x-1/2 whitespace-nowrap border border-line bg-surface px-2 py-1.5 text-2xs shadow-[var(--shadow)]",style:{left:Bs},children:[c.jsx("div",{className:"mb-0.5 font-mono text-faint",children:f(Te)}),Ue.map(ue=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"text-muted",children:ue.label}),c.jsx("span",{className:"font-mono tnum font-medium text-ink",children:a(ue.point.y)})]},`${ue.label}-${ue.index}`)),wt?c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"text-muted",children:h}),c.jsx("span",{className:"font-mono tnum text-muted",children:a(wt.y)})]}):null,xn!=null?c.jsxs("div",{className:`mt-0.5 text-right font-mono ${xn>0?"text-success":xn<0?"text-danger":"text-faint"}`,children:[xn.toLocaleString(void 0,{maximumFractionDigits:1,signDisplay:"exceptZero"}),"%"]}):null]}):null]})}const A_={positive:"text-success",negative:"text-danger",neutral:"text-faint"};function B_({metric:n,points:e,comparisonPoints:t,total:i,prevTotal:a,hasTime:u,loading:f,activeRange:h,comparisonLabel:m="Prev period",formatLabel:g,onBrush:v}){const x={format:n.format,type:n.type},b=a!==void 0?yy(i,a):null,w=`${n.label} over time. Total ${pt(i,x)}${b?`, ${b.label} versus the ${m.toLowerCase()}`:""}.`;return c.jsxs("section",{className:"flex flex-col gap-2",children:[c.jsxs("header",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-0.5 px-0.5",children:[c.jsx("h2",{className:"text-xs font-medium text-muted",children:n.label}),c.jsx("span",{className:"font-mono tnum text-xl font-semibold text-ink",children:pt(i,x)}),b?c.jsxs("span",{className:`text-xs ${A_[b.tone]}`,children:[b.label," vs ",m.toLowerCase()]}):null,u?null:c.jsx("span",{className:"text-2xs text-faint",children:"No time dimension"}),h?c.jsx("button",{type:"button",onClick:()=>v(null),className:"ml-auto inline-flex h-7 items-center rounded-full border border-line bg-surface px-3 text-xs text-muted hover:border-line-strong hover:text-ink",children:"Reset zoom"}):null]}),u?f&&e.length<2?c.jsx("div",{className:"skeleton h-[280px] w-full"}):c.jsx(Go,{points:e,comparison:t,formatValue:j=>pt(j,x),formatAxis:j=>Wt(j,x),formatLabel:g,comparisonLabel:m,ariaLabel:w,onBrush:v}):null]})}const E_=new Set(["and","as","asc","by","case","cast","count","date_trunc","desc","else","end","from","group","in","is","join","left","limit","not","null","on","or","order","over","partition","select","sum","then","when","where","with"]);function R_(n){const e=[];let t=0;for(;ta).map(([a,u])=>`-- ${a} +]`}concat(...e){const t=this.schema,i=this.data.concat(e.flatMap(({data:a})=>a));return new mn(t,i.map(a=>new An(t,a)))}slice(e,t){const i=this.schema;[e,t]=Jg({length:this.numRows},e,t);const a=ev(this.data,this._offsets,e,t);return new mn(i,a.map(u=>new An(i,u)))}getChild(e){return this.getChildAt(this.schema.fields.findIndex(t=>t.name===e))}getChildAt(e){if(e>-1&&ei.children[e]);if(t.length===0){const{type:i}=this.schema.fields[e],a=Ee({type:i,length:0,nullCount:0});t.push(a._changeLengthAndBackfillNullBitmap(this.numRows))}return new Je(t)}return null}setChild(e,t){var i;return this.setChildAt((i=this.schema.fields)===null||i===void 0?void 0:i.findIndex(a=>a.name===e),t)}setChildAt(e,t){let i=this.schema,a=[...this.batches];if(e>-1&&ethis.getChildAt(g));[u[e],h[e]]=[f,t],[i,a]=od(i,h)}return new mn(i,a)}select(e){const t=this.schema.fields.reduce((i,a,u)=>i.set(a.name,u),new Map);return this.selectAt(e.map(i=>t.get(i)).filter(i=>i>-1))}selectAt(e){const t=this.schema.selectAt(e),i=this.batches.map(a=>a.selectAt(e));return new mn(t,i)}assign(e){const t=this.schema.fields,[i,a]=e.schema.fields.reduce((h,m,g)=>{const[v,x]=h,b=t.findIndex(w=>w.name===m.name);return~b?x[b]=g:v.push(g),h},[[],[]]),u=this.schema.assign(e.schema),f=[...t.map((h,m)=>[m,a[m]]).map(([h,m])=>m===void 0?this.getChildAt(h):e.getChildAt(m)),...i.map(h=>e.getChildAt(h))].filter(Boolean);return new mn(...od(u,f))}}cv=Symbol.toStringTag;mn[cv]=(n=>(n.schema=null,n.batches=[],n._offsets=new Uint32Array([0]),n._nullCount=-1,n[Symbol.isConcatSpreadable]=!0,n.isValid=zl(Gd),n.get=zl(Gt.getVisitFn(D.Struct)),n.set=tv(vn.getVisitFn(D.Struct)),n.indexOf=nv(Vl.getVisitFn(D.Struct)),"Table"))(mn.prototype);var dv;let An=class Oo{constructor(...e){switch(e.length){case 2:{if([this.schema]=e,!(this.schema instanceof We))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");if([,this.data=Ee({nullCount:0,type:new Tt(this.schema.fields),children:this.schema.fields.map(t=>Ee({type:t.type,nullCount:0}))})]=e,!(this.data instanceof Ye))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");[this.schema,this.data]=Mm(this.schema,this.data.children);break}case 1:{const[t]=e,{fields:i,children:a,length:u}=Object.keys(t).reduce((m,g,v)=>(m.children[v]=t[g],m.length=Math.max(m.length,t[g].length),m.fields[v]=nt.new({name:g,type:t[g].type,nullable:!0}),m),{length:0,fields:new Array,children:new Array}),f=new We(i),h=Ee({type:new Tt(i),length:u,children:a,nullCount:0});[this.schema,this.data]=Mm(f,h.children,u);break}default:throw new TypeError("RecordBatch constructor expects an Object mapping names to child Data, or a [Schema, Data] pair.")}}get dictionaries(){return this._dictionaries||(this._dictionaries=fv(this.schema.fields,this.data.children))}get numCols(){return this.schema.fields.length}get numRows(){return this.data.length}get nullCount(){return this.data.nullCount}isValid(e){return this.data.getValid(e)}get(e){return Gt.visit(this.data,e)}at(e){return this.get(Vd(e,this.numRows))}set(e,t){return vn.visit(this.data,e,t)}indexOf(e,t){return Vl.visit(this.data,e,t)}[Symbol.iterator](){return Yd.visit(new Je([this.data]))}toArray(){return[...this]}concat(...e){return new mn(this.schema,[this,...e])}slice(e,t){const[i]=new Je([this.data]).slice(e,t).data;return new Oo(this.schema,i)}getChild(e){var t;return this.getChildAt((t=this.schema.fields)===null||t===void 0?void 0:t.findIndex(i=>i.name===e))}getChildAt(e){return e>-1&&ea.name===e),t)}setChildAt(e,t){let i=this.schema,a=this.data;if(e>-1&&eh.name===u);~f&&(a[f]=this.data.children[f])}return new Oo(t,Ee({type:i,length:this.numRows,children:a}))}selectAt(e){const t=this.schema.selectAt(e),i=e.map(u=>this.data.children[u]).filter(Boolean),a=Ee({type:new Tt(t.fields),length:this.numRows,children:i});return new Oo(t,a)}};dv=Symbol.toStringTag;An[dv]=(n=>(n._nullCount=-1,n[Symbol.isConcatSpreadable]=!0,"RecordBatch"))(An.prototype);function Mm(n,e,t=e.reduce((i,a)=>Math.max(i,a.length),0)){var i;const a=[...n.fields],u=[...e],f=(t+63&-64)>>3;for(const[h,m]of n.fields.entries()){const g=e[h];(!g||g.length!==t)&&(a[h]=m.clone({nullable:!0}),u[h]=(i=g==null?void 0:g._changeLengthAndBackfillNullBitmap(t))!==null&&i!==void 0?i:Ee({type:m.type,length:t,nullCount:t,nullBitmap:new Uint8Array(f)}))}return[n.assign(a),Ee({type:new Tt(a),length:t,children:u})]}function fv(n,e,t=new Map){var i,a;if(((i=n==null?void 0:n.length)!==null&&i!==void 0?i:0)>0&&(n==null?void 0:n.length)===(e==null?void 0:e.length))for(let u=-1,f=n.length;++uEe({type:a.type})),i=Ee({type:new Tt(e.fields),nullCount:0,children:t});super(e,i)}}let qr=class Hn{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsMessage(e,t){return(t||new Hn).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsMessage(e,t){return e.setPosition(e.position()+He),(t||new Hn).__init(e.readInt32(e.position())+e.position(),e)}version(){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):ht.V1}headerType(){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb_pos+e):Ve.NONE}header(e){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__union(e,this.bb_pos+t):null}bodyLength(){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt64(this.bb_pos+e):BigInt("0")}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,12);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}static startMessage(e){e.startObject(5)}static addVersion(e,t){e.addFieldInt16(0,t,ht.V1)}static addHeaderType(e,t){e.addFieldInt8(1,t,Ve.NONE)}static addHeader(e,t){e.addFieldOffset(2,t,0)}static addBodyLength(e,t){e.addFieldInt64(3,t,BigInt("0"))}static addCustomMetadata(e,t){e.addFieldOffset(4,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endMessage(e){return e.endObject()}static finishMessageBuffer(e,t){e.finish(t)}static finishSizePrefixedMessageBuffer(e,t){e.finish(t,void 0,!0)}static createMessage(e,t,i,a,u,f){return Hn.startMessage(e),Hn.addVersion(e,t),Hn.addHeaderType(e,i),Hn.addHeader(e,a),Hn.addBodyLength(e,u),Hn.addCustomMetadata(e,f),Hn.endMessage(e)}};class p1 extends Re{visit(e,t){return e==null||t==null?void 0:super.visit(e,t)}visitNull(e,t){return vm.startNull(t),vm.endNull(t)}visitInt(e,t){return en.startInt(t),en.addBitWidth(t,e.bitWidth),en.addIsSigned(t,e.isSigned),en.endInt(t)}visitFloat(e,t){return Kn.startFloatingPoint(t),Kn.addPrecision(t,e.precision),Kn.endFloatingPoint(t)}visitBinary(e,t){return hm.startBinary(t),hm.endBinary(t)}visitLargeBinary(e,t){return mm.startLargeBinary(t),mm.endLargeBinary(t)}visitBool(e,t){return pm.startBool(t),pm.endBool(t)}visitUtf8(e,t){return xm.startUtf8(t),xm.endUtf8(t)}visitLargeUtf8(e,t){return ym.startLargeUtf8(t),ym.endLargeUtf8(t)}visitDecimal(e,t){return ci.startDecimal(t),ci.addScale(t,e.scale),ci.addPrecision(t,e.precision),ci.addBitWidth(t,e.bitWidth),ci.endDecimal(t)}visitDate(e,t){return hl.startDate(t),hl.addUnit(t,e.unit),hl.endDate(t)}visitTime(e,t){return hn.startTime(t),hn.addUnit(t,e.unit),hn.addBitWidth(t,e.bitWidth),hn.endTime(t)}visitTimestamp(e,t){const i=e.timezone&&t.createString(e.timezone)||void 0;return pn.startTimestamp(t),pn.addUnit(t,e.unit),i!==void 0&&pn.addTimezone(t,i),pn.endTimestamp(t)}visitInterval(e,t){return Jn.startInterval(t),Jn.addUnit(t,e.unit),Jn.endInterval(t)}visitDuration(e,t){return pl.startDuration(t),pl.addUnit(t,e.unit),pl.endDuration(t)}visitList(e,t){return gm.startList(t),gm.endList(t)}visitStruct(e,t){return ks.startStruct_(t),ks.endStruct_(t)}visitUnion(e,t){Vt.startTypeIdsVector(t,e.typeIds.length);const i=Vt.createTypeIdsVector(t,e.typeIds);return Vt.startUnion(t),Vt.addMode(t,e.mode),Vt.addTypeIds(t,i),Vt.endUnion(t)}visitDictionary(e,t){const i=this.visit(e.indices,t);return wr.startDictionaryEncoding(t),wr.addId(t,BigInt(e.id)),wr.addIsOrdered(t,e.isOrdered),i!==void 0&&wr.addIndexType(t,i),wr.endDictionaryEncoding(t)}visitFixedSizeBinary(e,t){return ml.startFixedSizeBinary(t),ml.addByteWidth(t,e.byteWidth),ml.endFixedSizeBinary(t)}visitFixedSizeList(e,t){return yl.startFixedSizeList(t),yl.addListSize(t,e.listSize),yl.endFixedSizeList(t)}visitMap(e,t){return gl.startMap(t),gl.addKeysSorted(t,e.keysSorted),gl.endMap(t)}}const ad=new p1;function m1(n,e=new Map){return new We(g1(n,e),xl(n.metadata),e)}function pv(n){return new Rn(n.count,mv(n.columns),yv(n.columns))}function y1(n){return new kr(pv(n.data),n.id,n.isDelta)}function g1(n,e){return(n.fields||[]).filter(Boolean).map(t=>nt.fromJSON(t,e))}function Dm(n,e){return(n.children||[]).filter(Boolean).map(t=>nt.fromJSON(t,e))}function mv(n){return(n||[]).reduce((e,t)=>[...e,new Ai(t.count,v1(t.VALIDITY)),...mv(t.children)],[])}function yv(n,e=[]){for(let t=-1,i=(n||[]).length;++te+ +(t===0),0)}function x1(n,e){let t,i,a,u,f,h;return!e||!(u=n.dictionary)?(f=Fm(n,Dm(n,e)),a=new nt(n.name,f,n.nullable,xl(n.metadata))):e.has(t=u.id)?(i=(i=u.indexType)?Cm(i):new Lo,h=new Mi(e.get(t),i,t,u.isOrdered),a=new nt(n.name,h,n.nullable,xl(n.metadata))):(i=(i=u.indexType)?Cm(i):new Lo,e.set(t,f=Fm(n,Dm(n,e))),h=new Mi(f,i,t,u.isOrdered),a=new nt(n.name,h,n.nullable,xl(n.metadata))),a||null}function xl(n=[]){return new Map(n.map(({key:e,value:t})=>[e,t]))}function Cm(n){return new Ds(n.isSigned,n.bitWidth)}function Fm(n,e){const t=n.type.name;switch(t){case"NONE":return new ss;case"null":return new ss;case"binary":return new kl;case"largebinary":return new Il;case"utf8":return new Ml;case"largeutf8":return new Dl;case"bool":return new Cl;case"list":return new Rl((e||[])[0]);case"struct":return new Tt(e||[]);case"struct_":return new Tt(e||[])}switch(t){case"int":{const i=n.type;return new Ds(i.isSigned,i.bitWidth)}case"floatingpoint":{const i=n.type;return new jl(Dt[i.precision])}case"decimal":{const i=n.type;return new Fl(i.scale,i.precision,i.bitWidth)}case"date":{const i=n.type;return new Ol(gn[i.unit])}case"time":{const i=n.type;return new Tl(_e[i.unit],i.bitWidth)}case"timestamp":{const i=n.type;return new Al(_e[i.unit],i.timezone)}case"interval":{const i=n.type;return new Bl(nr[i.unit])}case"duration":{const i=n.type;return new El(_e[i.unit])}case"union":{const i=n.type,[a,...u]=(i.mode+"").toLowerCase(),f=a.toUpperCase()+u.join("");return new Ll(Ht[f],i.typeIds||[],e||[])}case"fixedsizebinary":{const i=n.type;return new Ul(i.byteWidth)}case"fixedsizelist":{const i=n.type;return new $l(i.listSize,(e||[])[0])}case"map":{const i=n.type;return new Pl((e||[])[0],i.keysSorted)}}throw new Error(`Unrecognized type: "${t}"`)}var b1=Cy,w1=ki;class Bn{static fromJSON(e,t){const i=new Bn(0,ht.V5,t);return i._createHeader=S1(e,t),i}static decode(e){e=new w1($e(e));const t=qr.getRootAsMessage(e),i=t.bodyLength(),a=t.version(),u=t.headerType(),f=new Bn(i,a,u);return f._createHeader=_1(t,u),f}static encode(e){const t=new b1;let i=-1;return e.isSchema()?i=We.encode(t,e.header()):e.isRecordBatch()?i=Rn.encode(t,e.header()):e.isDictionaryBatch()&&(i=kr.encode(t,e.header())),qr.startMessage(t),qr.addVersion(t,ht.V5),qr.addHeader(t,i),qr.addHeaderType(t,e.headerType),qr.addBodyLength(t,BigInt(e.bodyLength)),qr.finishMessageBuffer(t,qr.endMessage(t)),t.asUint8Array()}static from(e,t=0){if(e instanceof We)return new Bn(0,ht.V5,Ve.Schema,e);if(e instanceof Rn)return new Bn(t,ht.V5,Ve.RecordBatch,e);if(e instanceof kr)return new Bn(t,ht.V5,Ve.DictionaryBatch,e);throw new Error(`Unrecognized Message header: ${e}`)}get type(){return this.headerType}get version(){return this._version}get headerType(){return this._headerType}get bodyLength(){return this._bodyLength}header(){return this._createHeader()}isSchema(){return this.headerType===Ve.Schema}isRecordBatch(){return this.headerType===Ve.RecordBatch}isDictionaryBatch(){return this.headerType===Ve.DictionaryBatch}constructor(e,t,i,a){this._version=t,this._headerType=i,this.body=new Uint8Array(0),a&&(this._createHeader=()=>a),this._bodyLength=tt(e)}}class Rn{get nodes(){return this._nodes}get length(){return this._length}get buffers(){return this._buffers}constructor(e,t,i){this._nodes=t,this._buffers=i,this._length=tt(e)}}class kr{get id(){return this._id}get data(){return this._data}get isDelta(){return this._isDelta}get length(){return this.data.length}get nodes(){return this.data.nodes}get buffers(){return this.data.buffers}constructor(e,t,i=!1){this._data=e,this._isDelta=i,this._id=tt(t)}}class _r{constructor(e,t){this.offset=tt(e),this.length=tt(t)}}class Ai{constructor(e,t){this.length=tt(e),this.nullCount=tt(t)}}function S1(n,e){return(()=>{switch(e){case Ve.Schema:return We.fromJSON(n);case Ve.RecordBatch:return Rn.fromJSON(n);case Ve.DictionaryBatch:return kr.fromJSON(n)}throw new Error(`Unrecognized Message type: { name: ${Ve[e]}, type: ${e} }`)})}function _1(n,e){return(()=>{switch(e){case Ve.Schema:return We.decode(n.header(new Gn),new Map,n.version());case Ve.RecordBatch:return Rn.decode(n.header(new yr),n.version());case Ve.DictionaryBatch:return kr.decode(n.header(new li),n.version())}throw new Error(`Unrecognized Message type: { name: ${Ve[e]}, type: ${e} }`)})}nt.encode=A1;nt.decode=O1;nt.fromJSON=x1;We.encode=T1;We.decode=N1;We.fromJSON=m1;Rn.encode=B1;Rn.decode=j1;Rn.fromJSON=pv;kr.encode=E1;kr.decode=k1;kr.fromJSON=y1;Ai.encode=R1;Ai.decode=M1;_r.encode=L1;_r.decode=I1;function N1(n,e=new Map,t=ht.V5){const i=F1(n,e);return new We(i,bl(n),e,t)}function j1(n,e=ht.V5){if(n.compression()!==null)throw new Error("Record batch compression not implemented");return new Rn(n.length(),D1(n),C1(n,e))}function k1(n,e=ht.V5){return new kr(Rn.decode(n.data(),e),n.id(),n.isDelta())}function I1(n){return new _r(n.offset(),n.length())}function M1(n){return new Ai(n.length(),n.nullCount())}function D1(n){const e=[];for(let t,i=-1,a=-1,u=n.nodesLength();++int.encode(n,u));Gn.startFieldsVector(n,t.length);const i=Gn.createFieldsVector(n,t),a=e.metadata&&e.metadata.size>0?Gn.createCustomMetadataVector(n,[...e.metadata].map(([u,f])=>{const h=n.createString(`${u}`),m=n.createString(`${f}`);return gt.startKeyValue(n),gt.addKey(n,h),gt.addValue(n,m),gt.endKeyValue(n)})):-1;return Gn.startSchema(n),Gn.addFields(n,i),Gn.addEndianness(n,U1?Ii.Little:Ii.Big),a!==-1&&Gn.addCustomMetadata(n,a),Gn.endSchema(n)}function A1(n,e){let t=-1,i=-1,a=-1;const u=e.type;let f=e.typeId;me.isDictionary(u)?(f=u.dictionary.typeId,a=ad.visit(u,n),i=ad.visit(u.dictionary,n)):i=ad.visit(u,n);const h=(u.children||[]).map(v=>nt.encode(n,v)),m=dn.createChildrenVector(n,h),g=e.metadata&&e.metadata.size>0?dn.createCustomMetadataVector(n,[...e.metadata].map(([v,x])=>{const b=n.createString(`${v}`),w=n.createString(`${x}`);return gt.startKeyValue(n),gt.addKey(n,b),gt.addValue(n,w),gt.endKeyValue(n)})):-1;return e.name&&(t=n.createString(e.name)),dn.startField(n),dn.addType(n,i),dn.addTypeType(n,f),dn.addChildren(n,m),dn.addNullable(n,!!e.nullable),t!==-1&&dn.addName(n,t),a!==-1&&dn.addDictionary(n,a),g!==-1&&dn.addCustomMetadata(n,g),dn.endField(n)}function B1(n,e){const t=e.nodes||[],i=e.buffers||[];yr.startNodesVector(n,t.length);for(const f of t.slice().reverse())Ai.encode(n,f);const a=n.endVector();yr.startBuffersVector(n,i.length);for(const f of i.slice().reverse())_r.encode(n,f);const u=n.endVector();return yr.startRecordBatch(n),yr.addLength(n,BigInt(e.length)),yr.addNodes(n,a),yr.addBuffers(n,u),yr.endRecordBatch(n)}function E1(n,e){const t=Rn.encode(n,e.data);return li.startDictionaryBatch(n),li.addId(n,BigInt(e.id)),li.addIsDelta(n,e.isDelta),li.addData(n,t),li.endDictionaryBatch(n)}function R1(n,e){return Ty.createFieldNode(n,BigInt(e.length),BigInt(e.nullCount))}function L1(n,e){return Oy.createBuffer(n,BigInt(e.offset),BigInt(e.length))}const U1=(()=>{const n=new ArrayBuffer(2);return new DataView(n).setInt16(0,256,!0),new Int16Array(n)[0]===256})(),Xd=n=>`Expected ${Ve[n]} Message in stream, but was null or length 0.`,ef=n=>`Header pointer of flatbuffer-encoded ${Ve[n]} Message is null or length 0.`,gv=(n,e)=>`Expected to read ${n} metadata bytes, but only read ${e}.`,vv=(n,e)=>`Expected to read ${n} bytes for message body, but only read ${e}.`;class xv{constructor(e){this.source=e instanceof Hl?e:new Hl(e)}[Symbol.iterator](){return this}next(){let e;return(e=this.readMetadataLength()).done||e.value===-1&&(e=this.readMetadataLength()).done||(e=this.readMetadata(e.value)).done?at:e}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}readMessage(e){let t;if((t=this.next()).done)return null;if(e!=null&&t.value.headerType!==e)throw new Error(Xd(e));return t.value}readMessageBody(e){if(e<=0)return new Uint8Array(0);const t=$e(this.source.read(e));if(t.byteLength[...a,...u.VALIDITY&&[u.VALIDITY]||[],...u.TYPE_ID&&[u.TYPE_ID]||[],...u.OFFSET&&[u.OFFSET]||[],...u.DATA&&[u.DATA]||[],...t(u.children)],[])}}readMessage(e){let t;if((t=this.next()).done)return null;if(e!=null&&t.value.headerType!==e)throw new Error(Xd(e));return t.value}readSchema(){const e=Ve.Schema,t=this.readMessage(e),i=t==null?void 0:t.header();if(!t||!i)throw new Error(ef(e));return i}}const iu=4,Cd="ARROW1",Yl=new Uint8Array(Cd.length);for(let n=0;nthis):this}readRecordBatch(e){return this._impl.isFile()?this._impl.readRecordBatch(e):null}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}toDOMStream(){return fn.toDOMStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this})}toNodeStream(){return fn.toNodeStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this},{objectMode:!0})}static throughNode(e){throw new Error('"throughNode" not available in this environment')}static throughDOM(e,t){throw new Error('"throughDOM" not available in this environment')}static from(e){return e instanceof jr?e:bd(e)?G1(e):Ny(e)?K1(e):Ao(e)?Fe(this,void 0,void 0,function*(){return yield jr.from(yield e)}):jy(e)||Rd(e)||Iy(e)||Ed(e)?Q1(new Ci(e)):Y1(new Hl(e))}static readAll(e){return e instanceof jr?e.isSync()?Bm(e):Em(e):bd(e)||ArrayBuffer.isView(e)||nu(e)||_y(e)?Bm(e):Em(e)}}class Ql extends jr{constructor(e){super(e),this._impl=e}readAll(){return[...this]}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return qn(this,arguments,function*(){yield Ae(yield*fl(xi(this[Symbol.iterator]())))})}}class Kl extends jr{constructor(e){super(e),this._impl=e}readAll(){return Fe(this,void 0,void 0,function*(){var e,t,i,a;const u=new Array;try{for(var f=!0,h=xi(this),m;m=yield h.next(),e=m.done,!e;f=!0){a=m.value,f=!1;const g=a;u.push(g)}}catch(g){t={error:g}}finally{try{!f&&!e&&(i=h.return)&&(yield i.call(h))}finally{if(t)throw t.error}}return u})}[Symbol.iterator](){throw new Error("AsyncRecordBatchStreamReader is not Iterable")}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}}class wv extends Ql{constructor(e){super(e),this._impl=e}}class V1 extends Kl{constructor(e){super(e),this._impl=e}}class Sv{get numDictionaries(){return this._dictionaryIndex}get numRecordBatches(){return this._recordBatchIndex}constructor(e=new Map){this.closed=!1,this.autoDestroy=!0,this._dictionaryIndex=0,this._recordBatchIndex=0,this.dictionaries=e}isSync(){return!1}isAsync(){return!1}isFile(){return!1}isStream(){return!1}reset(e){return this._dictionaryIndex=0,this._recordBatchIndex=0,this.schema=e,this.dictionaries=new Map,this}_loadRecordBatch(e,t){const i=this._loadVectors(e,t,this.schema.fields),a=Ee({type:new Tt(this.schema.fields),length:e.length,children:i});return new An(this.schema,a)}_loadDictionaryBatch(e,t){const{id:i,isDelta:a}=e,{dictionaries:u,schema:f}=this,h=u.get(i),m=f.dictionaries.get(i),g=this._loadVectors(e.data,t,[m]);return(h&&a?h.concat(new Je(g)):new Je(g)).memoize()}_loadVectors(e,t,i){return new uv(t,e.nodes,e.buffers,this.dictionaries,this.schema.metadataVersion).visitMany(i)}}class Jl extends Sv{constructor(e,t){super(t),this._reader=bd(e)?new P1(this._handle=e):new xv(this._handle=e)}isSync(){return!0}isStream(){return!0}[Symbol.iterator](){return this}cancel(){!this.closed&&(this.closed=!0)&&(this.reset()._reader.return(),this._reader=null,this.dictionaries=null)}open(e){return this.closed||(this.autoDestroy=Nv(this,e),this.schema||(this.schema=this._reader.readSchema())||this.cancel()),this}throw(e){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.throw(e):at}return(e){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.return(e):at}next(){if(this.closed)return at;let e;const{_reader:t}=this;for(;e=this._readNextMessageAndValidate();)if(e.isSchema())this.reset(e.header());else if(e.isRecordBatch()){this._recordBatchIndex++;const i=e.header(),a=t.readMessageBody(e.bodyLength);return{done:!1,value:this._loadRecordBatch(i,a)}}else if(e.isDictionaryBatch()){this._dictionaryIndex++;const i=e.header(),a=t.readMessageBody(e.bodyLength),u=this._loadDictionaryBatch(i,a);this.dictionaries.set(i.id,u)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new hv(this.schema)}):this.return()}_readNextMessageAndValidate(e){return this._reader.readMessage(e)}}class ql extends Sv{constructor(e,t){super(t),this._reader=new $1(this._handle=e)}isAsync(){return!0}isStream(){return!0}[Symbol.asyncIterator](){return this}cancel(){return Fe(this,void 0,void 0,function*(){!this.closed&&(this.closed=!0)&&(yield this.reset()._reader.return(),this._reader=null,this.dictionaries=null)})}open(e){return Fe(this,void 0,void 0,function*(){return this.closed||(this.autoDestroy=Nv(this,e),this.schema||(this.schema=yield this._reader.readSchema())||(yield this.cancel())),this})}throw(e){return Fe(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.throw(e):at})}return(e){return Fe(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.return(e):at})}next(){return Fe(this,void 0,void 0,function*(){if(this.closed)return at;let e;const{_reader:t}=this;for(;e=yield this._readNextMessageAndValidate();)if(e.isSchema())yield this.reset(e.header());else if(e.isRecordBatch()){this._recordBatchIndex++;const i=e.header(),a=yield t.readMessageBody(e.bodyLength);return{done:!1,value:this._loadRecordBatch(i,a)}}else if(e.isDictionaryBatch()){this._dictionaryIndex++;const i=e.header(),a=yield t.readMessageBody(e.bodyLength),u=this._loadDictionaryBatch(i,a);this.dictionaries.set(i.id,u)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new hv(this.schema)}):yield this.return()})}_readNextMessageAndValidate(e){return Fe(this,void 0,void 0,function*(){return yield this._reader.readMessage(e)})}}class _v extends Jl{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(e,t){super(e instanceof Im?e:new Im(e),t)}isSync(){return!0}isFile(){return!0}open(e){if(!this.closed&&!this._footer){this.schema=(this._footer=this._readFooter()).schema;for(const t of this._footer.dictionaryBatches())t&&this._readDictionaryBatch(this._dictionaryIndex++)}return super.open(e)}readRecordBatch(e){var t;if(this.closed)return null;this._footer||this.open();const i=(t=this._footer)===null||t===void 0?void 0:t.getRecordBatch(e);if(i&&this._handle.seek(i.offset)){const a=this._reader.readMessage(Ve.RecordBatch);if(a!=null&&a.isRecordBatch()){const u=a.header(),f=this._reader.readMessageBody(a.bodyLength);return this._loadRecordBatch(u,f)}}return null}_readDictionaryBatch(e){var t;const i=(t=this._footer)===null||t===void 0?void 0:t.getDictionaryBatch(e);if(i&&this._handle.seek(i.offset)){const a=this._reader.readMessage(Ve.DictionaryBatch);if(a!=null&&a.isDictionaryBatch()){const u=a.header(),f=this._reader.readMessageBody(a.bodyLength),h=this._loadDictionaryBatch(u,f);this.dictionaries.set(u.id,h)}}}_readFooter(){const{_handle:e}=this,t=e.size-bv,i=e.readInt32(t),a=e.readAt(t-i,i);return Qd.decode(a)}_readNextMessageAndValidate(e){var t;if(this._footer||this.open(),this._footer&&this._recordBatchIndexsuper.open}});return Fe(this,void 0,void 0,function*(){if(!this.closed&&!this._footer){this.schema=(this._footer=yield this._readFooter()).schema;for(const i of this._footer.dictionaryBatches())i&&(yield this._readDictionaryBatch(this._dictionaryIndex++))}return yield t.open.call(this,e)})}readRecordBatch(e){return Fe(this,void 0,void 0,function*(){var t;if(this.closed)return null;this._footer||(yield this.open());const i=(t=this._footer)===null||t===void 0?void 0:t.getRecordBatch(e);if(i&&(yield this._handle.seek(i.offset))){const a=yield this._reader.readMessage(Ve.RecordBatch);if(a!=null&&a.isRecordBatch()){const u=a.header(),f=yield this._reader.readMessageBody(a.bodyLength);return this._loadRecordBatch(u,f)}}return null})}_readDictionaryBatch(e){return Fe(this,void 0,void 0,function*(){var t;const i=(t=this._footer)===null||t===void 0?void 0:t.getDictionaryBatch(e);if(i&&(yield this._handle.seek(i.offset))){const a=yield this._reader.readMessage(Ve.DictionaryBatch);if(a!=null&&a.isDictionaryBatch()){const u=a.header(),f=yield this._reader.readMessageBody(a.bodyLength),h=this._loadDictionaryBatch(u,f);this.dictionaries.set(u.id,h)}}})}_readFooter(){return Fe(this,void 0,void 0,function*(){const{_handle:e}=this;e._pending&&(yield e._pending);const t=e.size-bv,i=yield e.readInt32(t),a=yield e.readAt(t-i,i);return Qd.decode(a)})}_readNextMessageAndValidate(e){return Fe(this,void 0,void 0,function*(){if(this._footer||(yield this.open()),this._footer&&this._recordBatchIndex=4?tf(e)?new wv(new _v(n.read())):new Ql(new Jl(n)):new Ql(new Jl((function*(){})()))}function Q1(n){return Fe(this,void 0,void 0,function*(){const e=yield n.peek(Wo+7&-8);return e&&e.byteLength>=4?tf(e)?new wv(new _v(yield n.read())):new Kl(new ql(n)):new Kl(new ql((function(){return qn(this,arguments,function*(){})})()))})}function K1(n){return Fe(this,void 0,void 0,function*(){const{size:e}=yield n.stat(),t=new Gl(n,e);return e>=z1&&tf(yield t.readAt(0,Wo+7&-8))?new V1(new W1(t)):new Kl(new ql(t))})}function jv(n){const e=jr.from(n);return Ao(e)?e.then(t=>jv(t)):e.isAsync()?e.readAll().then(t=>new mn(t)):new mn(e.readAll())}function J1(n){if(n==null)return null;if(typeof n=="bigint"){const e=Number(n);return Number.isSafeInteger(e)?e:n.toString()}if(n instanceof Date){const e=n.toISOString();return e.endsWith("T00:00:00.000Z")?e.slice(0,10):e}return typeof n=="object"?String(n):n}function q1(n){const e=jv(n),t=e.schema.fields.map(a=>a.name),i=new Array(e.numRows);for(let a=0;a({...e,charts:e.charts.map(t=>{var f,h;const i=t.query,a=(f=t.interactions)==null?void 0:f.brush,u=(h=t.interactions)==null?void 0:h.select;return{...t,query:{...i,metrics:Zr(i.metrics)??[],dimensions:Zr(i.dimensions),filters:Zr(i.filters),segments:Zr(i.segments),order_by:Zr(i.order_by),orderBy:Zr(i.orderBy)},interactions:t.interactions?{...t.interactions,brush:typeof a=="object"?{...a,fields:Zr(a.fields)}:a,select:typeof u=="object"?{...u,fields:Zr(u.fields)}:u}:void 0}})}))}}const X1="application/vnd.apache.arrow.stream";class eS{constructor(e){Mn(this,"active",0);Mn(this,"waiters",[]);this.max=e}async run(e){var t;this.active>=this.max&&await new Promise(i=>this.waiters.push(i)),this.active+=1;try{return await e()}finally{this.active-=1,(t=this.waiters.shift())==null||t()}}}function tS(n){var t,i,a,u,f;const e={};return(t=n.metrics)!=null&&t.length&&(e.metrics=n.metrics),(i=n.dimensions)!=null&&i.length&&(e.dimensions=n.dimensions),(a=n.filters)!=null&&a.length&&(e.filters=n.filters),(u=n.segments)!=null&&u.length&&(e.segments=n.segments),(f=n.orderBy)!=null&&f.length&&(e.order_by=n.orderBy),n.limit!=null&&(e.limit=n.limit),n.offset!=null&&(e.offset=n.offset),n.ungrouped&&(e.ungrouped=!0),n.parameters&&(e.parameters=n.parameters),n.usePreaggregations!=null&&(e.use_preaggregations=n.usePreaggregations),n.timezone&&n.timezone!=="UTC"&&(e.timezone=n.timezone),e}class nS{constructor(e={}){Mn(this,"baseUrl");Mn(this,"token");Mn(this,"sessionToken");Mn(this,"transport");Mn(this,"usePreaggregations");Mn(this,"gate");Mn(this,"onUnauthorized");this.baseUrl=(e.baseUrl??"").replace(/\/$/,""),this.token=e.token,this.transport=e.transport??"json",this.usePreaggregations=e.usePreaggregations??!0,this.gate=new eS(e.maxConcurrency??6),this.onUnauthorized=e.onUnauthorized}body(e){return tS({usePreaggregations:this.usePreaggregations,...e})}headers(e){const t={...e};return this.sessionToken?t.Authorization=`Sidemantic-Session ${this.sessionToken}`:this.token&&(t.Authorization=`Bearer ${this.token}`),t}isCrossOrigin(){return!this.baseUrl||typeof globalThis.location>"u"?!1:new URL(this.baseUrl,globalThis.location.href).origin!==globalThis.location.origin}url(e){return`${this.baseUrl}${e}`}async getJson(e){const t=await fetch(this.url(e),{headers:this.headers(),credentials:"include"});if(!t.ok)throw new Error(await this.errorText(t,e));return await t.json()}async errorText(e,t){var a;e.status===401&&((a=this.onUnauthorized)==null||a.call(this));let i="";try{const u=await e.json();i=u.error??u.detail??""}catch{}return`${t} failed (${e.status})${i?`: ${i}`:""}`}async health(){try{return(await fetch(this.url("/health"),{headers:this.headers(),credentials:"include"})).ok}catch{return!1}}async getCatalog(){try{const t=await fetch(this.url("/describe"),{headers:this.headers(),credentials:"include"});if(t.ok){const i=wb(await t.json());try{return _b(i,await this.getJson("/graph"))}catch{return i}}}catch{}const e=await this.getJson("/graph");return Sb(e)}async getDashboard(){try{const e=await fetch(this.url("/dashboard"),{headers:this.headers()});if(e.status===404)return null;if(!e.ok)throw new Error(await this.errorText(e,"/dashboard"));if(!(e.headers.get("content-type")??"").includes("application/json"))return null;const t=await e.json();return typeof t.title=="string"&&Array.isArray(t.tabs)?Z1(t):null}catch{return null}}async compile(e){const t=await fetch(this.url("/compile"),{method:"POST",headers:this.headers({"Content-Type":"application/json"}),credentials:"include",body:JSON.stringify(this.body(e))});if(!t.ok)throw new Error(await this.errorText(t,"/compile"));return(await t.json()).sql}async runQuery(e){return this.gate.run(()=>this.transport==="arrow"?this.runQueryArrow(e):this.runQueryJson(e))}async runQueryJson(e){const t=await fetch(this.url("/query"),{method:"POST",headers:this.headers({"Content-Type":"application/json"}),credentials:"include",body:JSON.stringify(this.body(e))});if(!t.ok)throw new Error(await this.errorText(t,"/query"));const i=await t.json(),a=i.rows??[];return{columns:a.length?Object.keys(a[0]):[],rows:a,rowCount:i.row_count??a.length,sql:i.sql??""}}async runQueryArrow(e){const t=await fetch(this.url("/query?format=arrow"),{method:"POST",headers:this.headers({"Content-Type":"application/json",Accept:X1}),credentials:"include",body:JSON.stringify(this.body(e))});if(!t.ok)throw new Error(await this.errorText(t,"/query"));const i=new Uint8Array(await t.arrayBuffer()),{columns:a,rows:u}=q1(i),f=t.headers.get("X-Sidemantic-Sql")??"";return{columns:a,rows:u,rowCount:u.length,sql:f}}async createBrowserSession(e){var a;const t=this.isCrossOrigin(),i=await fetch(this.url("/auth/session"),{method:"POST",headers:{Authorization:`Bearer ${e}`,...t?{"X-Sidemantic-Session-Mode":"header"}:{}},credentials:"include"});if(i.status===404||i.ok&&!((a=i.headers.get("content-type"))!=null&&a.includes("application/json"))){this.token=e;return}if(!i.ok)throw new Error(await this.errorText(i,"/auth/session"));if(t){const u=await i.json();if(!u.session_token)throw new Error("/auth/session did not return a cross-origin session token");this.sessionToken=u.session_token}this.token=void 0}}function kv({brand:n,toolbar:e,filters:t,rail:i,children:a,drawer:u,showRail:f=!0,openRailRequest:h}){const[m,g]=M.useState(()=>typeof window<"u"&&window.matchMedia("(max-width: 767px)").matches),[v,x]=M.useState(()=>typeof window>"u"||!window.matchMedia("(max-width: 767px)").matches),b=M.useId(),w=M.useRef(null),j=M.useRef(null),C=f&&v;return M.useEffect(()=>{const O=window.matchMedia("(max-width: 767px)"),H=()=>{g(O.matches),x(!O.matches)};return O.addEventListener("change",H),()=>O.removeEventListener("change",H)},[]),M.useEffect(()=>{h&&!m&&x(!0)},[h,m]),M.useEffect(()=>{if(!m||!v)return;const O=j.current,H=document.body.style.overflow;document.body.style.overflow="hidden",window.requestAnimationFrame(()=>{var R,T;return(T=(R=w.current)==null?void 0:R.querySelector("button"))==null?void 0:T.focus()});function L(R){var U;if(R.key==="Escape"){R.preventDefault(),x(!1);return}if(R.key!=="Tab")return;const T=(U=w.current)==null?void 0:U.querySelectorAll('button:not(:disabled), select:not(:disabled), input:not(:disabled), [href], [tabindex]:not([tabindex="-1"])');if(!(T!=null&&T.length))return;const E=T[0],I=T[T.length-1];R.shiftKey&&document.activeElement===E?(R.preventDefault(),I.focus()):!R.shiftKey&&document.activeElement===I&&(R.preventDefault(),E.focus())}return document.addEventListener("keydown",L,!0),()=>{document.body.style.overflow=H,document.removeEventListener("keydown",L,!0),O==null||O.focus()}},[m,v]),c.jsxs("div",{className:"flex h-[100dvh] min-w-0 flex-col overflow-hidden bg-bg text-ink",children:[c.jsxs("header",{className:"relative z-40 flex shrink-0 flex-col gap-2 border-b border-line bg-surface px-3 py-2 md:flex-row md:items-center md:justify-between md:gap-3",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[f?c.jsx("button",{ref:j,type:"button","aria-label":m?"Open catalog":v?"Collapse sidebar":"Expand sidebar","aria-expanded":v,"aria-controls":b,onClick:()=>x(O=>!O),className:"grid size-7 shrink-0 place-items-center border border-line text-faint hover:border-faint hover:text-ink",children:v?"‹":"›"}):null,n]}),c.jsx("div",{className:"flex w-full min-w-0 flex-wrap items-center gap-2 overflow-visible md:w-auto md:shrink-0 md:flex-nowrap",children:e})]}),t?c.jsx("div",{className:"flex min-h-9 shrink-0 flex-wrap items-center gap-2 overflow-x-auto border-b border-line bg-surface px-3 py-2 md:h-9 md:flex-nowrap md:py-0",children:t}):null,c.jsxs("div",{className:`grid min-h-0 min-w-0 flex-1 grid-cols-1 ${C?"md:grid-cols-[260px_minmax(0,1fr)]":"md:grid-cols-1"}`,children:[f&&C?c.jsxs(c.Fragment,{children:[m?c.jsx("button",{type:"button","aria-label":"Close catalog",className:"fixed inset-0 z-40 bg-black/35 backdrop-blur-[2px]",onClick:()=>x(!1)}):null,c.jsxs("aside",{id:b,ref:w,role:m?"dialog":void 0,"aria-modal":m?"true":void 0,"aria-label":m?"Data catalog":void 0,onClick:O=>{m&&O.target.closest("[data-catalog-metric], [data-catalog-dimension]")&&x(!1)},onChange:()=>m&&x(!1),className:"fixed inset-y-0 left-0 z-50 min-h-0 w-[min(88vw,320px)] overflow-y-auto bg-surface shadow-[var(--shadow)] md:static md:z-auto md:w-auto md:border-r md:border-line md:shadow-none",children:[m?c.jsxs("div",{"data-testid":"catalog-drawer-header",className:"sticky top-0 z-10 flex items-center justify-between border-b border-line bg-surface px-4 py-3",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-sm font-semibold text-ink",children:"Catalog"}),c.jsx("p",{className:"text-xs text-muted",children:"Choose a model and fields"})]}),c.jsx("button",{type:"button","aria-label":"Close catalog",onClick:()=>x(!1),className:"grid size-10 place-items-center rounded-full bg-surface-soft text-muted hover:bg-line hover:text-ink",children:c.jsx("span",{"aria-hidden":"true",className:"text-xl leading-none",children:"×"})})]}):null,i]})]}):null,c.jsxs("main",{className:"relative min-h-0 min-w-0 overflow-hidden",children:[c.jsx("div",{className:`h-full overflow-y-auto ${u?"pb-8":""}`,children:a}),u]})]})]})}function rS({dashboardTitle:n,modelLabel:e,onHome:t}){const i=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-sm font-semibold text-ink",children:n??"Sidemantic"}),n===void 0&&e?c.jsx("span",{className:"truncate text-2xs text-faint",children:e}):null]});return n!==void 0?c.jsx("span",{className:"flex min-w-0 items-baseline gap-2",children:i}):c.jsx("button",{type:"button",onClick:t,"aria-label":"Home",className:"flex min-w-0 items-baseline gap-2",children:i})}const sS=new Set(["second","minute","hour","day","week","month","quarter","year"]);function il(n){return n===void 0?[]:Array.isArray(n)?n:[n]}function ol(n,e){return n.models.flatMap(t=>t.dimensions).find(t=>e===t.ref||e.startsWith(`${t.ref}__`))}function iS(n,e){const t=n.split("__").at(-1);return t&&sS.has(t)?t:e}function oS(n){var a;const e=(a=n.defaults)==null?void 0:a.query;if(!e||typeof e!="object")return;const t=e,i=t.use_preaggregations??t.usePreaggregations;return typeof i=="boolean"?i:void 0}function aS(n,e){var u;const t=(u=n.defaults)==null?void 0:u.query,i=t&&typeof t=="object"?t:{},a=e.query.interaction_preaggregations??e.query.interactionPreaggregations??e.interaction_preaggregations??e.interactionPreaggregations??i.interaction_preaggregations??i.interactionPreaggregations;return typeof a=="boolean"?a:void 0}function Cs(n,e,t){var T,E,I,U,G,V,Q;if(!(e!=null&&e.tabs.length))return null;const i=e.tabs.find(z=>z.id===t)??e.tabs[0],a=i.charts[0];if(!a)return null;const u=il(a.query.dimensions),f=il(a.query.metrics),h=f.map(z=>{var ee;return(ee=n.graphMetrics.find(X=>X.ref===z))==null?void 0:ee.ownerModel}).find(z=>!!z),m=((T=f.find(z=>z.includes(".")))==null?void 0:T.split(".")[0])??h??((E=u.find(z=>z.includes(".")))==null?void 0:E.split(".")[0]),g=n.models.find(z=>z.name===m)??n.models[0];if(!g)return null;const v=[...n.models.flatMap(z=>z.metrics),...ji(n,g.name)],x=f.map(z=>v.find(ee=>ee.ref===z)).filter(z=>!!z),b=u.map(z=>ol(n,z)).filter((z,ee,X)=>!!z&&X.findIndex(ie=>(ie==null?void 0:ie.ref)===(z==null?void 0:z.ref))===ee),w=(I=a.encoding)==null?void 0:I.y,C=(Array.isArray(w)?w:w?[w]:[]).find(z=>x.some(ee=>ee.ref===z))??((U=x[0])==null?void 0:U.ref)??((G=g.metrics[0])==null?void 0:G.ref)??"",O=(V=a.encoding)==null?void 0:V.x,H=(O&&((Q=ol(n,O))==null?void 0:Q.type)==="time"?O:void 0)??u.find(z=>{var ee;return((ee=ol(n,z))==null?void 0:ee.type)==="time"}),L=g.defaultGrain??"month",R=H?ol(n,H):g.timeDimension;return{id:i.id,label:i.label??i.id,title:a.title??e.title,model:g,metrics:x.length?x:g.metrics,dimensions:b.length?b:g.dimensions,timeDimension:R,selectedMetric:C,grain:H?iS(H,L):L,filters:il(a.query.filters),segments:il(a.query.segments),usePreaggregations:aS(e,a)??a.query.use_preaggregations??a.query.usePreaggregations??oS(e)}}const Fd=["second","minute","hour","day","week","month","quarter","year"];function lS(n,e){if(n!=null&&n.length){const i=new Set(n.map(u=>u.toLowerCase())),a=Fd.filter(u=>i.has(u));if(a.length)return a}const t=["day","week","month","quarter","year"];return e&&!t.includes(e)?Fd.filter(i=>i===e||t.includes(i)):t}function Ni(n){return n.toISOString().slice(0,10)}function nf(n){return n.slice(0,10)}function Oi(n){const e=n.trim();return/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:/[zZ]|[+-]\d{2}:?\d{2}$/.test(e)?e:`${e.replace(" ","T")}Z`}function Fs(n){return new Date(`${nf(n)}T00:00:00Z`)}function Uo(n,e){const t=Fs(n);return t.setUTCDate(t.getUTCDate()+e),Ni(t)}function uS(n){return Math.round((Fs(n.to).getTime()-Fs(n.from).getTime())/864e5)+1}function cS(n){if(n.from.includes("T")||n.to.includes("T")){const a=Date.parse(Oi(n.from)),f=Date.parse(Oi(n.to))-a;return{from:new Date(a-f).toISOString().slice(0,19),to:new Date(a).toISOString().slice(0,19)}}const e=uS(n),t=Uo(n.from,-1);return{from:Uo(t,-(e-1)),to:t}}function Rm(n){if(n.includes("T")){const f=new Date(Oi(n)),h=f.getUTCFullYear()-1,m=f.getUTCMonth(),g=new Date(Date.UTC(h,m+1,0)).getUTCDate();return new Date(Date.UTC(h,m,Math.min(f.getUTCDate(),g),f.getUTCHours(),f.getUTCMinutes(),f.getUTCSeconds())).toISOString().slice(0,19)}const e=Fs(n),t=e.getUTCFullYear()-1,i=e.getUTCMonth(),a=e.getUTCDate(),u=new Date(Date.UTC(t,i+1,0)).getUTCDate();return Ni(new Date(Date.UTC(t,i,Math.min(a,u))))}function dS(n){return{from:Rm(n.from),to:Rm(n.to)}}function fS(n,e){const t=n.trim(),i=t.slice(0,10);if(e!=="second"&&e!=="minute"&&e!=="hour")return i||n;const a=t.slice(10).match(/(\d{2}):(\d{2})(?::(\d{2}))?/);if(!a)return i||n;const u=e==="second"&&a[3]?`${a[1]}:${a[2]}:${a[3]}`:`${a[1]}:${a[2]}`;return`${i} ${u}`}const hS=[{key:"7d",label:"Last 7 days",days:7},{key:"28d",label:"Last 28 days",days:28},{key:"90d",label:"Last 90 days",days:90},{key:"180d",label:"Last 180 days",days:180},{key:"365d",label:"Last 12 months",days:365}];function pS(n,e=new Date){const t=Ni(e);return{from:Uo(t,-(n-1)),to:t}}function mS(n,e){return e.from.includes("T")||e.to.includes("T")?[`${n} >= cast('${e.from}' as timestamp)`,`${n} < cast('${e.to}' as timestamp)`]:[`${n} >= cast('${e.from}' as date)`,`${n} < cast('${Uo(e.to,1)}' as date)`]}function Lm(n,e,t){if(t==="second"||t==="minute"||t==="hour"){const f=t==="second"?1e3:t==="minute"?6e4:36e5;return Math.round((Date.parse(Oi(e))-Date.parse(Oi(n)))/f)}const i=Fs(n),a=Fs(e),u=(a.getUTCFullYear()-i.getUTCFullYear())*12+(a.getUTCMonth()-i.getUTCMonth());switch(t){case"week":return Math.round((a.getTime()-i.getTime())/(7*864e5));case"month":return u;case"quarter":return Math.round(u/3);case"year":return a.getUTCFullYear()-i.getUTCFullYear();default:return Math.round((a.getTime()-i.getTime())/864e5)}}function ld(n,e){return new Date(Date.parse(Oi(n))+e).toISOString().slice(0,19)}function yS(n,e){const t=nf(n),i=Fs(t);switch(e){case"second":return ld(n,1e3);case"minute":return ld(n,6e4);case"hour":return ld(n,36e5);case"day":return t;case"week":return Uo(n,6);case"month":return Ni(new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth()+1,0)));case"quarter":{const a=Math.floor(i.getUTCMonth()/3)*3+3;return Ni(new Date(Date.UTC(i.getUTCFullYear(),a,0)))}case"year":return Ni(new Date(Date.UTC(i.getUTCFullYear(),12,0)));default:return n}}function rf(n){return n.mode==="contains"?!n.pattern:n.values.length===0}function sf(n){return Object.fromEntries(n.map(e=>[e.ref,e.type]))}function ou(n){return sf(n.models.flatMap(e=>e.dimensions))}function Um(n,e){if((e==="numeric"||e==="number")&&n.trim()!==""&&Number.isFinite(Number(n)))return n;if(e==="boolean"){const t=n.toLowerCase();if(t==="true"||t==="false")return t}return Tn(n)}function Iv(n){return n.replaceAll("\\","\\\\").replaceAll("%","\\%").replaceAll("_","\\_")}function gS(n,e,t){const i=e.mode==="exclude",a=e.values.includes(er),u=e.values.filter(h=>h!==er);let f=null;if(u.length===1)f=`${n} ${i?"!=":"="} ${Um(u[0],t)}`;else if(u.length>1){const h=u.map(m=>Um(m,t)).join(", ");f=`${n} ${i?"NOT IN":"IN"} (${h})`}if(!i){const h=[];return f&&h.push(f),a&&h.push(`${n} IS NULL`),h.length===0?null:h.length===1?h[0]:`(${h.join(" OR ")})`}if(a){const h=[];return f&&h.push(f),h.push(`${n} IS NOT NULL`),h.length===1?h[0]:`(${h.join(" AND ")})`}return f?`(${f} OR ${n} IS NULL)`:null}function Mv(n,e={}){var i;const t=[];for(const[a,u]of Object.entries(n)){if(a===e.excludeDim||rf(u))continue;const f=(i=e.types)==null?void 0:i[a];if(u.mode==="contains"){const m=Tn(`%${Iv(u.pattern??"")}%`);t.push(`CAST(${a} AS VARCHAR) ILIKE ${m} ESCAPE '\\'`);continue}const h=gS(a,u,f);h&&t.push(h)}return t}function Os(n,e={}){const t=Mv(n,{types:e.types,excludeDim:e.excludeDim});return e.timeRef&&e.range&&t.push(...mS(e.timeRef,e.range)),t}function $m(n,e,t,i){return{metrics:n,filters:e,...t!=null&&t.length?{segments:t}:{},...i!=null?{usePreaggregations:i}:{}}}const vS={second:2e3,minute:2e3,hour:9600,day:4e3,week:800,month:240,quarter:120,year:60};function Pm(n,e,t,i,a,u,f=!1){const h=`${e}__${t}`,m=t==="second"||t==="minute",g=m&&!f;return{metrics:n,dimensions:[h],filters:i,...a!=null&&a.length?{segments:a}:{},...u!=null?{usePreaggregations:u}:{},orderBy:[`${h} ${g?"DESC":"ASC"}`],...!m||g?{limit:vS[t]??2e3}:{}}}function zm(n,e,t,i=6,a,u){return{metrics:[n],dimensions:[e],filters:t,...a!=null&&a.length?{segments:a}:{},...u!=null?{usePreaggregations:u}:{},orderBy:[`${n} DESC`],limit:i}}function xS(n,e,t=50,i,a){return{dimensions:[n],filters:e,...i!=null&&i.length?{segments:i}:{},...a!=null?{usePreaggregations:a}:{},orderBy:[`${n} ASC`],limit:t}}function bS(n,e,t,i,a=500){return{metrics:n,dimensions:e,filters:t,orderBy:i,limit:a}}function wS(n,e,t=50,i,a){return{dimensions:n.dimensions,metrics:n.metrics,filters:e,...i!=null&&i.length?{segments:i}:{},...a!=null?{usePreaggregations:a}:{},ungrouped:!0,limit:t}}function SS(n,e){const t=n??[];return t.includes(e)?t.filter(i=>i!==e):[...t,e]}function al(n,e,t){const i={...n};return rf(t)?delete i[e]:i[e]=t,i}function _S(n,e){switch(e.type){case"hydrate":return e.state;case"setView":return{...n,view:e.view};case"setDashboardTab":return{...n,view:"explore",dashboardTab:e.tab,model:e.model,selectedMetric:e.metric,grain:e.grain,filters:{},dateRange:void 0,pivotDims:[],pivotMetrics:[]};case"setModel":return{...n,model:e.model,selectedMetric:e.metric,grain:e.grain,filters:{},pivotDims:[],pivotMetrics:[]};case"setMetric":return{...n,selectedMetric:e.metric};case"toggleFilter":{const t=n.filters[e.dim],i=e.mode??(t&&t.mode!=="contains"?t.mode:"include"),a=t&&t.mode===i?t.values:[],u=SS(a,e.value);return{...n,filters:al(n.filters,e.dim,{mode:i,values:u})}}case"setFilterMode":{const t=n.filters[e.dim],i={mode:e.mode,values:(t==null?void 0:t.values)??[],pattern:t==null?void 0:t.pattern};return{...n,filters:al(n.filters,e.dim,i)}}case"setFilterPattern":{const t=n.filters[e.dim],i={mode:"contains",values:(t==null?void 0:t.values)??[],pattern:e.pattern};return{...n,filters:al(n.filters,e.dim,i)}}case"removeFilterValue":{const t=n.filters[e.dim];if(!t)return n;const i=t.values.filter(a=>a!==e.value);return{...n,filters:al(n.filters,e.dim,{...t,values:i})}}case"removeFilterDim":{const t={...n.filters};return delete t[e.dim],{...n,filters:t}}case"clearFilters":return{...n,filters:{}};case"setGrain":return{...n,grain:e.grain};case"setTimezone":return{...n,timezone:e.timezone};case"setDateRange":return{...n,dateRange:e.range};case"setContextColumn":return{...n,contextColumn:e.column};case"setComparison":return{...n,comparison:e.comparison,comparisonRange:e.comparison==="custom"?e.range:void 0};case"setPivotDims":return{...n,pivotDims:e.dims};case"setPivotMetrics":return{...n,pivotMetrics:e.metrics};case"reset":return{...e.initial,view:n.view};default:return n}}function NS(n){return n.models.find(e=>e.timeDimension)??n.models[0]}function Dv(n,e){var t,i;return((t=n==null?void 0:n.metrics[0])==null?void 0:t.ref)??(n?(i=ji(e,n.name)[0])==null?void 0:i.ref:void 0)??""}function Cv(n,e,t){const i=Cs(n,e,t),a=(i==null?void 0:i.model)??NS(n),u=(i==null?void 0:i.selectedMetric)??Dv(a,n);return{view:i?"explore":"home",dashboardTab:i==null?void 0:i.id,model:(a==null?void 0:a.name)??"",selectedMetric:u,filters:{},grain:(i==null?void 0:i.grain)??(a==null?void 0:a.defaultGrain)??"month",timezone:"UTC",dateRange:void 0,contextColumn:"none",comparison:"previous",comparisonRange:void 0,pivotDims:[],pivotMetrics:[]}}function jS(n,e,t){const i=new URLSearchParams(t),a=i.get("metric"),u=i.get("grain"),f=a===n.selectedMetric&&e.metrics.some(m=>m.ref===a),h=u===n.grain;return{...n,view:"explore",dashboardTab:e.id,model:e.model.name,selectedMetric:f?n.selectedMetric:e.selectedMetric,grain:h?n.grain:e.grain}}const kS=["home","explore","pivot"],IS=new Set(Fd),MS=new Set(["none","pctTotal","delta","deltaPct"]),DS=new Set(["off","previous","year","custom"]),CS="none",FS="previous",OS="UTC";function TS(n){return n!=null&&/^[A-Za-z][A-Za-z0-9/_+-]{0,63}$/.test(n)}function ud(n){if(n)try{return JSON.parse(n)}catch{return}}function Zl(n){return Array.isArray(n)&&n.every(e=>typeof e=="string")}function ll(n){return n!=null&&/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2})?$/.test(n)&&!Number.isNaN(Date.parse(n))}const AS=new Set(["include","exclude","contains"]);function BS(n){if(Zl(n))return{mode:"include",values:n};if(typeof n!="object"||n===null||Array.isArray(n))return null;const e=n;if(!AS.has(e.mode))return null;const t=e.mode,i=Zl(e.values)?e.values:[],a=typeof e.pattern=="string"?e.pattern:void 0,u={mode:t,values:i,pattern:a};return rf(u)?null:u}function ES(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;const e={};for(const[t,i]of Object.entries(n)){const a=BS(i);a&&(e[t]=a)}return e}function RS(n){const e={};for(const[t,i]of Object.entries(n))e[t]=i.mode==="include"?i.values:i;return e}function LS(n){const e=new URLSearchParams;return e.set("view",n.view),n.dashboardTab&&e.set("tab",n.dashboardTab),n.model&&e.set("model",n.model),n.selectedMetric&&e.set("metric",n.selectedMetric),n.grain&&e.set("grain",n.grain),n.timezone&&n.timezone!==OS&&e.set("tz",n.timezone),n.dateRange&&(e.set("from",n.dateRange.from),e.set("to",n.dateRange.to)),n.contextColumn!==CS&&e.set("ctx",n.contextColumn),n.comparison!==FS&&e.set("cmp",n.comparison),n.comparison==="custom"&&n.comparisonRange&&(e.set("cfrom",n.comparisonRange.from),e.set("cto",n.comparisonRange.to)),Object.keys(n.filters).length&&e.set("filters",JSON.stringify(RS(n.filters))),n.pivotDims.length&&e.set("pdims",JSON.stringify(n.pivotDims)),n.pivotMetrics.length&&e.set("pmetrics",JSON.stringify(n.pivotMetrics)),e.toString()}function US(n,e){const t=new URLSearchParams(n),i={...e},a=t.get("view");a&&kS.includes(a)&&(i.view=a);const u=t.get("tab");u&&(i.dashboardTab=u);const f=t.get("model");f&&(i.model=f);const h=t.get("metric");h&&(i.selectedMetric=h);const m=t.get("grain");m&&IS.has(m)&&(i.grain=m);const g=t.get("tz");TS(g)&&(i.timezone=g);const v=t.get("from"),x=t.get("to");ll(v)&&ll(x)&&Date.parse(v)<=Date.parse(x)&&(i.dateRange={from:v,to:x});const b=t.get("ctx");b&&MS.has(b)&&(i.contextColumn=b);const w=t.get("cmp");w&&DS.has(w)&&(i.comparison=w);const j=t.get("cfrom"),C=t.get("cto");i.comparison==="custom"&&ll(j)&&ll(C)&&Date.parse(j)<=Date.parse(C)&&(i.comparisonRange={from:j,to:C});const O=ES(ud(t.get("filters")));O&&(i.filters=O);const H=ud(t.get("pdims"));Zl(H)&&(i.pivotDims=H);const L=ud(t.get("pmetrics"));return Zl(L)&&(i.pivotMetrics=L),i}const Fv=M.createContext(null);function Vm(n){const e=LS(n);return e?`?${e}`:""}function Wm(n,e,t,i){const a=US(n,i),u=Cs(e,t,a.dashboardTab);return u?jS(a,u,n):a}const Hm=n=>n.startsWith("?")?n.slice(1):n;function $S({catalog:n,backend:e,dashboard:t,initialSearch:i,onSearchChange:a,children:u}){const f=M.useMemo(()=>Cv(n,t),[n,t]),[h,m]=M.useReducer(_S,void 0,()=>{const b=i??(typeof window>"u"?"":window.location.search);return Wm(b,n,t,f)}),g=M.useRef(i);M.useEffect(()=>{i===void 0||i===g.current||(g.current=i,Hm(i)!==Hm(Vm(h))&&m({type:"hydrate",state:Wm(i,n,t,f)}))},[i,h,n,t,f]);const v=M.useRef(a);v.current=a,M.useEffect(()=>{const b=Vm(h),w=v.current;if(w){w(b);return}typeof window>"u"||window.history.replaceState(null,"",`${window.location.pathname}${b}`)},[h]);const x=M.useMemo(()=>({state:h,dispatch:m,catalog:n,backend:e,initial:f,dashboard:t}),[h,n,e,f,t]);return c.jsx(Fv.Provider,{value:x,children:u})}function ls(){const n=M.useContext(Fv);if(!n)throw new Error("useExplorer must be used within ExplorerProvider");return n}const Is={active:0,listeners:new Set};function Ov(){for(const n of Is.listeners)n()}function PS(){Is.active+=1,Ov()}function zS(){Is.active=Math.max(0,Is.active-1),Ov()}function Tv(){return M.useSyncExternalStore(n=>(Is.listeners.add(n),()=>Is.listeners.delete(n)),()=>Is.active>0,()=>!1)}const VS=80;function Zn(n,e){const[t,i]=M.useState({loading:!1}),a=M.useRef(0),u=e?JSON.stringify(e):null;return M.useEffect(()=>{if(!e){i({loading:!1});return}const f=++a.current;i(m=>({result:m.result,loading:!0}));const h=setTimeout(()=>{PS(),n.runQuery(e).then(m=>{f===a.current&&i({result:m,loading:!1})}).catch(m=>{f===a.current&&i({loading:!1,error:m instanceof Error?m.message:String(m)})}).finally(()=>zS())},VS);return()=>clearTimeout(h)},[u,n]),t}const WS=[{mode:"include",label:"Include"},{mode:"exclude",label:"Exclude"},{mode:"contains",label:"Contains"}],HS=50,Gm=200;function Ym(n,e){const[t,i]=M.useState(n);return M.useEffect(()=>{const a=setTimeout(()=>i(n),e);return()=>clearTimeout(a)},[n,e]),t}function Av({dim:n,model:e,onClose:t}){var W,_;const{state:i,dispatch:a,backend:u,catalog:f,dashboard:h}=ls(),m=M.useMemo(()=>Cs(f,h,i.dashboardTab),[f,h,i.dashboardTab]),g=i.filters[n.ref],[v,x]=M.useState((g==null?void 0:g.mode)??"include"),b=M.useMemo(()=>new Set((g==null?void 0:g.mode)!=="contains"?(g==null?void 0:g.values)??[]:[]),[g]),w=M.useRef(null),j=M.useRef(null),C=M.useId(),[O,H]=M.useState(""),L=Ym(O,Gm),R=(g==null?void 0:g.mode)==="contains"?g.pattern??"":"",[T,E]=M.useState(R),I=Ym(T,Gm);M.useEffect(()=>{var te;const F=document.activeElement;return(te=j.current)==null||te.focus(),()=>{var pe;return(pe=F==null?void 0:F.focus)==null?void 0:pe.call(F)}},[]),M.useEffect(()=>{function F(pe){pe.key==="Escape"&&(pe.stopPropagation(),t())}function te(pe){w.current&&!w.current.contains(pe.target)&&t()}return document.addEventListener("keydown",F,!0),document.addEventListener("mousedown",te,!0),()=>{document.removeEventListener("keydown",F,!0),document.removeEventListener("mousedown",te,!0)}},[t]),M.useEffect(()=>{v==="contains"&&I!==R&&a({type:"setFilterPattern",dim:n.ref,pattern:I})},[I,v,n.ref,a]);const U=((W=m==null?void 0:m.timeDimension)==null?void 0:W.ref)??((_=e.timeDimension)==null?void 0:_.ref),G=M.useMemo(()=>ou(f),[f]),V=M.useMemo(()=>{const F=[...(m==null?void 0:m.filters)??[],...Os(i.filters,{timeRef:U,range:i.dateRange,excludeDim:n.ref,types:G})];if(L.trim()){const te=Tn(`%${Iv(L.trim())}%`);F.push(`CAST(${n.ref} AS VARCHAR) ILIKE ${te} ESCAPE '\\'`)}return F},[m,i.filters,U,i.dateRange,n.ref,L,G]),Q=v!=="contains",{result:z,loading:ee,error:X}=Zn(u,Q?xS(n.ref,V,HS,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations):null),ie=Sr(n.ref),ae=M.useMemo(()=>z?z.rows.map(F=>{const te=F[ie];return te==null?er:String(te)}):[],[z,ie]),re=!!z&&z.rows.length>0&&!z.columns.includes(ie),se=Q&&(ee||re);function A(F){x(F),g&&a({type:"setFilterMode",dim:n.ref,mode:F}),F==="contains"&&E(R)}function Y(F){var fe;if(F.key!=="Tab")return;const te=(fe=w.current)==null?void 0:fe.querySelectorAll('button, input, [href], select, textarea, [tabindex]:not([tabindex="-1"])');if(!te||te.length===0)return;const pe=te[0],ne=te[te.length-1];F.shiftKey&&document.activeElement===pe?(F.preventDefault(),ne.focus()):!F.shiftKey&&document.activeElement===ne&&(F.preventDefault(),pe.focus())}return c.jsxs("div",{ref:w,role:"dialog","aria-modal":"true","aria-labelledby":C,onKeyDown:Y,className:"absolute left-0 z-50 mt-1 w-64 border border-line bg-surface p-2 text-2xs shadow-lg",children:[c.jsxs("div",{id:C,className:"mb-2 flex items-baseline justify-between gap-2",children:[c.jsx("span",{className:"truncate font-semibold text-ink",children:n.label}),c.jsx("button",{type:"button","aria-label":"Close filter editor",onClick:t,className:"grid size-4 place-items-center rounded-full bg-surface-soft text-faint hover:bg-line hover:text-ink",children:"×"})]}),c.jsx("div",{role:"group","aria-label":"Filter mode",className:"mb-2 grid grid-cols-3 gap-px border border-line bg-line",children:WS.map(({mode:F,label:te})=>c.jsx("button",{type:"button","aria-pressed":v===F,onClick:()=>A(F),className:`px-1.5 py-1 text-center ${v===F?"bg-accent-soft font-medium text-accent":"bg-surface text-muted hover:bg-surface-soft"}`,children:te},F))}),v==="contains"?c.jsx("input",{ref:j,type:"text","aria-label":`${n.label} contains`,placeholder:"Substring…",value:T,onChange:F=>E(F.target.value),className:"w-full border border-line bg-surface px-1.5 py-1 text-2xs text-ink placeholder:text-faint"}):c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:j,type:"text","aria-label":`Search ${n.label} values`,placeholder:"Search values…",value:O,onChange:F=>H(F.target.value),className:"w-full border border-line bg-surface px-1.5 py-1 text-2xs text-ink placeholder:text-faint"}),c.jsx("div",{className:"mt-2 max-h-56 overflow-y-auto",role:"group","aria-label":`${n.label} values`,children:X?c.jsx("p",{className:"px-1 py-2 text-danger",children:X}):se?c.jsx("div",{className:"space-y-1.5 p-1",children:[0,1,2,3,4].map(F=>c.jsx("div",{className:"skeleton h-4 w-full"},F))}):ae.length===0?c.jsx("p",{className:"px-1 py-2 text-faint",children:"No values"}):ae.map(F=>{const te=b.has(F);return c.jsxs("label",{className:"flex cursor-pointer items-center gap-2 px-1 py-1 hover:bg-surface-soft",children:[c.jsx("input",{type:"checkbox",checked:te,onChange:()=>a({type:"toggleFilter",dim:n.ref,value:F,mode:v}),className:"size-3 accent-[var(--accent)]"}),c.jsx("span",{className:"min-w-0 truncate text-ink",children:rs(F)})]},F)})})]}),c.jsxs("div",{className:"mt-2 flex items-center justify-between border-t border-line pt-2",children:[c.jsx("button",{type:"button",onClick:()=>a({type:"removeFilterDim",dim:n.ref}),className:"text-muted underline-offset-2 hover:text-ink hover:underline",children:"Clear"}),c.jsx("button",{type:"button",onClick:t,className:"border border-line px-2 py-1 text-muted hover:bg-surface-soft",children:"Done"})]})]})}function GS({model:n}){const e=n.dimensions.filter(m=>m.type!=="time"),[t,i]=M.useState(!1),[a,u]=M.useState(null),f=M.useRef(null);M.useEffect(()=>{if(!t)return;function m(v){v.key==="Escape"&&h()}function g(v){a||f.current&&!f.current.contains(v.target)&&h()}return document.addEventListener("keydown",m,!0),document.addEventListener("mousedown",g,!0),()=>{document.removeEventListener("keydown",m,!0),document.removeEventListener("mousedown",g,!0)}},[t,a]);function h(){i(!1),u(null)}return e.length===0?null:c.jsxs("span",{ref:f,className:"relative inline-flex",children:[c.jsx("button",{type:"button","aria-haspopup":"dialog","aria-expanded":t,onClick:()=>t?h():i(!0),className:"inline-flex h-7 shrink-0 items-center rounded-full border border-dashed border-line px-3 text-xs text-muted hover:border-faint hover:text-ink",children:"+ Filter"}),t&&!a?c.jsx("div",{role:"menu","aria-label":"Add a filter for a dimension",className:"absolute left-0 z-50 mt-1 max-h-64 w-48 overflow-y-auto rounded-xl border border-line bg-surface p-1.5 text-2xs shadow-[var(--shadow)]",children:e.map(m=>c.jsx("button",{type:"button",role:"menuitem",onClick:()=>u(m),className:"block w-full truncate px-1.5 py-1 text-left text-muted hover:bg-surface-soft hover:text-ink",children:m.label},m.ref))}):null,t&&a?c.jsx(Av,{dim:a,model:n,onClose:h}):null]})}function cd(n,e){return n.includes(e)?n.filter(t=>t!==e):[...n,e]}function Qm({metric:n,selected:e,multiple:t,onSelect:i}){return c.jsxs("button",{type:"button","data-catalog-metric":n.ref,"data-selected":e||void 0,"aria-pressed":e,title:n.description,onClick:i,className:"flex w-full items-center justify-between gap-2 border-l-2 px-3 py-1 text-left text-xs hover:bg-surface-soft data-[selected=true]:border-l-accent data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent border-l-transparent text-muted",children:[c.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[t?c.jsx("span",{"aria-hidden":"true",className:"w-3 shrink-0 text-center text-accent",children:e?"✓":""}):null,c.jsx("span",{className:"truncate",children:n.label})]}),n.agg?c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:n.agg}):null]})}function YS({dimension:n,selected:e,onSelect:t}){return c.jsxs("button",{type:"button","data-catalog-dimension":n.ref,"data-selected":e||void 0,"aria-pressed":e,title:n.description,onClick:t,className:"flex w-full items-center justify-between gap-2 border-l-2 border-l-transparent px-3 py-1 text-left text-xs text-muted hover:bg-surface-soft data-[selected=true]:border-l-accent data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent",children:[c.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[c.jsx("span",{"aria-hidden":"true",className:"w-3 shrink-0 text-center",children:e?"✓":""}),c.jsx("span",{className:"truncate",children:n.label})]}),c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:n.type==="time"?"time":""})]})}function QS(){const{state:n,dispatch:e,catalog:t}=ls(),i=t.models.find(h=>h.name===n.model),a=ji(t,n.model),u=n.view==="pivot",f=n.pivotMetrics.length?n.pivotMetrics:n.selectedMetric?[n.selectedMetric]:[];return c.jsxs("nav",{"aria-label":"Semantic layer catalog",className:"flex flex-col gap-4 py-3 text-sm",children:[c.jsxs("section",{className:"px-3",children:[c.jsx("h2",{className:"mb-1 text-xs font-medium text-muted",children:"Model"}),c.jsx("select",{"aria-label":"Model",value:n.model,onChange:h=>{var v,x;const m=t.models.find(b=>b.name===h.target.value),g=((v=m==null?void 0:m.metrics[0])==null?void 0:v.ref)??((x=ji(t,h.target.value)[0])==null?void 0:x.ref)??"";e({type:"setModel",model:h.target.value,metric:g,grain:(m==null?void 0:m.defaultGrain)??"month"})},className:"w-full border border-line bg-surface px-2 py-1 text-xs text-ink",children:t.models.map(h=>c.jsx("option",{value:h.name,children:h.label},h.name))})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-1 px-3 text-xs font-medium text-muted",children:"Metrics"}),c.jsx("div",{children:((i==null?void 0:i.metrics)??[]).map(h=>c.jsx(Qm,{metric:h,selected:u?f.includes(h.ref):n.selectedMetric===h.ref,multiple:u,onSelect:()=>e(u?{type:"setPivotMetrics",metrics:cd(f,h.ref)}:{type:"setMetric",metric:h.ref})},h.ref))}),a.length?c.jsxs(c.Fragment,{children:[c.jsx("h3",{className:"mb-1 mt-3 px-3 text-xs font-medium text-muted",children:"Shared metrics"}),c.jsx("div",{children:a.map(h=>c.jsx(Qm,{metric:h,selected:u?f.includes(h.ref):n.selectedMetric===h.ref,multiple:u,onSelect:()=>e(u?{type:"setPivotMetrics",metrics:cd(f,h.ref)}:{type:"setMetric",metric:h.ref})},h.ref))})]}):null]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-1 px-3 text-xs font-medium text-muted",children:"Dimensions"}),u?c.jsx("div",{children:((i==null?void 0:i.dimensions)??[]).map(h=>c.jsx(YS,{dimension:h,selected:n.pivotDims.includes(h.ref),onSelect:()=>e({type:"setPivotDims",dims:cd(n.pivotDims,h.ref)})},h.ref))}):c.jsx("ul",{className:"px-3 text-xs text-muted",children:((i==null?void 0:i.dimensions)??[]).map(h=>c.jsxs("li",{className:"flex items-center justify-between gap-2 py-0.5",title:h.description,children:[c.jsx("span",{className:"truncate",children:h.label}),c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:h.type==="time"?"time":""})]},h.ref))})]})]})}class KS extends M.Component{constructor(){super(...arguments);Mn(this,"state",{})}static getDerivedStateFromError(t){return{error:t}}render(){return this.state.error?c.jsx("div",{className:"p-4",children:c.jsxs("div",{className:"border border-danger/40 bg-surface p-4",children:[c.jsx("p",{className:"text-sm font-semibold text-danger",children:"Something went wrong rendering this view."}),c.jsx("p",{className:"mt-1 break-words text-xs text-muted",children:this.state.error.message}),c.jsxs("div",{className:"mt-3 flex gap-2",children:[c.jsx("button",{type:"button",onClick:()=>this.setState({error:void 0}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Retry"}),c.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Reload"})]})]})}):this.props.children}}const JS=[{key:"off",label:"Off"},{key:"previous",label:"Previous period"},{key:"year",label:"Previous year"},{key:"custom",label:"Custom range"}];function Bv({range:n,disabled:e,onChange:t,comparison:i,comparisonRange:a,onComparisonChange:u}){const f=M.useRef(null),[h,m]=M.useState((n==null?void 0:n.from)??""),[g,v]=M.useState((n==null?void 0:n.to)??""),[x,b]=M.useState((a==null?void 0:a.from)??""),[w,j]=M.useState((a==null?void 0:a.to)??"");function C(){f.current&&(f.current.open=!1)}function O(T){t(T),C()}function H(T){T==="custom"?u("custom",x&&w?{from:x,to:w}:void 0):u(T)}const L=n?`${n.from} → ${n.to}`:"All time",R=!n;return c.jsxs("details",{ref:f,className:"relative text-xs",onToggle:T=>{e&&(T.currentTarget.open=!1)},children:[c.jsxs("summary",{"aria-disabled":e||void 0,tabIndex:e?-1:void 0,onClick:T=>e&&T.preventDefault(),onKeyDown:T=>{e&&(T.key==="Enter"||T.key===" ")&&T.preventDefault()},className:`flex h-7 cursor-pointer items-center gap-1.5 rounded-full border border-line bg-surface px-3 text-ink ${e?"cursor-not-allowed opacity-50":""}`,children:[c.jsx("span",{className:"text-faint",children:"Range"}),c.jsx("span",{className:"tnum",children:L}),c.jsx("span",{"aria-hidden":"true",className:"text-faint",children:"▾"})]}),c.jsxs("div",{className:"absolute right-0 z-50 mt-1 w-64 rounded-xl border border-line bg-surface p-1.5 shadow-[var(--shadow)]",children:[c.jsx("button",{type:"button",onClick:()=>O(void 0),className:"w-full rounded-lg px-2.5 py-1.5 text-left text-xs text-muted hover:bg-surface-soft hover:text-ink",children:"All time"}),c.jsx("div",{className:"grid grid-cols-2",children:hS.map(T=>c.jsx("button",{type:"button",onClick:()=>O(pS(T.days)),className:"rounded-lg px-2.5 py-1.5 text-left text-xs text-muted hover:bg-surface-soft hover:text-ink",children:T.label},T.key))}),c.jsxs("div",{className:"mt-2 px-1 pb-1",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("input",{type:"date","aria-label":"From date",value:h,onChange:T=>m(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"}),c.jsx("span",{className:"text-faint",children:"→"}),c.jsx("input",{type:"date","aria-label":"To date",value:g,onChange:T=>v(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"})]}),c.jsx("button",{type:"button",disabled:!h||!g,onClick:()=>O({from:h,to:g}),className:"mt-1.5 inline-flex h-7 w-full items-center justify-center rounded-full border border-accent bg-accent-soft text-xs font-medium text-accent hover:bg-accent hover:text-surface disabled:pointer-events-none disabled:opacity-50",children:"Apply custom range"})]}),c.jsxs("div",{className:"mt-1 px-1 pb-1","data-testid":"comparison-picker",children:[c.jsx("p",{className:"mb-1 px-1.5 text-2xs text-faint",children:"Compare to"}),c.jsx("div",{className:`grid grid-cols-2 ${R?"opacity-50":""}`,children:JS.map(T=>c.jsx("button",{type:"button",disabled:R,"data-comparison":T.key,"data-active":i===T.key||void 0,onClick:()=>H(T.key),className:"rounded-lg px-2.5 py-1.5 text-left text-xs text-muted hover:bg-surface-soft hover:text-ink data-[active=true]:bg-accent-soft data-[active=true]:text-accent",children:T.label},T.key))}),i==="custom"&&!R?c.jsxs("div",{className:"mt-1.5",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("input",{type:"date","aria-label":"Comparison from date",value:x,onChange:T=>b(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"}),c.jsx("span",{className:"text-faint",children:"→"}),c.jsx("input",{type:"date","aria-label":"Comparison to date",value:w,onChange:T=>j(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"})]}),c.jsx("button",{type:"button",disabled:!x||!w,onClick:()=>u("custom",{from:x,to:w}),className:"mt-1.5 inline-flex h-7 w-full items-center justify-center rounded-full border border-accent bg-accent-soft text-xs font-medium text-accent hover:bg-accent hover:text-surface disabled:pointer-events-none disabled:opacity-50",children:"Apply comparison"})]}):null]})]})]})}function Od(n){const[e,t]=M.useState(!1);if(!("dim"in n))return c.jsxs("span",{"data-dimension":n.dimension,"data-value":n.value,className:"inline-flex max-w-full items-center gap-1 rounded-full bg-surface-soft px-2 py-0.5 text-2xs leading-4 text-muted",children:[c.jsxs("span",{className:"truncate",children:[c.jsxs("span",{className:"text-faint",children:[n.dimensionLabel??n.dimension,":"]})," ",n.value]}),n.onRemove?c.jsx("button",{type:"button","aria-label":`Remove filter ${n.value}`,onClick:n.onRemove,className:"-mr-0.5 px-0.5 text-faint hover:text-ink",children:"×"}):null]});const{dim:i,model:a,filter:u,onRemove:f}=n;return c.jsxs("span",{className:"relative inline-flex max-w-full items-center","data-dimension":i.ref,"data-mode":u.mode,children:[c.jsxs("span",{className:"inline-flex max-w-full items-center gap-1 rounded-full bg-surface-soft px-2 py-0.5 text-2xs leading-4 text-muted",children:[c.jsxs("button",{type:"button","aria-label":`Edit filter ${i.label}`,"aria-haspopup":"dialog","aria-expanded":e,onClick:()=>t(h=>!h),className:"min-w-0 truncate text-left hover:text-ink",children:[c.jsx("span",{className:"text-faint",children:i.label})," ",xb(u)]}),c.jsx("button",{type:"button","aria-label":`Remove filter ${i.label}`,onClick:f,className:"grid size-3.5 shrink-0 place-items-center rounded-full bg-surface-soft text-faint hover:bg-line hover:text-ink",children:"×"})]}),e?c.jsx(Av,{dim:i,model:a,onClose:()=>t(!1)}):null]})}function Td({grain:n,options:e,disabled:t,onChange:i}){return c.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-faint",children:[c.jsx("span",{className:"hidden sm:inline",children:"Grain"}),c.jsx("select",{"aria-label":"Time grain",value:n,disabled:t,onChange:a=>i(a.target.value),className:"h-7 rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50",children:e.map(a=>c.jsx("option",{value:a,children:Le(a)},a))})]})}const qS=["UTC","America/Los_Angeles","America/Denver","America/Chicago","America/New_York","America/Sao_Paulo","Europe/London","Europe/Berlin","Europe/Paris","Europe/Moscow","Asia/Dubai","Asia/Kolkata","Asia/Singapore","Asia/Shanghai","Asia/Tokyo","Australia/Sydney"];let ul=null;function Km(){if(ul)return ul;const n=typeof Intl.supportedValuesOf=="function"?Intl.supportedValuesOf("timeZone"):[];return ul=[...new Set(["UTC",...n])].sort(),ul}function ZS(n){if(!n)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:n}),!0}catch{return!1}}function XS(n,e=new Date){var t;try{const u=(((t=new Intl.DateTimeFormat("en-US",{timeZone:n,timeZoneName:"shortOffset"}).formatToParts(e).find(g=>g.type==="timeZoneName"))==null?void 0:t.value)??"").match(/([+-])(\d{1,2})(?::(\d{2}))?/);if(!u)return n==="UTC"?"+00:00":"";const f=u[1],h=u[2].padStart(2,"0"),m=u[3]??"00";return`${f}${h}:${m}`}catch{return""}}const Jm="__search__";function e_({timezone:n,disabled:e,onChange:t}){const i=M.useId(),[a,u]=M.useState(!1),[f,h]=M.useState(""),m=M.useMemo(()=>{const b=new Set(qS);return n&&b.add(n),[...b]},[n]),g=M.useMemo(()=>a?Km():[],[a]);function v(b){const w=b.trim();ZS(w)&&(t(w),u(!1),h(""))}if(a)return c.jsxs("label",{className:"flex items-center gap-1.5 text-2xs text-faint",children:[c.jsx("span",{className:"hidden sm:inline",children:"Zone"}),c.jsx("input",{type:"text",list:i,autoFocus:!0,"aria-label":"Search timezone",placeholder:"Region/City…",value:f,disabled:e,onChange:b=>{h(b.target.value),Km().includes(b.target.value)&&v(b.target.value)},onKeyDown:b=>{b.key==="Enter"?v(f):b.key==="Escape"&&(u(!1),h(""))},onBlur:()=>{u(!1),h("")},className:"h-7 w-36 rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50"}),c.jsx("datalist",{id:i,children:g.map(b=>c.jsx("option",{value:b},b))})]});const x=XS(n);return c.jsxs("label",{className:"flex items-center gap-1.5 text-2xs text-faint",children:[c.jsx("span",{className:"hidden sm:inline",children:"Zone"}),c.jsxs("select",{"aria-label":"Timezone",value:n,disabled:e,onChange:b=>{b.target.value===Jm?u(!0):t(b.target.value)},className:"h-7 max-w-[11rem] rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50",children:[m.map(b=>c.jsxs("option",{value:b,children:[b,b==="UTC"?"":x&&b===n?` (${x})`:""]},b)),c.jsx("option",{value:Jm,children:"Search…"})]})]})}function t_(n,e,t){if(t==="count")return n.length;const i=n.map(u=>typeof u[e]=="number"?u[e]:Number(u[e])).filter(Number.isFinite);if(i.length===0)return Number.NaN;if(t==="min")return Math.min(...i);if(t==="max")return Math.max(...i);const a=i.reduce((u,f)=>u+f,0);return t==="avg"?a/i.length:a}const n_={sum:"Σ",avg:"avg",min:"min",max:"max",count:"n"};function Ho({columns:n,rows:e,loading:t,sortKey:i,sortDir:a,onSort:u,renderCell:f,pageSize:h=50,searchable:m,totals:g,stickyHeader:v=!0}){const[x,b]=M.useState(0),[w,j]=M.useState(""),C=M.useMemo(()=>{const I=w.trim().toLowerCase();return!m||!I?e:e.filter(U=>n.some(G=>String(U[G.key]??"").toLowerCase().includes(I)))},[e,n,w,m]),{paginate:O,pageCount:H,safePage:L,start:R,visibleRows:T}=mb(C,x,h);M.useEffect(()=>{b(0)},[e,h,i,a,w]);const E=g&&n.some(I=>g[I.key]);return c.jsxs("div",{children:[m?c.jsxs("div",{className:"mb-2 flex items-center justify-end gap-2",children:[w?c.jsxs("span",{className:"whitespace-nowrap text-2xs text-faint tnum",children:[C.length.toLocaleString()," of ",e.length.toLocaleString()]}):null,c.jsx("input",{type:"search","aria-label":"Search rows",placeholder:"Search…",value:w,onChange:I=>j(I.target.value),className:"h-7 w-full max-w-64 rounded-full border border-line bg-surface px-2.5 text-xs text-ink placeholder:text-faint"})]}):null,c.jsx("div",{className:"overflow-auto border border-line bg-surface",children:c.jsxs("table",{className:"w-max min-w-full border-collapse text-xs","data-testid":"pivot-table",children:[c.jsx("thead",{children:c.jsx("tr",{className:"bg-surface-soft",children:n.map(I=>{const U=i===I.key;return c.jsx("th",{className:`max-w-80 whitespace-nowrap border-b border-line bg-surface-soft px-3 py-1.5 font-semibold text-faint ${I.numeric?"min-w-32 text-right":"min-w-40 text-left"} ${v?"sticky top-0 z-10":""}`,children:I.sortable&&u?c.jsxs("button",{type:"button",onClick:()=>u(I.key),"aria-label":`Sort by ${I.label}${U?`, currently ${a==="asc"?"ascending":"descending"}`:""}`,className:`table-sort inline-flex max-w-full items-center gap-1 whitespace-nowrap hover:text-ink ${U?"text-ink":""}`,children:[c.jsx("span",{className:"truncate",children:I.label}),c.jsx("span",{"aria-hidden":"true",className:"text-[9px]",children:U?a==="asc"?"▲":"▼":"↕"})]}):c.jsx("span",{className:"block truncate",title:I.label,children:I.label})},I.key)})})}),c.jsx("tbody",{children:t&&C.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:n.length,className:"px-3 py-6 text-center text-faint",children:"Loading…"})}):C.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:n.length,className:"px-3 py-6 text-center text-faint",children:w?"No matching rows":"No rows"})}):T.map((I,U)=>c.jsx("tr",{className:"hover:bg-surface-soft",children:n.map(G=>{const V=f(G,I[G.key]);return c.jsx("td",{className:`max-w-80 whitespace-nowrap border-b border-line px-3 py-1.5 text-muted ${G.numeric?"min-w-32 text-right font-mono tnum text-ink":"min-w-40"}`,children:c.jsx("span",{className:"block max-w-80 truncate",title:V,children:V})},G.key)})},R+U))}),E&&C.length>0?c.jsx("tfoot",{children:c.jsx("tr",{className:"bg-surface-soft","data-testid":"table-totals",children:n.map(I=>{const U=g==null?void 0:g[I.key];if(!U)return c.jsx("td",{className:"border-t border-line px-3 py-1.5"},I.key);const G=t_(C,I.key,U),V=U==="count"?G.toLocaleString():Number.isFinite(G)?f(I,G):"—";return c.jsxs("td",{"data-total":U,className:`whitespace-nowrap border-t border-line px-3 py-1.5 font-mono tnum font-medium text-ink ${I.numeric?"text-right":"text-left"}`,children:[c.jsx("span",{"aria-hidden":"true",className:"mr-1 text-2xs text-faint",children:n_[U]}),V]},I.key)})})}):null]})}),O?c.jsxs("div",{"data-testid":"pivot-table-pager",className:"mt-1.5 flex items-center justify-between gap-3 text-2xs text-faint",children:[c.jsxs("span",{className:"tnum",children:[R+1,"–",Math.min(R+h,C.length)," of ",C.length.toLocaleString(),t?" · Updating…":""]}),c.jsxs("div",{className:"flex gap-1",children:[c.jsx("button",{type:"button",disabled:L===0,onClick:()=>b(I=>Math.max(0,I-1)),className:"table-pager-button px-2 py-1 text-muted hover:text-ink disabled:cursor-not-allowed disabled:opacity-40",children:"Prev"}),c.jsx("button",{type:"button",disabled:L>=H-1,onClick:()=>b(I=>Math.min(H-1,I+1)),className:"table-pager-button px-2 py-1 text-muted hover:text-ink disabled:cursor-not-allowed disabled:opacity-40",children:"Next"})]})]}):null]})}function r_(n,e){const t=e.filter(i=>n.some(a=>a.ref===i));return t.length?t:n.slice(0,6).map(i=>i.ref)}function s_(){var L,R;const[n,e]=M.useState(!1),{state:t,catalog:i,backend:a,dashboard:u}=ls(),f=i.models.find(T=>T.name===t.model),h=M.useMemo(()=>Cs(i,u,t.dashboardTab),[i,u,t.dashboardTab]),m=(h==null?void 0:h.dimensions)??(f==null?void 0:f.dimensions)??[],g=r_(m,t.pivotDims),v=((L=h==null?void 0:h.timeDimension)==null?void 0:L.ref)??((R=f==null?void 0:f.timeDimension)==null?void 0:R.ref),x=M.useMemo(()=>ou(i),[i]),b=M.useMemo(()=>[...(h==null?void 0:h.filters)??[],...Os(t.filters,{timeRef:v,range:t.dateRange,types:x})],[h,t.filters,v,t.dateRange,x]),w=n&&f?wS({dimensions:g,metrics:[]},b,50,h==null?void 0:h.segments,h==null?void 0:h.usePreaggregations):null,{result:j,loading:C,error:O}=Zn(a,w),H=[...g.map(T=>{var E;return{key:Sr(T),label:((E=m.find(I=>I.ref===T))==null?void 0:E.label)??Le(T)}})];return c.jsxs("section",{"data-testid":"row-preview-drawer","data-open":n||void 0,className:"absolute inset-x-0 bottom-0 z-30 border-t border-line bg-surface shadow-[0_-8px_24px_rgba(0,0,0,0.16)]",children:[c.jsxs("button",{type:"button","aria-expanded":n,onClick:()=>e(T=>!T),className:"flex h-8 w-full items-center justify-between px-3 text-left text-xs font-medium text-muted hover:bg-surface-soft hover:text-ink",children:[c.jsx("span",{children:"Rows preview"}),c.jsx("span",{"aria-hidden":"true",children:n?"▼":"▲"})]}),n?c.jsx("div",{className:"max-h-[45vh] overflow-auto border-t border-line",children:O?c.jsx("p",{role:"alert",className:"p-3 text-xs text-danger",children:O}):H.length===0?c.jsx("p",{className:"p-3 text-xs text-faint",children:"No preview fields are available."}):c.jsx(Ho,{columns:H,rows:(j==null?void 0:j.rows)??[],loading:C,pageSize:10,renderCell:(T,E)=>E==null||E===""?"—":String(E)})}):null]})}function of({tone:n,title:e,message:t}){const i=n==="danger";return c.jsx("div",{className:`grid min-h-[200px] place-items-center border bg-surface p-6 text-center ${i?"border-danger/40":"border-line"}`,"data-state":n,role:i?"alert":"status","aria-live":i?"assertive":"polite",children:c.jsxs("div",{className:"max-w-md",children:[n==="loading"?c.jsx("span",{"aria-hidden":"true",className:"motion-safe:animate-pulse inline-block size-2 rounded-full bg-accent"}):null,e?c.jsx("h3",{className:`text-sm font-semibold ${i?"text-danger":"text-ink"}`,children:e}):null,c.jsx("p",{className:`mt-1 text-xs ${i?"text-danger":"text-muted"}`,children:t})]})})}function af({title:n="Loading",message:e="Loading metrics…"}){return c.jsx(of,{tone:"loading",title:n,message:e})}function Xn({title:n="No results",message:e}){return c.jsx(of,{tone:"muted",title:n,message:e})}function Bi({title:n="Query failed",message:e}){return c.jsx(of,{tone:"danger",title:n,message:e})}function dd({status:n}){const e=n==="ok"?"bg-success":n==="loading"?"bg-faint animate-pulse":"bg-line";return c.jsx("span",{"aria-hidden":"true",className:`inline-block size-2 rounded-full ${e}`})}const Ev="sidemantic-theme";function lf(){var e;const n=localStorage.getItem(Ev);return n==="light"||n==="dark"?n:(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}function Rv(n){document.documentElement.dataset.theme=n}function i_(){Rv(lf())}function o_(){const n=lf()==="dark"?"light":"dark";return localStorage.setItem(Ev,n),Rv(n),n}function $o(){const[n,e]=M.useState(lf());return c.jsx("button",{type:"button","aria-label":n==="dark"?"Switch to light theme":"Switch to dark theme",title:n==="dark"?"Light theme":"Dark theme",onClick:()=>e(o_()),className:"grid size-7 place-items-center border border-line bg-surface text-faint hover:border-faint hover:text-ink",children:n==="dark"?c.jsxs("svg",{viewBox:"0 0 24 24",className:"size-3.5",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[c.jsx("circle",{cx:"12",cy:"12",r:"4"}),c.jsx("path",{d:"M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"})]}):c.jsx("svg",{viewBox:"0 0 24 24",className:"size-3.5",fill:"none",stroke:"currentColor",strokeWidth:"2",children:c.jsx("path",{d:"M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"})})})}const _o=[{key:"explore",label:"Explore"},{key:"pivot",label:"Pivot"}];function Lv({view:n,onChange:e}){const t=M.useRef(null);function i(a){const u=Math.max(0,_o.findIndex(h=>h.key===n)),f=_o[(u+a+_o.length)%_o.length];e(f.key),window.requestAnimationFrame(()=>{var h,m;return(m=(h=t.current)==null?void 0:h.querySelector(`[data-view="${f.key}"]`))==null?void 0:m.focus()})}return c.jsx("div",{ref:t,role:"tablist","aria-label":"View",className:"inline-flex items-center gap-0.5 rounded-full border border-line bg-surface p-px",children:_o.map(a=>c.jsx("button",{role:"tab",type:"button","aria-selected":n===a.key,tabIndex:n===a.key?0:-1,"data-view":a.key,"data-selected":n===a.key||void 0,onClick:()=>e(a.key),onKeyDown:u=>{u.key==="ArrowLeft"?(u.preventDefault(),i(-1)):u.key==="ArrowRight"&&(u.preventDefault(),i(1))},className:"inline-flex h-6 items-center rounded-full px-2.5 text-xs font-medium text-muted hover:bg-surface-soft hover:text-ink data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent",children:a.label},a.key))})}const Uv="dashboard_filters",$v="dashboard_ranges",Pv="dashboard_filter_sources",zv="dashboard_range_sources",Vv="dashboard_chart_filters",Wv="dashboard_chart_ranges";function a_(n,e){if(n==="/explore")return!0;const t=new URLSearchParams(e).get("view");return t==="explore"||t==="pivot"}function uf(n,e){var i,a;if(!e||!(n.query.dimensions??[]).includes(e))return!1;const t=(i=n.interactions)==null?void 0:i.select;return t===!0?!0:t?!((a=t.fields)!=null&&a.length)||t.fields.includes(e):!1}function l_(n){return(n.query.dimensions??[]).find(e=>uf(n,e))}function u_(n,e){var i,a;if(!e||!(n.query.dimensions??[]).includes(e))return!1;const t=(i=n.interactions)==null?void 0:i.brush;return t===!0?!0:!t||t.channel&&t.channel!=="x"?!1:!((a=t.fields)!=null&&a.length)||t.fields.includes(e)}function Xl(n){return n==null?er:String(n)}function c_(n){let e=n.trim().replaceAll(/[^A-Za-z0-9_]/g,"_").replaceAll(/^_+|_+$/g,"")||"field";return/^\d/.test(e)&&(e=`field_${e}`),e}function xr(n,e){const t=Sr(n),i=c_(n);return i!==t&&e.includes(i)?i:e.includes(t)?t:e.find(a=>a.endsWith(t))??t}function d_(n){var t;const e=(t=n.encoding)==null?void 0:t.y;return Array.isArray(e)&&e.length?e:typeof e=="string"?[e]:n.query.metrics.slice(0,1)}function f_(n,e,t,i,a){return Object.fromEntries([[e,t],...i.map((u,f)=>[u,a[f]])].filter(u=>typeof u[1]=="string"&&uf(n,u[0])))}function h_(n,e,t){return[e,...t].some(i=>uf(n,i))}const p_=new Set(["second","minute","hour","day","week","month","quarter","year"]);function Ms(n){const e=n.lastIndexOf("__");if(e<0)return null;const t=n.slice(e+2);return p_.has(t)?{baseDimension:n.slice(0,e),grain:t}:null}function Hv(n,e){var u,f;if(n.type&&n.type!=="auto")return n.type;const t=((u=n.encoding)==null?void 0:u.x)??((f=n.query.dimensions)==null?void 0:f[0])??"",i=Ms(t);return(e[t]??(i?e[i.baseDimension]:void 0))==="time"?"line":"bar"}function Gv(n,e){const t=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/.test(n)?`${n}Z`:n,i=new Date(t);return Number.isFinite(i.getTime())?(e==="second"?i.setUTCSeconds(i.getUTCSeconds()+1):e==="minute"?i.setUTCMinutes(i.getUTCMinutes()+1):e==="hour"?i.setUTCHours(i.getUTCHours()+1):e==="day"?i.setUTCDate(i.getUTCDate()+1):e==="week"?i.setUTCDate(i.getUTCDate()+7):e==="month"?i.setUTCMonth(i.getUTCMonth()+1):e==="quarter"?i.setUTCMonth(i.getUTCMonth()+3):e==="year"&&i.setUTCFullYear(i.getUTCFullYear()+1),/^\d{4}-\d{2}-\d{2}$/.test(n)?i.toISOString().slice(0,10):i.toISOString()):null}function Yv(n,e){const t=Ms(n);if(t){const i=Gv(e.to,t.grain);return i?`${t.baseDimension} >= ${Tn(e.from)} AND ${t.baseDimension} < ${Tn(i)}`:`${t.baseDimension} >= ${Tn(e.from)} AND ${t.baseDimension} <= ${Tn(e.to)}`}return`${n} >= ${Tn(e.from)} AND ${n} <= ${Tn(e.to)}`}function m_(n,e,t){const i=Ms(n);return i?e===er?[`${i.baseDimension} IS NULL`]:[Yv(n,{from:e,to:e})]:Mv({[n]:{mode:"include",values:[e]}},{types:t})}function eu(n,e){const t=n.tabs.find(i=>i.charts.includes(e));return`${(t==null?void 0:t.id)??"dashboard"}:${e.id}`}function cf(n,e,t){var f,h,m,g,v;const i=((h=(f=n.defaults)==null?void 0:f.interactions)==null?void 0:h.scope)??"dashboard";if(i==="dashboard")return t;if(i==="chart"){const x=eu(n,e);return{filters:{...Object.fromEntries(Object.entries(t.filters).filter(([b])=>t.filterSources[b]===x)),...((m=t.chartFilters)==null?void 0:m[x])??{}},ranges:{...Object.fromEntries(Object.entries(t.ranges).filter(([b])=>t.rangeSources[b]===x)),...((g=t.chartRanges)==null?void 0:g[x])??{}}}}const a=((v=n.tabs.find(x=>x.charts.includes(e)))==null?void 0:v.charts)??[e],u=new Set(a.flatMap(x=>x.query.dimensions??[]));return{filters:Object.fromEntries(Object.entries(t.filters).filter(([x])=>u.has(x))),ranges:Object.fromEntries(Object.entries(t.ranges).filter(([x])=>u.has(x)))}}function y_(n,e,t,i,a={},u={filterSources:{},rangeSources:{}}){var b,w,j,C,O,H;const f=cf(n,e,{filters:t,ranges:a,...u}),h=((b=e.encoding)==null?void 0:b.x)??((w=e.query.dimensions)==null?void 0:w[0])??"",m=e.query.order_by??e.query.orderBy,g=h&&["line","area"].includes(Hv(e,i))?[`${h} ASC`]:void 0,v={metrics:e.query.metrics,dimensions:e.query.dimensions,filters:[...e.query.filters??[],...Object.entries(f.filters).flatMap(([L,R])=>m_(L,R,i)),...Object.entries(f.ranges).map(([L,R])=>Yv(L,R))],segments:e.query.segments,orderBy:m??g,limit:e.query.limit??500},x=e.query.use_preaggregations??e.query.usePreaggregations??((C=(j=n.defaults)==null?void 0:j.query)==null?void 0:C.use_preaggregations)??((H=(O=n.defaults)==null?void 0:O.query)==null?void 0:H.usePreaggregations);return x!==void 0&&(v.usePreaggregations=x),v}function qm(n){const e=/^(\d{4}-\d{2}-\d{2})/.exec(n);return(e==null?void 0:e[1])??null}function Zm(n,e){const t=qm(e.from);if(!t)return null;const i=Ms(n);if(!i){const f=qm(e.to);return f?{from:t,to:f}:null}const a=Gv(e.to,i.grain);if(!a)return null;const u=new Date(a);return u.setUTCMilliseconds(u.getUTCMilliseconds()-1),{from:t,to:u.toISOString().slice(0,10)}}function g_(n,e,t,i={},a){var T,E,I;const u=(T=e.encoding)==null?void 0:T.y,f=(Array.isArray(u)?u[0]:u)??e.query.metrics[0]??"",h=e.query.dimensions??[],m=a==null?void 0:a.graphMetrics.find(U=>U.ref===f),g=f.includes(".")?f.split(".")[0]:((E=h[0])==null?void 0:E.split(".")[0])??(m==null?void 0:m.ownerModel)??(m==null?void 0:m.model)??"",v=cf(n,e,t),x=Object.entries(v.filters).flatMap(([U,G])=>{const V=Ms(U);return V?[{dimension:U,value:G,baseDimension:V.baseDimension}]:[]}),b=Object.fromEntries(Object.entries(v.filters).flatMap(([U,G])=>{const V=Ms(U);return V?G===er?[[V.baseDimension,[G]]]:[]:[[U,[G]]]})),w=new URLSearchParams({view:"explore",model:g,metric:f});Object.keys(b).length&&w.set("filters",JSON.stringify(b));const j=((I=e.encoding)==null?void 0:I.x)??h[0],C=x.find(({baseDimension:U,value:G})=>G!==er&&(!g||U.startsWith(`${g}.`))),O=Object.keys(v.ranges),H=[j,...O].find((U,G,V)=>{if(!U||V.indexOf(U)!==G||!v.ranges[U])return!1;const Q=Ms(U);return((i[U]??(Q?i[Q.baseDimension]:void 0))==="time"||!!Q)&&(!g||U.startsWith(`${g}.`))}),L=H?v.ranges[H]:void 0,R=C?Zm(C.dimension,{from:C.value,to:C.value}):H&&L?Zm(H,L):null;return R&&(w.set("from",R.from),w.set("to",R.to)),`/explore?${w}`}function v_(n,e,t,i){const a=new Map;for(const u of n){const f=Number(u[t]);if(!Number.isFinite(f))continue;const h=i.map(b=>Xl(u[b])),m=JSON.stringify(h),g=h.length?h.map(rs).join(" · "):"Current",v=a.get(m)??{label:g,filterValues:h,data:[]},x=Xl(u[e]);v.data.push({label:rs(x),filterValue:x,value:f}),a.set(m,v)}return[...a.values()]}function x_(n,e,t,i){const a=[],u=new Set,f=new Map;for(const h of n){if(h[e]==null)continue;const m=String(h[e]),g=Number(h[t]);if(!Number.isFinite(g))continue;u.has(m)||(u.add(m),a.push(m));const v=i.map(j=>Xl(h[j])),x=JSON.stringify(v),b=v.length?v.map(rs).join(" · "):"Current",w=f.get(x)??{label:b,values:new Map};w.values.set(m,g),f.set(x,w)}return[...f.values()].map(h=>({label:h.label,points:a.map(m=>({x:m,y:h.values.get(m)??Number.NaN}))}))}function df(n,e){if(typeof n!="object"||n===null||Array.isArray(n))return{};const t={};for(const[i,a]of Object.entries(n))e.has(i)&&typeof a=="string"&&(t[i]=a);return t}function ff(n,e){if(typeof n!="object"||n===null||Array.isArray(n))return{};const t={};for(const[i,a]of Object.entries(n)){if(!e.has(i)||typeof a!="object"||a===null||Array.isArray(a))continue;const u=a;typeof u.from=="string"&&typeof u.to=="string"&&(t[i]={from:u.from,to:u.to})}return t}function tu(n,e){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).filter(t=>e.has(t[0])&&typeof t[1]=="string"))}function Qv(n,e){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).flatMap(([t,i])=>{const a=e.get(t);if(!a)return[];const u=df(i,a);return Object.keys(u).length?[[t,u]]:[]}))}function Kv(n,e){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).flatMap(([t,i])=>{const a=e.get(t);if(!a)return[];const u=ff(i,a);return Object.keys(u).length?[[t,u]]:[]}))}function Jv(n){return new Set(n.tabs.flatMap(e=>e.charts.flatMap(t=>t.query.dimensions??[])))}function qv(n){return new Map(n.tabs.flatMap(e=>e.charts.map(t=>[eu(n,t),new Set(t.query.dimensions??[])])))}function b_(n,e){var j;const t=new URLSearchParams(n),i=((j=e.tabs[0])==null?void 0:j.id)??"",a=t.get("tab"),u=e.tabs.some(C=>C.id===a)?a??i:i;let f,h,m,g,v,x;try{f=JSON.parse(t.get(Uv)??"{}")}catch{f={}}try{h=JSON.parse(t.get($v)??"{}")}catch{h={}}try{m=JSON.parse(t.get(Pv)??"{}")}catch{m={}}try{g=JSON.parse(t.get(zv)??"{}")}catch{g={}}try{v=JSON.parse(t.get(Vv)??"{}")}catch{v={}}try{x=JSON.parse(t.get(Wv)??"{}")}catch{x={}}const b=Jv(e),w=qv(e);return{tab:u,filters:df(f,b),ranges:ff(h,b),filterSources:tu(m,b),rangeSources:tu(g,b),chartFilters:Qv(v,w),chartRanges:Kv(x,w)}}function w_(n,e){var u;const t=new URLSearchParams;n.tab&&n.tab!==((u=e.tabs[0])==null?void 0:u.id)&&t.set("tab",n.tab),Object.keys(n.filters).length&&t.set(Uv,JSON.stringify(n.filters)),Object.keys(n.ranges).length&&t.set($v,JSON.stringify(n.ranges));const i=Object.fromEntries(Object.entries(n.filterSources).filter(([f])=>f in n.filters)),a=Object.fromEntries(Object.entries(n.rangeSources).filter(([f])=>f in n.ranges));return Object.keys(i).length&&t.set(Pv,JSON.stringify(i)),Object.keys(a).length&&t.set(zv,JSON.stringify(a)),Object.keys(n.chartFilters??{}).length&&t.set(Vv,JSON.stringify(n.chartFilters)),Object.keys(n.chartRanges??{}).length&&t.set(Wv,JSON.stringify(n.chartRanges)),t.toString()}function Zv(n){return`sidemantic-dashboard-views:${`${n.schema??"sidemantic.dashboard.v1"}:${n.title}`}`}function S_(n){try{const e=JSON.parse(localStorage.getItem(Zv(n))??"[]");if(!Array.isArray(e))return[];const t=Jv(n);return e.flatMap(i=>{var m;if(typeof i!="object"||i===null||Array.isArray(i))return[];const a=i;if(typeof a.name!="string"||!a.name.trim())return[];if(typeof a.state!="object"||a.state===null||Array.isArray(a.state))return[];const u=a.state,f=n.tabs.some(g=>g.id===u.tab)?String(u.tab):((m=n.tabs[0])==null?void 0:m.id)??"",h=qv(n);return[{name:a.name,state:{tab:f,filters:df(u.filters,t),ranges:ff(u.ranges,t),filterSources:tu(u.filterSources,t),rangeSources:tu(u.rangeSources,t),chartFilters:Qv(u.chartFilters,h),chartRanges:Kv(u.chartRanges,h)}}]})}catch{return[]}}function __(n,e){try{return localStorage.setItem(Zv(n),JSON.stringify(e)),!0}catch{return!1}}function Xm(n){if(n==null)return"";const e=String(n);return/[",\r\n]/.test(e)?`"${e.replaceAll('"','""')}"`:e}function N_(n,e){return[n.map(Xm).join(","),...e.map(t=>n.map(i=>Xm(t[i])).join(","))].join(`\r +`)}function j_(n){var e;return((e=n.label)==null?void 0:e.trim())||n.id}function fd(n,e){return`${n} ${e}${n===1?"":"s"}`}function k_(){const{catalog:n,dispatch:e}=ls(),t=i=>{const a=n.models.find(h=>h.name===i),u=Dv(a,n),f=(a==null?void 0:a.defaultGrain)??"month";e({type:"setModel",model:i,metric:u,grain:f}),e({type:"setView",view:"explore"})};return c.jsxs("div",{className:"mx-auto w-full max-w-5xl p-6",children:[c.jsxs("div",{className:"mb-4",children:[c.jsx("h1",{className:"text-base font-semibold text-ink",children:"Explore"}),c.jsxs("p",{className:"text-2xs text-muted",children:[fd(n.models.length,"model")," · pick one to explore"]})]}),c.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3",children:n.models.map(i=>c.jsxs("button",{type:"button","data-testid":"explore-card","data-model":i.name,onClick:()=>t(i.name),className:"flex min-h-32 flex-col gap-2 rounded-xl border border-line bg-surface p-4 text-left shadow-[var(--shadow-sm)] transition-colors hover:border-line-strong",children:[c.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[c.jsx("span",{className:"truncate text-sm font-medium text-ink",children:i.label}),i.timeDimension?c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:"time series"}):null]}),i.description?c.jsx("p",{className:"line-clamp-2 text-2xs text-muted",children:i.description}):null,c.jsx("div",{className:"mt-auto flex flex-wrap gap-1 pt-1",children:i.metrics.slice(0,3).map(a=>c.jsx("span",{className:"rounded-full bg-surface-soft px-2 py-0.5 text-2xs text-muted",children:a.label},a.ref))}),c.jsxs("div",{className:"text-2xs text-faint",children:[fd(i.metrics.length,"metric")," · ",fd(i.dimensions.length,"dimension")]})]},i.name))})]})}const I_="600px";function M_(n){for(let e=n.parentElement;e;e=e.parentElement){const t=getComputedStyle(e).overflowY;if(t==="auto"||t==="scroll")return e}return null}function D_(n,e,t=I_){if(typeof IntersectionObserver>"u")return e(),()=>{};const i=new IntersectionObserver(a=>{a.some(u=>u.isIntersecting)&&(i.disconnect(),e())},{root:M_(n),rootMargin:t});return i.observe(n),()=>i.disconnect()}const C_={positive:"text-success",negative:"text-danger",neutral:"text-faint"};function Xv({dimension:n,title:e,metricLabel:t,rows:i,selectedValues:a=[],loading:u,formatMetric:f,onToggle:h,contextColumn:m="none",contextOptions:g,onContextColumn:v,collapsedLimit:x=6,expanded:b=!1,onExpandedChange:w,containerRef:j}){const C=new Set(a),O=b?i:i.slice(0,x),H=Math.max(1,...O.map(E=>Math.abs(E.metric))),L=b||i.length>x,R=m!=="none",T=R?"grid-cols-[minmax(0,1fr)_auto_auto]":"grid-cols-[minmax(0,1fr)_auto]";return c.jsxs("section",{ref:j,"data-testid":"dimension-leaderboard","data-dimension":n,"data-expanded":b||void 0,"aria-label":`${e}, ranked by ${t}`,className:"flex min-h-40 flex-col border-b border-r border-line bg-surface data-[expanded=true]:col-span-full",children:[c.jsxs("header",{className:"flex items-center justify-between gap-3 px-3 pb-2 pt-2.5",children:[c.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[c.jsx("h3",{className:"truncate text-sm font-semibold text-ink",children:e}),c.jsxs("p",{className:"sr-only",children:["Ranked by ",t]})]}),g&&v?c.jsx("div",{role:"group","aria-label":"Context column","data-testid":"leaderboard-context-toggle",className:"flex shrink-0 overflow-hidden border border-line text-2xs",children:g.map(E=>c.jsx("button",{type:"button",title:E.title,"aria-pressed":m===E.key,"data-context":E.key,"data-active":m===E.key||void 0,onClick:()=>v(E.key),className:"border-l border-line px-1.5 py-0.5 font-mono text-faint first:border-l-0 hover:bg-surface-soft data-[active=true]:bg-accent-soft data-[active=true]:text-accent",children:E.label},E.key))}):null]}),c.jsx("div",{"data-testid":"leaderboard-rows",children:u&&i.length===0?c.jsx("div",{className:"space-y-2 p-3",children:[0,1,2,3].map(E=>c.jsx("div",{className:"skeleton h-5 w-full"},E))}):i.length===0?c.jsx("p",{className:"px-3 py-4 text-xs text-faint",children:"No values"}):O.map(E=>{var V,Q,z;const I=E.metric<0?"negative":"positive",U=C.has(E.value),G=`${Math.round(Math.abs(E.metric)/H*100)}%`;return c.jsxs("button",{type:"button","data-dimension":n,"data-value":E.value,"data-selected":U||void 0,"data-tone":I,onClick:()=>h==null?void 0:h(E.value),"aria-pressed":U,className:`leaderboard-row relative grid w-full ${T} items-center gap-3 overflow-hidden border-0 bg-transparent px-3 py-1 text-left text-xs text-ink data-[selected=true]:bg-chart-primary-selected`,children:[c.jsx("span",{"aria-hidden":"true",className:`absolute inset-y-0 left-0 ${I==="negative"?"bg-danger-soft":"bg-chart-primary-soft"}`,style:{width:G}}),c.jsx("span",{className:"relative min-w-0 truncate text-muted",children:rs(E.value)}),c.jsx("strong",{className:"relative tnum font-semibold text-ink",children:f(E.metric)}),R?c.jsx("span",{"data-testid":"leaderboard-context","data-tone":((V=E.context)==null?void 0:V.tone)??"neutral",className:`relative w-14 text-right font-mono tnum text-2xs ${C_[((Q=E.context)==null?void 0:Q.tone)??"neutral"]}`,children:((z=E.context)==null?void 0:z.label)??"—"}):null]},`${n}:${E.value}`)})}),L&&!u?c.jsx("button",{type:"button","data-action":b?"leaderboard-back":"leaderboard-expand","aria-expanded":b,onClick:()=>w==null?void 0:w(!b),className:"leaderboard-expand border-0 border-t border-line bg-transparent px-3 py-1 text-left text-xs font-normal text-faint hover:text-accent",children:b?"← All dimensions":`Expand table (${i.length})`}):null]})}const F_=[{key:"none",label:"—",title:"No context column"},{key:"pctTotal",label:"%",title:"Share of total"},{key:"delta",label:"Δ",title:"Absolute change vs comparison period"},{key:"deltaPct",label:"Δ%",title:"Percent change vs comparison period"}],O_=[],T_=[];function A_({dim:n,model:e,timeDimensionRef:t,rankMetric:i,contextColumn:a,metricTotal:u,comparisonRange:f,baseFilters:h=O_,baseSegments:m=T_,usePreaggregations:g,limit:v=6,expanded:x=!1,onExpandedChange:b}){var pe;const{state:w,dispatch:j,backend:C,catalog:O}=ls(),H=M.useRef(null),[L,R]=M.useState(!1);M.useEffect(()=>{if(!(L||!H.current))return D_(H.current,()=>R(!0))},[L]);const T=t??((pe=e.timeDimension)==null?void 0:pe.ref),E=M.useMemo(()=>ou(O),[O]),I=M.useMemo(()=>[...h,...Os(w.filters,{timeRef:T,range:w.dateRange,excludeDim:n.ref,types:E})],[h,w.filters,T,w.dateRange,n.ref,E]),{result:U,loading:G,error:V}=Zn(C,L?zm(i.ref,n.ref,I,v,m,g):null),Q=w.filters[n.ref],z=(Q==null?void 0:Q.mode)==="include"?Q.values:void 0,ee=[i.ref,n.ref],X=Fn(n.ref,ee),ie=a==="delta"||a==="deltaPct",ae=M.useMemo(()=>{if(!U||!U.columns.includes(X))return null;const ne=[];let fe=!1;for(const Te of U.rows){const Ue=Te[X];Ue==null?fe=!0:ne.push(String(Ue))}const Ce=[];return ne.length&&Ce.push(`CAST(${n.ref} AS VARCHAR) IN (${ne.map(Tn).join(", ")})`),fe&&Ce.push(`${n.ref} IS NULL`),Ce.length?Ce.length===1?Ce[0]:`(${Ce.join(" OR ")})`:null},[U,X,n.ref]),re=M.useMemo(()=>ie&&f&&T&&ae?[...h,...Os(w.filters,{timeRef:T,range:f,excludeDim:n.ref,types:E}),ae]:null,[ie,f,T,w.filters,n.ref,E,ae,h]),se=Zn(C,re?zm(i.ref,n.ref,re,v,m,g):null),A=Fn(i.ref,ee),Y=!!U&&U.rows.length>0&&!U.columns.includes(A),W=M.useMemo(()=>{const ne=new Map;if(!se.result||!se.result.columns.includes(A))return ne;for(const fe of se.result.rows){const Ce=fe[X],Te=Ce==null?er:String(Ce);ne.set(Te,Number(fe[A]))}return ne},[se.result,X,A]),_={format:i.format,type:i.type};function F(ne,fe){switch(a){case"pctTotal":return u===void 0?void 0:yb(fe,u);case"delta":return gb(fe,W.get(ne),_);case"deltaPct":return vb(fe,W.get(ne));default:return}}const te=U&&!Y?U.rows.map(ne=>{const fe=ne[X],Ce=fe==null?er:String(fe),Te=Number(ne[A]??0);return{value:Ce,metric:Te,context:F(Ce,Te)}}):[];return V?c.jsx(Bi,{title:n.label,message:V}):c.jsx(Xv,{dimension:n.ref,title:n.label,metricLabel:i.label,rows:te,containerRef:H,loading:!L||G||Y,selectedValues:z,formatMetric:ne=>Wt(ne,_),onToggle:ne=>j({type:"toggleFilter",dim:n.ref,value:ne}),contextColumn:a,contextOptions:F_,onContextColumn:ne=>j({type:"setContextColumn",column:ne}),collapsedLimit:v,expanded:x,onExpandedChange:b})}function Dr(){const[n,e]=M.useState(null);return{tip:n,handlers:i=>({onMouseEnter:a=>e({content:i,x:a.clientX,y:a.clientY}),onMouseMove:a=>e({content:i,x:a.clientX,y:a.clientY}),onMouseLeave:()=>e(null)})}}function rr({tip:n,position:e="fixed",offset:t=12,className:i,style:a}){return n?c.jsx("div",{role:"tooltip",style:{position:e,left:n.x+t,top:n.y+t,pointerEvents:"none",zIndex:50,...a},className:i||"rounded-lg border border-line bg-surface px-2.5 py-1.5 text-xs text-ink shadow-[var(--shadow)]",children:n.content}):null}function os({title:n,rows:e}){return c.jsxs("div",{className:"min-w-28",children:[n?c.jsx("div",{className:"mb-0.5 font-mono text-faint",children:n}):null,e.map((t,i)=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs("span",{className:"flex items-center gap-1 text-muted",children:[t.swatch?c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-sm",style:{background:t.swatch}}):null,t.label]}),c.jsx("span",{className:"font-mono tnum font-medium text-ink",children:t.value})]},i))]})}function e0({values:n,labels:e,height:t=44,ariaLabel:i,formatValue:a=h=>h.toLocaleString(void 0,{maximumFractionDigits:2}),onHover:u,onBrush:f}){const h=M.useRef(null),m=M.useId(),g=M.useRef(null),v=M.useRef(null),[x,b]=M.useState(200),[w,j]=M.useState(null),[C,O]=M.useState(null),[H,L]=M.useState(null);M.useEffect(()=>{const W=h.current;if(!W||typeof ResizeObserver>"u")return;const _=new ResizeObserver(F=>{for(const te of F)b(Math.max(40,te.contentRect.width))});return _.observe(W),()=>_.disconnect()},[]);const R=n.map((W,_)=>({index:_,value:W})).filter(W=>Number.isFinite(W.value));if(R.length<2)return c.jsx("svg",{ref:g,role:"img","aria-label":i||"No trend data",className:"h-11 w-full",viewBox:`0 0 ${x} ${t}`});const T=3,E=Math.min(...R.map(W=>W.value)),U=Math.max(...R.map(W=>W.value))-E||1,G=R.map((W,_)=>({...W,x:T+_/(R.length-1)*(x-T*2),y:T+(1-(W.value-E)/U)*(t-T*2)})),V=G.map(({x:W,y:_})=>`${W.toFixed(1)},${_.toFixed(1)}`).join(" L "),Q=`M ${G[0].x.toFixed(1)},${t-T} L ${V} L ${G.at(-1).x.toFixed(1)},${t-T} Z`,z=G.at(-1),ee=i||`Trend of ${R.length} points, latest ${a(z.value)}`;function X(W){var F;const _=(F=g.current)==null?void 0:F.getBoundingClientRect();return _?Math.max(T,Math.min(x-T,(W.clientX-_.left)/_.width*x)):T}function ie(W){return Math.max(0,Math.min(G.length-1,Math.round((W-T)/(x-T*2)*(G.length-1))))}function ae(W){const _=X(W),F=ie(_),te=G[F];j(F),L({content:`${e!=null&&e[te.index]?`${e[te.index]}: `:""}${a(te.value)}`,x:W.clientX,y:W.clientY}),u==null||u({index:te.index,label:e==null?void 0:e[te.index],value:te.value}),v.current!==null&&O({a:v.current,b:_})}function re(W){if(!f||!(e!=null&&e.length))return;W.currentTarget.setPointerCapture(W.pointerId);const _=X(W);v.current=_,O({a:_,b:_})}function se(W){if(v.current===null||!f||!(e!=null&&e.length))return;W.currentTarget.hasPointerCapture(W.pointerId)&&W.currentTarget.releasePointerCapture(W.pointerId);const _=X(W);if(Math.abs(_-v.current)>6){const F=G[ie(Math.min(v.current,_))],te=G[ie(Math.max(v.current,_))];f({from:e[F.index],to:e[te.index]})}v.current=null,O(null)}function A(){j(null),L(null),u==null||u(null),v.current===null&&O(null)}const Y=w===null?null:G[w];return c.jsxs("span",{ref:h,className:"relative block w-full",children:[c.jsxs("svg",{ref:g,role:"img","aria-label":ee,className:`h-11 w-full overflow-hidden text-chart-primary ${f?"touch-none select-none":""}`,viewBox:`0 0 ${x} ${t}`,preserveAspectRatio:"none",onPointerMove:ae,onPointerDown:re,onPointerUp:se,onPointerCancel:A,onPointerLeave:A,onDoubleClick:()=>f==null?void 0:f(null),children:[c.jsx("defs",{children:c.jsxs("linearGradient",{id:m,x1:"0",y1:"0",x2:"0",y2:"1",children:[c.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:.16}),c.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:0})]})}),c.jsx("path",{d:Q,fill:`url(#${m})`}),c.jsx("path",{d:`M ${V}`,fill:"none",stroke:"currentColor",strokeWidth:1.5,vectorEffect:"non-scaling-stroke"}),C?c.jsx("rect",{x:Math.min(C.a,C.b),y:0,width:Math.abs(C.b-C.a),height:t,fill:"currentColor",opacity:.12}):null,Y?c.jsxs(c.Fragment,{children:[c.jsx("line",{x1:Y.x,x2:Y.x,y1:0,y2:t,stroke:"currentColor",strokeWidth:1,opacity:.45}),c.jsx("circle",{cx:Y.x,cy:Y.y,r:2.5,fill:"currentColor"})]}):c.jsx("circle",{cx:z.x,cy:z.y,r:2.25,fill:"currentColor"})]}),c.jsx(rr,{tip:H})]})}const B_={positive:"text-success",negative:"text-danger",neutral:"text-faint"},E_={positive:"▲",negative:"▼",neutral:"·"};function Nr({metric:n,label:e,value:t,valueText:i,format:a,delta:u,comparison:f,sparkValues:h=[],sparkLabels:m,selected:g,loading:v,onSelect:x,onSparkHover:b,onSparkBrush:w}){const[j,C]=M.useState(null),O=c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[c.jsx("span",{className:"truncate text-xs font-medium text-muted",children:e}),j!=null&&j.label?c.jsx("span",{className:"shrink-0 font-mono text-2xs text-faint",children:j.label}):null]}),c.jsx("div",{className:"font-mono tnum text-[19px] font-semibold leading-tight tracking-tight text-ink",children:v?c.jsx("span",{className:"skeleton inline-block h-6 w-24 align-middle"}):j?pt(j.value,a):i??pt(t,a)}),u||f?c.jsxs("div",{className:"flex items-baseline gap-1 text-2xs",children:[u?c.jsxs("span",{"data-tone":u.tone,className:`font-mono tnum font-medium ${B_[u.tone]}`,children:[c.jsx("span",{"aria-hidden":"true",className:"mr-0.5 text-[8px]",children:E_[u.tone]}),u.label]}):null,f?c.jsx("span",{className:"truncate text-faint",children:f}):null]}):null]}),H="group flex w-full flex-col gap-1.5 overflow-hidden rounded-xl border border-line bg-surface px-3.5 pt-3 text-left shadow-[var(--shadow-sm)] transition-colors hover:border-line-strong data-[selected=true]:border-accent",L=c.jsx("div",{className:"-mx-3.5 mt-auto",children:c.jsx(e0,{values:h,labels:m,onHover:R=>{C(R),b==null||b(R)},onBrush:w,formatValue:R=>pt(R,a)})});return x?c.jsxs("article",{"data-metric":n,"data-selected":g||void 0,className:H,children:[c.jsx("button",{type:"button","data-metric":n,"aria-pressed":!!g,onClick:()=>x(n),className:"-m-1 flex flex-col gap-1 border-0 bg-transparent p-1 text-left transition hover:opacity-75",children:O}),L]}):c.jsxs("article",{"data-metric":n,"data-selected":g||void 0,className:H,children:[O,L]})}const cl=280,qt={top:14,right:18,bottom:26,left:60},ey=["var(--accent)","var(--danger)","#0f9f8f","#d98921","#a66dd4","#3b82c4"];function hd(n){return ey[n%ey.length]}function ty(n,e,t){return Math.min(Math.max(n,e),t)}function Go({points:n,seriesLabel:e="Current",additionalSeries:t=[],comparison:i,formatValue:a,formatAxis:u=a,formatLabel:f=v=>v,comparisonLabel:h="Previous",ariaLabel:m,onBrush:g}){var Fr;const v=M.useRef(null),x=M.useRef(null),b=M.useRef(!1),w=M.useRef(null),[j,C]=M.useState(820),[O,H]=M.useState(null),[L,R]=M.useState(null);M.useEffect(()=>{const ue=v.current;if(!ue)return;const Oe=new ResizeObserver(rt=>{for(const Nt of rt)C(Math.max(320,Nt.contentRect.width))});return Oe.observe(ue),()=>Oe.disconnect()},[]);const T=n.length,E=[{label:e,points:n},...t],I=[...E.flatMap(ue=>ue.points),...i??[]].map(ue=>ue.y).filter(Number.isFinite),U=T<2||I.length===0,G=U?0:Math.min(0,...I),V=U?1:Math.max(...I),Q=V-G||1,z=j-qt.left-qt.right,ee=cl-qt.top-qt.bottom,X=ue=>qt.left+(T<=1?0:ue/(T-1)*z),ie=ue=>qt.top+(1-(ue-G)/Q)*ee,ae=ue=>ty(Math.round((ue-qt.left)/z*(T-1)),0,T-1),re=ue=>{const Oe=[];let rt=[];return ue.forEach((Nt,Un)=>{Number.isFinite(Nt.y)?rt.push(`${X(Un).toFixed(1)},${ie(Nt.y).toFixed(1)}`):rt.length&&(Oe.push(rt.join(" L ")),rt=[])}),rt.length&&Oe.push(rt.join(" L ")),Oe.map(Nt=>`M ${Nt}`).join(" ")},se=U||n.some(ue=>!Number.isFinite(ue.y))?"":`M ${X(0).toFixed(1)},${ie(G).toFixed(1)} L ${n.map((ue,Oe)=>`${X(Oe).toFixed(1)},${ie(ue.y).toFixed(1)}`).join(" L ")} L ${X(T-1).toFixed(1)},${ie(G).toFixed(1)} Z`;function A(ue){var rt;const Oe=(rt=x.current)==null?void 0:rt.getBoundingClientRect();return Oe?ue.clientX-Oe.left:0}function Y(ue){if(U)return;const Oe=A(ue);H(ae(Oe)),b.current&&w.current&&(w.current={a:w.current.a,b:Oe},R({...w.current}))}function W(ue){if(U||!g)return;ue.currentTarget.setPointerCapture(ue.pointerId),b.current=!0;const Oe=A(ue);w.current={a:Oe,b:Oe},R({...w.current})}function _(ue){ue.currentTarget.hasPointerCapture(ue.pointerId)&&ue.currentTarget.releasePointerCapture(ue.pointerId);const Oe=w.current;if(b.current&&Oe&&g){const rt=ae(Math.min(Oe.a,Oe.b)),Nt=ae(Math.max(Oe.a,Oe.b));Nt>rt&&g({from:n[rt].x,to:n[Nt].x})}b.current=!1,w.current=null,R(null)}function F(){H(null),b.current=!1,w.current=null,R(null)}const te=Math.max(1,Math.ceil(T/8)),pe=[V,G+Q*.66,G+Q*.33,G],ne=O!=null&&O>=0&&O{const rt=ue.points[ne];return rt&&Number.isFinite(rt.y)?[{...ue,point:rt,index:Oe}]:[]}),lt=ne!=null?(i==null?void 0:i[ne])??null:null,wt=lt&&Number.isFinite(lt.y)?lt:null,Bs=ne!=null?ty(X(ne),80,j-80):0,xn=Ce&&wt&&wt.y!==0?(Ce.y-wt.y)/Math.abs(wt.y)*100:null,Cr=m??(U?"Time series chart: not enough data to plot.":`Time series chart, ${T} points from ${f(n[0].x)} to ${f(n[T-1].x)}.`);return c.jsxs("div",{className:"relative text-chart-primary",children:[c.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-x-3 gap-y-0.5 px-3 pt-2 text-2xs text-faint",children:[E.map((ue,Oe)=>c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"inline-block h-0.5 w-3",style:{backgroundColor:hd(Oe)}})," ",ue.label]},`${ue.label}-${Oe}`)),i!=null&&i.length?c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"inline-block h-0 w-3 border-t border-dashed border-faint"})," ",h]}):null]}),c.jsx("div",{ref:v,className:"w-full",children:U?c.jsx("div",{className:"grid h-[280px] place-items-center text-xs text-faint",children:"Not enough data to chart."}):c.jsxs("svg",{ref:x,width:j,height:cl,role:"img","aria-label":Cr,className:"block touch-none select-none",onPointerMove:Y,onPointerDown:W,onPointerUp:_,onPointerLeave:F,onPointerCancel:F,onDoubleClick:()=>g==null?void 0:g(null),children:[c.jsx("defs",{children:c.jsxs("linearGradient",{id:"ts-fill",x1:"0",y1:"0",x2:"0",y2:"1",children:[c.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:.18}),c.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:0})]})}),pe.map((ue,Oe)=>c.jsxs("g",{children:[c.jsx("line",{x1:qt.left,x2:j-qt.right,y1:ie(ue),y2:ie(ue),className:"stroke-line"}),c.jsx("text",{x:qt.left-8,y:ie(ue)+3,textAnchor:"end",className:"fill-faint font-mono text-[10px]",children:u(ue)})]},Oe)),i&&i.length>=2?c.jsx("path",{d:re(i),fill:"none",className:"stroke-faint",strokeWidth:1.25,strokeDasharray:"4 3"}):null,se?c.jsx("path",{d:se,fill:"url(#ts-fill)"}):null,E.map((ue,Oe)=>c.jsx("path",{d:re(ue.points),fill:"none",stroke:hd(Oe),strokeWidth:1.75},`${ue.label}-${Oe}`)),L?c.jsx("rect",{x:Math.min(L.a,L.b),y:qt.top,width:Math.abs(L.b-L.a),height:ee,className:"fill-chart-primary",opacity:.12}):null,ne!=null&&Ue.length?c.jsxs("g",{children:[c.jsx("line",{x1:X(ne),x2:X(ne),y1:qt.top,y2:cl-qt.bottom,className:"stroke-faint",strokeDasharray:"3 3"}),wt?c.jsx("circle",{cx:X(ne),cy:ie(wt.y),r:3,className:"fill-faint"}):null,Ue.map(ue=>c.jsx("circle",{cx:X(ne),cy:ie(ue.point.y),r:3.5,fill:hd(ue.index)},`${ue.label}-${ue.index}`))]}):null,n.map((ue,Oe)=>Oe%te===0||Oe===T-1?c.jsx("text",{x:X(Oe),y:cl-8,textAnchor:"middle",className:"fill-faint font-mono text-[10px]",children:f(ue.x)},ue.x):null)]})}),Ue.length&&Te?c.jsxs("div",{className:"pointer-events-none absolute top-8 z-20 -translate-x-1/2 whitespace-nowrap border border-line bg-surface px-2 py-1.5 text-2xs shadow-[var(--shadow)]",style:{left:Bs},children:[c.jsx("div",{className:"mb-0.5 font-mono text-faint",children:f(Te)}),Ue.map(ue=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"text-muted",children:ue.label}),c.jsx("span",{className:"font-mono tnum font-medium text-ink",children:a(ue.point.y)})]},`${ue.label}-${ue.index}`)),wt?c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"text-muted",children:h}),c.jsx("span",{className:"font-mono tnum text-muted",children:a(wt.y)})]}):null,xn!=null?c.jsxs("div",{className:`mt-0.5 text-right font-mono ${xn>0?"text-success":xn<0?"text-danger":"text-faint"}`,children:[xn.toLocaleString(void 0,{maximumFractionDigits:1,signDisplay:"exceptZero"}),"%"]}):null]}):null]})}const R_={positive:"text-success",negative:"text-danger",neutral:"text-faint"};function L_({metric:n,points:e,comparisonPoints:t,total:i,prevTotal:a,hasTime:u,loading:f,activeRange:h,comparisonLabel:m="Prev period",formatLabel:g,onBrush:v}){const x={format:n.format,type:n.type},b=a!==void 0?xy(i,a):null,w=`${n.label} over time. Total ${pt(i,x)}${b?`, ${b.label} versus the ${m.toLowerCase()}`:""}.`;return c.jsxs("section",{className:"flex flex-col gap-2",children:[c.jsxs("header",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-0.5 px-0.5",children:[c.jsx("h2",{className:"text-xs font-medium text-muted",children:n.label}),c.jsx("span",{className:"font-mono tnum text-xl font-semibold text-ink",children:pt(i,x)}),b?c.jsxs("span",{className:`text-xs ${R_[b.tone]}`,children:[b.label," vs ",m.toLowerCase()]}):null,u?null:c.jsx("span",{className:"text-2xs text-faint",children:"No time dimension"}),h?c.jsx("button",{type:"button",onClick:()=>v(null),className:"ml-auto inline-flex h-7 items-center rounded-full border border-line bg-surface px-3 text-xs text-muted hover:border-line-strong hover:text-ink",children:"Reset zoom"}):null]}),u?f&&e.length<2?c.jsx("div",{className:"skeleton h-[280px] w-full"}):c.jsx(Go,{points:e,comparison:t,formatValue:j=>pt(j,x),formatAxis:j=>Wt(j,x),formatLabel:g,comparisonLabel:m,ariaLabel:w,onBrush:v}):null]})}const U_=new Set(["and","as","asc","by","case","cast","count","date_trunc","desc","else","end","from","group","in","is","join","left","limit","not","null","on","or","order","over","partition","select","sum","then","when","where","with"]);function $_(n){const e=[];let t=0;for(;ta).map(([a,u])=>`-- ${a} ${u}`).join(` -`),i=R_(t||"No queries yet.");return c.jsxs("details",{className:"border border-line bg-surface",children:[c.jsx("summary",{className:"cursor-pointer px-3 py-2 text-xs font-medium text-muted",children:"Generated SQL"}),Object.keys(e).length>0?c.jsx("div",{"data-testid":"query-inputs",className:"grid gap-px border-t border-line bg-line sm:grid-cols-2",children:Object.entries(e).map(([a,u])=>u?c.jsxs("section",{className:"min-w-0 bg-surface px-3 py-2 text-2xs",children:[c.jsx("h3",{className:"mb-1 font-semibold text-ink",children:a}),[["Metrics",u.metrics],["Dimensions",u.dimensions],["Filters",u.filters]].map(([f,h])=>h!=null&&h.length?c.jsxs("p",{className:"truncate text-muted",title:h.join(", "),children:[c.jsxs("strong",{className:"font-medium text-faint",children:[f,":"]})," ",h.join(", ")]},f):null)]},a):null)}):null,c.jsx("pre",{"data-testid":"query-debug",className:"max-h-72 overflow-auto whitespace-pre-wrap border-t border-line px-3 py-2 font-mono text-2xs text-muted",children:i.map((a,u)=>Xm[a.kind]?c.jsx("span",{className:Xm[a.kind],"data-token":a.kind,children:a.value},u):a.value)})]})}function L_(n){return{format:n==null?void 0:n.format,type:n==null?void 0:n.type}}function U_(n,e){return n&&e.some(t=>t.ref===n)?n:null}function ey(n,e){return[...n].sort((t,i)=>String(t[e]??"").localeCompare(String(i[e]??"")))}function $_(n,e){return{from:e==="second"||e==="minute"||e==="hour"?n.from.replace(" ","T"):nf(n.from),to:hS(n.to,e)}}function P_(){var Cr,Fr,ue,Oe,rt,Nt,Un,sr,Es,Ei;const{state:n,dispatch:e,catalog:t,backend:i,dashboard:a}=ls(),[u,f]=D.useState(null),h=t.models.find(Se=>Se.name===n.model),m=D.useMemo(()=>Cs(t,a,n.dashboardTab),[t,a,n.dashboardTab]);D.useEffect(()=>{f(null)},[n.dashboardTab,n.model]);const g=(m==null?void 0:m.metrics)??(h==null?void 0:h.metrics)??[],v=new Set(g.map(Se=>Se.ref)),x=ji(t,n.model).filter(Se=>!m||v.has(Se.ref)),b=((Cr=m==null?void 0:m.timeDimension)==null?void 0:Cr.ref)??((Fr=h==null?void 0:h.timeDimension)==null?void 0:Fr.ref),w=g.find(Se=>Se.ref===n.selectedMetric)??x.find(Se=>Se.ref===n.selectedMetric)??g[0],j=!!w&&g.some(Se=>Se.ref===w.ref),C=D.useMemo(()=>{const Se=g.map(bn=>bn.ref);return w&&!j?[...Se,w.ref]:Se},[g,w,j]),O=D.useMemo(()=>ou(t),[t]),H=D.useMemo(()=>[...(m==null?void 0:m.filters)??[],...Os(n.filters,{timeRef:b,range:n.dateRange,types:O})],[m,n.filters,b,n.dateRange,O]),L=D.useMemo(()=>n.comparison==="off"||!n.dateRange?null:n.comparison==="year"?lS(n.dateRange):n.comparison==="custom"?n.comparisonRange??null:aS(n.dateRange),[n.comparison,n.dateRange,n.comparisonRange]),R=D.useMemo(()=>L&&b?[...(m==null?void 0:m.filters)??[],...Os(n.filters,{timeRef:b,range:L,types:O})]:null,[m,n.filters,b,L,O]),T=n.timezone,E=Se=>Se?{...Se,timezone:T}:null,I=Zn(i,C.length?E($m(C,H,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations)):null),U=Zn(i,C.length&&b?E(Pm(C,b,n.grain,H,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations,!!n.dateRange)):null),G=Zn(i,C.length&&R?E($m(C,R,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations)):null),V=Zn(i,w&&b&&R?E(Pm([w.ref],b,n.grain,R,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations,!0)):null),Q=I.error??U.error??G.error??V.error;if(!h)return c.jsx("div",{className:"p-4",children:c.jsx(Xn,{message:"No model available in this semantic layer."})});const z=((m==null?void 0:m.dimensions)??h.dimensions).filter(Se=>Se.type!=="time"),ee=U_(u,z),X=n.comparison==="year"?"Prev year":n.comparison==="custom"?"Comparison":"Prev period",ie=b?`${b}__${n.grain}`:"",ae=ie?[...C,ie]:C,re=w&&ie?[w.ref,ie]:[],se=g[0]?Fn(g[0].ref,C):w?Fn(w.ref,C):null,A=Se=>!Se||!se||Se.columns.includes(se),Y=A(I.result)?(ue=I.result)==null?void 0:ue.rows[0]:void 0,W=A(G.result)?(Oe=G.result)==null?void 0:Oe.rows[0]:void 0,_=A(U.result)?((rt=U.result)==null?void 0:rt.rows)??[]:[],F=w?Fn(w.ref,C):"",te=w?Fn(w.ref,ae):"",pe=w?Fn(w.ref,re):"",ne=ie?Fn(ie,ae):"",fe=ie?Fn(ie,re):"",Ce=ne?ey(_,ne):_,Te=Y&&F?Number(Y[F]):NaN,Ue=W&&F?Number(W[F]):void 0,lt=te?Ce.map(Se=>({x:String(Se[ne]??""),y:Number(Se[te])})):[],wt=fe?ey(((Nt=V.result)==null?void 0:Nt.rows)??[],fe):[],Bs=pe&<.length>0&&wt.length>0?(()=>{const Se=String(wt[0][fe]??""),bn=lt[0].x,cs=new Map;for(const tn of wt)cs.set(Lm(Se,String(tn[fe]??""),n.grain),Number(tn[pe]));return lt.map(tn=>({x:tn.x,y:cs.get(Lm(bn,tn.x,n.grain))??NaN}))})():[];function xn(Se){e(Se?{type:"setDateRange",range:$_(Se,n.grain)}:{type:"setDateRange",range:void 0})}return c.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[Q?c.jsx(Bi,{message:Q}):null,c.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6","data-testid":"metric-totals",children:g.length===0?c.jsx("div",{className:"col-span-full",children:c.jsx(Xn,{message:"This model has no metrics."})}):g.map(Se=>{const bn=Fn(Se.ref,C),cs=Fn(Se.ref,ae),tn=Y?Number(Y[bn]):NaN,ds=W?Number(W[bn]):void 0,Yo=Ce.map(ir=>Number(ir[cs])).filter(Number.isFinite);return c.jsx(Nr,{metric:Se.ref,label:Se.label,valueText:pt(tn,L_(Se)),delta:ds!==void 0?yy(tn,ds):null,sparkValues:Yo,selected:n.selectedMetric===Se.ref,loading:I.loading&&!Y,onSelect:ir=>e({type:"setMetric",metric:ir})},Se.ref)})}),w?c.jsx(B_,{metric:w,points:lt,comparisonPoints:L?Bs:void 0,total:Te,prevTotal:L?Ue:void 0,hasTime:!!b,loading:U.loading,activeRange:n.dateRange,comparisonLabel:X,formatLabel:Se=>uS(Se,n.grain),onBrush:xn}):null,c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(220px,1fr))] gap-0 border-l border-t border-line",children:w&&z.length?z.filter(Se=>ee===null||ee===Se.ref).map(Se=>c.jsx(F_,{dim:Se,model:h,timeDimensionRef:b,rankMetric:w,contextColumn:n.contextColumn,metricTotal:Number.isFinite(Te)?Te:void 0,comparisonRange:L??void 0,baseFilters:m==null?void 0:m.filters,baseSegments:m==null?void 0:m.segments,usePreaggregations:m==null?void 0:m.usePreaggregations,expanded:ee===Se.ref,onExpandedChange:bn=>f(bn?Se.ref:null)},Se.ref)):c.jsx(Xn,{message:"No categorical dimensions to break down."})}),c.jsx(au,{queries:{Totals:(Un=I.result)==null?void 0:Un.sql,Series:(sr=U.result)==null?void 0:sr.sql,Comparison:(Es=G.result)==null?void 0:Es.sql,"Prev series":(Ei=V.result)==null?void 0:Ei.sql}})]})}function z_(){var ie,ae;const{state:n,catalog:e,backend:t}=ls(),i=e.models.find(re=>re.name===n.model),a=(i==null?void 0:i.dimensions)??[],u=ji(e,n.model),f=D.useMemo(()=>[...(i==null?void 0:i.metrics)??[],...u],[i,u]),h=(ie=i==null?void 0:i.timeDimension)==null?void 0:ie.ref,m=re=>a.some(se=>se.ref===re),g=re=>f.some(se=>se.ref===re),v=n.pivotDims.filter(m),x=n.pivotMetrics.filter(g),b=g(n.selectedMetric)?n.selectedMetric:(ae=i==null?void 0:i.metrics[0])==null?void 0:ae.ref,w=x.length?x:b?[b]:[],[j,C]=D.useState(null),O=D.useMemo(()=>sf(a),[a]),H=D.useMemo(()=>Os(n.filters,{timeRef:h,range:n.dateRange,types:O}),[n.filters,h,n.dateRange,O]),L=j??(w[0]?{ref:w[0],dir:"desc"}:null),R=L?[`${L.ref} ${L.dir.toUpperCase()}`]:void 0,T=w.length||v.length?gS(w,v,H,R,500):null,E=T?{...T,timezone:n.timezone}:null,{result:I,loading:U,error:G}=Zn(t,E),V=D.useMemo(()=>new Map(f.map(re=>[re.ref,re])),[f]),Q=D.useMemo(()=>{const re=new Map;for(const se of[...v,...w])re.set(Sr(se),se);return re},[v,w]),z=[...v.map(re=>{var se;return{key:Sr(re),label:((se=a.find(A=>A.ref===re))==null?void 0:se.label)??Le(re),numeric:!1}}),...w.map(re=>{var se;return{key:Sr(re),label:((se=V.get(re))==null?void 0:se.label)??Le(re),numeric:!0,sortable:!0}})];function ee(re){const se=Q.get(re);se&&C(A=>A&&A.ref===se?{ref:se,dir:A.dir==="desc"?"asc":"desc"}:{ref:se,dir:"desc"})}function X(re,se){if(re.numeric){const A=V.get(Q.get(re.key)??"");return pt(se,{format:A==null?void 0:A.format,type:A==null?void 0:A.type})}return se==null||se===""?"—":String(se)}return i?c.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[G?c.jsx(Bi,{message:G}):z.length===0?c.jsx(Xn,{title:"Nothing selected",message:"Pick at least one metric or dimension above."}):c.jsx(Ho,{columns:z,rows:(I==null?void 0:I.rows)??[],loading:U,sortKey:L?Sr(L.ref):void 0,sortDir:L==null?void 0:L.dir,onSort:ee,renderCell:X}),c.jsx(au,{queries:{Pivot:I==null?void 0:I.sql}})]}):c.jsx("div",{className:"p-4",children:c.jsx(Xn,{message:"No model available."})})}const Dn={top:12,right:14,bottom:26,left:44};function V_(n,e,t=4){if(!(e>n))return[n];const i=(e-n)/(t-1);return Array.from({length:t},(a,u)=>n+i*u)}function Zv({data:n,height:e=200,ariaLabel:t,selectedLabel:i,onSelect:a}){const u=D.useRef(null),[f,h]=D.useState(640),{tip:m,handlers:g}=Dr();D.useEffect(()=>{const I=u.current;if(!I||typeof ResizeObserver>"u")return;const U=new ResizeObserver(G=>{for(const V of G)h(Math.max(160,V.contentRect.width))});return U.observe(I),()=>U.disconnect()},[]);const v=n.map(I=>Number.isFinite(I.value)?I.value:0),x=Math.min(0,...v),b=Math.max(0,...v),w=b-x||1,j=f-Dn.left-Dn.right,C=e-Dn.top-Dn.bottom,O=I=>Dn.top+(1-(I-x)/w)*C,H=O(0),L=j/Math.max(n.length,1),R=Math.max(8,Math.min(48,L*.62)),T=V_(x,b,4),E=t||`Bar chart, ${n.length} categories, up to ${Wt(b)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:u,role:"img","aria-label":E,className:"h-[200px] w-full overflow-hidden",viewBox:`0 0 ${f} ${e}`,children:[T.map((I,U)=>{const G=O(I);return c.jsxs("g",{children:[c.jsx("line",{x1:Dn.left,x2:f-Dn.right,y1:G,y2:G,className:"stroke-line"}),c.jsx("text",{x:Dn.left-6,y:G+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(I)})]},U)}),c.jsx("line",{x1:Dn.left,x2:f-Dn.right,y1:H,y2:H,className:"stroke-line"}),n.map((I,U)=>{const G=I.filterValue??I.label,V=v[U]??0,Q=O(V),z=Math.abs(Q-H),ee=Dn.left+L*U+(L-R)/2,X=Math.min(Q,H);return c.jsxs("g",{role:a?"button":void 0,tabIndex:a?0:void 0,"aria-label":a?`Filter to ${I.label}`:void 0,"aria-pressed":a?i===G:void 0,onClick:a?()=>a(G):void 0,onKeyDown:a?ie=>{(ie.key==="Enter"||ie.key===" ")&&a(G)}:void 0,className:a?"cursor-pointer":void 0,children:[c.jsx("rect",{x:ee,y:X,width:R,height:z,"data-label":I.label,"data-value":V,"data-tone":V<0?"negative":"positive",className:i===G?"fill-accent":V<0?"fill-danger":"fill-chart-primary",...g(`${I.label}: ${pt(V)}`)}),c.jsx("text",{x:ee+R/2,y:e-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:I.label.slice(0,8)})]},`${G}-${U}`)})]}),c.jsx(rr,{tip:m})]})}const pd=7;function yn(n){return`var(--viz-${(n%pd+pd)%pd+1})`}function Ts(n,e,t=4){if(!(e>n))return[n];const i=(e-n)/(t-1);return Array.from({length:t},(a,u)=>n+i*u)}function us(n,e,t){if(!n||typeof ResizeObserver>"u")return()=>{};const i=new ResizeObserver(a=>{for(const u of a)t(Math.max(e,u.contentRect.width))});return i.observe(n),()=>i.disconnect()}const Pt={top:12,right:14,bottom:30,left:48};function Xv({points:n,height:e=240,xLabel:t,yLabel:i,formatX:a=Wt,formatY:u=Wt,ariaLabel:f}){const h=D.useRef(null),[m,g]=D.useState(640),{tip:v,handlers:x}=Dr();D.useEffect(()=>us(h.current,200,g),[]);const b=n.filter(z=>Number.isFinite(z.x)&&Number.isFinite(z.y));if(b.length===0)return c.jsx("div",{className:"grid h-[240px] place-items-center text-xs text-faint",children:"No points to chart."});const w=[...new Set(b.map(z=>z.series??""))],j=b.map(z=>z.x),C=b.map(z=>z.y),O=Math.min(...j),H=Math.max(...j),L=Math.min(...C),R=Math.max(...C),T=H-O||1,E=R-L||1,I=m-Pt.left-Pt.right,U=e-Pt.top-Pt.bottom,G=z=>Pt.left+(z-O)/T*I,V=z=>Pt.top+(1-(z-L)/E)*U,Q=f||`Scatter plot, ${b.length} points${t&&i?` of ${i} by ${t}`:""}`;return c.jsxs(c.Fragment,{children:[w.length>1?c.jsx("div",{className:"mb-1 flex flex-wrap items-center gap-3 text-2xs text-faint",children:w.map((z,ee)=>c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-full",style:{background:yn(ee)}}),z||"(default)"]},z||"(default)"))}):null,c.jsxs("svg",{ref:h,role:"img","aria-label":Q,className:"w-full overflow-hidden",style:{height:e},viewBox:`0 0 ${m} ${e}`,children:[Ts(L,R,4).map((z,ee)=>{const X=V(z);return c.jsxs("g",{children:[c.jsx("line",{x1:Pt.left,x2:m-Pt.right,y1:X,y2:X,className:"stroke-line"}),c.jsx("text",{x:Pt.left-6,y:X+3,textAnchor:"end",className:"fill-faint text-[10px]",children:u(z)})]},`y${ee}`)}),Ts(O,H,5).map((z,ee)=>{const X=G(z);return c.jsxs("g",{children:[c.jsx("line",{x1:X,x2:X,y1:Pt.top,y2:e-Pt.bottom,className:"stroke-line"}),c.jsx("text",{x:X,y:e-14,textAnchor:"middle",className:"fill-faint text-[10px]",children:a(z)})]},`x${ee}`)}),t?c.jsx("text",{x:Pt.left+I/2,y:e-2,textAnchor:"middle",className:"fill-muted text-[10px]",children:t}):null,i?c.jsx("text",{x:10,y:Pt.top+U/2,textAnchor:"middle",transform:`rotate(-90 10 ${Pt.top+U/2})`,className:"fill-muted text-[10px]",children:i}):null,b.map((z,ee)=>c.jsx("circle",{cx:G(z.x),cy:V(z.y),r:3.5,fill:yn(w.indexOf(z.series??"")),fillOpacity:.75,"data-x":z.x,"data-y":z.y,"data-label":z.label,...x(c.jsx(os,{title:z.label??z.series,rows:[{label:t??"x",value:a(z.x)},{label:i??"y",value:u(z.y)}]}))},ee))]}),c.jsx(rr,{tip:v})]})}function W_(){const n=Cv();return c.jsx("span",{className:"text-2xs text-faint",children:n?"Querying…":"Live data"})}function md(n,e){for(const i of n.models){const a=i.metrics.find(u=>u.ref===e);if(a)return{format:a.format,type:a.type}}const t=n.graphMetrics.find(i=>i.ref===e);return{format:t==null?void 0:t.format,type:t==null?void 0:t.type}}function H_(n){return sf(n.models.flatMap(e=>e.dimensions))}function G_(n){var t;const e=(t=n.encoding)==null?void 0:t.y;return(Array.isArray(e)?e[0]:e)??n.query.metrics[0]??""}function Y_({chart:n,columns:e,rows:t}){const i=w_(e,t);return c.jsx("a",{href:`data:text/csv;charset=utf-8,${encodeURIComponent(i)}`,download:`${n.id}.csv`,className:"border border-line px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Export CSV"})}function Q_({chart:n,columns:e,rows:t,loading:i,onDrill:a}){const u=e.map(g=>({key:g,label:Le(g),numeric:n.query.metrics.some(v=>xr(v,e)===g)})),f=i_(n),h=f?xr(f,e):void 0,m=!!f;return c.jsxs("div",{className:"border-t border-line bg-surface-soft p-3","data-testid":`chart-details-${n.id}`,children:[c.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[c.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wide text-faint",children:"Drill details"}),m&&f&&h?c.jsxs("span",{className:"text-2xs text-faint",children:["Choose a ",Le(f)," value to filter every chart."]}):null]}),c.jsx(Ho,{columns:u,rows:t,loading:i,pageSize:20,renderCell:(g,v)=>String(v??"—")}),m&&f&&h&&t.length?c.jsx("div",{className:"mt-2 flex flex-wrap gap-1","aria-label":`Drill by ${Le(f)}`,children:t.slice(0,12).map((g,v)=>{const x=Xl(g[h]);return c.jsxs("button",{type:"button",onClick:()=>a(f,x),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-accent hover:text-ink",children:["Filter to ",rs(x)]},`${String(x)}-${v}`)})}):null]})}function K_({document:n,chart:e,catalog:t,backend:i,state:a,setFilters:u,setRange:f}){var z,ee,X,ie,ae,re,se;const[h,m]=D.useState(!1),g=D.useMemo(()=>H_(t),[t]),v=D.useMemo(()=>h_(n,e,a.filters,g,a.ranges,a),[e,n,a,g]),x=Zn(i,v),b=((z=x.result)==null?void 0:z.rows)??[],w=((ee=x.result)==null?void 0:ee.columns)??[],j=e.query.dimensions??[],C=((X=e.encoding)==null?void 0:X.x)??j[0]??"",O=l_(e),H=O[0]??G_(e),L=xr(C,w),R=cf(n,e,a),T=zv(e,g),E=o_(e,C),I=((ie=e.title)==null?void 0:ie.trim())||Le(e.id),U=[(ae=e.encoding)==null?void 0:ae.color,...j.filter(A=>A!==C)].filter((A,Y,W)=>!!A&&W.indexOf(A)===Y),G=c_(e,C,U),V=U.map(A=>xr(A,w));let Q;if(x.loading&&!x.result)Q=c.jsx(af,{title:`Loading ${I}`});else if(x.error)Q=c.jsx(Bi,{title:`Could not load ${I}`,message:x.error});else if(!b.length)Q=c.jsx(Xn,{title:I,message:"The query returned no rows."});else if(j.length)if(T==="scatter"||T==="point"){const A=(re=e.encoding)!=null&&re.color?xr(e.encoding.color,w):V[0];Q=c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3",children:O.map(Y=>{const W=xr(Y,w),_=b.map(F=>({x:Number(F[L]),y:Number(F[W]),label:String(F[L]??""),series:A?String(F[A]??""):void 0}));return c.jsxs("div",{className:"min-w-0",children:[O.length>1?c.jsx("h3",{className:"mb-1 text-2xs font-semibold text-muted",children:Le(Y)}):null,c.jsx(Xv,{points:_,xLabel:Le(C),yLabel:Le(Y),formatY:F=>pt(F,md(t,Y)),ariaLabel:`${I}, ${Le(Y)} by ${Le(C)}, ${_.length} points`})]},Y)})})}else T==="line"||T==="area"?Q=c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3",children:O.map(A=>{const Y=y_(b,L,xr(A,w),V),W=Y[0]??{label:"Current",points:[]},_=md(t,A);return c.jsxs("div",{className:"min-w-0",children:[O.length>1?c.jsx("h3",{className:"mb-1 text-2xs font-semibold text-muted",children:Le(A)}):null,c.jsx(Go,{points:W.points,seriesLabel:W.label,additionalSeries:Y.slice(1),formatValue:F=>pt(F,_),ariaLabel:`${I}, ${Le(A)}, ${Y.length} series and ${W.points.length} buckets`,onBrush:E?F=>f(C,F):void 0})]},A)})}):Q=c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3",children:O.map(A=>{const Y=xr(A,w),W=m_(b,L,Y,V);return W.map((_,F)=>{const te=_.data.slice(0,30),pe=O.length>1||W.length>1,ne=[O.length>1?Le(A):"",W.length>1?_.label:""].filter(Boolean).join(" · ");return c.jsxs("div",{className:"min-w-0",children:[pe?c.jsx("h3",{className:"mb-1 text-2xs font-semibold text-muted",children:ne}):null,c.jsx(Zv,{data:te,ariaLabel:`${I}, ${ne||Le(A)}, ${te.length} categories`,selectedLabel:R.filters[C],onSelect:G?fe=>{u(u_(e,C,fe,U,_.filterValues)),m(!0)}:void 0})]},`${A}-${_.label}-${F}`)})})});else{const A=b[0];Q=c.jsx("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:e.query.metrics.map(Y=>c.jsx(Nr,{metric:Y,label:Le(Y),value:A[xr(Y,w)],format:md(t,Y)},Y))})}return c.jsxs("article",{className:"min-w-0 overflow-hidden border border-line bg-surface","data-testid":"dashboard-chart","data-chart-id":e.id,children:[c.jsxs("header",{className:"flex min-h-12 flex-wrap items-center justify-between gap-2 border-b border-line px-3 py-2",children:[c.jsxs("div",{className:"min-w-0",children:[c.jsx("h2",{className:"truncate text-sm font-semibold text-ink",children:I}),c.jsxs("p",{className:"text-2xs text-faint",children:[Le(H),C?` by ${Le(C)}`:""]})]}),c.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.jsx("button",{type:"button","aria-expanded":h,onClick:()=>m(A=>!A),className:"border border-line px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:h?"Hide details":"Drill details"}),c.jsx("a",{href:p_(n,e,a,g,t),className:"border border-line px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Explore from here"}),c.jsx(Y_,{chart:e,columns:w,rows:b})]})]}),c.jsx("div",{className:"min-h-64 overflow-hidden p-3",children:Q}),h?c.jsx(Q_,{chart:e,columns:w,rows:b,loading:x.loading,onDrill:(A,Y)=>u({[A]:Y})}):null,(se=x.result)!=null&&se.sql?c.jsx("div",{className:"border-t border-line px-3 py-2",children:c.jsx(au,{queries:{Query:x.result.sql}})}):null]})}function J_({document:n,state:e,onLoad:t}){const[i,a]=D.useState(""),[u,f]=D.useState(()=>x_(n)),[h,m]=D.useState(!1);function g(v){f(v),m(!b_(n,v))}return c.jsxs("details",{className:"relative",children:[c.jsx("summary",{className:"cursor-pointer list-none border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Saved views"}),c.jsxs("div",{className:"absolute right-0 z-50 mt-1 w-72 border border-line bg-surface p-3 shadow-[var(--shadow)]",children:[c.jsx("p",{className:"mb-2 text-2xs text-faint",children:"Stored only in this browser. Nothing is written to the server."}),c.jsxs("div",{className:"flex gap-1",children:[c.jsx("input",{value:i,onChange:v=>a(v.target.value),placeholder:"View name","aria-label":"Saved view name",className:"min-w-0 flex-1 border border-line bg-bg px-2 py-1 text-xs text-ink"}),c.jsx("button",{type:"button",disabled:!i.trim(),onClick:()=>{const v=[...u.filter(x=>x.name!==i.trim()),{name:i.trim(),state:e}];g(v),a("")},className:"border border-line px-2 py-1 text-2xs text-muted hover:text-ink disabled:opacity-40",children:"Save"})]}),h?c.jsx("p",{role:"alert",className:"mt-2 text-2xs text-danger",children:"Browser storage is unavailable."}):null,c.jsx("div",{className:"mt-2 flex flex-col gap-1",children:u.length?u.map(v=>c.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-line pt-1",children:[c.jsx("button",{type:"button",onClick:()=>t(v.state),className:"min-w-0 flex-1 truncate text-left text-xs text-muted hover:text-ink",children:v.name}),c.jsx("button",{type:"button","aria-label":`Delete saved view ${v.name}`,onClick:()=>g(u.filter(x=>x.name!==v.name)),className:"text-2xs text-faint hover:text-danger",children:"Delete"})]},v.name)):c.jsx("span",{className:"text-2xs text-faint",children:"No local views yet."})})]})]})}function q_(){const[n,e]=D.useState(!1);return c.jsx("button",{type:"button",title:"Copies the active tab, filters, and brushed ranges. Data is queried live; local saved views are not shared.",onClick:async()=>{await navigator.clipboard.writeText(window.location.href),e(!0),window.setTimeout(()=>e(!1),1200)},className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:n?"Share URL copied":"Copy share URL"})}function Z_({document:n,catalog:e,backend:t}){const[i,a]=D.useState(()=>g_(window.location.search,n)),u=n.tabs.find(b=>b.id===i.tab)??n.tabs[0];D.useEffect(()=>{window.document.title=n.title},[n.title]),D.useEffect(()=>{const b=v_(i,n);window.history.replaceState(null,"",`${window.location.pathname}${b?`?${b}`:""}`)},[n,i]);function f(b,w){var C,O;const j=eu(n,b);if((((O=(C=n.defaults)==null?void 0:C.interactions)==null?void 0:O.scope)??"dashboard")==="chart"){a(H=>{var L;return{...H,chartFilters:{...H.chartFilters??{},[j]:{...((L=H.chartFilters)==null?void 0:L[j])??{},...w}}}});return}a(H=>({...H,filters:{...H.filters,...w},filterSources:{...H.filterSources,...Object.fromEntries(Object.keys(w).map(L=>[L,j]))}}))}function h(b,w,j){var O,H;const C=eu(n,b);if((((H=(O=n.defaults)==null?void 0:O.interactions)==null?void 0:H.scope)??"dashboard")==="chart"){a(L=>{const R={...L.chartRanges??{}},T={...R[C]??{}};return j?T[w]=j:delete T[w],Object.keys(T).length?R[C]=T:delete R[C],{...L,chartRanges:R}});return}a(L=>{const R={...L.ranges},T={...L.rangeSources};return j?(R[w]=j,T[w]=C):(delete R[w],delete T[w]),{...L,ranges:R,rangeSources:T}})}const m=c.jsxs(c.Fragment,{children:[c.jsx(J_,{document:n,state:i,onLoad:a}),c.jsx(q_,{}),c.jsx($o,{}),c.jsx(W_,{})]}),g=Object.entries(i.chartFilters??{}).flatMap(([b,w])=>Object.entries(w).map(([j,C])=>({source:b,dimension:j,value:C}))),v=Object.entries(i.chartRanges??{}).flatMap(([b,w])=>Object.entries(w).map(([j,C])=>({source:b,dimension:j,range:C}))),x=Object.entries(i.filters).length||Object.entries(i.ranges).length||g.length||v.length?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"shrink-0 text-2xs font-semibold uppercase tracking-wide text-faint",children:"Filters"}),Object.entries(i.filters).map(([b,w])=>c.jsxs("button",{type:"button","aria-label":`Remove filter ${Le(b)} ${w}`,onClick:()=>a(j=>{const C={...j.filters},O={...j.filterSources};return delete C[b],delete O[b],{...j,filters:C,filterSources:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(b)," = ",w," ×"]},b)),Object.entries(i.ranges).map(([b,w])=>c.jsxs("button",{type:"button","aria-label":`Remove range ${Le(b)} ${w.from} to ${w.to}`,onClick:()=>a(j=>{const C={...j.ranges},O={...j.rangeSources};return delete C[b],delete O[b],{...j,ranges:C,rangeSources:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(b),": ",w.from,"–",w.to," ×"]},`range-${b}`)),g.map(({source:b,dimension:w,value:j})=>c.jsxs("button",{type:"button","aria-label":`Remove filter ${Le(w)} ${j} from ${b}`,onClick:()=>a(C=>{const O={...C.chartFilters??{}},H={...O[b]??{}};return delete H[w],Object.keys(H).length?O[b]=H:delete O[b],{...C,chartFilters:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(w)," = ",j," · ",b," ×"]},`chart-filter-${b}-${w}`)),v.map(({source:b,dimension:w,range:j})=>c.jsxs("button",{type:"button","aria-label":`Remove range ${Le(w)} ${j.from} to ${j.to} from ${b}`,onClick:()=>a(C=>{const O={...C.chartRanges??{}},H={...O[b]??{}};return delete H[w],Object.keys(H).length?O[b]=H:delete O[b],{...C,chartRanges:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(w),": ",j.from,"–",j.to," · ",b," ×"]},`chart-range-${b}-${w}`)),c.jsx("button",{type:"button",onClick:()=>a(b=>({...b,filters:{},ranges:{},filterSources:{},rangeSources:{},chartFilters:{},chartRanges:{}})),className:"text-2xs text-muted hover:text-ink",children:"Clear all"})]}):void 0;return c.jsx(_v,{brand:c.jsxs("div",{className:"min-w-0",children:[c.jsx("h1",{className:"truncate text-sm font-semibold text-ink",children:n.title}),c.jsx("p",{className:"text-2xs text-faint",children:"Declarative dashboard"})]}),toolbar:m,filters:x,rail:null,showRail:!1,children:c.jsxs("div",{"data-testid":"dashboard-document",className:"flex min-h-full flex-col",children:[c.jsx("nav",{className:"flex shrink-0 gap-1 overflow-x-auto border-b border-line bg-surface px-3 pt-2","aria-label":"Dashboard tabs",children:n.tabs.map(b=>c.jsx("button",{type:"button",role:"tab","aria-selected":b.id===(u==null?void 0:u.id),"data-tab-id":b.id,onClick:()=>a(w=>{var j,C;return w.tab===b.id?w:(((C=(j=n.defaults)==null?void 0:j.interactions)==null?void 0:C.scope)??"dashboard")==="dashboard"?{...w,tab:b.id}:{...w,tab:b.id,filters:{},ranges:{},filterSources:{},rangeSources:{},chartFilters:{},chartRanges:{}}}),className:"border border-b-0 border-line px-3 py-2 text-xs text-muted aria-selected:border-accent aria-selected:bg-bg aria-selected:text-ink",children:S_(b)},b.id))}),u?c.jsx("section",{className:"grid min-w-0 grid-cols-1 gap-3 p-3 xl:grid-cols-2","data-testid":"dashboard-chart-grid","data-tab-id":u.id,children:u.charts.map(b=>c.jsx(K_,{document:n,chart:b,catalog:e,backend:t,state:i,setFilters:w=>f(b,w),setRange:(w,j)=>h(b,w,j)},b.id))}):c.jsx(Xn,{title:"No dashboard tabs",message:"This dashboard document has no tabs to render."})]})})}function ty(){const n=Cv();return c.jsxs("span",{role:"status","aria-live":"polite","aria-atomic":"true",className:"flex items-center gap-1.5 text-2xs text-faint",title:n?"Updating data":"Data is up to date",children:[n?c.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",className:"spinner size-3.5 text-accent",fill:"none",stroke:"currentColor",strokeWidth:"3",children:c.jsx("path",{d:"M12 3a9 9 0 1 0 9 9",strokeLinecap:"round"})}):c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-full bg-accent"}),c.jsx("span",{className:"sr-only",children:n?"Updating data":"Data is up to date"})]})}function X_(){const[n,e]=D.useState(!1);return c.jsx("button",{type:"button",onClick:async()=>{await navigator.clipboard.writeText(window.location.href),e(!0),window.setTimeout(()=>e(!1),1200)},className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:n?"Copied":"Copy link"})}function dl({children:n}){return c.jsx("div",{className:"grid h-screen place-items-center bg-bg p-6",children:n})}function e2({backend:n,onAuthenticated:e}){const[t,i]=D.useState(""),[a,u]=D.useState(null),[f,h]=D.useState(!1);return c.jsxs("div",{className:"w-full max-w-sm border border-line bg-surface p-6 shadow-sm",children:[c.jsx("h1",{className:"text-base font-semibold text-ink",children:"Connect to Sidemantic"}),c.jsx("p",{className:"mt-2 text-xs leading-5 text-muted",children:"Enter the API bearer once. It is exchanged for a short-lived, HttpOnly browser session where supported, and is never placed in the URL or browser storage."}),c.jsxs("form",{className:"mt-5 space-y-3",onSubmit:async m=>{m.preventDefault(),h(!0),u(null);try{await n.createBrowserSession(t),i(""),e()}catch(g){u(g instanceof Error?g.message:String(g))}finally{h(!1)}},children:[c.jsx("label",{className:"block text-xs font-medium text-ink",htmlFor:"api-token",children:"API bearer token"}),c.jsx("input",{id:"api-token",type:"password",autoComplete:"off",required:!0,value:t,onChange:m=>i(m.target.value),className:"w-full border border-line bg-bg px-3 py-2 text-sm text-ink outline-none focus:border-accent"}),a?c.jsx("p",{className:"text-xs text-red-700",children:a}):null,c.jsx("button",{type:"submit",disabled:f||!t,className:"w-full bg-accent px-3 py-2 text-xs font-semibold text-white disabled:opacity-50",children:f?"Connecting…":"Connect"})]})]})}function t2(){const{state:n,dispatch:e,catalog:t,initial:i,dashboard:a}=ls(),u=!!a,f=n.view==="home"&&!u,h=t.models.find(R=>R.name===n.model),m=D.useMemo(()=>Cs(t,a,n.dashboardTab),[t,a,n.dashboardTab]),g=D.useMemo(()=>a?Iv(t,a,n.dashboardTab):i,[t,a,i,n.dashboardTab]),v=n.dateRange!=null||Object.keys(n.filters).length>0,x=(m==null?void 0:m.timeDimension)??(h==null?void 0:h.timeDimension),b=!!x,w=iS(x==null?void 0:x.supportedGranularities,n.grain),j=D.useMemo(()=>{const R=new Map;for(const T of t.models)for(const E of T.dimensions)R.set(E.ref,{dim:E,model:T});return R},[t]),C=Object.entries(n.filters).flatMap(([R,T])=>{const E=j.get(R);return E?[c.jsx(Od,{dim:E.dim,model:E.model,filter:T,onRemove:()=>e({type:"removeFilterDim",dim:R})},R)]:[]}),O=c.jsx(eS,{dashboardTitle:a==null?void 0:a.title,modelLabel:!f&&!u?h==null?void 0:h.label:void 0,onHome:()=>e({type:"setView",view:"home"})}),H=f?c.jsxs(c.Fragment,{children:[c.jsx($o,{}),c.jsx(ty,{})]}):c.jsxs(c.Fragment,{children:[a?c.jsx("div",{className:"flex items-center border border-line bg-surface",role:"tablist","aria-label":"Dashboard tabs",children:a.tabs.map(R=>{const T=R.id===n.dashboardTab;return c.jsx("button",{type:"button",role:"tab","aria-selected":T,className:`px-2 py-1 text-2xs ${T?"bg-accent text-white":"text-muted hover:text-ink"}`,onClick:()=>{const E=Cs(t,a,R.id);E&&e({type:"setDashboardTab",tab:E.id,model:E.model.name,metric:E.selectedMetric,grain:E.grain})},children:R.label??R.id},R.id)})}):c.jsx(Bv,{view:n.view,onChange:R=>e({type:"setView",view:R})}),c.jsx(Ov,{range:n.dateRange,disabled:!b,onChange:R=>e({type:"setDateRange",range:R}),comparison:n.comparison,comparisonRange:n.comparisonRange,onComparisonChange:(R,T)=>e({type:"setComparison",comparison:R,range:T})}),c.jsx(Td,{grain:n.grain,options:w,disabled:!b,onChange:R=>e({type:"setGrain",grain:R})}),c.jsx(qS,{timezone:n.timezone,disabled:!b,onChange:R=>e({type:"setTimezone",timezone:R})}),v?c.jsx("button",{type:"button",onClick:()=>e({type:"reset",initial:g}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Reset"}):null,c.jsx(X_,{}),c.jsx($o,{}),c.jsx(ty,{})]}),L=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"shrink-0 text-xs font-medium text-muted",children:"Filters"}),C.length?C:c.jsx("span",{className:"text-2xs text-faint",children:"None"}),h?c.jsx(VS,{model:h}):null,C.length?c.jsx("button",{type:"button",onClick:()=>e({type:"clearFilters"}),className:"shrink-0 text-2xs text-muted underline-offset-2 hover:text-ink hover:underline",children:"Clear"}):null]});return c.jsx(_v,{brand:O,toolbar:H,filters:f?void 0:L,rail:c.jsx(HS,{}),showRail:!f&&!u,openRailRequest:n.view==="pivot",drawer:f?void 0:c.jsx(t_,{}),children:c.jsxs(GS,{children:[n.view==="home"?c.jsx(__,{}):null,n.view==="explore"?c.jsx(P_,{}):null,n.view==="pivot"?c.jsx(z_,{}):null]},n.view)})}function n2(){const[n,e]=D.useState(!1),t=D.useMemo(()=>new X1({transport:"json",onUnauthorized:()=>e(!0)}),[]),[i,a]=D.useState(null),[u,f]=D.useState(null),[h,m]=D.useState(0),g=s_(window.location.pathname,window.location.search);return D.useEffect(()=>{let v=!0;return Promise.all([t.getCatalog(),g?Promise.resolve(null):t.getDashboard()]).then(([x,b])=>v&&a({catalog:x,dashboard:b})).catch(x=>v&&f(x instanceof Error?x.message:String(x))),()=>{v=!1}},[t,g,h]),n?c.jsx(dl,{children:c.jsx(e2,{backend:t,onAuthenticated:()=>{e(!1),f(null),m(v=>v+1)}})}):u?c.jsx(dl,{children:c.jsx(Bi,{title:"Could not load semantic layer",message:u})}):i?i.catalog.models.length?i.dashboard?c.jsx(Z_,{document:i.dashboard,catalog:i.catalog,backend:t}):c.jsx(RS,{catalog:i.catalog,backend:t,children:c.jsx(t2,{})}):c.jsx(dl,{children:c.jsx(Xn,{title:"Empty semantic layer",message:"No models were found."})}):c.jsx(dl,{children:c.jsx(af,{title:"Loading semantic layer",message:"Reading models and metrics…"})})}const Zt={top:14,right:48,bottom:26,left:48};function r2({data:n,barLabel:e="Bars",lineLabel:t="Line",height:i=220,formatBar:a=pt,formatLine:u=pt,ariaLabel:f}){const h=D.useRef(null),[m,g]=D.useState(640),{tip:v,handlers:x}=Dr();if(D.useEffect(()=>us(h.current,240,g),[]),n.length===0)return c.jsx("div",{className:"grid h-[220px] place-items-center text-xs text-faint",children:"No data to chart."});const b=n.map(ae=>Number.isFinite(ae.bar)?ae.bar:0),w=n.map(ae=>Number.isFinite(ae.line)?ae.line:0),j=Math.min(0,...b),C=Math.max(0,...b),O=C-j||1,H=Math.min(...w),L=Math.max(...w),R=L-H||1,T=m-Zt.left-Zt.right,E=i-Zt.top-Zt.bottom,I=ae=>Zt.top+(1-(ae-j)/O)*E,U=ae=>Zt.top+(1-(ae-H)/R)*E,G=T/n.length,V=Math.max(8,Math.min(48,G*.55)),Q=ae=>Zt.left+G*ae+G/2,z=I(0),ee=n.map((ae,re)=>`${Q(re).toFixed(1)},${U(w[re]).toFixed(1)}`).join(" L "),X=yn(1),ie=f||`Combo chart, ${n.length} categories: ${e} bars with a ${t} line`;return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"mb-1 flex items-center gap-3 text-2xs text-faint",children:[c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block h-2 w-3 bg-chart-primary"})," ",e]}),c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block h-0.5 w-3",style:{background:X}})," ",t]})]}),c.jsxs("svg",{ref:h,role:"img","aria-label":ie,className:"w-full overflow-hidden",style:{height:i},viewBox:`0 0 ${m} ${i}`,children:[Ts(j,C,4).map((ae,re)=>{const se=I(ae);return c.jsxs("g",{children:[c.jsx("line",{x1:Zt.left,x2:m-Zt.right,y1:se,y2:se,className:"stroke-line"}),c.jsx("text",{x:Zt.left-6,y:se+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(ae)})]},re)}),Ts(H,L,4).map((ae,re)=>c.jsx("text",{x:m-Zt.right+6,y:U(ae)+3,textAnchor:"start",className:"text-[10px]",fill:X,children:u(ae)},re)),c.jsx("line",{x1:Zt.left,x2:m-Zt.right,y1:z,y2:z,className:"stroke-line"}),n.map((ae,re)=>{const se=b[re],A=I(se);return c.jsxs("g",{children:[c.jsx("rect",{x:Q(re)-V/2,y:Math.min(A,z),width:V,height:Math.abs(A-z),"data-label":ae.label,"data-bar":se,"data-line":w[re],className:se<0?"fill-danger":"fill-chart-primary",...x(c.jsx(os,{title:ae.label,rows:[{label:e,value:a(se),swatch:"var(--chart-primary)"},{label:t,value:u(w[re]),swatch:X}]}))}),c.jsx("text",{x:Q(re),y:i-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:ae.label.slice(0,8)})]},ae.label)}),c.jsx("path",{d:`M ${ee}`,fill:"none",stroke:X,strokeWidth:1.75}),n.map((ae,re)=>c.jsx("circle",{cx:Q(re),cy:U(w[re]),r:3,fill:X,...x(c.jsx(os,{title:ae.label,rows:[{label:e,value:a(b[re]),swatch:"var(--chart-primary)"},{label:t,value:u(w[re]),swatch:X}]}))},ae.label))]}),c.jsx(rr,{tip:v})]})}const s2={primary:"border-accent bg-accent-soft font-medium text-accent hover:bg-accent hover:text-surface",secondary:"border-line bg-surface text-ink hover:bg-surface-soft",ghost:"border-transparent bg-transparent text-muted hover:bg-surface-soft hover:text-ink",danger:"border-danger bg-danger-soft font-medium text-danger hover:bg-danger hover:text-surface"};function No({variant:n="secondary",size:e="md",type:t="button",className:i,...a}){const u=e==="sm"?"h-6 px-2.5 text-2xs":"h-7 px-3 text-xs";return c.jsx("button",{type:t,"data-variant":n,className:`inline-flex items-center justify-center rounded-full border ${u} ${s2[n]} disabled:pointer-events-none disabled:opacity-50 ${i??""}`,...a})}function i2(n,e){const t=e.trim().toLowerCase();return t?n.filter(i=>i.value.toLowerCase().includes(t)||(i.label??"").toLowerCase().includes(t)):n}function ny(n){const{options:e,placeholder:t="Search…",ariaLabel:i,disabled:a,maxVisible:u=50}=n,f=D.useId(),h=D.useRef(null),[m,g]=D.useState(!1),[v,x]=D.useState(""),[b,w]=D.useState(0),j=D.useMemo(()=>i2(e,v).slice(0,u),[e,v,u]),C=n.multiple?n.values:n.value!=null?[n.value]:[],O=new Set(C),H=I=>{var U;return((U=e.find(G=>G.value===I))==null?void 0:U.label)??I};D.useEffect(()=>{if(!m)return;function I(U){h.current&&!h.current.contains(U.target)&&g(!1)}return document.addEventListener("mousedown",I,!0),()=>document.removeEventListener("mousedown",I,!0)},[m]);function L(I){if(I){if(n.multiple){const U=O.has(I.value)?n.values.filter(G=>G!==I.value):[...n.values,I.value];n.onChange(U);return}n.onChange(I.value),x(""),g(!1)}}function R(){n.multiple?n.onChange([]):n.onChange(null),x("")}function T(I){I.key==="ArrowDown"?(I.preventDefault(),g(!0),w(U=>Math.min(U+1,j.length-1))):I.key==="ArrowUp"?(I.preventDefault(),w(U=>Math.max(U-1,0))):I.key==="Enter"?(I.preventDefault(),m&&L(j[b])):I.key==="Escape"?g(!1):I.key==="Backspace"&&n.multiple&&!v&&n.values.length&&n.onChange(n.values.slice(0,-1))}const E=!n.multiple&&n.value!=null?H(n.value):t;return c.jsxs("div",{ref:h,className:"relative inline-flex min-w-40 flex-wrap items-center gap-1 text-xs",children:[n.multiple?n.values.map(I=>c.jsxs("span",{"data-chip":I,className:"inline-flex items-center gap-1 rounded-full bg-surface-soft px-2 py-0.5 leading-4 text-muted",children:[c.jsx("span",{className:"max-w-32 truncate",children:H(I)}),c.jsx("button",{type:"button","aria-label":`Remove ${H(I)}`,disabled:a,onClick:()=>n.onChange(n.values.filter(U=>U!==I)),className:"text-faint hover:text-ink",children:"×"})]},I)):null,c.jsxs("span",{className:"relative min-w-28 flex-1",children:[c.jsx("input",{type:"text",role:"combobox","aria-expanded":m,"aria-controls":f,"aria-autocomplete":"list","aria-activedescendant":m&&j[b]?`${f}-${b}`:void 0,"aria-label":i,disabled:a,placeholder:E,value:v,onChange:I=>{x(I.target.value),w(0),g(!0)},onFocus:()=>g(!0),onKeyDown:T,className:"h-7 w-full rounded-full border border-line bg-surface px-3 text-ink placeholder:text-faint disabled:opacity-50"}),C.length>0?c.jsx("button",{type:"button","aria-label":"Clear selection",disabled:a,onClick:R,className:"absolute right-1 top-1/2 -translate-y-1/2 px-1 text-faint hover:text-ink",children:"×"}):null]}),m?c.jsxs("ul",{id:f,role:"listbox","aria-multiselectable":n.multiple||void 0,className:"absolute left-0 top-full z-50 mt-1 max-h-56 w-full min-w-40 overflow-y-auto rounded-xl border border-line bg-surface p-1.5 shadow-[var(--shadow)]",children:[j.length===0?c.jsx("li",{className:"px-1.5 py-1 text-faint",children:"No matches"}):null,j.map((I,U)=>c.jsxs("li",{id:`${f}-${U}`,role:"option","aria-selected":O.has(I.value),"data-active":U===b||void 0,onMouseEnter:()=>w(U),onMouseDown:G=>{G.preventDefault(),L(I)},className:"cursor-pointer truncate rounded-md px-2 py-1 text-muted data-[active=true]:bg-surface-soft data-[active=true]:text-ink",children:[I.label??I.value,O.has(I.value)?c.jsx("span",{className:"float-right text-accent",children:"✓"}):null]},I.value))]}):null]})}function o2({title:n,eyebrow:e="Sidemantic",status:t,toolbar:i,children:a}){return c.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-5 text-ink sm:px-6",children:[c.jsxs("header",{className:"flex flex-wrap items-end justify-between gap-4 border-b border-line pb-4",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-xs font-medium text-faint",children:e}),c.jsx("h1",{className:"mt-1 text-2xl font-semibold text-ink",children:n})]}),t?c.jsx("div",{className:"text-sm text-muted",children:t}):null]}),i?c.jsx("section",{className:"flex flex-wrap gap-2 py-3",children:i}):null,c.jsx("section",{className:"grid gap-4 py-4",children:a})]})}const a2=["Su","Mo","Tu","We","Th","Fr","Sa"],ry=["January","February","March","April","May","June","July","August","September","October","November","December"];function e0(n,e,t){return`${String(n).padStart(4,"0")}-${String(e+1).padStart(2,"0")}-${String(t).padStart(2,"0")}`}function l2(n,e){const t=new Date(Date.UTC(n,e,1)),i=new Date(t);i.setUTCDate(1-t.getUTCDay());const a=[],u=new Date(i);do{const f=[];for(let h=0;h<7;h+=1)f.push({iso:e0(u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()),day:u.getUTCDate(),inMonth:u.getUTCMonth()===e}),u.setUTCDate(u.getUTCDate()+1);a.push(f)}while(u.getUTCMonth()===e);return a}function yd(){const n=new Date;return e0(n.getFullYear(),n.getMonth(),n.getDate())}function sy(n){var T;const{inline:e,ariaLabel:t,disabled:i}=n,a=n.mode==="range",u=a?((T=n.value)==null?void 0:T.from)??null:n.value,[f,h]=D.useState(()=>Number((u??yd()).slice(0,4))),[m,g]=D.useState(()=>Number((u??yd()).slice(5,7))-1),[v,x]=D.useState(null),b=D.useRef(null);function w(E){const I=new Date(Date.UTC(f,m+E,1));h(I.getUTCFullYear()),g(I.getUTCMonth())}function j(E){if(!a){n.onChange(E),b.current&&(b.current.open=!1);return}if(!v){x(E);return}const[I,U]=v<=E?[v,E]:[E,v];n.onChange({from:I,to:U}),x(null),b.current&&(b.current.open=!1)}function C(E){return a?v?E===v:n.value!=null&&E>=n.value.from&&E<=n.value.to:E===n.value}function O(E){return a?v?E===v:n.value!=null&&(E===n.value.from||E===n.value.to):E===n.value}const H=yd(),L=c.jsxs("div",{className:"w-56 select-none rounded-xl border border-line bg-surface p-2.5 text-2xs","aria-label":t??"Calendar",children:[c.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[c.jsx("button",{type:"button","aria-label":"Previous month",onClick:()=>w(-1),className:"px-1.5 py-0.5 text-muted hover:bg-surface-soft hover:text-ink",children:"‹"}),c.jsxs("span",{className:"font-medium text-ink",children:[ry[m]," ",f]}),c.jsx("button",{type:"button","aria-label":"Next month",onClick:()=>w(1),className:"px-1.5 py-0.5 text-muted hover:bg-surface-soft hover:text-ink",children:"›"})]}),c.jsx("div",{className:"grid grid-cols-7 text-center text-faint",children:a2.map(E=>c.jsx("span",{className:"py-0.5",children:E},E))}),c.jsx("div",{role:"grid","aria-label":`${ry[m]} ${f}`,children:l2(f,m).map((E,I)=>c.jsx("div",{role:"row",className:"grid grid-cols-7",children:E.map(U=>c.jsx("button",{type:"button",role:"gridcell","aria-selected":C(U.iso),"data-date":U.iso,onClick:()=>j(U.iso),className:`py-1 text-center tnum ${O(U.iso)?"bg-accent text-surface":C(U.iso)?"bg-accent-soft text-accent":U.inMonth?"text-ink hover:bg-surface-soft":"text-faint hover:bg-surface-soft"} ${U.iso===H?"underline underline-offset-2":""}`,children:U.day},U.iso))},I))}),a&&v?c.jsxs("p",{className:"mt-1 text-faint",children:["Start ",v," — pick an end date."]}):null,n.value!=null?c.jsx("button",{type:"button",onClick:()=>n.onChange(null),className:"mt-1 w-full rounded-lg border border-line px-2 py-1 text-left text-muted hover:bg-surface-soft",children:"Clear"}):null]});if(e)return L;const R=a?n.value?`${n.value.from} → ${n.value.to}`:"Any dates":n.value??"Any date";return c.jsxs("details",{ref:b,className:"relative inline-block text-xs",children:[c.jsxs("summary",{className:`flex cursor-pointer items-center h-7 gap-1.5 rounded-full border border-line bg-surface px-3 text-ink ${i?"pointer-events-none opacity-50":""}`,children:[c.jsx("span",{className:"text-faint",children:t??"Date"}),c.jsx("span",{className:"tnum",children:R}),c.jsx("span",{"aria-hidden":"true",className:"text-faint",children:"▾"})]}),c.jsx("div",{className:"absolute left-0 z-50 mt-1 shadow-[var(--shadow)]",children:L})]})}function u2({result:n,pageSize:e=10}){const t=(n==null?void 0:n.columns)??[];return c.jsx(Ho,{columns:t.map(i=>({key:i,label:Le(i),numeric:n==null?void 0:n.sample_rows.some(a=>typeof a[i]=="number")})),rows:(n==null?void 0:n.sample_rows)??[],pageSize:e,renderCell:(i,a)=>pt(a)})}function c2({data:n,height:e=200,ariaLabel:t}){return c.jsx("div",{style:{minHeight:e},children:c.jsx(Go,{points:n.map(({label:i,value:a})=>({x:i,y:a})),formatValue:i=>pt(i),ariaLabel:t})})}const t0=Math.PI*2;function d2(n){const e=n.map((a,u)=>({...a,colorIndex:u})).filter(a=>Number.isFinite(a.value)&&a.value>0),t=e.reduce((a,u)=>a+u.value,0);if(t<=0)return[];let i=-Math.PI/2;return e.map(a=>{const u=a.value/t,f=i;return i+=u*t0,{label:a.label,value:a.value,share:u,startAngle:f,endAngle:i,colorIndex:a.colorIndex}})}function f2(n,e,t,i,a,u){const f=Math.min(u-a,t0-1e-4),h=a+f,m=f>Math.PI?1:0,g=n+i*Math.cos(a),v=e+i*Math.sin(a),x=n+i*Math.cos(h),b=e+i*Math.sin(h),w=n+t*Math.cos(h),j=e+t*Math.sin(h),C=n+t*Math.cos(a),O=e+t*Math.sin(a);return[`M ${g.toFixed(2)} ${v.toFixed(2)}`,`A ${i} ${i} 0 ${m} 1 ${x.toFixed(2)} ${b.toFixed(2)}`,`L ${w.toFixed(2)} ${j.toFixed(2)}`,`A ${t} ${t} 0 ${m} 0 ${C.toFixed(2)} ${O.toFixed(2)}`,"Z"].join(" ")}function h2({data:n,height:e=200,centerLabel:t="Total",format:i=pt,ariaLabel:a}){const u=D.useRef(null),[f,h]=D.useState(360),{tip:m,handlers:g}=Dr();D.useEffect(()=>us(u.current,220,h),[]);const v=d2(n),x=v.reduce((L,R)=>L+R.value,0),b=Math.min(e,f*.55),w=b/2,j=e/2,C=b/2-6,O=Math.max(C*.62,C-34),H=a||`Donut chart, ${v.length} segments totaling ${Wt(x)}`;return v.length===0?c.jsx("div",{className:"grid h-[200px] place-items-center text-xs text-faint",children:"No positive values to chart."}):c.jsxs("div",{ref:u,className:"flex w-full items-center gap-4",style:{height:e},children:[c.jsxs("svg",{role:"img","aria-label":H,width:b,height:e,className:"shrink-0 overflow-hidden",children:[v.map(L=>c.jsx("path",{d:f2(w,j,O,C,L.startAngle,L.endAngle),fill:yn(L.colorIndex),stroke:"var(--surface)",strokeWidth:1,"data-label":L.label,"data-value":L.value,...g(c.jsx(os,{title:L.label,rows:[{label:"Value",value:i(L.value),swatch:yn(L.colorIndex)},{label:"Share",value:`${(L.share*100).toFixed(1)}%`}]}))},L.label)),c.jsx("text",{x:w,y:j-4,textAnchor:"middle",className:"fill-ink font-mono tnum text-sm font-medium",children:Wt(x)}),c.jsx("text",{x:w,y:j+12,textAnchor:"middle",className:"fill-faint text-[10px]",children:t})]}),c.jsx("ul",{className:"min-w-0 flex-1 space-y-1 text-2xs",children:v.map(L=>c.jsxs("li",{className:"flex items-center gap-2","data-label":L.label,children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 shrink-0",style:{background:yn(L.colorIndex)}}),c.jsx("span",{className:"truncate text-muted",children:L.label}),c.jsx("span",{className:"ml-auto font-mono tnum text-ink",children:i(L.value)}),c.jsxs("span",{className:"w-10 text-right font-mono tnum text-faint",children:[(L.share*100).toFixed(1),"%"]})]},L.label))}),c.jsx(rr,{tip:m})]})}const pr={top:8,right:8,bottom:26,left:76};function iy(n,e,t){if(t!=null&&t.length)return t;const i=[];for(const a of n)i.includes(a[e])||i.push(a[e]);return i}function p2({cells:n,xLabels:e,yLabels:t,height:i=240,format:a=pt,ariaLabel:u}){const f=D.useRef(null),[h,m]=D.useState(640),{tip:g,handlers:v}=Dr();D.useEffect(()=>us(f.current,240,m),[]);const x=iy(n,"x",e),b=iy(n,"y",t);if(x.length===0||b.length===0)return c.jsx("div",{className:"grid h-[240px] place-items-center text-xs text-faint",children:"No cells to chart."});const w=new Map(n.map(I=>[`${I.x}\0${I.y}`,I.value])),j=n.map(I=>Math.abs(I.value)).filter(Number.isFinite),C=Math.max(...j,0)||1,O=h-pr.left-pr.right,H=i-pr.top-pr.bottom,L=O/x.length,R=H/b.length,T=Math.max(1,Math.ceil(x.length/Math.max(1,Math.floor(O/56)))),E=u||`Heatmap, ${x.length} by ${b.length} cells`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:f,role:"img","aria-label":E,className:"w-full overflow-hidden",style:{height:i},viewBox:`0 0 ${h} ${i}`,children:[b.map((I,U)=>c.jsx("text",{x:pr.left-6,y:pr.top+U*R+R/2+3,textAnchor:"end",className:"fill-muted text-[10px]",children:I.slice(0,12)},I)),x.map((I,U)=>U%T===0?c.jsx("text",{x:pr.left+U*L+L/2,y:i-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:I.slice(0,8)},I):null),b.map((I,U)=>x.map((G,V)=>{const Q=w.get(`${G}\0${I}`),z=Q!=null&&Number.isFinite(Q),ee=z?.06+.94*(Math.abs(Q)/C):0;return c.jsx("rect",{x:pr.left+V*L+.5,y:pr.top+U*R+.5,width:Math.max(1,L-1),height:Math.max(1,R-1),"data-x":G,"data-y":I,"data-value":z?Q:void 0,className:z&&Q<0?"fill-danger":"fill-chart-primary",fillOpacity:z?ee:.03,...v(c.jsx(os,{title:`${I} / ${G}`,rows:[{label:"Value",value:z?a(Q):"no data"}]}))},`${G}\0${I}`)}))]}),c.jsx(rr,{tip:g})]})}function m2(n,e){const t=n.filter(Number.isFinite);if(t.length===0)return[];const i=Math.min(...t),a=Math.max(...t),u=Math.max(1,Math.floor(e??Math.min(40,Math.ceil(Math.log2(t.length)+1))));if(i===a)return[{x0:i,x1:a,count:t.length}];const f=(a-i)/u,h=Array.from({length:u},(m,g)=>({x0:i+g*f,x1:i+(g+1)*f,count:0}));for(const m of t){const g=Math.min(u-1,Math.floor((m-i)/f));h[g].count+=1}return h}const Cn={top:12,right:14,bottom:26,left:44};function y2({values:n,bins:e,height:t=200,format:i=Wt,ariaLabel:a}){const u=D.useRef(null),[f,h]=D.useState(640),{tip:m,handlers:g}=Dr();D.useEffect(()=>us(u.current,160,h),[]);const v=m2(n,e);if(v.length===0)return c.jsx("div",{className:"grid h-[200px] place-items-center text-xs text-faint",children:"No numeric values to chart."});const x=Math.max(...v.map(R=>R.count),1),b=f-Cn.left-Cn.right,w=t-Cn.top-Cn.bottom,j=R=>Cn.top+(1-R/x)*w,C=b/v.length,O=Ts(0,x,4),H=Math.max(1,Math.ceil(v.length/6)),L=a||`Histogram, ${v.length} bins from ${i(v[0].x0)} to ${i(v[v.length-1].x1)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:u,role:"img","aria-label":L,className:"w-full overflow-hidden",style:{height:t},viewBox:`0 0 ${f} ${t}`,children:[O.map((R,T)=>{const E=j(R);return c.jsxs("g",{children:[c.jsx("line",{x1:Cn.left,x2:f-Cn.right,y1:E,y2:E,className:"stroke-line"}),c.jsx("text",{x:Cn.left-6,y:E+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(R)})]},T)}),v.map((R,T)=>{const E=Cn.left+C*T,I=j(R.count);return c.jsx("rect",{x:E+.5,y:I,width:Math.max(1,C-1),height:Cn.top+w-I,"data-x0":R.x0,"data-x1":R.x1,"data-count":R.count,className:"fill-chart-primary",...g(c.jsx(os,{title:`${i(R.x0)} – ${i(R.x1)}`,rows:[{label:"Count",value:R.count.toLocaleString()}]}))},T)}),v.map((R,T)=>T%H===0?c.jsx("text",{x:Cn.left+C*T,y:t-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:i(R.x0)},T):null)]}),c.jsx(rr,{tip:m})]})}function g2(n){let e=2166136261;for(let t=0;t>>0}function v2(n){let e=n||1;return()=>{e|=0,e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function x2(n,e,{width:t=640,height:i=320,iterations:a=150}={}){if(n.length===0)return[];const u=v2(g2(n.map(G=>G.id).join("\0"))),f=new Map(n.map((G,V)=>[G.id,V])),h=n.map(()=>u()*t),m=n.map(()=>u()*i),g=n.map(()=>0),v=n.map(()=>0),x=n.map(()=>0),b=[];for(const G of e){const V=f.get(G.source),Q=f.get(G.target);V==null||Q==null||V===Q||(b.push([V,Q]),x[V]+=1,x[Q]+=1)}const w=t*i,j=Math.sqrt(w/n.length);let C=Math.max(t,i)/8;const O=C/(a+1);for(let G=0;G({...G,x:H+(h[V]-L)/I*(t-H*2),y:H+(m[V]-T)/U*(i-H*2),degree:x[V]}))}function b2({nodes:n,links:e,height:t=320,ariaLabel:i}){const a=D.useRef(null),[u,f]=D.useState(640),{tip:h,handlers:m}=Dr();D.useEffect(()=>us(a.current,240,f),[]);const g=D.useMemo(()=>x2(n,e,{width:u,height:t}),[n,e,u,t]),v=D.useMemo(()=>new Map(g.map(j=>[j.id,j])),[g]),x=D.useMemo(()=>[...new Set(n.map(j=>j.group??""))],[n]),b=Math.max(...e.map(j=>j.weight??1),1);if(g.length===0)return c.jsx("div",{className:"grid h-[320px] place-items-center text-xs text-faint",children:"No nodes to chart."});const w=i||`Network graph, ${n.length} nodes and ${e.length} links`;return c.jsxs(c.Fragment,{children:[x.length>1?c.jsx("div",{className:"mb-1 flex flex-wrap items-center gap-3 text-2xs text-faint",children:x.map((j,C)=>c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-full",style:{background:yn(C)}}),j||"(default)"]},j||"(default)"))}):null,c.jsxs("svg",{ref:a,role:"img","aria-label":w,className:"w-full overflow-hidden",style:{height:t},viewBox:`0 0 ${u} ${t}`,children:[e.map((j,C)=>{const O=v.get(j.source),H=v.get(j.target);return!O||!H?null:c.jsx("line",{x1:O.x,y1:O.y,x2:H.x,y2:H.y,className:"stroke-line",strokeWidth:.75+2.25*((j.weight??1)/b),"data-source":j.source,"data-target":j.target},C)}),g.map(j=>{const C=5+Math.min(9,j.degree*1.5);return c.jsxs("g",{children:[c.jsx("circle",{cx:j.x,cy:j.y,r:C,fill:yn(x.indexOf(j.group??"")),stroke:"var(--surface)",strokeWidth:1.5,"data-id":j.id,"data-degree":j.degree,...m(c.jsx(os,{title:j.label??j.id,rows:[{label:"Connections",value:String(j.degree)},...j.group?[{label:"Group",value:j.group,swatch:yn(x.indexOf(j.group))}]:[]]}))}),c.jsx("text",{x:j.x,y:j.y-C-4,textAnchor:"middle",className:"pointer-events-none fill-muted text-[10px]",children:(j.label??j.id).slice(0,14)})]},j.id)})]}),c.jsx(rr,{tip:h})]})}function wl({value:n,options:e,onChange:t,label:i,ariaLabel:a,placeholder:u,disabled:f}){return c.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-faint",children:[i?c.jsx("span",{className:"hidden sm:inline",children:i}):null,c.jsxs("select",{"aria-label":a??i,value:n,disabled:f,onChange:h=>t(h.target.value),className:"h-7 rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50",children:[u?c.jsx("option",{value:"",disabled:!0,children:u}):null,e.map(h=>c.jsx("option",{value:h.value,children:h.label??h.value},h.value))]})]})}const un={top:12,right:14,bottom:26,left:48};function w2(n,e,t){return Math.min(Math.max(n,e),t)}function S2({labels:n,series:e,height:t=240,format:i=pt,formatLabel:a=f=>f,ariaLabel:u}){const f=D.useRef(null),[h,m]=D.useState(640),[g,v]=D.useState(null);D.useEffect(()=>us(f.current,240,m),[]);const x=n.length;if(x<2||e.length===0)return c.jsx("div",{className:"grid h-[240px] place-items-center text-xs text-faint",children:"Not enough data to chart."});const b=e.map(V=>({name:V.name,values:n.map((Q,z)=>{const ee=V.values[z];return Number.isFinite(ee)&&ee>0?ee:0})})),w=[];let j=n.map(()=>0);for(const V of b){const Q=V.values.map((z,ee)=>j[ee]+z);w.push(Q),j=Q}const C=Math.max(...j,1),O=h-un.left-un.right,H=t-un.top-un.bottom,L=V=>un.left+V/(x-1)*O,R=V=>un.top+(1-V/C)*H,T=Math.max(1,Math.ceil(x/8)),E=u||`Stacked area chart, ${e.length} series over ${x} points`;function I(V){const Q=w[V],z=V===0?n.map(()=>0):w[V-1],ee=Q.map((ie,ae)=>`${L(ae).toFixed(1)},${R(ie).toFixed(1)}`).join(" L "),X=[...z.keys()].reverse().map(ie=>`${L(ie).toFixed(1)},${R(z[ie]).toFixed(1)}`).join(" L ");return`M ${ee} L ${X} Z`}function U(V){const Q=V.currentTarget.getBoundingClientRect(),z=(V.clientX-Q.left)/Q.width*h,ee=Math.round((z-un.left)/O*(x-1));v(ee>=0&&eec.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2",style:{background:yn(Q)}}),V.name]},V.name))}),c.jsxs("svg",{role:"img","aria-label":E,className:"w-full overflow-hidden",style:{height:t},viewBox:`0 0 ${h} ${t}`,onMouseMove:U,onMouseLeave:()=>v(null),children:[Ts(0,C,4).map((V,Q)=>{const z=R(V);return c.jsxs("g",{children:[c.jsx("line",{x1:un.left,x2:h-un.right,y1:z,y2:z,className:"stroke-line"}),c.jsx("text",{x:un.left-6,y:z+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(V)})]},Q)}),b.map((V,Q)=>c.jsx("path",{d:I(Q),fill:yn(Q),fillOpacity:.8,"data-series":V.name},V.name)),g!=null?c.jsx("line",{x1:L(g),x2:L(g),y1:un.top,y2:t-un.bottom,className:"stroke-faint",strokeDasharray:"3 3"}):null,n.map((V,Q)=>Q%T===0||Q===x-1?c.jsx("text",{x:L(Q),y:t-8,textAnchor:"middle",className:"fill-faint font-mono text-[10px]",children:a(V)},V):null)]}),g!=null?c.jsxs("div",{className:"pointer-events-none absolute top-8 z-20 -translate-x-1/2 whitespace-nowrap border border-line bg-surface px-2 py-1.5 text-2xs shadow-[var(--shadow)]",style:{left:G},children:[c.jsx("div",{className:"mb-0.5 font-mono text-faint",children:a(n[g])}),b.map((V,Q)=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs("span",{className:"flex items-center gap-1 text-muted",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2",style:{background:yn(Q)}}),V.name]}),c.jsx("span",{className:"font-mono tnum text-ink",children:i(V.values[g])})]},V.name))]}):null]})}function _2({checked:n,onChange:e,label:t,ariaLabel:i,disabled:a}){return c.jsxs("label",{className:`flex items-center gap-1.5 text-xs ${a?"opacity-50":""}`,children:[c.jsx("button",{type:"button",role:"switch","aria-checked":n,"aria-label":i??t,disabled:a,onClick:()=>e(!n),"data-checked":n||void 0,className:`relative h-4 w-7 shrink-0 rounded-full border transition-colors ${n?"border-accent bg-accent":"border-line bg-surface-soft"}`,children:c.jsx("span",{"aria-hidden":"true",className:`absolute top-1/2 size-3 -translate-y-1/2 rounded-full bg-surface shadow transition-[left] ${n?"left-[14px]":"left-[2px]"}`})}),t?c.jsx("span",{className:"text-muted",children:t}):null]})}function N2({tabs:n,active:e,onChange:t,ariaLabel:i="Tabs"}){return c.jsx("div",{role:"tablist","aria-label":i,className:"inline-flex items-center gap-0.5 rounded-full border border-line bg-surface p-px",children:n.map(a=>c.jsx("button",{role:"tab",type:"button","aria-selected":e===a.key,"data-tab":a.key,"data-selected":e===a.key||void 0,onClick:()=>t(a.key),className:"inline-flex h-6 items-center rounded-full px-2.5 text-xs font-medium text-muted hover:bg-surface-soft hover:text-ink data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent",children:a.label},a.key))})}function j2({content:n,children:e,className:t}){const{tip:i,handlers:a}=Dr();return c.jsxs(c.Fragment,{children:[c.jsx("span",{className:t??"inline-flex",...a(n),children:e}),c.jsx(rr,{tip:i})]})}function k2(n){let e=0;return n.map(t=>{const i=Number.isFinite(t.value)?t.value:0;if(t.isTotal)return e=i,{...t,value:i,start:0,end:i};const a=e;return e+=i,{...t,value:i,start:a,end:e}})}const cn={top:12,right:14,bottom:26,left:48};function I2({data:n,height:e=220,format:t=pt,ariaLabel:i}){const a=D.useRef(null),[u,f]=D.useState(640),{tip:h,handlers:m}=Dr();D.useEffect(()=>us(a.current,200,f),[]);const g=k2(n);if(g.length===0)return c.jsx("div",{className:"grid h-[220px] place-items-center text-xs text-faint",children:"No steps to chart."});const v=g.flatMap(E=>[E.start,E.end]),x=Math.min(0,...v),b=Math.max(0,...v),w=b-x||1,j=u-cn.left-cn.right,C=e-cn.top-cn.bottom,O=E=>cn.top+(1-(E-x)/w)*C,H=j/g.length,L=Math.max(10,Math.min(56,H*.62)),R=Ts(x,b,4),T=i||`Waterfall chart, ${g.length} steps ending at ${t(g[g.length-1].end)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:a,role:"img","aria-label":T,className:"w-full overflow-hidden",style:{height:e},viewBox:`0 0 ${u} ${e}`,children:[R.map((E,I)=>{const U=O(E);return c.jsxs("g",{children:[c.jsx("line",{x1:cn.left,x2:u-cn.right,y1:U,y2:U,className:"stroke-line"}),c.jsx("text",{x:cn.left-6,y:U+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(E)})]},I)}),c.jsx("line",{x1:cn.left,x2:u-cn.right,y1:O(0),y2:O(0),className:"stroke-faint"}),g.map((E,I)=>{const U=cn.left+H*I+(H-L)/2,G=O(E.start),V=O(E.end),Q=E.isTotal?"total":E.value<0?"negative":"positive",z=E.isTotal?"fill-faint":E.value<0?"fill-danger":"fill-chart-primary",ee=g[I+1];return c.jsxs("g",{children:[c.jsx("rect",{x:U,y:Math.min(G,V),width:L,height:Math.max(1,Math.abs(V-G)),"data-label":E.label,"data-value":E.value,"data-tone":Q,className:z,...m(c.jsx(os,{title:E.label,rows:E.isTotal?[{label:"Total",value:t(E.end)}]:[{label:"Change",value:t(E.value)},{label:"Running",value:t(E.end)}]}))}),ee?c.jsx("line",{x1:U+L,x2:cn.left+H*(I+1)+(H-L)/2,y1:V,y2:V,className:"stroke-faint",strokeDasharray:"3 3"}):null,c.jsx("text",{x:U+L/2,y:e-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:E.label.slice(0,9)})]},`${E.label}-${I}`)})]}),c.jsx(rr,{tip:h})]})}function oy(n){return n==null?"∅":String(n)}function M2(n){const e=typeof n=="number"?n:Number(n);return Number.isFinite(e)?e:Number.NaN}function D2(n,e){const t=[],i=[],a=new Map;for(const u of n){const f=oy(u[e.x]),h=oy(u[e.series]);t.includes(f)||t.push(f),i.includes(h)||i.push(h),a.set(`${h}\0${f}`,M2(u[e.y]))}return{labels:t,series:i.map(u=>({name:u,values:t.map(f=>a.get(`${u}\0${f}`)??0)}))}}const C2=[{dimension:"orders.region",title:"Customer Region",rows:[["East",83262],["South",80579],["West",71561],["North",52889]].map(([n,e])=>({value:String(n),metric:Number(e)}))},{dimension:"orders.status",title:"Order Status",rows:[["completed",170379],["cancelled",64637],["pending",53275]].map(([n,e])=>({value:String(n),metric:Number(e)}))},{dimension:"products.category",title:"Product Category",rows:[["Electronics",202015],["Furniture",83848],["Office Supplies",2428]].map(([n,e])=>({value:String(n),metric:Number(e)}))},{dimension:"customers.name",title:"Top Customers",rows:[["Bob Smith",46690],["Carol Davis",42227],["Henry Taylor",41633],["Grace Lee",41035],["Frank Brown",33890],["David Wilson",29928],["Alice Johnson",27114],["Emma Martinez",24802]].map(([n,e])=>({value:String(n),metric:Number(e)}))}],F2=[{key:"region",label:"Region",sortable:!0},{key:"revenue",label:"Revenue",numeric:!0,sortable:!0},{key:"orders",label:"Orders",numeric:!0,sortable:!0}],ay=Array.from({length:17},(n,e)=>({region:["East","South","West","North"][e%4],revenue:91e3-e*2875,orders:420-e*11})),hf=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug"],O2=hf.flatMap((n,e)=>[{month:n,plan:"Basic",revenue:120+e*26},{month:n,plan:"Pro",revenue:60+e*24},{month:n,plan:"Enterprise",revenue:e<2?0:10+e*12}]),T2=Array.from({length:48},(n,e)=>({x:e+1,y:(e+1)*1.6+Math.sin(e*78.233)*43758.5453%18,label:`Account ${e+1}`,series:e%2?"Returning":"New"})),A2=Array.from({length:400},(n,e)=>Math.abs(Math.sin(e*12.9898)*43758.5453%1)*100),B2=["East","South","West","North"].flatMap((n,e)=>hf.map((t,i)=>({x:t,y:n,value:(e+1)*(i+1)*7-(i%4===3?80:0)}))),ly=[{value:"orders.revenue",label:"Revenue"},{value:"orders.count",label:"Order count"},{value:"customers.count",label:"Customer count"},{value:"orders.margin",label:"Gross margin"}];function E2(){const[n,e]=D.useState("orders.revenue"),[t,i]=D.useState({}),[a,u]=D.useState(null),[f,h]=D.useState({"orders.region":["East","West"],"orders.status":["completed"]}),[m,g]=D.useState({from:"2025-01-01",to:"2025-06-30"}),[v,x]=D.useState("month"),[b,w]=D.useState("explore"),[j,C]=D.useState("previous"),[O,H]=D.useState("orders.revenue"),[L,R]=D.useState(["orders.revenue","orders.count"]),[T,E]=D.useState("apple"),[I,U]=D.useState(!0),[G,V]=D.useState("explore"),[Q,z]=D.useState("2025-06-15"),[ee,X]=D.useState({from:"2025-06-01",to:"2025-06-21"}),ie=D.useMemo(()=>D2(O2,{x:"month",y:"revenue",series:"plan"}),[]),[ae,re]=D.useState({key:"revenue",dir:"desc"}),se=D.useMemo(()=>[...ay].sort((A,Y)=>{const W=A[ae.key],_=Y[ae.key],F=typeof W=="number"&&typeof _=="number"?W-_:String(W).localeCompare(String(_));return ae.dir==="asc"?F:-F}),[ae]);return c.jsxs("main",{className:"min-h-screen bg-bg text-ink",children:[c.jsxs("header",{className:"sticky top-0 z-20 flex items-center justify-between border-b border-line bg-surface px-4 py-3",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-sm font-semibold",children:"Sidemantic component gallery"}),c.jsxs("p",{className:"text-2xs text-faint",children:["Canonical React primitives · ",c.jsx("a",{className:"text-accent hover:underline",href:"/typography",children:"typography workbench →"})]})]}),c.jsx($o,{})]}),c.jsxs("div",{className:"space-y-8 p-4",children:[c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Metric cards"}),c.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-3",children:[c.jsx(Nr,{metric:"orders.revenue",label:"Revenue",value:288291,format:{format:"currency"},selected:n==="orders.revenue",sparkValues:[31,42,38,55,60,74],onSelect:e}),c.jsx(Nr,{metric:"orders.count",label:"Order Count",value:447,selected:n==="orders.count",sparkValues:[21,34,28,41,44,51],onSelect:e}),c.jsx(Nr,{metric:"orders.margin",label:"Gross Margin",value:.324,format:{format:"percent"},delta:{label:"+1.1pt",tone:"positive"},comparison:"vs previous month",sparkValues:[24,26,29,27,31,32],selected:n==="orders.margin",onSelect:e})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Leaderboard cards"}),c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(220px,1fr))] gap-0 border-l border-t border-line",children:C2.filter(A=>a===null||a===A.dimension).map(A=>c.jsx(Jv,{dimension:A.dimension,title:A.title,metricLabel:"Total Revenue",rows:A.rows,selectedValues:t[A.dimension],formatMetric:Y=>pt(Y,{format:"currency"}),onToggle:Y=>i(W=>{const _=W[A.dimension]??[];return{...W,[A.dimension]:_.includes(Y)?_.filter(F=>F!==Y):[..._,Y]}}),expanded:a===A.dimension,onExpandedChange:Y=>u(Y?A.dimension:null)},A.dimension))})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Filters and controls"}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{"data-testid":"gallery-filter-pills",className:"flex min-h-8 flex-wrap items-center gap-2",children:[Object.entries(f).flatMap(([A,Y])=>Y.map(W=>c.jsx(Od,{dimension:A,value:W,onRemove:()=>h(_=>({..._,[A]:_[A].filter(F=>F!==W)}))},`${A}:${W}`))),Object.values(f).every(A=>A.length===0)?c.jsx("span",{className:"text-2xs text-faint",children:"No active filters"}):null]}),c.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[c.jsx(Ov,{range:m,onChange:g,comparison:j,onComparisonChange:C}),c.jsx(Td,{grain:v,options:["day","week","month","quarter","year"],onChange:x}),c.jsx(Bv,{view:b,onChange:w}),c.jsxs("span",{className:"inline-flex items-center gap-1.5 text-2xs text-muted",children:[c.jsx(dd,{status:"ok"})," Ready"]}),c.jsxs("span",{className:"inline-flex items-center gap-1.5 text-2xs text-muted",children:[c.jsx(dd,{status:"loading"})," Updating"]}),c.jsx("button",{type:"button",onClick:()=>h({"orders.region":["East","West"],"orders.status":["completed"]}),className:"inline-flex h-7 items-center rounded-full border border-line px-3 text-xs text-muted hover:bg-surface-soft",children:"Reset filters"})]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Charts"}),c.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Sparkline"}),c.jsx(qv,{values:[31,42,38,55,60,74,69,83],labels:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug"],ariaLabel:"Eight month revenue trend"})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Column chart"}),c.jsx(Zv,{data:[{label:"East",value:83},{label:"South",value:81},{label:"West",value:72},{label:"Returns",value:-18}]})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Line chart compatibility export"}),c.jsx(c2,{data:[{label:"Jan",value:31},{label:"Feb",value:42},{label:"Mar",value:38},{label:"Apr",value:55},{label:"May",value:60}]})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Interactive time series"}),c.jsx(Go,{points:[31,42,38,55,60,74].map((A,Y)=>({x:`2025-0${Y+1}-01`,y:A})),comparison:[27,35,33,48,52,61].map((A,Y)=>({x:`2024-0${Y+1}-01`,y:A})),formatValue:A=>`$${A.toLocaleString()}k`})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Donut"}),c.jsx(h2,{data:[{label:"iOS",value:4200},{label:"Android",value:3100},{label:"Web",value:1900},{label:"Other",value:400}]})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Stacked area (long rows via rowsToSeries)"}),c.jsx(S2,{labels:ie.labels,series:ie.series,height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Bar + line combo (dual axis)"}),c.jsx(r2,{data:hf.map((A,Y)=>({label:A,bar:200+Y*42,line:.02+Y*.004})),barLabel:"Revenue",lineLabel:"Conversion",formatLine:A=>`${(A*100).toFixed(1)}%`,height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Histogram"}),c.jsx(y2,{values:A2,bins:20})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Scatter"}),c.jsx(Xv,{points:T2,xLabel:"Sessions",yLabel:"Orders",height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Heatmap"}),c.jsx(p2,{cells:B2,height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Waterfall"}),c.jsx(I2,{data:[{label:"Gross",value:1e3,isTotal:!0},{label:"Refunds",value:-140},{label:"Discounts",value:-90},{label:"Upsells",value:130},{label:"Net",value:900,isTotal:!0}],height:200})]}),c.jsxs("article",{className:"min-w-0 xl:col-span-2",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Network"}),c.jsx(b2,{nodes:[{id:"orders",group:"fact"},{id:"payments",group:"fact"},{id:"customers",group:"dimension"},{id:"products",group:"dimension"},{id:"regions",group:"dimension"}],links:[{source:"orders",target:"customers",weight:3},{source:"orders",target:"products",weight:2},{source:"orders",target:"regions"},{source:"payments",target:"orders",weight:2},{source:"payments",target:"customers"}],height:260})]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Inputs"}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[c.jsx(No,{variant:"primary",children:"Primary"}),c.jsx(No,{children:"Secondary"}),c.jsx(No,{variant:"ghost",children:"Ghost"}),c.jsx(No,{variant:"danger",children:"Danger"}),c.jsx(No,{size:"sm",children:"Small"}),c.jsx(wl,{label:"Fruit",value:T,onChange:E,options:[{value:"apple",label:"Apple"},{value:"banana",label:"Banana"},{value:"cherry",label:"Cherry"}]}),c.jsx(_2,{checked:I,onChange:U,label:"Compact rows"}),c.jsx(N2,{tabs:[{key:"explore",label:"Explore"},{key:"pivot",label:"Pivot"},{key:"sql",label:"SQL"}],active:G,onChange:V}),c.jsx(j2,{content:"Revenue in USD, net of refunds",children:c.jsx("span",{className:"cursor-help text-2xs text-muted underline decoration-dotted",children:"What is revenue?"})})]}),c.jsxs("div",{className:"flex flex-wrap items-start gap-3",children:[c.jsx(ny,{value:O,onChange:H,options:ly,ariaLabel:"Metric"}),c.jsx(ny,{multiple:!0,values:L,onChange:R,options:ly,ariaLabel:"Metrics"}),c.jsx(sy,{mode:"single",value:Q,onChange:z,ariaLabel:"Date"}),c.jsx(sy,{mode:"range",value:ee,onChange:X,ariaLabel:"Range"})]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Analytical table"}),c.jsx(Ho,{columns:F2,rows:se,pageSize:6,sortKey:ae.key,sortDir:ae.dir,onSort:A=>re(Y=>({key:A,dir:Y.key===A&&Y.dir==="desc"?"asc":"desc"})),renderCell:(A,Y)=>A.numeric?Number(Y).toLocaleString():String(Y),searchable:!0,totals:{region:"count",revenue:"sum",orders:"sum"}}),c.jsxs("div",{className:"mt-3",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold text-muted",children:"Distribution-friendly data preview"}),c.jsx(u2,{result:{columns:["region","revenue","orders"],sample_rows:ay.slice(0,8)},pageSize:4})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Query inspection"}),c.jsx(au,{inputs:{Revenue:{metrics:["orders.revenue"],dimensions:["orders.region"],filters:["orders.status = 'completed'"]}},queries:{Revenue:`SELECT orders.region, SUM(orders.revenue) AS revenue +`),i=$_(t||"No queries yet.");return c.jsxs("details",{className:"border border-line bg-surface",children:[c.jsx("summary",{className:"cursor-pointer px-3 py-2 text-xs font-medium text-muted",children:"Generated SQL"}),Object.keys(e).length>0?c.jsx("div",{"data-testid":"query-inputs",className:"grid gap-px border-t border-line bg-line sm:grid-cols-2",children:Object.entries(e).map(([a,u])=>u?c.jsxs("section",{className:"min-w-0 bg-surface px-3 py-2 text-2xs",children:[c.jsx("h3",{className:"mb-1 font-semibold text-ink",children:a}),[["Metrics",u.metrics],["Dimensions",u.dimensions],["Filters",u.filters]].map(([f,h])=>h!=null&&h.length?c.jsxs("p",{className:"truncate text-muted",title:h.join(", "),children:[c.jsxs("strong",{className:"font-medium text-faint",children:[f,":"]})," ",h.join(", ")]},f):null)]},a):null)}):null,c.jsx("pre",{"data-testid":"query-debug",className:"max-h-72 overflow-auto whitespace-pre-wrap border-t border-line px-3 py-2 font-mono text-2xs text-muted",children:i.map((a,u)=>ny[a.kind]?c.jsx("span",{className:ny[a.kind],"data-token":a.kind,children:a.value},u):a.value)})]})}function P_(n){return{format:n==null?void 0:n.format,type:n==null?void 0:n.type}}function z_(n,e){return n&&e.some(t=>t.ref===n)?n:null}function ry(n,e){return[...n].sort((t,i)=>String(t[e]??"").localeCompare(String(i[e]??"")))}function V_(n,e){return{from:e==="second"||e==="minute"||e==="hour"?n.from.replace(" ","T"):nf(n.from),to:yS(n.to,e)}}function W_(){var Cr,Fr,ue,Oe,rt,Nt,Un,sr,Es,Ei;const{state:n,dispatch:e,catalog:t,backend:i,dashboard:a}=ls(),[u,f]=M.useState(null),h=t.models.find(Se=>Se.name===n.model),m=M.useMemo(()=>Cs(t,a,n.dashboardTab),[t,a,n.dashboardTab]);M.useEffect(()=>{f(null)},[n.dashboardTab,n.model]);const g=(m==null?void 0:m.metrics)??(h==null?void 0:h.metrics)??[],v=new Set(g.map(Se=>Se.ref)),x=ji(t,n.model).filter(Se=>!m||v.has(Se.ref)),b=((Cr=m==null?void 0:m.timeDimension)==null?void 0:Cr.ref)??((Fr=h==null?void 0:h.timeDimension)==null?void 0:Fr.ref),w=g.find(Se=>Se.ref===n.selectedMetric)??x.find(Se=>Se.ref===n.selectedMetric)??g[0],j=!!w&&g.some(Se=>Se.ref===w.ref),C=M.useMemo(()=>{const Se=g.map(bn=>bn.ref);return w&&!j?[...Se,w.ref]:Se},[g,w,j]),O=M.useMemo(()=>ou(t),[t]),H=M.useMemo(()=>[...(m==null?void 0:m.filters)??[],...Os(n.filters,{timeRef:b,range:n.dateRange,types:O})],[m,n.filters,b,n.dateRange,O]),L=M.useMemo(()=>n.comparison==="off"||!n.dateRange?null:n.comparison==="year"?dS(n.dateRange):n.comparison==="custom"?n.comparisonRange??null:cS(n.dateRange),[n.comparison,n.dateRange,n.comparisonRange]),R=M.useMemo(()=>L&&b?[...(m==null?void 0:m.filters)??[],...Os(n.filters,{timeRef:b,range:L,types:O})]:null,[m,n.filters,b,L,O]),T=n.timezone,E=Se=>Se?{...Se,timezone:T}:null,I=Zn(i,C.length?E($m(C,H,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations)):null),U=Zn(i,C.length&&b?E(Pm(C,b,n.grain,H,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations,!!n.dateRange)):null),G=Zn(i,C.length&&R?E($m(C,R,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations)):null),V=Zn(i,w&&b&&R?E(Pm([w.ref],b,n.grain,R,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations,!0)):null),Q=I.error??U.error??G.error??V.error;if(!h)return c.jsx("div",{className:"p-4",children:c.jsx(Xn,{message:"No model available in this semantic layer."})});const z=((m==null?void 0:m.dimensions)??h.dimensions).filter(Se=>Se.type!=="time"),ee=z_(u,z),X=n.comparison==="year"?"Prev year":n.comparison==="custom"?"Comparison":"Prev period",ie=b?`${b}__${n.grain}`:"",ae=ie?[...C,ie]:C,re=w&&ie?[w.ref,ie]:[],se=g[0]?Fn(g[0].ref,C):w?Fn(w.ref,C):null,A=Se=>!Se||!se||Se.columns.includes(se),Y=A(I.result)?(ue=I.result)==null?void 0:ue.rows[0]:void 0,W=A(G.result)?(Oe=G.result)==null?void 0:Oe.rows[0]:void 0,_=A(U.result)?((rt=U.result)==null?void 0:rt.rows)??[]:[],F=w?Fn(w.ref,C):"",te=w?Fn(w.ref,ae):"",pe=w?Fn(w.ref,re):"",ne=ie?Fn(ie,ae):"",fe=ie?Fn(ie,re):"",Ce=ne?ry(_,ne):_,Te=Y&&F?Number(Y[F]):NaN,Ue=W&&F?Number(W[F]):void 0,lt=te?Ce.map(Se=>({x:String(Se[ne]??""),y:Number(Se[te])})):[],wt=fe?ry(((Nt=V.result)==null?void 0:Nt.rows)??[],fe):[],Bs=pe&<.length>0&&wt.length>0?(()=>{const Se=String(wt[0][fe]??""),bn=lt[0].x,cs=new Map;for(const tn of wt)cs.set(Lm(Se,String(tn[fe]??""),n.grain),Number(tn[pe]));return lt.map(tn=>({x:tn.x,y:cs.get(Lm(bn,tn.x,n.grain))??NaN}))})():[];function xn(Se){e(Se?{type:"setDateRange",range:V_(Se,n.grain)}:{type:"setDateRange",range:void 0})}return c.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[Q?c.jsx(Bi,{message:Q}):null,c.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6","data-testid":"metric-totals",children:g.length===0?c.jsx("div",{className:"col-span-full",children:c.jsx(Xn,{message:"This model has no metrics."})}):g.map(Se=>{const bn=Fn(Se.ref,C),cs=Fn(Se.ref,ae),tn=Y?Number(Y[bn]):NaN,ds=W?Number(W[bn]):void 0,Yo=Ce.map(ir=>Number(ir[cs])).filter(Number.isFinite);return c.jsx(Nr,{metric:Se.ref,label:Se.label,valueText:pt(tn,P_(Se)),delta:ds!==void 0?xy(tn,ds):null,sparkValues:Yo,selected:n.selectedMetric===Se.ref,loading:I.loading&&!Y,onSelect:ir=>e({type:"setMetric",metric:ir})},Se.ref)})}),w?c.jsx(L_,{metric:w,points:lt,comparisonPoints:L?Bs:void 0,total:Te,prevTotal:L?Ue:void 0,hasTime:!!b,loading:U.loading,activeRange:n.dateRange,comparisonLabel:X,formatLabel:Se=>fS(Se,n.grain),onBrush:xn}):null,c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(220px,1fr))] gap-0 border-l border-t border-line",children:w&&z.length?z.filter(Se=>ee===null||ee===Se.ref).map(Se=>c.jsx(A_,{dim:Se,model:h,timeDimensionRef:b,rankMetric:w,contextColumn:n.contextColumn,metricTotal:Number.isFinite(Te)?Te:void 0,comparisonRange:L??void 0,baseFilters:m==null?void 0:m.filters,baseSegments:m==null?void 0:m.segments,usePreaggregations:m==null?void 0:m.usePreaggregations,expanded:ee===Se.ref,onExpandedChange:bn=>f(bn?Se.ref:null)},Se.ref)):c.jsx(Xn,{message:"No categorical dimensions to break down."})}),c.jsx(au,{queries:{Totals:(Un=I.result)==null?void 0:Un.sql,Series:(sr=U.result)==null?void 0:sr.sql,Comparison:(Es=G.result)==null?void 0:Es.sql,"Prev series":(Ei=V.result)==null?void 0:Ei.sql}})]})}function H_(){var ie,ae;const{state:n,catalog:e,backend:t}=ls(),i=e.models.find(re=>re.name===n.model),a=(i==null?void 0:i.dimensions)??[],u=ji(e,n.model),f=M.useMemo(()=>[...(i==null?void 0:i.metrics)??[],...u],[i,u]),h=(ie=i==null?void 0:i.timeDimension)==null?void 0:ie.ref,m=re=>a.some(se=>se.ref===re),g=re=>f.some(se=>se.ref===re),v=n.pivotDims.filter(m),x=n.pivotMetrics.filter(g),b=g(n.selectedMetric)?n.selectedMetric:(ae=i==null?void 0:i.metrics[0])==null?void 0:ae.ref,w=x.length?x:b?[b]:[],[j,C]=M.useState(null),O=M.useMemo(()=>sf(a),[a]),H=M.useMemo(()=>Os(n.filters,{timeRef:h,range:n.dateRange,types:O}),[n.filters,h,n.dateRange,O]),L=j??(w[0]?{ref:w[0],dir:"desc"}:null),R=L?[`${L.ref} ${L.dir.toUpperCase()}`]:void 0,T=w.length||v.length?bS(w,v,H,R,500):null,E=T?{...T,timezone:n.timezone}:null,{result:I,loading:U,error:G}=Zn(t,E),V=M.useMemo(()=>new Map(f.map(re=>[re.ref,re])),[f]),Q=M.useMemo(()=>{const re=new Map;for(const se of[...v,...w])re.set(Sr(se),se);return re},[v,w]),z=[...v.map(re=>{var se;return{key:Sr(re),label:((se=a.find(A=>A.ref===re))==null?void 0:se.label)??Le(re),numeric:!1}}),...w.map(re=>{var se;return{key:Sr(re),label:((se=V.get(re))==null?void 0:se.label)??Le(re),numeric:!0,sortable:!0}})];function ee(re){const se=Q.get(re);se&&C(A=>A&&A.ref===se?{ref:se,dir:A.dir==="desc"?"asc":"desc"}:{ref:se,dir:"desc"})}function X(re,se){if(re.numeric){const A=V.get(Q.get(re.key)??"");return pt(se,{format:A==null?void 0:A.format,type:A==null?void 0:A.type})}return se==null||se===""?"—":String(se)}return i?c.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[G?c.jsx(Bi,{message:G}):z.length===0?c.jsx(Xn,{title:"Nothing selected",message:"Pick at least one metric or dimension above."}):c.jsx(Ho,{columns:z,rows:(I==null?void 0:I.rows)??[],loading:U,sortKey:L?Sr(L.ref):void 0,sortDir:L==null?void 0:L.dir,onSort:ee,renderCell:X}),c.jsx(au,{queries:{Pivot:I==null?void 0:I.sql}})]}):c.jsx("div",{className:"p-4",children:c.jsx(Xn,{message:"No model available."})})}const Dn={top:12,right:14,bottom:26,left:44};function G_(n,e,t=4){if(!(e>n))return[n];const i=(e-n)/(t-1);return Array.from({length:t},(a,u)=>n+i*u)}function t0({data:n,height:e=200,ariaLabel:t,selectedLabel:i,onSelect:a}){const u=M.useRef(null),[f,h]=M.useState(640),{tip:m,handlers:g}=Dr();M.useEffect(()=>{const I=u.current;if(!I||typeof ResizeObserver>"u")return;const U=new ResizeObserver(G=>{for(const V of G)h(Math.max(160,V.contentRect.width))});return U.observe(I),()=>U.disconnect()},[]);const v=n.map(I=>Number.isFinite(I.value)?I.value:0),x=Math.min(0,...v),b=Math.max(0,...v),w=b-x||1,j=f-Dn.left-Dn.right,C=e-Dn.top-Dn.bottom,O=I=>Dn.top+(1-(I-x)/w)*C,H=O(0),L=j/Math.max(n.length,1),R=Math.max(8,Math.min(48,L*.62)),T=G_(x,b,4),E=t||`Bar chart, ${n.length} categories, up to ${Wt(b)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:u,role:"img","aria-label":E,className:"h-[200px] w-full overflow-hidden",viewBox:`0 0 ${f} ${e}`,children:[T.map((I,U)=>{const G=O(I);return c.jsxs("g",{children:[c.jsx("line",{x1:Dn.left,x2:f-Dn.right,y1:G,y2:G,className:"stroke-line"}),c.jsx("text",{x:Dn.left-6,y:G+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(I)})]},U)}),c.jsx("line",{x1:Dn.left,x2:f-Dn.right,y1:H,y2:H,className:"stroke-line"}),n.map((I,U)=>{const G=I.filterValue??I.label,V=v[U]??0,Q=O(V),z=Math.abs(Q-H),ee=Dn.left+L*U+(L-R)/2,X=Math.min(Q,H);return c.jsxs("g",{role:a?"button":void 0,tabIndex:a?0:void 0,"aria-label":a?`Filter to ${I.label}`:void 0,"aria-pressed":a?i===G:void 0,onClick:a?()=>a(G):void 0,onKeyDown:a?ie=>{(ie.key==="Enter"||ie.key===" ")&&a(G)}:void 0,className:a?"cursor-pointer":void 0,children:[c.jsx("rect",{x:ee,y:X,width:R,height:z,"data-label":I.label,"data-value":V,"data-tone":V<0?"negative":"positive",className:i===G?"fill-accent":V<0?"fill-danger":"fill-chart-primary",...g(`${I.label}: ${pt(V)}`)}),c.jsx("text",{x:ee+R/2,y:e-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:I.label.slice(0,8)})]},`${G}-${U}`)})]}),c.jsx(rr,{tip:m})]})}const pd=7;function yn(n){return`var(--viz-${(n%pd+pd)%pd+1})`}function Ts(n,e,t=4){if(!(e>n))return[n];const i=(e-n)/(t-1);return Array.from({length:t},(a,u)=>n+i*u)}function us(n,e,t){if(!n||typeof ResizeObserver>"u")return()=>{};const i=new ResizeObserver(a=>{for(const u of a)t(Math.max(e,u.contentRect.width))});return i.observe(n),()=>i.disconnect()}const Pt={top:12,right:14,bottom:30,left:48};function n0({points:n,height:e=240,xLabel:t,yLabel:i,formatX:a=Wt,formatY:u=Wt,ariaLabel:f}){const h=M.useRef(null),[m,g]=M.useState(640),{tip:v,handlers:x}=Dr();M.useEffect(()=>us(h.current,200,g),[]);const b=n.filter(z=>Number.isFinite(z.x)&&Number.isFinite(z.y));if(b.length===0)return c.jsx("div",{className:"grid h-[240px] place-items-center text-xs text-faint",children:"No points to chart."});const w=[...new Set(b.map(z=>z.series??""))],j=b.map(z=>z.x),C=b.map(z=>z.y),O=Math.min(...j),H=Math.max(...j),L=Math.min(...C),R=Math.max(...C),T=H-O||1,E=R-L||1,I=m-Pt.left-Pt.right,U=e-Pt.top-Pt.bottom,G=z=>Pt.left+(z-O)/T*I,V=z=>Pt.top+(1-(z-L)/E)*U,Q=f||`Scatter plot, ${b.length} points${t&&i?` of ${i} by ${t}`:""}`;return c.jsxs(c.Fragment,{children:[w.length>1?c.jsx("div",{className:"mb-1 flex flex-wrap items-center gap-3 text-2xs text-faint",children:w.map((z,ee)=>c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-full",style:{background:yn(ee)}}),z||"(default)"]},z||"(default)"))}):null,c.jsxs("svg",{ref:h,role:"img","aria-label":Q,className:"w-full overflow-hidden",style:{height:e},viewBox:`0 0 ${m} ${e}`,children:[Ts(L,R,4).map((z,ee)=>{const X=V(z);return c.jsxs("g",{children:[c.jsx("line",{x1:Pt.left,x2:m-Pt.right,y1:X,y2:X,className:"stroke-line"}),c.jsx("text",{x:Pt.left-6,y:X+3,textAnchor:"end",className:"fill-faint text-[10px]",children:u(z)})]},`y${ee}`)}),Ts(O,H,5).map((z,ee)=>{const X=G(z);return c.jsxs("g",{children:[c.jsx("line",{x1:X,x2:X,y1:Pt.top,y2:e-Pt.bottom,className:"stroke-line"}),c.jsx("text",{x:X,y:e-14,textAnchor:"middle",className:"fill-faint text-[10px]",children:a(z)})]},`x${ee}`)}),t?c.jsx("text",{x:Pt.left+I/2,y:e-2,textAnchor:"middle",className:"fill-muted text-[10px]",children:t}):null,i?c.jsx("text",{x:10,y:Pt.top+U/2,textAnchor:"middle",transform:`rotate(-90 10 ${Pt.top+U/2})`,className:"fill-muted text-[10px]",children:i}):null,b.map((z,ee)=>c.jsx("circle",{cx:G(z.x),cy:V(z.y),r:3.5,fill:yn(w.indexOf(z.series??"")),fillOpacity:.75,"data-x":z.x,"data-y":z.y,"data-label":z.label,...x(c.jsx(os,{title:z.label??z.series,rows:[{label:t??"x",value:a(z.x)},{label:i??"y",value:u(z.y)}]}))},ee))]}),c.jsx(rr,{tip:v})]})}function Y_(){const n=Tv();return c.jsx("span",{className:"text-2xs text-faint",children:n?"Querying…":"Live data"})}function md(n,e){for(const i of n.models){const a=i.metrics.find(u=>u.ref===e);if(a)return{format:a.format,type:a.type}}const t=n.graphMetrics.find(i=>i.ref===e);return{format:t==null?void 0:t.format,type:t==null?void 0:t.type}}function Q_(n){return sf(n.models.flatMap(e=>e.dimensions))}function K_(n){var t;const e=(t=n.encoding)==null?void 0:t.y;return(Array.isArray(e)?e[0]:e)??n.query.metrics[0]??""}function J_({chart:n,columns:e,rows:t}){const i=N_(e,t);return c.jsx("a",{href:`data:text/csv;charset=utf-8,${encodeURIComponent(i)}`,download:`${n.id}.csv`,className:"border border-line px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Export CSV"})}function q_({chart:n,columns:e,rows:t,loading:i,onDrill:a}){const u=e.map(g=>({key:g,label:Le(g),numeric:n.query.metrics.some(v=>xr(v,e)===g)})),f=l_(n),h=f?xr(f,e):void 0,m=!!f;return c.jsxs("div",{className:"border-t border-line bg-surface-soft p-3","data-testid":`chart-details-${n.id}`,children:[c.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[c.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wide text-faint",children:"Drill details"}),m&&f&&h?c.jsxs("span",{className:"text-2xs text-faint",children:["Choose a ",Le(f)," value to filter every chart."]}):null]}),c.jsx(Ho,{columns:u,rows:t,loading:i,pageSize:20,renderCell:(g,v)=>String(v??"—")}),m&&f&&h&&t.length?c.jsx("div",{className:"mt-2 flex flex-wrap gap-1","aria-label":`Drill by ${Le(f)}`,children:t.slice(0,12).map((g,v)=>{const x=Xl(g[h]);return c.jsxs("button",{type:"button",onClick:()=>a(f,x),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-accent hover:text-ink",children:["Filter to ",rs(x)]},`${String(x)}-${v}`)})}):null]})}function Z_({document:n,chart:e,catalog:t,backend:i,state:a,setFilters:u,setRange:f}){var z,ee,X,ie,ae,re,se;const[h,m]=M.useState(!1),g=M.useMemo(()=>Q_(t),[t]),v=M.useMemo(()=>y_(n,e,a.filters,g,a.ranges,a),[e,n,a,g]),x=Zn(i,v),b=((z=x.result)==null?void 0:z.rows)??[],w=((ee=x.result)==null?void 0:ee.columns)??[],j=e.query.dimensions??[],C=((X=e.encoding)==null?void 0:X.x)??j[0]??"",O=d_(e),H=O[0]??K_(e),L=xr(C,w),R=cf(n,e,a),T=Hv(e,g),E=u_(e,C),I=((ie=e.title)==null?void 0:ie.trim())||Le(e.id),U=[(ae=e.encoding)==null?void 0:ae.color,...j.filter(A=>A!==C)].filter((A,Y,W)=>!!A&&W.indexOf(A)===Y),G=h_(e,C,U),V=U.map(A=>xr(A,w));let Q;if(x.loading&&!x.result)Q=c.jsx(af,{title:`Loading ${I}`});else if(x.error)Q=c.jsx(Bi,{title:`Could not load ${I}`,message:x.error});else if(!b.length)Q=c.jsx(Xn,{title:I,message:"The query returned no rows."});else if(j.length)if(T==="scatter"||T==="point"){const A=(re=e.encoding)!=null&&re.color?xr(e.encoding.color,w):V[0];Q=c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3",children:O.map(Y=>{const W=xr(Y,w),_=b.map(F=>({x:Number(F[L]),y:Number(F[W]),label:String(F[L]??""),series:A?String(F[A]??""):void 0}));return c.jsxs("div",{className:"min-w-0",children:[O.length>1?c.jsx("h3",{className:"mb-1 text-2xs font-semibold text-muted",children:Le(Y)}):null,c.jsx(n0,{points:_,xLabel:Le(C),yLabel:Le(Y),formatY:F=>pt(F,md(t,Y)),ariaLabel:`${I}, ${Le(Y)} by ${Le(C)}, ${_.length} points`})]},Y)})})}else T==="line"||T==="area"?Q=c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3",children:O.map(A=>{const Y=x_(b,L,xr(A,w),V),W=Y[0]??{label:"Current",points:[]},_=md(t,A);return c.jsxs("div",{className:"min-w-0",children:[O.length>1?c.jsx("h3",{className:"mb-1 text-2xs font-semibold text-muted",children:Le(A)}):null,c.jsx(Go,{points:W.points,seriesLabel:W.label,additionalSeries:Y.slice(1),formatValue:F=>pt(F,_),ariaLabel:`${I}, ${Le(A)}, ${Y.length} series and ${W.points.length} buckets`,onBrush:E?F=>f(C,F):void 0})]},A)})}):Q=c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3",children:O.map(A=>{const Y=xr(A,w),W=v_(b,L,Y,V);return W.map((_,F)=>{const te=_.data.slice(0,30),pe=O.length>1||W.length>1,ne=[O.length>1?Le(A):"",W.length>1?_.label:""].filter(Boolean).join(" · ");return c.jsxs("div",{className:"min-w-0",children:[pe?c.jsx("h3",{className:"mb-1 text-2xs font-semibold text-muted",children:ne}):null,c.jsx(t0,{data:te,ariaLabel:`${I}, ${ne||Le(A)}, ${te.length} categories`,selectedLabel:R.filters[C],onSelect:G?fe=>{u(f_(e,C,fe,U,_.filterValues)),m(!0)}:void 0})]},`${A}-${_.label}-${F}`)})})});else{const A=b[0];Q=c.jsx("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:e.query.metrics.map(Y=>c.jsx(Nr,{metric:Y,label:Le(Y),value:A[xr(Y,w)],format:md(t,Y)},Y))})}return c.jsxs("article",{className:"min-w-0 overflow-hidden border border-line bg-surface","data-testid":"dashboard-chart","data-chart-id":e.id,children:[c.jsxs("header",{className:"flex min-h-12 flex-wrap items-center justify-between gap-2 border-b border-line px-3 py-2",children:[c.jsxs("div",{className:"min-w-0",children:[c.jsx("h2",{className:"truncate text-sm font-semibold text-ink",children:I}),c.jsxs("p",{className:"text-2xs text-faint",children:[Le(H),C?` by ${Le(C)}`:""]})]}),c.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.jsx("button",{type:"button","aria-expanded":h,onClick:()=>m(A=>!A),className:"border border-line px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:h?"Hide details":"Drill details"}),c.jsx("a",{href:g_(n,e,a,g,t),className:"border border-line px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Explore from here"}),c.jsx(J_,{chart:e,columns:w,rows:b})]})]}),c.jsx("div",{className:"min-h-64 overflow-hidden p-3",children:Q}),h?c.jsx(q_,{chart:e,columns:w,rows:b,loading:x.loading,onDrill:(A,Y)=>u({[A]:Y})}):null,(se=x.result)!=null&&se.sql?c.jsx("div",{className:"border-t border-line px-3 py-2",children:c.jsx(au,{queries:{Query:x.result.sql}})}):null]})}function X_({document:n,state:e,onLoad:t}){const[i,a]=M.useState(""),[u,f]=M.useState(()=>S_(n)),[h,m]=M.useState(!1);function g(v){f(v),m(!__(n,v))}return c.jsxs("details",{className:"relative",children:[c.jsx("summary",{className:"cursor-pointer list-none border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Saved views"}),c.jsxs("div",{className:"absolute right-0 z-50 mt-1 w-72 border border-line bg-surface p-3 shadow-[var(--shadow)]",children:[c.jsx("p",{className:"mb-2 text-2xs text-faint",children:"Stored only in this browser. Nothing is written to the server."}),c.jsxs("div",{className:"flex gap-1",children:[c.jsx("input",{value:i,onChange:v=>a(v.target.value),placeholder:"View name","aria-label":"Saved view name",className:"min-w-0 flex-1 border border-line bg-bg px-2 py-1 text-xs text-ink"}),c.jsx("button",{type:"button",disabled:!i.trim(),onClick:()=>{const v=[...u.filter(x=>x.name!==i.trim()),{name:i.trim(),state:e}];g(v),a("")},className:"border border-line px-2 py-1 text-2xs text-muted hover:text-ink disabled:opacity-40",children:"Save"})]}),h?c.jsx("p",{role:"alert",className:"mt-2 text-2xs text-danger",children:"Browser storage is unavailable."}):null,c.jsx("div",{className:"mt-2 flex flex-col gap-1",children:u.length?u.map(v=>c.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-line pt-1",children:[c.jsx("button",{type:"button",onClick:()=>t(v.state),className:"min-w-0 flex-1 truncate text-left text-xs text-muted hover:text-ink",children:v.name}),c.jsx("button",{type:"button","aria-label":`Delete saved view ${v.name}`,onClick:()=>g(u.filter(x=>x.name!==v.name)),className:"text-2xs text-faint hover:text-danger",children:"Delete"})]},v.name)):c.jsx("span",{className:"text-2xs text-faint",children:"No local views yet."})})]})]})}function e2(){const[n,e]=M.useState(!1);return c.jsx("button",{type:"button",title:"Copies the active tab, filters, and brushed ranges. Data is queried live; local saved views are not shared.",onClick:async()=>{await navigator.clipboard.writeText(window.location.href),e(!0),window.setTimeout(()=>e(!1),1200)},className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:n?"Share URL copied":"Copy share URL"})}function t2({document:n,catalog:e,backend:t}){const[i,a]=M.useState(()=>b_(window.location.search,n)),u=n.tabs.find(b=>b.id===i.tab)??n.tabs[0];M.useEffect(()=>{window.document.title=n.title},[n.title]),M.useEffect(()=>{const b=w_(i,n);window.history.replaceState(null,"",`${window.location.pathname}${b?`?${b}`:""}`)},[n,i]);function f(b,w){var C,O;const j=eu(n,b);if((((O=(C=n.defaults)==null?void 0:C.interactions)==null?void 0:O.scope)??"dashboard")==="chart"){a(H=>{var L;return{...H,chartFilters:{...H.chartFilters??{},[j]:{...((L=H.chartFilters)==null?void 0:L[j])??{},...w}}}});return}a(H=>({...H,filters:{...H.filters,...w},filterSources:{...H.filterSources,...Object.fromEntries(Object.keys(w).map(L=>[L,j]))}}))}function h(b,w,j){var O,H;const C=eu(n,b);if((((H=(O=n.defaults)==null?void 0:O.interactions)==null?void 0:H.scope)??"dashboard")==="chart"){a(L=>{const R={...L.chartRanges??{}},T={...R[C]??{}};return j?T[w]=j:delete T[w],Object.keys(T).length?R[C]=T:delete R[C],{...L,chartRanges:R}});return}a(L=>{const R={...L.ranges},T={...L.rangeSources};return j?(R[w]=j,T[w]=C):(delete R[w],delete T[w]),{...L,ranges:R,rangeSources:T}})}const m=c.jsxs(c.Fragment,{children:[c.jsx(X_,{document:n,state:i,onLoad:a}),c.jsx(e2,{}),c.jsx($o,{}),c.jsx(Y_,{})]}),g=Object.entries(i.chartFilters??{}).flatMap(([b,w])=>Object.entries(w).map(([j,C])=>({source:b,dimension:j,value:C}))),v=Object.entries(i.chartRanges??{}).flatMap(([b,w])=>Object.entries(w).map(([j,C])=>({source:b,dimension:j,range:C}))),x=Object.entries(i.filters).length||Object.entries(i.ranges).length||g.length||v.length?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"shrink-0 text-2xs font-semibold uppercase tracking-wide text-faint",children:"Filters"}),Object.entries(i.filters).map(([b,w])=>c.jsxs("button",{type:"button","aria-label":`Remove filter ${Le(b)} ${w}`,onClick:()=>a(j=>{const C={...j.filters},O={...j.filterSources};return delete C[b],delete O[b],{...j,filters:C,filterSources:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(b)," = ",w," ×"]},b)),Object.entries(i.ranges).map(([b,w])=>c.jsxs("button",{type:"button","aria-label":`Remove range ${Le(b)} ${w.from} to ${w.to}`,onClick:()=>a(j=>{const C={...j.ranges},O={...j.rangeSources};return delete C[b],delete O[b],{...j,ranges:C,rangeSources:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(b),": ",w.from,"–",w.to," ×"]},`range-${b}`)),g.map(({source:b,dimension:w,value:j})=>c.jsxs("button",{type:"button","aria-label":`Remove filter ${Le(w)} ${j} from ${b}`,onClick:()=>a(C=>{const O={...C.chartFilters??{}},H={...O[b]??{}};return delete H[w],Object.keys(H).length?O[b]=H:delete O[b],{...C,chartFilters:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(w)," = ",j," · ",b," ×"]},`chart-filter-${b}-${w}`)),v.map(({source:b,dimension:w,range:j})=>c.jsxs("button",{type:"button","aria-label":`Remove range ${Le(w)} ${j.from} to ${j.to} from ${b}`,onClick:()=>a(C=>{const O={...C.chartRanges??{}},H={...O[b]??{}};return delete H[w],Object.keys(H).length?O[b]=H:delete O[b],{...C,chartRanges:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(w),": ",j.from,"–",j.to," · ",b," ×"]},`chart-range-${b}-${w}`)),c.jsx("button",{type:"button",onClick:()=>a(b=>({...b,filters:{},ranges:{},filterSources:{},rangeSources:{},chartFilters:{},chartRanges:{}})),className:"text-2xs text-muted hover:text-ink",children:"Clear all"})]}):void 0;return c.jsx(kv,{brand:c.jsxs("div",{className:"min-w-0",children:[c.jsx("h1",{className:"truncate text-sm font-semibold text-ink",children:n.title}),c.jsx("p",{className:"text-2xs text-faint",children:"Declarative dashboard"})]}),toolbar:m,filters:x,rail:null,showRail:!1,children:c.jsxs("div",{"data-testid":"dashboard-document",className:"flex min-h-full flex-col",children:[c.jsx("nav",{className:"flex shrink-0 gap-1 overflow-x-auto border-b border-line bg-surface px-3 pt-2","aria-label":"Dashboard tabs",children:n.tabs.map(b=>c.jsx("button",{type:"button",role:"tab","aria-selected":b.id===(u==null?void 0:u.id),"data-tab-id":b.id,onClick:()=>a(w=>{var j,C;return w.tab===b.id?w:(((C=(j=n.defaults)==null?void 0:j.interactions)==null?void 0:C.scope)??"dashboard")==="dashboard"?{...w,tab:b.id}:{...w,tab:b.id,filters:{},ranges:{},filterSources:{},rangeSources:{},chartFilters:{},chartRanges:{}}}),className:"border border-b-0 border-line px-3 py-2 text-xs text-muted aria-selected:border-accent aria-selected:bg-bg aria-selected:text-ink",children:j_(b)},b.id))}),u?c.jsx("section",{className:"grid min-w-0 grid-cols-1 gap-3 p-3 xl:grid-cols-2","data-testid":"dashboard-chart-grid","data-tab-id":u.id,children:u.charts.map(b=>c.jsx(Z_,{document:n,chart:b,catalog:e,backend:t,state:i,setFilters:w=>f(b,w),setRange:(w,j)=>h(b,w,j)},b.id))}):c.jsx(Xn,{title:"No dashboard tabs",message:"This dashboard document has no tabs to render."})]})})}function sy(){const n=Tv();return c.jsxs("span",{role:"status","aria-live":"polite","aria-atomic":"true",className:"flex items-center gap-1.5 text-2xs text-faint",title:n?"Updating data":"Data is up to date",children:[n?c.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",className:"spinner size-3.5 text-accent",fill:"none",stroke:"currentColor",strokeWidth:"3",children:c.jsx("path",{d:"M12 3a9 9 0 1 0 9 9",strokeLinecap:"round"})}):c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-full bg-accent"}),c.jsx("span",{className:"sr-only",children:n?"Updating data":"Data is up to date"})]})}function n2(){const[n,e]=M.useState(!1);return c.jsx("button",{type:"button",onClick:async()=>{await navigator.clipboard.writeText(window.location.href),e(!0),window.setTimeout(()=>e(!1),1200)},className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:n?"Copied":"Copy link"})}function dl({children:n}){return c.jsx("div",{className:"grid h-screen place-items-center bg-bg p-6",children:n})}function r2({backend:n,onAuthenticated:e}){const[t,i]=M.useState(""),[a,u]=M.useState(null),[f,h]=M.useState(!1);return c.jsxs("div",{className:"w-full max-w-sm border border-line bg-surface p-6 shadow-sm",children:[c.jsx("h1",{className:"text-base font-semibold text-ink",children:"Connect to Sidemantic"}),c.jsx("p",{className:"mt-2 text-xs leading-5 text-muted",children:"Enter the API bearer once. It is exchanged for a short-lived, HttpOnly browser session where supported, and is never placed in the URL or browser storage."}),c.jsxs("form",{className:"mt-5 space-y-3",onSubmit:async m=>{m.preventDefault(),h(!0),u(null);try{await n.createBrowserSession(t),i(""),e()}catch(g){u(g instanceof Error?g.message:String(g))}finally{h(!1)}},children:[c.jsx("label",{className:"block text-xs font-medium text-ink",htmlFor:"api-token",children:"API bearer token"}),c.jsx("input",{id:"api-token",type:"password",autoComplete:"off",required:!0,value:t,onChange:m=>i(m.target.value),className:"w-full border border-line bg-bg px-3 py-2 text-sm text-ink outline-none focus:border-accent"}),a?c.jsx("p",{className:"text-xs text-red-700",children:a}):null,c.jsx("button",{type:"submit",disabled:f||!t,className:"w-full bg-accent px-3 py-2 text-xs font-semibold text-white disabled:opacity-50",children:f?"Connecting…":"Connect"})]})]})}function s2(){const{state:n,dispatch:e,catalog:t,initial:i,dashboard:a}=ls(),u=!!a,f=n.view==="home"&&!u,h=t.models.find(R=>R.name===n.model),m=M.useMemo(()=>Cs(t,a,n.dashboardTab),[t,a,n.dashboardTab]),g=M.useMemo(()=>a?Cv(t,a,n.dashboardTab):i,[t,a,i,n.dashboardTab]),v=n.dateRange!=null||Object.keys(n.filters).length>0,x=(m==null?void 0:m.timeDimension)??(h==null?void 0:h.timeDimension),b=!!x,w=lS(x==null?void 0:x.supportedGranularities,n.grain),j=M.useMemo(()=>{const R=new Map;for(const T of t.models)for(const E of T.dimensions)R.set(E.ref,{dim:E,model:T});return R},[t]),C=Object.entries(n.filters).flatMap(([R,T])=>{const E=j.get(R);return E?[c.jsx(Od,{dim:E.dim,model:E.model,filter:T,onRemove:()=>e({type:"removeFilterDim",dim:R})},R)]:[]}),O=c.jsx(rS,{dashboardTitle:a==null?void 0:a.title,modelLabel:!f&&!u?h==null?void 0:h.label:void 0,onHome:()=>e({type:"setView",view:"home"})}),H=f?c.jsxs(c.Fragment,{children:[c.jsx($o,{}),c.jsx(sy,{})]}):c.jsxs(c.Fragment,{children:[a?c.jsx("div",{className:"flex items-center border border-line bg-surface",role:"tablist","aria-label":"Dashboard tabs",children:a.tabs.map(R=>{const T=R.id===n.dashboardTab;return c.jsx("button",{type:"button",role:"tab","aria-selected":T,className:`px-2 py-1 text-2xs ${T?"bg-accent text-white":"text-muted hover:text-ink"}`,onClick:()=>{const E=Cs(t,a,R.id);E&&e({type:"setDashboardTab",tab:E.id,model:E.model.name,metric:E.selectedMetric,grain:E.grain})},children:R.label??R.id},R.id)})}):c.jsx(Lv,{view:n.view,onChange:R=>e({type:"setView",view:R})}),c.jsx(Bv,{range:n.dateRange,disabled:!b,onChange:R=>e({type:"setDateRange",range:R}),comparison:n.comparison,comparisonRange:n.comparisonRange,onComparisonChange:(R,T)=>e({type:"setComparison",comparison:R,range:T})}),c.jsx(Td,{grain:n.grain,options:w,disabled:!b,onChange:R=>e({type:"setGrain",grain:R})}),c.jsx(e_,{timezone:n.timezone,disabled:!b,onChange:R=>e({type:"setTimezone",timezone:R})}),v?c.jsx("button",{type:"button",onClick:()=>e({type:"reset",initial:g}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Reset"}):null,c.jsx(n2,{}),c.jsx($o,{}),c.jsx(sy,{})]}),L=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"shrink-0 text-xs font-medium text-muted",children:"Filters"}),C.length?C:c.jsx("span",{className:"text-2xs text-faint",children:"None"}),h?c.jsx(GS,{model:h}):null,C.length?c.jsx("button",{type:"button",onClick:()=>e({type:"clearFilters"}),className:"shrink-0 text-2xs text-muted underline-offset-2 hover:text-ink hover:underline",children:"Clear"}):null]});return c.jsx(kv,{brand:O,toolbar:H,filters:f?void 0:L,rail:c.jsx(QS,{}),showRail:!f&&!u,openRailRequest:n.view==="pivot",drawer:f?void 0:c.jsx(s_,{}),children:c.jsxs(KS,{children:[n.view==="home"?c.jsx(k_,{}):null,n.view==="explore"?c.jsx(W_,{}):null,n.view==="pivot"?c.jsx(H_,{}):null]},n.view)})}function i2(){const[n,e]=M.useState(!1),t=M.useMemo(()=>new nS({transport:"json",onUnauthorized:()=>e(!0)}),[]),[i,a]=M.useState(null),[u,f]=M.useState(null),[h,m]=M.useState(0),g=a_(window.location.pathname,window.location.search);return M.useEffect(()=>{let v=!0;return Promise.all([t.getCatalog(),g?Promise.resolve(null):t.getDashboard()]).then(([x,b])=>v&&a({catalog:x,dashboard:b})).catch(x=>v&&f(x instanceof Error?x.message:String(x))),()=>{v=!1}},[t,g,h]),n?c.jsx(dl,{children:c.jsx(r2,{backend:t,onAuthenticated:()=>{e(!1),f(null),m(v=>v+1)}})}):u?c.jsx(dl,{children:c.jsx(Bi,{title:"Could not load semantic layer",message:u})}):i?i.catalog.models.length?i.dashboard?c.jsx(t2,{document:i.dashboard,catalog:i.catalog,backend:t}):c.jsx($S,{catalog:i.catalog,backend:t,children:c.jsx(s2,{})}):c.jsx(dl,{children:c.jsx(Xn,{title:"Empty semantic layer",message:"No models were found."})}):c.jsx(dl,{children:c.jsx(af,{title:"Loading semantic layer",message:"Reading models and metrics…"})})}const Zt={top:14,right:48,bottom:26,left:48};function o2({data:n,barLabel:e="Bars",lineLabel:t="Line",height:i=220,formatBar:a=pt,formatLine:u=pt,ariaLabel:f}){const h=M.useRef(null),[m,g]=M.useState(640),{tip:v,handlers:x}=Dr();if(M.useEffect(()=>us(h.current,240,g),[]),n.length===0)return c.jsx("div",{className:"grid h-[220px] place-items-center text-xs text-faint",children:"No data to chart."});const b=n.map(ae=>Number.isFinite(ae.bar)?ae.bar:0),w=n.map(ae=>Number.isFinite(ae.line)?ae.line:0),j=Math.min(0,...b),C=Math.max(0,...b),O=C-j||1,H=Math.min(...w),L=Math.max(...w),R=L-H||1,T=m-Zt.left-Zt.right,E=i-Zt.top-Zt.bottom,I=ae=>Zt.top+(1-(ae-j)/O)*E,U=ae=>Zt.top+(1-(ae-H)/R)*E,G=T/n.length,V=Math.max(8,Math.min(48,G*.55)),Q=ae=>Zt.left+G*ae+G/2,z=I(0),ee=n.map((ae,re)=>`${Q(re).toFixed(1)},${U(w[re]).toFixed(1)}`).join(" L "),X=yn(1),ie=f||`Combo chart, ${n.length} categories: ${e} bars with a ${t} line`;return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"mb-1 flex items-center gap-3 text-2xs text-faint",children:[c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block h-2 w-3 bg-chart-primary"})," ",e]}),c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block h-0.5 w-3",style:{background:X}})," ",t]})]}),c.jsxs("svg",{ref:h,role:"img","aria-label":ie,className:"w-full overflow-hidden",style:{height:i},viewBox:`0 0 ${m} ${i}`,children:[Ts(j,C,4).map((ae,re)=>{const se=I(ae);return c.jsxs("g",{children:[c.jsx("line",{x1:Zt.left,x2:m-Zt.right,y1:se,y2:se,className:"stroke-line"}),c.jsx("text",{x:Zt.left-6,y:se+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(ae)})]},re)}),Ts(H,L,4).map((ae,re)=>c.jsx("text",{x:m-Zt.right+6,y:U(ae)+3,textAnchor:"start",className:"text-[10px]",fill:X,children:u(ae)},re)),c.jsx("line",{x1:Zt.left,x2:m-Zt.right,y1:z,y2:z,className:"stroke-line"}),n.map((ae,re)=>{const se=b[re],A=I(se);return c.jsxs("g",{children:[c.jsx("rect",{x:Q(re)-V/2,y:Math.min(A,z),width:V,height:Math.abs(A-z),"data-label":ae.label,"data-bar":se,"data-line":w[re],className:se<0?"fill-danger":"fill-chart-primary",...x(c.jsx(os,{title:ae.label,rows:[{label:e,value:a(se),swatch:"var(--chart-primary)"},{label:t,value:u(w[re]),swatch:X}]}))}),c.jsx("text",{x:Q(re),y:i-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:ae.label.slice(0,8)})]},ae.label)}),c.jsx("path",{d:`M ${ee}`,fill:"none",stroke:X,strokeWidth:1.75}),n.map((ae,re)=>c.jsx("circle",{cx:Q(re),cy:U(w[re]),r:3,fill:X,...x(c.jsx(os,{title:ae.label,rows:[{label:e,value:a(b[re]),swatch:"var(--chart-primary)"},{label:t,value:u(w[re]),swatch:X}]}))},ae.label))]}),c.jsx(rr,{tip:v})]})}const a2={primary:"border-accent bg-accent-soft font-medium text-accent hover:bg-accent hover:text-surface",secondary:"border-line bg-surface text-ink hover:bg-surface-soft",ghost:"border-transparent bg-transparent text-muted hover:bg-surface-soft hover:text-ink",danger:"border-danger bg-danger-soft font-medium text-danger hover:bg-danger hover:text-surface"};function No({variant:n="secondary",size:e="md",type:t="button",className:i,...a}){const u=e==="sm"?"h-6 px-2.5 text-2xs":"h-7 px-3 text-xs";return c.jsx("button",{type:t,"data-variant":n,className:`inline-flex items-center justify-center rounded-full border ${u} ${a2[n]} disabled:pointer-events-none disabled:opacity-50 ${i??""}`,...a})}function l2(n,e){const t=e.trim().toLowerCase();return t?n.filter(i=>i.value.toLowerCase().includes(t)||(i.label??"").toLowerCase().includes(t)):n}function iy(n){const{options:e,placeholder:t="Search…",ariaLabel:i,disabled:a,maxVisible:u=50}=n,f=M.useId(),h=M.useRef(null),[m,g]=M.useState(!1),[v,x]=M.useState(""),[b,w]=M.useState(0),j=M.useMemo(()=>l2(e,v).slice(0,u),[e,v,u]),C=n.multiple?n.values:n.value!=null?[n.value]:[],O=new Set(C),H=I=>{var U;return((U=e.find(G=>G.value===I))==null?void 0:U.label)??I};M.useEffect(()=>{if(!m)return;function I(U){h.current&&!h.current.contains(U.target)&&g(!1)}return document.addEventListener("mousedown",I,!0),()=>document.removeEventListener("mousedown",I,!0)},[m]);function L(I){if(I){if(n.multiple){const U=O.has(I.value)?n.values.filter(G=>G!==I.value):[...n.values,I.value];n.onChange(U);return}n.onChange(I.value),x(""),g(!1)}}function R(){n.multiple?n.onChange([]):n.onChange(null),x("")}function T(I){I.key==="ArrowDown"?(I.preventDefault(),g(!0),w(U=>Math.min(U+1,j.length-1))):I.key==="ArrowUp"?(I.preventDefault(),w(U=>Math.max(U-1,0))):I.key==="Enter"?(I.preventDefault(),m&&L(j[b])):I.key==="Escape"?g(!1):I.key==="Backspace"&&n.multiple&&!v&&n.values.length&&n.onChange(n.values.slice(0,-1))}const E=!n.multiple&&n.value!=null?H(n.value):t;return c.jsxs("div",{ref:h,className:"relative inline-flex min-w-40 flex-wrap items-center gap-1 text-xs",children:[n.multiple?n.values.map(I=>c.jsxs("span",{"data-chip":I,className:"inline-flex items-center gap-1 rounded-full bg-surface-soft px-2 py-0.5 leading-4 text-muted",children:[c.jsx("span",{className:"max-w-32 truncate",children:H(I)}),c.jsx("button",{type:"button","aria-label":`Remove ${H(I)}`,disabled:a,onClick:()=>n.onChange(n.values.filter(U=>U!==I)),className:"text-faint hover:text-ink",children:"×"})]},I)):null,c.jsxs("span",{className:"relative min-w-28 flex-1",children:[c.jsx("input",{type:"text",role:"combobox","aria-expanded":m,"aria-controls":f,"aria-autocomplete":"list","aria-activedescendant":m&&j[b]?`${f}-${b}`:void 0,"aria-label":i,disabled:a,placeholder:E,value:v,onChange:I=>{x(I.target.value),w(0),g(!0)},onFocus:()=>g(!0),onKeyDown:T,className:"h-7 w-full rounded-full border border-line bg-surface px-3 text-ink placeholder:text-faint disabled:opacity-50"}),C.length>0?c.jsx("button",{type:"button","aria-label":"Clear selection",disabled:a,onClick:R,className:"absolute right-1 top-1/2 -translate-y-1/2 px-1 text-faint hover:text-ink",children:"×"}):null]}),m?c.jsxs("ul",{id:f,role:"listbox","aria-multiselectable":n.multiple||void 0,className:"absolute left-0 top-full z-50 mt-1 max-h-56 w-full min-w-40 overflow-y-auto rounded-xl border border-line bg-surface p-1.5 shadow-[var(--shadow)]",children:[j.length===0?c.jsx("li",{className:"px-1.5 py-1 text-faint",children:"No matches"}):null,j.map((I,U)=>c.jsxs("li",{id:`${f}-${U}`,role:"option","aria-selected":O.has(I.value),"data-active":U===b||void 0,onMouseEnter:()=>w(U),onMouseDown:G=>{G.preventDefault(),L(I)},className:"cursor-pointer truncate rounded-md px-2 py-1 text-muted data-[active=true]:bg-surface-soft data-[active=true]:text-ink",children:[I.label??I.value,O.has(I.value)?c.jsx("span",{className:"float-right text-accent",children:"✓"}):null]},I.value))]}):null]})}function u2({title:n,eyebrow:e="Sidemantic",status:t,toolbar:i,children:a}){return c.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-5 text-ink sm:px-6",children:[c.jsxs("header",{className:"flex flex-wrap items-end justify-between gap-4 border-b border-line pb-4",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-xs font-medium text-faint",children:e}),c.jsx("h1",{className:"mt-1 text-2xl font-semibold text-ink",children:n})]}),t?c.jsx("div",{className:"text-sm text-muted",children:t}):null]}),i?c.jsx("section",{className:"flex flex-wrap gap-2 py-3",children:i}):null,c.jsx("section",{className:"grid gap-4 py-4",children:a})]})}const c2=["Su","Mo","Tu","We","Th","Fr","Sa"],oy=["January","February","March","April","May","June","July","August","September","October","November","December"];function r0(n,e,t){return`${String(n).padStart(4,"0")}-${String(e+1).padStart(2,"0")}-${String(t).padStart(2,"0")}`}function d2(n,e){const t=new Date(Date.UTC(n,e,1)),i=new Date(t);i.setUTCDate(1-t.getUTCDay());const a=[],u=new Date(i);do{const f=[];for(let h=0;h<7;h+=1)f.push({iso:r0(u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()),day:u.getUTCDate(),inMonth:u.getUTCMonth()===e}),u.setUTCDate(u.getUTCDate()+1);a.push(f)}while(u.getUTCMonth()===e);return a}function yd(){const n=new Date;return r0(n.getFullYear(),n.getMonth(),n.getDate())}function ay(n){var T;const{inline:e,ariaLabel:t,disabled:i}=n,a=n.mode==="range",u=a?((T=n.value)==null?void 0:T.from)??null:n.value,[f,h]=M.useState(()=>Number((u??yd()).slice(0,4))),[m,g]=M.useState(()=>Number((u??yd()).slice(5,7))-1),[v,x]=M.useState(null),b=M.useRef(null);function w(E){const I=new Date(Date.UTC(f,m+E,1));h(I.getUTCFullYear()),g(I.getUTCMonth())}function j(E){if(!a){n.onChange(E),b.current&&(b.current.open=!1);return}if(!v){x(E);return}const[I,U]=v<=E?[v,E]:[E,v];n.onChange({from:I,to:U}),x(null),b.current&&(b.current.open=!1)}function C(E){return a?v?E===v:n.value!=null&&E>=n.value.from&&E<=n.value.to:E===n.value}function O(E){return a?v?E===v:n.value!=null&&(E===n.value.from||E===n.value.to):E===n.value}const H=yd(),L=c.jsxs("div",{className:"w-56 select-none rounded-xl border border-line bg-surface p-2.5 text-2xs","aria-label":t??"Calendar",children:[c.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[c.jsx("button",{type:"button","aria-label":"Previous month",onClick:()=>w(-1),className:"px-1.5 py-0.5 text-muted hover:bg-surface-soft hover:text-ink",children:"‹"}),c.jsxs("span",{className:"font-medium text-ink",children:[oy[m]," ",f]}),c.jsx("button",{type:"button","aria-label":"Next month",onClick:()=>w(1),className:"px-1.5 py-0.5 text-muted hover:bg-surface-soft hover:text-ink",children:"›"})]}),c.jsx("div",{className:"grid grid-cols-7 text-center text-faint",children:c2.map(E=>c.jsx("span",{className:"py-0.5",children:E},E))}),c.jsx("div",{role:"grid","aria-label":`${oy[m]} ${f}`,children:d2(f,m).map((E,I)=>c.jsx("div",{role:"row",className:"grid grid-cols-7",children:E.map(U=>c.jsx("button",{type:"button",role:"gridcell","aria-selected":C(U.iso),"data-date":U.iso,onClick:()=>j(U.iso),className:`py-1 text-center tnum ${O(U.iso)?"bg-accent text-surface":C(U.iso)?"bg-accent-soft text-accent":U.inMonth?"text-ink hover:bg-surface-soft":"text-faint hover:bg-surface-soft"} ${U.iso===H?"underline underline-offset-2":""}`,children:U.day},U.iso))},I))}),a&&v?c.jsxs("p",{className:"mt-1 text-faint",children:["Start ",v," — pick an end date."]}):null,n.value!=null?c.jsx("button",{type:"button",onClick:()=>n.onChange(null),className:"mt-1 w-full rounded-lg border border-line px-2 py-1 text-left text-muted hover:bg-surface-soft",children:"Clear"}):null]});if(e)return L;const R=a?n.value?`${n.value.from} → ${n.value.to}`:"Any dates":n.value??"Any date";return c.jsxs("details",{ref:b,className:"relative inline-block text-xs",children:[c.jsxs("summary",{className:`flex cursor-pointer items-center h-7 gap-1.5 rounded-full border border-line bg-surface px-3 text-ink ${i?"pointer-events-none opacity-50":""}`,children:[c.jsx("span",{className:"text-faint",children:t??"Date"}),c.jsx("span",{className:"tnum",children:R}),c.jsx("span",{"aria-hidden":"true",className:"text-faint",children:"▾"})]}),c.jsx("div",{className:"absolute left-0 z-50 mt-1 shadow-[var(--shadow)]",children:L})]})}function f2({result:n,pageSize:e=10}){const t=(n==null?void 0:n.columns)??[];return c.jsx(Ho,{columns:t.map(i=>({key:i,label:Le(i),numeric:n==null?void 0:n.sample_rows.some(a=>typeof a[i]=="number")})),rows:(n==null?void 0:n.sample_rows)??[],pageSize:e,renderCell:(i,a)=>pt(a)})}function h2({data:n,height:e=200,ariaLabel:t}){return c.jsx("div",{style:{minHeight:e},children:c.jsx(Go,{points:n.map(({label:i,value:a})=>({x:i,y:a})),formatValue:i=>pt(i),ariaLabel:t})})}const s0=Math.PI*2;function p2(n){const e=n.map((a,u)=>({...a,colorIndex:u})).filter(a=>Number.isFinite(a.value)&&a.value>0),t=e.reduce((a,u)=>a+u.value,0);if(t<=0)return[];let i=-Math.PI/2;return e.map(a=>{const u=a.value/t,f=i;return i+=u*s0,{label:a.label,value:a.value,share:u,startAngle:f,endAngle:i,colorIndex:a.colorIndex}})}function m2(n,e,t,i,a,u){const f=Math.min(u-a,s0-1e-4),h=a+f,m=f>Math.PI?1:0,g=n+i*Math.cos(a),v=e+i*Math.sin(a),x=n+i*Math.cos(h),b=e+i*Math.sin(h),w=n+t*Math.cos(h),j=e+t*Math.sin(h),C=n+t*Math.cos(a),O=e+t*Math.sin(a);return[`M ${g.toFixed(2)} ${v.toFixed(2)}`,`A ${i} ${i} 0 ${m} 1 ${x.toFixed(2)} ${b.toFixed(2)}`,`L ${w.toFixed(2)} ${j.toFixed(2)}`,`A ${t} ${t} 0 ${m} 0 ${C.toFixed(2)} ${O.toFixed(2)}`,"Z"].join(" ")}function y2({data:n,height:e=200,centerLabel:t="Total",format:i=pt,ariaLabel:a}){const u=M.useRef(null),[f,h]=M.useState(360),{tip:m,handlers:g}=Dr();M.useEffect(()=>us(u.current,220,h),[]);const v=p2(n),x=v.reduce((L,R)=>L+R.value,0),b=Math.min(e,f*.55),w=b/2,j=e/2,C=b/2-6,O=Math.max(C*.62,C-34),H=a||`Donut chart, ${v.length} segments totaling ${Wt(x)}`;return v.length===0?c.jsx("div",{className:"grid h-[200px] place-items-center text-xs text-faint",children:"No positive values to chart."}):c.jsxs("div",{ref:u,className:"flex w-full items-center gap-4",style:{height:e},children:[c.jsxs("svg",{role:"img","aria-label":H,width:b,height:e,className:"shrink-0 overflow-hidden",children:[v.map(L=>c.jsx("path",{d:m2(w,j,O,C,L.startAngle,L.endAngle),fill:yn(L.colorIndex),stroke:"var(--surface)",strokeWidth:1,"data-label":L.label,"data-value":L.value,...g(c.jsx(os,{title:L.label,rows:[{label:"Value",value:i(L.value),swatch:yn(L.colorIndex)},{label:"Share",value:`${(L.share*100).toFixed(1)}%`}]}))},L.label)),c.jsx("text",{x:w,y:j-4,textAnchor:"middle",className:"fill-ink font-mono tnum text-sm font-medium",children:Wt(x)}),c.jsx("text",{x:w,y:j+12,textAnchor:"middle",className:"fill-faint text-[10px]",children:t})]}),c.jsx("ul",{className:"min-w-0 flex-1 space-y-1 text-2xs",children:v.map(L=>c.jsxs("li",{className:"flex items-center gap-2","data-label":L.label,children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 shrink-0",style:{background:yn(L.colorIndex)}}),c.jsx("span",{className:"truncate text-muted",children:L.label}),c.jsx("span",{className:"ml-auto font-mono tnum text-ink",children:i(L.value)}),c.jsxs("span",{className:"w-10 text-right font-mono tnum text-faint",children:[(L.share*100).toFixed(1),"%"]})]},L.label))}),c.jsx(rr,{tip:m})]})}const pr={top:8,right:8,bottom:26,left:76};function ly(n,e,t){if(t!=null&&t.length)return t;const i=[];for(const a of n)i.includes(a[e])||i.push(a[e]);return i}function g2({cells:n,xLabels:e,yLabels:t,height:i=240,format:a=pt,ariaLabel:u}){const f=M.useRef(null),[h,m]=M.useState(640),{tip:g,handlers:v}=Dr();M.useEffect(()=>us(f.current,240,m),[]);const x=ly(n,"x",e),b=ly(n,"y",t);if(x.length===0||b.length===0)return c.jsx("div",{className:"grid h-[240px] place-items-center text-xs text-faint",children:"No cells to chart."});const w=new Map(n.map(I=>[`${I.x}\0${I.y}`,I.value])),j=n.map(I=>Math.abs(I.value)).filter(Number.isFinite),C=Math.max(...j,0)||1,O=h-pr.left-pr.right,H=i-pr.top-pr.bottom,L=O/x.length,R=H/b.length,T=Math.max(1,Math.ceil(x.length/Math.max(1,Math.floor(O/56)))),E=u||`Heatmap, ${x.length} by ${b.length} cells`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:f,role:"img","aria-label":E,className:"w-full overflow-hidden",style:{height:i},viewBox:`0 0 ${h} ${i}`,children:[b.map((I,U)=>c.jsx("text",{x:pr.left-6,y:pr.top+U*R+R/2+3,textAnchor:"end",className:"fill-muted text-[10px]",children:I.slice(0,12)},I)),x.map((I,U)=>U%T===0?c.jsx("text",{x:pr.left+U*L+L/2,y:i-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:I.slice(0,8)},I):null),b.map((I,U)=>x.map((G,V)=>{const Q=w.get(`${G}\0${I}`),z=Q!=null&&Number.isFinite(Q),ee=z?.06+.94*(Math.abs(Q)/C):0;return c.jsx("rect",{x:pr.left+V*L+.5,y:pr.top+U*R+.5,width:Math.max(1,L-1),height:Math.max(1,R-1),"data-x":G,"data-y":I,"data-value":z?Q:void 0,className:z&&Q<0?"fill-danger":"fill-chart-primary",fillOpacity:z?ee:.03,...v(c.jsx(os,{title:`${I} / ${G}`,rows:[{label:"Value",value:z?a(Q):"no data"}]}))},`${G}\0${I}`)}))]}),c.jsx(rr,{tip:g})]})}function v2(n,e){const t=n.filter(Number.isFinite);if(t.length===0)return[];const i=Math.min(...t),a=Math.max(...t),u=Math.max(1,Math.floor(e??Math.min(40,Math.ceil(Math.log2(t.length)+1))));if(i===a)return[{x0:i,x1:a,count:t.length}];const f=(a-i)/u,h=Array.from({length:u},(m,g)=>({x0:i+g*f,x1:i+(g+1)*f,count:0}));for(const m of t){const g=Math.min(u-1,Math.floor((m-i)/f));h[g].count+=1}return h}const Cn={top:12,right:14,bottom:26,left:44};function x2({values:n,bins:e,height:t=200,format:i=Wt,ariaLabel:a}){const u=M.useRef(null),[f,h]=M.useState(640),{tip:m,handlers:g}=Dr();M.useEffect(()=>us(u.current,160,h),[]);const v=v2(n,e);if(v.length===0)return c.jsx("div",{className:"grid h-[200px] place-items-center text-xs text-faint",children:"No numeric values to chart."});const x=Math.max(...v.map(R=>R.count),1),b=f-Cn.left-Cn.right,w=t-Cn.top-Cn.bottom,j=R=>Cn.top+(1-R/x)*w,C=b/v.length,O=Ts(0,x,4),H=Math.max(1,Math.ceil(v.length/6)),L=a||`Histogram, ${v.length} bins from ${i(v[0].x0)} to ${i(v[v.length-1].x1)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:u,role:"img","aria-label":L,className:"w-full overflow-hidden",style:{height:t},viewBox:`0 0 ${f} ${t}`,children:[O.map((R,T)=>{const E=j(R);return c.jsxs("g",{children:[c.jsx("line",{x1:Cn.left,x2:f-Cn.right,y1:E,y2:E,className:"stroke-line"}),c.jsx("text",{x:Cn.left-6,y:E+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(R)})]},T)}),v.map((R,T)=>{const E=Cn.left+C*T,I=j(R.count);return c.jsx("rect",{x:E+.5,y:I,width:Math.max(1,C-1),height:Cn.top+w-I,"data-x0":R.x0,"data-x1":R.x1,"data-count":R.count,className:"fill-chart-primary",...g(c.jsx(os,{title:`${i(R.x0)} – ${i(R.x1)}`,rows:[{label:"Count",value:R.count.toLocaleString()}]}))},T)}),v.map((R,T)=>T%H===0?c.jsx("text",{x:Cn.left+C*T,y:t-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:i(R.x0)},T):null)]}),c.jsx(rr,{tip:m})]})}function b2(n){let e=2166136261;for(let t=0;t>>0}function w2(n){let e=n||1;return()=>{e|=0,e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function S2(n,e,{width:t=640,height:i=320,iterations:a=150}={}){if(n.length===0)return[];const u=w2(b2(n.map(G=>G.id).join("\0"))),f=new Map(n.map((G,V)=>[G.id,V])),h=n.map(()=>u()*t),m=n.map(()=>u()*i),g=n.map(()=>0),v=n.map(()=>0),x=n.map(()=>0),b=[];for(const G of e){const V=f.get(G.source),Q=f.get(G.target);V==null||Q==null||V===Q||(b.push([V,Q]),x[V]+=1,x[Q]+=1)}const w=t*i,j=Math.sqrt(w/n.length);let C=Math.max(t,i)/8;const O=C/(a+1);for(let G=0;G({...G,x:H+(h[V]-L)/I*(t-H*2),y:H+(m[V]-T)/U*(i-H*2),degree:x[V]}))}function _2({nodes:n,links:e,height:t=320,ariaLabel:i}){const a=M.useRef(null),[u,f]=M.useState(640),{tip:h,handlers:m}=Dr();M.useEffect(()=>us(a.current,240,f),[]);const g=M.useMemo(()=>S2(n,e,{width:u,height:t}),[n,e,u,t]),v=M.useMemo(()=>new Map(g.map(j=>[j.id,j])),[g]),x=M.useMemo(()=>[...new Set(n.map(j=>j.group??""))],[n]),b=Math.max(...e.map(j=>j.weight??1),1);if(g.length===0)return c.jsx("div",{className:"grid h-[320px] place-items-center text-xs text-faint",children:"No nodes to chart."});const w=i||`Network graph, ${n.length} nodes and ${e.length} links`;return c.jsxs(c.Fragment,{children:[x.length>1?c.jsx("div",{className:"mb-1 flex flex-wrap items-center gap-3 text-2xs text-faint",children:x.map((j,C)=>c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-full",style:{background:yn(C)}}),j||"(default)"]},j||"(default)"))}):null,c.jsxs("svg",{ref:a,role:"img","aria-label":w,className:"w-full overflow-hidden",style:{height:t},viewBox:`0 0 ${u} ${t}`,children:[e.map((j,C)=>{const O=v.get(j.source),H=v.get(j.target);return!O||!H?null:c.jsx("line",{x1:O.x,y1:O.y,x2:H.x,y2:H.y,className:"stroke-line",strokeWidth:.75+2.25*((j.weight??1)/b),"data-source":j.source,"data-target":j.target},C)}),g.map(j=>{const C=5+Math.min(9,j.degree*1.5);return c.jsxs("g",{children:[c.jsx("circle",{cx:j.x,cy:j.y,r:C,fill:yn(x.indexOf(j.group??"")),stroke:"var(--surface)",strokeWidth:1.5,"data-id":j.id,"data-degree":j.degree,...m(c.jsx(os,{title:j.label??j.id,rows:[{label:"Connections",value:String(j.degree)},...j.group?[{label:"Group",value:j.group,swatch:yn(x.indexOf(j.group))}]:[]]}))}),c.jsx("text",{x:j.x,y:j.y-C-4,textAnchor:"middle",className:"pointer-events-none fill-muted text-[10px]",children:(j.label??j.id).slice(0,14)})]},j.id)})]}),c.jsx(rr,{tip:h})]})}function wl({value:n,options:e,onChange:t,label:i,ariaLabel:a,placeholder:u,disabled:f}){return c.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-faint",children:[i?c.jsx("span",{className:"hidden sm:inline",children:i}):null,c.jsxs("select",{"aria-label":a??i,value:n,disabled:f,onChange:h=>t(h.target.value),className:"h-7 rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50",children:[u?c.jsx("option",{value:"",disabled:!0,children:u}):null,e.map(h=>c.jsx("option",{value:h.value,children:h.label??h.value},h.value))]})]})}const un={top:12,right:14,bottom:26,left:48};function N2(n,e,t){return Math.min(Math.max(n,e),t)}function j2({labels:n,series:e,height:t=240,format:i=pt,formatLabel:a=f=>f,ariaLabel:u}){const f=M.useRef(null),[h,m]=M.useState(640),[g,v]=M.useState(null);M.useEffect(()=>us(f.current,240,m),[]);const x=n.length;if(x<2||e.length===0)return c.jsx("div",{className:"grid h-[240px] place-items-center text-xs text-faint",children:"Not enough data to chart."});const b=e.map(V=>({name:V.name,values:n.map((Q,z)=>{const ee=V.values[z];return Number.isFinite(ee)&&ee>0?ee:0})})),w=[];let j=n.map(()=>0);for(const V of b){const Q=V.values.map((z,ee)=>j[ee]+z);w.push(Q),j=Q}const C=Math.max(...j,1),O=h-un.left-un.right,H=t-un.top-un.bottom,L=V=>un.left+V/(x-1)*O,R=V=>un.top+(1-V/C)*H,T=Math.max(1,Math.ceil(x/8)),E=u||`Stacked area chart, ${e.length} series over ${x} points`;function I(V){const Q=w[V],z=V===0?n.map(()=>0):w[V-1],ee=Q.map((ie,ae)=>`${L(ae).toFixed(1)},${R(ie).toFixed(1)}`).join(" L "),X=[...z.keys()].reverse().map(ie=>`${L(ie).toFixed(1)},${R(z[ie]).toFixed(1)}`).join(" L ");return`M ${ee} L ${X} Z`}function U(V){const Q=V.currentTarget.getBoundingClientRect(),z=(V.clientX-Q.left)/Q.width*h,ee=Math.round((z-un.left)/O*(x-1));v(ee>=0&&eec.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2",style:{background:yn(Q)}}),V.name]},V.name))}),c.jsxs("svg",{role:"img","aria-label":E,className:"w-full overflow-hidden",style:{height:t},viewBox:`0 0 ${h} ${t}`,onMouseMove:U,onMouseLeave:()=>v(null),children:[Ts(0,C,4).map((V,Q)=>{const z=R(V);return c.jsxs("g",{children:[c.jsx("line",{x1:un.left,x2:h-un.right,y1:z,y2:z,className:"stroke-line"}),c.jsx("text",{x:un.left-6,y:z+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(V)})]},Q)}),b.map((V,Q)=>c.jsx("path",{d:I(Q),fill:yn(Q),fillOpacity:.8,"data-series":V.name},V.name)),g!=null?c.jsx("line",{x1:L(g),x2:L(g),y1:un.top,y2:t-un.bottom,className:"stroke-faint",strokeDasharray:"3 3"}):null,n.map((V,Q)=>Q%T===0||Q===x-1?c.jsx("text",{x:L(Q),y:t-8,textAnchor:"middle",className:"fill-faint font-mono text-[10px]",children:a(V)},V):null)]}),g!=null?c.jsxs("div",{className:"pointer-events-none absolute top-8 z-20 -translate-x-1/2 whitespace-nowrap border border-line bg-surface px-2 py-1.5 text-2xs shadow-[var(--shadow)]",style:{left:G},children:[c.jsx("div",{className:"mb-0.5 font-mono text-faint",children:a(n[g])}),b.map((V,Q)=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs("span",{className:"flex items-center gap-1 text-muted",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2",style:{background:yn(Q)}}),V.name]}),c.jsx("span",{className:"font-mono tnum text-ink",children:i(V.values[g])})]},V.name))]}):null]})}function k2({checked:n,onChange:e,label:t,ariaLabel:i,disabled:a}){return c.jsxs("label",{className:`flex items-center gap-1.5 text-xs ${a?"opacity-50":""}`,children:[c.jsx("button",{type:"button",role:"switch","aria-checked":n,"aria-label":i??t,disabled:a,onClick:()=>e(!n),"data-checked":n||void 0,className:`relative h-4 w-7 shrink-0 rounded-full border transition-colors ${n?"border-accent bg-accent":"border-line bg-surface-soft"}`,children:c.jsx("span",{"aria-hidden":"true",className:`absolute top-1/2 size-3 -translate-y-1/2 rounded-full bg-surface shadow transition-[left] ${n?"left-[14px]":"left-[2px]"}`})}),t?c.jsx("span",{className:"text-muted",children:t}):null]})}function I2({tabs:n,active:e,onChange:t,ariaLabel:i="Tabs"}){return c.jsx("div",{role:"tablist","aria-label":i,className:"inline-flex items-center gap-0.5 rounded-full border border-line bg-surface p-px",children:n.map(a=>c.jsx("button",{role:"tab",type:"button","aria-selected":e===a.key,"data-tab":a.key,"data-selected":e===a.key||void 0,onClick:()=>t(a.key),className:"inline-flex h-6 items-center rounded-full px-2.5 text-xs font-medium text-muted hover:bg-surface-soft hover:text-ink data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent",children:a.label},a.key))})}function M2({content:n,children:e,className:t}){const{tip:i,handlers:a}=Dr();return c.jsxs(c.Fragment,{children:[c.jsx("span",{className:t??"inline-flex",...a(n),children:e}),c.jsx(rr,{tip:i})]})}function D2(n){let e=0;return n.map(t=>{const i=Number.isFinite(t.value)?t.value:0;if(t.isTotal)return e=i,{...t,value:i,start:0,end:i};const a=e;return e+=i,{...t,value:i,start:a,end:e}})}const cn={top:12,right:14,bottom:26,left:48};function C2({data:n,height:e=220,format:t=pt,ariaLabel:i}){const a=M.useRef(null),[u,f]=M.useState(640),{tip:h,handlers:m}=Dr();M.useEffect(()=>us(a.current,200,f),[]);const g=D2(n);if(g.length===0)return c.jsx("div",{className:"grid h-[220px] place-items-center text-xs text-faint",children:"No steps to chart."});const v=g.flatMap(E=>[E.start,E.end]),x=Math.min(0,...v),b=Math.max(0,...v),w=b-x||1,j=u-cn.left-cn.right,C=e-cn.top-cn.bottom,O=E=>cn.top+(1-(E-x)/w)*C,H=j/g.length,L=Math.max(10,Math.min(56,H*.62)),R=Ts(x,b,4),T=i||`Waterfall chart, ${g.length} steps ending at ${t(g[g.length-1].end)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:a,role:"img","aria-label":T,className:"w-full overflow-hidden",style:{height:e},viewBox:`0 0 ${u} ${e}`,children:[R.map((E,I)=>{const U=O(E);return c.jsxs("g",{children:[c.jsx("line",{x1:cn.left,x2:u-cn.right,y1:U,y2:U,className:"stroke-line"}),c.jsx("text",{x:cn.left-6,y:U+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(E)})]},I)}),c.jsx("line",{x1:cn.left,x2:u-cn.right,y1:O(0),y2:O(0),className:"stroke-faint"}),g.map((E,I)=>{const U=cn.left+H*I+(H-L)/2,G=O(E.start),V=O(E.end),Q=E.isTotal?"total":E.value<0?"negative":"positive",z=E.isTotal?"fill-faint":E.value<0?"fill-danger":"fill-chart-primary",ee=g[I+1];return c.jsxs("g",{children:[c.jsx("rect",{x:U,y:Math.min(G,V),width:L,height:Math.max(1,Math.abs(V-G)),"data-label":E.label,"data-value":E.value,"data-tone":Q,className:z,...m(c.jsx(os,{title:E.label,rows:E.isTotal?[{label:"Total",value:t(E.end)}]:[{label:"Change",value:t(E.value)},{label:"Running",value:t(E.end)}]}))}),ee?c.jsx("line",{x1:U+L,x2:cn.left+H*(I+1)+(H-L)/2,y1:V,y2:V,className:"stroke-faint",strokeDasharray:"3 3"}):null,c.jsx("text",{x:U+L/2,y:e-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:E.label.slice(0,9)})]},`${E.label}-${I}`)})]}),c.jsx(rr,{tip:h})]})}function uy(n){return n==null?"∅":String(n)}function F2(n){const e=typeof n=="number"?n:Number(n);return Number.isFinite(e)?e:Number.NaN}function O2(n,e){const t=[],i=[],a=new Map;for(const u of n){const f=uy(u[e.x]),h=uy(u[e.series]);t.includes(f)||t.push(f),i.includes(h)||i.push(h),a.set(`${h}\0${f}`,F2(u[e.y]))}return{labels:t,series:i.map(u=>({name:u,values:t.map(f=>a.get(`${u}\0${f}`)??0)}))}}const T2=[{dimension:"orders.region",title:"Customer Region",rows:[["East",83262],["South",80579],["West",71561],["North",52889]].map(([n,e])=>({value:String(n),metric:Number(e)}))},{dimension:"orders.status",title:"Order Status",rows:[["completed",170379],["cancelled",64637],["pending",53275]].map(([n,e])=>({value:String(n),metric:Number(e)}))},{dimension:"products.category",title:"Product Category",rows:[["Electronics",202015],["Furniture",83848],["Office Supplies",2428]].map(([n,e])=>({value:String(n),metric:Number(e)}))},{dimension:"customers.name",title:"Top Customers",rows:[["Bob Smith",46690],["Carol Davis",42227],["Henry Taylor",41633],["Grace Lee",41035],["Frank Brown",33890],["David Wilson",29928],["Alice Johnson",27114],["Emma Martinez",24802]].map(([n,e])=>({value:String(n),metric:Number(e)}))}],A2=[{key:"region",label:"Region",sortable:!0},{key:"revenue",label:"Revenue",numeric:!0,sortable:!0},{key:"orders",label:"Orders",numeric:!0,sortable:!0}],cy=Array.from({length:17},(n,e)=>({region:["East","South","West","North"][e%4],revenue:91e3-e*2875,orders:420-e*11})),hf=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug"],B2=hf.flatMap((n,e)=>[{month:n,plan:"Basic",revenue:120+e*26},{month:n,plan:"Pro",revenue:60+e*24},{month:n,plan:"Enterprise",revenue:e<2?0:10+e*12}]),E2=Array.from({length:48},(n,e)=>({x:e+1,y:(e+1)*1.6+Math.sin(e*78.233)*43758.5453%18,label:`Account ${e+1}`,series:e%2?"Returning":"New"})),R2=Array.from({length:400},(n,e)=>Math.abs(Math.sin(e*12.9898)*43758.5453%1)*100),L2=["East","South","West","North"].flatMap((n,e)=>hf.map((t,i)=>({x:t,y:n,value:(e+1)*(i+1)*7-(i%4===3?80:0)}))),dy=[{value:"orders.revenue",label:"Revenue"},{value:"orders.count",label:"Order count"},{value:"customers.count",label:"Customer count"},{value:"orders.margin",label:"Gross margin"}];function U2(){const[n,e]=M.useState("orders.revenue"),[t,i]=M.useState({}),[a,u]=M.useState(null),[f,h]=M.useState({"orders.region":["East","West"],"orders.status":["completed"]}),[m,g]=M.useState({from:"2025-01-01",to:"2025-06-30"}),[v,x]=M.useState("month"),[b,w]=M.useState("explore"),[j,C]=M.useState("previous"),[O,H]=M.useState("orders.revenue"),[L,R]=M.useState(["orders.revenue","orders.count"]),[T,E]=M.useState("apple"),[I,U]=M.useState(!0),[G,V]=M.useState("explore"),[Q,z]=M.useState("2025-06-15"),[ee,X]=M.useState({from:"2025-06-01",to:"2025-06-21"}),ie=M.useMemo(()=>O2(B2,{x:"month",y:"revenue",series:"plan"}),[]),[ae,re]=M.useState({key:"revenue",dir:"desc"}),se=M.useMemo(()=>[...cy].sort((A,Y)=>{const W=A[ae.key],_=Y[ae.key],F=typeof W=="number"&&typeof _=="number"?W-_:String(W).localeCompare(String(_));return ae.dir==="asc"?F:-F}),[ae]);return c.jsxs("main",{className:"min-h-screen bg-bg text-ink",children:[c.jsxs("header",{className:"sticky top-0 z-20 flex items-center justify-between border-b border-line bg-surface px-4 py-3",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-sm font-semibold",children:"Sidemantic component gallery"}),c.jsxs("p",{className:"text-2xs text-faint",children:["Canonical React primitives · ",c.jsx("a",{className:"text-accent hover:underline",href:"/typography",children:"typography workbench →"})]})]}),c.jsx($o,{})]}),c.jsxs("div",{className:"space-y-8 p-4",children:[c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Metric cards"}),c.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-3",children:[c.jsx(Nr,{metric:"orders.revenue",label:"Revenue",value:288291,format:{format:"currency"},selected:n==="orders.revenue",sparkValues:[31,42,38,55,60,74],onSelect:e}),c.jsx(Nr,{metric:"orders.count",label:"Order Count",value:447,selected:n==="orders.count",sparkValues:[21,34,28,41,44,51],onSelect:e}),c.jsx(Nr,{metric:"orders.margin",label:"Gross Margin",value:.324,format:{format:"percent"},delta:{label:"+1.1pt",tone:"positive"},comparison:"vs previous month",sparkValues:[24,26,29,27,31,32],selected:n==="orders.margin",onSelect:e})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Leaderboard cards"}),c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(220px,1fr))] gap-0 border-l border-t border-line",children:T2.filter(A=>a===null||a===A.dimension).map(A=>c.jsx(Xv,{dimension:A.dimension,title:A.title,metricLabel:"Total Revenue",rows:A.rows,selectedValues:t[A.dimension],formatMetric:Y=>pt(Y,{format:"currency"}),onToggle:Y=>i(W=>{const _=W[A.dimension]??[];return{...W,[A.dimension]:_.includes(Y)?_.filter(F=>F!==Y):[..._,Y]}}),expanded:a===A.dimension,onExpandedChange:Y=>u(Y?A.dimension:null)},A.dimension))})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Filters and controls"}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{"data-testid":"gallery-filter-pills",className:"flex min-h-8 flex-wrap items-center gap-2",children:[Object.entries(f).flatMap(([A,Y])=>Y.map(W=>c.jsx(Od,{dimension:A,value:W,onRemove:()=>h(_=>({..._,[A]:_[A].filter(F=>F!==W)}))},`${A}:${W}`))),Object.values(f).every(A=>A.length===0)?c.jsx("span",{className:"text-2xs text-faint",children:"No active filters"}):null]}),c.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[c.jsx(Bv,{range:m,onChange:g,comparison:j,onComparisonChange:C}),c.jsx(Td,{grain:v,options:["day","week","month","quarter","year"],onChange:x}),c.jsx(Lv,{view:b,onChange:w}),c.jsxs("span",{className:"inline-flex items-center gap-1.5 text-2xs text-muted",children:[c.jsx(dd,{status:"ok"})," Ready"]}),c.jsxs("span",{className:"inline-flex items-center gap-1.5 text-2xs text-muted",children:[c.jsx(dd,{status:"loading"})," Updating"]}),c.jsx("button",{type:"button",onClick:()=>h({"orders.region":["East","West"],"orders.status":["completed"]}),className:"inline-flex h-7 items-center rounded-full border border-line px-3 text-xs text-muted hover:bg-surface-soft",children:"Reset filters"})]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Charts"}),c.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Sparkline"}),c.jsx(e0,{values:[31,42,38,55,60,74,69,83],labels:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug"],ariaLabel:"Eight month revenue trend"})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Column chart"}),c.jsx(t0,{data:[{label:"East",value:83},{label:"South",value:81},{label:"West",value:72},{label:"Returns",value:-18}]})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Line chart compatibility export"}),c.jsx(h2,{data:[{label:"Jan",value:31},{label:"Feb",value:42},{label:"Mar",value:38},{label:"Apr",value:55},{label:"May",value:60}]})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Interactive time series"}),c.jsx(Go,{points:[31,42,38,55,60,74].map((A,Y)=>({x:`2025-0${Y+1}-01`,y:A})),comparison:[27,35,33,48,52,61].map((A,Y)=>({x:`2024-0${Y+1}-01`,y:A})),formatValue:A=>`$${A.toLocaleString()}k`})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Donut"}),c.jsx(y2,{data:[{label:"iOS",value:4200},{label:"Android",value:3100},{label:"Web",value:1900},{label:"Other",value:400}]})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Stacked area (long rows via rowsToSeries)"}),c.jsx(j2,{labels:ie.labels,series:ie.series,height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Bar + line combo (dual axis)"}),c.jsx(o2,{data:hf.map((A,Y)=>({label:A,bar:200+Y*42,line:.02+Y*.004})),barLabel:"Revenue",lineLabel:"Conversion",formatLine:A=>`${(A*100).toFixed(1)}%`,height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Histogram"}),c.jsx(x2,{values:R2,bins:20})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Scatter"}),c.jsx(n0,{points:E2,xLabel:"Sessions",yLabel:"Orders",height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Heatmap"}),c.jsx(g2,{cells:L2,height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Waterfall"}),c.jsx(C2,{data:[{label:"Gross",value:1e3,isTotal:!0},{label:"Refunds",value:-140},{label:"Discounts",value:-90},{label:"Upsells",value:130},{label:"Net",value:900,isTotal:!0}],height:200})]}),c.jsxs("article",{className:"min-w-0 xl:col-span-2",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Network"}),c.jsx(_2,{nodes:[{id:"orders",group:"fact"},{id:"payments",group:"fact"},{id:"customers",group:"dimension"},{id:"products",group:"dimension"},{id:"regions",group:"dimension"}],links:[{source:"orders",target:"customers",weight:3},{source:"orders",target:"products",weight:2},{source:"orders",target:"regions"},{source:"payments",target:"orders",weight:2},{source:"payments",target:"customers"}],height:260})]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Inputs"}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[c.jsx(No,{variant:"primary",children:"Primary"}),c.jsx(No,{children:"Secondary"}),c.jsx(No,{variant:"ghost",children:"Ghost"}),c.jsx(No,{variant:"danger",children:"Danger"}),c.jsx(No,{size:"sm",children:"Small"}),c.jsx(wl,{label:"Fruit",value:T,onChange:E,options:[{value:"apple",label:"Apple"},{value:"banana",label:"Banana"},{value:"cherry",label:"Cherry"}]}),c.jsx(k2,{checked:I,onChange:U,label:"Compact rows"}),c.jsx(I2,{tabs:[{key:"explore",label:"Explore"},{key:"pivot",label:"Pivot"},{key:"sql",label:"SQL"}],active:G,onChange:V}),c.jsx(M2,{content:"Revenue in USD, net of refunds",children:c.jsx("span",{className:"cursor-help text-2xs text-muted underline decoration-dotted",children:"What is revenue?"})})]}),c.jsxs("div",{className:"flex flex-wrap items-start gap-3",children:[c.jsx(iy,{value:O,onChange:H,options:dy,ariaLabel:"Metric"}),c.jsx(iy,{multiple:!0,values:L,onChange:R,options:dy,ariaLabel:"Metrics"}),c.jsx(ay,{mode:"single",value:Q,onChange:z,ariaLabel:"Date"}),c.jsx(ay,{mode:"range",value:ee,onChange:X,ariaLabel:"Range"})]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Analytical table"}),c.jsx(Ho,{columns:A2,rows:se,pageSize:6,sortKey:ae.key,sortDir:ae.dir,onSort:A=>re(Y=>({key:A,dir:Y.key===A&&Y.dir==="desc"?"asc":"desc"})),renderCell:(A,Y)=>A.numeric?Number(Y).toLocaleString():String(Y),searchable:!0,totals:{region:"count",revenue:"sum",orders:"sum"}}),c.jsxs("div",{className:"mt-3",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold text-muted",children:"Distribution-friendly data preview"}),c.jsx(f2,{result:{columns:["region","revenue","orders"],sample_rows:cy.slice(0,8)},pageSize:4})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Query inspection"}),c.jsx(au,{inputs:{Revenue:{metrics:["orders.revenue"],dimensions:["orders.region"],filters:["orders.status = 'completed'"]}},queries:{Revenue:`SELECT orders.region, SUM(orders.revenue) AS revenue FROM orders WHERE orders.status = 'completed' GROUP BY orders.region -ORDER BY revenue DESC`}})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"States"}),c.jsxs("div",{className:"grid gap-2 lg:grid-cols-3",children:[c.jsx(af,{message:"Loading metric results…"}),c.jsx(Xn,{message:"No matching rows."}),c.jsx(Bi,{message:"The query could not be completed."})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Dashboard shell"}),c.jsx("div",{children:c.jsx(o2,{eyebrow:"Embedded shell example",title:"Revenue overview",status:c.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[c.jsx(dd,{status:"ok"})," Connected"]}),toolbar:c.jsxs(c.Fragment,{children:[c.jsx(Od,{dimension:"orders.region",value:"East"}),c.jsx(Td,{grain:v,options:["day","month","quarter"],onChange:x})]}),children:c.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[c.jsx(Nr,{metric:"orders.revenue",label:"Revenue",value:288291,format:{format:"currency"},sparkValues:[31,42,38,55,60]}),c.jsx(Xn,{title:"Optional panel",message:"Shell content is composed from the same primitives."})]})})})]})]})]})}function ns(n){return`https://api.fontshare.com/v2/css?f[]=${n}&display=swap`}const uy=[{value:"system",label:"System (SF Pro)",stack:"system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif"},{value:"geist",label:"Geist",gf:"Geist:wght@400;500;600",stack:"'Geist', system-ui, sans-serif"},{value:"inter",label:"Inter",gf:"Inter:wght@400;500;600",stack:"'Inter', system-ui, sans-serif"},{value:"instrument",label:"Instrument Sans",gf:"Instrument+Sans:wght@400;500;600",stack:"'Instrument Sans', system-ui, sans-serif"},{value:"plex",label:"IBM Plex Sans",gf:"IBM+Plex+Sans:wght@400;500;600",stack:"'IBM Plex Sans', system-ui, sans-serif"},{value:"schibsted",label:"Schibsted Grotesk",gf:"Schibsted+Grotesk:wght@400;500;600",stack:"'Schibsted Grotesk', system-ui, sans-serif"},{value:"figtree",label:"Figtree",gf:"Figtree:wght@400;500;600",stack:"'Figtree', system-ui, sans-serif"},{value:"manrope",label:"Manrope",gf:"Manrope:wght@400;500;600",stack:"'Manrope', system-ui, sans-serif"},{value:"publicsans",label:"Public Sans",gf:"Public+Sans:wght@400;500;600",stack:"'Public Sans', system-ui, sans-serif"},{value:"spacegrotesk",label:"Space Grotesk",gf:"Space+Grotesk:wght@400;500;600",stack:"'Space Grotesk', system-ui, sans-serif"},{value:"satoshi",label:"Satoshi ✦",url:ns("satoshi@400,500,700"),stack:"'Satoshi', system-ui, sans-serif"},{value:"generalsans",label:"General Sans ✦",url:ns("general-sans@400,500,600"),stack:"'General Sans', system-ui, sans-serif"},{value:"switzer",label:"Switzer ✦",url:ns("switzer@400,500,600"),stack:"'Switzer', system-ui, sans-serif"},{value:"cabinet",label:"Cabinet Grotesk ✦",url:ns("cabinet-grotesk@400,500,700"),stack:"'Cabinet Grotesk', system-ui, sans-serif"},{value:"bricolage",label:"Bricolage Grotesque ✦",gf:"Bricolage+Grotesque:wght@400;500;600",stack:"'Bricolage Grotesque', system-ui, sans-serif"},{value:"familjen",label:"Familjen Grotesk ✦",gf:"Familjen+Grotesk:wght@400;500;600",stack:"'Familjen Grotesk', system-ui, sans-serif"},{value:"hanken",label:"Hanken Grotesk ✦",gf:"Hanken+Grotesk:wght@400;500;600",stack:"'Hanken Grotesk', system-ui, sans-serif"},{value:"reddit",label:"Reddit Sans ✦",gf:"Reddit+Sans:wght@400;500;600",stack:"'Reddit Sans', system-ui, sans-serif"},{value:"chivo",label:"Chivo ✦",gf:"Chivo:wght@400;500;600",stack:"'Chivo', system-ui, sans-serif"},{value:"hostgrotesk",label:"Host Grotesk ✦",gf:"Host+Grotesk:wght@400;500;600",stack:"'Host Grotesk', system-ui, sans-serif"},{value:"sora",label:"Sora ✦",gf:"Sora:wght@400;500;600",stack:"'Sora', system-ui, sans-serif"}],cy=[{value:"system",label:"System (SF Mono)",stack:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"},{value:"geistmono",label:"Geist Mono",gf:"Geist+Mono:wght@400;500",stack:"'Geist Mono', ui-monospace, monospace"},{value:"jetbrains",label:"JetBrains Mono",gf:"JetBrains+Mono:wght@400;500",stack:"'JetBrains Mono', ui-monospace, monospace"},{value:"plexmono",label:"IBM Plex Mono",gf:"IBM+Plex+Mono:wght@400;500",stack:"'IBM Plex Mono', ui-monospace, monospace"},{value:"firacode",label:"Fira Code",gf:"Fira+Code:wght@400;500",stack:"'Fira Code', ui-monospace, monospace"},{value:"splinemono",label:"Spline Sans Mono",gf:"Spline+Sans+Mono:wght@400;500",stack:"'Spline Sans Mono', ui-monospace, monospace"},{value:"dmmono",label:"DM Mono",gf:"DM+Mono:wght@400;500",stack:"'DM Mono', ui-monospace, monospace"},{value:"martianmono",label:"Martian Mono ✦",gf:"Martian+Mono:wght@400;500",stack:"'Martian Mono', ui-monospace, monospace"},{value:"fragment",label:"Fragment Mono ✦",gf:"Fragment+Mono",stack:"'Fragment Mono', ui-monospace, monospace"},{value:"redhatmono",label:"Red Hat Mono ✦",gf:"Red+Hat+Mono:wght@400;500",stack:"'Red Hat Mono', ui-monospace, monospace"},{value:"chivomono",label:"Chivo Mono ✦",gf:"Chivo+Mono:wght@400;500",stack:"'Chivo Mono', ui-monospace, monospace"},{value:"azeret",label:"Azeret Mono ✦",gf:"Azeret+Mono:wght@400;500",stack:"'Azeret Mono', ui-monospace, monospace"},{value:"spacemono",label:"Space Mono ✦",gf:"Space+Mono:wght@400;700",stack:"'Space Mono', ui-monospace, monospace"}],dy=[{value:"sans",label:"Same as sans",stack:""},{value:"newsreader",label:"Newsreader (serif)",gf:"Newsreader:opsz,wght@6..72,400..700",stack:"'Newsreader', Georgia, serif"},{value:"sourceserif",label:"Source Serif 4",gf:"Source+Serif+4:opsz,wght@8..60,400..700",stack:"'Source Serif 4', Georgia, serif"},{value:"fraunces",label:"Fraunces",gf:"Fraunces:opsz,wght@9..144,400..700",stack:"'Fraunces', Georgia, serif"},{value:"instrumentserif",label:"Instrument Serif",gf:"Instrument+Serif",stack:"'Instrument Serif', Georgia, serif"},{value:"spacegrotesk",label:"Space Grotesk",gf:"Space+Grotesk:wght@400;500;600",stack:"'Space Grotesk', system-ui, sans-serif"},{value:"clash",label:"Clash Display ✦",url:ns("clash-display@400,500,600"),stack:"'Clash Display', system-ui, sans-serif"},{value:"cabinetdisplay",label:"Cabinet Grotesk ✦",url:ns("cabinet-grotesk@500,700,800"),stack:"'Cabinet Grotesk', system-ui, sans-serif"},{value:"sentient",label:"Sentient (serif) ✦",url:ns("sentient@400,500,700"),stack:"'Sentient', Georgia, serif"},{value:"gambetta",label:"Gambetta (serif) ✦",url:ns("gambetta@400,500,700"),stack:"'Gambetta', Georgia, serif"},{value:"bricolagedisplay",label:"Bricolage Grotesque ✦",gf:"Bricolage+Grotesque:opsz,wght@12..96,400..700",stack:"'Bricolage Grotesque', system-ui, sans-serif"},{value:"youngserif",label:"Young Serif ✦",gf:"Young+Serif",stack:"'Young Serif', Georgia, serif"},{value:"unbounded",label:"Unbounded ✦",gf:"Unbounded:wght@400;500;600",stack:"'Unbounded', system-ui, sans-serif"}],R2=[{label:"Geist / Geist Mono",sans:"geist",mono:"geistmono",display:"sans"},{label:"Inter / JetBrains",sans:"inter",mono:"jetbrains",display:"sans"},{label:"IBM Plex",sans:"plex",mono:"plexmono",display:"sans"},{label:"Instrument / Spline",sans:"instrument",mono:"splinemono",display:"sans"},{label:"Schibsted / Fira",sans:"schibsted",mono:"firacode",display:"sans"},{label:"Editorial: Geist + Newsreader",sans:"geist",mono:"geistmono",display:"newsreader"},{label:"Satoshi / Martian ✦",sans:"satoshi",mono:"martianmono",display:"sans"},{label:"General Sans / Fragment ✦",sans:"generalsans",mono:"fragment",display:"sans"},{label:"Switzer + Clash headings ✦",sans:"switzer",mono:"redhatmono",display:"clash"},{label:"Cabinet + Gambetta ✦",sans:"cabinet",mono:"chivomono",display:"gambetta"},{label:"Bricolage all the way ✦",sans:"bricolage",mono:"spacemono",display:"bricolagedisplay"}],fy=new Set;function gd(n){if(!n)return;const e=n.url??(n.gf?`https://fonts.googleapis.com/css2?family=${n.gf}&display=swap`:void 0);if(!e||fy.has(e))return;fy.add(e);const t=document.createElement("link");t.rel="stylesheet",t.href=e,document.head.appendChild(t)}function vd(n,e){return n.find(t=>t.value===e)??n[0]}const L2=[{px:"8",cls:"text-[8px]",usage:"MetricCard delta arrow glyph",sample:"▲"},{px:"9",cls:"text-[9px]",usage:"DataTable sort direction glyph",sample:"▲▼"},{px:"10",cls:"text-[10px]",usage:"Chart axis labels (all 9 charts)",sample:"Jan Feb Mar 12.4k 18.2k"},{px:"11",cls:"text-2xs",usage:"Captions, chips, table body, helper text (58 uses)",sample:"Canonical React primitives · updated 2h ago"},{px:"12",cls:"text-xs",usage:"Controls, labels, leaderboard rows — the workhorse (70 uses)",sample:"Revenue by region, last 28 days"},{px:"13",cls:"text-sm",usage:"Section titles, panel headers (9 uses); also the body default",sample:"Customer Region"},{px:"14",cls:"text-base",usage:"Explore index page title (1 use)",sample:"Explore"},{px:"19",cls:"text-[19px]",usage:"MetricCard value",sample:"$288,291"},{px:"20",cls:"text-xl",usage:"MetricTimeSeries headline total",sample:"$1,282,392"},{px:"24",cls:"text-2xl",usage:"DashboardShell page title",sample:"Revenue overview"}],U2=[{name:"A — Current",note:"11 / 12 / 13 base. Dense, reads small on 27″ displays.",caption:11,label:12,body:13,section:13,value:19,headline:20,title:24},{name:"B — One up",note:"12 / 13 / 14 base. Same hierarchy, comfortably legible.",caption:12,label:13,body:14,section:14,value:22,headline:24,title:28},{name:"C — Quiet UI, loud numbers",note:"Keeps the dense chrome, doubles down on data: bigger values and titles.",caption:11,label:12,body:13,section:13,value:24,headline:28,title:30}],$2=[31,42,38,55,60,74],P2=Array.from({length:12},(n,e)=>({x:`2025-${String(e+1).padStart(2,"0")}-01`,y:96e3+e*14e3+e%3*9e3})),z2=`select region, sum(revenue) as revenue +ORDER BY revenue DESC`}})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"States"}),c.jsxs("div",{className:"grid gap-2 lg:grid-cols-3",children:[c.jsx(af,{message:"Loading metric results…"}),c.jsx(Xn,{message:"No matching rows."}),c.jsx(Bi,{message:"The query could not be completed."})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Dashboard shell"}),c.jsx("div",{children:c.jsx(u2,{eyebrow:"Embedded shell example",title:"Revenue overview",status:c.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[c.jsx(dd,{status:"ok"})," Connected"]}),toolbar:c.jsxs(c.Fragment,{children:[c.jsx(Od,{dimension:"orders.region",value:"East"}),c.jsx(Td,{grain:v,options:["day","month","quarter"],onChange:x})]}),children:c.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[c.jsx(Nr,{metric:"orders.revenue",label:"Revenue",value:288291,format:{format:"currency"},sparkValues:[31,42,38,55,60]}),c.jsx(Xn,{title:"Optional panel",message:"Shell content is composed from the same primitives."})]})})})]})]})]})}function ns(n){return`https://api.fontshare.com/v2/css?f[]=${n}&display=swap`}const fy=[{value:"system",label:"System (SF Pro)",stack:"system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif"},{value:"geist",label:"Geist",gf:"Geist:wght@400;500;600",stack:"'Geist', system-ui, sans-serif"},{value:"inter",label:"Inter",gf:"Inter:wght@400;500;600",stack:"'Inter', system-ui, sans-serif"},{value:"instrument",label:"Instrument Sans",gf:"Instrument+Sans:wght@400;500;600",stack:"'Instrument Sans', system-ui, sans-serif"},{value:"plex",label:"IBM Plex Sans",gf:"IBM+Plex+Sans:wght@400;500;600",stack:"'IBM Plex Sans', system-ui, sans-serif"},{value:"schibsted",label:"Schibsted Grotesk",gf:"Schibsted+Grotesk:wght@400;500;600",stack:"'Schibsted Grotesk', system-ui, sans-serif"},{value:"figtree",label:"Figtree",gf:"Figtree:wght@400;500;600",stack:"'Figtree', system-ui, sans-serif"},{value:"manrope",label:"Manrope",gf:"Manrope:wght@400;500;600",stack:"'Manrope', system-ui, sans-serif"},{value:"publicsans",label:"Public Sans",gf:"Public+Sans:wght@400;500;600",stack:"'Public Sans', system-ui, sans-serif"},{value:"spacegrotesk",label:"Space Grotesk",gf:"Space+Grotesk:wght@400;500;600",stack:"'Space Grotesk', system-ui, sans-serif"},{value:"satoshi",label:"Satoshi ✦",url:ns("satoshi@400,500,700"),stack:"'Satoshi', system-ui, sans-serif"},{value:"generalsans",label:"General Sans ✦",url:ns("general-sans@400,500,600"),stack:"'General Sans', system-ui, sans-serif"},{value:"switzer",label:"Switzer ✦",url:ns("switzer@400,500,600"),stack:"'Switzer', system-ui, sans-serif"},{value:"cabinet",label:"Cabinet Grotesk ✦",url:ns("cabinet-grotesk@400,500,700"),stack:"'Cabinet Grotesk', system-ui, sans-serif"},{value:"bricolage",label:"Bricolage Grotesque ✦",gf:"Bricolage+Grotesque:wght@400;500;600",stack:"'Bricolage Grotesque', system-ui, sans-serif"},{value:"familjen",label:"Familjen Grotesk ✦",gf:"Familjen+Grotesk:wght@400;500;600",stack:"'Familjen Grotesk', system-ui, sans-serif"},{value:"hanken",label:"Hanken Grotesk ✦",gf:"Hanken+Grotesk:wght@400;500;600",stack:"'Hanken Grotesk', system-ui, sans-serif"},{value:"reddit",label:"Reddit Sans ✦",gf:"Reddit+Sans:wght@400;500;600",stack:"'Reddit Sans', system-ui, sans-serif"},{value:"chivo",label:"Chivo ✦",gf:"Chivo:wght@400;500;600",stack:"'Chivo', system-ui, sans-serif"},{value:"hostgrotesk",label:"Host Grotesk ✦",gf:"Host+Grotesk:wght@400;500;600",stack:"'Host Grotesk', system-ui, sans-serif"},{value:"sora",label:"Sora ✦",gf:"Sora:wght@400;500;600",stack:"'Sora', system-ui, sans-serif"}],hy=[{value:"system",label:"System (SF Mono)",stack:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"},{value:"geistmono",label:"Geist Mono",gf:"Geist+Mono:wght@400;500",stack:"'Geist Mono', ui-monospace, monospace"},{value:"jetbrains",label:"JetBrains Mono",gf:"JetBrains+Mono:wght@400;500",stack:"'JetBrains Mono', ui-monospace, monospace"},{value:"plexmono",label:"IBM Plex Mono",gf:"IBM+Plex+Mono:wght@400;500",stack:"'IBM Plex Mono', ui-monospace, monospace"},{value:"firacode",label:"Fira Code",gf:"Fira+Code:wght@400;500",stack:"'Fira Code', ui-monospace, monospace"},{value:"splinemono",label:"Spline Sans Mono",gf:"Spline+Sans+Mono:wght@400;500",stack:"'Spline Sans Mono', ui-monospace, monospace"},{value:"dmmono",label:"DM Mono",gf:"DM+Mono:wght@400;500",stack:"'DM Mono', ui-monospace, monospace"},{value:"martianmono",label:"Martian Mono ✦",gf:"Martian+Mono:wght@400;500",stack:"'Martian Mono', ui-monospace, monospace"},{value:"fragment",label:"Fragment Mono ✦",gf:"Fragment+Mono",stack:"'Fragment Mono', ui-monospace, monospace"},{value:"redhatmono",label:"Red Hat Mono ✦",gf:"Red+Hat+Mono:wght@400;500",stack:"'Red Hat Mono', ui-monospace, monospace"},{value:"chivomono",label:"Chivo Mono ✦",gf:"Chivo+Mono:wght@400;500",stack:"'Chivo Mono', ui-monospace, monospace"},{value:"azeret",label:"Azeret Mono ✦",gf:"Azeret+Mono:wght@400;500",stack:"'Azeret Mono', ui-monospace, monospace"},{value:"spacemono",label:"Space Mono ✦",gf:"Space+Mono:wght@400;700",stack:"'Space Mono', ui-monospace, monospace"}],py=[{value:"sans",label:"Same as sans",stack:""},{value:"newsreader",label:"Newsreader (serif)",gf:"Newsreader:opsz,wght@6..72,400..700",stack:"'Newsreader', Georgia, serif"},{value:"sourceserif",label:"Source Serif 4",gf:"Source+Serif+4:opsz,wght@8..60,400..700",stack:"'Source Serif 4', Georgia, serif"},{value:"fraunces",label:"Fraunces",gf:"Fraunces:opsz,wght@9..144,400..700",stack:"'Fraunces', Georgia, serif"},{value:"instrumentserif",label:"Instrument Serif",gf:"Instrument+Serif",stack:"'Instrument Serif', Georgia, serif"},{value:"spacegrotesk",label:"Space Grotesk",gf:"Space+Grotesk:wght@400;500;600",stack:"'Space Grotesk', system-ui, sans-serif"},{value:"clash",label:"Clash Display ✦",url:ns("clash-display@400,500,600"),stack:"'Clash Display', system-ui, sans-serif"},{value:"cabinetdisplay",label:"Cabinet Grotesk ✦",url:ns("cabinet-grotesk@500,700,800"),stack:"'Cabinet Grotesk', system-ui, sans-serif"},{value:"sentient",label:"Sentient (serif) ✦",url:ns("sentient@400,500,700"),stack:"'Sentient', Georgia, serif"},{value:"gambetta",label:"Gambetta (serif) ✦",url:ns("gambetta@400,500,700"),stack:"'Gambetta', Georgia, serif"},{value:"bricolagedisplay",label:"Bricolage Grotesque ✦",gf:"Bricolage+Grotesque:opsz,wght@12..96,400..700",stack:"'Bricolage Grotesque', system-ui, sans-serif"},{value:"youngserif",label:"Young Serif ✦",gf:"Young+Serif",stack:"'Young Serif', Georgia, serif"},{value:"unbounded",label:"Unbounded ✦",gf:"Unbounded:wght@400;500;600",stack:"'Unbounded', system-ui, sans-serif"}],$2=[{label:"Geist / Geist Mono",sans:"geist",mono:"geistmono",display:"sans"},{label:"Inter / JetBrains",sans:"inter",mono:"jetbrains",display:"sans"},{label:"IBM Plex",sans:"plex",mono:"plexmono",display:"sans"},{label:"Instrument / Spline",sans:"instrument",mono:"splinemono",display:"sans"},{label:"Schibsted / Fira",sans:"schibsted",mono:"firacode",display:"sans"},{label:"Editorial: Geist + Newsreader",sans:"geist",mono:"geistmono",display:"newsreader"},{label:"Satoshi / Martian ✦",sans:"satoshi",mono:"martianmono",display:"sans"},{label:"General Sans / Fragment ✦",sans:"generalsans",mono:"fragment",display:"sans"},{label:"Switzer + Clash headings ✦",sans:"switzer",mono:"redhatmono",display:"clash"},{label:"Cabinet + Gambetta ✦",sans:"cabinet",mono:"chivomono",display:"gambetta"},{label:"Bricolage all the way ✦",sans:"bricolage",mono:"spacemono",display:"bricolagedisplay"}],my=new Set;function gd(n){if(!n)return;const e=n.url??(n.gf?`https://fonts.googleapis.com/css2?family=${n.gf}&display=swap`:void 0);if(!e||my.has(e))return;my.add(e);const t=document.createElement("link");t.rel="stylesheet",t.href=e,document.head.appendChild(t)}function vd(n,e){return n.find(t=>t.value===e)??n[0]}const P2=[{px:"8",cls:"text-[8px]",usage:"MetricCard delta arrow glyph",sample:"▲"},{px:"9",cls:"text-[9px]",usage:"DataTable sort direction glyph",sample:"▲▼"},{px:"10",cls:"text-[10px]",usage:"Chart axis labels (all 9 charts)",sample:"Jan Feb Mar 12.4k 18.2k"},{px:"11",cls:"text-2xs",usage:"Captions, chips, table body, helper text (58 uses)",sample:"Canonical React primitives · updated 2h ago"},{px:"12",cls:"text-xs",usage:"Controls, labels, leaderboard rows — the workhorse (70 uses)",sample:"Revenue by region, last 28 days"},{px:"13",cls:"text-sm",usage:"Section titles, panel headers (9 uses); also the body default",sample:"Customer Region"},{px:"14",cls:"text-base",usage:"Explore index page title (1 use)",sample:"Explore"},{px:"19",cls:"text-[19px]",usage:"MetricCard value",sample:"$288,291"},{px:"20",cls:"text-xl",usage:"MetricTimeSeries headline total",sample:"$1,282,392"},{px:"24",cls:"text-2xl",usage:"DashboardShell page title",sample:"Revenue overview"}],z2=[{name:"A — Current",note:"11 / 12 / 13 base. Dense, reads small on 27″ displays.",caption:11,label:12,body:13,section:13,value:19,headline:20,title:24},{name:"B — One up",note:"12 / 13 / 14 base. Same hierarchy, comfortably legible.",caption:12,label:13,body:14,section:14,value:22,headline:24,title:28},{name:"C — Quiet UI, loud numbers",note:"Keeps the dense chrome, doubles down on data: bigger values and titles.",caption:11,label:12,body:13,section:13,value:24,headline:28,title:30}],V2=[31,42,38,55,60,74],W2=Array.from({length:12},(n,e)=>({x:`2025-${String(e+1).padStart(2,"0")}-01`,y:96e3+e*14e3+e%3*9e3})),H2=`select region, sum(revenue) as revenue from orders where created_at >= date '2025-01-01' group by all -order by revenue desc`;function hy({family:n,size:e}){return c.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-6 gap-y-1",style:{fontFamily:n},children:[c.jsx("span",{className:`${e} font-normal`,children:"Regular 400 — Revenue by payment method"}),c.jsx("span",{className:`${e} font-medium`,children:"Medium 500 — Revenue by payment method"}),c.jsx("span",{className:`${e} font-semibold`,children:"Semibold 600 — Revenue by payment method"})]})}function V2(){const[n,e]=D.useState("geist"),[t,i]=D.useState("geistmono"),[a,u]=D.useState("sans"),f=vd(uy,n),h=vd(cy,t),m=vd(dy,a),g=m.stack||f.stack;D.useEffect(()=>{gd(f),gd(h),gd(m)},[f,h,m]);const v={"--font-sans":f.stack,"--font-mono":h.stack,"--font-display":g,fontFamily:"var(--font-sans)"};return c.jsxs("main",{className:"min-h-screen bg-bg text-ink",children:[c.jsxs("header",{className:"sticky top-0 z-20 flex items-center justify-between gap-3 border-b border-line bg-surface px-4 py-3",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-sm font-semibold",children:"Typography workbench"}),c.jsxs("p",{className:"text-2xs text-faint",children:["Pick faces, judge them on real components · ",c.jsx("a",{className:"text-accent hover:underline",href:"/components",children:"component gallery →"})]})]}),c.jsx($o,{})]}),c.jsxs("div",{className:"space-y-10 p-4",children:[c.jsx("section",{children:c.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[c.jsx(wl,{label:"Sans",value:n,options:uy.map(({value:x,label:b})=>({value:x,label:b})),onChange:e}),c.jsx(wl,{label:"Mono",value:t,options:cy.map(({value:x,label:b})=>({value:x,label:b})),onChange:i}),c.jsx(wl,{label:"Headings",value:a,options:dy.map(({value:x,label:b})=>({value:x,label:b})),onChange:u}),c.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:R2.map(x=>{const b=x.sans===n&&x.mono===t&&x.display===a;return c.jsx("button",{type:"button","data-selected":b||void 0,onClick:()=>{e(x.sans),i(x.mono),u(x.display)},className:`inline-flex h-7 items-center rounded-full border px-3 text-xs transition-colors ${b?"border-accent text-accent":"border-line bg-surface text-muted hover:border-line-strong"}`,children:x.label},x.label)})})]})}),c.jsxs("div",{style:v,className:"space-y-10",children:[c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"In context"}),c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-2xs text-faint",children:"Acme Analytics · production"}),c.jsx("h1",{className:"mt-1 text-2xl font-semibold text-ink",children:"Revenue overview"}),c.jsx("div",{className:"text-sm text-muted",children:"Updated 2 minutes ago · 448,214 rows scanned"})]}),c.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-3",children:[c.jsx(Nr,{metric:"t.revenue",label:"Revenue",value:288291,format:{format:"currency"},delta:{label:"+12.4%",tone:"positive"},comparison:"vs previous month",sparkValues:$2,selected:!0,onSelect:()=>{}}),c.jsx(Nr,{metric:"t.orders",label:"Order Count",value:447,delta:{label:"-2.1%",tone:"negative"},comparison:"vs previous month",sparkValues:[21,34,28,41,44,38],onSelect:()=>{}}),c.jsx(Nr,{metric:"t.margin",label:"Gross Margin",value:.324,format:{format:"percent"},delta:{label:"+1.1pt",tone:"positive"},comparison:"vs previous month",sparkValues:[24,26,29,27,31,32],onSelect:()=>{}})]}),c.jsx(Go,{points:P2,formatValue:x=>`$${Math.round(x).toLocaleString("en-US")}`,formatAxis:x=>`$${Math.round(x/1e3)}k`,formatLabel:x=>x.slice(0,7),ariaLabel:"Twelve month revenue trend"}),c.jsxs("div",{className:"max-w-xl",children:[c.jsx("h3",{className:"text-sm font-semibold text-ink",children:"How the comparison works"}),c.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"The overlay shifts the previous period onto the current axis so both lines share a scale. Deltas are computed on the visible range only — zooming recomputes them. Hover any point for the exact pair of values; the quiet gray line is always the older period."})]}),c.jsx("pre",{className:"overflow-x-auto font-mono text-xs leading-5 text-muted",children:z2})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Numerals — mono, tabular"}),c.jsxs("div",{className:"flex flex-wrap gap-12",children:[c.jsx("div",{className:"font-mono tnum text-sm text-ink",children:["$1,204,918.24","$984,003.10","$88,214.00","$1,111,111.11"].map(x=>c.jsx("div",{className:"text-right",children:x},x))}),c.jsx("div",{className:"font-mono tnum text-sm text-ink",children:["2025-06-30 23:59:59","2025-07-01 00:00:00","2025-12-31 08:15:42"].map(x=>c.jsx("div",{children:x},x))}),c.jsxs("div",{className:"font-mono text-sm text-ink",children:["0O · 1lI · 5S · 8B · ","->"," ","=>"," ","!="," ",">="]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Weights in use — 400 / 500 / 600 (no bold anywhere)"}),c.jsxs("div",{className:"space-y-2 text-ink",children:[c.jsx(hy,{family:"var(--font-sans)",size:"text-sm"}),c.jsx(hy,{family:"var(--font-sans)",size:"text-xs"}),c.jsx("div",{className:"text-xl font-semibold",style:{fontFamily:"var(--font-display)"},children:"Display 600 — Quarterly revenue, all regions"})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Current ramp — every size in the app and where it appears"}),c.jsx("div",{className:"space-y-1.5",children:L2.map(x=>c.jsxs("div",{className:"grid grid-cols-[3rem_7rem_1fr_1.2fr] items-baseline gap-3",children:[c.jsxs("span",{className:"font-mono tnum text-2xs text-faint",children:[x.px,"px"]}),c.jsx("span",{className:"font-mono text-2xs text-faint",children:x.cls}),c.jsx("span",{className:"truncate text-ink",style:{fontSize:`${x.px}px`,lineHeight:1.3},children:x.sample}),c.jsx("span",{className:"text-2xs text-faint",children:x.usage})]},x.px))})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Size ramp candidates"}),c.jsx("div",{className:"grid grid-cols-1 gap-8 lg:grid-cols-3",children:U2.map(x=>c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"text-sm font-semibold text-ink",children:x.name}),c.jsx("p",{className:"mt-0.5 text-2xs text-faint",children:x.note}),c.jsxs("div",{className:"mt-3 space-y-2",children:[c.jsxs("div",{className:"text-faint",style:{fontSize:x.caption,lineHeight:1.3},children:["Caption ",x.caption,"px · vs previous month"]}),c.jsxs("div",{className:"text-muted",style:{fontSize:x.label,lineHeight:1.35},children:["Label ",x.label,"px · Revenue by region"]}),c.jsxs("div",{className:"text-ink",style:{fontSize:x.body,lineHeight:1.45},children:["Body ",x.body,"px · The overlay shifts the previous period onto the current axis so both lines share a scale."]}),c.jsxs("div",{className:"font-semibold text-ink",style:{fontSize:x.section,lineHeight:1.35},children:["Section title ",x.section,"px"]}),c.jsx("div",{className:"font-mono tnum font-semibold text-ink",style:{fontSize:x.value,lineHeight:1.15},children:"$288,291"}),c.jsx("div",{className:"font-mono tnum font-semibold text-ink",style:{fontSize:x.headline,lineHeight:1.15},children:"$1,282,392"}),c.jsx("div",{className:"font-semibold text-ink",style:{fontFamily:"var(--font-display)",fontSize:x.title,lineHeight:1.2,letterSpacing:"-0.025em"},children:"Revenue overview"})]})]},x.name))})]})]})]})]})}n_();const n0=document.getElementById("root");if(!n0)throw new Error("Missing #root element");ub.createRoot(n0).render(c.jsx(D.StrictMode,{children:window.location.pathname==="/components"?c.jsx(E2,{}):window.location.pathname==="/typography"?c.jsx(V2,{}):c.jsx(n2,{})})); +order by revenue desc`;function yy({family:n,size:e}){return c.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-6 gap-y-1",style:{fontFamily:n},children:[c.jsx("span",{className:`${e} font-normal`,children:"Regular 400 — Revenue by payment method"}),c.jsx("span",{className:`${e} font-medium`,children:"Medium 500 — Revenue by payment method"}),c.jsx("span",{className:`${e} font-semibold`,children:"Semibold 600 — Revenue by payment method"})]})}function G2(){const[n,e]=M.useState("geist"),[t,i]=M.useState("geistmono"),[a,u]=M.useState("sans"),f=vd(fy,n),h=vd(hy,t),m=vd(py,a),g=m.stack||f.stack;M.useEffect(()=>{gd(f),gd(h),gd(m)},[f,h,m]);const v={"--font-sans":f.stack,"--font-mono":h.stack,"--font-display":g,fontFamily:"var(--font-sans)"};return c.jsxs("main",{className:"min-h-screen bg-bg text-ink",children:[c.jsxs("header",{className:"sticky top-0 z-20 flex items-center justify-between gap-3 border-b border-line bg-surface px-4 py-3",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-sm font-semibold",children:"Typography workbench"}),c.jsxs("p",{className:"text-2xs text-faint",children:["Pick faces, judge them on real components · ",c.jsx("a",{className:"text-accent hover:underline",href:"/components",children:"component gallery →"})]})]}),c.jsx($o,{})]}),c.jsxs("div",{className:"space-y-10 p-4",children:[c.jsx("section",{children:c.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[c.jsx(wl,{label:"Sans",value:n,options:fy.map(({value:x,label:b})=>({value:x,label:b})),onChange:e}),c.jsx(wl,{label:"Mono",value:t,options:hy.map(({value:x,label:b})=>({value:x,label:b})),onChange:i}),c.jsx(wl,{label:"Headings",value:a,options:py.map(({value:x,label:b})=>({value:x,label:b})),onChange:u}),c.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:$2.map(x=>{const b=x.sans===n&&x.mono===t&&x.display===a;return c.jsx("button",{type:"button","data-selected":b||void 0,onClick:()=>{e(x.sans),i(x.mono),u(x.display)},className:`inline-flex h-7 items-center rounded-full border px-3 text-xs transition-colors ${b?"border-accent text-accent":"border-line bg-surface text-muted hover:border-line-strong"}`,children:x.label},x.label)})})]})}),c.jsxs("div",{style:v,className:"space-y-10",children:[c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"In context"}),c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-2xs text-faint",children:"Acme Analytics · production"}),c.jsx("h1",{className:"mt-1 text-2xl font-semibold text-ink",children:"Revenue overview"}),c.jsx("div",{className:"text-sm text-muted",children:"Updated 2 minutes ago · 448,214 rows scanned"})]}),c.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-3",children:[c.jsx(Nr,{metric:"t.revenue",label:"Revenue",value:288291,format:{format:"currency"},delta:{label:"+12.4%",tone:"positive"},comparison:"vs previous month",sparkValues:V2,selected:!0,onSelect:()=>{}}),c.jsx(Nr,{metric:"t.orders",label:"Order Count",value:447,delta:{label:"-2.1%",tone:"negative"},comparison:"vs previous month",sparkValues:[21,34,28,41,44,38],onSelect:()=>{}}),c.jsx(Nr,{metric:"t.margin",label:"Gross Margin",value:.324,format:{format:"percent"},delta:{label:"+1.1pt",tone:"positive"},comparison:"vs previous month",sparkValues:[24,26,29,27,31,32],onSelect:()=>{}})]}),c.jsx(Go,{points:W2,formatValue:x=>`$${Math.round(x).toLocaleString("en-US")}`,formatAxis:x=>`$${Math.round(x/1e3)}k`,formatLabel:x=>x.slice(0,7),ariaLabel:"Twelve month revenue trend"}),c.jsxs("div",{className:"max-w-xl",children:[c.jsx("h3",{className:"text-sm font-semibold text-ink",children:"How the comparison works"}),c.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"The overlay shifts the previous period onto the current axis so both lines share a scale. Deltas are computed on the visible range only — zooming recomputes them. Hover any point for the exact pair of values; the quiet gray line is always the older period."})]}),c.jsx("pre",{className:"overflow-x-auto font-mono text-xs leading-5 text-muted",children:H2})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Numerals — mono, tabular"}),c.jsxs("div",{className:"flex flex-wrap gap-12",children:[c.jsx("div",{className:"font-mono tnum text-sm text-ink",children:["$1,204,918.24","$984,003.10","$88,214.00","$1,111,111.11"].map(x=>c.jsx("div",{className:"text-right",children:x},x))}),c.jsx("div",{className:"font-mono tnum text-sm text-ink",children:["2025-06-30 23:59:59","2025-07-01 00:00:00","2025-12-31 08:15:42"].map(x=>c.jsx("div",{children:x},x))}),c.jsxs("div",{className:"font-mono text-sm text-ink",children:["0O · 1lI · 5S · 8B · ","->"," ","=>"," ","!="," ",">="]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Weights in use — 400 / 500 / 600 (no bold anywhere)"}),c.jsxs("div",{className:"space-y-2 text-ink",children:[c.jsx(yy,{family:"var(--font-sans)",size:"text-sm"}),c.jsx(yy,{family:"var(--font-sans)",size:"text-xs"}),c.jsx("div",{className:"text-xl font-semibold",style:{fontFamily:"var(--font-display)"},children:"Display 600 — Quarterly revenue, all regions"})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Current ramp — every size in the app and where it appears"}),c.jsx("div",{className:"space-y-1.5",children:P2.map(x=>c.jsxs("div",{className:"grid grid-cols-[3rem_7rem_1fr_1.2fr] items-baseline gap-3",children:[c.jsxs("span",{className:"font-mono tnum text-2xs text-faint",children:[x.px,"px"]}),c.jsx("span",{className:"font-mono text-2xs text-faint",children:x.cls}),c.jsx("span",{className:"truncate text-ink",style:{fontSize:`${x.px}px`,lineHeight:1.3},children:x.sample}),c.jsx("span",{className:"text-2xs text-faint",children:x.usage})]},x.px))})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Size ramp candidates"}),c.jsx("div",{className:"grid grid-cols-1 gap-8 lg:grid-cols-3",children:z2.map(x=>c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"text-sm font-semibold text-ink",children:x.name}),c.jsx("p",{className:"mt-0.5 text-2xs text-faint",children:x.note}),c.jsxs("div",{className:"mt-3 space-y-2",children:[c.jsxs("div",{className:"text-faint",style:{fontSize:x.caption,lineHeight:1.3},children:["Caption ",x.caption,"px · vs previous month"]}),c.jsxs("div",{className:"text-muted",style:{fontSize:x.label,lineHeight:1.35},children:["Label ",x.label,"px · Revenue by region"]}),c.jsxs("div",{className:"text-ink",style:{fontSize:x.body,lineHeight:1.45},children:["Body ",x.body,"px · The overlay shifts the previous period onto the current axis so both lines share a scale."]}),c.jsxs("div",{className:"font-semibold text-ink",style:{fontSize:x.section,lineHeight:1.35},children:["Section title ",x.section,"px"]}),c.jsx("div",{className:"font-mono tnum font-semibold text-ink",style:{fontSize:x.value,lineHeight:1.15},children:"$288,291"}),c.jsx("div",{className:"font-mono tnum font-semibold text-ink",style:{fontSize:x.headline,lineHeight:1.15},children:"$1,282,392"}),c.jsx("div",{className:"font-semibold text-ink",style:{fontFamily:"var(--font-display)",fontSize:x.title,lineHeight:1.2,letterSpacing:"-0.025em"},children:"Revenue overview"})]})]},x.name))})]})]})]})]})}i_();const i0=document.getElementById("root");if(!i0)throw new Error("Missing #root element");fb.createRoot(i0).render(c.jsx(M.StrictMode,{children:window.location.pathname==="/components"?c.jsx(U2,{}):window.location.pathname==="/typography"?c.jsx(G2,{}):c.jsx(i2,{})})); diff --git a/sidemantic-rs/ui/index.html b/sidemantic-rs/ui/index.html index bb523053..228aea02 100644 --- a/sidemantic-rs/ui/index.html +++ b/sidemantic-rs/ui/index.html @@ -4,7 +4,7 @@ Sidemantic - + diff --git a/sidemantic/ui/static/assets/index-iemRTgYP.js b/sidemantic/ui/static/assets/index-D-e4ps_P.js similarity index 77% rename from sidemantic/ui/static/assets/index-iemRTgYP.js rename to sidemantic/ui/static/assets/index-D-e4ps_P.js index 873cbd34..212baf71 100644 --- a/sidemantic/ui/static/assets/index-iemRTgYP.js +++ b/sidemantic/ui/static/assets/index-D-e4ps_P.js @@ -1,4 +1,4 @@ -var Xx=Object.defineProperty;var eb=(n,e,t)=>e in n?Xx(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Mn=(n,e,t)=>eb(n,typeof e!="symbol"?e+"":e,t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))i(a);new MutationObserver(a=>{for(const u of a)if(u.type==="childList")for(const f of u.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&i(f)}).observe(document,{childList:!0,subtree:!0});function t(a){const u={};return a.integrity&&(u.integrity=a.integrity),a.referrerPolicy&&(u.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?u.credentials="include":a.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function i(a){if(a.ep)return;a.ep=!0;const u=t(a);fetch(a.href,u)}})();var Jc={exports:{}},wo={},qc={exports:{}},Be={};/** +var nb=Object.defineProperty;var rb=(n,e,t)=>e in n?nb(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Mn=(n,e,t)=>rb(n,typeof e!="symbol"?e+"":e,t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))i(a);new MutationObserver(a=>{for(const u of a)if(u.type==="childList")for(const f of u.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&i(f)}).observe(document,{childList:!0,subtree:!0});function t(a){const u={};return a.integrity&&(u.integrity=a.integrity),a.referrerPolicy&&(u.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?u.credentials="include":a.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function i(a){if(a.ep)return;a.ep=!0;const u=t(a);fetch(a.href,u)}})();var Jc={exports:{}},wo={},qc={exports:{}},Be={};/** * @license React * react.production.min.js * @@ -6,7 +6,7 @@ var Xx=Object.defineProperty;var eb=(n,e,t)=>e in n?Xx(n,e,{enumerable:!0,config * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var Xp;function tb(){if(Xp)return Be;Xp=1;var n=Symbol.for("react.element"),e=Symbol.for("react.portal"),t=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),u=Symbol.for("react.provider"),f=Symbol.for("react.context"),h=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),g=Symbol.for("react.memo"),v=Symbol.for("react.lazy"),x=Symbol.iterator;function b(_){return _===null||typeof _!="object"?null:(_=x&&_[x]||_["@@iterator"],typeof _=="function"?_:null)}var w={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},j=Object.assign,C={};function O(_,F,te){this.props=_,this.context=F,this.refs=C,this.updater=te||w}O.prototype.isReactComponent={},O.prototype.setState=function(_,F){if(typeof _!="object"&&typeof _!="function"&&_!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,_,F,"setState")},O.prototype.forceUpdate=function(_){this.updater.enqueueForceUpdate(this,_,"forceUpdate")};function H(){}H.prototype=O.prototype;function L(_,F,te){this.props=_,this.context=F,this.refs=C,this.updater=te||w}var R=L.prototype=new H;R.constructor=L,j(R,O.prototype),R.isPureReactComponent=!0;var T=Array.isArray,E=Object.prototype.hasOwnProperty,I={current:null},U={key:!0,ref:!0,__self:!0,__source:!0};function G(_,F,te){var pe,ne={},fe=null,Ce=null;if(F!=null)for(pe in F.ref!==void 0&&(Ce=F.ref),F.key!==void 0&&(fe=""+F.key),F)E.call(F,pe)&&!U.hasOwnProperty(pe)&&(ne[pe]=F[pe]);var Te=arguments.length-2;if(Te===1)ne.children=te;else if(1e in n?Xx(n,e,{enumerable:!0,config * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var tm;function nb(){if(tm)return wo;tm=1;var n=Ad(),e=Symbol.for("react.element"),t=Symbol.for("react.fragment"),i=Object.prototype.hasOwnProperty,a=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,u={key:!0,ref:!0,__self:!0,__source:!0};function f(h,m,g){var v,x={},b=null,w=null;g!==void 0&&(b=""+g),m.key!==void 0&&(b=""+m.key),m.ref!==void 0&&(w=m.ref);for(v in m)i.call(m,v)&&!u.hasOwnProperty(v)&&(x[v]=m[v]);if(h&&h.defaultProps)for(v in m=h.defaultProps,m)x[v]===void 0&&(x[v]=m[v]);return{$$typeof:e,type:h,key:b,ref:w,props:x,_owner:a.current}}return wo.Fragment=t,wo.jsx=f,wo.jsxs=f,wo}var nm;function rb(){return nm||(nm=1,Jc.exports=nb()),Jc.exports}var c=rb(),D=Ad(),tl={},Zc={exports:{}},$t={},Xc={exports:{}},ed={};/** + */var tm;function ib(){if(tm)return wo;tm=1;var n=Ad(),e=Symbol.for("react.element"),t=Symbol.for("react.fragment"),i=Object.prototype.hasOwnProperty,a=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,u={key:!0,ref:!0,__self:!0,__source:!0};function f(h,m,g){var v,x={},b=null,w=null;g!==void 0&&(b=""+g),m.key!==void 0&&(b=""+m.key),m.ref!==void 0&&(w=m.ref);for(v in m)i.call(m,v)&&!u.hasOwnProperty(v)&&(x[v]=m[v]);if(h&&h.defaultProps)for(v in m=h.defaultProps,m)x[v]===void 0&&(x[v]=m[v]);return{$$typeof:e,type:h,key:b,ref:w,props:x,_owner:a.current}}return wo.Fragment=t,wo.jsx=f,wo.jsxs=f,wo}var nm;function ob(){return nm||(nm=1,Jc.exports=ib()),Jc.exports}var c=ob(),M=Ad(),tl={},Zc={exports:{}},$t={},Xc={exports:{}},ed={};/** * @license React * scheduler.production.min.js * @@ -22,7 +22,7 @@ var Xx=Object.defineProperty;var eb=(n,e,t)=>e in n?Xx(n,e,{enumerable:!0,config * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var rm;function sb(){return rm||(rm=1,(function(n){function e(A,Y){var W=A.length;A.push(Y);e:for(;0>>1,F=A[_];if(0>>1;_a(ne,W))fea(Ce,ne)?(A[_]=Ce,A[fe]=W,_=fe):(A[_]=ne,A[pe]=W,_=pe);else if(fea(Ce,W))A[_]=Ce,A[fe]=W,_=fe;else break e}}return Y}function a(A,Y){var W=A.sortIndex-Y.sortIndex;return W!==0?W:A.id-Y.id}if(typeof performance=="object"&&typeof performance.now=="function"){var u=performance;n.unstable_now=function(){return u.now()}}else{var f=Date,h=f.now();n.unstable_now=function(){return f.now()-h}}var m=[],g=[],v=1,x=null,b=3,w=!1,j=!1,C=!1,O=typeof setTimeout=="function"?setTimeout:null,H=typeof clearTimeout=="function"?clearTimeout:null,L=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function R(A){for(var Y=t(g);Y!==null;){if(Y.callback===null)i(g);else if(Y.startTime<=A)i(g),Y.sortIndex=Y.expirationTime,e(m,Y);else break;Y=t(g)}}function T(A){if(C=!1,R(A),!j)if(t(m)!==null)j=!0,re(E);else{var Y=t(g);Y!==null&&se(T,Y.startTime-A)}}function E(A,Y){j=!1,C&&(C=!1,H(G),G=-1),w=!0;var W=b;try{for(R(Y),x=t(m);x!==null&&(!(x.expirationTime>Y)||A&&!z());){var _=x.callback;if(typeof _=="function"){x.callback=null,b=x.priorityLevel;var F=_(x.expirationTime<=Y);Y=n.unstable_now(),typeof F=="function"?x.callback=F:x===t(m)&&i(m),R(Y)}else i(m);x=t(m)}if(x!==null)var te=!0;else{var pe=t(g);pe!==null&&se(T,pe.startTime-Y),te=!1}return te}finally{x=null,b=W,w=!1}}var I=!1,U=null,G=-1,V=5,Q=-1;function z(){return!(n.unstable_now()-QA||125_?(A.sortIndex=W,e(g,A),t(m)===null&&A===t(g)&&(C?(H(G),G=-1):C=!0,se(T,W-_))):(A.sortIndex=F,e(m,A),j||w||(j=!0,re(E))),A},n.unstable_shouldYield=z,n.unstable_wrapCallback=function(A){var Y=b;return function(){var W=b;b=Y;try{return A.apply(this,arguments)}finally{b=W}}}})(ed)),ed}var sm;function ib(){return sm||(sm=1,Xc.exports=sb()),Xc.exports}/** + */var rm;function ab(){return rm||(rm=1,(function(n){function e(A,Y){var W=A.length;A.push(Y);e:for(;0>>1,F=A[_];if(0>>1;_a(ne,W))fea(Ce,ne)?(A[_]=Ce,A[fe]=W,_=fe):(A[_]=ne,A[pe]=W,_=pe);else if(fea(Ce,W))A[_]=Ce,A[fe]=W,_=fe;else break e}}return Y}function a(A,Y){var W=A.sortIndex-Y.sortIndex;return W!==0?W:A.id-Y.id}if(typeof performance=="object"&&typeof performance.now=="function"){var u=performance;n.unstable_now=function(){return u.now()}}else{var f=Date,h=f.now();n.unstable_now=function(){return f.now()-h}}var m=[],g=[],v=1,x=null,b=3,w=!1,j=!1,C=!1,O=typeof setTimeout=="function"?setTimeout:null,H=typeof clearTimeout=="function"?clearTimeout:null,L=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function R(A){for(var Y=t(g);Y!==null;){if(Y.callback===null)i(g);else if(Y.startTime<=A)i(g),Y.sortIndex=Y.expirationTime,e(m,Y);else break;Y=t(g)}}function T(A){if(C=!1,R(A),!j)if(t(m)!==null)j=!0,re(E);else{var Y=t(g);Y!==null&&se(T,Y.startTime-A)}}function E(A,Y){j=!1,C&&(C=!1,H(G),G=-1),w=!0;var W=b;try{for(R(Y),x=t(m);x!==null&&(!(x.expirationTime>Y)||A&&!z());){var _=x.callback;if(typeof _=="function"){x.callback=null,b=x.priorityLevel;var F=_(x.expirationTime<=Y);Y=n.unstable_now(),typeof F=="function"?x.callback=F:x===t(m)&&i(m),R(Y)}else i(m);x=t(m)}if(x!==null)var te=!0;else{var pe=t(g);pe!==null&&se(T,pe.startTime-Y),te=!1}return te}finally{x=null,b=W,w=!1}}var I=!1,U=null,G=-1,V=5,Q=-1;function z(){return!(n.unstable_now()-QA||125_?(A.sortIndex=W,e(g,A),t(m)===null&&A===t(g)&&(C?(H(G),G=-1):C=!0,se(T,W-_))):(A.sortIndex=F,e(m,A),j||w||(j=!0,re(E))),A},n.unstable_shouldYield=z,n.unstable_wrapCallback=function(A){var Y=b;return function(){var W=b;b=Y;try{return A.apply(this,arguments)}finally{b=W}}}})(ed)),ed}var sm;function lb(){return sm||(sm=1,Xc.exports=ab()),Xc.exports}/** * @license React * react-dom.production.min.js * @@ -30,26 +30,26 @@ var Xx=Object.defineProperty;var eb=(n,e,t)=>e in n?Xx(n,e,{enumerable:!0,config * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var im;function ob(){if(im)return $t;im=1;var n=Ad(),e=ib();function t(r){for(var s="https://reactjs.org/docs/error-decoder.html?invariant="+r,o=1;o"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),m=Object.prototype.hasOwnProperty,g=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,v={},x={};function b(r){return m.call(x,r)?!0:m.call(v,r)?!1:g.test(r)?x[r]=!0:(v[r]=!0,!1)}function w(r,s,o,l){if(o!==null&&o.type===0)return!1;switch(typeof s){case"function":case"symbol":return!0;case"boolean":return l?!1:o!==null?!o.acceptsBooleans:(r=r.toLowerCase().slice(0,5),r!=="data-"&&r!=="aria-");default:return!1}}function j(r,s,o,l){if(s===null||typeof s>"u"||w(r,s,o,l))return!0;if(l)return!1;if(o!==null)switch(o.type){case 3:return!s;case 4:return s===!1;case 5:return isNaN(s);case 6:return isNaN(s)||1>s}return!1}function C(r,s,o,l,d,p,y){this.acceptsBooleans=s===2||s===3||s===4,this.attributeName=l,this.attributeNamespace=d,this.mustUseProperty=o,this.propertyName=r,this.type=s,this.sanitizeURL=p,this.removeEmptyString=y}var O={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(r){O[r]=new C(r,0,!1,r,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(r){var s=r[0];O[s]=new C(s,1,!1,r[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(r){O[r]=new C(r,2,!1,r.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(r){O[r]=new C(r,2,!1,r,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(r){O[r]=new C(r,3,!1,r.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(r){O[r]=new C(r,3,!0,r,null,!1,!1)}),["capture","download"].forEach(function(r){O[r]=new C(r,4,!1,r,null,!1,!1)}),["cols","rows","size","span"].forEach(function(r){O[r]=new C(r,6,!1,r,null,!1,!1)}),["rowSpan","start"].forEach(function(r){O[r]=new C(r,5,!1,r.toLowerCase(),null,!1,!1)});var H=/[\-:]([a-z])/g;function L(r){return r[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(r){var s=r.replace(H,L);O[s]=new C(s,1,!1,r,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(r){var s=r.replace(H,L);O[s]=new C(s,1,!1,r,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(r){var s=r.replace(H,L);O[s]=new C(s,1,!1,r,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(r){O[r]=new C(r,1,!1,r.toLowerCase(),null,!1,!1)}),O.xlinkHref=new C("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(r){O[r]=new C(r,1,!1,r.toLowerCase(),null,!0,!0)});function R(r,s,o,l){var d=O.hasOwnProperty(s)?O[s]:null;(d!==null?d.type!==0:l||!(2"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),m=Object.prototype.hasOwnProperty,g=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,v={},x={};function b(r){return m.call(x,r)?!0:m.call(v,r)?!1:g.test(r)?x[r]=!0:(v[r]=!0,!1)}function w(r,s,o,l){if(o!==null&&o.type===0)return!1;switch(typeof s){case"function":case"symbol":return!0;case"boolean":return l?!1:o!==null?!o.acceptsBooleans:(r=r.toLowerCase().slice(0,5),r!=="data-"&&r!=="aria-");default:return!1}}function j(r,s,o,l){if(s===null||typeof s>"u"||w(r,s,o,l))return!0;if(l)return!1;if(o!==null)switch(o.type){case 3:return!s;case 4:return s===!1;case 5:return isNaN(s);case 6:return isNaN(s)||1>s}return!1}function C(r,s,o,l,d,p,y){this.acceptsBooleans=s===2||s===3||s===4,this.attributeName=l,this.attributeNamespace=d,this.mustUseProperty=o,this.propertyName=r,this.type=s,this.sanitizeURL=p,this.removeEmptyString=y}var O={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(r){O[r]=new C(r,0,!1,r,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(r){var s=r[0];O[s]=new C(s,1,!1,r[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(r){O[r]=new C(r,2,!1,r.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(r){O[r]=new C(r,2,!1,r,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(r){O[r]=new C(r,3,!1,r.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(r){O[r]=new C(r,3,!0,r,null,!1,!1)}),["capture","download"].forEach(function(r){O[r]=new C(r,4,!1,r,null,!1,!1)}),["cols","rows","size","span"].forEach(function(r){O[r]=new C(r,6,!1,r,null,!1,!1)}),["rowSpan","start"].forEach(function(r){O[r]=new C(r,5,!1,r.toLowerCase(),null,!1,!1)});var H=/[\-:]([a-z])/g;function L(r){return r[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(r){var s=r.replace(H,L);O[s]=new C(s,1,!1,r,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(r){var s=r.replace(H,L);O[s]=new C(s,1,!1,r,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(r){var s=r.replace(H,L);O[s]=new C(s,1,!1,r,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(r){O[r]=new C(r,1,!1,r.toLowerCase(),null,!1,!1)}),O.xlinkHref=new C("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(r){O[r]=new C(r,1,!1,r.toLowerCase(),null,!0,!0)});function R(r,s,o,l){var d=O.hasOwnProperty(s)?O[s]:null;(d!==null?d.type!==0:l||!(2S||d[y]!==p[S]){var N=` -`+d[y].replace(" at new "," at ");return r.displayName&&N.includes("")&&(N=N.replace("",r.displayName)),N}while(1<=y&&0<=S);break}}}finally{te=!1,Error.prepareStackTrace=o}return(r=r?r.displayName||r.name:"")?F(r):""}function ne(r){switch(r.tag){case 5:return F(r.type);case 16:return F("Lazy");case 13:return F("Suspense");case 19:return F("SuspenseList");case 0:case 2:case 15:return r=pe(r.type,!1),r;case 11:return r=pe(r.type.render,!1),r;case 1:return r=pe(r.type,!0),r;default:return""}}function fe(r){if(r==null)return null;if(typeof r=="function")return r.displayName||r.name||null;if(typeof r=="string")return r;switch(r){case U:return"Fragment";case I:return"Portal";case V:return"Profiler";case G:return"StrictMode";case X:return"Suspense";case ie:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case z:return(r.displayName||"Context")+".Consumer";case Q:return(r._context.displayName||"Context")+".Provider";case ee:var s=r.render;return r=r.displayName,r||(r=s.displayName||s.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case ae:return s=r.displayName||null,s!==null?s:fe(r.type)||"Memo";case re:s=r._payload,r=r._init;try{return fe(r(s))}catch{}}return null}function Ce(r){var s=r.type;switch(r.tag){case 24:return"Cache";case 9:return(s.displayName||"Context")+".Consumer";case 10:return(s._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return r=s.render,r=r.displayName||r.name||"",s.displayName||(r!==""?"ForwardRef("+r+")":"ForwardRef");case 7:return"Fragment";case 5:return s;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return fe(s);case 8:return s===G?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof s=="function")return s.displayName||s.name||null;if(typeof s=="string")return s}return null}function Te(r){switch(typeof r){case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function Ue(r){var s=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(s==="checkbox"||s==="radio")}function lt(r){var s=Ue(r)?"checked":"value",o=Object.getOwnPropertyDescriptor(r.constructor.prototype,s),l=""+r[s];if(!r.hasOwnProperty(s)&&typeof o<"u"&&typeof o.get=="function"&&typeof o.set=="function"){var d=o.get,p=o.set;return Object.defineProperty(r,s,{configurable:!0,get:function(){return d.call(this)},set:function(y){l=""+y,p.call(this,y)}}),Object.defineProperty(r,s,{enumerable:o.enumerable}),{getValue:function(){return l},setValue:function(y){l=""+y},stopTracking:function(){r._valueTracker=null,delete r[s]}}}}function wt(r){r._valueTracker||(r._valueTracker=lt(r))}function Bs(r){if(!r)return!1;var s=r._valueTracker;if(!s)return!0;var o=s.getValue(),l="";return r&&(l=Ue(r)?r.checked?"true":"false":r.value),r=l,r!==o?(s.setValue(r),!0):!1}function xn(r){if(r=r||(typeof document<"u"?document:void 0),typeof r>"u")return null;try{return r.activeElement||r.body}catch{return r.body}}function Cr(r,s){var o=s.checked;return W({},s,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:o??r._wrapperState.initialChecked})}function Fr(r,s){var o=s.defaultValue==null?"":s.defaultValue,l=s.checked!=null?s.checked:s.defaultChecked;o=Te(s.value!=null?s.value:o),r._wrapperState={initialChecked:l,initialValue:o,controlled:s.type==="checkbox"||s.type==="radio"?s.checked!=null:s.value!=null}}function ue(r,s){s=s.checked,s!=null&&R(r,"checked",s,!1)}function Oe(r,s){ue(r,s);var o=Te(s.value),l=s.type;if(o!=null)l==="number"?(o===0&&r.value===""||r.value!=o)&&(r.value=""+o):r.value!==""+o&&(r.value=""+o);else if(l==="submit"||l==="reset"){r.removeAttribute("value");return}s.hasOwnProperty("value")?Nt(r,s.type,o):s.hasOwnProperty("defaultValue")&&Nt(r,s.type,Te(s.defaultValue)),s.checked==null&&s.defaultChecked!=null&&(r.defaultChecked=!!s.defaultChecked)}function rt(r,s,o){if(s.hasOwnProperty("value")||s.hasOwnProperty("defaultValue")){var l=s.type;if(!(l!=="submit"&&l!=="reset"||s.value!==void 0&&s.value!==null))return;s=""+r._wrapperState.initialValue,o||s===r.value||(r.value=s),r.defaultValue=s}o=r.name,o!==""&&(r.name=""),r.defaultChecked=!!r._wrapperState.initialChecked,o!==""&&(r.name=o)}function Nt(r,s,o){(s!=="number"||xn(r.ownerDocument)!==r)&&(o==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+o&&(r.defaultValue=""+o))}var Un=Array.isArray;function sr(r,s,o,l){if(r=r.options,s){s={};for(var d=0;d"+s.valueOf().toString()+"",s=ds.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;s.firstChild;)r.appendChild(s.firstChild)}});function ir(r,s){if(s){var o=r.firstChild;if(o&&o===r.lastChild&&o.nodeType===3){o.nodeValue=s;return}}r.textContent=s}var Ri={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},r0=["Webkit","ms","Moz","O"];Object.keys(Ri).forEach(function(r){r0.forEach(function(s){s=s+r.charAt(0).toUpperCase()+r.substring(1),Ri[s]=Ri[r]})});function pf(r,s,o){return s==null||typeof s=="boolean"||s===""?"":o||typeof s!="number"||s===0||Ri.hasOwnProperty(r)&&Ri[r]?(""+s).trim():s+"px"}function mf(r,s){r=r.style;for(var o in s)if(s.hasOwnProperty(o)){var l=o.indexOf("--")===0,d=pf(o,s[o],l);o==="float"&&(o="cssFloat"),l?r.setProperty(o,d):r[o]=d}}var s0=W({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function lu(r,s){if(s){if(s0[r]&&(s.children!=null||s.dangerouslySetInnerHTML!=null))throw Error(t(137,r));if(s.dangerouslySetInnerHTML!=null){if(s.children!=null)throw Error(t(60));if(typeof s.dangerouslySetInnerHTML!="object"||!("__html"in s.dangerouslySetInnerHTML))throw Error(t(61))}if(s.style!=null&&typeof s.style!="object")throw Error(t(62))}}function uu(r,s){if(r.indexOf("-")===-1)return typeof s.is=="string";switch(r){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var cu=null;function du(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var fu=null,Rs=null,Ls=null;function yf(r){if(r=io(r)){if(typeof fu!="function")throw Error(t(280));var s=r.stateNode;s&&(s=ya(s),fu(r.stateNode,r.type,s))}}function gf(r){Rs?Ls?Ls.push(r):Ls=[r]:Rs=r}function vf(){if(Rs){var r=Rs,s=Ls;if(Ls=Rs=null,yf(r),s)for(r=0;r>>=0,r===0?32:31-(m0(r)/y0|0)|0}var Zo=64,Xo=4194304;function Pi(r){switch(r&-r){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return r&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return r}}function ea(r,s){var o=r.pendingLanes;if(o===0)return 0;var l=0,d=r.suspendedLanes,p=r.pingedLanes,y=o&268435455;if(y!==0){var S=y&~d;S!==0?l=Pi(S):(p&=y,p!==0&&(l=Pi(p)))}else y=o&~d,y!==0?l=Pi(y):p!==0&&(l=Pi(p));if(l===0)return 0;if(s!==0&&s!==l&&(s&d)===0&&(d=l&-l,p=s&-s,d>=p||d===16&&(p&4194240)!==0))return s;if((l&4)!==0&&(l|=o&16),s=r.entangledLanes,s!==0)for(r=r.entanglements,s&=l;0o;o++)s.push(r);return s}function zi(r,s,o){r.pendingLanes|=s,s!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,s=31-wn(s),r[s]=o}function b0(r,s){var o=r.pendingLanes&~s;r.pendingLanes=s,r.suspendedLanes=0,r.pingedLanes=0,r.expiredLanes&=s,r.mutableReadLanes&=s,r.entangledLanes&=s,s=r.entanglements;var l=r.eventTimes;for(r=r.expirationTimes;0=Ji),Gf=" ",Yf=!1;function Qf(r,s){switch(r){case"keyup":return Q0.indexOf(s.keyCode)!==-1;case"keydown":return s.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Kf(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var Ps=!1;function J0(r,s){switch(r){case"compositionend":return Kf(s);case"keypress":return s.which!==32?null:(Yf=!0,Gf);case"textInput":return r=s.data,r===Gf&&Yf?null:r;default:return null}}function q0(r,s){if(Ps)return r==="compositionend"||!Cu&&Qf(r,s)?(r=$f(),ia=Nu=Er=null,Ps=!1,r):null;switch(r){case"paste":return null;case"keypress":if(!(s.ctrlKey||s.altKey||s.metaKey)||s.ctrlKey&&s.altKey){if(s.char&&1=s)return{node:o,offset:s-r};r=l}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=nh(o)}}function sh(r,s){return r&&s?r===s?!0:r&&r.nodeType===3?!1:s&&s.nodeType===3?sh(r,s.parentNode):"contains"in r?r.contains(s):r.compareDocumentPosition?!!(r.compareDocumentPosition(s)&16):!1:!1}function ih(){for(var r=window,s=xn();s instanceof r.HTMLIFrameElement;){try{var o=typeof s.contentWindow.location.href=="string"}catch{o=!1}if(o)r=s.contentWindow;else break;s=xn(r.document)}return s}function Tu(r){var s=r&&r.nodeName&&r.nodeName.toLowerCase();return s&&(s==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||s==="textarea"||r.contentEditable==="true")}function ox(r){var s=ih(),o=r.focusedElem,l=r.selectionRange;if(s!==o&&o&&o.ownerDocument&&sh(o.ownerDocument.documentElement,o)){if(l!==null&&Tu(o)){if(s=l.start,r=l.end,r===void 0&&(r=s),"selectionStart"in o)o.selectionStart=s,o.selectionEnd=Math.min(r,o.value.length);else if(r=(s=o.ownerDocument||document)&&s.defaultView||window,r.getSelection){r=r.getSelection();var d=o.textContent.length,p=Math.min(l.start,d);l=l.end===void 0?p:Math.min(l.end,d),!r.extend&&p>l&&(d=l,l=p,p=d),d=rh(o,p);var y=rh(o,l);d&&y&&(r.rangeCount!==1||r.anchorNode!==d.node||r.anchorOffset!==d.offset||r.focusNode!==y.node||r.focusOffset!==y.offset)&&(s=s.createRange(),s.setStart(d.node,d.offset),r.removeAllRanges(),p>l?(r.addRange(s),r.extend(y.node,y.offset)):(s.setEnd(y.node,y.offset),r.addRange(s)))}}for(s=[],r=o;r=r.parentNode;)r.nodeType===1&&s.push({element:r,left:r.scrollLeft,top:r.scrollTop});for(typeof o.focus=="function"&&o.focus(),o=0;o=document.documentMode,zs=null,Au=null,eo=null,Bu=!1;function oh(r,s,o){var l=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;Bu||zs==null||zs!==xn(l)||(l=zs,"selectionStart"in l&&Tu(l)?l={start:l.selectionStart,end:l.selectionEnd}:(l=(l.ownerDocument&&l.ownerDocument.defaultView||window).getSelection(),l={anchorNode:l.anchorNode,anchorOffset:l.anchorOffset,focusNode:l.focusNode,focusOffset:l.focusOffset}),eo&&Xi(eo,l)||(eo=l,l=ha(Au,"onSelect"),0Ys||(r.current=Yu[Ys],Yu[Ys]=null,Ys--)}function qe(r,s){Ys++,Yu[Ys]=r.current,r.current=s}var $r={},jt=Ur($r),Bt=Ur(!1),ps=$r;function Qs(r,s){var o=r.type.contextTypes;if(!o)return $r;var l=r.stateNode;if(l&&l.__reactInternalMemoizedUnmaskedChildContext===s)return l.__reactInternalMemoizedMaskedChildContext;var d={},p;for(p in o)d[p]=s[p];return l&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=s,r.__reactInternalMemoizedMaskedChildContext=d),d}function Et(r){return r=r.childContextTypes,r!=null}function ga(){et(Bt),et(jt)}function wh(r,s,o){if(jt.current!==$r)throw Error(t(168));qe(jt,s),qe(Bt,o)}function Sh(r,s,o){var l=r.stateNode;if(s=s.childContextTypes,typeof l.getChildContext!="function")return o;l=l.getChildContext();for(var d in l)if(!(d in s))throw Error(t(108,Ce(r)||"Unknown",d));return W({},o,l)}function va(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||$r,ps=jt.current,qe(jt,r),qe(Bt,Bt.current),!0}function _h(r,s,o){var l=r.stateNode;if(!l)throw Error(t(169));o?(r=Sh(r,s,ps),l.__reactInternalMemoizedMergedChildContext=r,et(Bt),et(jt),qe(jt,r)):et(Bt),qe(Bt,o)}var ar=null,xa=!1,Qu=!1;function Nh(r){ar===null?ar=[r]:ar.push(r)}function vx(r){xa=!0,Nh(r)}function Pr(){if(!Qu&&ar!==null){Qu=!0;var r=0,s=Ge;try{var o=ar;for(Ge=1;r>=y,d-=y,lr=1<<32-wn(s)+d|o<Me?(bt=ge,ge=null):bt=ge.sibling;var ze=K(B,ge,$[Me],Z);if(ze===null){ge===null&&(ge=bt);break}r&&ge&&ze.alternate===null&&s(B,ge),k=p(ze,k,Me),ye===null?he=ze:ye.sibling=ze,ye=ze,ge=bt}if(Me===$.length)return o(B,ge),st&&ys(B,Me),he;if(ge===null){for(;Me<$.length;Me++)ge=q(B,$[Me],Z),ge!==null&&(k=p(ge,k,Me),ye===null?he=ge:ye.sibling=ge,ye=ge);return st&&ys(B,Me),he}for(ge=l(B,ge);Me<$.length;Me++)bt=oe(ge,B,Me,$[Me],Z),bt!==null&&(r&&bt.alternate!==null&&ge.delete(bt.key===null?Me:bt.key),k=p(bt,k,Me),ye===null?he=bt:ye.sibling=bt,ye=bt);return r&&ge.forEach(function(Jr){return s(B,Jr)}),st&&ys(B,Me),he}function de(B,k,$,Z){var he=Y($);if(typeof he!="function")throw Error(t(150));if($=he.call($),$==null)throw Error(t(151));for(var ye=he=null,ge=k,Me=k=0,bt=null,ze=$.next();ge!==null&&!ze.done;Me++,ze=$.next()){ge.index>Me?(bt=ge,ge=null):bt=ge.sibling;var Jr=K(B,ge,ze.value,Z);if(Jr===null){ge===null&&(ge=bt);break}r&&ge&&Jr.alternate===null&&s(B,ge),k=p(Jr,k,Me),ye===null?he=Jr:ye.sibling=Jr,ye=Jr,ge=bt}if(ze.done)return o(B,ge),st&&ys(B,Me),he;if(ge===null){for(;!ze.done;Me++,ze=$.next())ze=q(B,ze.value,Z),ze!==null&&(k=p(ze,k,Me),ye===null?he=ze:ye.sibling=ze,ye=ze);return st&&ys(B,Me),he}for(ge=l(B,ge);!ze.done;Me++,ze=$.next())ze=oe(ge,B,Me,ze.value,Z),ze!==null&&(r&&ze.alternate!==null&&ge.delete(ze.key===null?Me:ze.key),k=p(ze,k,Me),ye===null?he=ze:ye.sibling=ze,ye=ze);return r&&ge.forEach(function(Zx){return s(B,Zx)}),st&&ys(B,Me),he}function dt(B,k,$,Z){if(typeof $=="object"&&$!==null&&$.type===U&&$.key===null&&($=$.props.children),typeof $=="object"&&$!==null){switch($.$$typeof){case E:e:{for(var he=$.key,ye=k;ye!==null;){if(ye.key===he){if(he=$.type,he===U){if(ye.tag===7){o(B,ye.sibling),k=d(ye,$.props.children),k.return=B,B=k;break e}}else if(ye.elementType===he||typeof he=="object"&&he!==null&&he.$$typeof===re&&Ch(he)===ye.type){o(B,ye.sibling),k=d(ye,$.props),k.ref=oo(B,ye,$),k.return=B,B=k;break e}o(B,ye);break}else s(B,ye);ye=ye.sibling}$.type===U?(k=Ns($.props.children,B.mode,Z,$.key),k.return=B,B=k):(Z=Ya($.type,$.key,$.props,null,B.mode,Z),Z.ref=oo(B,k,$),Z.return=B,B=Z)}return y(B);case I:e:{for(ye=$.key;k!==null;){if(k.key===ye)if(k.tag===4&&k.stateNode.containerInfo===$.containerInfo&&k.stateNode.implementation===$.implementation){o(B,k.sibling),k=d(k,$.children||[]),k.return=B,B=k;break e}else{o(B,k);break}else s(B,k);k=k.sibling}k=Hc($,B.mode,Z),k.return=B,B=k}return y(B);case re:return ye=$._init,dt(B,k,ye($._payload),Z)}if(Un($))return ce(B,k,$,Z);if(Y($))return de(B,k,$,Z);_a(B,$)}return typeof $=="string"&&$!==""||typeof $=="number"?($=""+$,k!==null&&k.tag===6?(o(B,k.sibling),k=d(k,$),k.return=B,B=k):(o(B,k),k=Wc($,B.mode,Z),k.return=B,B=k),y(B)):o(B,k)}return dt}var Zs=Fh(!0),Oh=Fh(!1),Na=Ur(null),ja=null,Xs=null,ec=null;function tc(){ec=Xs=ja=null}function nc(r){var s=Na.current;et(Na),r._currentValue=s}function rc(r,s,o){for(;r!==null;){var l=r.alternate;if((r.childLanes&s)!==s?(r.childLanes|=s,l!==null&&(l.childLanes|=s)):l!==null&&(l.childLanes&s)!==s&&(l.childLanes|=s),r===o)break;r=r.return}}function ei(r,s){ja=r,ec=Xs=null,r=r.dependencies,r!==null&&r.firstContext!==null&&((r.lanes&s)!==0&&(Rt=!0),r.firstContext=null)}function sn(r){var s=r._currentValue;if(ec!==r)if(r={context:r,memoizedValue:s,next:null},Xs===null){if(ja===null)throw Error(t(308));Xs=r,ja.dependencies={lanes:0,firstContext:r}}else Xs=Xs.next=r;return s}var gs=null;function sc(r){gs===null?gs=[r]:gs.push(r)}function Th(r,s,o,l){var d=s.interleaved;return d===null?(o.next=o,sc(s)):(o.next=d.next,d.next=o),s.interleaved=o,cr(r,l)}function cr(r,s){r.lanes|=s;var o=r.alternate;for(o!==null&&(o.lanes|=s),o=r,r=r.return;r!==null;)r.childLanes|=s,o=r.alternate,o!==null&&(o.childLanes|=s),o=r,r=r.return;return o.tag===3?o.stateNode:null}var zr=!1;function ic(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ah(r,s){r=r.updateQueue,s.updateQueue===r&&(s.updateQueue={baseState:r.baseState,firstBaseUpdate:r.firstBaseUpdate,lastBaseUpdate:r.lastBaseUpdate,shared:r.shared,effects:r.effects})}function dr(r,s){return{eventTime:r,lane:s,tag:0,payload:null,callback:null,next:null}}function Vr(r,s,o){var l=r.updateQueue;if(l===null)return null;if(l=l.shared,(Pe&2)!==0){var d=l.pending;return d===null?s.next=s:(s.next=d.next,d.next=s),l.pending=s,cr(r,o)}return d=l.interleaved,d===null?(s.next=s,sc(l)):(s.next=d.next,d.next=s),l.interleaved=s,cr(r,o)}function ka(r,s,o){if(s=s.updateQueue,s!==null&&(s=s.shared,(o&4194240)!==0)){var l=s.lanes;l&=r.pendingLanes,o|=l,s.lanes=o,xu(r,o)}}function Bh(r,s){var o=r.updateQueue,l=r.alternate;if(l!==null&&(l=l.updateQueue,o===l)){var d=null,p=null;if(o=o.firstBaseUpdate,o!==null){do{var y={eventTime:o.eventTime,lane:o.lane,tag:o.tag,payload:o.payload,callback:o.callback,next:null};p===null?d=p=y:p=p.next=y,o=o.next}while(o!==null);p===null?d=p=s:p=p.next=s}else d=p=s;o={baseState:l.baseState,firstBaseUpdate:d,lastBaseUpdate:p,shared:l.shared,effects:l.effects},r.updateQueue=o;return}r=o.lastBaseUpdate,r===null?o.firstBaseUpdate=s:r.next=s,o.lastBaseUpdate=s}function Ia(r,s,o,l){var d=r.updateQueue;zr=!1;var p=d.firstBaseUpdate,y=d.lastBaseUpdate,S=d.shared.pending;if(S!==null){d.shared.pending=null;var N=S,P=N.next;N.next=null,y===null?p=P:y.next=P,y=N;var J=r.alternate;J!==null&&(J=J.updateQueue,S=J.lastBaseUpdate,S!==y&&(S===null?J.firstBaseUpdate=P:S.next=P,J.lastBaseUpdate=N))}if(p!==null){var q=d.baseState;y=0,J=P=N=null,S=p;do{var K=S.lane,oe=S.eventTime;if((l&K)===K){J!==null&&(J=J.next={eventTime:oe,lane:0,tag:S.tag,payload:S.payload,callback:S.callback,next:null});e:{var ce=r,de=S;switch(K=s,oe=o,de.tag){case 1:if(ce=de.payload,typeof ce=="function"){q=ce.call(oe,q,K);break e}q=ce;break e;case 3:ce.flags=ce.flags&-65537|128;case 0:if(ce=de.payload,K=typeof ce=="function"?ce.call(oe,q,K):ce,K==null)break e;q=W({},q,K);break e;case 2:zr=!0}}S.callback!==null&&S.lane!==0&&(r.flags|=64,K=d.effects,K===null?d.effects=[S]:K.push(S))}else oe={eventTime:oe,lane:K,tag:S.tag,payload:S.payload,callback:S.callback,next:null},J===null?(P=J=oe,N=q):J=J.next=oe,y|=K;if(S=S.next,S===null){if(S=d.shared.pending,S===null)break;K=S,S=K.next,K.next=null,d.lastBaseUpdate=K,d.shared.pending=null}}while(!0);if(J===null&&(N=q),d.baseState=N,d.firstBaseUpdate=P,d.lastBaseUpdate=J,s=d.shared.interleaved,s!==null){d=s;do y|=d.lane,d=d.next;while(d!==s)}else p===null&&(d.shared.lanes=0);bs|=y,r.lanes=y,r.memoizedState=q}}function Eh(r,s,o){if(r=s.effects,s.effects=null,r!==null)for(s=0;so?o:4,r(!0);var l=cc.transition;cc.transition={};try{r(!1),s()}finally{Ge=o,cc.transition=l}}function tp(){return on().memoizedState}function Sx(r,s,o){var l=Yr(r);if(o={lane:l,action:o,hasEagerState:!1,eagerState:null,next:null},np(r))rp(s,o);else if(o=Th(r,s,o,l),o!==null){var d=Ft();In(o,r,l,d),sp(o,s,l)}}function _x(r,s,o){var l=Yr(r),d={lane:l,action:o,hasEagerState:!1,eagerState:null,next:null};if(np(r))rp(s,d);else{var p=r.alternate;if(r.lanes===0&&(p===null||p.lanes===0)&&(p=s.lastRenderedReducer,p!==null))try{var y=s.lastRenderedState,S=p(y,o);if(d.hasEagerState=!0,d.eagerState=S,Sn(S,y)){var N=s.interleaved;N===null?(d.next=d,sc(s)):(d.next=N.next,N.next=d),s.interleaved=d;return}}catch{}finally{}o=Th(r,s,d,l),o!==null&&(d=Ft(),In(o,r,l,d),sp(o,s,l))}}function np(r){var s=r.alternate;return r===ot||s!==null&&s===ot}function rp(r,s){co=Ca=!0;var o=r.pending;o===null?s.next=s:(s.next=o.next,o.next=s),r.pending=s}function sp(r,s,o){if((o&4194240)!==0){var l=s.lanes;l&=r.pendingLanes,o|=l,s.lanes=o,xu(r,o)}}var Ta={readContext:sn,useCallback:kt,useContext:kt,useEffect:kt,useImperativeHandle:kt,useInsertionEffect:kt,useLayoutEffect:kt,useMemo:kt,useReducer:kt,useRef:kt,useState:kt,useDebugValue:kt,useDeferredValue:kt,useTransition:kt,useMutableSource:kt,useSyncExternalStore:kt,useId:kt,unstable_isNewReconciler:!1},Nx={readContext:sn,useCallback:function(r,s){return Vn().memoizedState=[r,s===void 0?null:s],r},useContext:sn,useEffect:Yh,useImperativeHandle:function(r,s,o){return o=o!=null?o.concat([r]):null,Fa(4194308,4,Jh.bind(null,s,r),o)},useLayoutEffect:function(r,s){return Fa(4194308,4,r,s)},useInsertionEffect:function(r,s){return Fa(4,2,r,s)},useMemo:function(r,s){var o=Vn();return s=s===void 0?null:s,r=r(),o.memoizedState=[r,s],r},useReducer:function(r,s,o){var l=Vn();return s=o!==void 0?o(s):s,l.memoizedState=l.baseState=s,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:s},l.queue=r,r=r.dispatch=Sx.bind(null,ot,r),[l.memoizedState,r]},useRef:function(r){var s=Vn();return r={current:r},s.memoizedState=r},useState:Hh,useDebugValue:gc,useDeferredValue:function(r){return Vn().memoizedState=r},useTransition:function(){var r=Hh(!1),s=r[0];return r=wx.bind(null,r[1]),Vn().memoizedState=r,[s,r]},useMutableSource:function(){},useSyncExternalStore:function(r,s,o){var l=ot,d=Vn();if(st){if(o===void 0)throw Error(t(407));o=o()}else{if(o=s(),xt===null)throw Error(t(349));(xs&30)!==0||$h(l,s,o)}d.memoizedState=o;var p={value:o,getSnapshot:s};return d.queue=p,Yh(zh.bind(null,l,p,r),[r]),l.flags|=2048,po(9,Ph.bind(null,l,p,o,s),void 0,null),o},useId:function(){var r=Vn(),s=xt.identifierPrefix;if(st){var o=ur,l=lr;o=(l&~(1<<32-wn(l)-1)).toString(32)+o,s=":"+s+"R"+o,o=fo++,0")&&(N=N.replace("",r.displayName)),N}while(1<=y&&0<=S);break}}}finally{te=!1,Error.prepareStackTrace=o}return(r=r?r.displayName||r.name:"")?F(r):""}function ne(r){switch(r.tag){case 5:return F(r.type);case 16:return F("Lazy");case 13:return F("Suspense");case 19:return F("SuspenseList");case 0:case 2:case 15:return r=pe(r.type,!1),r;case 11:return r=pe(r.type.render,!1),r;case 1:return r=pe(r.type,!0),r;default:return""}}function fe(r){if(r==null)return null;if(typeof r=="function")return r.displayName||r.name||null;if(typeof r=="string")return r;switch(r){case U:return"Fragment";case I:return"Portal";case V:return"Profiler";case G:return"StrictMode";case X:return"Suspense";case ie:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case z:return(r.displayName||"Context")+".Consumer";case Q:return(r._context.displayName||"Context")+".Provider";case ee:var s=r.render;return r=r.displayName,r||(r=s.displayName||s.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case ae:return s=r.displayName||null,s!==null?s:fe(r.type)||"Memo";case re:s=r._payload,r=r._init;try{return fe(r(s))}catch{}}return null}function Ce(r){var s=r.type;switch(r.tag){case 24:return"Cache";case 9:return(s.displayName||"Context")+".Consumer";case 10:return(s._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return r=s.render,r=r.displayName||r.name||"",s.displayName||(r!==""?"ForwardRef("+r+")":"ForwardRef");case 7:return"Fragment";case 5:return s;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return fe(s);case 8:return s===G?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof s=="function")return s.displayName||s.name||null;if(typeof s=="string")return s}return null}function Te(r){switch(typeof r){case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function Ue(r){var s=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(s==="checkbox"||s==="radio")}function lt(r){var s=Ue(r)?"checked":"value",o=Object.getOwnPropertyDescriptor(r.constructor.prototype,s),l=""+r[s];if(!r.hasOwnProperty(s)&&typeof o<"u"&&typeof o.get=="function"&&typeof o.set=="function"){var d=o.get,p=o.set;return Object.defineProperty(r,s,{configurable:!0,get:function(){return d.call(this)},set:function(y){l=""+y,p.call(this,y)}}),Object.defineProperty(r,s,{enumerable:o.enumerable}),{getValue:function(){return l},setValue:function(y){l=""+y},stopTracking:function(){r._valueTracker=null,delete r[s]}}}}function wt(r){r._valueTracker||(r._valueTracker=lt(r))}function Bs(r){if(!r)return!1;var s=r._valueTracker;if(!s)return!0;var o=s.getValue(),l="";return r&&(l=Ue(r)?r.checked?"true":"false":r.value),r=l,r!==o?(s.setValue(r),!0):!1}function xn(r){if(r=r||(typeof document<"u"?document:void 0),typeof r>"u")return null;try{return r.activeElement||r.body}catch{return r.body}}function Cr(r,s){var o=s.checked;return W({},s,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:o??r._wrapperState.initialChecked})}function Fr(r,s){var o=s.defaultValue==null?"":s.defaultValue,l=s.checked!=null?s.checked:s.defaultChecked;o=Te(s.value!=null?s.value:o),r._wrapperState={initialChecked:l,initialValue:o,controlled:s.type==="checkbox"||s.type==="radio"?s.checked!=null:s.value!=null}}function ue(r,s){s=s.checked,s!=null&&R(r,"checked",s,!1)}function Oe(r,s){ue(r,s);var o=Te(s.value),l=s.type;if(o!=null)l==="number"?(o===0&&r.value===""||r.value!=o)&&(r.value=""+o):r.value!==""+o&&(r.value=""+o);else if(l==="submit"||l==="reset"){r.removeAttribute("value");return}s.hasOwnProperty("value")?Nt(r,s.type,o):s.hasOwnProperty("defaultValue")&&Nt(r,s.type,Te(s.defaultValue)),s.checked==null&&s.defaultChecked!=null&&(r.defaultChecked=!!s.defaultChecked)}function rt(r,s,o){if(s.hasOwnProperty("value")||s.hasOwnProperty("defaultValue")){var l=s.type;if(!(l!=="submit"&&l!=="reset"||s.value!==void 0&&s.value!==null))return;s=""+r._wrapperState.initialValue,o||s===r.value||(r.value=s),r.defaultValue=s}o=r.name,o!==""&&(r.name=""),r.defaultChecked=!!r._wrapperState.initialChecked,o!==""&&(r.name=o)}function Nt(r,s,o){(s!=="number"||xn(r.ownerDocument)!==r)&&(o==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+o&&(r.defaultValue=""+o))}var Un=Array.isArray;function sr(r,s,o,l){if(r=r.options,s){s={};for(var d=0;d"+s.valueOf().toString()+"",s=ds.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;s.firstChild;)r.appendChild(s.firstChild)}});function ir(r,s){if(s){var o=r.firstChild;if(o&&o===r.lastChild&&o.nodeType===3){o.nodeValue=s;return}}r.textContent=s}var Ri={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},o0=["Webkit","ms","Moz","O"];Object.keys(Ri).forEach(function(r){o0.forEach(function(s){s=s+r.charAt(0).toUpperCase()+r.substring(1),Ri[s]=Ri[r]})});function pf(r,s,o){return s==null||typeof s=="boolean"||s===""?"":o||typeof s!="number"||s===0||Ri.hasOwnProperty(r)&&Ri[r]?(""+s).trim():s+"px"}function mf(r,s){r=r.style;for(var o in s)if(s.hasOwnProperty(o)){var l=o.indexOf("--")===0,d=pf(o,s[o],l);o==="float"&&(o="cssFloat"),l?r.setProperty(o,d):r[o]=d}}var a0=W({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function lu(r,s){if(s){if(a0[r]&&(s.children!=null||s.dangerouslySetInnerHTML!=null))throw Error(t(137,r));if(s.dangerouslySetInnerHTML!=null){if(s.children!=null)throw Error(t(60));if(typeof s.dangerouslySetInnerHTML!="object"||!("__html"in s.dangerouslySetInnerHTML))throw Error(t(61))}if(s.style!=null&&typeof s.style!="object")throw Error(t(62))}}function uu(r,s){if(r.indexOf("-")===-1)return typeof s.is=="string";switch(r){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var cu=null;function du(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var fu=null,Rs=null,Ls=null;function yf(r){if(r=io(r)){if(typeof fu!="function")throw Error(t(280));var s=r.stateNode;s&&(s=ya(s),fu(r.stateNode,r.type,s))}}function gf(r){Rs?Ls?Ls.push(r):Ls=[r]:Rs=r}function vf(){if(Rs){var r=Rs,s=Ls;if(Ls=Rs=null,yf(r),s)for(r=0;r>>=0,r===0?32:31-(v0(r)/x0|0)|0}var Zo=64,Xo=4194304;function Pi(r){switch(r&-r){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return r&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return r}}function ea(r,s){var o=r.pendingLanes;if(o===0)return 0;var l=0,d=r.suspendedLanes,p=r.pingedLanes,y=o&268435455;if(y!==0){var S=y&~d;S!==0?l=Pi(S):(p&=y,p!==0&&(l=Pi(p)))}else y=o&~d,y!==0?l=Pi(y):p!==0&&(l=Pi(p));if(l===0)return 0;if(s!==0&&s!==l&&(s&d)===0&&(d=l&-l,p=s&-s,d>=p||d===16&&(p&4194240)!==0))return s;if((l&4)!==0&&(l|=o&16),s=r.entangledLanes,s!==0)for(r=r.entanglements,s&=l;0o;o++)s.push(r);return s}function zi(r,s,o){r.pendingLanes|=s,s!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,s=31-wn(s),r[s]=o}function _0(r,s){var o=r.pendingLanes&~s;r.pendingLanes=s,r.suspendedLanes=0,r.pingedLanes=0,r.expiredLanes&=s,r.mutableReadLanes&=s,r.entangledLanes&=s,s=r.entanglements;var l=r.eventTimes;for(r=r.expirationTimes;0=Ji),Gf=" ",Yf=!1;function Qf(r,s){switch(r){case"keyup":return q0.indexOf(s.keyCode)!==-1;case"keydown":return s.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Kf(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var Ps=!1;function X0(r,s){switch(r){case"compositionend":return Kf(s);case"keypress":return s.which!==32?null:(Yf=!0,Gf);case"textInput":return r=s.data,r===Gf&&Yf?null:r;default:return null}}function ex(r,s){if(Ps)return r==="compositionend"||!Cu&&Qf(r,s)?(r=$f(),ia=Nu=Er=null,Ps=!1,r):null;switch(r){case"paste":return null;case"keypress":if(!(s.ctrlKey||s.altKey||s.metaKey)||s.ctrlKey&&s.altKey){if(s.char&&1=s)return{node:o,offset:s-r};r=l}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=nh(o)}}function sh(r,s){return r&&s?r===s?!0:r&&r.nodeType===3?!1:s&&s.nodeType===3?sh(r,s.parentNode):"contains"in r?r.contains(s):r.compareDocumentPosition?!!(r.compareDocumentPosition(s)&16):!1:!1}function ih(){for(var r=window,s=xn();s instanceof r.HTMLIFrameElement;){try{var o=typeof s.contentWindow.location.href=="string"}catch{o=!1}if(o)r=s.contentWindow;else break;s=xn(r.document)}return s}function Tu(r){var s=r&&r.nodeName&&r.nodeName.toLowerCase();return s&&(s==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||s==="textarea"||r.contentEditable==="true")}function ux(r){var s=ih(),o=r.focusedElem,l=r.selectionRange;if(s!==o&&o&&o.ownerDocument&&sh(o.ownerDocument.documentElement,o)){if(l!==null&&Tu(o)){if(s=l.start,r=l.end,r===void 0&&(r=s),"selectionStart"in o)o.selectionStart=s,o.selectionEnd=Math.min(r,o.value.length);else if(r=(s=o.ownerDocument||document)&&s.defaultView||window,r.getSelection){r=r.getSelection();var d=o.textContent.length,p=Math.min(l.start,d);l=l.end===void 0?p:Math.min(l.end,d),!r.extend&&p>l&&(d=l,l=p,p=d),d=rh(o,p);var y=rh(o,l);d&&y&&(r.rangeCount!==1||r.anchorNode!==d.node||r.anchorOffset!==d.offset||r.focusNode!==y.node||r.focusOffset!==y.offset)&&(s=s.createRange(),s.setStart(d.node,d.offset),r.removeAllRanges(),p>l?(r.addRange(s),r.extend(y.node,y.offset)):(s.setEnd(y.node,y.offset),r.addRange(s)))}}for(s=[],r=o;r=r.parentNode;)r.nodeType===1&&s.push({element:r,left:r.scrollLeft,top:r.scrollTop});for(typeof o.focus=="function"&&o.focus(),o=0;o=document.documentMode,zs=null,Au=null,eo=null,Bu=!1;function oh(r,s,o){var l=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;Bu||zs==null||zs!==xn(l)||(l=zs,"selectionStart"in l&&Tu(l)?l={start:l.selectionStart,end:l.selectionEnd}:(l=(l.ownerDocument&&l.ownerDocument.defaultView||window).getSelection(),l={anchorNode:l.anchorNode,anchorOffset:l.anchorOffset,focusNode:l.focusNode,focusOffset:l.focusOffset}),eo&&Xi(eo,l)||(eo=l,l=ha(Au,"onSelect"),0Ys||(r.current=Yu[Ys],Yu[Ys]=null,Ys--)}function qe(r,s){Ys++,Yu[Ys]=r.current,r.current=s}var $r={},jt=Ur($r),Bt=Ur(!1),ps=$r;function Qs(r,s){var o=r.type.contextTypes;if(!o)return $r;var l=r.stateNode;if(l&&l.__reactInternalMemoizedUnmaskedChildContext===s)return l.__reactInternalMemoizedMaskedChildContext;var d={},p;for(p in o)d[p]=s[p];return l&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=s,r.__reactInternalMemoizedMaskedChildContext=d),d}function Et(r){return r=r.childContextTypes,r!=null}function ga(){et(Bt),et(jt)}function wh(r,s,o){if(jt.current!==$r)throw Error(t(168));qe(jt,s),qe(Bt,o)}function Sh(r,s,o){var l=r.stateNode;if(s=s.childContextTypes,typeof l.getChildContext!="function")return o;l=l.getChildContext();for(var d in l)if(!(d in s))throw Error(t(108,Ce(r)||"Unknown",d));return W({},o,l)}function va(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||$r,ps=jt.current,qe(jt,r),qe(Bt,Bt.current),!0}function _h(r,s,o){var l=r.stateNode;if(!l)throw Error(t(169));o?(r=Sh(r,s,ps),l.__reactInternalMemoizedMergedChildContext=r,et(Bt),et(jt),qe(jt,r)):et(Bt),qe(Bt,o)}var ar=null,xa=!1,Qu=!1;function Nh(r){ar===null?ar=[r]:ar.push(r)}function wx(r){xa=!0,Nh(r)}function Pr(){if(!Qu&&ar!==null){Qu=!0;var r=0,s=Ge;try{var o=ar;for(Ge=1;r>=y,d-=y,lr=1<<32-wn(s)+d|o<Me?(bt=ge,ge=null):bt=ge.sibling;var ze=K(B,ge,$[Me],Z);if(ze===null){ge===null&&(ge=bt);break}r&&ge&&ze.alternate===null&&s(B,ge),k=p(ze,k,Me),ye===null?he=ze:ye.sibling=ze,ye=ze,ge=bt}if(Me===$.length)return o(B,ge),st&&ys(B,Me),he;if(ge===null){for(;Me<$.length;Me++)ge=q(B,$[Me],Z),ge!==null&&(k=p(ge,k,Me),ye===null?he=ge:ye.sibling=ge,ye=ge);return st&&ys(B,Me),he}for(ge=l(B,ge);Me<$.length;Me++)bt=oe(ge,B,Me,$[Me],Z),bt!==null&&(r&&bt.alternate!==null&&ge.delete(bt.key===null?Me:bt.key),k=p(bt,k,Me),ye===null?he=bt:ye.sibling=bt,ye=bt);return r&&ge.forEach(function(Jr){return s(B,Jr)}),st&&ys(B,Me),he}function de(B,k,$,Z){var he=Y($);if(typeof he!="function")throw Error(t(150));if($=he.call($),$==null)throw Error(t(151));for(var ye=he=null,ge=k,Me=k=0,bt=null,ze=$.next();ge!==null&&!ze.done;Me++,ze=$.next()){ge.index>Me?(bt=ge,ge=null):bt=ge.sibling;var Jr=K(B,ge,ze.value,Z);if(Jr===null){ge===null&&(ge=bt);break}r&&ge&&Jr.alternate===null&&s(B,ge),k=p(Jr,k,Me),ye===null?he=Jr:ye.sibling=Jr,ye=Jr,ge=bt}if(ze.done)return o(B,ge),st&&ys(B,Me),he;if(ge===null){for(;!ze.done;Me++,ze=$.next())ze=q(B,ze.value,Z),ze!==null&&(k=p(ze,k,Me),ye===null?he=ze:ye.sibling=ze,ye=ze);return st&&ys(B,Me),he}for(ge=l(B,ge);!ze.done;Me++,ze=$.next())ze=oe(ge,B,Me,ze.value,Z),ze!==null&&(r&&ze.alternate!==null&&ge.delete(ze.key===null?Me:ze.key),k=p(ze,k,Me),ye===null?he=ze:ye.sibling=ze,ye=ze);return r&&ge.forEach(function(tb){return s(B,tb)}),st&&ys(B,Me),he}function dt(B,k,$,Z){if(typeof $=="object"&&$!==null&&$.type===U&&$.key===null&&($=$.props.children),typeof $=="object"&&$!==null){switch($.$$typeof){case E:e:{for(var he=$.key,ye=k;ye!==null;){if(ye.key===he){if(he=$.type,he===U){if(ye.tag===7){o(B,ye.sibling),k=d(ye,$.props.children),k.return=B,B=k;break e}}else if(ye.elementType===he||typeof he=="object"&&he!==null&&he.$$typeof===re&&Ch(he)===ye.type){o(B,ye.sibling),k=d(ye,$.props),k.ref=oo(B,ye,$),k.return=B,B=k;break e}o(B,ye);break}else s(B,ye);ye=ye.sibling}$.type===U?(k=Ns($.props.children,B.mode,Z,$.key),k.return=B,B=k):(Z=Ya($.type,$.key,$.props,null,B.mode,Z),Z.ref=oo(B,k,$),Z.return=B,B=Z)}return y(B);case I:e:{for(ye=$.key;k!==null;){if(k.key===ye)if(k.tag===4&&k.stateNode.containerInfo===$.containerInfo&&k.stateNode.implementation===$.implementation){o(B,k.sibling),k=d(k,$.children||[]),k.return=B,B=k;break e}else{o(B,k);break}else s(B,k);k=k.sibling}k=Hc($,B.mode,Z),k.return=B,B=k}return y(B);case re:return ye=$._init,dt(B,k,ye($._payload),Z)}if(Un($))return ce(B,k,$,Z);if(Y($))return de(B,k,$,Z);_a(B,$)}return typeof $=="string"&&$!==""||typeof $=="number"?($=""+$,k!==null&&k.tag===6?(o(B,k.sibling),k=d(k,$),k.return=B,B=k):(o(B,k),k=Wc($,B.mode,Z),k.return=B,B=k),y(B)):o(B,k)}return dt}var Zs=Fh(!0),Oh=Fh(!1),Na=Ur(null),ja=null,Xs=null,ec=null;function tc(){ec=Xs=ja=null}function nc(r){var s=Na.current;et(Na),r._currentValue=s}function rc(r,s,o){for(;r!==null;){var l=r.alternate;if((r.childLanes&s)!==s?(r.childLanes|=s,l!==null&&(l.childLanes|=s)):l!==null&&(l.childLanes&s)!==s&&(l.childLanes|=s),r===o)break;r=r.return}}function ei(r,s){ja=r,ec=Xs=null,r=r.dependencies,r!==null&&r.firstContext!==null&&((r.lanes&s)!==0&&(Rt=!0),r.firstContext=null)}function sn(r){var s=r._currentValue;if(ec!==r)if(r={context:r,memoizedValue:s,next:null},Xs===null){if(ja===null)throw Error(t(308));Xs=r,ja.dependencies={lanes:0,firstContext:r}}else Xs=Xs.next=r;return s}var gs=null;function sc(r){gs===null?gs=[r]:gs.push(r)}function Th(r,s,o,l){var d=s.interleaved;return d===null?(o.next=o,sc(s)):(o.next=d.next,d.next=o),s.interleaved=o,cr(r,l)}function cr(r,s){r.lanes|=s;var o=r.alternate;for(o!==null&&(o.lanes|=s),o=r,r=r.return;r!==null;)r.childLanes|=s,o=r.alternate,o!==null&&(o.childLanes|=s),o=r,r=r.return;return o.tag===3?o.stateNode:null}var zr=!1;function ic(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ah(r,s){r=r.updateQueue,s.updateQueue===r&&(s.updateQueue={baseState:r.baseState,firstBaseUpdate:r.firstBaseUpdate,lastBaseUpdate:r.lastBaseUpdate,shared:r.shared,effects:r.effects})}function dr(r,s){return{eventTime:r,lane:s,tag:0,payload:null,callback:null,next:null}}function Vr(r,s,o){var l=r.updateQueue;if(l===null)return null;if(l=l.shared,(Pe&2)!==0){var d=l.pending;return d===null?s.next=s:(s.next=d.next,d.next=s),l.pending=s,cr(r,o)}return d=l.interleaved,d===null?(s.next=s,sc(l)):(s.next=d.next,d.next=s),l.interleaved=s,cr(r,o)}function ka(r,s,o){if(s=s.updateQueue,s!==null&&(s=s.shared,(o&4194240)!==0)){var l=s.lanes;l&=r.pendingLanes,o|=l,s.lanes=o,xu(r,o)}}function Bh(r,s){var o=r.updateQueue,l=r.alternate;if(l!==null&&(l=l.updateQueue,o===l)){var d=null,p=null;if(o=o.firstBaseUpdate,o!==null){do{var y={eventTime:o.eventTime,lane:o.lane,tag:o.tag,payload:o.payload,callback:o.callback,next:null};p===null?d=p=y:p=p.next=y,o=o.next}while(o!==null);p===null?d=p=s:p=p.next=s}else d=p=s;o={baseState:l.baseState,firstBaseUpdate:d,lastBaseUpdate:p,shared:l.shared,effects:l.effects},r.updateQueue=o;return}r=o.lastBaseUpdate,r===null?o.firstBaseUpdate=s:r.next=s,o.lastBaseUpdate=s}function Ia(r,s,o,l){var d=r.updateQueue;zr=!1;var p=d.firstBaseUpdate,y=d.lastBaseUpdate,S=d.shared.pending;if(S!==null){d.shared.pending=null;var N=S,P=N.next;N.next=null,y===null?p=P:y.next=P,y=N;var J=r.alternate;J!==null&&(J=J.updateQueue,S=J.lastBaseUpdate,S!==y&&(S===null?J.firstBaseUpdate=P:S.next=P,J.lastBaseUpdate=N))}if(p!==null){var q=d.baseState;y=0,J=P=N=null,S=p;do{var K=S.lane,oe=S.eventTime;if((l&K)===K){J!==null&&(J=J.next={eventTime:oe,lane:0,tag:S.tag,payload:S.payload,callback:S.callback,next:null});e:{var ce=r,de=S;switch(K=s,oe=o,de.tag){case 1:if(ce=de.payload,typeof ce=="function"){q=ce.call(oe,q,K);break e}q=ce;break e;case 3:ce.flags=ce.flags&-65537|128;case 0:if(ce=de.payload,K=typeof ce=="function"?ce.call(oe,q,K):ce,K==null)break e;q=W({},q,K);break e;case 2:zr=!0}}S.callback!==null&&S.lane!==0&&(r.flags|=64,K=d.effects,K===null?d.effects=[S]:K.push(S))}else oe={eventTime:oe,lane:K,tag:S.tag,payload:S.payload,callback:S.callback,next:null},J===null?(P=J=oe,N=q):J=J.next=oe,y|=K;if(S=S.next,S===null){if(S=d.shared.pending,S===null)break;K=S,S=K.next,K.next=null,d.lastBaseUpdate=K,d.shared.pending=null}}while(!0);if(J===null&&(N=q),d.baseState=N,d.firstBaseUpdate=P,d.lastBaseUpdate=J,s=d.shared.interleaved,s!==null){d=s;do y|=d.lane,d=d.next;while(d!==s)}else p===null&&(d.shared.lanes=0);bs|=y,r.lanes=y,r.memoizedState=q}}function Eh(r,s,o){if(r=s.effects,s.effects=null,r!==null)for(s=0;so?o:4,r(!0);var l=cc.transition;cc.transition={};try{r(!1),s()}finally{Ge=o,cc.transition=l}}function tp(){return on().memoizedState}function jx(r,s,o){var l=Yr(r);if(o={lane:l,action:o,hasEagerState:!1,eagerState:null,next:null},np(r))rp(s,o);else if(o=Th(r,s,o,l),o!==null){var d=Ft();In(o,r,l,d),sp(o,s,l)}}function kx(r,s,o){var l=Yr(r),d={lane:l,action:o,hasEagerState:!1,eagerState:null,next:null};if(np(r))rp(s,d);else{var p=r.alternate;if(r.lanes===0&&(p===null||p.lanes===0)&&(p=s.lastRenderedReducer,p!==null))try{var y=s.lastRenderedState,S=p(y,o);if(d.hasEagerState=!0,d.eagerState=S,Sn(S,y)){var N=s.interleaved;N===null?(d.next=d,sc(s)):(d.next=N.next,N.next=d),s.interleaved=d;return}}catch{}finally{}o=Th(r,s,d,l),o!==null&&(d=Ft(),In(o,r,l,d),sp(o,s,l))}}function np(r){var s=r.alternate;return r===ot||s!==null&&s===ot}function rp(r,s){co=Ca=!0;var o=r.pending;o===null?s.next=s:(s.next=o.next,o.next=s),r.pending=s}function sp(r,s,o){if((o&4194240)!==0){var l=s.lanes;l&=r.pendingLanes,o|=l,s.lanes=o,xu(r,o)}}var Ta={readContext:sn,useCallback:kt,useContext:kt,useEffect:kt,useImperativeHandle:kt,useInsertionEffect:kt,useLayoutEffect:kt,useMemo:kt,useReducer:kt,useRef:kt,useState:kt,useDebugValue:kt,useDeferredValue:kt,useTransition:kt,useMutableSource:kt,useSyncExternalStore:kt,useId:kt,unstable_isNewReconciler:!1},Ix={readContext:sn,useCallback:function(r,s){return Vn().memoizedState=[r,s===void 0?null:s],r},useContext:sn,useEffect:Yh,useImperativeHandle:function(r,s,o){return o=o!=null?o.concat([r]):null,Fa(4194308,4,Jh.bind(null,s,r),o)},useLayoutEffect:function(r,s){return Fa(4194308,4,r,s)},useInsertionEffect:function(r,s){return Fa(4,2,r,s)},useMemo:function(r,s){var o=Vn();return s=s===void 0?null:s,r=r(),o.memoizedState=[r,s],r},useReducer:function(r,s,o){var l=Vn();return s=o!==void 0?o(s):s,l.memoizedState=l.baseState=s,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:s},l.queue=r,r=r.dispatch=jx.bind(null,ot,r),[l.memoizedState,r]},useRef:function(r){var s=Vn();return r={current:r},s.memoizedState=r},useState:Hh,useDebugValue:gc,useDeferredValue:function(r){return Vn().memoizedState=r},useTransition:function(){var r=Hh(!1),s=r[0];return r=Nx.bind(null,r[1]),Vn().memoizedState=r,[s,r]},useMutableSource:function(){},useSyncExternalStore:function(r,s,o){var l=ot,d=Vn();if(st){if(o===void 0)throw Error(t(407));o=o()}else{if(o=s(),xt===null)throw Error(t(349));(xs&30)!==0||$h(l,s,o)}d.memoizedState=o;var p={value:o,getSnapshot:s};return d.queue=p,Yh(zh.bind(null,l,p,r),[r]),l.flags|=2048,po(9,Ph.bind(null,l,p,o,s),void 0,null),o},useId:function(){var r=Vn(),s=xt.identifierPrefix;if(st){var o=ur,l=lr;o=(l&~(1<<32-wn(l)-1)).toString(32)+o,s=":"+s+"R"+o,o=fo++,0<\/script>",r=r.removeChild(r.firstChild)):typeof l.is=="string"?r=y.createElement(o,{is:l.is}):(r=y.createElement(o),o==="select"&&(y=r,l.multiple?y.multiple=!0:l.size&&(y.size=l.size))):r=y.createElementNS(r,o),r[Pn]=s,r[so]=l,Np(r,s,!1,!1),s.stateNode=r;e:{switch(y=uu(o,l),o){case"dialog":Xe("cancel",r),Xe("close",r),d=l;break;case"iframe":case"object":case"embed":Xe("load",r),d=l;break;case"video":case"audio":for(d=0;dii&&(s.flags|=128,l=!0,mo(p,!1),s.lanes=4194304)}else{if(!l)if(r=Ma(y),r!==null){if(s.flags|=128,l=!0,o=r.updateQueue,o!==null&&(s.updateQueue=o,s.flags|=4),mo(p,!0),p.tail===null&&p.tailMode==="hidden"&&!y.alternate&&!st)return It(s),null}else 2*ct()-p.renderingStartTime>ii&&o!==1073741824&&(s.flags|=128,l=!0,mo(p,!1),s.lanes=4194304);p.isBackwards?(y.sibling=s.child,s.child=y):(o=p.last,o!==null?o.sibling=y:s.child=y,p.last=y)}return p.tail!==null?(s=p.tail,p.rendering=s,p.tail=s.sibling,p.renderingStartTime=ct(),s.sibling=null,o=it.current,qe(it,l?o&1|2:o&1),s):(It(s),null);case 22:case 23:return Pc(),l=s.memoizedState!==null,r!==null&&r.memoizedState!==null!==l&&(s.flags|=8192),l&&(s.mode&1)!==0?(Jt&1073741824)!==0&&(It(s),s.subtreeFlags&6&&(s.flags|=8192)):It(s),null;case 24:return null;case 25:return null}throw Error(t(156,s.tag))}function Ox(r,s){switch(Ju(s),s.tag){case 1:return Et(s.type)&&ga(),r=s.flags,r&65536?(s.flags=r&-65537|128,s):null;case 3:return ti(),et(Bt),et(jt),uc(),r=s.flags,(r&65536)!==0&&(r&128)===0?(s.flags=r&-65537|128,s):null;case 5:return ac(s),null;case 13:if(et(it),r=s.memoizedState,r!==null&&r.dehydrated!==null){if(s.alternate===null)throw Error(t(340));qs()}return r=s.flags,r&65536?(s.flags=r&-65537|128,s):null;case 19:return et(it),null;case 4:return ti(),null;case 10:return nc(s.type._context),null;case 22:case 23:return Pc(),null;case 24:return null;default:return null}}var Ra=!1,Mt=!1,Tx=typeof WeakSet=="function"?WeakSet:Set,le=null;function ri(r,s){var o=r.ref;if(o!==null)if(typeof o=="function")try{o(null)}catch(l){ut(r,s,l)}else o.current=null}function Dc(r,s,o){try{o()}catch(l){ut(r,s,l)}}var Ip=!1;function Ax(r,s){if(Pu=ra,r=ih(),Tu(r)){if("selectionStart"in r)var o={start:r.selectionStart,end:r.selectionEnd};else e:{o=(o=r.ownerDocument)&&o.defaultView||window;var l=o.getSelection&&o.getSelection();if(l&&l.rangeCount!==0){o=l.anchorNode;var d=l.anchorOffset,p=l.focusNode;l=l.focusOffset;try{o.nodeType,p.nodeType}catch{o=null;break e}var y=0,S=-1,N=-1,P=0,J=0,q=r,K=null;t:for(;;){for(var oe;q!==o||d!==0&&q.nodeType!==3||(S=y+d),q!==p||l!==0&&q.nodeType!==3||(N=y+l),q.nodeType===3&&(y+=q.nodeValue.length),(oe=q.firstChild)!==null;)K=q,q=oe;for(;;){if(q===r)break t;if(K===o&&++P===d&&(S=y),K===p&&++J===l&&(N=y),(oe=q.nextSibling)!==null)break;q=K,K=q.parentNode}q=oe}o=S===-1||N===-1?null:{start:S,end:N}}else o=null}o=o||{start:0,end:0}}else o=null;for(zu={focusedElem:r,selectionRange:o},ra=!1,le=s;le!==null;)if(s=le,r=s.child,(s.subtreeFlags&1028)!==0&&r!==null)r.return=s,le=r;else for(;le!==null;){s=le;try{var ce=s.alternate;if((s.flags&1024)!==0)switch(s.tag){case 0:case 11:case 15:break;case 1:if(ce!==null){var de=ce.memoizedProps,dt=ce.memoizedState,B=s.stateNode,k=B.getSnapshotBeforeUpdate(s.elementType===s.type?de:Nn(s.type,de),dt);B.__reactInternalSnapshotBeforeUpdate=k}break;case 3:var $=s.stateNode.containerInfo;$.nodeType===1?$.textContent="":$.nodeType===9&&$.documentElement&&$.removeChild($.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(t(163))}}catch(Z){ut(s,s.return,Z)}if(r=s.sibling,r!==null){r.return=s.return,le=r;break}le=s.return}return ce=Ip,Ip=!1,ce}function yo(r,s,o){var l=s.updateQueue;if(l=l!==null?l.lastEffect:null,l!==null){var d=l=l.next;do{if((d.tag&r)===r){var p=d.destroy;d.destroy=void 0,p!==void 0&&Dc(s,o,p)}d=d.next}while(d!==l)}}function La(r,s){if(s=s.updateQueue,s=s!==null?s.lastEffect:null,s!==null){var o=s=s.next;do{if((o.tag&r)===r){var l=o.create;o.destroy=l()}o=o.next}while(o!==s)}}function Cc(r){var s=r.ref;if(s!==null){var o=r.stateNode;switch(r.tag){case 5:r=o;break;default:r=o}typeof s=="function"?s(r):s.current=r}}function Mp(r){var s=r.alternate;s!==null&&(r.alternate=null,Mp(s)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(s=r.stateNode,s!==null&&(delete s[Pn],delete s[so],delete s[Gu],delete s[yx],delete s[gx])),r.stateNode=null,r.return=null,r.dependencies=null,r.memoizedProps=null,r.memoizedState=null,r.pendingProps=null,r.stateNode=null,r.updateQueue=null}function Dp(r){return r.tag===5||r.tag===3||r.tag===4}function Cp(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||Dp(r.return))return null;r=r.return}for(r.sibling.return=r.return,r=r.sibling;r.tag!==5&&r.tag!==6&&r.tag!==18;){if(r.flags&2||r.child===null||r.tag===4)continue e;r.child.return=r,r=r.child}if(!(r.flags&2))return r.stateNode}}function Fc(r,s,o){var l=r.tag;if(l===5||l===6)r=r.stateNode,s?o.nodeType===8?o.parentNode.insertBefore(r,s):o.insertBefore(r,s):(o.nodeType===8?(s=o.parentNode,s.insertBefore(r,o)):(s=o,s.appendChild(r)),o=o._reactRootContainer,o!=null||s.onclick!==null||(s.onclick=ma));else if(l!==4&&(r=r.child,r!==null))for(Fc(r,s,o),r=r.sibling;r!==null;)Fc(r,s,o),r=r.sibling}function Oc(r,s,o){var l=r.tag;if(l===5||l===6)r=r.stateNode,s?o.insertBefore(r,s):o.appendChild(r);else if(l!==4&&(r=r.child,r!==null))for(Oc(r,s,o),r=r.sibling;r!==null;)Oc(r,s,o),r=r.sibling}var St=null,jn=!1;function Wr(r,s,o){for(o=o.child;o!==null;)Fp(r,s,o),o=o.sibling}function Fp(r,s,o){if($n&&typeof $n.onCommitFiberUnmount=="function")try{$n.onCommitFiberUnmount(qo,o)}catch{}switch(o.tag){case 5:Mt||ri(o,s);case 6:var l=St,d=jn;St=null,Wr(r,s,o),St=l,jn=d,St!==null&&(jn?(r=St,o=o.stateNode,r.nodeType===8?r.parentNode.removeChild(o):r.removeChild(o)):St.removeChild(o.stateNode));break;case 18:St!==null&&(jn?(r=St,o=o.stateNode,r.nodeType===8?Hu(r.parentNode,o):r.nodeType===1&&Hu(r,o),Yi(r)):Hu(St,o.stateNode));break;case 4:l=St,d=jn,St=o.stateNode.containerInfo,jn=!0,Wr(r,s,o),St=l,jn=d;break;case 0:case 11:case 14:case 15:if(!Mt&&(l=o.updateQueue,l!==null&&(l=l.lastEffect,l!==null))){d=l=l.next;do{var p=d,y=p.destroy;p=p.tag,y!==void 0&&((p&2)!==0||(p&4)!==0)&&Dc(o,s,y),d=d.next}while(d!==l)}Wr(r,s,o);break;case 1:if(!Mt&&(ri(o,s),l=o.stateNode,typeof l.componentWillUnmount=="function"))try{l.props=o.memoizedProps,l.state=o.memoizedState,l.componentWillUnmount()}catch(S){ut(o,s,S)}Wr(r,s,o);break;case 21:Wr(r,s,o);break;case 22:o.mode&1?(Mt=(l=Mt)||o.memoizedState!==null,Wr(r,s,o),Mt=l):Wr(r,s,o);break;default:Wr(r,s,o)}}function Op(r){var s=r.updateQueue;if(s!==null){r.updateQueue=null;var o=r.stateNode;o===null&&(o=r.stateNode=new Tx),s.forEach(function(l){var d=Vx.bind(null,r,l);o.has(l)||(o.add(l),l.then(d,d))})}}function kn(r,s){var o=s.deletions;if(o!==null)for(var l=0;ld&&(d=y),l&=~p}if(l=d,l=ct()-l,l=(120>l?120:480>l?480:1080>l?1080:1920>l?1920:3e3>l?3e3:4320>l?4320:1960*Ex(l/1960))-l,10r?16:r,Gr===null)var l=!1;else{if(r=Gr,Gr=null,Va=0,(Pe&6)!==0)throw Error(t(331));var d=Pe;for(Pe|=4,le=r.current;le!==null;){var p=le,y=p.child;if((le.flags&16)!==0){var S=p.deletions;if(S!==null){for(var N=0;Nct()-Bc?Ss(r,0):Ac|=o),Ut(r,s)}function Hp(r,s){s===0&&((r.mode&1)===0?s=1:(s=Xo,Xo<<=1,(Xo&130023424)===0&&(Xo=4194304)));var o=Ft();r=cr(r,s),r!==null&&(zi(r,s,o),Ut(r,o))}function zx(r){var s=r.memoizedState,o=0;s!==null&&(o=s.retryLane),Hp(r,o)}function Vx(r,s){var o=0;switch(r.tag){case 13:var l=r.stateNode,d=r.memoizedState;d!==null&&(o=d.retryLane);break;case 19:l=r.stateNode;break;default:throw Error(t(314))}l!==null&&l.delete(s),Hp(r,o)}var Gp;Gp=function(r,s,o){if(r!==null)if(r.memoizedProps!==s.pendingProps||Bt.current)Rt=!0;else{if((r.lanes&o)===0&&(s.flags&128)===0)return Rt=!1,Cx(r,s,o);Rt=(r.flags&131072)!==0}else Rt=!1,st&&(s.flags&1048576)!==0&&jh(s,wa,s.index);switch(s.lanes=0,s.tag){case 2:var l=s.type;Ea(r,s),r=s.pendingProps;var d=Qs(s,jt.current);ei(s,o),d=fc(null,s,l,r,d,o);var p=hc();return s.flags|=1,typeof d=="object"&&d!==null&&typeof d.render=="function"&&d.$$typeof===void 0?(s.tag=1,s.memoizedState=null,s.updateQueue=null,Et(l)?(p=!0,va(s)):p=!1,s.memoizedState=d.state!==null&&d.state!==void 0?d.state:null,ic(s),d.updater=Aa,s.stateNode=d,d._reactInternals=s,xc(s,l,r,o),s=_c(null,s,l,!0,p,o)):(s.tag=0,st&&p&&Ku(s),Ct(null,s,d,o),s=s.child),s;case 16:l=s.elementType;e:{switch(Ea(r,s),r=s.pendingProps,d=l._init,l=d(l._payload),s.type=l,d=s.tag=Hx(l),r=Nn(l,r),d){case 0:s=Sc(null,s,l,r,o);break e;case 1:s=vp(null,s,l,r,o);break e;case 11:s=hp(null,s,l,r,o);break e;case 14:s=pp(null,s,l,Nn(l.type,r),o);break e}throw Error(t(306,l,""))}return s;case 0:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),Sc(r,s,l,d,o);case 1:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),vp(r,s,l,d,o);case 3:e:{if(xp(s),r===null)throw Error(t(387));l=s.pendingProps,p=s.memoizedState,d=p.element,Ah(r,s),Ia(s,l,null,o);var y=s.memoizedState;if(l=y.element,p.isDehydrated)if(p={element:l,isDehydrated:!1,cache:y.cache,pendingSuspenseBoundaries:y.pendingSuspenseBoundaries,transitions:y.transitions},s.updateQueue.baseState=p,s.memoizedState=p,s.flags&256){d=ni(Error(t(423)),s),s=bp(r,s,l,o,d);break e}else if(l!==d){d=ni(Error(t(424)),s),s=bp(r,s,l,o,d);break e}else for(Kt=Lr(s.stateNode.containerInfo.firstChild),Qt=s,st=!0,_n=null,o=Oh(s,null,l,o),s.child=o;o;)o.flags=o.flags&-3|4096,o=o.sibling;else{if(qs(),l===d){s=fr(r,s,o);break e}Ct(r,s,l,o)}s=s.child}return s;case 5:return Rh(s),r===null&&Zu(s),l=s.type,d=s.pendingProps,p=r!==null?r.memoizedProps:null,y=d.children,Vu(l,d)?y=null:p!==null&&Vu(l,p)&&(s.flags|=32),gp(r,s),Ct(r,s,y,o),s.child;case 6:return r===null&&Zu(s),null;case 13:return wp(r,s,o);case 4:return oc(s,s.stateNode.containerInfo),l=s.pendingProps,r===null?s.child=Zs(s,null,l,o):Ct(r,s,l,o),s.child;case 11:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),hp(r,s,l,d,o);case 7:return Ct(r,s,s.pendingProps,o),s.child;case 8:return Ct(r,s,s.pendingProps.children,o),s.child;case 12:return Ct(r,s,s.pendingProps.children,o),s.child;case 10:e:{if(l=s.type._context,d=s.pendingProps,p=s.memoizedProps,y=d.value,qe(Na,l._currentValue),l._currentValue=y,p!==null)if(Sn(p.value,y)){if(p.children===d.children&&!Bt.current){s=fr(r,s,o);break e}}else for(p=s.child,p!==null&&(p.return=s);p!==null;){var S=p.dependencies;if(S!==null){y=p.child;for(var N=S.firstContext;N!==null;){if(N.context===l){if(p.tag===1){N=dr(-1,o&-o),N.tag=2;var P=p.updateQueue;if(P!==null){P=P.shared;var J=P.pending;J===null?N.next=N:(N.next=J.next,J.next=N),P.pending=N}}p.lanes|=o,N=p.alternate,N!==null&&(N.lanes|=o),rc(p.return,o,s),S.lanes|=o;break}N=N.next}}else if(p.tag===10)y=p.type===s.type?null:p.child;else if(p.tag===18){if(y=p.return,y===null)throw Error(t(341));y.lanes|=o,S=y.alternate,S!==null&&(S.lanes|=o),rc(y,o,s),y=p.sibling}else y=p.child;if(y!==null)y.return=p;else for(y=p;y!==null;){if(y===s){y=null;break}if(p=y.sibling,p!==null){p.return=y.return,y=p;break}y=y.return}p=y}Ct(r,s,d.children,o),s=s.child}return s;case 9:return d=s.type,l=s.pendingProps.children,ei(s,o),d=sn(d),l=l(d),s.flags|=1,Ct(r,s,l,o),s.child;case 14:return l=s.type,d=Nn(l,s.pendingProps),d=Nn(l.type,d),pp(r,s,l,d,o);case 15:return mp(r,s,s.type,s.pendingProps,o);case 17:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),Ea(r,s),s.tag=1,Et(l)?(r=!0,va(s)):r=!1,ei(s,o),op(s,l,d),xc(s,l,d,o),_c(null,s,l,!0,r,o);case 19:return _p(r,s,o);case 22:return yp(r,s,o)}throw Error(t(156,s.tag))};function Yp(r,s){return kf(r,s)}function Wx(r,s,o,l){this.tag=r,this.key=o,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=s,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=l,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ln(r,s,o,l){return new Wx(r,s,o,l)}function Vc(r){return r=r.prototype,!(!r||!r.isReactComponent)}function Hx(r){if(typeof r=="function")return Vc(r)?1:0;if(r!=null){if(r=r.$$typeof,r===ee)return 11;if(r===ae)return 14}return 2}function Kr(r,s){var o=r.alternate;return o===null?(o=ln(r.tag,s,r.key,r.mode),o.elementType=r.elementType,o.type=r.type,o.stateNode=r.stateNode,o.alternate=r,r.alternate=o):(o.pendingProps=s,o.type=r.type,o.flags=0,o.subtreeFlags=0,o.deletions=null),o.flags=r.flags&14680064,o.childLanes=r.childLanes,o.lanes=r.lanes,o.child=r.child,o.memoizedProps=r.memoizedProps,o.memoizedState=r.memoizedState,o.updateQueue=r.updateQueue,s=r.dependencies,o.dependencies=s===null?null:{lanes:s.lanes,firstContext:s.firstContext},o.sibling=r.sibling,o.index=r.index,o.ref=r.ref,o}function Ya(r,s,o,l,d,p){var y=2;if(l=r,typeof r=="function")Vc(r)&&(y=1);else if(typeof r=="string")y=5;else e:switch(r){case U:return Ns(o.children,d,p,s);case G:y=8,d|=8;break;case V:return r=ln(12,o,s,d|2),r.elementType=V,r.lanes=p,r;case X:return r=ln(13,o,s,d),r.elementType=X,r.lanes=p,r;case ie:return r=ln(19,o,s,d),r.elementType=ie,r.lanes=p,r;case se:return Qa(o,d,p,s);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case Q:y=10;break e;case z:y=9;break e;case ee:y=11;break e;case ae:y=14;break e;case re:y=16,l=null;break e}throw Error(t(130,r==null?r:typeof r,""))}return s=ln(y,o,s,d),s.elementType=r,s.type=l,s.lanes=p,s}function Ns(r,s,o,l){return r=ln(7,r,l,s),r.lanes=o,r}function Qa(r,s,o,l){return r=ln(22,r,l,s),r.elementType=se,r.lanes=o,r.stateNode={isHidden:!1},r}function Wc(r,s,o){return r=ln(6,r,null,s),r.lanes=o,r}function Hc(r,s,o){return s=ln(4,r.children!==null?r.children:[],r.key,s),s.lanes=o,s.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},s}function Gx(r,s,o,l,d){this.tag=s,this.containerInfo=r,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=vu(0),this.expirationTimes=vu(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=vu(0),this.identifierPrefix=l,this.onRecoverableError=d,this.mutableSourceEagerHydrationData=null}function Gc(r,s,o,l,d,p,y,S,N){return r=new Gx(r,s,o,S,N),s===1?(s=1,p===!0&&(s|=8)):s=0,p=ln(3,null,null,s),r.current=p,p.stateNode=r,p.memoizedState={element:l,isDehydrated:o,cache:null,transitions:null,pendingSuspenseBoundaries:null},ic(p),r}function Yx(r,s,o){var l=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),Zc.exports=ob(),Zc.exports}var am;function lb(){if(am)return tl;am=1;var n=ab();return tl.createRoot=n.createRoot,tl.hydrateRoot=n.hydrateRoot,tl}var ub=lb();function Sr(n){return n.split(".").at(-1)||n}function Fn(n,e){const t=Sr(n);if(e.filter(a=>Sr(a)===t).length<2)return t;const i=n.indexOf(".");return i>0?`${n.slice(0,i)}_${t}`:t}const er="\0__null__";function cb(n){return String(n||"").replaceAll("_"," ").replaceAll("."," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}function py(n,e={}){if(n==null||n==="")return"—";const t=typeof n=="number"?n:Number(n);if(!Number.isFinite(t))return String(n);const i=String(e.format||"").toLowerCase();if(e.style==="percent"||i.includes("%")||i.includes("percent")||i.includes("pct")||e.type==="ratio")return(e.style==="percent"?t:Math.abs(t)<=1?t*100:t).toLocaleString(void 0,{maximumFractionDigits:e.maximumFractionDigits??1,style:e.style==="percent"?"percent":"decimal"})+(e.style==="percent"?"":"%");const u=e.style==="currency"||e.currency||i.includes("$")||i.includes("usd")||i.includes("currency")||i.includes("dollar");return t.toLocaleString(void 0,{currency:u?e.currency||"USD":void 0,maximumFractionDigits:e.maximumFractionDigits??2,notation:e.compact?"compact":"standard",style:u?"currency":"decimal"})}function db(n,e={}){return py(n,{...e,compact:!0,maximumFractionDigits:e.maximumFractionDigits??1})}function fb(n,e,t){const i=t>0&&n.length>t,a=i?Math.ceil(n.length/t):1,u=Math.max(0,Math.min(e,a-1)),f=i?u*t:0;return{paginate:i,pageCount:a,safePage:u,start:f,visibleRows:i?n.slice(f,f+t):n}}function rs(n){return n===er||n===""?"—":n}function Le(n){return cb(n)}function pt(n,e={}){return py(n,e)}function Wt(n,e={}){return db(n,e)}function my(n){return!Number.isFinite(n)||n===0?"neutral":n>0?"positive":"negative"}function hb(n,e){return!Number.isFinite(n)||!Number.isFinite(e)||e<=0?{label:"—",tone:"neutral"}:{label:`${(n/e*100).toLocaleString(void 0,{maximumFractionDigits:1})}%`,tone:"neutral"}}function pb(n,e,t={}){if(e==null||!Number.isFinite(e)||!Number.isFinite(n))return{label:"—",tone:"neutral"};const i=n-e;return{label:`${i>0?"+":i<0?"−":""}${Wt(Math.abs(i),t)}`,tone:my(i)}}function mb(n,e){if(e==null||!Number.isFinite(e)||e===0||!Number.isFinite(n))return{label:"—",tone:"neutral"};const t=(n-e)/Math.abs(e);return{label:`${(t*100).toLocaleString(void 0,{maximumFractionDigits:1,signDisplay:"exceptZero"})}%`,tone:my(t)}}function yy(n,e){if(e==null||!Number.isFinite(e)||e===0||!Number.isFinite(n))return null;const t=(n-e)/Math.abs(e),i=(t*100).toLocaleString(void 0,{maximumFractionDigits:1,signDisplay:"exceptZero"}),a=t>0?"positive":t<0?"negative":"neutral";return{label:`${i}%`,tone:a}}function Tn(n){return`'${n.replaceAll("'","''")}'`}function yb(n){if(n.mode==="contains")return`contains ${Tn(n.pattern??"")}`;const{values:e}=n,t=n.mode==="exclude"?"is not":"is";return e.length===0?t:e.length===1?`${t} ${rs(e[0])}`:e.length<=2?`${t} ${e.map(rs).join(", ")}`:`${t} ${e.length} values`}const td=n=>n.public!==!1,gy=/(^|_)(date|time|day|month|week|year|quarter|created|updated|timestamp|_at|_on)($|_)/i;function vy(n,e){if(e){const t=n.find(i=>i.name===e);if(t)return t}return n.find(t=>t.type==="time")??n.find(t=>gy.test(t.name))}function gb(n,e){var f;const t=new Set;if(!n)return t;const i=new Set(e.map(h=>h.name)),a=n.match(/[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*/g)??[];for(const h of a){const[m]=h.split(".");i.has(m)&&t.add(m)}if(t.size)return t;const u=(f=n.match(/^[A-Za-z_][A-Za-z0-9_]*$/))==null?void 0:f[0];if(!u)return t;for(const h of e)h.metrics.some(m=>m.name===u)&&t.add(h.name);return t}function xy(n,e){const t=new Set;for(const i of[n.base_metric,n.numerator,n.denominator,n.sql])for(const a of gb(i,e))t.add(a);return t.size===1?[...t][0]:void 0}function vb(n){const e=(n.models??[]).map(i=>{const a=(i.dimensions??[]).filter(td).map(h=>({ref:`${i.name}.${h.name}`,name:h.name,model:i.name,label:h.label||Le(h.name),description:h.description,type:h.type||"categorical",granularity:h.granularity,supportedGranularities:h.supported_granularities,format:h.format})),u=(i.metrics??[]).filter(td).map(h=>({ref:`${i.name}.${h.name}`,name:h.name,model:i.name,label:h.label||Le(h.name),description:h.description,agg:h.agg,type:h.type,format:h.format})),f=vy(a,i.default_time_dimension);return{name:i.name,label:Le(i.name),description:i.description,table:i.table,dimensions:a,metrics:u,timeDimension:f,defaultGrain:i.default_grain||(f==null?void 0:f.granularity)||"day"}}),t=(n.metrics??[]).filter(td).map(i=>({ref:i.name,name:i.name,ownerModel:xy(i,e),baseMetric:i.base_metric,label:i.label||Le(i.name),description:i.description,type:i.type,format:i.format}));return{models:e,graphMetrics:t,dialect:n.dialect}}function xb(n){const e=n??{},t=(e.models??[]).map(a=>{const u=(a.dimensions??[]).map(m=>({ref:`${a.name}.${m}`,name:m,model:a.name,label:Le(m),type:gy.test(m)?"time":"categorical"})),f=(a.metrics??[]).map(m=>({ref:`${a.name}.${m}`,name:m,model:a.name,label:Le(m)})),h=vy(u);return{name:a.name,label:Le(a.name),table:a.table,dimensions:u,metrics:f,timeDimension:h,defaultGrain:(h==null?void 0:h.granularity)||"day"}}),i=(e.graph_metrics??[]).map(a=>({ref:a.name,name:a.name,ownerModel:xy(a,t),baseMetric:a.base_metric,label:Le(a.name),type:a.type,description:a.description}));return{models:t,graphMetrics:i,joinablePairs:e.joinable_pairs??[]}}function bb(n,e){return{...n,joinablePairs:(e??{}).joinable_pairs??n.joinablePairs??[]}}function ji(n,e){const t=new Set;for(const i of n.joinablePairs??[])i.from===e&&t.add(i.to),i.to===e&&t.add(i.from);return n.graphMetrics.filter(i=>i.ownerModel?i.ownerModel===e||t.has(i.ownerModel):!0)}function Fe(n,e,t,i){function a(u){return u instanceof t?u:new t(function(f){f(u)})}return new(t||(t=Promise))(function(u,f){function h(v){try{g(i.next(v))}catch(x){f(x)}}function m(v){try{g(i.throw(v))}catch(x){f(x)}}function g(v){v.done?u(v.value):a(v.value).then(h,m)}g((i=i.apply(n,e||[])).next())})}function lm(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ae(n){return this instanceof Ae?(this.v=n,this):new Ae(n)}function qn(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),a,u=[];return a=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),h("next"),h("throw"),h("return",f),a[Symbol.asyncIterator]=function(){return this},a;function f(w){return function(j){return Promise.resolve(j).then(w,x)}}function h(w,j){i[w]&&(a[w]=function(C){return new Promise(function(O,H){u.push([w,C,O,H])>1||m(w,C)})},j&&(a[w]=j(a[w])))}function m(w,j){try{g(i[w](j))}catch(C){b(u[0][3],C)}}function g(w){w.value instanceof Ae?Promise.resolve(w.value.v).then(v,x):b(u[0][2],w)}function v(w){m("next",w)}function x(w){m("throw",w)}function b(w,j){w(j),u.shift(),u.length&&m(u[0][0],u[0][1])}}function fl(n){var e,t;return e={},i("next"),i("throw",function(a){throw a}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(a,u){e[a]=n[a]?function(f){return(t=!t)?{value:Ae(n[a](f)),done:!1}:u?u(f):f}:u}}function xi(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof lm=="function"?lm(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(u){t[u]=n[u]&&function(f){return new Promise(function(h,m){f=n[u](f),a(h,m,f.done,f.value)})}}function a(u,f,h,m){Promise.resolve(m).then(function(g){u({value:g,done:h})},f)}}const wb=new TextDecoder("utf-8"),xd=n=>wb.decode(n),Sb=new TextEncoder,Bd=n=>Sb.encode(n),_b=n=>typeof n=="number",Nb=n=>typeof n=="boolean",Ot=n=>typeof n=="function",En=n=>n!=null&&Object(n)===n,Ao=n=>En(n)&&Ot(n.then),nu=n=>En(n)&&Ot(n[Symbol.iterator]),Ed=n=>En(n)&&Ot(n[Symbol.asyncIterator]),bd=n=>En(n)&&En(n.schema),by=n=>En(n)&&"done"in n&&"value"in n,wy=n=>En(n)&&Ot(n.stat)&&_b(n.fd),Sy=n=>En(n)&&Rd(n.body),_y=n=>"_getDOMStream"in n&&"_getNodeStream"in n,Rd=n=>En(n)&&Ot(n.cancel)&&Ot(n.getReader)&&!_y(n),Ny=n=>En(n)&&Ot(n.read)&&Ot(n.pipe)&&Nb(n.readable)&&!_y(n),jb=n=>En(n)&&Ot(n.clear)&&Ot(n.bytes)&&Ot(n.position)&&Ot(n.setPosition)&&Ot(n.capacity)&&Ot(n.getBufferIdentifier)&&Ot(n.createLong),Ld=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function kb(n){const e=n[0]?[n[0]]:[];let t,i,a,u;for(let f,h,m=0,g=0,v=n.length;++mv+x.byteLength,0);let a,u,f,h=0,m=-1;const g=Math.min(e||Number.POSITIVE_INFINITY,i);for(const v=t.length;++mKe(Int32Array,n),cm=n=>Ke(BigInt64Array,n),$e=n=>Ke(Uint8Array,n),wd=n=>(n.next(),n);function*Ib(n,e){const t=function*(a){yield a},i=typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof Ld?t(e):nu(e)?e:t(e);return yield*wd((function*(a){let u=null;do u=a.next(yield Ke(n,u));while(!u.done)})(i[Symbol.iterator]())),new n}const Mb=n=>Ib(Uint8Array,n);function jy(n,e){return qn(this,arguments,function*(){if(Ao(e))return yield Ae(yield Ae(yield*fl(xi(jy(n,yield Ae(e))))));const i=function(f){return qn(this,arguments,function*(){yield yield Ae(yield Ae(f))})},a=function(f){return qn(this,arguments,function*(){yield Ae(yield*fl(xi(wd((function*(h){let m=null;do m=h.next(yield m==null?void 0:m.value);while(!m.done)})(f[Symbol.iterator]())))))})},u=typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof Ld?i(e):nu(e)?a(e):Ed(e)?e:i(e);return yield Ae(yield*fl(xi(wd((function(f){return qn(this,arguments,function*(){let h=null;do h=yield Ae(f.next(yield yield Ae(Ke(n,h))));while(!h.done)})})(u[Symbol.asyncIterator]()))))),yield Ae(new n)})}const Db=n=>jy(Uint8Array,n);function Cb(n,e){let t=0;const i=n.length;if(i!==e.length)return!1;if(i>0)do if(n[t]!==e[t])return!1;while(++t(n.next(),n);function*Fb(n){let e,t=!1,i=[],a,u,f,h=0;function m(){return u==="peek"?tr(i,f)[0]:([a,i,h]=tr(i,f),a)}({cmd:u,size:f}=(yield null)||{cmd:"read",size:0});const g=Mb(n)[Symbol.iterator]();try{do if({done:e,value:a}=Number.isNaN(f-h)?g.next():g.next(f-h),!e&&a.byteLength>0&&(i.push(a),h+=a.byteLength),e||f<=h)do({cmd:u,size:f}=yield m());while(f0&&(a.push(u),m+=u.byteLength),t||h<=m)do({cmd:f,size:h}=yield yield Ae(g()));while(h0&&(a.push($e(u)),m+=u.byteLength),t||h<=m)do({cmd:f,size:h}=yield yield Ae(g()));while(h{})}get closed(){return this.reader?this.reader.closed.catch(()=>{}):Promise.resolve()}releaseLock(){this.reader&&this.reader.releaseLock(),this.reader=null}cancel(e){return Fe(this,void 0,void 0,function*(){const{reader:t,source:i}=this;t&&(yield t.cancel(e).catch(()=>{})),i&&i.locked&&this.releaseLock()})}read(e){return Fe(this,void 0,void 0,function*(){if(e===0)return{done:this.reader==null,value:new Uint8Array(0)};const t=yield this.reader.read();return!t.done&&(t.value=$e(t)),t})}}const nd=(n,e)=>{const t=a=>i([e,a]);let i;return[e,t,new Promise(a=>(i=a)&&n.once(e,t))]};function Bb(n){return qn(this,arguments,function*(){const t=[];let i="error",a=!1,u=null,f,h,m=0,g=[],v;function x(){return f==="peek"?tr(g,h)[0]:([v,g,m]=tr(g,h),v)}if({cmd:f,size:h}=(yield yield Ae(null))||{cmd:"read",size:0},n.isTTY)return yield yield Ae(new Uint8Array(0)),yield Ae(null);try{t[0]=nd(n,"end"),t[1]=nd(n,"error");do{if(t[2]=nd(n,"readable"),[i,u]=yield Ae(Promise.race(t.map(w=>w[2]))),i==="error")break;if((a=i==="end")||(Number.isFinite(h-m)?(v=$e(n.read(h-m)),v.byteLength0&&(g.push(v),m+=v.byteLength)),a||h<=m)do({cmd:f,size:h}=yield yield Ae(x()));while(h{for(const[H,L]of w)n.off(H,L);try{const H=n.destroy;H&&H.call(n,j),j=void 0}catch(H){j=H||j}finally{j!=null?O(j):C()}})}})}var ht;(function(n){n[n.V1=0]="V1",n[n.V2=1]="V2",n[n.V3=2]="V3",n[n.V4=3]="V4",n[n.V5=4]="V5"})(ht||(ht={}));var Ht;(function(n){n[n.Sparse=0]="Sparse",n[n.Dense=1]="Dense"})(Ht||(Ht={}));var Dt;(function(n){n[n.HALF=0]="HALF",n[n.SINGLE=1]="SINGLE",n[n.DOUBLE=2]="DOUBLE"})(Dt||(Dt={}));var gn;(function(n){n[n.DAY=0]="DAY",n[n.MILLISECOND=1]="MILLISECOND"})(gn||(gn={}));var _e;(function(n){n[n.SECOND=0]="SECOND",n[n.MILLISECOND=1]="MILLISECOND",n[n.MICROSECOND=2]="MICROSECOND",n[n.NANOSECOND=3]="NANOSECOND"})(_e||(_e={}));var nr;(function(n){n[n.YEAR_MONTH=0]="YEAR_MONTH",n[n.DAY_TIME=1]="DAY_TIME",n[n.MONTH_DAY_NANO=2]="MONTH_DAY_NANO"})(nr||(nr={}));const rd=2,Qn=4,br=4,He=4,es=new Int32Array(2),dm=new Float32Array(es.buffer),fm=new Float64Array(es.buffer),rl=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Sd;(function(n){n[n.UTF8_BYTES=1]="UTF8_BYTES",n[n.UTF16_STRING=2]="UTF16_STRING"})(Sd||(Sd={}));let ki=class ky{constructor(e){this.bytes_=e,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(e){return new ky(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return BigInt.asIntN(64,BigInt(this.readUint32(e))+(BigInt(this.readUint32(e+4))<>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,Number(BigInt.asIntN(32,t))),this.writeInt32(e+4,Number(BigInt.asIntN(32,t>>BigInt(32))))}writeUint64(e,t){this.writeUint32(e,Number(BigInt.asUintN(32,t))),this.writeUint32(e+4,Number(BigInt.asUintN(32,t>>BigInt(32))))}writeFloat32(e,t){dm[0]=t,this.writeInt32(e,es[0])}writeFloat64(e,t){fm[0]=t,this.writeInt32(e,es[rl?0:1]),this.writeInt32(e+4,es[rl?1:0])}getBufferIdentifier(){if(this.bytes_.lengththis.minalign&&(this.minalign=e);const i=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space=0&&this.vtable[t]==0;t--);const i=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);const a=2;this.addInt16(e-this.object_start);const u=(i+a)*rd;this.addInt16(u);let f=0;const h=this.space;e:for(t=0;t=0;f--)this.writeInt8(u.charCodeAt(f))}this.prep(this.minalign,Qn+a),this.addOffset(e),a&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){const i=this.bb.capacity()-e,a=i-this.bb.readInt32(i);if(!(t=0;i--)e.addInt32(t[i]);return e.endVector()}static startTypeIdsVector(e,t){e.startVector(4,t,4)}static endUnion(e){return e.endObject()}static createUnion(e,t,i){return Vt.startUnion(e),Vt.addMode(e,t),Vt.addTypeIds(e,i),Vt.endUnion(e)}}let xm=class Fo{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsUtf8(e,t){return(t||new Fo).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsUtf8(e,t){return e.setPosition(e.position()+He),(t||new Fo).__init(e.readInt32(e.position())+e.position(),e)}static startUtf8(e){e.startObject(0)}static endUtf8(e){return e.endObject()}static createUtf8(e){return Fo.startUtf8(e),Fo.endUtf8(e)}};var Ze;(function(n){n[n.NONE=0]="NONE",n[n.Null=1]="Null",n[n.Int=2]="Int",n[n.FloatingPoint=3]="FloatingPoint",n[n.Binary=4]="Binary",n[n.Utf8=5]="Utf8",n[n.Bool=6]="Bool",n[n.Decimal=7]="Decimal",n[n.Date=8]="Date",n[n.Time=9]="Time",n[n.Timestamp=10]="Timestamp",n[n.Interval=11]="Interval",n[n.List=12]="List",n[n.Struct_=13]="Struct_",n[n.Union=14]="Union",n[n.FixedSizeBinary=15]="FixedSizeBinary",n[n.FixedSizeList=16]="FixedSizeList",n[n.Map=17]="Map",n[n.Duration=18]="Duration",n[n.LargeBinary=19]="LargeBinary",n[n.LargeUtf8=20]="LargeUtf8",n[n.LargeList=21]="LargeList",n[n.RunEndEncoded=22]="RunEndEncoded"})(Ze||(Ze={}));let dn=class vl{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsField(e,t){return(t||new vl).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsField(e,t){return e.setPosition(e.position()+He),(t||new vl).__init(e.readInt32(e.position())+e.position(),e)}name(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}nullable(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}typeType(){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readUint8(this.bb_pos+e):Ze.NONE}type(e){const t=this.bb.__offset(this.bb_pos,10);return t?this.bb.__union(e,this.bb_pos+t):null}dictionary(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new wr).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}children(e,t){const i=this.bb.__offset(this.bb_pos,14);return i?(t||new vl).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}childrenLength(){const e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,16);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__vector_len(this.bb_pos+e):0}static startField(e){e.startObject(7)}static addName(e,t){e.addFieldOffset(0,t,0)}static addNullable(e,t){e.addFieldInt8(1,+t,0)}static addTypeType(e,t){e.addFieldInt8(2,t,Ze.NONE)}static addType(e,t){e.addFieldOffset(3,t,0)}static addDictionary(e,t){e.addFieldOffset(4,t,0)}static addChildren(e,t){e.addFieldOffset(5,t,0)}static createChildrenVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startChildrenVector(e,t){e.startVector(4,t,4)}static addCustomMetadata(e,t){e.addFieldOffset(6,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endField(e){return e.endObject()}},Gn=class mr{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSchema(e,t){return(t||new mr).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSchema(e,t){return e.setPosition(e.position()+He),(t||new mr).__init(e.readInt32(e.position())+e.position(),e)}endianness(){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):Ii.Little}fields(e,t){const i=this.bb.__offset(this.bb_pos,6);return i?(t||new dn).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}fieldsLength(){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,8);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}features(e){const t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+e*8):BigInt(0)}featuresLength(){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__vector_len(this.bb_pos+e):0}static startSchema(e){e.startObject(4)}static addEndianness(e,t){e.addFieldInt16(0,t,Ii.Little)}static addFields(e,t){e.addFieldOffset(1,t,0)}static createFieldsVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startFieldsVector(e,t){e.startVector(4,t,4)}static addCustomMetadata(e,t){e.addFieldOffset(2,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static addFeatures(e,t){e.addFieldOffset(3,t,0)}static createFeaturesVector(e,t){e.startVector(8,t.length,8);for(let i=t.length-1;i>=0;i--)e.addInt64(t[i]);return e.endVector()}static startFeaturesVector(e,t){e.startVector(8,t,8)}static endSchema(e){return e.endObject()}static finishSchemaBuffer(e,t){e.finish(t)}static finishSizePrefixedSchemaBuffer(e,t){e.finish(t,void 0,!0)}static createSchema(e,t,i,a,u){return mr.startSchema(e),mr.addEndianness(e,t),mr.addFields(e,i),mr.addCustomMetadata(e,a),mr.addFeatures(e,u),mr.endSchema(e)}};var Ve;(function(n){n[n.NONE=0]="NONE",n[n.Schema=1]="Schema",n[n.DictionaryBatch=2]="DictionaryBatch",n[n.RecordBatch=3]="RecordBatch",n[n.Tensor=4]="Tensor",n[n.SparseTensor=5]="SparseTensor"})(Ve||(Ve={}));var M;(function(n){n[n.NONE=0]="NONE",n[n.Null=1]="Null",n[n.Int=2]="Int",n[n.Float=3]="Float",n[n.Binary=4]="Binary",n[n.Utf8=5]="Utf8",n[n.Bool=6]="Bool",n[n.Decimal=7]="Decimal",n[n.Date=8]="Date",n[n.Time=9]="Time",n[n.Timestamp=10]="Timestamp",n[n.Interval=11]="Interval",n[n.List=12]="List",n[n.Struct=13]="Struct",n[n.Union=14]="Union",n[n.FixedSizeBinary=15]="FixedSizeBinary",n[n.FixedSizeList=16]="FixedSizeList",n[n.Map=17]="Map",n[n.Duration=18]="Duration",n[n.LargeBinary=19]="LargeBinary",n[n.LargeUtf8=20]="LargeUtf8",n[n.Dictionary=-1]="Dictionary",n[n.Int8=-2]="Int8",n[n.Int16=-3]="Int16",n[n.Int32=-4]="Int32",n[n.Int64=-5]="Int64",n[n.Uint8=-6]="Uint8",n[n.Uint16=-7]="Uint16",n[n.Uint32=-8]="Uint32",n[n.Uint64=-9]="Uint64",n[n.Float16=-10]="Float16",n[n.Float32=-11]="Float32",n[n.Float64=-12]="Float64",n[n.DateDay=-13]="DateDay",n[n.DateMillisecond=-14]="DateMillisecond",n[n.TimestampSecond=-15]="TimestampSecond",n[n.TimestampMillisecond=-16]="TimestampMillisecond",n[n.TimestampMicrosecond=-17]="TimestampMicrosecond",n[n.TimestampNanosecond=-18]="TimestampNanosecond",n[n.TimeSecond=-19]="TimeSecond",n[n.TimeMillisecond=-20]="TimeMillisecond",n[n.TimeMicrosecond=-21]="TimeMicrosecond",n[n.TimeNanosecond=-22]="TimeNanosecond",n[n.DenseUnion=-23]="DenseUnion",n[n.SparseUnion=-24]="SparseUnion",n[n.IntervalDayTime=-25]="IntervalDayTime",n[n.IntervalYearMonth=-26]="IntervalYearMonth",n[n.DurationSecond=-27]="DurationSecond",n[n.DurationMillisecond=-28]="DurationMillisecond",n[n.DurationMicrosecond=-29]="DurationMicrosecond",n[n.DurationNanosecond=-30]="DurationNanosecond"})(M||(M={}));var gr;(function(n){n[n.OFFSET=0]="OFFSET",n[n.DATA=1]="DATA",n[n.VALIDITY=2]="VALIDITY",n[n.TYPE=3]="TYPE"})(gr||(gr={}));const Eb=void 0;function Bo(n){if(n===null)return"null";if(n===Eb)return"undefined";switch(typeof n){case"number":return`${n}`;case"bigint":return`${n}`;case"string":return`"${n}"`}return typeof n[Symbol.toPrimitive]=="function"?n[Symbol.toPrimitive]("string"):ArrayBuffer.isView(n)?n instanceof BigInt64Array||n instanceof BigUint64Array?`[${[...n].map(e=>Bo(e))}]`:`[${n}]`:ArrayBuffer.isView(n)?`[${n}]`:JSON.stringify(n,(e,t)=>typeof t=="bigint"?`${t}`:t)}function tt(n){if(typeof n=="bigint"&&(nNumber.MAX_SAFE_INTEGER))throw new TypeError(`${n} is not safe to convert to a number.`);return Number(n)}function Fy(n,e){return tt(n/e)+tt(n%e)/tt(e)}const Rb=Symbol.for("isArrowBigNum");function Ln(n,...e){return e.length===0?Object.setPrototypeOf(Ke(this.TypedArray,n),this.constructor.prototype):Object.setPrototypeOf(new this.TypedArray(n,...e),this.constructor.prototype)}Ln.prototype[Rb]=!0;Ln.prototype.toJSON=function(){return`"${Ro(this)}"`};Ln.prototype.valueOf=function(n){return Oy(this,n)};Ln.prototype.toString=function(){return Ro(this)};Ln.prototype[Symbol.toPrimitive]=function(n="default"){switch(n){case"number":return Oy(this);case"string":return Ro(this);case"default":return $b(this)}return Ro(this)};function bi(...n){return Ln.apply(this,n)}function wi(...n){return Ln.apply(this,n)}function Eo(...n){return Ln.apply(this,n)}Object.setPrototypeOf(bi.prototype,Object.create(Int32Array.prototype));Object.setPrototypeOf(wi.prototype,Object.create(Uint32Array.prototype));Object.setPrototypeOf(Eo.prototype,Object.create(Uint32Array.prototype));Object.assign(bi.prototype,Ln.prototype,{constructor:bi,signed:!0,TypedArray:Int32Array,BigIntArray:BigInt64Array});Object.assign(wi.prototype,Ln.prototype,{constructor:wi,signed:!1,TypedArray:Uint32Array,BigIntArray:BigUint64Array});Object.assign(Eo.prototype,Ln.prototype,{constructor:Eo,signed:!0,TypedArray:Uint32Array,BigIntArray:BigUint64Array});const Lb=BigInt(4294967296)*BigInt(4294967296),Ub=Lb-BigInt(1);function Oy(n,e){const{buffer:t,byteOffset:i,byteLength:a,signed:u}=n,f=new BigUint64Array(t,i,a/8),h=u&&f.at(-1)&BigInt(1)<=0)return sd(n);e=e.slice();let i=1;for(let u=0;u(n.children=null,n.ArrayType=Array,n.OffsetArrayType=Int32Array,n[Symbol.toStringTag]="DataType"))(me.prototype);class ss extends me{constructor(){super(M.Null)}toString(){return"Null"}}Ay=Symbol.toStringTag;ss[Ay]=(n=>n[Symbol.toStringTag]="Null")(ss.prototype);class Ds extends me{constructor(e,t){super(M.Int),this.isSigned=e,this.bitWidth=t}get ArrayType(){switch(this.bitWidth){case 8:return this.isSigned?Int8Array:Uint8Array;case 16:return this.isSigned?Int16Array:Uint16Array;case 32:return this.isSigned?Int32Array:Uint32Array;case 64:return this.isSigned?BigInt64Array:BigUint64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`${this.isSigned?"I":"Ui"}nt${this.bitWidth}`}}By=Symbol.toStringTag;Ds[By]=(n=>(n.isSigned=null,n.bitWidth=null,n[Symbol.toStringTag]="Int"))(Ds.prototype);class Lo extends Ds{constructor(){super(!0,32)}get ArrayType(){return Int32Array}}Object.defineProperty(Lo.prototype,"ArrayType",{value:Int32Array});class jl extends me{constructor(e){super(M.Float),this.precision=e}get ArrayType(){switch(this.precision){case Dt.HALF:return Uint16Array;case Dt.SINGLE:return Float32Array;case Dt.DOUBLE:return Float64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`Float${this.precision<<5||16}`}}Ey=Symbol.toStringTag;jl[Ey]=(n=>(n.precision=null,n[Symbol.toStringTag]="Float"))(jl.prototype);class kl extends me{constructor(){super(M.Binary)}toString(){return"Binary"}}Ry=Symbol.toStringTag;kl[Ry]=(n=>(n.ArrayType=Uint8Array,n[Symbol.toStringTag]="Binary"))(kl.prototype);class Il extends me{constructor(){super(M.LargeBinary)}toString(){return"LargeBinary"}}Ly=Symbol.toStringTag;Il[Ly]=(n=>(n.ArrayType=Uint8Array,n.OffsetArrayType=BigInt64Array,n[Symbol.toStringTag]="LargeBinary"))(Il.prototype);class Ml extends me{constructor(){super(M.Utf8)}toString(){return"Utf8"}}Uy=Symbol.toStringTag;Ml[Uy]=(n=>(n.ArrayType=Uint8Array,n[Symbol.toStringTag]="Utf8"))(Ml.prototype);class Dl extends me{constructor(){super(M.LargeUtf8)}toString(){return"LargeUtf8"}}$y=Symbol.toStringTag;Dl[$y]=(n=>(n.ArrayType=Uint8Array,n.OffsetArrayType=BigInt64Array,n[Symbol.toStringTag]="LargeUtf8"))(Dl.prototype);class Cl extends me{constructor(){super(M.Bool)}toString(){return"Bool"}}Py=Symbol.toStringTag;Cl[Py]=(n=>(n.ArrayType=Uint8Array,n[Symbol.toStringTag]="Bool"))(Cl.prototype);class Fl extends me{constructor(e,t,i=128){super(M.Decimal),this.scale=e,this.precision=t,this.bitWidth=i}toString(){return`Decimal[${this.precision}e${this.scale>0?"+":""}${this.scale}]`}}zy=Symbol.toStringTag;Fl[zy]=(n=>(n.scale=null,n.precision=null,n.ArrayType=Uint32Array,n[Symbol.toStringTag]="Decimal"))(Fl.prototype);class Ol extends me{constructor(e){super(M.Date),this.unit=e}toString(){return`Date${(this.unit+1)*32}<${gn[this.unit]}>`}get ArrayType(){return this.unit===gn.DAY?Int32Array:BigInt64Array}}Vy=Symbol.toStringTag;Ol[Vy]=(n=>(n.unit=null,n[Symbol.toStringTag]="Date"))(Ol.prototype);class Tl extends me{constructor(e,t){super(M.Time),this.unit=e,this.bitWidth=t}toString(){return`Time${this.bitWidth}<${_e[this.unit]}>`}get ArrayType(){switch(this.bitWidth){case 32:return Int32Array;case 64:return BigInt64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}}Wy=Symbol.toStringTag;Tl[Wy]=(n=>(n.unit=null,n.bitWidth=null,n[Symbol.toStringTag]="Time"))(Tl.prototype);class Al extends me{constructor(e,t){super(M.Timestamp),this.unit=e,this.timezone=t}toString(){return`Timestamp<${_e[this.unit]}${this.timezone?`, ${this.timezone}`:""}>`}}Hy=Symbol.toStringTag;Al[Hy]=(n=>(n.unit=null,n.timezone=null,n.ArrayType=BigInt64Array,n[Symbol.toStringTag]="Timestamp"))(Al.prototype);class Bl extends me{constructor(e){super(M.Interval),this.unit=e}toString(){return`Interval<${nr[this.unit]}>`}}Gy=Symbol.toStringTag;Bl[Gy]=(n=>(n.unit=null,n.ArrayType=Int32Array,n[Symbol.toStringTag]="Interval"))(Bl.prototype);class El extends me{constructor(e){super(M.Duration),this.unit=e}toString(){return`Duration<${_e[this.unit]}>`}}Yy=Symbol.toStringTag;El[Yy]=(n=>(n.unit=null,n.ArrayType=BigInt64Array,n[Symbol.toStringTag]="Duration"))(El.prototype);class Rl extends me{constructor(e){super(M.List),this.children=[e]}toString(){return`List<${this.valueType}>`}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}}Qy=Symbol.toStringTag;Rl[Qy]=(n=>(n.children=null,n[Symbol.toStringTag]="List"))(Rl.prototype);class Tt extends me{constructor(e){super(M.Struct),this.children=e}toString(){return`Struct<{${this.children.map(e=>`${e.name}:${e.type}`).join(", ")}}>`}}Ky=Symbol.toStringTag;Tt[Ky]=(n=>(n.children=null,n[Symbol.toStringTag]="Struct"))(Tt.prototype);class Ll extends me{constructor(e,t,i){super(M.Union),this.mode=e,this.children=i,this.typeIds=t=Int32Array.from(t),this.typeIdToChildIndex=t.reduce((a,u,f)=>(a[u]=f)&&a||a,Object.create(null))}toString(){return`${this[Symbol.toStringTag]}<${this.children.map(e=>`${e.type}`).join(" | ")}>`}}Jy=Symbol.toStringTag;Ll[Jy]=(n=>(n.mode=null,n.typeIds=null,n.children=null,n.typeIdToChildIndex=null,n.ArrayType=Int8Array,n[Symbol.toStringTag]="Union"))(Ll.prototype);class Ul extends me{constructor(e){super(M.FixedSizeBinary),this.byteWidth=e}toString(){return`FixedSizeBinary[${this.byteWidth}]`}}qy=Symbol.toStringTag;Ul[qy]=(n=>(n.byteWidth=null,n.ArrayType=Uint8Array,n[Symbol.toStringTag]="FixedSizeBinary"))(Ul.prototype);class $l extends me{constructor(e,t){super(M.FixedSizeList),this.listSize=e,this.children=[t]}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}toString(){return`FixedSizeList[${this.listSize}]<${this.valueType}>`}}Zy=Symbol.toStringTag;$l[Zy]=(n=>(n.children=null,n.listSize=null,n[Symbol.toStringTag]="FixedSizeList"))($l.prototype);class Pl extends me{constructor(e,t=!1){var i,a,u;if(super(M.Map),this.children=[e],this.keysSorted=t,e&&(e.name="entries",!((i=e==null?void 0:e.type)===null||i===void 0)&&i.children)){const f=(a=e==null?void 0:e.type)===null||a===void 0?void 0:a.children[0];f&&(f.name="key");const h=(u=e==null?void 0:e.type)===null||u===void 0?void 0:u.children[1];h&&(h.name="value")}}get keyType(){return this.children[0].type.children[0].type}get valueType(){return this.children[0].type.children[1].type}get childType(){return this.children[0].type}toString(){return`Map<{${this.children[0].type.children.map(e=>`${e.name}:${e.type}`).join(", ")}}>`}}Xy=Symbol.toStringTag;Pl[Xy]=(n=>(n.children=null,n.keysSorted=null,n[Symbol.toStringTag]="Map_"))(Pl.prototype);const Pb=(n=>()=>++n)(-1);class Mi extends me{constructor(e,t,i,a){super(M.Dictionary),this.indices=t,this.dictionary=e,this.isOrdered=a||!1,this.id=i==null?Pb():tt(i)}get children(){return this.dictionary.children}get valueType(){return this.dictionary}get ArrayType(){return this.dictionary.ArrayType}toString(){return`Dictionary<${this.indices}, ${this.dictionary}>`}}eg=Symbol.toStringTag;Mi[eg]=(n=>(n.id=null,n.indices=null,n.isOrdered=null,n.dictionary=null,n[Symbol.toStringTag]="Dictionary"))(Mi.prototype);function vr(n){const e=n;switch(n.typeId){case M.Decimal:return n.bitWidth/32;case M.Interval:return 1+e.unit;case M.FixedSizeList:return e.listSize;case M.FixedSizeBinary:return e.byteWidth;default:return 1}}class Re{visitMany(e,...t){return e.map((i,a)=>this.visit(i,...t.map(u=>u[a])))}visit(...e){return this.getVisitFn(e[0],!1).apply(this,e)}getVisitFn(e,t=!0){return zb(this,e,t)}getVisitFnByTypeId(e,t=!0){return mi(this,e,t)}visitNull(e,...t){return null}visitBool(e,...t){return null}visitInt(e,...t){return null}visitFloat(e,...t){return null}visitUtf8(e,...t){return null}visitLargeUtf8(e,...t){return null}visitBinary(e,...t){return null}visitLargeBinary(e,...t){return null}visitFixedSizeBinary(e,...t){return null}visitDate(e,...t){return null}visitTimestamp(e,...t){return null}visitTime(e,...t){return null}visitDecimal(e,...t){return null}visitList(e,...t){return null}visitStruct(e,...t){return null}visitUnion(e,...t){return null}visitDictionary(e,...t){return null}visitInterval(e,...t){return null}visitDuration(e,...t){return null}visitFixedSizeList(e,...t){return null}visitMap(e,...t){return null}}function zb(n,e,t=!0){return typeof e=="number"?mi(n,e,t):typeof e=="string"&&e in M?mi(n,M[e],t):e&&e instanceof me?mi(n,bm(e),t):e!=null&&e.type&&e.type instanceof me?mi(n,bm(e.type),t):mi(n,M.NONE,t)}function mi(n,e,t=!0){let i=null;switch(e){case M.Null:i=n.visitNull;break;case M.Bool:i=n.visitBool;break;case M.Int:i=n.visitInt;break;case M.Int8:i=n.visitInt8||n.visitInt;break;case M.Int16:i=n.visitInt16||n.visitInt;break;case M.Int32:i=n.visitInt32||n.visitInt;break;case M.Int64:i=n.visitInt64||n.visitInt;break;case M.Uint8:i=n.visitUint8||n.visitInt;break;case M.Uint16:i=n.visitUint16||n.visitInt;break;case M.Uint32:i=n.visitUint32||n.visitInt;break;case M.Uint64:i=n.visitUint64||n.visitInt;break;case M.Float:i=n.visitFloat;break;case M.Float16:i=n.visitFloat16||n.visitFloat;break;case M.Float32:i=n.visitFloat32||n.visitFloat;break;case M.Float64:i=n.visitFloat64||n.visitFloat;break;case M.Utf8:i=n.visitUtf8;break;case M.LargeUtf8:i=n.visitLargeUtf8;break;case M.Binary:i=n.visitBinary;break;case M.LargeBinary:i=n.visitLargeBinary;break;case M.FixedSizeBinary:i=n.visitFixedSizeBinary;break;case M.Date:i=n.visitDate;break;case M.DateDay:i=n.visitDateDay||n.visitDate;break;case M.DateMillisecond:i=n.visitDateMillisecond||n.visitDate;break;case M.Timestamp:i=n.visitTimestamp;break;case M.TimestampSecond:i=n.visitTimestampSecond||n.visitTimestamp;break;case M.TimestampMillisecond:i=n.visitTimestampMillisecond||n.visitTimestamp;break;case M.TimestampMicrosecond:i=n.visitTimestampMicrosecond||n.visitTimestamp;break;case M.TimestampNanosecond:i=n.visitTimestampNanosecond||n.visitTimestamp;break;case M.Time:i=n.visitTime;break;case M.TimeSecond:i=n.visitTimeSecond||n.visitTime;break;case M.TimeMillisecond:i=n.visitTimeMillisecond||n.visitTime;break;case M.TimeMicrosecond:i=n.visitTimeMicrosecond||n.visitTime;break;case M.TimeNanosecond:i=n.visitTimeNanosecond||n.visitTime;break;case M.Decimal:i=n.visitDecimal;break;case M.List:i=n.visitList;break;case M.Struct:i=n.visitStruct;break;case M.Union:i=n.visitUnion;break;case M.DenseUnion:i=n.visitDenseUnion||n.visitUnion;break;case M.SparseUnion:i=n.visitSparseUnion||n.visitUnion;break;case M.Dictionary:i=n.visitDictionary;break;case M.Interval:i=n.visitInterval;break;case M.IntervalDayTime:i=n.visitIntervalDayTime||n.visitInterval;break;case M.IntervalYearMonth:i=n.visitIntervalYearMonth||n.visitInterval;break;case M.Duration:i=n.visitDuration;break;case M.DurationSecond:i=n.visitDurationSecond||n.visitDuration;break;case M.DurationMillisecond:i=n.visitDurationMillisecond||n.visitDuration;break;case M.DurationMicrosecond:i=n.visitDurationMicrosecond||n.visitDuration;break;case M.DurationNanosecond:i=n.visitDurationNanosecond||n.visitDuration;break;case M.FixedSizeList:i=n.visitFixedSizeList;break;case M.Map:i=n.visitMap;break}if(typeof i=="function")return i;if(!t)return()=>null;throw new Error(`Unrecognized type '${M[e]}'`)}function bm(n){switch(n.typeId){case M.Null:return M.Null;case M.Int:{const{bitWidth:e,isSigned:t}=n;switch(e){case 8:return t?M.Int8:M.Uint8;case 16:return t?M.Int16:M.Uint16;case 32:return t?M.Int32:M.Uint32;case 64:return t?M.Int64:M.Uint64}return M.Int}case M.Float:switch(n.precision){case Dt.HALF:return M.Float16;case Dt.SINGLE:return M.Float32;case Dt.DOUBLE:return M.Float64}return M.Float;case M.Binary:return M.Binary;case M.LargeBinary:return M.LargeBinary;case M.Utf8:return M.Utf8;case M.LargeUtf8:return M.LargeUtf8;case M.Bool:return M.Bool;case M.Decimal:return M.Decimal;case M.Time:switch(n.unit){case _e.SECOND:return M.TimeSecond;case _e.MILLISECOND:return M.TimeMillisecond;case _e.MICROSECOND:return M.TimeMicrosecond;case _e.NANOSECOND:return M.TimeNanosecond}return M.Time;case M.Timestamp:switch(n.unit){case _e.SECOND:return M.TimestampSecond;case _e.MILLISECOND:return M.TimestampMillisecond;case _e.MICROSECOND:return M.TimestampMicrosecond;case _e.NANOSECOND:return M.TimestampNanosecond}return M.Timestamp;case M.Date:switch(n.unit){case gn.DAY:return M.DateDay;case gn.MILLISECOND:return M.DateMillisecond}return M.Date;case M.Interval:switch(n.unit){case nr.DAY_TIME:return M.IntervalDayTime;case nr.YEAR_MONTH:return M.IntervalYearMonth}return M.Interval;case M.Duration:switch(n.unit){case _e.SECOND:return M.DurationSecond;case _e.MILLISECOND:return M.DurationMillisecond;case _e.MICROSECOND:return M.DurationMicrosecond;case _e.NANOSECOND:return M.DurationNanosecond}return M.Duration;case M.Map:return M.Map;case M.List:return M.List;case M.Struct:return M.Struct;case M.Union:switch(n.mode){case Ht.Dense:return M.DenseUnion;case Ht.Sparse:return M.SparseUnion}return M.Union;case M.FixedSizeBinary:return M.FixedSizeBinary;case M.FixedSizeList:return M.FixedSizeList;case M.Dictionary:return M.Dictionary}throw new Error(`Unrecognized type '${M[n.typeId]}'`)}Re.prototype.visitInt8=null;Re.prototype.visitInt16=null;Re.prototype.visitInt32=null;Re.prototype.visitInt64=null;Re.prototype.visitUint8=null;Re.prototype.visitUint16=null;Re.prototype.visitUint32=null;Re.prototype.visitUint64=null;Re.prototype.visitFloat16=null;Re.prototype.visitFloat32=null;Re.prototype.visitFloat64=null;Re.prototype.visitDateDay=null;Re.prototype.visitDateMillisecond=null;Re.prototype.visitTimestampSecond=null;Re.prototype.visitTimestampMillisecond=null;Re.prototype.visitTimestampMicrosecond=null;Re.prototype.visitTimestampNanosecond=null;Re.prototype.visitTimeSecond=null;Re.prototype.visitTimeMillisecond=null;Re.prototype.visitTimeMicrosecond=null;Re.prototype.visitTimeNanosecond=null;Re.prototype.visitDenseUnion=null;Re.prototype.visitSparseUnion=null;Re.prototype.visitIntervalDayTime=null;Re.prototype.visitIntervalYearMonth=null;Re.prototype.visitDuration=null;Re.prototype.visitDurationSecond=null;Re.prototype.visitDurationMillisecond=null;Re.prototype.visitDurationMicrosecond=null;Re.prototype.visitDurationNanosecond=null;const tg=new Float64Array(1),ai=new Uint32Array(tg.buffer);function ng(n){const e=(n&31744)>>10,t=(n&1023)/1024,i=Math.pow(-1,(n&32768)>>15);switch(e){case 31:return i*(t?Number.NaN:1/0);case 0:return i*(t?6103515625e-14*t:0)}return i*Math.pow(2,e-15)*(1+t)}function Vb(n){if(n!==n)return 32256;tg[0]=n;const e=(ai[1]&2147483648)>>16&65535;let t=ai[1]&2146435072,i=0;return t>=1089470464?ai[0]>0?t=31744:(t=(t&2080374784)>>16,i=(ai[1]&1048575)>>10):t<=1056964608?(i=1048576+(ai[1]&1048575),i=1048576+(i<<(t>>20)-998)>>21,t=0):(t=t-1056964608>>10,i=(ai[1]&1048575)+512>>10),e|t|i&65535}class Ne extends Re{}function Ie(n){return(e,t,i)=>{if(e.setValid(t,i!=null))return n(e,t,i)}}const Wb=(n,e,t)=>{n[e]=Math.floor(t/864e5)},rg=(n,e,t,i)=>{if(t+1{const a=n+t;i?e[a>>3]|=1<>3]&=~(1<{n[e]=t},$d=({values:n},e,t)=>{n[e]=t},sg=({values:n},e,t)=>{n[e]=Vb(t)},Gb=(n,e,t)=>{switch(n.type.precision){case Dt.HALF:return sg(n,e,t);case Dt.SINGLE:case Dt.DOUBLE:return $d(n,e,t)}},ig=({values:n},e,t)=>{Wb(n,e,t.valueOf())},og=({values:n},e,t)=>{n[e]=BigInt(t)},Yb=({stride:n,values:e},t,i)=>{e.set(i.subarray(0,n),n*t)},ag=({values:n,valueOffsets:e},t,i)=>rg(n,e,t,i),lg=({values:n,valueOffsets:e},t,i)=>rg(n,e,t,Bd(i)),Qb=(n,e,t)=>{n.type.unit===gn.DAY?ig(n,e,t):og(n,e,t)},ug=({values:n},e,t)=>{n[e]=BigInt(t/1e3)},cg=({values:n},e,t)=>{n[e]=BigInt(t)},dg=({values:n},e,t)=>{n[e]=BigInt(t*1e3)},fg=({values:n},e,t)=>{n[e]=BigInt(t*1e6)},Kb=(n,e,t)=>{switch(n.type.unit){case _e.SECOND:return ug(n,e,t);case _e.MILLISECOND:return cg(n,e,t);case _e.MICROSECOND:return dg(n,e,t);case _e.NANOSECOND:return fg(n,e,t)}},hg=({values:n},e,t)=>{n[e]=t},pg=({values:n},e,t)=>{n[e]=t},mg=({values:n},e,t)=>{n[e]=t},yg=({values:n},e,t)=>{n[e]=t},Jb=(n,e,t)=>{switch(n.type.unit){case _e.SECOND:return hg(n,e,t);case _e.MILLISECOND:return pg(n,e,t);case _e.MICROSECOND:return mg(n,e,t);case _e.NANOSECOND:return yg(n,e,t)}},qb=({values:n,stride:e},t,i)=>{n.set(i.subarray(0,e),e*t)},Zb=(n,e,t)=>{const i=n.children[0],a=n.valueOffsets,u=vn.getVisitFn(i);if(Array.isArray(t))for(let f=-1,h=a[e],m=a[e+1];h{const i=n.children[0],{valueOffsets:a}=n,u=vn.getVisitFn(i);let{[e]:f,[e+1]:h}=a;const m=t instanceof Map?t.entries():Object.entries(t);for(const g of m)if(u(i,f,g),++f>=h)break},ew=(n,e)=>(t,i,a,u)=>i&&t(i,n,e[u]),tw=(n,e)=>(t,i,a,u)=>i&&t(i,n,e.get(u)),nw=(n,e)=>(t,i,a,u)=>i&&t(i,n,e.get(a.name)),rw=(n,e)=>(t,i,a,u)=>i&&t(i,n,e[a.name]),sw=(n,e,t)=>{const i=n.type.children.map(u=>vn.getVisitFn(u.type)),a=t instanceof Map?nw(e,t):t instanceof Je?tw(e,t):Array.isArray(t)?ew(e,t):rw(e,t);n.type.children.forEach((u,f)=>a(i[f],n.children[f],u,f))},iw=(n,e,t)=>{n.type.mode===Ht.Dense?gg(n,e,t):vg(n,e,t)},gg=(n,e,t)=>{const i=n.type.typeIdToChildIndex[n.typeIds[e]],a=n.children[i];vn.visit(a,n.valueOffsets[e],t)},vg=(n,e,t)=>{const i=n.type.typeIdToChildIndex[n.typeIds[e]],a=n.children[i];vn.visit(a,e,t)},ow=(n,e,t)=>{var i;(i=n.dictionary)===null||i===void 0||i.set(n.values[e],t)},aw=(n,e,t)=>{n.type.unit===nr.DAY_TIME?xg(n,e,t):bg(n,e,t)},xg=({values:n},e,t)=>{n.set(t.subarray(0,2),2*e)},bg=({values:n},e,t)=>{n[e]=t[0]*12+t[1]%12},wg=({values:n},e,t)=>{n[e]=t},Sg=({values:n},e,t)=>{n[e]=t},_g=({values:n},e,t)=>{n[e]=t},Ng=({values:n},e,t)=>{n[e]=t},lw=(n,e,t)=>{switch(n.type.unit){case _e.SECOND:return wg(n,e,t);case _e.MILLISECOND:return Sg(n,e,t);case _e.MICROSECOND:return _g(n,e,t);case _e.NANOSECOND:return Ng(n,e,t)}},uw=(n,e,t)=>{const{stride:i}=n,a=n.children[0],u=vn.getVisitFn(a);if(Array.isArray(t))for(let f=-1,h=e*i;++f`${Bo(e)}: ${Bo(t)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}[Symbol.iterator](){return new cw(this[On],this[Si])}}class cw{constructor(e,t){this.childIndex=0,this.children=e.children,this.rowIndex=t,this.childFields=e.type.children,this.numChildren=this.childFields.length}[Symbol.iterator](){return this}next(){const e=this.childIndex;return et.name)}has(e,t){return e[On].type.children.findIndex(i=>i.name===t)!==-1}getOwnPropertyDescriptor(e,t){if(e[On].type.children.findIndex(i=>i.name===t)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(e,t){if(Reflect.has(e,t))return e[t];const i=e[On].type.children.findIndex(a=>a.name===t);if(i!==-1){const a=Gt.visit(e[On].children[i],e[Si]);return Reflect.set(e,t,a),a}}set(e,t,i){const a=e[On].type.children.findIndex(u=>u.name===t);return a!==-1?(vn.visit(e[On].children[a],e[Si],i),Reflect.set(e,t,i)):Reflect.has(e,t)||typeof t=="symbol"?Reflect.set(e,t,i):!1}}class ve extends Re{}function je(n){return(e,t)=>e.getValid(t)?n(e,t):null}const fw=(n,e)=>864e5*n[e],hw=(n,e)=>null,jg=(n,e,t)=>{if(t+1>=e.length)return null;const i=tt(e[t]),a=tt(e[t+1]);return n.subarray(i,a)},pw=({offset:n,values:e},t)=>{const i=n+t;return(e[i>>3]&1<fw(n,e),Ig=({values:n},e)=>tt(n[e]),as=({stride:n,values:e},t)=>e[n*t],mw=({stride:n,values:e},t)=>ng(e[n*t]),Mg=({values:n},e)=>n[e],yw=({stride:n,values:e},t)=>e.subarray(n*t,n*(t+1)),Dg=({values:n,valueOffsets:e},t)=>jg(n,e,t),Cg=({values:n,valueOffsets:e},t)=>{const i=jg(n,e,t);return i!==null?xd(i):null},gw=({values:n},e)=>n[e],vw=({type:n,values:e},t)=>n.precision!==Dt.HALF?e[t]:ng(e[t]),xw=(n,e)=>n.type.unit===gn.DAY?kg(n,e):Ig(n,e),Fg=({values:n},e)=>1e3*tt(n[e]),Og=({values:n},e)=>tt(n[e]),Tg=({values:n},e)=>Fy(n[e],BigInt(1e3)),Ag=({values:n},e)=>Fy(n[e],BigInt(1e6)),bw=(n,e)=>{switch(n.type.unit){case _e.SECOND:return Fg(n,e);case _e.MILLISECOND:return Og(n,e);case _e.MICROSECOND:return Tg(n,e);case _e.NANOSECOND:return Ag(n,e)}},Bg=({values:n},e)=>n[e],Eg=({values:n},e)=>n[e],Rg=({values:n},e)=>n[e],Lg=({values:n},e)=>n[e],ww=(n,e)=>{switch(n.type.unit){case _e.SECOND:return Bg(n,e);case _e.MILLISECOND:return Eg(n,e);case _e.MICROSECOND:return Rg(n,e);case _e.NANOSECOND:return Lg(n,e)}},Sw=({values:n,stride:e},t)=>Ud.decimal(n.subarray(e*t,e*(t+1))),_w=(n,e)=>{const{valueOffsets:t,stride:i,children:a}=n,{[e*i]:u,[e*i+1]:f}=t,m=a[0].slice(u,f-u);return new Je([m])},Nw=(n,e)=>{const{valueOffsets:t,children:i}=n,{[e]:a,[e+1]:u}=t,f=i[0];return new zd(f.slice(a,u-a))},jw=(n,e)=>new Pd(n,e),kw=(n,e)=>n.type.mode===Ht.Dense?Ug(n,e):$g(n,e),Ug=(n,e)=>{const t=n.type.typeIdToChildIndex[n.typeIds[e]],i=n.children[t];return Gt.visit(i,n.valueOffsets[e])},$g=(n,e)=>{const t=n.type.typeIdToChildIndex[n.typeIds[e]],i=n.children[t];return Gt.visit(i,e)},Iw=(n,e)=>{var t;return(t=n.dictionary)===null||t===void 0?void 0:t.get(n.values[e])},Mw=(n,e)=>n.type.unit===nr.DAY_TIME?Pg(n,e):zg(n,e),Pg=({values:n},e)=>n.subarray(2*e,2*(e+1)),zg=({values:n},e)=>{const t=n[e],i=new Int32Array(2);return i[0]=Math.trunc(t/12),i[1]=Math.trunc(t%12),i},Vg=({values:n},e)=>n[e],Wg=({values:n},e)=>n[e],Hg=({values:n},e)=>n[e],Gg=({values:n},e)=>n[e],Dw=(n,e)=>{switch(n.type.unit){case _e.SECOND:return Vg(n,e);case _e.MILLISECOND:return Wg(n,e);case _e.MICROSECOND:return Hg(n,e);case _e.NANOSECOND:return Gg(n,e)}},Cw=(n,e)=>{const{stride:t,children:i}=n,u=i[0].slice(e*t,t);return new Je([u])};ve.prototype.visitNull=je(hw);ve.prototype.visitBool=je(pw);ve.prototype.visitInt=je(gw);ve.prototype.visitInt8=je(as);ve.prototype.visitInt16=je(as);ve.prototype.visitInt32=je(as);ve.prototype.visitInt64=je(Mg);ve.prototype.visitUint8=je(as);ve.prototype.visitUint16=je(as);ve.prototype.visitUint32=je(as);ve.prototype.visitUint64=je(Mg);ve.prototype.visitFloat=je(vw);ve.prototype.visitFloat16=je(mw);ve.prototype.visitFloat32=je(as);ve.prototype.visitFloat64=je(as);ve.prototype.visitUtf8=je(Cg);ve.prototype.visitLargeUtf8=je(Cg);ve.prototype.visitBinary=je(Dg);ve.prototype.visitLargeBinary=je(Dg);ve.prototype.visitFixedSizeBinary=je(yw);ve.prototype.visitDate=je(xw);ve.prototype.visitDateDay=je(kg);ve.prototype.visitDateMillisecond=je(Ig);ve.prototype.visitTimestamp=je(bw);ve.prototype.visitTimestampSecond=je(Fg);ve.prototype.visitTimestampMillisecond=je(Og);ve.prototype.visitTimestampMicrosecond=je(Tg);ve.prototype.visitTimestampNanosecond=je(Ag);ve.prototype.visitTime=je(ww);ve.prototype.visitTimeSecond=je(Bg);ve.prototype.visitTimeMillisecond=je(Eg);ve.prototype.visitTimeMicrosecond=je(Rg);ve.prototype.visitTimeNanosecond=je(Lg);ve.prototype.visitDecimal=je(Sw);ve.prototype.visitList=je(_w);ve.prototype.visitStruct=je(jw);ve.prototype.visitUnion=je(kw);ve.prototype.visitDenseUnion=je(Ug);ve.prototype.visitSparseUnion=je($g);ve.prototype.visitDictionary=je(Iw);ve.prototype.visitInterval=je(Mw);ve.prototype.visitIntervalDayTime=je(Pg);ve.prototype.visitIntervalYearMonth=je(zg);ve.prototype.visitDuration=je(Dw);ve.prototype.visitDurationSecond=je(Vg);ve.prototype.visitDurationMillisecond=je(Wg);ve.prototype.visitDurationMicrosecond=je(Hg);ve.prototype.visitDurationNanosecond=je(Gg);ve.prototype.visitFixedSizeList=je(Cw);ve.prototype.visitMap=je(Nw);const Gt=new ve,yi=Symbol.for("keys"),_i=Symbol.for("vals"),gi=Symbol.for("kKeysAsStrings"),jd=Symbol.for("_kKeysAsStrings");class zd{constructor(e){return this[yi]=new Je([e.children[0]]).memoize(),this[_i]=e.children[1],new Proxy(this,new Ow)}get[gi](){return this[jd]||(this[jd]=Array.from(this[yi].toArray(),String))}[Symbol.iterator](){return new Fw(this[yi],this[_i])}get size(){return this[yi].length}toArray(){return Object.values(this.toJSON())}toJSON(){const e=this[yi],t=this[_i],i={};for(let a=-1,u=e.length;++a`${Bo(e)}: ${Bo(t)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}class Fw{constructor(e,t){this.keys=e,this.vals=t,this.keyIndex=0,this.numKeys=e.length}[Symbol.iterator](){return this}next(){const e=this.keyIndex;return e===this.numKeys?{done:!0,value:null}:(this.keyIndex++,{done:!1,value:[this.keys.get(e),Gt.visit(this.vals,e)]})}}class Ow{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(e){return e[gi]}has(e,t){return e[gi].includes(t)}getOwnPropertyDescriptor(e,t){if(e[gi].indexOf(t)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(e,t){if(Reflect.has(e,t))return e[t];const i=e[gi].indexOf(t);if(i!==-1){const a=Gt.visit(Reflect.get(e,_i),i);return Reflect.set(e,t,a),a}}set(e,t,i){const a=e[gi].indexOf(t);return a!==-1?(vn.visit(Reflect.get(e,_i),a,i),Reflect.set(e,t,i)):Reflect.has(e,t)?Reflect.set(e,t,i):!1}}Object.defineProperties(zd.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:"Row"},[yi]:{writable:!0,enumerable:!1,configurable:!1,value:null},[_i]:{writable:!0,enumerable:!1,configurable:!1,value:null},[jd]:{writable:!0,enumerable:!1,configurable:!1,value:null}});let wm;function Yg(n,e,t,i){const{length:a=0}=n;let u=typeof e!="number"?0:e,f=typeof t!="number"?a:t;return u<0&&(u=(u%a+a)%a),f<0&&(f=(f%a+a)%a),fa&&(f=a),i?i(n,u,f):[u,f]}const Vd=(n,e)=>n<0?e+n:n,Sm=n=>n!==n;function Ti(n){if(typeof n!=="object"||n===null)return Sm(n)?Sm:t=>t===n;if(n instanceof Date){const t=n.valueOf();return i=>i instanceof Date?i.valueOf()===t:!1}return ArrayBuffer.isView(n)?t=>t?Cb(n,t):!1:n instanceof Map?Aw(n):Array.isArray(n)?Tw(n):n instanceof Je?Bw(n):Ew(n,!0)}function Tw(n){const e=[];for(let t=-1,i=n.length;++t!1;const i=[];for(let a=-1,u=t.length;++a{if(!t||typeof t!="object")return!1;switch(t.constructor){case Array:return Rw(n,t);case Map:return _m(n,t,t.keys());case zd:case Pd:case Object:case void 0:return _m(n,t,e||Object.keys(t))}return t instanceof Je?Lw(n,t):!1}}function Rw(n,e){const t=n.length;if(e.length!==t)return!1;for(let i=-1;++i>i}function Nm(n,e,t){const i=t.byteLength+7&-8;if(n>0||t.byteLength>3):kd(new Wd(t,n,e,null,Qg)).subarray(0,i)),a}return t}function kd(n){const e=[];let t=0,i=0,a=0;for(const f of n)f&&(a|=1<0)&&(e[t++]=a);const u=new Uint8Array(e.length+7&-8);return u.set(e),u}class Wd{constructor(e,t,i,a,u){this.bytes=e,this.length=i,this.context=a,this.get=u,this.bit=t%8,this.byteIndex=t>>3,this.byte=e[this.byteIndex++],this.index=0}next(){return this.index>3<<3,a=e+(e%8===0?0:8-e%8);return Id(n,e,a)+Id(n,i,t)+$w(n,a>>3,i-a>>3)}function $w(n,e,t){let i=0,a=Math.trunc(e);const u=new DataView(n.buffer,n.byteOffset,n.byteLength),f=t===void 0?n.byteLength:a+t;for(;f-a>=4;)i+=id(u.getUint32(a)),a+=4;for(;f-a>=2;)i+=id(u.getUint16(a)),a+=2;for(;f-a>=1;)i+=id(u.getUint8(a)),a+=1;return i}function id(n){let e=Math.trunc(n);return e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),(e+(e>>>4)&252645135)*16843009>>>24}const Pw=-1;class Ye{get typeId(){return this.type.typeId}get ArrayType(){return this.type.ArrayType}get buffers(){return[this.valueOffsets,this.values,this.nullBitmap,this.typeIds]}get nullable(){if(this._nullCount!==0){const{type:e}=this;return me.isSparseUnion(e)?this.children.some(t=>t.nullable):me.isDenseUnion(e)?this.children.some(t=>t.nullable):this.nullBitmap&&this.nullBitmap.byteLength>0}return!0}get byteLength(){let e=0;const{valueOffsets:t,values:i,nullBitmap:a,typeIds:u}=this;return t&&(e+=t.byteLength),i&&(e+=i.byteLength),a&&(e+=a.byteLength),u&&(e+=u.byteLength),this.children.reduce((f,h)=>f+h.byteLength,e)}get nullCount(){if(me.isUnion(this.type))return this.children.reduce((i,a)=>i+a.nullCount,0);let e=this._nullCount,t;return e<=Pw&&(t=this.nullBitmap)&&(this._nullCount=e=t.length===0?0:this.length-Id(t,this.offset,this.offset+this.length)),e}constructor(e,t,i,a,u,f=[],h){this.type=e,this.children=f,this.dictionary=h,this.offset=Math.floor(Math.max(t||0,0)),this.length=Math.floor(Math.max(i||0,0)),this._nullCount=Math.floor(Math.max(a||0,-1));let m;u instanceof Ye?(this.stride=u.stride,this.values=u.values,this.typeIds=u.typeIds,this.nullBitmap=u.nullBitmap,this.valueOffsets=u.valueOffsets):(this.stride=vr(e),u&&((m=u[0])&&(this.valueOffsets=m),(m=u[1])&&(this.values=m),(m=u[2])&&(this.nullBitmap=m),(m=u[3])&&(this.typeIds=m)))}getValid(e){const{type:t}=this;if(me.isUnion(t)){const i=t,a=this.children[i.typeIdToChildIndex[this.typeIds[e]]],u=i.mode===Ht.Dense?this.valueOffsets[e]:e;return a.getValid(u)}if(this.nullable&&this.nullCount>0){const i=this.offset+e;return(this.nullBitmap[i>>3]&1<>3;(!u||u.byteLength<=v)&&(u=new Uint8Array((f+h+63&-64)>>3).fill(255),this.nullCount>0?(u.set(Nm(f,h,this.nullBitmap),0),Object.assign(this,{nullBitmap:u})):Object.assign(this,{nullBitmap:u,_nullCount:0}));const x=u[v];i=(x&g)!==0,u[v]=t?x|g:x&~g}return i!==!!t&&(this._nullCount=this.nullCount+(t?-1:1)),t}clone(e=this.type,t=this.offset,i=this.length,a=this._nullCount,u=this,f=this.children){return new Ye(e,t,i,a,u,f,this.dictionary)}slice(e,t){const{stride:i,typeId:a,children:u}=this,f=+(this._nullCount===0)-1,h=a===16?i:1,m=this._sliceBuffers(e,t,i,a);return this.clone(this.type,this.offset+e,t,f,m,u.length===0||this.valueOffsets?u:this._sliceChildren(u,h*e,h*t))}_changeLengthAndBackfillNullBitmap(e){if(this.typeId===M.Null)return this.clone(this.type,0,e,0);const{length:t,nullCount:i}=this,a=new Uint8Array((e+63&-64)>>3).fill(255,0,t>>3);a[t>>3]=(1<0&&a.set(Nm(this.offset,t,this.nullBitmap),0);const u=this.buffers;return u[gr.VALIDITY]=a,this.clone(this.type,0,e,i+(e-t),u)}_sliceBuffers(e,t,i,a){let u;const{buffers:f}=this;return(u=f[gr.TYPE])&&(f[gr.TYPE]=u.subarray(e,e+t)),(u=f[gr.OFFSET])&&(f[gr.OFFSET]=u.subarray(e,e+t+1))||(u=f[gr.DATA])&&(f[gr.DATA]=a===6?u:u.subarray(i*e,i*(e+t))),f}_sliceChildren(e,t,i){return e.map(a=>a.slice(t,i))}}Ye.prototype.children=Object.freeze([]);class To extends Re{visit(e){return this.getVisitFn(e.type).call(this,e)}visitNull(e){const{["type"]:t,["offset"]:i=0,["length"]:a=0}=e;return new Ye(t,i,a,a)}visitBool(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length>>3,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitInt(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitFloat(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitUtf8(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitLargeUtf8(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=cm(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitBinary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitLargeBinary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=cm(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitFixedSizeBinary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitDate(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitTimestamp(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitTime(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitDecimal(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitList(e){const{["type"]:t,["offset"]:i=0,["child"]:a}=e,u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,void 0,u],[a])}visitStruct(e){const{["type"]:t,["offset"]:i=0,["children"]:a=[]}=e,u=$e(e.nullBitmap),{length:f=a.reduce((m,{length:g})=>Math.max(m,g),0),nullCount:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,void 0,u],a)}visitUnion(e){const{["type"]:t,["offset"]:i=0,["children"]:a=[]}=e,u=Ke(t.ArrayType,e.typeIds),{["length"]:f=u.length,["nullCount"]:h=-1}=e;if(me.isSparseUnion(t))return new Ye(t,i,f,h,[void 0,void 0,void 0,u],a);const m=So(e.valueOffsets);return new Ye(t,i,f,h,[m,void 0,void 0,u],a)}visitDictionary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.indices.ArrayType,e.data),{["dictionary"]:f=new Je([new To().visit({type:t.dictionary})])}=e,{["length"]:h=u.length,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[void 0,u,a],[],f)}visitInterval(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitDuration(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitFixedSizeList(e){const{["type"]:t,["offset"]:i=0,["child"]:a=new To().visit({type:t.valueType})}=e,u=$e(e.nullBitmap),{["length"]:f=a.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,void 0,u],[a])}visitMap(e){const{["type"]:t,["offset"]:i=0,["child"]:a=new To().visit({type:t.childType})}=e,u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,void 0,u],[a])}}const zw=new To;function Ee(n){return zw.visit(n)}class jm{constructor(e=0,t){this.numChunks=e,this.getChunkIterator=t,this.chunkIndex=0,this.chunkIterator=this.getChunkIterator(0)}next(){for(;this.chunkIndexe.nullable)}function Kg(n){return n.reduce((e,t)=>e+t.nullCount,0)}function Jg(n){return n.reduce((e,t,i)=>(e[i+1]=e[i]+t.length,e),new Uint32Array(n.length+1))}function qg(n,e,t,i){const a=[];for(let u=-1,f=n.length;++u=i)break;if(t>=m+g)continue;if(m>=t&&m+g<=i){a.push(h);continue}const v=Math.max(0,t-m),x=Math.min(i-m,g);a.push(h.slice(v,x-v))}return a.length===0&&a.push(n[0].slice(0,0)),a}function Hd(n,e,t,i){let a=0,u=0,f=e.length-1;do{if(a>=f-1)return t0?0:-1}function Hw(n,e){const{nullBitmap:t}=n;if(!t||n.nullCount<=0)return-1;let i=0;for(const a of new Wd(t,n.offset+(e||0),n.length,t,Qg)){if(!a)return i;++i}return-1}function De(n,e,t){if(e===void 0)return-1;if(e===null)switch(n.typeId){case M.Union:break;case M.Dictionary:break;default:return Hw(n,t)}const i=Gt.getVisitFn(n),a=Ti(e);for(let u=(t||0)-1,f=n.length;++u{const a=n.data[i];return a.values.subarray(0,a.length)[Symbol.iterator]()});let t=0;return new jm(n.data.length,i=>{const u=n.data[i].length,f=n.slice(t,t+u);return t+=u,new Gw(f)})}class Gw{constructor(e){this.vector=e,this.index=0}next(){return this.indexh.data):e;if(u.length===0||u.some(h=>!(h instanceof Ye)))throw new TypeError("Vector constructor expects an Array of Data instances.");const f=(t=u[0])===null||t===void 0?void 0:t.type;switch(u.length){case 0:this._offsets=[0];break;case 1:{const{get:h,set:m,indexOf:g}=nv[f.typeId],v=u[0];this.isValid=x=>Gd(v,x),this.get=x=>h(v,x),this.set=(x,b)=>m(v,x,b),this.indexOf=x=>g(v,x),this._offsets=[0,v.length];break}default:Object.setPrototypeOf(this,rv[f.typeId]),this._offsets=Jg(u);break}this.data=u,this.type=f,this.stride=vr(f),this.numChildren=(a=(i=f.children)===null||i===void 0?void 0:i.length)!==null&&a!==void 0?a:0,this.length=this._offsets.at(-1)}get byteLength(){return this.data.reduce((e,t)=>e+t.byteLength,0)}get nullable(){return Vw(this.data)}get nullCount(){return Kg(this.data)}get ArrayType(){return this.type.ArrayType}get[Symbol.toStringTag](){return`${this.VectorName}<${this.type[Symbol.toStringTag]}>`}get VectorName(){return`${M[this.type.typeId]}Vector`}isValid(e){return!1}get(e){return null}at(e){return this.get(Vd(e,this.length))}set(e,t){}indexOf(e,t){return-1}includes(e,t){return this.indexOf(e,t)>-1}[Symbol.iterator](){return Yd.visit(this)}concat(...e){return new Je(this.data.concat(e.flatMap(t=>t.data).flat(Number.POSITIVE_INFINITY)))}slice(e,t){return new Je(Yg(this,e,t,({data:i,_offsets:a},u,f)=>qg(i,a,u,f)))}toJSON(){return[...this]}toArray(){const{type:e,data:t,length:i,stride:a,ArrayType:u}=this;switch(e.typeId){case M.Int:case M.Float:case M.Decimal:case M.Time:case M.Timestamp:switch(t.length){case 0:return new u;case 1:return t[0].values.subarray(0,i*a);default:return t.reduce((f,{values:h,length:m})=>(f.array.set(h.subarray(0,m*a),f.offset),f.offset+=m*a,f),{array:new u(i*a),offset:0}).array}}return[...this]}toString(){return`[${[...this].join(",")}]`}getChild(e){var t;return this.getChildAt((t=this.type.children)===null||t===void 0?void 0:t.findIndex(i=>i.name===e))}getChildAt(e){return e>-1&&et[e])):null}get isMemoized(){return me.isDictionary(this.type)?this.data[0].dictionary.isMemoized:!1}memoize(){if(me.isDictionary(this.type)){const e=new Wl(this.data[0].dictionary),t=this.data.map(i=>{const a=i.clone();return a.dictionary=e,a});return new Je(t)}return new Wl(this)}unmemoize(){if(me.isDictionary(this.type)&&this.isMemoized){const e=this.data[0].dictionary.unmemoize(),t=this.data.map(i=>{const a=i.clone();return a.dictionary=e,a});return new Je(t)}return this}}tv=Symbol.toStringTag;Je[tv]=(n=>{n.type=me.prototype,n.data=[],n.length=0,n.stride=1,n.numChildren=0,n._offsets=new Uint32Array([0]),n[Symbol.isConcatSpreadable]=!0;const e=Object.keys(M).map(t=>M[t]).filter(t=>typeof t=="number"&&t!==M.NONE);for(const t of e){const i=Gt.getVisitFnByTypeId(t),a=vn.getVisitFnByTypeId(t),u=Vl.getVisitFnByTypeId(t);nv[t]={get:i,set:a,indexOf:u},rv[t]=Object.create(n,{isValid:{value:zl(Gd)},get:{value:zl(Gt.getVisitFnByTypeId(t))},set:{value:Zg(vn.getVisitFnByTypeId(t))},indexOf:{value:Xg(Vl.getVisitFnByTypeId(t))}})}return"Vector"})(Je.prototype);class Wl extends Je{constructor(e){super(e.data);const t=this.get,i=this.set,a=this.slice,u=new Array(this.length);Object.defineProperty(this,"get",{value(f){const h=u[f];if(h!==void 0)return h;const m=t.call(this,f);return u[f]=m,m}}),Object.defineProperty(this,"set",{value(f,h){i.call(this,f,h),u[f]=h}}),Object.defineProperty(this,"slice",{value:(f,h)=>new Wl(a.call(this,f,h))}),Object.defineProperty(this,"isMemoized",{value:!0}),Object.defineProperty(this,"unmemoize",{value:()=>new Je(this.data)}),Object.defineProperty(this,"memoize",{value:()=>this})}}class Md{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}offset(){return this.bb.readInt64(this.bb_pos)}metaDataLength(){return this.bb.readInt32(this.bb_pos+8)}bodyLength(){return this.bb.readInt64(this.bb_pos+16)}static sizeOf(){return 24}static createBlock(e,t,i,a){return e.prep(8,24),e.writeInt64(BigInt(a??0)),e.pad(4),e.writeInt32(i),e.writeInt64(BigInt(t??0)),e.offset()}}class Xt{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsFooter(e,t){return(t||new Xt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsFooter(e,t){return e.setPosition(e.position()+He),(t||new Xt).__init(e.readInt32(e.position())+e.position(),e)}version(){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):ht.V1}schema(e){const t=this.bb.__offset(this.bb_pos,6);return t?(e||new Gn).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}dictionaries(e,t){const i=this.bb.__offset(this.bb_pos,8);return i?(t||new Md).__init(this.bb.__vector(this.bb_pos+i)+e*24,this.bb):null}dictionariesLength(){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}recordBatches(e,t){const i=this.bb.__offset(this.bb_pos,10);return i?(t||new Md).__init(this.bb.__vector(this.bb_pos+i)+e*24,this.bb):null}recordBatchesLength(){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,12);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}static startFooter(e){e.startObject(5)}static addVersion(e,t){e.addFieldInt16(0,t,ht.V1)}static addSchema(e,t){e.addFieldOffset(1,t,0)}static addDictionaries(e,t){e.addFieldOffset(2,t,0)}static startDictionariesVector(e,t){e.startVector(24,t,8)}static addRecordBatches(e,t){e.addFieldOffset(3,t,0)}static startRecordBatchesVector(e,t){e.startVector(24,t,8)}static addCustomMetadata(e,t){e.addFieldOffset(4,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endFooter(e){return e.endObject()}static finishFooterBuffer(e,t){e.finish(t)}static finishSizePrefixedFooterBuffer(e,t){e.finish(t,void 0,!0)}}class We{constructor(e=[],t,i,a=ht.V5){this.fields=e||[],this.metadata=t||new Map,i||(i=Dd(this.fields)),this.dictionaries=i,this.metadataVersion=a}get[Symbol.toStringTag](){return"Schema"}get names(){return this.fields.map(e=>e.name)}toString(){return`Schema<{ ${this.fields.map((e,t)=>`${t}: ${e}`).join(", ")} }>`}select(e){const t=new Set(e),i=this.fields.filter(a=>t.has(a.name));return new We(i,this.metadata)}selectAt(e){const t=e.map(i=>this.fields[i]).filter(Boolean);return new We(t,this.metadata)}assign(...e){const t=e[0]instanceof We?e[0]:Array.isArray(e[0])?new We(e[0]):new We(e),i=[...this.fields],a=sl(sl(new Map,this.metadata),t.metadata),u=t.fields.filter(h=>{const m=i.findIndex(g=>g.name===h.name);return~m?(i[m]=h.clone({metadata:sl(sl(new Map,i[m].metadata),h.metadata)}))&&!1:!0}),f=Dd(u,new Map);return new We([...i,...u],a,new Map([...this.dictionaries,...f]))}}We.prototype.fields=null;We.prototype.metadata=null;We.prototype.dictionaries=null;class nt{static new(...e){let[t,i,a,u]=e;return e[0]&&typeof e[0]=="object"&&({name:t}=e[0],i===void 0&&(i=e[0].type),a===void 0&&(a=e[0].nullable),u===void 0&&(u=e[0].metadata)),new nt(`${t}`,i,a,u)}constructor(e,t,i=!1,a){this.name=e,this.type=t,this.nullable=i,this.metadata=a||new Map}get typeId(){return this.type.typeId}get[Symbol.toStringTag](){return"Field"}toString(){return`${this.name}: ${this.type}`}clone(...e){let[t,i,a,u]=e;return!e[0]||typeof e[0]!="object"?[t=this.name,i=this.type,a=this.nullable,u=this.metadata]=e:{name:t=this.name,type:i=this.type,nullable:a=this.nullable,metadata:u=this.metadata}=e[0],nt.new(t,i,a,u)}}nt.prototype.type=null;nt.prototype.name=null;nt.prototype.nullable=null;nt.prototype.metadata=null;function sl(n,e){return new Map([...n||new Map,...e||new Map])}function Dd(n,e=new Map){for(let t=-1,i=n.length;++t0&&Dd(u.children,e)}return e}var Yw=Iy,Qw=ki;class Qd{static decode(e){e=new Qw($e(e));const t=Xt.getRootAsFooter(e),i=We.decode(t.schema(),new Map,t.version());return new Kw(i,t)}static encode(e){const t=new Yw,i=We.encode(t,e.schema);Xt.startRecordBatchesVector(t,e.numRecordBatches);for(const f of[...e.recordBatches()].slice().reverse())Di.encode(t,f);const a=t.endVector();Xt.startDictionariesVector(t,e.numDictionaries);for(const f of[...e.dictionaryBatches()].slice().reverse())Di.encode(t,f);const u=t.endVector();return Xt.startFooter(t),Xt.addSchema(t,i),Xt.addVersion(t,ht.V5),Xt.addRecordBatches(t,a),Xt.addDictionaries(t,u),Xt.finishFooterBuffer(t,Xt.endFooter(t)),t.asUint8Array()}get numRecordBatches(){return this._recordBatches.length}get numDictionaries(){return this._dictionaryBatches.length}constructor(e,t=ht.V5,i,a){this.schema=e,this.version=t,i&&(this._recordBatches=i),a&&(this._dictionaryBatches=a)}*recordBatches(){for(let e,t=-1,i=this.numRecordBatches;++t=0&&e=0&&e=0&&e=0&&ethis._closedPromiseResolve=e)}get closed(){return this._closedPromise}cancel(e){return Fe(this,void 0,void 0,function*(){yield this.return(e)})}write(e){this._ensureOpen()&&(this.resolvers.length<=0?this._values.push(e):this.resolvers.shift().resolve({done:!1,value:e}))}abort(e){this._closedPromiseResolve&&(this.resolvers.length<=0?this._error={error:e}:this.resolvers.shift().reject({done:!0,value:e}))}close(){if(this._closedPromiseResolve){const{resolvers:e}=this;for(;e.length>0;)e.shift().resolve(at);this._closedPromiseResolve(),this._closedPromiseResolve=void 0}}[Symbol.asyncIterator](){return this}toDOMStream(e){return fn.toDOMStream(this._closedPromiseResolve||this._error?this:this._values,e)}toNodeStream(e){return fn.toNodeStream(this._closedPromiseResolve||this._error?this:this._values,e)}throw(e){return Fe(this,void 0,void 0,function*(){return yield this.abort(e),at})}return(e){return Fe(this,void 0,void 0,function*(){return yield this.close(),at})}read(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"read")).value})}peek(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"peek")).value})}next(...e){return this._values.length>0?Promise.resolve({done:!1,value:this._values.shift()}):this._error?Promise.reject({done:!0,value:this._error.error}):this._closedPromiseResolve?new Promise((t,i)=>{this.resolvers.push({resolve:t,reject:i})}):Promise.resolve(at)}_ensureOpen(){if(this._closedPromiseResolve)return!0;throw new Error("AsyncQueue is closed")}}class qw extends Jw{write(e){if((e=$e(e)).byteLength>0)return super.write(e)}toString(e=!1){return e?xd(this.toUint8Array(!0)):this.toUint8Array(!1).then(xd)}toUint8Array(e=!1){return e?tr(this._values)[0]:Fe(this,void 0,void 0,function*(){var t,i,a,u;const f=[];let h=0;try{for(var m=!0,g=xi(this),v;v=yield g.next(),t=v.done,!t;m=!0){u=v.value,m=!1;const x=u;f.push(x),h+=x.byteLength}}catch(x){i={error:x}}finally{try{!m&&!t&&(a=g.return)&&(yield a.call(g))}finally{if(i)throw i.error}}return tr(f,h)[0]})}}class Hl{constructor(e){e&&(this.source=new Zw(fn.fromIterable(e)))}[Symbol.iterator](){return this}next(e){return this.source.next(e)}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}peek(e){return this.source.peek(e)}read(e){return this.source.read(e)}}class Ci{constructor(e){e instanceof Ci?this.source=e.source:e instanceof qw?this.source=new js(fn.fromAsyncIterable(e)):Ny(e)?this.source=new js(fn.fromNodeStream(e)):Rd(e)?this.source=new js(fn.fromDOMStream(e)):Sy(e)?this.source=new js(fn.fromDOMStream(e.body)):nu(e)?this.source=new js(fn.fromIterable(e)):Ao(e)?this.source=new js(fn.fromAsyncIterable(e)):Ed(e)&&(this.source=new js(fn.fromAsyncIterable(e)))}[Symbol.asyncIterator](){return this}next(e){return this.source.next(e)}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}get closed(){return this.source.closed}cancel(e){return this.source.cancel(e)}peek(e){return this.source.peek(e)}read(e){return this.source.read(e)}}class Zw{constructor(e){this.source=e}cancel(e){this.return(e)}peek(e){return this.next(e,"peek").value}read(e){return this.next(e,"read").value}next(e,t="read"){return this.source.next({cmd:t,size:e})}throw(e){return Object.create(this.source.throw&&this.source.throw(e)||at)}return(e){return Object.create(this.source.return&&this.source.return(e)||at)}}class js{constructor(e){this.source=e,this._closedPromise=new Promise(t=>this._closedPromiseResolve=t)}cancel(e){return Fe(this,void 0,void 0,function*(){yield this.return(e)})}get closed(){return this._closedPromise}read(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"read")).value})}peek(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"peek")).value})}next(e){return Fe(this,arguments,void 0,function*(t,i="read"){return yield this.source.next({cmd:i,size:t})})}throw(e){return Fe(this,void 0,void 0,function*(){const t=this.source.throw&&(yield this.source.throw(e))||at;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(t)})}return(e){return Fe(this,void 0,void 0,function*(){const t=this.source.return&&(yield this.source.return(e))||at;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(t)})}}class Im extends Hl{constructor(e,t){super(),this.position=0,this.buffer=$e(e),this.size=t===void 0?this.buffer.byteLength:t}readInt32(e){const{buffer:t,byteOffset:i}=this.readAt(e,4);return new DataView(t,i).getInt32(0,!0)}seek(e){return this.position=Math.min(e,this.size),e>>16,this.buffer[1]&65535,this.buffer[0]>>>16,this.buffer[0]&65535]),i=new Uint32Array([e.buffer[1]>>>16,e.buffer[1]&65535,e.buffer[0]>>>16,e.buffer[0]&65535]);let a=t[3]*i[3];this.buffer[0]=a&65535;let u=a>>>16;return a=t[2]*i[3],u+=a,a=t[3]*i[2]>>>0,u+=a,this.buffer[0]+=u<<16,this.buffer[1]=u>>>0>>16,this.buffer[1]+=t[1]*i[3]+t[2]*i[2]+t[3]*i[1],this.buffer[1]+=t[0]*i[3]+t[1]*i[2]+t[2]*i[1]+t[3]*i[0]<<16,this}_plus(e){const t=this.buffer[0]+e.buffer[0]>>>0;this.buffer[1]+=e.buffer[1],t>>0&&++this.buffer[1],this.buffer[0]=t}lessThan(e){return this.buffer[1]>>0,t[2]=this.buffer[2]+e.buffer[2]>>>0,t[1]=this.buffer[1]+e.buffer[1]>>>0,t[0]=this.buffer[0]+e.buffer[0]>>>0,t[0]>>0&&++t[1],t[1]>>0&&++t[2],t[2]>>0&&++t[3],this.buffer[3]=t[3],this.buffer[2]=t[2],this.buffer[1]=t[1],this.buffer[0]=t[0],this}hex(){return`${vi(this.buffer[3])} ${vi(this.buffer[2])} ${vi(this.buffer[1])} ${vi(this.buffer[0])}`}static multiply(e,t){return new Yn(new Uint32Array(e.buffer)).times(t)}static add(e,t){return new Yn(new Uint32Array(e.buffer)).plus(t)}static from(e,t=new Uint32Array(4)){return Yn.fromString(typeof e=="string"?e:e.toString(),t)}static fromNumber(e,t=new Uint32Array(4)){return Yn.fromString(e.toString(),t)}static fromString(e,t=new Uint32Array(4)){const i=e.startsWith("-"),a=e.length,u=new Yn(t);for(let f=i?1:0;f0&&this.readData(e,i)||new Uint8Array(0)}readOffsets(e,t){return this.readData(e,t)}readTypeIds(e,t){return this.readData(e,t)}readData(e,{length:t,offset:i}=this.nextBufferRange()){return this.bytes.subarray(i,i+t)}readDictionary(e){return this.dictionaries.get(e.id)}}class e1 extends ov{constructor(e,t,i,a,u){super(new Uint8Array(0),t,i,a,u),this.sources=e}readNullBitmap(e,t,{offset:i}=this.nextBufferRange()){return t<=0?new Uint8Array(0):kd(this.sources[i])}readOffsets(e,{offset:t}=this.nextBufferRange()){return Ke(Uint8Array,Ke(e.OffsetArrayType,this.sources[t]))}readTypeIds(e,{offset:t}=this.nextBufferRange()){return Ke(Uint8Array,Ke(e.ArrayType,this.sources[t]))}readData(e,{offset:t}=this.nextBufferRange()){const{sources:i}=this;return me.isTimestamp(e)||(me.isInt(e)||me.isTime(e))&&e.bitWidth===64||me.isDuration(e)||me.isDate(e)&&e.unit===gn.MILLISECOND?Ke(Uint8Array,zt.convertArray(i[t])):me.isDecimal(e)?Ke(Uint8Array,Yn.convertArray(i[t])):me.isBinary(e)||me.isLargeBinary(e)||me.isFixedSizeBinary(e)?t1(i[t]):me.isBool(e)?kd(i[t]):me.isUtf8(e)||me.isLargeUtf8(e)?Bd(i[t].join("")):Ke(Uint8Array,Ke(e.ArrayType,i[t].map(a=>+a)))}}function t1(n){const e=n.join(""),t=new Uint8Array(e.length/2);for(let i=0;i>1]=Number.parseInt(e.slice(i,i+2),16);return t}class we extends Re{compareSchemas(e,t){return e===t||t instanceof e.constructor&&this.compareManyFields(e.fields,t.fields)}compareManyFields(e,t){return e===t||Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>this.compareFields(i,t[a]))}compareFields(e,t){return e===t||t instanceof e.constructor&&e.name===t.name&&e.nullable===t.nullable&&this.visit(e.type,t.type)}}function At(n,e){return e instanceof n.constructor}function As(n,e){return n===e||At(n,e)}function Mr(n,e){return n===e||At(n,e)&&n.bitWidth===e.bitWidth&&n.isSigned===e.isSigned}function su(n,e){return n===e||At(n,e)&&n.precision===e.precision}function n1(n,e){return n===e||At(n,e)&&n.byteWidth===e.byteWidth}function Jd(n,e){return n===e||At(n,e)&&n.unit===e.unit}function Po(n,e){return n===e||At(n,e)&&n.unit===e.unit&&n.timezone===e.timezone}function zo(n,e){return n===e||At(n,e)&&n.unit===e.unit&&n.bitWidth===e.bitWidth}function r1(n,e){return n===e||At(n,e)&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}function s1(n,e){return n===e||At(n,e)&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}function qd(n,e){return n===e||At(n,e)&&n.mode===e.mode&&n.typeIds.every((t,i)=>t===e.typeIds[i])&&is.compareManyFields(n.children,e.children)}function i1(n,e){return n===e||At(n,e)&&n.id===e.id&&n.isOrdered===e.isOrdered&&is.visit(n.indices,e.indices)&&is.visit(n.dictionary,e.dictionary)}function Zd(n,e){return n===e||At(n,e)&&n.unit===e.unit}function Vo(n,e){return n===e||At(n,e)&&n.unit===e.unit}function o1(n,e){return n===e||At(n,e)&&n.listSize===e.listSize&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}function a1(n,e){return n===e||At(n,e)&&n.keysSorted===e.keysSorted&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}we.prototype.visitNull=As;we.prototype.visitBool=As;we.prototype.visitInt=Mr;we.prototype.visitInt8=Mr;we.prototype.visitInt16=Mr;we.prototype.visitInt32=Mr;we.prototype.visitInt64=Mr;we.prototype.visitUint8=Mr;we.prototype.visitUint16=Mr;we.prototype.visitUint32=Mr;we.prototype.visitUint64=Mr;we.prototype.visitFloat=su;we.prototype.visitFloat16=su;we.prototype.visitFloat32=su;we.prototype.visitFloat64=su;we.prototype.visitUtf8=As;we.prototype.visitLargeUtf8=As;we.prototype.visitBinary=As;we.prototype.visitLargeBinary=As;we.prototype.visitFixedSizeBinary=n1;we.prototype.visitDate=Jd;we.prototype.visitDateDay=Jd;we.prototype.visitDateMillisecond=Jd;we.prototype.visitTimestamp=Po;we.prototype.visitTimestampSecond=Po;we.prototype.visitTimestampMillisecond=Po;we.prototype.visitTimestampMicrosecond=Po;we.prototype.visitTimestampNanosecond=Po;we.prototype.visitTime=zo;we.prototype.visitTimeSecond=zo;we.prototype.visitTimeMillisecond=zo;we.prototype.visitTimeMicrosecond=zo;we.prototype.visitTimeNanosecond=zo;we.prototype.visitDecimal=As;we.prototype.visitList=r1;we.prototype.visitStruct=s1;we.prototype.visitUnion=qd;we.prototype.visitDenseUnion=qd;we.prototype.visitSparseUnion=qd;we.prototype.visitDictionary=i1;we.prototype.visitInterval=Zd;we.prototype.visitIntervalDayTime=Zd;we.prototype.visitIntervalYearMonth=Zd;we.prototype.visitDuration=Vo;we.prototype.visitDurationSecond=Vo;we.prototype.visitDurationMillisecond=Vo;we.prototype.visitDurationMicrosecond=Vo;we.prototype.visitDurationNanosecond=Vo;we.prototype.visitFixedSizeList=o1;we.prototype.visitMap=a1;const is=new we;function l1(n,e){return is.compareSchemas(n,e)}function od(n,e){return u1(n,e.map(t=>t.data.concat()))}function u1(n,e){const t=[...n.fields],i=[],a={numBatches:e.reduce((x,b)=>Math.max(x,b.length),0)};let u=0,f=0,h=-1;const m=e.length;let g,v=[];for(;a.numBatches-- >0;){for(f=Number.POSITIVE_INFINITY,h=-1;++h0&&(i[u++]=Ee({type:new Tt(t),length:f,nullCount:0,children:v.slice()})))}return[n=n.assign(t),i.map(x=>new An(n,x))]}function c1(n,e,t,i,a){var u;const f=(e+63&-64)>>3;for(let h=-1,m=i.length;++h=e)v===e?t[h]=g:(t[h]=g.slice(0,e),a.numBatches=Math.max(a.numBatches,i[h].unshift(g.slice(e,v-e))));else{const x=n[h];n[h]=x.clone({nullable:!0}),t[h]=(u=g==null?void 0:g._changeLengthAndBackfillNullBitmap(e))!==null&&u!==void 0?u:Ee({type:x.type,length:e,nullCount:e,nullBitmap:new Uint8Array(f)})}}return t}var av;class mn{constructor(...e){var t,i;if(e.length===0)return this.batches=[],this.schema=new We([]),this._offsets=[0],this;let a,u;e[0]instanceof We&&(a=e.shift()),e.at(-1)instanceof Uint32Array&&(u=e.pop());const f=m=>{if(m){if(m instanceof An)return[m];if(m instanceof mn)return m.batches;if(m instanceof Ye){if(m.type instanceof Tt)return[new An(new We(m.type.children),m)]}else{if(Array.isArray(m))return m.flatMap(g=>f(g));if(typeof m[Symbol.iterator]=="function")return[...m].flatMap(g=>f(g));if(typeof m=="object"){const g=Object.keys(m),v=g.map(w=>new Je([m[w]])),x=a??new We(g.map((w,j)=>new nt(String(w),v[j].type,v[j].nullable))),[,b]=od(x,v);return b.length===0?[new An(m)]:b}}}return[]},h=e.flatMap(m=>f(m));if(a=(i=a??((t=h[0])===null||t===void 0?void 0:t.schema))!==null&&i!==void 0?i:new We([]),!(a instanceof We))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");for(const m of h){if(!(m instanceof An))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");if(!l1(a,m.schema))throw new TypeError("Table and inner RecordBatch schemas must be equivalent.")}this.schema=a,this.batches=h,this._offsets=u??Jg(this.data)}get data(){return this.batches.map(({data:e})=>e)}get numCols(){return this.schema.fields.length}get numRows(){return this.data.reduce((e,t)=>e+t.length,0)}get nullCount(){return this._nullCount===-1&&(this._nullCount=Kg(this.data)),this._nullCount}isValid(e){return!1}get(e){return null}at(e){return this.get(Vd(e,this.numRows))}set(e,t){}indexOf(e,t){return-1}[Symbol.iterator](){return this.batches.length>0?Yd.visit(new Je(this.data)):new Array(0)[Symbol.iterator]()}toArray(){return[...this]}toString(){return`[ +`+p.stack}return{value:r,source:s,stack:d,digest:null}}function bc(r,s,o){return{value:r,source:null,stack:o??null,digest:s??null}}function wc(r,s){try{console.error(s.value)}catch(o){setTimeout(function(){throw o})}}var Cx=typeof WeakMap=="function"?WeakMap:Map;function lp(r,s,o){o=dr(-1,o),o.tag=3,o.payload={element:null};var l=s.value;return o.callback=function(){Pa||(Pa=!0,Ec=l),wc(r,s)},o}function up(r,s,o){o=dr(-1,o),o.tag=3;var l=r.type.getDerivedStateFromError;if(typeof l=="function"){var d=s.value;o.payload=function(){return l(d)},o.callback=function(){wc(r,s)}}var p=r.stateNode;return p!==null&&typeof p.componentDidCatch=="function"&&(o.callback=function(){wc(r,s),typeof l!="function"&&(Hr===null?Hr=new Set([this]):Hr.add(this));var y=s.stack;this.componentDidCatch(s.value,{componentStack:y!==null?y:""})}),o}function cp(r,s,o){var l=r.pingCache;if(l===null){l=r.pingCache=new Cx;var d=new Set;l.set(s,d)}else d=l.get(s),d===void 0&&(d=new Set,l.set(s,d));d.has(o)||(d.add(o),r=Wx.bind(null,r,s,o),s.then(r,r))}function dp(r){do{var s;if((s=r.tag===13)&&(s=r.memoizedState,s=s!==null?s.dehydrated!==null:!0),s)return r;r=r.return}while(r!==null);return null}function fp(r,s,o,l,d){return(r.mode&1)===0?(r===s?r.flags|=65536:(r.flags|=128,o.flags|=131072,o.flags&=-52805,o.tag===1&&(o.alternate===null?o.tag=17:(s=dr(-1,1),s.tag=2,Vr(o,s,1))),o.lanes|=1),r):(r.flags|=65536,r.lanes=d,r)}var Fx=T.ReactCurrentOwner,Rt=!1;function Ct(r,s,o,l){s.child=r===null?Oh(s,null,o,l):Zs(s,r.child,o,l)}function hp(r,s,o,l,d){o=o.render;var p=s.ref;return ei(s,d),l=fc(r,s,o,l,p,d),o=hc(),r!==null&&!Rt?(s.updateQueue=r.updateQueue,s.flags&=-2053,r.lanes&=~d,fr(r,s,d)):(st&&o&&Ku(s),s.flags|=1,Ct(r,s,l,d),s.child)}function pp(r,s,o,l,d){if(r===null){var p=o.type;return typeof p=="function"&&!Vc(p)&&p.defaultProps===void 0&&o.compare===null&&o.defaultProps===void 0?(s.tag=15,s.type=p,mp(r,s,p,l,d)):(r=Ya(o.type,null,l,s,s.mode,d),r.ref=s.ref,r.return=s,s.child=r)}if(p=r.child,(r.lanes&d)===0){var y=p.memoizedProps;if(o=o.compare,o=o!==null?o:Xi,o(y,l)&&r.ref===s.ref)return fr(r,s,d)}return s.flags|=1,r=Kr(p,l),r.ref=s.ref,r.return=s,s.child=r}function mp(r,s,o,l,d){if(r!==null){var p=r.memoizedProps;if(Xi(p,l)&&r.ref===s.ref)if(Rt=!1,s.pendingProps=l=p,(r.lanes&d)!==0)(r.flags&131072)!==0&&(Rt=!0);else return s.lanes=r.lanes,fr(r,s,d)}return Sc(r,s,o,l,d)}function yp(r,s,o){var l=s.pendingProps,d=l.children,p=r!==null?r.memoizedState:null;if(l.mode==="hidden")if((s.mode&1)===0)s.memoizedState={baseLanes:0,cachePool:null,transitions:null},qe(si,Jt),Jt|=o;else{if((o&1073741824)===0)return r=p!==null?p.baseLanes|o:o,s.lanes=s.childLanes=1073741824,s.memoizedState={baseLanes:r,cachePool:null,transitions:null},s.updateQueue=null,qe(si,Jt),Jt|=r,null;s.memoizedState={baseLanes:0,cachePool:null,transitions:null},l=p!==null?p.baseLanes:o,qe(si,Jt),Jt|=l}else p!==null?(l=p.baseLanes|o,s.memoizedState=null):l=o,qe(si,Jt),Jt|=l;return Ct(r,s,d,o),s.child}function gp(r,s){var o=s.ref;(r===null&&o!==null||r!==null&&r.ref!==o)&&(s.flags|=512,s.flags|=2097152)}function Sc(r,s,o,l,d){var p=Et(o)?ps:jt.current;return p=Qs(s,p),ei(s,d),o=fc(r,s,o,l,p,d),l=hc(),r!==null&&!Rt?(s.updateQueue=r.updateQueue,s.flags&=-2053,r.lanes&=~d,fr(r,s,d)):(st&&l&&Ku(s),s.flags|=1,Ct(r,s,o,d),s.child)}function vp(r,s,o,l,d){if(Et(o)){var p=!0;va(s)}else p=!1;if(ei(s,d),s.stateNode===null)Ea(r,s),op(s,o,l),xc(s,o,l,d),l=!0;else if(r===null){var y=s.stateNode,S=s.memoizedProps;y.props=S;var N=y.context,P=o.contextType;typeof P=="object"&&P!==null?P=sn(P):(P=Et(o)?ps:jt.current,P=Qs(s,P));var J=o.getDerivedStateFromProps,q=typeof J=="function"||typeof y.getSnapshotBeforeUpdate=="function";q||typeof y.UNSAFE_componentWillReceiveProps!="function"&&typeof y.componentWillReceiveProps!="function"||(S!==l||N!==P)&&ap(s,y,l,P),zr=!1;var K=s.memoizedState;y.state=K,Ia(s,l,y,d),N=s.memoizedState,S!==l||K!==N||Bt.current||zr?(typeof J=="function"&&(vc(s,o,J,l),N=s.memoizedState),(S=zr||ip(s,o,S,l,K,N,P))?(q||typeof y.UNSAFE_componentWillMount!="function"&&typeof y.componentWillMount!="function"||(typeof y.componentWillMount=="function"&&y.componentWillMount(),typeof y.UNSAFE_componentWillMount=="function"&&y.UNSAFE_componentWillMount()),typeof y.componentDidMount=="function"&&(s.flags|=4194308)):(typeof y.componentDidMount=="function"&&(s.flags|=4194308),s.memoizedProps=l,s.memoizedState=N),y.props=l,y.state=N,y.context=P,l=S):(typeof y.componentDidMount=="function"&&(s.flags|=4194308),l=!1)}else{y=s.stateNode,Ah(r,s),S=s.memoizedProps,P=s.type===s.elementType?S:Nn(s.type,S),y.props=P,q=s.pendingProps,K=y.context,N=o.contextType,typeof N=="object"&&N!==null?N=sn(N):(N=Et(o)?ps:jt.current,N=Qs(s,N));var oe=o.getDerivedStateFromProps;(J=typeof oe=="function"||typeof y.getSnapshotBeforeUpdate=="function")||typeof y.UNSAFE_componentWillReceiveProps!="function"&&typeof y.componentWillReceiveProps!="function"||(S!==q||K!==N)&&ap(s,y,l,N),zr=!1,K=s.memoizedState,y.state=K,Ia(s,l,y,d);var ce=s.memoizedState;S!==q||K!==ce||Bt.current||zr?(typeof oe=="function"&&(vc(s,o,oe,l),ce=s.memoizedState),(P=zr||ip(s,o,P,l,K,ce,N)||!1)?(J||typeof y.UNSAFE_componentWillUpdate!="function"&&typeof y.componentWillUpdate!="function"||(typeof y.componentWillUpdate=="function"&&y.componentWillUpdate(l,ce,N),typeof y.UNSAFE_componentWillUpdate=="function"&&y.UNSAFE_componentWillUpdate(l,ce,N)),typeof y.componentDidUpdate=="function"&&(s.flags|=4),typeof y.getSnapshotBeforeUpdate=="function"&&(s.flags|=1024)):(typeof y.componentDidUpdate!="function"||S===r.memoizedProps&&K===r.memoizedState||(s.flags|=4),typeof y.getSnapshotBeforeUpdate!="function"||S===r.memoizedProps&&K===r.memoizedState||(s.flags|=1024),s.memoizedProps=l,s.memoizedState=ce),y.props=l,y.state=ce,y.context=N,l=P):(typeof y.componentDidUpdate!="function"||S===r.memoizedProps&&K===r.memoizedState||(s.flags|=4),typeof y.getSnapshotBeforeUpdate!="function"||S===r.memoizedProps&&K===r.memoizedState||(s.flags|=1024),l=!1)}return _c(r,s,o,l,p,d)}function _c(r,s,o,l,d,p){gp(r,s);var y=(s.flags&128)!==0;if(!l&&!y)return d&&_h(s,o,!1),fr(r,s,p);l=s.stateNode,Fx.current=s;var S=y&&typeof o.getDerivedStateFromError!="function"?null:l.render();return s.flags|=1,r!==null&&y?(s.child=Zs(s,r.child,null,p),s.child=Zs(s,null,S,p)):Ct(r,s,S,p),s.memoizedState=l.state,d&&_h(s,o,!0),s.child}function xp(r){var s=r.stateNode;s.pendingContext?wh(r,s.pendingContext,s.pendingContext!==s.context):s.context&&wh(r,s.context,!1),oc(r,s.containerInfo)}function bp(r,s,o,l,d){return qs(),Xu(d),s.flags|=256,Ct(r,s,o,l),s.child}var Nc={dehydrated:null,treeContext:null,retryLane:0};function jc(r){return{baseLanes:r,cachePool:null,transitions:null}}function wp(r,s,o){var l=s.pendingProps,d=it.current,p=!1,y=(s.flags&128)!==0,S;if((S=y)||(S=r!==null&&r.memoizedState===null?!1:(d&2)!==0),S?(p=!0,s.flags&=-129):(r===null||r.memoizedState!==null)&&(d|=1),qe(it,d&1),r===null)return Zu(s),r=s.memoizedState,r!==null&&(r=r.dehydrated,r!==null)?((s.mode&1)===0?s.lanes=1:r.data==="$!"?s.lanes=8:s.lanes=1073741824,null):(y=l.children,r=l.fallback,p?(l=s.mode,p=s.child,y={mode:"hidden",children:y},(l&1)===0&&p!==null?(p.childLanes=0,p.pendingProps=y):p=Qa(y,l,0,null),r=Ns(r,l,o,null),p.return=s,r.return=s,p.sibling=r,s.child=p,s.child.memoizedState=jc(o),s.memoizedState=Nc,r):kc(s,y));if(d=r.memoizedState,d!==null&&(S=d.dehydrated,S!==null))return Ox(r,s,y,l,S,d,o);if(p){p=l.fallback,y=s.mode,d=r.child,S=d.sibling;var N={mode:"hidden",children:l.children};return(y&1)===0&&s.child!==d?(l=s.child,l.childLanes=0,l.pendingProps=N,s.deletions=null):(l=Kr(d,N),l.subtreeFlags=d.subtreeFlags&14680064),S!==null?p=Kr(S,p):(p=Ns(p,y,o,null),p.flags|=2),p.return=s,l.return=s,l.sibling=p,s.child=l,l=p,p=s.child,y=r.child.memoizedState,y=y===null?jc(o):{baseLanes:y.baseLanes|o,cachePool:null,transitions:y.transitions},p.memoizedState=y,p.childLanes=r.childLanes&~o,s.memoizedState=Nc,l}return p=r.child,r=p.sibling,l=Kr(p,{mode:"visible",children:l.children}),(s.mode&1)===0&&(l.lanes=o),l.return=s,l.sibling=null,r!==null&&(o=s.deletions,o===null?(s.deletions=[r],s.flags|=16):o.push(r)),s.child=l,s.memoizedState=null,l}function kc(r,s){return s=Qa({mode:"visible",children:s},r.mode,0,null),s.return=r,r.child=s}function Ba(r,s,o,l){return l!==null&&Xu(l),Zs(s,r.child,null,o),r=kc(s,s.pendingProps.children),r.flags|=2,s.memoizedState=null,r}function Ox(r,s,o,l,d,p,y){if(o)return s.flags&256?(s.flags&=-257,l=bc(Error(t(422))),Ba(r,s,y,l)):s.memoizedState!==null?(s.child=r.child,s.flags|=128,null):(p=l.fallback,d=s.mode,l=Qa({mode:"visible",children:l.children},d,0,null),p=Ns(p,d,y,null),p.flags|=2,l.return=s,p.return=s,l.sibling=p,s.child=l,(s.mode&1)!==0&&Zs(s,r.child,null,y),s.child.memoizedState=jc(y),s.memoizedState=Nc,p);if((s.mode&1)===0)return Ba(r,s,y,null);if(d.data==="$!"){if(l=d.nextSibling&&d.nextSibling.dataset,l)var S=l.dgst;return l=S,p=Error(t(419)),l=bc(p,l,void 0),Ba(r,s,y,l)}if(S=(y&r.childLanes)!==0,Rt||S){if(l=xt,l!==null){switch(y&-y){case 4:d=2;break;case 16:d=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:d=32;break;case 536870912:d=268435456;break;default:d=0}d=(d&(l.suspendedLanes|y))!==0?0:d,d!==0&&d!==p.retryLane&&(p.retryLane=d,cr(r,d),In(l,r,d,-1))}return zc(),l=bc(Error(t(421))),Ba(r,s,y,l)}return d.data==="$?"?(s.flags|=128,s.child=r.child,s=Hx.bind(null,r),d._reactRetry=s,null):(r=p.treeContext,Kt=Lr(d.nextSibling),Qt=s,st=!0,_n=null,r!==null&&(nn[rn++]=lr,nn[rn++]=ur,nn[rn++]=ms,lr=r.id,ur=r.overflow,ms=s),s=kc(s,l.children),s.flags|=4096,s)}function Sp(r,s,o){r.lanes|=s;var l=r.alternate;l!==null&&(l.lanes|=s),rc(r.return,s,o)}function Ic(r,s,o,l,d){var p=r.memoizedState;p===null?r.memoizedState={isBackwards:s,rendering:null,renderingStartTime:0,last:l,tail:o,tailMode:d}:(p.isBackwards=s,p.rendering=null,p.renderingStartTime=0,p.last=l,p.tail=o,p.tailMode=d)}function _p(r,s,o){var l=s.pendingProps,d=l.revealOrder,p=l.tail;if(Ct(r,s,l.children,o),l=it.current,(l&2)!==0)l=l&1|2,s.flags|=128;else{if(r!==null&&(r.flags&128)!==0)e:for(r=s.child;r!==null;){if(r.tag===13)r.memoizedState!==null&&Sp(r,o,s);else if(r.tag===19)Sp(r,o,s);else if(r.child!==null){r.child.return=r,r=r.child;continue}if(r===s)break e;for(;r.sibling===null;){if(r.return===null||r.return===s)break e;r=r.return}r.sibling.return=r.return,r=r.sibling}l&=1}if(qe(it,l),(s.mode&1)===0)s.memoizedState=null;else switch(d){case"forwards":for(o=s.child,d=null;o!==null;)r=o.alternate,r!==null&&Ma(r)===null&&(d=o),o=o.sibling;o=d,o===null?(d=s.child,s.child=null):(d=o.sibling,o.sibling=null),Ic(s,!1,d,o,p);break;case"backwards":for(o=null,d=s.child,s.child=null;d!==null;){if(r=d.alternate,r!==null&&Ma(r)===null){s.child=d;break}r=d.sibling,d.sibling=o,o=d,d=r}Ic(s,!0,o,null,p);break;case"together":Ic(s,!1,null,null,void 0);break;default:s.memoizedState=null}return s.child}function Ea(r,s){(s.mode&1)===0&&r!==null&&(r.alternate=null,s.alternate=null,s.flags|=2)}function fr(r,s,o){if(r!==null&&(s.dependencies=r.dependencies),bs|=s.lanes,(o&s.childLanes)===0)return null;if(r!==null&&s.child!==r.child)throw Error(t(153));if(s.child!==null){for(r=s.child,o=Kr(r,r.pendingProps),s.child=o,o.return=s;r.sibling!==null;)r=r.sibling,o=o.sibling=Kr(r,r.pendingProps),o.return=s;o.sibling=null}return s.child}function Tx(r,s,o){switch(s.tag){case 3:xp(s),qs();break;case 5:Rh(s);break;case 1:Et(s.type)&&va(s);break;case 4:oc(s,s.stateNode.containerInfo);break;case 10:var l=s.type._context,d=s.memoizedProps.value;qe(Na,l._currentValue),l._currentValue=d;break;case 13:if(l=s.memoizedState,l!==null)return l.dehydrated!==null?(qe(it,it.current&1),s.flags|=128,null):(o&s.child.childLanes)!==0?wp(r,s,o):(qe(it,it.current&1),r=fr(r,s,o),r!==null?r.sibling:null);qe(it,it.current&1);break;case 19:if(l=(o&s.childLanes)!==0,(r.flags&128)!==0){if(l)return _p(r,s,o);s.flags|=128}if(d=s.memoizedState,d!==null&&(d.rendering=null,d.tail=null,d.lastEffect=null),qe(it,it.current),l)break;return null;case 22:case 23:return s.lanes=0,yp(r,s,o)}return fr(r,s,o)}var Np,Mc,jp,kp;Np=function(r,s){for(var o=s.child;o!==null;){if(o.tag===5||o.tag===6)r.appendChild(o.stateNode);else if(o.tag!==4&&o.child!==null){o.child.return=o,o=o.child;continue}if(o===s)break;for(;o.sibling===null;){if(o.return===null||o.return===s)return;o=o.return}o.sibling.return=o.return,o=o.sibling}},Mc=function(){},jp=function(r,s,o,l){var d=r.memoizedProps;if(d!==l){r=s.stateNode,vs(zn.current);var p=null;switch(o){case"input":d=Cr(r,d),l=Cr(r,l),p=[];break;case"select":d=W({},d,{value:void 0}),l=W({},l,{value:void 0}),p=[];break;case"textarea":d=Es(r,d),l=Es(r,l),p=[];break;default:typeof d.onClick!="function"&&typeof l.onClick=="function"&&(r.onclick=ma)}lu(o,l);var y;o=null;for(P in d)if(!l.hasOwnProperty(P)&&d.hasOwnProperty(P)&&d[P]!=null)if(P==="style"){var S=d[P];for(y in S)S.hasOwnProperty(y)&&(o||(o={}),o[y]="")}else P!=="dangerouslySetInnerHTML"&&P!=="children"&&P!=="suppressContentEditableWarning"&&P!=="suppressHydrationWarning"&&P!=="autoFocus"&&(a.hasOwnProperty(P)?p||(p=[]):(p=p||[]).push(P,null));for(P in l){var N=l[P];if(S=d!=null?d[P]:void 0,l.hasOwnProperty(P)&&N!==S&&(N!=null||S!=null))if(P==="style")if(S){for(y in S)!S.hasOwnProperty(y)||N&&N.hasOwnProperty(y)||(o||(o={}),o[y]="");for(y in N)N.hasOwnProperty(y)&&S[y]!==N[y]&&(o||(o={}),o[y]=N[y])}else o||(p||(p=[]),p.push(P,o)),o=N;else P==="dangerouslySetInnerHTML"?(N=N?N.__html:void 0,S=S?S.__html:void 0,N!=null&&S!==N&&(p=p||[]).push(P,N)):P==="children"?typeof N!="string"&&typeof N!="number"||(p=p||[]).push(P,""+N):P!=="suppressContentEditableWarning"&&P!=="suppressHydrationWarning"&&(a.hasOwnProperty(P)?(N!=null&&P==="onScroll"&&Xe("scroll",r),p||S===N||(p=[])):(p=p||[]).push(P,N))}o&&(p=p||[]).push("style",o);var P=p;(s.updateQueue=P)&&(s.flags|=4)}},kp=function(r,s,o,l){o!==l&&(s.flags|=4)};function mo(r,s){if(!st)switch(r.tailMode){case"hidden":s=r.tail;for(var o=null;s!==null;)s.alternate!==null&&(o=s),s=s.sibling;o===null?r.tail=null:o.sibling=null;break;case"collapsed":o=r.tail;for(var l=null;o!==null;)o.alternate!==null&&(l=o),o=o.sibling;l===null?s||r.tail===null?r.tail=null:r.tail.sibling=null:l.sibling=null}}function It(r){var s=r.alternate!==null&&r.alternate.child===r.child,o=0,l=0;if(s)for(var d=r.child;d!==null;)o|=d.lanes|d.childLanes,l|=d.subtreeFlags&14680064,l|=d.flags&14680064,d.return=r,d=d.sibling;else for(d=r.child;d!==null;)o|=d.lanes|d.childLanes,l|=d.subtreeFlags,l|=d.flags,d.return=r,d=d.sibling;return r.subtreeFlags|=l,r.childLanes=o,s}function Ax(r,s,o){var l=s.pendingProps;switch(Ju(s),s.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return It(s),null;case 1:return Et(s.type)&&ga(),It(s),null;case 3:return l=s.stateNode,ti(),et(Bt),et(jt),uc(),l.pendingContext&&(l.context=l.pendingContext,l.pendingContext=null),(r===null||r.child===null)&&(Sa(s)?s.flags|=4:r===null||r.memoizedState.isDehydrated&&(s.flags&256)===0||(s.flags|=1024,_n!==null&&(Uc(_n),_n=null))),Mc(r,s),It(s),null;case 5:ac(s);var d=vs(uo.current);if(o=s.type,r!==null&&s.stateNode!=null)jp(r,s,o,l,d),r.ref!==s.ref&&(s.flags|=512,s.flags|=2097152);else{if(!l){if(s.stateNode===null)throw Error(t(166));return It(s),null}if(r=vs(zn.current),Sa(s)){l=s.stateNode,o=s.type;var p=s.memoizedProps;switch(l[Pn]=s,l[so]=p,r=(s.mode&1)!==0,o){case"dialog":Xe("cancel",l),Xe("close",l);break;case"iframe":case"object":case"embed":Xe("load",l);break;case"video":case"audio":for(d=0;d<\/script>",r=r.removeChild(r.firstChild)):typeof l.is=="string"?r=y.createElement(o,{is:l.is}):(r=y.createElement(o),o==="select"&&(y=r,l.multiple?y.multiple=!0:l.size&&(y.size=l.size))):r=y.createElementNS(r,o),r[Pn]=s,r[so]=l,Np(r,s,!1,!1),s.stateNode=r;e:{switch(y=uu(o,l),o){case"dialog":Xe("cancel",r),Xe("close",r),d=l;break;case"iframe":case"object":case"embed":Xe("load",r),d=l;break;case"video":case"audio":for(d=0;dii&&(s.flags|=128,l=!0,mo(p,!1),s.lanes=4194304)}else{if(!l)if(r=Ma(y),r!==null){if(s.flags|=128,l=!0,o=r.updateQueue,o!==null&&(s.updateQueue=o,s.flags|=4),mo(p,!0),p.tail===null&&p.tailMode==="hidden"&&!y.alternate&&!st)return It(s),null}else 2*ct()-p.renderingStartTime>ii&&o!==1073741824&&(s.flags|=128,l=!0,mo(p,!1),s.lanes=4194304);p.isBackwards?(y.sibling=s.child,s.child=y):(o=p.last,o!==null?o.sibling=y:s.child=y,p.last=y)}return p.tail!==null?(s=p.tail,p.rendering=s,p.tail=s.sibling,p.renderingStartTime=ct(),s.sibling=null,o=it.current,qe(it,l?o&1|2:o&1),s):(It(s),null);case 22:case 23:return Pc(),l=s.memoizedState!==null,r!==null&&r.memoizedState!==null!==l&&(s.flags|=8192),l&&(s.mode&1)!==0?(Jt&1073741824)!==0&&(It(s),s.subtreeFlags&6&&(s.flags|=8192)):It(s),null;case 24:return null;case 25:return null}throw Error(t(156,s.tag))}function Bx(r,s){switch(Ju(s),s.tag){case 1:return Et(s.type)&&ga(),r=s.flags,r&65536?(s.flags=r&-65537|128,s):null;case 3:return ti(),et(Bt),et(jt),uc(),r=s.flags,(r&65536)!==0&&(r&128)===0?(s.flags=r&-65537|128,s):null;case 5:return ac(s),null;case 13:if(et(it),r=s.memoizedState,r!==null&&r.dehydrated!==null){if(s.alternate===null)throw Error(t(340));qs()}return r=s.flags,r&65536?(s.flags=r&-65537|128,s):null;case 19:return et(it),null;case 4:return ti(),null;case 10:return nc(s.type._context),null;case 22:case 23:return Pc(),null;case 24:return null;default:return null}}var Ra=!1,Mt=!1,Ex=typeof WeakSet=="function"?WeakSet:Set,le=null;function ri(r,s){var o=r.ref;if(o!==null)if(typeof o=="function")try{o(null)}catch(l){ut(r,s,l)}else o.current=null}function Dc(r,s,o){try{o()}catch(l){ut(r,s,l)}}var Ip=!1;function Rx(r,s){if(Pu=ra,r=ih(),Tu(r)){if("selectionStart"in r)var o={start:r.selectionStart,end:r.selectionEnd};else e:{o=(o=r.ownerDocument)&&o.defaultView||window;var l=o.getSelection&&o.getSelection();if(l&&l.rangeCount!==0){o=l.anchorNode;var d=l.anchorOffset,p=l.focusNode;l=l.focusOffset;try{o.nodeType,p.nodeType}catch{o=null;break e}var y=0,S=-1,N=-1,P=0,J=0,q=r,K=null;t:for(;;){for(var oe;q!==o||d!==0&&q.nodeType!==3||(S=y+d),q!==p||l!==0&&q.nodeType!==3||(N=y+l),q.nodeType===3&&(y+=q.nodeValue.length),(oe=q.firstChild)!==null;)K=q,q=oe;for(;;){if(q===r)break t;if(K===o&&++P===d&&(S=y),K===p&&++J===l&&(N=y),(oe=q.nextSibling)!==null)break;q=K,K=q.parentNode}q=oe}o=S===-1||N===-1?null:{start:S,end:N}}else o=null}o=o||{start:0,end:0}}else o=null;for(zu={focusedElem:r,selectionRange:o},ra=!1,le=s;le!==null;)if(s=le,r=s.child,(s.subtreeFlags&1028)!==0&&r!==null)r.return=s,le=r;else for(;le!==null;){s=le;try{var ce=s.alternate;if((s.flags&1024)!==0)switch(s.tag){case 0:case 11:case 15:break;case 1:if(ce!==null){var de=ce.memoizedProps,dt=ce.memoizedState,B=s.stateNode,k=B.getSnapshotBeforeUpdate(s.elementType===s.type?de:Nn(s.type,de),dt);B.__reactInternalSnapshotBeforeUpdate=k}break;case 3:var $=s.stateNode.containerInfo;$.nodeType===1?$.textContent="":$.nodeType===9&&$.documentElement&&$.removeChild($.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(t(163))}}catch(Z){ut(s,s.return,Z)}if(r=s.sibling,r!==null){r.return=s.return,le=r;break}le=s.return}return ce=Ip,Ip=!1,ce}function yo(r,s,o){var l=s.updateQueue;if(l=l!==null?l.lastEffect:null,l!==null){var d=l=l.next;do{if((d.tag&r)===r){var p=d.destroy;d.destroy=void 0,p!==void 0&&Dc(s,o,p)}d=d.next}while(d!==l)}}function La(r,s){if(s=s.updateQueue,s=s!==null?s.lastEffect:null,s!==null){var o=s=s.next;do{if((o.tag&r)===r){var l=o.create;o.destroy=l()}o=o.next}while(o!==s)}}function Cc(r){var s=r.ref;if(s!==null){var o=r.stateNode;switch(r.tag){case 5:r=o;break;default:r=o}typeof s=="function"?s(r):s.current=r}}function Mp(r){var s=r.alternate;s!==null&&(r.alternate=null,Mp(s)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(s=r.stateNode,s!==null&&(delete s[Pn],delete s[so],delete s[Gu],delete s[xx],delete s[bx])),r.stateNode=null,r.return=null,r.dependencies=null,r.memoizedProps=null,r.memoizedState=null,r.pendingProps=null,r.stateNode=null,r.updateQueue=null}function Dp(r){return r.tag===5||r.tag===3||r.tag===4}function Cp(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||Dp(r.return))return null;r=r.return}for(r.sibling.return=r.return,r=r.sibling;r.tag!==5&&r.tag!==6&&r.tag!==18;){if(r.flags&2||r.child===null||r.tag===4)continue e;r.child.return=r,r=r.child}if(!(r.flags&2))return r.stateNode}}function Fc(r,s,o){var l=r.tag;if(l===5||l===6)r=r.stateNode,s?o.nodeType===8?o.parentNode.insertBefore(r,s):o.insertBefore(r,s):(o.nodeType===8?(s=o.parentNode,s.insertBefore(r,o)):(s=o,s.appendChild(r)),o=o._reactRootContainer,o!=null||s.onclick!==null||(s.onclick=ma));else if(l!==4&&(r=r.child,r!==null))for(Fc(r,s,o),r=r.sibling;r!==null;)Fc(r,s,o),r=r.sibling}function Oc(r,s,o){var l=r.tag;if(l===5||l===6)r=r.stateNode,s?o.insertBefore(r,s):o.appendChild(r);else if(l!==4&&(r=r.child,r!==null))for(Oc(r,s,o),r=r.sibling;r!==null;)Oc(r,s,o),r=r.sibling}var St=null,jn=!1;function Wr(r,s,o){for(o=o.child;o!==null;)Fp(r,s,o),o=o.sibling}function Fp(r,s,o){if($n&&typeof $n.onCommitFiberUnmount=="function")try{$n.onCommitFiberUnmount(qo,o)}catch{}switch(o.tag){case 5:Mt||ri(o,s);case 6:var l=St,d=jn;St=null,Wr(r,s,o),St=l,jn=d,St!==null&&(jn?(r=St,o=o.stateNode,r.nodeType===8?r.parentNode.removeChild(o):r.removeChild(o)):St.removeChild(o.stateNode));break;case 18:St!==null&&(jn?(r=St,o=o.stateNode,r.nodeType===8?Hu(r.parentNode,o):r.nodeType===1&&Hu(r,o),Yi(r)):Hu(St,o.stateNode));break;case 4:l=St,d=jn,St=o.stateNode.containerInfo,jn=!0,Wr(r,s,o),St=l,jn=d;break;case 0:case 11:case 14:case 15:if(!Mt&&(l=o.updateQueue,l!==null&&(l=l.lastEffect,l!==null))){d=l=l.next;do{var p=d,y=p.destroy;p=p.tag,y!==void 0&&((p&2)!==0||(p&4)!==0)&&Dc(o,s,y),d=d.next}while(d!==l)}Wr(r,s,o);break;case 1:if(!Mt&&(ri(o,s),l=o.stateNode,typeof l.componentWillUnmount=="function"))try{l.props=o.memoizedProps,l.state=o.memoizedState,l.componentWillUnmount()}catch(S){ut(o,s,S)}Wr(r,s,o);break;case 21:Wr(r,s,o);break;case 22:o.mode&1?(Mt=(l=Mt)||o.memoizedState!==null,Wr(r,s,o),Mt=l):Wr(r,s,o);break;default:Wr(r,s,o)}}function Op(r){var s=r.updateQueue;if(s!==null){r.updateQueue=null;var o=r.stateNode;o===null&&(o=r.stateNode=new Ex),s.forEach(function(l){var d=Gx.bind(null,r,l);o.has(l)||(o.add(l),l.then(d,d))})}}function kn(r,s){var o=s.deletions;if(o!==null)for(var l=0;ld&&(d=y),l&=~p}if(l=d,l=ct()-l,l=(120>l?120:480>l?480:1080>l?1080:1920>l?1920:3e3>l?3e3:4320>l?4320:1960*Ux(l/1960))-l,10r?16:r,Gr===null)var l=!1;else{if(r=Gr,Gr=null,Va=0,(Pe&6)!==0)throw Error(t(331));var d=Pe;for(Pe|=4,le=r.current;le!==null;){var p=le,y=p.child;if((le.flags&16)!==0){var S=p.deletions;if(S!==null){for(var N=0;Nct()-Bc?Ss(r,0):Ac|=o),Ut(r,s)}function Hp(r,s){s===0&&((r.mode&1)===0?s=1:(s=Xo,Xo<<=1,(Xo&130023424)===0&&(Xo=4194304)));var o=Ft();r=cr(r,s),r!==null&&(zi(r,s,o),Ut(r,o))}function Hx(r){var s=r.memoizedState,o=0;s!==null&&(o=s.retryLane),Hp(r,o)}function Gx(r,s){var o=0;switch(r.tag){case 13:var l=r.stateNode,d=r.memoizedState;d!==null&&(o=d.retryLane);break;case 19:l=r.stateNode;break;default:throw Error(t(314))}l!==null&&l.delete(s),Hp(r,o)}var Gp;Gp=function(r,s,o){if(r!==null)if(r.memoizedProps!==s.pendingProps||Bt.current)Rt=!0;else{if((r.lanes&o)===0&&(s.flags&128)===0)return Rt=!1,Tx(r,s,o);Rt=(r.flags&131072)!==0}else Rt=!1,st&&(s.flags&1048576)!==0&&jh(s,wa,s.index);switch(s.lanes=0,s.tag){case 2:var l=s.type;Ea(r,s),r=s.pendingProps;var d=Qs(s,jt.current);ei(s,o),d=fc(null,s,l,r,d,o);var p=hc();return s.flags|=1,typeof d=="object"&&d!==null&&typeof d.render=="function"&&d.$$typeof===void 0?(s.tag=1,s.memoizedState=null,s.updateQueue=null,Et(l)?(p=!0,va(s)):p=!1,s.memoizedState=d.state!==null&&d.state!==void 0?d.state:null,ic(s),d.updater=Aa,s.stateNode=d,d._reactInternals=s,xc(s,l,r,o),s=_c(null,s,l,!0,p,o)):(s.tag=0,st&&p&&Ku(s),Ct(null,s,d,o),s=s.child),s;case 16:l=s.elementType;e:{switch(Ea(r,s),r=s.pendingProps,d=l._init,l=d(l._payload),s.type=l,d=s.tag=Qx(l),r=Nn(l,r),d){case 0:s=Sc(null,s,l,r,o);break e;case 1:s=vp(null,s,l,r,o);break e;case 11:s=hp(null,s,l,r,o);break e;case 14:s=pp(null,s,l,Nn(l.type,r),o);break e}throw Error(t(306,l,""))}return s;case 0:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),Sc(r,s,l,d,o);case 1:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),vp(r,s,l,d,o);case 3:e:{if(xp(s),r===null)throw Error(t(387));l=s.pendingProps,p=s.memoizedState,d=p.element,Ah(r,s),Ia(s,l,null,o);var y=s.memoizedState;if(l=y.element,p.isDehydrated)if(p={element:l,isDehydrated:!1,cache:y.cache,pendingSuspenseBoundaries:y.pendingSuspenseBoundaries,transitions:y.transitions},s.updateQueue.baseState=p,s.memoizedState=p,s.flags&256){d=ni(Error(t(423)),s),s=bp(r,s,l,o,d);break e}else if(l!==d){d=ni(Error(t(424)),s),s=bp(r,s,l,o,d);break e}else for(Kt=Lr(s.stateNode.containerInfo.firstChild),Qt=s,st=!0,_n=null,o=Oh(s,null,l,o),s.child=o;o;)o.flags=o.flags&-3|4096,o=o.sibling;else{if(qs(),l===d){s=fr(r,s,o);break e}Ct(r,s,l,o)}s=s.child}return s;case 5:return Rh(s),r===null&&Zu(s),l=s.type,d=s.pendingProps,p=r!==null?r.memoizedProps:null,y=d.children,Vu(l,d)?y=null:p!==null&&Vu(l,p)&&(s.flags|=32),gp(r,s),Ct(r,s,y,o),s.child;case 6:return r===null&&Zu(s),null;case 13:return wp(r,s,o);case 4:return oc(s,s.stateNode.containerInfo),l=s.pendingProps,r===null?s.child=Zs(s,null,l,o):Ct(r,s,l,o),s.child;case 11:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),hp(r,s,l,d,o);case 7:return Ct(r,s,s.pendingProps,o),s.child;case 8:return Ct(r,s,s.pendingProps.children,o),s.child;case 12:return Ct(r,s,s.pendingProps.children,o),s.child;case 10:e:{if(l=s.type._context,d=s.pendingProps,p=s.memoizedProps,y=d.value,qe(Na,l._currentValue),l._currentValue=y,p!==null)if(Sn(p.value,y)){if(p.children===d.children&&!Bt.current){s=fr(r,s,o);break e}}else for(p=s.child,p!==null&&(p.return=s);p!==null;){var S=p.dependencies;if(S!==null){y=p.child;for(var N=S.firstContext;N!==null;){if(N.context===l){if(p.tag===1){N=dr(-1,o&-o),N.tag=2;var P=p.updateQueue;if(P!==null){P=P.shared;var J=P.pending;J===null?N.next=N:(N.next=J.next,J.next=N),P.pending=N}}p.lanes|=o,N=p.alternate,N!==null&&(N.lanes|=o),rc(p.return,o,s),S.lanes|=o;break}N=N.next}}else if(p.tag===10)y=p.type===s.type?null:p.child;else if(p.tag===18){if(y=p.return,y===null)throw Error(t(341));y.lanes|=o,S=y.alternate,S!==null&&(S.lanes|=o),rc(y,o,s),y=p.sibling}else y=p.child;if(y!==null)y.return=p;else for(y=p;y!==null;){if(y===s){y=null;break}if(p=y.sibling,p!==null){p.return=y.return,y=p;break}y=y.return}p=y}Ct(r,s,d.children,o),s=s.child}return s;case 9:return d=s.type,l=s.pendingProps.children,ei(s,o),d=sn(d),l=l(d),s.flags|=1,Ct(r,s,l,o),s.child;case 14:return l=s.type,d=Nn(l,s.pendingProps),d=Nn(l.type,d),pp(r,s,l,d,o);case 15:return mp(r,s,s.type,s.pendingProps,o);case 17:return l=s.type,d=s.pendingProps,d=s.elementType===l?d:Nn(l,d),Ea(r,s),s.tag=1,Et(l)?(r=!0,va(s)):r=!1,ei(s,o),op(s,l,d),xc(s,l,d,o),_c(null,s,l,!0,r,o);case 19:return _p(r,s,o);case 22:return yp(r,s,o)}throw Error(t(156,s.tag))};function Yp(r,s){return kf(r,s)}function Yx(r,s,o,l){this.tag=r,this.key=o,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=s,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=l,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ln(r,s,o,l){return new Yx(r,s,o,l)}function Vc(r){return r=r.prototype,!(!r||!r.isReactComponent)}function Qx(r){if(typeof r=="function")return Vc(r)?1:0;if(r!=null){if(r=r.$$typeof,r===ee)return 11;if(r===ae)return 14}return 2}function Kr(r,s){var o=r.alternate;return o===null?(o=ln(r.tag,s,r.key,r.mode),o.elementType=r.elementType,o.type=r.type,o.stateNode=r.stateNode,o.alternate=r,r.alternate=o):(o.pendingProps=s,o.type=r.type,o.flags=0,o.subtreeFlags=0,o.deletions=null),o.flags=r.flags&14680064,o.childLanes=r.childLanes,o.lanes=r.lanes,o.child=r.child,o.memoizedProps=r.memoizedProps,o.memoizedState=r.memoizedState,o.updateQueue=r.updateQueue,s=r.dependencies,o.dependencies=s===null?null:{lanes:s.lanes,firstContext:s.firstContext},o.sibling=r.sibling,o.index=r.index,o.ref=r.ref,o}function Ya(r,s,o,l,d,p){var y=2;if(l=r,typeof r=="function")Vc(r)&&(y=1);else if(typeof r=="string")y=5;else e:switch(r){case U:return Ns(o.children,d,p,s);case G:y=8,d|=8;break;case V:return r=ln(12,o,s,d|2),r.elementType=V,r.lanes=p,r;case X:return r=ln(13,o,s,d),r.elementType=X,r.lanes=p,r;case ie:return r=ln(19,o,s,d),r.elementType=ie,r.lanes=p,r;case se:return Qa(o,d,p,s);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case Q:y=10;break e;case z:y=9;break e;case ee:y=11;break e;case ae:y=14;break e;case re:y=16,l=null;break e}throw Error(t(130,r==null?r:typeof r,""))}return s=ln(y,o,s,d),s.elementType=r,s.type=l,s.lanes=p,s}function Ns(r,s,o,l){return r=ln(7,r,l,s),r.lanes=o,r}function Qa(r,s,o,l){return r=ln(22,r,l,s),r.elementType=se,r.lanes=o,r.stateNode={isHidden:!1},r}function Wc(r,s,o){return r=ln(6,r,null,s),r.lanes=o,r}function Hc(r,s,o){return s=ln(4,r.children!==null?r.children:[],r.key,s),s.lanes=o,s.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},s}function Kx(r,s,o,l,d){this.tag=s,this.containerInfo=r,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=vu(0),this.expirationTimes=vu(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=vu(0),this.identifierPrefix=l,this.onRecoverableError=d,this.mutableSourceEagerHydrationData=null}function Gc(r,s,o,l,d,p,y,S,N){return r=new Kx(r,s,o,S,N),s===1?(s=1,p===!0&&(s|=8)):s=0,p=ln(3,null,null,s),r.current=p,p.stateNode=r,p.memoizedState={element:l,isDehydrated:o,cache:null,transitions:null,pendingSuspenseBoundaries:null},ic(p),r}function Jx(r,s,o){var l=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),Zc.exports=ub(),Zc.exports}var am;function db(){if(am)return tl;am=1;var n=cb();return tl.createRoot=n.createRoot,tl.hydrateRoot=n.hydrateRoot,tl}var fb=db();function Sr(n){return n.split(".").at(-1)||n}function Fn(n,e){const t=Sr(n);if(e.filter(a=>Sr(a)===t).length<2)return t;const i=n.indexOf(".");return i>0?`${n.slice(0,i)}_${t}`:t}const er="\0__null__";function hb(n){return String(n||"").replaceAll("_"," ").replaceAll("."," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}function gy(n,e={}){if(n==null||n==="")return"—";const t=typeof n=="number"?n:Number(n);if(!Number.isFinite(t))return String(n);const i=String(e.format||"").toLowerCase();if(e.style==="percent"||i.includes("%")||i.includes("percent")||i.includes("pct")||e.type==="ratio")return(e.style==="percent"?t:Math.abs(t)<=1?t*100:t).toLocaleString(void 0,{maximumFractionDigits:e.maximumFractionDigits??1,style:e.style==="percent"?"percent":"decimal"})+(e.style==="percent"?"":"%");const u=e.style==="currency"||e.currency||i.includes("$")||i.includes("usd")||i.includes("currency")||i.includes("dollar");return t.toLocaleString(void 0,{currency:u?e.currency||"USD":void 0,maximumFractionDigits:e.maximumFractionDigits??2,notation:e.compact?"compact":"standard",style:u?"currency":"decimal"})}function pb(n,e={}){return gy(n,{...e,compact:!0,maximumFractionDigits:e.maximumFractionDigits??1})}function mb(n,e,t){const i=t>0&&n.length>t,a=i?Math.ceil(n.length/t):1,u=Math.max(0,Math.min(e,a-1)),f=i?u*t:0;return{paginate:i,pageCount:a,safePage:u,start:f,visibleRows:i?n.slice(f,f+t):n}}function rs(n){return n===er||n===""?"—":n}function Le(n){return hb(n)}function pt(n,e={}){return gy(n,e)}function Wt(n,e={}){return pb(n,e)}function vy(n){return!Number.isFinite(n)||n===0?"neutral":n>0?"positive":"negative"}function yb(n,e){return!Number.isFinite(n)||!Number.isFinite(e)||e<=0?{label:"—",tone:"neutral"}:{label:`${(n/e*100).toLocaleString(void 0,{maximumFractionDigits:1})}%`,tone:"neutral"}}function gb(n,e,t={}){if(e==null||!Number.isFinite(e)||!Number.isFinite(n))return{label:"—",tone:"neutral"};const i=n-e;return{label:`${i>0?"+":i<0?"−":""}${Wt(Math.abs(i),t)}`,tone:vy(i)}}function vb(n,e){if(e==null||!Number.isFinite(e)||e===0||!Number.isFinite(n))return{label:"—",tone:"neutral"};const t=(n-e)/Math.abs(e);return{label:`${(t*100).toLocaleString(void 0,{maximumFractionDigits:1,signDisplay:"exceptZero"})}%`,tone:vy(t)}}function xy(n,e){if(e==null||!Number.isFinite(e)||e===0||!Number.isFinite(n))return null;const t=(n-e)/Math.abs(e),i=(t*100).toLocaleString(void 0,{maximumFractionDigits:1,signDisplay:"exceptZero"}),a=t>0?"positive":t<0?"negative":"neutral";return{label:`${i}%`,tone:a}}function Tn(n){return`'${n.replaceAll("'","''")}'`}function xb(n){if(n.mode==="contains")return`contains ${Tn(n.pattern??"")}`;const{values:e}=n,t=n.mode==="exclude"?"is not":"is";return e.length===0?t:e.length===1?`${t} ${rs(e[0])}`:e.length<=2?`${t} ${e.map(rs).join(", ")}`:`${t} ${e.length} values`}const td=n=>n.public!==!1,by=/(^|_)(date|time|day|month|week|year|quarter|created|updated|timestamp|_at|_on)($|_)/i;function wy(n,e){if(e){const t=n.find(i=>i.name===e);if(t)return t}return n.find(t=>t.type==="time")??n.find(t=>by.test(t.name))}function bb(n,e){var f;const t=new Set;if(!n)return t;const i=new Set(e.map(h=>h.name)),a=n.match(/[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*/g)??[];for(const h of a){const[m]=h.split(".");i.has(m)&&t.add(m)}if(t.size)return t;const u=(f=n.match(/^[A-Za-z_][A-Za-z0-9_]*$/))==null?void 0:f[0];if(!u)return t;for(const h of e)h.metrics.some(m=>m.name===u)&&t.add(h.name);return t}function Sy(n,e){const t=new Set;for(const i of[n.base_metric,n.numerator,n.denominator,n.sql])for(const a of bb(i,e))t.add(a);return t.size===1?[...t][0]:void 0}function wb(n){const e=(n.models??[]).map(i=>{const a=(i.dimensions??[]).filter(td).map(h=>({ref:`${i.name}.${h.name}`,name:h.name,model:i.name,label:h.label||Le(h.name),description:h.description,type:h.type||"categorical",granularity:h.granularity,supportedGranularities:h.supported_granularities,format:h.format})),u=(i.metrics??[]).filter(td).map(h=>({ref:`${i.name}.${h.name}`,name:h.name,model:i.name,label:h.label||Le(h.name),description:h.description,agg:h.agg,type:h.type,format:h.format})),f=wy(a,i.default_time_dimension);return{name:i.name,label:Le(i.name),description:i.description,table:i.table,dimensions:a,metrics:u,timeDimension:f,defaultGrain:i.default_grain||(f==null?void 0:f.granularity)||"day"}}),t=(n.metrics??[]).filter(td).map(i=>({ref:i.name,name:i.name,ownerModel:Sy(i,e),baseMetric:i.base_metric,label:i.label||Le(i.name),description:i.description,type:i.type,format:i.format}));return{models:e,graphMetrics:t,dialect:n.dialect}}function Sb(n){const e=n??{},t=(e.models??[]).map(a=>{const u=(a.dimensions??[]).map(m=>({ref:`${a.name}.${m}`,name:m,model:a.name,label:Le(m),type:by.test(m)?"time":"categorical"})),f=(a.metrics??[]).map(m=>({ref:`${a.name}.${m}`,name:m,model:a.name,label:Le(m)})),h=wy(u);return{name:a.name,label:Le(a.name),table:a.table,dimensions:u,metrics:f,timeDimension:h,defaultGrain:(h==null?void 0:h.granularity)||"day"}}),i=(e.graph_metrics??[]).map(a=>({ref:a.name,name:a.name,ownerModel:Sy(a,t),baseMetric:a.base_metric,label:Le(a.name),type:a.type,description:a.description}));return{models:t,graphMetrics:i,joinablePairs:e.joinable_pairs??[]}}function _b(n,e){return{...n,joinablePairs:(e??{}).joinable_pairs??n.joinablePairs??[]}}function ji(n,e){const t=new Set;for(const i of n.joinablePairs??[])i.from===e&&t.add(i.to),i.to===e&&t.add(i.from);return n.graphMetrics.filter(i=>i.ownerModel?i.ownerModel===e||t.has(i.ownerModel):!0)}function Fe(n,e,t,i){function a(u){return u instanceof t?u:new t(function(f){f(u)})}return new(t||(t=Promise))(function(u,f){function h(v){try{g(i.next(v))}catch(x){f(x)}}function m(v){try{g(i.throw(v))}catch(x){f(x)}}function g(v){v.done?u(v.value):a(v.value).then(h,m)}g((i=i.apply(n,e||[])).next())})}function lm(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ae(n){return this instanceof Ae?(this.v=n,this):new Ae(n)}function qn(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),a,u=[];return a=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),h("next"),h("throw"),h("return",f),a[Symbol.asyncIterator]=function(){return this},a;function f(w){return function(j){return Promise.resolve(j).then(w,x)}}function h(w,j){i[w]&&(a[w]=function(C){return new Promise(function(O,H){u.push([w,C,O,H])>1||m(w,C)})},j&&(a[w]=j(a[w])))}function m(w,j){try{g(i[w](j))}catch(C){b(u[0][3],C)}}function g(w){w.value instanceof Ae?Promise.resolve(w.value.v).then(v,x):b(u[0][2],w)}function v(w){m("next",w)}function x(w){m("throw",w)}function b(w,j){w(j),u.shift(),u.length&&m(u[0][0],u[0][1])}}function fl(n){var e,t;return e={},i("next"),i("throw",function(a){throw a}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(a,u){e[a]=n[a]?function(f){return(t=!t)?{value:Ae(n[a](f)),done:!1}:u?u(f):f}:u}}function xi(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof lm=="function"?lm(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(u){t[u]=n[u]&&function(f){return new Promise(function(h,m){f=n[u](f),a(h,m,f.done,f.value)})}}function a(u,f,h,m){Promise.resolve(m).then(function(g){u({value:g,done:h})},f)}}const Nb=new TextDecoder("utf-8"),xd=n=>Nb.decode(n),jb=new TextEncoder,Bd=n=>jb.encode(n),kb=n=>typeof n=="number",Ib=n=>typeof n=="boolean",Ot=n=>typeof n=="function",En=n=>n!=null&&Object(n)===n,Ao=n=>En(n)&&Ot(n.then),nu=n=>En(n)&&Ot(n[Symbol.iterator]),Ed=n=>En(n)&&Ot(n[Symbol.asyncIterator]),bd=n=>En(n)&&En(n.schema),_y=n=>En(n)&&"done"in n&&"value"in n,Ny=n=>En(n)&&Ot(n.stat)&&kb(n.fd),jy=n=>En(n)&&Rd(n.body),ky=n=>"_getDOMStream"in n&&"_getNodeStream"in n,Rd=n=>En(n)&&Ot(n.cancel)&&Ot(n.getReader)&&!ky(n),Iy=n=>En(n)&&Ot(n.read)&&Ot(n.pipe)&&Ib(n.readable)&&!ky(n),Mb=n=>En(n)&&Ot(n.clear)&&Ot(n.bytes)&&Ot(n.position)&&Ot(n.setPosition)&&Ot(n.capacity)&&Ot(n.getBufferIdentifier)&&Ot(n.createLong),Ld=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function Db(n){const e=n[0]?[n[0]]:[];let t,i,a,u;for(let f,h,m=0,g=0,v=n.length;++mv+x.byteLength,0);let a,u,f,h=0,m=-1;const g=Math.min(e||Number.POSITIVE_INFINITY,i);for(const v=t.length;++mKe(Int32Array,n),cm=n=>Ke(BigInt64Array,n),$e=n=>Ke(Uint8Array,n),wd=n=>(n.next(),n);function*Cb(n,e){const t=function*(a){yield a},i=typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof Ld?t(e):nu(e)?e:t(e);return yield*wd((function*(a){let u=null;do u=a.next(yield Ke(n,u));while(!u.done)})(i[Symbol.iterator]())),new n}const Fb=n=>Cb(Uint8Array,n);function My(n,e){return qn(this,arguments,function*(){if(Ao(e))return yield Ae(yield Ae(yield*fl(xi(My(n,yield Ae(e))))));const i=function(f){return qn(this,arguments,function*(){yield yield Ae(yield Ae(f))})},a=function(f){return qn(this,arguments,function*(){yield Ae(yield*fl(xi(wd((function*(h){let m=null;do m=h.next(yield m==null?void 0:m.value);while(!m.done)})(f[Symbol.iterator]())))))})},u=typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof Ld?i(e):nu(e)?a(e):Ed(e)?e:i(e);return yield Ae(yield*fl(xi(wd((function(f){return qn(this,arguments,function*(){let h=null;do h=yield Ae(f.next(yield yield Ae(Ke(n,h))));while(!h.done)})})(u[Symbol.asyncIterator]()))))),yield Ae(new n)})}const Ob=n=>My(Uint8Array,n);function Tb(n,e){let t=0;const i=n.length;if(i!==e.length)return!1;if(i>0)do if(n[t]!==e[t])return!1;while(++t(n.next(),n);function*Ab(n){let e,t=!1,i=[],a,u,f,h=0;function m(){return u==="peek"?tr(i,f)[0]:([a,i,h]=tr(i,f),a)}({cmd:u,size:f}=(yield null)||{cmd:"read",size:0});const g=Fb(n)[Symbol.iterator]();try{do if({done:e,value:a}=Number.isNaN(f-h)?g.next():g.next(f-h),!e&&a.byteLength>0&&(i.push(a),h+=a.byteLength),e||f<=h)do({cmd:u,size:f}=yield m());while(f0&&(a.push(u),m+=u.byteLength),t||h<=m)do({cmd:f,size:h}=yield yield Ae(g()));while(h0&&(a.push($e(u)),m+=u.byteLength),t||h<=m)do({cmd:f,size:h}=yield yield Ae(g()));while(h{})}get closed(){return this.reader?this.reader.closed.catch(()=>{}):Promise.resolve()}releaseLock(){this.reader&&this.reader.releaseLock(),this.reader=null}cancel(e){return Fe(this,void 0,void 0,function*(){const{reader:t,source:i}=this;t&&(yield t.cancel(e).catch(()=>{})),i&&i.locked&&this.releaseLock()})}read(e){return Fe(this,void 0,void 0,function*(){if(e===0)return{done:this.reader==null,value:new Uint8Array(0)};const t=yield this.reader.read();return!t.done&&(t.value=$e(t)),t})}}const nd=(n,e)=>{const t=a=>i([e,a]);let i;return[e,t,new Promise(a=>(i=a)&&n.once(e,t))]};function Lb(n){return qn(this,arguments,function*(){const t=[];let i="error",a=!1,u=null,f,h,m=0,g=[],v;function x(){return f==="peek"?tr(g,h)[0]:([v,g,m]=tr(g,h),v)}if({cmd:f,size:h}=(yield yield Ae(null))||{cmd:"read",size:0},n.isTTY)return yield yield Ae(new Uint8Array(0)),yield Ae(null);try{t[0]=nd(n,"end"),t[1]=nd(n,"error");do{if(t[2]=nd(n,"readable"),[i,u]=yield Ae(Promise.race(t.map(w=>w[2]))),i==="error")break;if((a=i==="end")||(Number.isFinite(h-m)?(v=$e(n.read(h-m)),v.byteLength0&&(g.push(v),m+=v.byteLength)),a||h<=m)do({cmd:f,size:h}=yield yield Ae(x()));while(h{for(const[H,L]of w)n.off(H,L);try{const H=n.destroy;H&&H.call(n,j),j=void 0}catch(H){j=H||j}finally{j!=null?O(j):C()}})}})}var ht;(function(n){n[n.V1=0]="V1",n[n.V2=1]="V2",n[n.V3=2]="V3",n[n.V4=3]="V4",n[n.V5=4]="V5"})(ht||(ht={}));var Ht;(function(n){n[n.Sparse=0]="Sparse",n[n.Dense=1]="Dense"})(Ht||(Ht={}));var Dt;(function(n){n[n.HALF=0]="HALF",n[n.SINGLE=1]="SINGLE",n[n.DOUBLE=2]="DOUBLE"})(Dt||(Dt={}));var gn;(function(n){n[n.DAY=0]="DAY",n[n.MILLISECOND=1]="MILLISECOND"})(gn||(gn={}));var _e;(function(n){n[n.SECOND=0]="SECOND",n[n.MILLISECOND=1]="MILLISECOND",n[n.MICROSECOND=2]="MICROSECOND",n[n.NANOSECOND=3]="NANOSECOND"})(_e||(_e={}));var nr;(function(n){n[n.YEAR_MONTH=0]="YEAR_MONTH",n[n.DAY_TIME=1]="DAY_TIME",n[n.MONTH_DAY_NANO=2]="MONTH_DAY_NANO"})(nr||(nr={}));const rd=2,Qn=4,br=4,He=4,es=new Int32Array(2),dm=new Float32Array(es.buffer),fm=new Float64Array(es.buffer),rl=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Sd;(function(n){n[n.UTF8_BYTES=1]="UTF8_BYTES",n[n.UTF16_STRING=2]="UTF16_STRING"})(Sd||(Sd={}));let ki=class Dy{constructor(e){this.bytes_=e,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(e){return new Dy(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return BigInt.asIntN(64,BigInt(this.readUint32(e))+(BigInt(this.readUint32(e+4))<>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,Number(BigInt.asIntN(32,t))),this.writeInt32(e+4,Number(BigInt.asIntN(32,t>>BigInt(32))))}writeUint64(e,t){this.writeUint32(e,Number(BigInt.asUintN(32,t))),this.writeUint32(e+4,Number(BigInt.asUintN(32,t>>BigInt(32))))}writeFloat32(e,t){dm[0]=t,this.writeInt32(e,es[0])}writeFloat64(e,t){fm[0]=t,this.writeInt32(e,es[rl?0:1]),this.writeInt32(e+4,es[rl?1:0])}getBufferIdentifier(){if(this.bytes_.lengththis.minalign&&(this.minalign=e);const i=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space=0&&this.vtable[t]==0;t--);const i=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);const a=2;this.addInt16(e-this.object_start);const u=(i+a)*rd;this.addInt16(u);let f=0;const h=this.space;e:for(t=0;t=0;f--)this.writeInt8(u.charCodeAt(f))}this.prep(this.minalign,Qn+a),this.addOffset(e),a&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){const i=this.bb.capacity()-e,a=i-this.bb.readInt32(i);if(!(t=0;i--)e.addInt32(t[i]);return e.endVector()}static startTypeIdsVector(e,t){e.startVector(4,t,4)}static endUnion(e){return e.endObject()}static createUnion(e,t,i){return Vt.startUnion(e),Vt.addMode(e,t),Vt.addTypeIds(e,i),Vt.endUnion(e)}}let xm=class Fo{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsUtf8(e,t){return(t||new Fo).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsUtf8(e,t){return e.setPosition(e.position()+He),(t||new Fo).__init(e.readInt32(e.position())+e.position(),e)}static startUtf8(e){e.startObject(0)}static endUtf8(e){return e.endObject()}static createUtf8(e){return Fo.startUtf8(e),Fo.endUtf8(e)}};var Ze;(function(n){n[n.NONE=0]="NONE",n[n.Null=1]="Null",n[n.Int=2]="Int",n[n.FloatingPoint=3]="FloatingPoint",n[n.Binary=4]="Binary",n[n.Utf8=5]="Utf8",n[n.Bool=6]="Bool",n[n.Decimal=7]="Decimal",n[n.Date=8]="Date",n[n.Time=9]="Time",n[n.Timestamp=10]="Timestamp",n[n.Interval=11]="Interval",n[n.List=12]="List",n[n.Struct_=13]="Struct_",n[n.Union=14]="Union",n[n.FixedSizeBinary=15]="FixedSizeBinary",n[n.FixedSizeList=16]="FixedSizeList",n[n.Map=17]="Map",n[n.Duration=18]="Duration",n[n.LargeBinary=19]="LargeBinary",n[n.LargeUtf8=20]="LargeUtf8",n[n.LargeList=21]="LargeList",n[n.RunEndEncoded=22]="RunEndEncoded"})(Ze||(Ze={}));let dn=class vl{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsField(e,t){return(t||new vl).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsField(e,t){return e.setPosition(e.position()+He),(t||new vl).__init(e.readInt32(e.position())+e.position(),e)}name(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}nullable(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}typeType(){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readUint8(this.bb_pos+e):Ze.NONE}type(e){const t=this.bb.__offset(this.bb_pos,10);return t?this.bb.__union(e,this.bb_pos+t):null}dictionary(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new wr).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}children(e,t){const i=this.bb.__offset(this.bb_pos,14);return i?(t||new vl).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}childrenLength(){const e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,16);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__vector_len(this.bb_pos+e):0}static startField(e){e.startObject(7)}static addName(e,t){e.addFieldOffset(0,t,0)}static addNullable(e,t){e.addFieldInt8(1,+t,0)}static addTypeType(e,t){e.addFieldInt8(2,t,Ze.NONE)}static addType(e,t){e.addFieldOffset(3,t,0)}static addDictionary(e,t){e.addFieldOffset(4,t,0)}static addChildren(e,t){e.addFieldOffset(5,t,0)}static createChildrenVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startChildrenVector(e,t){e.startVector(4,t,4)}static addCustomMetadata(e,t){e.addFieldOffset(6,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endField(e){return e.endObject()}},Gn=class mr{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSchema(e,t){return(t||new mr).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSchema(e,t){return e.setPosition(e.position()+He),(t||new mr).__init(e.readInt32(e.position())+e.position(),e)}endianness(){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):Ii.Little}fields(e,t){const i=this.bb.__offset(this.bb_pos,6);return i?(t||new dn).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}fieldsLength(){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,8);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}features(e){const t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+e*8):BigInt(0)}featuresLength(){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__vector_len(this.bb_pos+e):0}static startSchema(e){e.startObject(4)}static addEndianness(e,t){e.addFieldInt16(0,t,Ii.Little)}static addFields(e,t){e.addFieldOffset(1,t,0)}static createFieldsVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startFieldsVector(e,t){e.startVector(4,t,4)}static addCustomMetadata(e,t){e.addFieldOffset(2,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static addFeatures(e,t){e.addFieldOffset(3,t,0)}static createFeaturesVector(e,t){e.startVector(8,t.length,8);for(let i=t.length-1;i>=0;i--)e.addInt64(t[i]);return e.endVector()}static startFeaturesVector(e,t){e.startVector(8,t,8)}static endSchema(e){return e.endObject()}static finishSchemaBuffer(e,t){e.finish(t)}static finishSizePrefixedSchemaBuffer(e,t){e.finish(t,void 0,!0)}static createSchema(e,t,i,a,u){return mr.startSchema(e),mr.addEndianness(e,t),mr.addFields(e,i),mr.addCustomMetadata(e,a),mr.addFeatures(e,u),mr.endSchema(e)}};var Ve;(function(n){n[n.NONE=0]="NONE",n[n.Schema=1]="Schema",n[n.DictionaryBatch=2]="DictionaryBatch",n[n.RecordBatch=3]="RecordBatch",n[n.Tensor=4]="Tensor",n[n.SparseTensor=5]="SparseTensor"})(Ve||(Ve={}));var D;(function(n){n[n.NONE=0]="NONE",n[n.Null=1]="Null",n[n.Int=2]="Int",n[n.Float=3]="Float",n[n.Binary=4]="Binary",n[n.Utf8=5]="Utf8",n[n.Bool=6]="Bool",n[n.Decimal=7]="Decimal",n[n.Date=8]="Date",n[n.Time=9]="Time",n[n.Timestamp=10]="Timestamp",n[n.Interval=11]="Interval",n[n.List=12]="List",n[n.Struct=13]="Struct",n[n.Union=14]="Union",n[n.FixedSizeBinary=15]="FixedSizeBinary",n[n.FixedSizeList=16]="FixedSizeList",n[n.Map=17]="Map",n[n.Duration=18]="Duration",n[n.LargeBinary=19]="LargeBinary",n[n.LargeUtf8=20]="LargeUtf8",n[n.Dictionary=-1]="Dictionary",n[n.Int8=-2]="Int8",n[n.Int16=-3]="Int16",n[n.Int32=-4]="Int32",n[n.Int64=-5]="Int64",n[n.Uint8=-6]="Uint8",n[n.Uint16=-7]="Uint16",n[n.Uint32=-8]="Uint32",n[n.Uint64=-9]="Uint64",n[n.Float16=-10]="Float16",n[n.Float32=-11]="Float32",n[n.Float64=-12]="Float64",n[n.DateDay=-13]="DateDay",n[n.DateMillisecond=-14]="DateMillisecond",n[n.TimestampSecond=-15]="TimestampSecond",n[n.TimestampMillisecond=-16]="TimestampMillisecond",n[n.TimestampMicrosecond=-17]="TimestampMicrosecond",n[n.TimestampNanosecond=-18]="TimestampNanosecond",n[n.TimeSecond=-19]="TimeSecond",n[n.TimeMillisecond=-20]="TimeMillisecond",n[n.TimeMicrosecond=-21]="TimeMicrosecond",n[n.TimeNanosecond=-22]="TimeNanosecond",n[n.DenseUnion=-23]="DenseUnion",n[n.SparseUnion=-24]="SparseUnion",n[n.IntervalDayTime=-25]="IntervalDayTime",n[n.IntervalYearMonth=-26]="IntervalYearMonth",n[n.DurationSecond=-27]="DurationSecond",n[n.DurationMillisecond=-28]="DurationMillisecond",n[n.DurationMicrosecond=-29]="DurationMicrosecond",n[n.DurationNanosecond=-30]="DurationNanosecond"})(D||(D={}));var gr;(function(n){n[n.OFFSET=0]="OFFSET",n[n.DATA=1]="DATA",n[n.VALIDITY=2]="VALIDITY",n[n.TYPE=3]="TYPE"})(gr||(gr={}));const Ub=void 0;function Bo(n){if(n===null)return"null";if(n===Ub)return"undefined";switch(typeof n){case"number":return`${n}`;case"bigint":return`${n}`;case"string":return`"${n}"`}return typeof n[Symbol.toPrimitive]=="function"?n[Symbol.toPrimitive]("string"):ArrayBuffer.isView(n)?n instanceof BigInt64Array||n instanceof BigUint64Array?`[${[...n].map(e=>Bo(e))}]`:`[${n}]`:ArrayBuffer.isView(n)?`[${n}]`:JSON.stringify(n,(e,t)=>typeof t=="bigint"?`${t}`:t)}function tt(n){if(typeof n=="bigint"&&(nNumber.MAX_SAFE_INTEGER))throw new TypeError(`${n} is not safe to convert to a number.`);return Number(n)}function Ay(n,e){return tt(n/e)+tt(n%e)/tt(e)}const $b=Symbol.for("isArrowBigNum");function Ln(n,...e){return e.length===0?Object.setPrototypeOf(Ke(this.TypedArray,n),this.constructor.prototype):Object.setPrototypeOf(new this.TypedArray(n,...e),this.constructor.prototype)}Ln.prototype[$b]=!0;Ln.prototype.toJSON=function(){return`"${Ro(this)}"`};Ln.prototype.valueOf=function(n){return By(this,n)};Ln.prototype.toString=function(){return Ro(this)};Ln.prototype[Symbol.toPrimitive]=function(n="default"){switch(n){case"number":return By(this);case"string":return Ro(this);case"default":return Vb(this)}return Ro(this)};function bi(...n){return Ln.apply(this,n)}function wi(...n){return Ln.apply(this,n)}function Eo(...n){return Ln.apply(this,n)}Object.setPrototypeOf(bi.prototype,Object.create(Int32Array.prototype));Object.setPrototypeOf(wi.prototype,Object.create(Uint32Array.prototype));Object.setPrototypeOf(Eo.prototype,Object.create(Uint32Array.prototype));Object.assign(bi.prototype,Ln.prototype,{constructor:bi,signed:!0,TypedArray:Int32Array,BigIntArray:BigInt64Array});Object.assign(wi.prototype,Ln.prototype,{constructor:wi,signed:!1,TypedArray:Uint32Array,BigIntArray:BigUint64Array});Object.assign(Eo.prototype,Ln.prototype,{constructor:Eo,signed:!0,TypedArray:Uint32Array,BigIntArray:BigUint64Array});const Pb=BigInt(4294967296)*BigInt(4294967296),zb=Pb-BigInt(1);function By(n,e){const{buffer:t,byteOffset:i,byteLength:a,signed:u}=n,f=new BigUint64Array(t,i,a/8),h=u&&f.at(-1)&BigInt(1)<=0)return sd(n);e=e.slice();let i=1;for(let u=0;u(n.children=null,n.ArrayType=Array,n.OffsetArrayType=Int32Array,n[Symbol.toStringTag]="DataType"))(me.prototype);class ss extends me{constructor(){super(D.Null)}toString(){return"Null"}}Ry=Symbol.toStringTag;ss[Ry]=(n=>n[Symbol.toStringTag]="Null")(ss.prototype);class Ds extends me{constructor(e,t){super(D.Int),this.isSigned=e,this.bitWidth=t}get ArrayType(){switch(this.bitWidth){case 8:return this.isSigned?Int8Array:Uint8Array;case 16:return this.isSigned?Int16Array:Uint16Array;case 32:return this.isSigned?Int32Array:Uint32Array;case 64:return this.isSigned?BigInt64Array:BigUint64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`${this.isSigned?"I":"Ui"}nt${this.bitWidth}`}}Ly=Symbol.toStringTag;Ds[Ly]=(n=>(n.isSigned=null,n.bitWidth=null,n[Symbol.toStringTag]="Int"))(Ds.prototype);class Lo extends Ds{constructor(){super(!0,32)}get ArrayType(){return Int32Array}}Object.defineProperty(Lo.prototype,"ArrayType",{value:Int32Array});class jl extends me{constructor(e){super(D.Float),this.precision=e}get ArrayType(){switch(this.precision){case Dt.HALF:return Uint16Array;case Dt.SINGLE:return Float32Array;case Dt.DOUBLE:return Float64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`Float${this.precision<<5||16}`}}Uy=Symbol.toStringTag;jl[Uy]=(n=>(n.precision=null,n[Symbol.toStringTag]="Float"))(jl.prototype);class kl extends me{constructor(){super(D.Binary)}toString(){return"Binary"}}$y=Symbol.toStringTag;kl[$y]=(n=>(n.ArrayType=Uint8Array,n[Symbol.toStringTag]="Binary"))(kl.prototype);class Il extends me{constructor(){super(D.LargeBinary)}toString(){return"LargeBinary"}}Py=Symbol.toStringTag;Il[Py]=(n=>(n.ArrayType=Uint8Array,n.OffsetArrayType=BigInt64Array,n[Symbol.toStringTag]="LargeBinary"))(Il.prototype);class Ml extends me{constructor(){super(D.Utf8)}toString(){return"Utf8"}}zy=Symbol.toStringTag;Ml[zy]=(n=>(n.ArrayType=Uint8Array,n[Symbol.toStringTag]="Utf8"))(Ml.prototype);class Dl extends me{constructor(){super(D.LargeUtf8)}toString(){return"LargeUtf8"}}Vy=Symbol.toStringTag;Dl[Vy]=(n=>(n.ArrayType=Uint8Array,n.OffsetArrayType=BigInt64Array,n[Symbol.toStringTag]="LargeUtf8"))(Dl.prototype);class Cl extends me{constructor(){super(D.Bool)}toString(){return"Bool"}}Wy=Symbol.toStringTag;Cl[Wy]=(n=>(n.ArrayType=Uint8Array,n[Symbol.toStringTag]="Bool"))(Cl.prototype);class Fl extends me{constructor(e,t,i=128){super(D.Decimal),this.scale=e,this.precision=t,this.bitWidth=i}toString(){return`Decimal[${this.precision}e${this.scale>0?"+":""}${this.scale}]`}}Hy=Symbol.toStringTag;Fl[Hy]=(n=>(n.scale=null,n.precision=null,n.ArrayType=Uint32Array,n[Symbol.toStringTag]="Decimal"))(Fl.prototype);class Ol extends me{constructor(e){super(D.Date),this.unit=e}toString(){return`Date${(this.unit+1)*32}<${gn[this.unit]}>`}get ArrayType(){return this.unit===gn.DAY?Int32Array:BigInt64Array}}Gy=Symbol.toStringTag;Ol[Gy]=(n=>(n.unit=null,n[Symbol.toStringTag]="Date"))(Ol.prototype);class Tl extends me{constructor(e,t){super(D.Time),this.unit=e,this.bitWidth=t}toString(){return`Time${this.bitWidth}<${_e[this.unit]}>`}get ArrayType(){switch(this.bitWidth){case 32:return Int32Array;case 64:return BigInt64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}}Yy=Symbol.toStringTag;Tl[Yy]=(n=>(n.unit=null,n.bitWidth=null,n[Symbol.toStringTag]="Time"))(Tl.prototype);class Al extends me{constructor(e,t){super(D.Timestamp),this.unit=e,this.timezone=t}toString(){return`Timestamp<${_e[this.unit]}${this.timezone?`, ${this.timezone}`:""}>`}}Qy=Symbol.toStringTag;Al[Qy]=(n=>(n.unit=null,n.timezone=null,n.ArrayType=BigInt64Array,n[Symbol.toStringTag]="Timestamp"))(Al.prototype);class Bl extends me{constructor(e){super(D.Interval),this.unit=e}toString(){return`Interval<${nr[this.unit]}>`}}Ky=Symbol.toStringTag;Bl[Ky]=(n=>(n.unit=null,n.ArrayType=Int32Array,n[Symbol.toStringTag]="Interval"))(Bl.prototype);class El extends me{constructor(e){super(D.Duration),this.unit=e}toString(){return`Duration<${_e[this.unit]}>`}}Jy=Symbol.toStringTag;El[Jy]=(n=>(n.unit=null,n.ArrayType=BigInt64Array,n[Symbol.toStringTag]="Duration"))(El.prototype);class Rl extends me{constructor(e){super(D.List),this.children=[e]}toString(){return`List<${this.valueType}>`}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}}qy=Symbol.toStringTag;Rl[qy]=(n=>(n.children=null,n[Symbol.toStringTag]="List"))(Rl.prototype);class Tt extends me{constructor(e){super(D.Struct),this.children=e}toString(){return`Struct<{${this.children.map(e=>`${e.name}:${e.type}`).join(", ")}}>`}}Zy=Symbol.toStringTag;Tt[Zy]=(n=>(n.children=null,n[Symbol.toStringTag]="Struct"))(Tt.prototype);class Ll extends me{constructor(e,t,i){super(D.Union),this.mode=e,this.children=i,this.typeIds=t=Int32Array.from(t),this.typeIdToChildIndex=t.reduce((a,u,f)=>(a[u]=f)&&a||a,Object.create(null))}toString(){return`${this[Symbol.toStringTag]}<${this.children.map(e=>`${e.type}`).join(" | ")}>`}}Xy=Symbol.toStringTag;Ll[Xy]=(n=>(n.mode=null,n.typeIds=null,n.children=null,n.typeIdToChildIndex=null,n.ArrayType=Int8Array,n[Symbol.toStringTag]="Union"))(Ll.prototype);class Ul extends me{constructor(e){super(D.FixedSizeBinary),this.byteWidth=e}toString(){return`FixedSizeBinary[${this.byteWidth}]`}}eg=Symbol.toStringTag;Ul[eg]=(n=>(n.byteWidth=null,n.ArrayType=Uint8Array,n[Symbol.toStringTag]="FixedSizeBinary"))(Ul.prototype);class $l extends me{constructor(e,t){super(D.FixedSizeList),this.listSize=e,this.children=[t]}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}toString(){return`FixedSizeList[${this.listSize}]<${this.valueType}>`}}tg=Symbol.toStringTag;$l[tg]=(n=>(n.children=null,n.listSize=null,n[Symbol.toStringTag]="FixedSizeList"))($l.prototype);class Pl extends me{constructor(e,t=!1){var i,a,u;if(super(D.Map),this.children=[e],this.keysSorted=t,e&&(e.name="entries",!((i=e==null?void 0:e.type)===null||i===void 0)&&i.children)){const f=(a=e==null?void 0:e.type)===null||a===void 0?void 0:a.children[0];f&&(f.name="key");const h=(u=e==null?void 0:e.type)===null||u===void 0?void 0:u.children[1];h&&(h.name="value")}}get keyType(){return this.children[0].type.children[0].type}get valueType(){return this.children[0].type.children[1].type}get childType(){return this.children[0].type}toString(){return`Map<{${this.children[0].type.children.map(e=>`${e.name}:${e.type}`).join(", ")}}>`}}ng=Symbol.toStringTag;Pl[ng]=(n=>(n.children=null,n.keysSorted=null,n[Symbol.toStringTag]="Map_"))(Pl.prototype);const Wb=(n=>()=>++n)(-1);class Mi extends me{constructor(e,t,i,a){super(D.Dictionary),this.indices=t,this.dictionary=e,this.isOrdered=a||!1,this.id=i==null?Wb():tt(i)}get children(){return this.dictionary.children}get valueType(){return this.dictionary}get ArrayType(){return this.dictionary.ArrayType}toString(){return`Dictionary<${this.indices}, ${this.dictionary}>`}}rg=Symbol.toStringTag;Mi[rg]=(n=>(n.id=null,n.indices=null,n.isOrdered=null,n.dictionary=null,n[Symbol.toStringTag]="Dictionary"))(Mi.prototype);function vr(n){const e=n;switch(n.typeId){case D.Decimal:return n.bitWidth/32;case D.Interval:return 1+e.unit;case D.FixedSizeList:return e.listSize;case D.FixedSizeBinary:return e.byteWidth;default:return 1}}class Re{visitMany(e,...t){return e.map((i,a)=>this.visit(i,...t.map(u=>u[a])))}visit(...e){return this.getVisitFn(e[0],!1).apply(this,e)}getVisitFn(e,t=!0){return Hb(this,e,t)}getVisitFnByTypeId(e,t=!0){return mi(this,e,t)}visitNull(e,...t){return null}visitBool(e,...t){return null}visitInt(e,...t){return null}visitFloat(e,...t){return null}visitUtf8(e,...t){return null}visitLargeUtf8(e,...t){return null}visitBinary(e,...t){return null}visitLargeBinary(e,...t){return null}visitFixedSizeBinary(e,...t){return null}visitDate(e,...t){return null}visitTimestamp(e,...t){return null}visitTime(e,...t){return null}visitDecimal(e,...t){return null}visitList(e,...t){return null}visitStruct(e,...t){return null}visitUnion(e,...t){return null}visitDictionary(e,...t){return null}visitInterval(e,...t){return null}visitDuration(e,...t){return null}visitFixedSizeList(e,...t){return null}visitMap(e,...t){return null}}function Hb(n,e,t=!0){return typeof e=="number"?mi(n,e,t):typeof e=="string"&&e in D?mi(n,D[e],t):e&&e instanceof me?mi(n,bm(e),t):e!=null&&e.type&&e.type instanceof me?mi(n,bm(e.type),t):mi(n,D.NONE,t)}function mi(n,e,t=!0){let i=null;switch(e){case D.Null:i=n.visitNull;break;case D.Bool:i=n.visitBool;break;case D.Int:i=n.visitInt;break;case D.Int8:i=n.visitInt8||n.visitInt;break;case D.Int16:i=n.visitInt16||n.visitInt;break;case D.Int32:i=n.visitInt32||n.visitInt;break;case D.Int64:i=n.visitInt64||n.visitInt;break;case D.Uint8:i=n.visitUint8||n.visitInt;break;case D.Uint16:i=n.visitUint16||n.visitInt;break;case D.Uint32:i=n.visitUint32||n.visitInt;break;case D.Uint64:i=n.visitUint64||n.visitInt;break;case D.Float:i=n.visitFloat;break;case D.Float16:i=n.visitFloat16||n.visitFloat;break;case D.Float32:i=n.visitFloat32||n.visitFloat;break;case D.Float64:i=n.visitFloat64||n.visitFloat;break;case D.Utf8:i=n.visitUtf8;break;case D.LargeUtf8:i=n.visitLargeUtf8;break;case D.Binary:i=n.visitBinary;break;case D.LargeBinary:i=n.visitLargeBinary;break;case D.FixedSizeBinary:i=n.visitFixedSizeBinary;break;case D.Date:i=n.visitDate;break;case D.DateDay:i=n.visitDateDay||n.visitDate;break;case D.DateMillisecond:i=n.visitDateMillisecond||n.visitDate;break;case D.Timestamp:i=n.visitTimestamp;break;case D.TimestampSecond:i=n.visitTimestampSecond||n.visitTimestamp;break;case D.TimestampMillisecond:i=n.visitTimestampMillisecond||n.visitTimestamp;break;case D.TimestampMicrosecond:i=n.visitTimestampMicrosecond||n.visitTimestamp;break;case D.TimestampNanosecond:i=n.visitTimestampNanosecond||n.visitTimestamp;break;case D.Time:i=n.visitTime;break;case D.TimeSecond:i=n.visitTimeSecond||n.visitTime;break;case D.TimeMillisecond:i=n.visitTimeMillisecond||n.visitTime;break;case D.TimeMicrosecond:i=n.visitTimeMicrosecond||n.visitTime;break;case D.TimeNanosecond:i=n.visitTimeNanosecond||n.visitTime;break;case D.Decimal:i=n.visitDecimal;break;case D.List:i=n.visitList;break;case D.Struct:i=n.visitStruct;break;case D.Union:i=n.visitUnion;break;case D.DenseUnion:i=n.visitDenseUnion||n.visitUnion;break;case D.SparseUnion:i=n.visitSparseUnion||n.visitUnion;break;case D.Dictionary:i=n.visitDictionary;break;case D.Interval:i=n.visitInterval;break;case D.IntervalDayTime:i=n.visitIntervalDayTime||n.visitInterval;break;case D.IntervalYearMonth:i=n.visitIntervalYearMonth||n.visitInterval;break;case D.Duration:i=n.visitDuration;break;case D.DurationSecond:i=n.visitDurationSecond||n.visitDuration;break;case D.DurationMillisecond:i=n.visitDurationMillisecond||n.visitDuration;break;case D.DurationMicrosecond:i=n.visitDurationMicrosecond||n.visitDuration;break;case D.DurationNanosecond:i=n.visitDurationNanosecond||n.visitDuration;break;case D.FixedSizeList:i=n.visitFixedSizeList;break;case D.Map:i=n.visitMap;break}if(typeof i=="function")return i;if(!t)return()=>null;throw new Error(`Unrecognized type '${D[e]}'`)}function bm(n){switch(n.typeId){case D.Null:return D.Null;case D.Int:{const{bitWidth:e,isSigned:t}=n;switch(e){case 8:return t?D.Int8:D.Uint8;case 16:return t?D.Int16:D.Uint16;case 32:return t?D.Int32:D.Uint32;case 64:return t?D.Int64:D.Uint64}return D.Int}case D.Float:switch(n.precision){case Dt.HALF:return D.Float16;case Dt.SINGLE:return D.Float32;case Dt.DOUBLE:return D.Float64}return D.Float;case D.Binary:return D.Binary;case D.LargeBinary:return D.LargeBinary;case D.Utf8:return D.Utf8;case D.LargeUtf8:return D.LargeUtf8;case D.Bool:return D.Bool;case D.Decimal:return D.Decimal;case D.Time:switch(n.unit){case _e.SECOND:return D.TimeSecond;case _e.MILLISECOND:return D.TimeMillisecond;case _e.MICROSECOND:return D.TimeMicrosecond;case _e.NANOSECOND:return D.TimeNanosecond}return D.Time;case D.Timestamp:switch(n.unit){case _e.SECOND:return D.TimestampSecond;case _e.MILLISECOND:return D.TimestampMillisecond;case _e.MICROSECOND:return D.TimestampMicrosecond;case _e.NANOSECOND:return D.TimestampNanosecond}return D.Timestamp;case D.Date:switch(n.unit){case gn.DAY:return D.DateDay;case gn.MILLISECOND:return D.DateMillisecond}return D.Date;case D.Interval:switch(n.unit){case nr.DAY_TIME:return D.IntervalDayTime;case nr.YEAR_MONTH:return D.IntervalYearMonth}return D.Interval;case D.Duration:switch(n.unit){case _e.SECOND:return D.DurationSecond;case _e.MILLISECOND:return D.DurationMillisecond;case _e.MICROSECOND:return D.DurationMicrosecond;case _e.NANOSECOND:return D.DurationNanosecond}return D.Duration;case D.Map:return D.Map;case D.List:return D.List;case D.Struct:return D.Struct;case D.Union:switch(n.mode){case Ht.Dense:return D.DenseUnion;case Ht.Sparse:return D.SparseUnion}return D.Union;case D.FixedSizeBinary:return D.FixedSizeBinary;case D.FixedSizeList:return D.FixedSizeList;case D.Dictionary:return D.Dictionary}throw new Error(`Unrecognized type '${D[n.typeId]}'`)}Re.prototype.visitInt8=null;Re.prototype.visitInt16=null;Re.prototype.visitInt32=null;Re.prototype.visitInt64=null;Re.prototype.visitUint8=null;Re.prototype.visitUint16=null;Re.prototype.visitUint32=null;Re.prototype.visitUint64=null;Re.prototype.visitFloat16=null;Re.prototype.visitFloat32=null;Re.prototype.visitFloat64=null;Re.prototype.visitDateDay=null;Re.prototype.visitDateMillisecond=null;Re.prototype.visitTimestampSecond=null;Re.prototype.visitTimestampMillisecond=null;Re.prototype.visitTimestampMicrosecond=null;Re.prototype.visitTimestampNanosecond=null;Re.prototype.visitTimeSecond=null;Re.prototype.visitTimeMillisecond=null;Re.prototype.visitTimeMicrosecond=null;Re.prototype.visitTimeNanosecond=null;Re.prototype.visitDenseUnion=null;Re.prototype.visitSparseUnion=null;Re.prototype.visitIntervalDayTime=null;Re.prototype.visitIntervalYearMonth=null;Re.prototype.visitDuration=null;Re.prototype.visitDurationSecond=null;Re.prototype.visitDurationMillisecond=null;Re.prototype.visitDurationMicrosecond=null;Re.prototype.visitDurationNanosecond=null;const sg=new Float64Array(1),ai=new Uint32Array(sg.buffer);function ig(n){const e=(n&31744)>>10,t=(n&1023)/1024,i=Math.pow(-1,(n&32768)>>15);switch(e){case 31:return i*(t?Number.NaN:1/0);case 0:return i*(t?6103515625e-14*t:0)}return i*Math.pow(2,e-15)*(1+t)}function Gb(n){if(n!==n)return 32256;sg[0]=n;const e=(ai[1]&2147483648)>>16&65535;let t=ai[1]&2146435072,i=0;return t>=1089470464?ai[0]>0?t=31744:(t=(t&2080374784)>>16,i=(ai[1]&1048575)>>10):t<=1056964608?(i=1048576+(ai[1]&1048575),i=1048576+(i<<(t>>20)-998)>>21,t=0):(t=t-1056964608>>10,i=(ai[1]&1048575)+512>>10),e|t|i&65535}class Ne extends Re{}function Ie(n){return(e,t,i)=>{if(e.setValid(t,i!=null))return n(e,t,i)}}const Yb=(n,e,t)=>{n[e]=Math.floor(t/864e5)},og=(n,e,t,i)=>{if(t+1{const a=n+t;i?e[a>>3]|=1<>3]&=~(1<{n[e]=t},$d=({values:n},e,t)=>{n[e]=t},ag=({values:n},e,t)=>{n[e]=Gb(t)},Kb=(n,e,t)=>{switch(n.type.precision){case Dt.HALF:return ag(n,e,t);case Dt.SINGLE:case Dt.DOUBLE:return $d(n,e,t)}},lg=({values:n},e,t)=>{Yb(n,e,t.valueOf())},ug=({values:n},e,t)=>{n[e]=BigInt(t)},Jb=({stride:n,values:e},t,i)=>{e.set(i.subarray(0,n),n*t)},cg=({values:n,valueOffsets:e},t,i)=>og(n,e,t,i),dg=({values:n,valueOffsets:e},t,i)=>og(n,e,t,Bd(i)),qb=(n,e,t)=>{n.type.unit===gn.DAY?lg(n,e,t):ug(n,e,t)},fg=({values:n},e,t)=>{n[e]=BigInt(t/1e3)},hg=({values:n},e,t)=>{n[e]=BigInt(t)},pg=({values:n},e,t)=>{n[e]=BigInt(t*1e3)},mg=({values:n},e,t)=>{n[e]=BigInt(t*1e6)},Zb=(n,e,t)=>{switch(n.type.unit){case _e.SECOND:return fg(n,e,t);case _e.MILLISECOND:return hg(n,e,t);case _e.MICROSECOND:return pg(n,e,t);case _e.NANOSECOND:return mg(n,e,t)}},yg=({values:n},e,t)=>{n[e]=t},gg=({values:n},e,t)=>{n[e]=t},vg=({values:n},e,t)=>{n[e]=t},xg=({values:n},e,t)=>{n[e]=t},Xb=(n,e,t)=>{switch(n.type.unit){case _e.SECOND:return yg(n,e,t);case _e.MILLISECOND:return gg(n,e,t);case _e.MICROSECOND:return vg(n,e,t);case _e.NANOSECOND:return xg(n,e,t)}},ew=({values:n,stride:e},t,i)=>{n.set(i.subarray(0,e),e*t)},tw=(n,e,t)=>{const i=n.children[0],a=n.valueOffsets,u=vn.getVisitFn(i);if(Array.isArray(t))for(let f=-1,h=a[e],m=a[e+1];h{const i=n.children[0],{valueOffsets:a}=n,u=vn.getVisitFn(i);let{[e]:f,[e+1]:h}=a;const m=t instanceof Map?t.entries():Object.entries(t);for(const g of m)if(u(i,f,g),++f>=h)break},rw=(n,e)=>(t,i,a,u)=>i&&t(i,n,e[u]),sw=(n,e)=>(t,i,a,u)=>i&&t(i,n,e.get(u)),iw=(n,e)=>(t,i,a,u)=>i&&t(i,n,e.get(a.name)),ow=(n,e)=>(t,i,a,u)=>i&&t(i,n,e[a.name]),aw=(n,e,t)=>{const i=n.type.children.map(u=>vn.getVisitFn(u.type)),a=t instanceof Map?iw(e,t):t instanceof Je?sw(e,t):Array.isArray(t)?rw(e,t):ow(e,t);n.type.children.forEach((u,f)=>a(i[f],n.children[f],u,f))},lw=(n,e,t)=>{n.type.mode===Ht.Dense?bg(n,e,t):wg(n,e,t)},bg=(n,e,t)=>{const i=n.type.typeIdToChildIndex[n.typeIds[e]],a=n.children[i];vn.visit(a,n.valueOffsets[e],t)},wg=(n,e,t)=>{const i=n.type.typeIdToChildIndex[n.typeIds[e]],a=n.children[i];vn.visit(a,e,t)},uw=(n,e,t)=>{var i;(i=n.dictionary)===null||i===void 0||i.set(n.values[e],t)},cw=(n,e,t)=>{n.type.unit===nr.DAY_TIME?Sg(n,e,t):_g(n,e,t)},Sg=({values:n},e,t)=>{n.set(t.subarray(0,2),2*e)},_g=({values:n},e,t)=>{n[e]=t[0]*12+t[1]%12},Ng=({values:n},e,t)=>{n[e]=t},jg=({values:n},e,t)=>{n[e]=t},kg=({values:n},e,t)=>{n[e]=t},Ig=({values:n},e,t)=>{n[e]=t},dw=(n,e,t)=>{switch(n.type.unit){case _e.SECOND:return Ng(n,e,t);case _e.MILLISECOND:return jg(n,e,t);case _e.MICROSECOND:return kg(n,e,t);case _e.NANOSECOND:return Ig(n,e,t)}},fw=(n,e,t)=>{const{stride:i}=n,a=n.children[0],u=vn.getVisitFn(a);if(Array.isArray(t))for(let f=-1,h=e*i;++f`${Bo(e)}: ${Bo(t)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}[Symbol.iterator](){return new hw(this[On],this[Si])}}class hw{constructor(e,t){this.childIndex=0,this.children=e.children,this.rowIndex=t,this.childFields=e.type.children,this.numChildren=this.childFields.length}[Symbol.iterator](){return this}next(){const e=this.childIndex;return et.name)}has(e,t){return e[On].type.children.findIndex(i=>i.name===t)!==-1}getOwnPropertyDescriptor(e,t){if(e[On].type.children.findIndex(i=>i.name===t)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(e,t){if(Reflect.has(e,t))return e[t];const i=e[On].type.children.findIndex(a=>a.name===t);if(i!==-1){const a=Gt.visit(e[On].children[i],e[Si]);return Reflect.set(e,t,a),a}}set(e,t,i){const a=e[On].type.children.findIndex(u=>u.name===t);return a!==-1?(vn.visit(e[On].children[a],e[Si],i),Reflect.set(e,t,i)):Reflect.has(e,t)||typeof t=="symbol"?Reflect.set(e,t,i):!1}}class ve extends Re{}function je(n){return(e,t)=>e.getValid(t)?n(e,t):null}const mw=(n,e)=>864e5*n[e],yw=(n,e)=>null,Mg=(n,e,t)=>{if(t+1>=e.length)return null;const i=tt(e[t]),a=tt(e[t+1]);return n.subarray(i,a)},gw=({offset:n,values:e},t)=>{const i=n+t;return(e[i>>3]&1<mw(n,e),Cg=({values:n},e)=>tt(n[e]),as=({stride:n,values:e},t)=>e[n*t],vw=({stride:n,values:e},t)=>ig(e[n*t]),Fg=({values:n},e)=>n[e],xw=({stride:n,values:e},t)=>e.subarray(n*t,n*(t+1)),Og=({values:n,valueOffsets:e},t)=>Mg(n,e,t),Tg=({values:n,valueOffsets:e},t)=>{const i=Mg(n,e,t);return i!==null?xd(i):null},bw=({values:n},e)=>n[e],ww=({type:n,values:e},t)=>n.precision!==Dt.HALF?e[t]:ig(e[t]),Sw=(n,e)=>n.type.unit===gn.DAY?Dg(n,e):Cg(n,e),Ag=({values:n},e)=>1e3*tt(n[e]),Bg=({values:n},e)=>tt(n[e]),Eg=({values:n},e)=>Ay(n[e],BigInt(1e3)),Rg=({values:n},e)=>Ay(n[e],BigInt(1e6)),_w=(n,e)=>{switch(n.type.unit){case _e.SECOND:return Ag(n,e);case _e.MILLISECOND:return Bg(n,e);case _e.MICROSECOND:return Eg(n,e);case _e.NANOSECOND:return Rg(n,e)}},Lg=({values:n},e)=>n[e],Ug=({values:n},e)=>n[e],$g=({values:n},e)=>n[e],Pg=({values:n},e)=>n[e],Nw=(n,e)=>{switch(n.type.unit){case _e.SECOND:return Lg(n,e);case _e.MILLISECOND:return Ug(n,e);case _e.MICROSECOND:return $g(n,e);case _e.NANOSECOND:return Pg(n,e)}},jw=({values:n,stride:e},t)=>Ud.decimal(n.subarray(e*t,e*(t+1))),kw=(n,e)=>{const{valueOffsets:t,stride:i,children:a}=n,{[e*i]:u,[e*i+1]:f}=t,m=a[0].slice(u,f-u);return new Je([m])},Iw=(n,e)=>{const{valueOffsets:t,children:i}=n,{[e]:a,[e+1]:u}=t,f=i[0];return new zd(f.slice(a,u-a))},Mw=(n,e)=>new Pd(n,e),Dw=(n,e)=>n.type.mode===Ht.Dense?zg(n,e):Vg(n,e),zg=(n,e)=>{const t=n.type.typeIdToChildIndex[n.typeIds[e]],i=n.children[t];return Gt.visit(i,n.valueOffsets[e])},Vg=(n,e)=>{const t=n.type.typeIdToChildIndex[n.typeIds[e]],i=n.children[t];return Gt.visit(i,e)},Cw=(n,e)=>{var t;return(t=n.dictionary)===null||t===void 0?void 0:t.get(n.values[e])},Fw=(n,e)=>n.type.unit===nr.DAY_TIME?Wg(n,e):Hg(n,e),Wg=({values:n},e)=>n.subarray(2*e,2*(e+1)),Hg=({values:n},e)=>{const t=n[e],i=new Int32Array(2);return i[0]=Math.trunc(t/12),i[1]=Math.trunc(t%12),i},Gg=({values:n},e)=>n[e],Yg=({values:n},e)=>n[e],Qg=({values:n},e)=>n[e],Kg=({values:n},e)=>n[e],Ow=(n,e)=>{switch(n.type.unit){case _e.SECOND:return Gg(n,e);case _e.MILLISECOND:return Yg(n,e);case _e.MICROSECOND:return Qg(n,e);case _e.NANOSECOND:return Kg(n,e)}},Tw=(n,e)=>{const{stride:t,children:i}=n,u=i[0].slice(e*t,t);return new Je([u])};ve.prototype.visitNull=je(yw);ve.prototype.visitBool=je(gw);ve.prototype.visitInt=je(bw);ve.prototype.visitInt8=je(as);ve.prototype.visitInt16=je(as);ve.prototype.visitInt32=je(as);ve.prototype.visitInt64=je(Fg);ve.prototype.visitUint8=je(as);ve.prototype.visitUint16=je(as);ve.prototype.visitUint32=je(as);ve.prototype.visitUint64=je(Fg);ve.prototype.visitFloat=je(ww);ve.prototype.visitFloat16=je(vw);ve.prototype.visitFloat32=je(as);ve.prototype.visitFloat64=je(as);ve.prototype.visitUtf8=je(Tg);ve.prototype.visitLargeUtf8=je(Tg);ve.prototype.visitBinary=je(Og);ve.prototype.visitLargeBinary=je(Og);ve.prototype.visitFixedSizeBinary=je(xw);ve.prototype.visitDate=je(Sw);ve.prototype.visitDateDay=je(Dg);ve.prototype.visitDateMillisecond=je(Cg);ve.prototype.visitTimestamp=je(_w);ve.prototype.visitTimestampSecond=je(Ag);ve.prototype.visitTimestampMillisecond=je(Bg);ve.prototype.visitTimestampMicrosecond=je(Eg);ve.prototype.visitTimestampNanosecond=je(Rg);ve.prototype.visitTime=je(Nw);ve.prototype.visitTimeSecond=je(Lg);ve.prototype.visitTimeMillisecond=je(Ug);ve.prototype.visitTimeMicrosecond=je($g);ve.prototype.visitTimeNanosecond=je(Pg);ve.prototype.visitDecimal=je(jw);ve.prototype.visitList=je(kw);ve.prototype.visitStruct=je(Mw);ve.prototype.visitUnion=je(Dw);ve.prototype.visitDenseUnion=je(zg);ve.prototype.visitSparseUnion=je(Vg);ve.prototype.visitDictionary=je(Cw);ve.prototype.visitInterval=je(Fw);ve.prototype.visitIntervalDayTime=je(Wg);ve.prototype.visitIntervalYearMonth=je(Hg);ve.prototype.visitDuration=je(Ow);ve.prototype.visitDurationSecond=je(Gg);ve.prototype.visitDurationMillisecond=je(Yg);ve.prototype.visitDurationMicrosecond=je(Qg);ve.prototype.visitDurationNanosecond=je(Kg);ve.prototype.visitFixedSizeList=je(Tw);ve.prototype.visitMap=je(Iw);const Gt=new ve,yi=Symbol.for("keys"),_i=Symbol.for("vals"),gi=Symbol.for("kKeysAsStrings"),jd=Symbol.for("_kKeysAsStrings");class zd{constructor(e){return this[yi]=new Je([e.children[0]]).memoize(),this[_i]=e.children[1],new Proxy(this,new Bw)}get[gi](){return this[jd]||(this[jd]=Array.from(this[yi].toArray(),String))}[Symbol.iterator](){return new Aw(this[yi],this[_i])}get size(){return this[yi].length}toArray(){return Object.values(this.toJSON())}toJSON(){const e=this[yi],t=this[_i],i={};for(let a=-1,u=e.length;++a`${Bo(e)}: ${Bo(t)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}class Aw{constructor(e,t){this.keys=e,this.vals=t,this.keyIndex=0,this.numKeys=e.length}[Symbol.iterator](){return this}next(){const e=this.keyIndex;return e===this.numKeys?{done:!0,value:null}:(this.keyIndex++,{done:!1,value:[this.keys.get(e),Gt.visit(this.vals,e)]})}}class Bw{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(e){return e[gi]}has(e,t){return e[gi].includes(t)}getOwnPropertyDescriptor(e,t){if(e[gi].indexOf(t)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(e,t){if(Reflect.has(e,t))return e[t];const i=e[gi].indexOf(t);if(i!==-1){const a=Gt.visit(Reflect.get(e,_i),i);return Reflect.set(e,t,a),a}}set(e,t,i){const a=e[gi].indexOf(t);return a!==-1?(vn.visit(Reflect.get(e,_i),a,i),Reflect.set(e,t,i)):Reflect.has(e,t)?Reflect.set(e,t,i):!1}}Object.defineProperties(zd.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:"Row"},[yi]:{writable:!0,enumerable:!1,configurable:!1,value:null},[_i]:{writable:!0,enumerable:!1,configurable:!1,value:null},[jd]:{writable:!0,enumerable:!1,configurable:!1,value:null}});let wm;function Jg(n,e,t,i){const{length:a=0}=n;let u=typeof e!="number"?0:e,f=typeof t!="number"?a:t;return u<0&&(u=(u%a+a)%a),f<0&&(f=(f%a+a)%a),fa&&(f=a),i?i(n,u,f):[u,f]}const Vd=(n,e)=>n<0?e+n:n,Sm=n=>n!==n;function Ti(n){if(typeof n!=="object"||n===null)return Sm(n)?Sm:t=>t===n;if(n instanceof Date){const t=n.valueOf();return i=>i instanceof Date?i.valueOf()===t:!1}return ArrayBuffer.isView(n)?t=>t?Tb(n,t):!1:n instanceof Map?Rw(n):Array.isArray(n)?Ew(n):n instanceof Je?Lw(n):Uw(n,!0)}function Ew(n){const e=[];for(let t=-1,i=n.length;++t!1;const i=[];for(let a=-1,u=t.length;++a{if(!t||typeof t!="object")return!1;switch(t.constructor){case Array:return $w(n,t);case Map:return _m(n,t,t.keys());case zd:case Pd:case Object:case void 0:return _m(n,t,e||Object.keys(t))}return t instanceof Je?Pw(n,t):!1}}function $w(n,e){const t=n.length;if(e.length!==t)return!1;for(let i=-1;++i>i}function Nm(n,e,t){const i=t.byteLength+7&-8;if(n>0||t.byteLength>3):kd(new Wd(t,n,e,null,qg)).subarray(0,i)),a}return t}function kd(n){const e=[];let t=0,i=0,a=0;for(const f of n)f&&(a|=1<0)&&(e[t++]=a);const u=new Uint8Array(e.length+7&-8);return u.set(e),u}class Wd{constructor(e,t,i,a,u){this.bytes=e,this.length=i,this.context=a,this.get=u,this.bit=t%8,this.byteIndex=t>>3,this.byte=e[this.byteIndex++],this.index=0}next(){return this.index>3<<3,a=e+(e%8===0?0:8-e%8);return Id(n,e,a)+Id(n,i,t)+Vw(n,a>>3,i-a>>3)}function Vw(n,e,t){let i=0,a=Math.trunc(e);const u=new DataView(n.buffer,n.byteOffset,n.byteLength),f=t===void 0?n.byteLength:a+t;for(;f-a>=4;)i+=id(u.getUint32(a)),a+=4;for(;f-a>=2;)i+=id(u.getUint16(a)),a+=2;for(;f-a>=1;)i+=id(u.getUint8(a)),a+=1;return i}function id(n){let e=Math.trunc(n);return e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),(e+(e>>>4)&252645135)*16843009>>>24}const Ww=-1;class Ye{get typeId(){return this.type.typeId}get ArrayType(){return this.type.ArrayType}get buffers(){return[this.valueOffsets,this.values,this.nullBitmap,this.typeIds]}get nullable(){if(this._nullCount!==0){const{type:e}=this;return me.isSparseUnion(e)?this.children.some(t=>t.nullable):me.isDenseUnion(e)?this.children.some(t=>t.nullable):this.nullBitmap&&this.nullBitmap.byteLength>0}return!0}get byteLength(){let e=0;const{valueOffsets:t,values:i,nullBitmap:a,typeIds:u}=this;return t&&(e+=t.byteLength),i&&(e+=i.byteLength),a&&(e+=a.byteLength),u&&(e+=u.byteLength),this.children.reduce((f,h)=>f+h.byteLength,e)}get nullCount(){if(me.isUnion(this.type))return this.children.reduce((i,a)=>i+a.nullCount,0);let e=this._nullCount,t;return e<=Ww&&(t=this.nullBitmap)&&(this._nullCount=e=t.length===0?0:this.length-Id(t,this.offset,this.offset+this.length)),e}constructor(e,t,i,a,u,f=[],h){this.type=e,this.children=f,this.dictionary=h,this.offset=Math.floor(Math.max(t||0,0)),this.length=Math.floor(Math.max(i||0,0)),this._nullCount=Math.floor(Math.max(a||0,-1));let m;u instanceof Ye?(this.stride=u.stride,this.values=u.values,this.typeIds=u.typeIds,this.nullBitmap=u.nullBitmap,this.valueOffsets=u.valueOffsets):(this.stride=vr(e),u&&((m=u[0])&&(this.valueOffsets=m),(m=u[1])&&(this.values=m),(m=u[2])&&(this.nullBitmap=m),(m=u[3])&&(this.typeIds=m)))}getValid(e){const{type:t}=this;if(me.isUnion(t)){const i=t,a=this.children[i.typeIdToChildIndex[this.typeIds[e]]],u=i.mode===Ht.Dense?this.valueOffsets[e]:e;return a.getValid(u)}if(this.nullable&&this.nullCount>0){const i=this.offset+e;return(this.nullBitmap[i>>3]&1<>3;(!u||u.byteLength<=v)&&(u=new Uint8Array((f+h+63&-64)>>3).fill(255),this.nullCount>0?(u.set(Nm(f,h,this.nullBitmap),0),Object.assign(this,{nullBitmap:u})):Object.assign(this,{nullBitmap:u,_nullCount:0}));const x=u[v];i=(x&g)!==0,u[v]=t?x|g:x&~g}return i!==!!t&&(this._nullCount=this.nullCount+(t?-1:1)),t}clone(e=this.type,t=this.offset,i=this.length,a=this._nullCount,u=this,f=this.children){return new Ye(e,t,i,a,u,f,this.dictionary)}slice(e,t){const{stride:i,typeId:a,children:u}=this,f=+(this._nullCount===0)-1,h=a===16?i:1,m=this._sliceBuffers(e,t,i,a);return this.clone(this.type,this.offset+e,t,f,m,u.length===0||this.valueOffsets?u:this._sliceChildren(u,h*e,h*t))}_changeLengthAndBackfillNullBitmap(e){if(this.typeId===D.Null)return this.clone(this.type,0,e,0);const{length:t,nullCount:i}=this,a=new Uint8Array((e+63&-64)>>3).fill(255,0,t>>3);a[t>>3]=(1<0&&a.set(Nm(this.offset,t,this.nullBitmap),0);const u=this.buffers;return u[gr.VALIDITY]=a,this.clone(this.type,0,e,i+(e-t),u)}_sliceBuffers(e,t,i,a){let u;const{buffers:f}=this;return(u=f[gr.TYPE])&&(f[gr.TYPE]=u.subarray(e,e+t)),(u=f[gr.OFFSET])&&(f[gr.OFFSET]=u.subarray(e,e+t+1))||(u=f[gr.DATA])&&(f[gr.DATA]=a===6?u:u.subarray(i*e,i*(e+t))),f}_sliceChildren(e,t,i){return e.map(a=>a.slice(t,i))}}Ye.prototype.children=Object.freeze([]);class To extends Re{visit(e){return this.getVisitFn(e.type).call(this,e)}visitNull(e){const{["type"]:t,["offset"]:i=0,["length"]:a=0}=e;return new Ye(t,i,a,a)}visitBool(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length>>3,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitInt(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitFloat(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitUtf8(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitLargeUtf8(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=cm(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitBinary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitLargeBinary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.data),u=$e(e.nullBitmap),f=cm(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,a,u])}visitFixedSizeBinary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitDate(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitTimestamp(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitTime(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitDecimal(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitList(e){const{["type"]:t,["offset"]:i=0,["child"]:a}=e,u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,void 0,u],[a])}visitStruct(e){const{["type"]:t,["offset"]:i=0,["children"]:a=[]}=e,u=$e(e.nullBitmap),{length:f=a.reduce((m,{length:g})=>Math.max(m,g),0),nullCount:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,void 0,u],a)}visitUnion(e){const{["type"]:t,["offset"]:i=0,["children"]:a=[]}=e,u=Ke(t.ArrayType,e.typeIds),{["length"]:f=u.length,["nullCount"]:h=-1}=e;if(me.isSparseUnion(t))return new Ye(t,i,f,h,[void 0,void 0,void 0,u],a);const m=So(e.valueOffsets);return new Ye(t,i,f,h,[m,void 0,void 0,u],a)}visitDictionary(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.indices.ArrayType,e.data),{["dictionary"]:f=new Je([new To().visit({type:t.dictionary})])}=e,{["length"]:h=u.length,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[void 0,u,a],[],f)}visitInterval(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitDuration(e){const{["type"]:t,["offset"]:i=0}=e,a=$e(e.nullBitmap),u=Ke(t.ArrayType,e.data),{["length"]:f=u.length,["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,u,a])}visitFixedSizeList(e){const{["type"]:t,["offset"]:i=0,["child"]:a=new To().visit({type:t.valueType})}=e,u=$e(e.nullBitmap),{["length"]:f=a.length/vr(t),["nullCount"]:h=e.nullBitmap?-1:0}=e;return new Ye(t,i,f,h,[void 0,void 0,u],[a])}visitMap(e){const{["type"]:t,["offset"]:i=0,["child"]:a=new To().visit({type:t.childType})}=e,u=$e(e.nullBitmap),f=So(e.valueOffsets),{["length"]:h=f.length-1,["nullCount"]:m=e.nullBitmap?-1:0}=e;return new Ye(t,i,h,m,[f,void 0,u],[a])}}const Hw=new To;function Ee(n){return Hw.visit(n)}class jm{constructor(e=0,t){this.numChunks=e,this.getChunkIterator=t,this.chunkIndex=0,this.chunkIterator=this.getChunkIterator(0)}next(){for(;this.chunkIndexe.nullable)}function Zg(n){return n.reduce((e,t)=>e+t.nullCount,0)}function Xg(n){return n.reduce((e,t,i)=>(e[i+1]=e[i]+t.length,e),new Uint32Array(n.length+1))}function ev(n,e,t,i){const a=[];for(let u=-1,f=n.length;++u=i)break;if(t>=m+g)continue;if(m>=t&&m+g<=i){a.push(h);continue}const v=Math.max(0,t-m),x=Math.min(i-m,g);a.push(h.slice(v,x-v))}return a.length===0&&a.push(n[0].slice(0,0)),a}function Hd(n,e,t,i){let a=0,u=0,f=e.length-1;do{if(a>=f-1)return t0?0:-1}function Qw(n,e){const{nullBitmap:t}=n;if(!t||n.nullCount<=0)return-1;let i=0;for(const a of new Wd(t,n.offset+(e||0),n.length,t,qg)){if(!a)return i;++i}return-1}function De(n,e,t){if(e===void 0)return-1;if(e===null)switch(n.typeId){case D.Union:break;case D.Dictionary:break;default:return Qw(n,t)}const i=Gt.getVisitFn(n),a=Ti(e);for(let u=(t||0)-1,f=n.length;++u{const a=n.data[i];return a.values.subarray(0,a.length)[Symbol.iterator]()});let t=0;return new jm(n.data.length,i=>{const u=n.data[i].length,f=n.slice(t,t+u);return t+=u,new Kw(f)})}class Kw{constructor(e){this.vector=e,this.index=0}next(){return this.indexh.data):e;if(u.length===0||u.some(h=>!(h instanceof Ye)))throw new TypeError("Vector constructor expects an Array of Data instances.");const f=(t=u[0])===null||t===void 0?void 0:t.type;switch(u.length){case 0:this._offsets=[0];break;case 1:{const{get:h,set:m,indexOf:g}=iv[f.typeId],v=u[0];this.isValid=x=>Gd(v,x),this.get=x=>h(v,x),this.set=(x,b)=>m(v,x,b),this.indexOf=x=>g(v,x),this._offsets=[0,v.length];break}default:Object.setPrototypeOf(this,ov[f.typeId]),this._offsets=Xg(u);break}this.data=u,this.type=f,this.stride=vr(f),this.numChildren=(a=(i=f.children)===null||i===void 0?void 0:i.length)!==null&&a!==void 0?a:0,this.length=this._offsets.at(-1)}get byteLength(){return this.data.reduce((e,t)=>e+t.byteLength,0)}get nullable(){return Gw(this.data)}get nullCount(){return Zg(this.data)}get ArrayType(){return this.type.ArrayType}get[Symbol.toStringTag](){return`${this.VectorName}<${this.type[Symbol.toStringTag]}>`}get VectorName(){return`${D[this.type.typeId]}Vector`}isValid(e){return!1}get(e){return null}at(e){return this.get(Vd(e,this.length))}set(e,t){}indexOf(e,t){return-1}includes(e,t){return this.indexOf(e,t)>-1}[Symbol.iterator](){return Yd.visit(this)}concat(...e){return new Je(this.data.concat(e.flatMap(t=>t.data).flat(Number.POSITIVE_INFINITY)))}slice(e,t){return new Je(Jg(this,e,t,({data:i,_offsets:a},u,f)=>ev(i,a,u,f)))}toJSON(){return[...this]}toArray(){const{type:e,data:t,length:i,stride:a,ArrayType:u}=this;switch(e.typeId){case D.Int:case D.Float:case D.Decimal:case D.Time:case D.Timestamp:switch(t.length){case 0:return new u;case 1:return t[0].values.subarray(0,i*a);default:return t.reduce((f,{values:h,length:m})=>(f.array.set(h.subarray(0,m*a),f.offset),f.offset+=m*a,f),{array:new u(i*a),offset:0}).array}}return[...this]}toString(){return`[${[...this].join(",")}]`}getChild(e){var t;return this.getChildAt((t=this.type.children)===null||t===void 0?void 0:t.findIndex(i=>i.name===e))}getChildAt(e){return e>-1&&et[e])):null}get isMemoized(){return me.isDictionary(this.type)?this.data[0].dictionary.isMemoized:!1}memoize(){if(me.isDictionary(this.type)){const e=new Wl(this.data[0].dictionary),t=this.data.map(i=>{const a=i.clone();return a.dictionary=e,a});return new Je(t)}return new Wl(this)}unmemoize(){if(me.isDictionary(this.type)&&this.isMemoized){const e=this.data[0].dictionary.unmemoize(),t=this.data.map(i=>{const a=i.clone();return a.dictionary=e,a});return new Je(t)}return this}}sv=Symbol.toStringTag;Je[sv]=(n=>{n.type=me.prototype,n.data=[],n.length=0,n.stride=1,n.numChildren=0,n._offsets=new Uint32Array([0]),n[Symbol.isConcatSpreadable]=!0;const e=Object.keys(D).map(t=>D[t]).filter(t=>typeof t=="number"&&t!==D.NONE);for(const t of e){const i=Gt.getVisitFnByTypeId(t),a=vn.getVisitFnByTypeId(t),u=Vl.getVisitFnByTypeId(t);iv[t]={get:i,set:a,indexOf:u},ov[t]=Object.create(n,{isValid:{value:zl(Gd)},get:{value:zl(Gt.getVisitFnByTypeId(t))},set:{value:tv(vn.getVisitFnByTypeId(t))},indexOf:{value:nv(Vl.getVisitFnByTypeId(t))}})}return"Vector"})(Je.prototype);class Wl extends Je{constructor(e){super(e.data);const t=this.get,i=this.set,a=this.slice,u=new Array(this.length);Object.defineProperty(this,"get",{value(f){const h=u[f];if(h!==void 0)return h;const m=t.call(this,f);return u[f]=m,m}}),Object.defineProperty(this,"set",{value(f,h){i.call(this,f,h),u[f]=h}}),Object.defineProperty(this,"slice",{value:(f,h)=>new Wl(a.call(this,f,h))}),Object.defineProperty(this,"isMemoized",{value:!0}),Object.defineProperty(this,"unmemoize",{value:()=>new Je(this.data)}),Object.defineProperty(this,"memoize",{value:()=>this})}}class Md{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}offset(){return this.bb.readInt64(this.bb_pos)}metaDataLength(){return this.bb.readInt32(this.bb_pos+8)}bodyLength(){return this.bb.readInt64(this.bb_pos+16)}static sizeOf(){return 24}static createBlock(e,t,i,a){return e.prep(8,24),e.writeInt64(BigInt(a??0)),e.pad(4),e.writeInt32(i),e.writeInt64(BigInt(t??0)),e.offset()}}class Xt{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsFooter(e,t){return(t||new Xt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsFooter(e,t){return e.setPosition(e.position()+He),(t||new Xt).__init(e.readInt32(e.position())+e.position(),e)}version(){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):ht.V1}schema(e){const t=this.bb.__offset(this.bb_pos,6);return t?(e||new Gn).__init(this.bb.__indirect(this.bb_pos+t),this.bb):null}dictionaries(e,t){const i=this.bb.__offset(this.bb_pos,8);return i?(t||new Md).__init(this.bb.__vector(this.bb_pos+i)+e*24,this.bb):null}dictionariesLength(){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}recordBatches(e,t){const i=this.bb.__offset(this.bb_pos,10);return i?(t||new Md).__init(this.bb.__vector(this.bb_pos+i)+e*24,this.bb):null}recordBatchesLength(){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__vector_len(this.bb_pos+e):0}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,12);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}static startFooter(e){e.startObject(5)}static addVersion(e,t){e.addFieldInt16(0,t,ht.V1)}static addSchema(e,t){e.addFieldOffset(1,t,0)}static addDictionaries(e,t){e.addFieldOffset(2,t,0)}static startDictionariesVector(e,t){e.startVector(24,t,8)}static addRecordBatches(e,t){e.addFieldOffset(3,t,0)}static startRecordBatchesVector(e,t){e.startVector(24,t,8)}static addCustomMetadata(e,t){e.addFieldOffset(4,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endFooter(e){return e.endObject()}static finishFooterBuffer(e,t){e.finish(t)}static finishSizePrefixedFooterBuffer(e,t){e.finish(t,void 0,!0)}}class We{constructor(e=[],t,i,a=ht.V5){this.fields=e||[],this.metadata=t||new Map,i||(i=Dd(this.fields)),this.dictionaries=i,this.metadataVersion=a}get[Symbol.toStringTag](){return"Schema"}get names(){return this.fields.map(e=>e.name)}toString(){return`Schema<{ ${this.fields.map((e,t)=>`${t}: ${e}`).join(", ")} }>`}select(e){const t=new Set(e),i=this.fields.filter(a=>t.has(a.name));return new We(i,this.metadata)}selectAt(e){const t=e.map(i=>this.fields[i]).filter(Boolean);return new We(t,this.metadata)}assign(...e){const t=e[0]instanceof We?e[0]:Array.isArray(e[0])?new We(e[0]):new We(e),i=[...this.fields],a=sl(sl(new Map,this.metadata),t.metadata),u=t.fields.filter(h=>{const m=i.findIndex(g=>g.name===h.name);return~m?(i[m]=h.clone({metadata:sl(sl(new Map,i[m].metadata),h.metadata)}))&&!1:!0}),f=Dd(u,new Map);return new We([...i,...u],a,new Map([...this.dictionaries,...f]))}}We.prototype.fields=null;We.prototype.metadata=null;We.prototype.dictionaries=null;class nt{static new(...e){let[t,i,a,u]=e;return e[0]&&typeof e[0]=="object"&&({name:t}=e[0],i===void 0&&(i=e[0].type),a===void 0&&(a=e[0].nullable),u===void 0&&(u=e[0].metadata)),new nt(`${t}`,i,a,u)}constructor(e,t,i=!1,a){this.name=e,this.type=t,this.nullable=i,this.metadata=a||new Map}get typeId(){return this.type.typeId}get[Symbol.toStringTag](){return"Field"}toString(){return`${this.name}: ${this.type}`}clone(...e){let[t,i,a,u]=e;return!e[0]||typeof e[0]!="object"?[t=this.name,i=this.type,a=this.nullable,u=this.metadata]=e:{name:t=this.name,type:i=this.type,nullable:a=this.nullable,metadata:u=this.metadata}=e[0],nt.new(t,i,a,u)}}nt.prototype.type=null;nt.prototype.name=null;nt.prototype.nullable=null;nt.prototype.metadata=null;function sl(n,e){return new Map([...n||new Map,...e||new Map])}function Dd(n,e=new Map){for(let t=-1,i=n.length;++t0&&Dd(u.children,e)}return e}var Jw=Cy,qw=ki;class Qd{static decode(e){e=new qw($e(e));const t=Xt.getRootAsFooter(e),i=We.decode(t.schema(),new Map,t.version());return new Zw(i,t)}static encode(e){const t=new Jw,i=We.encode(t,e.schema);Xt.startRecordBatchesVector(t,e.numRecordBatches);for(const f of[...e.recordBatches()].slice().reverse())Di.encode(t,f);const a=t.endVector();Xt.startDictionariesVector(t,e.numDictionaries);for(const f of[...e.dictionaryBatches()].slice().reverse())Di.encode(t,f);const u=t.endVector();return Xt.startFooter(t),Xt.addSchema(t,i),Xt.addVersion(t,ht.V5),Xt.addRecordBatches(t,a),Xt.addDictionaries(t,u),Xt.finishFooterBuffer(t,Xt.endFooter(t)),t.asUint8Array()}get numRecordBatches(){return this._recordBatches.length}get numDictionaries(){return this._dictionaryBatches.length}constructor(e,t=ht.V5,i,a){this.schema=e,this.version=t,i&&(this._recordBatches=i),a&&(this._dictionaryBatches=a)}*recordBatches(){for(let e,t=-1,i=this.numRecordBatches;++t=0&&e=0&&e=0&&e=0&&ethis._closedPromiseResolve=e)}get closed(){return this._closedPromise}cancel(e){return Fe(this,void 0,void 0,function*(){yield this.return(e)})}write(e){this._ensureOpen()&&(this.resolvers.length<=0?this._values.push(e):this.resolvers.shift().resolve({done:!1,value:e}))}abort(e){this._closedPromiseResolve&&(this.resolvers.length<=0?this._error={error:e}:this.resolvers.shift().reject({done:!0,value:e}))}close(){if(this._closedPromiseResolve){const{resolvers:e}=this;for(;e.length>0;)e.shift().resolve(at);this._closedPromiseResolve(),this._closedPromiseResolve=void 0}}[Symbol.asyncIterator](){return this}toDOMStream(e){return fn.toDOMStream(this._closedPromiseResolve||this._error?this:this._values,e)}toNodeStream(e){return fn.toNodeStream(this._closedPromiseResolve||this._error?this:this._values,e)}throw(e){return Fe(this,void 0,void 0,function*(){return yield this.abort(e),at})}return(e){return Fe(this,void 0,void 0,function*(){return yield this.close(),at})}read(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"read")).value})}peek(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"peek")).value})}next(...e){return this._values.length>0?Promise.resolve({done:!1,value:this._values.shift()}):this._error?Promise.reject({done:!0,value:this._error.error}):this._closedPromiseResolve?new Promise((t,i)=>{this.resolvers.push({resolve:t,reject:i})}):Promise.resolve(at)}_ensureOpen(){if(this._closedPromiseResolve)return!0;throw new Error("AsyncQueue is closed")}}class e1 extends Xw{write(e){if((e=$e(e)).byteLength>0)return super.write(e)}toString(e=!1){return e?xd(this.toUint8Array(!0)):this.toUint8Array(!1).then(xd)}toUint8Array(e=!1){return e?tr(this._values)[0]:Fe(this,void 0,void 0,function*(){var t,i,a,u;const f=[];let h=0;try{for(var m=!0,g=xi(this),v;v=yield g.next(),t=v.done,!t;m=!0){u=v.value,m=!1;const x=u;f.push(x),h+=x.byteLength}}catch(x){i={error:x}}finally{try{!m&&!t&&(a=g.return)&&(yield a.call(g))}finally{if(i)throw i.error}}return tr(f,h)[0]})}}class Hl{constructor(e){e&&(this.source=new t1(fn.fromIterable(e)))}[Symbol.iterator](){return this}next(e){return this.source.next(e)}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}peek(e){return this.source.peek(e)}read(e){return this.source.read(e)}}class Ci{constructor(e){e instanceof Ci?this.source=e.source:e instanceof e1?this.source=new js(fn.fromAsyncIterable(e)):Iy(e)?this.source=new js(fn.fromNodeStream(e)):Rd(e)?this.source=new js(fn.fromDOMStream(e)):jy(e)?this.source=new js(fn.fromDOMStream(e.body)):nu(e)?this.source=new js(fn.fromIterable(e)):Ao(e)?this.source=new js(fn.fromAsyncIterable(e)):Ed(e)&&(this.source=new js(fn.fromAsyncIterable(e)))}[Symbol.asyncIterator](){return this}next(e){return this.source.next(e)}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}get closed(){return this.source.closed}cancel(e){return this.source.cancel(e)}peek(e){return this.source.peek(e)}read(e){return this.source.read(e)}}class t1{constructor(e){this.source=e}cancel(e){this.return(e)}peek(e){return this.next(e,"peek").value}read(e){return this.next(e,"read").value}next(e,t="read"){return this.source.next({cmd:t,size:e})}throw(e){return Object.create(this.source.throw&&this.source.throw(e)||at)}return(e){return Object.create(this.source.return&&this.source.return(e)||at)}}class js{constructor(e){this.source=e,this._closedPromise=new Promise(t=>this._closedPromiseResolve=t)}cancel(e){return Fe(this,void 0,void 0,function*(){yield this.return(e)})}get closed(){return this._closedPromise}read(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"read")).value})}peek(e){return Fe(this,void 0,void 0,function*(){return(yield this.next(e,"peek")).value})}next(e){return Fe(this,arguments,void 0,function*(t,i="read"){return yield this.source.next({cmd:i,size:t})})}throw(e){return Fe(this,void 0,void 0,function*(){const t=this.source.throw&&(yield this.source.throw(e))||at;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(t)})}return(e){return Fe(this,void 0,void 0,function*(){const t=this.source.return&&(yield this.source.return(e))||at;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(t)})}}class Im extends Hl{constructor(e,t){super(),this.position=0,this.buffer=$e(e),this.size=t===void 0?this.buffer.byteLength:t}readInt32(e){const{buffer:t,byteOffset:i}=this.readAt(e,4);return new DataView(t,i).getInt32(0,!0)}seek(e){return this.position=Math.min(e,this.size),e>>16,this.buffer[1]&65535,this.buffer[0]>>>16,this.buffer[0]&65535]),i=new Uint32Array([e.buffer[1]>>>16,e.buffer[1]&65535,e.buffer[0]>>>16,e.buffer[0]&65535]);let a=t[3]*i[3];this.buffer[0]=a&65535;let u=a>>>16;return a=t[2]*i[3],u+=a,a=t[3]*i[2]>>>0,u+=a,this.buffer[0]+=u<<16,this.buffer[1]=u>>>0>>16,this.buffer[1]+=t[1]*i[3]+t[2]*i[2]+t[3]*i[1],this.buffer[1]+=t[0]*i[3]+t[1]*i[2]+t[2]*i[1]+t[3]*i[0]<<16,this}_plus(e){const t=this.buffer[0]+e.buffer[0]>>>0;this.buffer[1]+=e.buffer[1],t>>0&&++this.buffer[1],this.buffer[0]=t}lessThan(e){return this.buffer[1]>>0,t[2]=this.buffer[2]+e.buffer[2]>>>0,t[1]=this.buffer[1]+e.buffer[1]>>>0,t[0]=this.buffer[0]+e.buffer[0]>>>0,t[0]>>0&&++t[1],t[1]>>0&&++t[2],t[2]>>0&&++t[3],this.buffer[3]=t[3],this.buffer[2]=t[2],this.buffer[1]=t[1],this.buffer[0]=t[0],this}hex(){return`${vi(this.buffer[3])} ${vi(this.buffer[2])} ${vi(this.buffer[1])} ${vi(this.buffer[0])}`}static multiply(e,t){return new Yn(new Uint32Array(e.buffer)).times(t)}static add(e,t){return new Yn(new Uint32Array(e.buffer)).plus(t)}static from(e,t=new Uint32Array(4)){return Yn.fromString(typeof e=="string"?e:e.toString(),t)}static fromNumber(e,t=new Uint32Array(4)){return Yn.fromString(e.toString(),t)}static fromString(e,t=new Uint32Array(4)){const i=e.startsWith("-"),a=e.length,u=new Yn(t);for(let f=i?1:0;f0&&this.readData(e,i)||new Uint8Array(0)}readOffsets(e,t){return this.readData(e,t)}readTypeIds(e,t){return this.readData(e,t)}readData(e,{length:t,offset:i}=this.nextBufferRange()){return this.bytes.subarray(i,i+t)}readDictionary(e){return this.dictionaries.get(e.id)}}class r1 extends uv{constructor(e,t,i,a,u){super(new Uint8Array(0),t,i,a,u),this.sources=e}readNullBitmap(e,t,{offset:i}=this.nextBufferRange()){return t<=0?new Uint8Array(0):kd(this.sources[i])}readOffsets(e,{offset:t}=this.nextBufferRange()){return Ke(Uint8Array,Ke(e.OffsetArrayType,this.sources[t]))}readTypeIds(e,{offset:t}=this.nextBufferRange()){return Ke(Uint8Array,Ke(e.ArrayType,this.sources[t]))}readData(e,{offset:t}=this.nextBufferRange()){const{sources:i}=this;return me.isTimestamp(e)||(me.isInt(e)||me.isTime(e))&&e.bitWidth===64||me.isDuration(e)||me.isDate(e)&&e.unit===gn.MILLISECOND?Ke(Uint8Array,zt.convertArray(i[t])):me.isDecimal(e)?Ke(Uint8Array,Yn.convertArray(i[t])):me.isBinary(e)||me.isLargeBinary(e)||me.isFixedSizeBinary(e)?s1(i[t]):me.isBool(e)?kd(i[t]):me.isUtf8(e)||me.isLargeUtf8(e)?Bd(i[t].join("")):Ke(Uint8Array,Ke(e.ArrayType,i[t].map(a=>+a)))}}function s1(n){const e=n.join(""),t=new Uint8Array(e.length/2);for(let i=0;i>1]=Number.parseInt(e.slice(i,i+2),16);return t}class we extends Re{compareSchemas(e,t){return e===t||t instanceof e.constructor&&this.compareManyFields(e.fields,t.fields)}compareManyFields(e,t){return e===t||Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>this.compareFields(i,t[a]))}compareFields(e,t){return e===t||t instanceof e.constructor&&e.name===t.name&&e.nullable===t.nullable&&this.visit(e.type,t.type)}}function At(n,e){return e instanceof n.constructor}function As(n,e){return n===e||At(n,e)}function Mr(n,e){return n===e||At(n,e)&&n.bitWidth===e.bitWidth&&n.isSigned===e.isSigned}function su(n,e){return n===e||At(n,e)&&n.precision===e.precision}function i1(n,e){return n===e||At(n,e)&&n.byteWidth===e.byteWidth}function Jd(n,e){return n===e||At(n,e)&&n.unit===e.unit}function Po(n,e){return n===e||At(n,e)&&n.unit===e.unit&&n.timezone===e.timezone}function zo(n,e){return n===e||At(n,e)&&n.unit===e.unit&&n.bitWidth===e.bitWidth}function o1(n,e){return n===e||At(n,e)&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}function a1(n,e){return n===e||At(n,e)&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}function qd(n,e){return n===e||At(n,e)&&n.mode===e.mode&&n.typeIds.every((t,i)=>t===e.typeIds[i])&&is.compareManyFields(n.children,e.children)}function l1(n,e){return n===e||At(n,e)&&n.id===e.id&&n.isOrdered===e.isOrdered&&is.visit(n.indices,e.indices)&&is.visit(n.dictionary,e.dictionary)}function Zd(n,e){return n===e||At(n,e)&&n.unit===e.unit}function Vo(n,e){return n===e||At(n,e)&&n.unit===e.unit}function u1(n,e){return n===e||At(n,e)&&n.listSize===e.listSize&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}function c1(n,e){return n===e||At(n,e)&&n.keysSorted===e.keysSorted&&n.children.length===e.children.length&&is.compareManyFields(n.children,e.children)}we.prototype.visitNull=As;we.prototype.visitBool=As;we.prototype.visitInt=Mr;we.prototype.visitInt8=Mr;we.prototype.visitInt16=Mr;we.prototype.visitInt32=Mr;we.prototype.visitInt64=Mr;we.prototype.visitUint8=Mr;we.prototype.visitUint16=Mr;we.prototype.visitUint32=Mr;we.prototype.visitUint64=Mr;we.prototype.visitFloat=su;we.prototype.visitFloat16=su;we.prototype.visitFloat32=su;we.prototype.visitFloat64=su;we.prototype.visitUtf8=As;we.prototype.visitLargeUtf8=As;we.prototype.visitBinary=As;we.prototype.visitLargeBinary=As;we.prototype.visitFixedSizeBinary=i1;we.prototype.visitDate=Jd;we.prototype.visitDateDay=Jd;we.prototype.visitDateMillisecond=Jd;we.prototype.visitTimestamp=Po;we.prototype.visitTimestampSecond=Po;we.prototype.visitTimestampMillisecond=Po;we.prototype.visitTimestampMicrosecond=Po;we.prototype.visitTimestampNanosecond=Po;we.prototype.visitTime=zo;we.prototype.visitTimeSecond=zo;we.prototype.visitTimeMillisecond=zo;we.prototype.visitTimeMicrosecond=zo;we.prototype.visitTimeNanosecond=zo;we.prototype.visitDecimal=As;we.prototype.visitList=o1;we.prototype.visitStruct=a1;we.prototype.visitUnion=qd;we.prototype.visitDenseUnion=qd;we.prototype.visitSparseUnion=qd;we.prototype.visitDictionary=l1;we.prototype.visitInterval=Zd;we.prototype.visitIntervalDayTime=Zd;we.prototype.visitIntervalYearMonth=Zd;we.prototype.visitDuration=Vo;we.prototype.visitDurationSecond=Vo;we.prototype.visitDurationMillisecond=Vo;we.prototype.visitDurationMicrosecond=Vo;we.prototype.visitDurationNanosecond=Vo;we.prototype.visitFixedSizeList=u1;we.prototype.visitMap=c1;const is=new we;function d1(n,e){return is.compareSchemas(n,e)}function od(n,e){return f1(n,e.map(t=>t.data.concat()))}function f1(n,e){const t=[...n.fields],i=[],a={numBatches:e.reduce((x,b)=>Math.max(x,b.length),0)};let u=0,f=0,h=-1;const m=e.length;let g,v=[];for(;a.numBatches-- >0;){for(f=Number.POSITIVE_INFINITY,h=-1;++h0&&(i[u++]=Ee({type:new Tt(t),length:f,nullCount:0,children:v.slice()})))}return[n=n.assign(t),i.map(x=>new An(n,x))]}function h1(n,e,t,i,a){var u;const f=(e+63&-64)>>3;for(let h=-1,m=i.length;++h=e)v===e?t[h]=g:(t[h]=g.slice(0,e),a.numBatches=Math.max(a.numBatches,i[h].unshift(g.slice(e,v-e))));else{const x=n[h];n[h]=x.clone({nullable:!0}),t[h]=(u=g==null?void 0:g._changeLengthAndBackfillNullBitmap(e))!==null&&u!==void 0?u:Ee({type:x.type,length:e,nullCount:e,nullBitmap:new Uint8Array(f)})}}return t}var cv;class mn{constructor(...e){var t,i;if(e.length===0)return this.batches=[],this.schema=new We([]),this._offsets=[0],this;let a,u;e[0]instanceof We&&(a=e.shift()),e.at(-1)instanceof Uint32Array&&(u=e.pop());const f=m=>{if(m){if(m instanceof An)return[m];if(m instanceof mn)return m.batches;if(m instanceof Ye){if(m.type instanceof Tt)return[new An(new We(m.type.children),m)]}else{if(Array.isArray(m))return m.flatMap(g=>f(g));if(typeof m[Symbol.iterator]=="function")return[...m].flatMap(g=>f(g));if(typeof m=="object"){const g=Object.keys(m),v=g.map(w=>new Je([m[w]])),x=a??new We(g.map((w,j)=>new nt(String(w),v[j].type,v[j].nullable))),[,b]=od(x,v);return b.length===0?[new An(m)]:b}}}return[]},h=e.flatMap(m=>f(m));if(a=(i=a??((t=h[0])===null||t===void 0?void 0:t.schema))!==null&&i!==void 0?i:new We([]),!(a instanceof We))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");for(const m of h){if(!(m instanceof An))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");if(!d1(a,m.schema))throw new TypeError("Table and inner RecordBatch schemas must be equivalent.")}this.schema=a,this.batches=h,this._offsets=u??Xg(this.data)}get data(){return this.batches.map(({data:e})=>e)}get numCols(){return this.schema.fields.length}get numRows(){return this.data.reduce((e,t)=>e+t.length,0)}get nullCount(){return this._nullCount===-1&&(this._nullCount=Zg(this.data)),this._nullCount}isValid(e){return!1}get(e){return null}at(e){return this.get(Vd(e,this.numRows))}set(e,t){}indexOf(e,t){return-1}[Symbol.iterator](){return this.batches.length>0?Yd.visit(new Je(this.data)):new Array(0)[Symbol.iterator]()}toArray(){return[...this]}toString(){return`[ ${this.toArray().join(`, `)} -]`}concat(...e){const t=this.schema,i=this.data.concat(e.flatMap(({data:a})=>a));return new mn(t,i.map(a=>new An(t,a)))}slice(e,t){const i=this.schema;[e,t]=Yg({length:this.numRows},e,t);const a=qg(this.data,this._offsets,e,t);return new mn(i,a.map(u=>new An(i,u)))}getChild(e){return this.getChildAt(this.schema.fields.findIndex(t=>t.name===e))}getChildAt(e){if(e>-1&&ei.children[e]);if(t.length===0){const{type:i}=this.schema.fields[e],a=Ee({type:i,length:0,nullCount:0});t.push(a._changeLengthAndBackfillNullBitmap(this.numRows))}return new Je(t)}return null}setChild(e,t){var i;return this.setChildAt((i=this.schema.fields)===null||i===void 0?void 0:i.findIndex(a=>a.name===e),t)}setChildAt(e,t){let i=this.schema,a=[...this.batches];if(e>-1&&ethis.getChildAt(g));[u[e],h[e]]=[f,t],[i,a]=od(i,h)}return new mn(i,a)}select(e){const t=this.schema.fields.reduce((i,a,u)=>i.set(a.name,u),new Map);return this.selectAt(e.map(i=>t.get(i)).filter(i=>i>-1))}selectAt(e){const t=this.schema.selectAt(e),i=this.batches.map(a=>a.selectAt(e));return new mn(t,i)}assign(e){const t=this.schema.fields,[i,a]=e.schema.fields.reduce((h,m,g)=>{const[v,x]=h,b=t.findIndex(w=>w.name===m.name);return~b?x[b]=g:v.push(g),h},[[],[]]),u=this.schema.assign(e.schema),f=[...t.map((h,m)=>[m,a[m]]).map(([h,m])=>m===void 0?this.getChildAt(h):e.getChildAt(m)),...i.map(h=>e.getChildAt(h))].filter(Boolean);return new mn(...od(u,f))}}av=Symbol.toStringTag;mn[av]=(n=>(n.schema=null,n.batches=[],n._offsets=new Uint32Array([0]),n._nullCount=-1,n[Symbol.isConcatSpreadable]=!0,n.isValid=zl(Gd),n.get=zl(Gt.getVisitFn(M.Struct)),n.set=Zg(vn.getVisitFn(M.Struct)),n.indexOf=Xg(Vl.getVisitFn(M.Struct)),"Table"))(mn.prototype);var lv;let An=class Oo{constructor(...e){switch(e.length){case 2:{if([this.schema]=e,!(this.schema instanceof We))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");if([,this.data=Ee({nullCount:0,type:new Tt(this.schema.fields),children:this.schema.fields.map(t=>Ee({type:t.type,nullCount:0}))})]=e,!(this.data instanceof Ye))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");[this.schema,this.data]=Mm(this.schema,this.data.children);break}case 1:{const[t]=e,{fields:i,children:a,length:u}=Object.keys(t).reduce((m,g,v)=>(m.children[v]=t[g],m.length=Math.max(m.length,t[g].length),m.fields[v]=nt.new({name:g,type:t[g].type,nullable:!0}),m),{length:0,fields:new Array,children:new Array}),f=new We(i),h=Ee({type:new Tt(i),length:u,children:a,nullCount:0});[this.schema,this.data]=Mm(f,h.children,u);break}default:throw new TypeError("RecordBatch constructor expects an Object mapping names to child Data, or a [Schema, Data] pair.")}}get dictionaries(){return this._dictionaries||(this._dictionaries=uv(this.schema.fields,this.data.children))}get numCols(){return this.schema.fields.length}get numRows(){return this.data.length}get nullCount(){return this.data.nullCount}isValid(e){return this.data.getValid(e)}get(e){return Gt.visit(this.data,e)}at(e){return this.get(Vd(e,this.numRows))}set(e,t){return vn.visit(this.data,e,t)}indexOf(e,t){return Vl.visit(this.data,e,t)}[Symbol.iterator](){return Yd.visit(new Je([this.data]))}toArray(){return[...this]}concat(...e){return new mn(this.schema,[this,...e])}slice(e,t){const[i]=new Je([this.data]).slice(e,t).data;return new Oo(this.schema,i)}getChild(e){var t;return this.getChildAt((t=this.schema.fields)===null||t===void 0?void 0:t.findIndex(i=>i.name===e))}getChildAt(e){return e>-1&&ea.name===e),t)}setChildAt(e,t){let i=this.schema,a=this.data;if(e>-1&&eh.name===u);~f&&(a[f]=this.data.children[f])}return new Oo(t,Ee({type:i,length:this.numRows,children:a}))}selectAt(e){const t=this.schema.selectAt(e),i=e.map(u=>this.data.children[u]).filter(Boolean),a=Ee({type:new Tt(t.fields),length:this.numRows,children:i});return new Oo(t,a)}};lv=Symbol.toStringTag;An[lv]=(n=>(n._nullCount=-1,n[Symbol.isConcatSpreadable]=!0,"RecordBatch"))(An.prototype);function Mm(n,e,t=e.reduce((i,a)=>Math.max(i,a.length),0)){var i;const a=[...n.fields],u=[...e],f=(t+63&-64)>>3;for(const[h,m]of n.fields.entries()){const g=e[h];(!g||g.length!==t)&&(a[h]=m.clone({nullable:!0}),u[h]=(i=g==null?void 0:g._changeLengthAndBackfillNullBitmap(t))!==null&&i!==void 0?i:Ee({type:m.type,length:t,nullCount:t,nullBitmap:new Uint8Array(f)}))}return[n.assign(a),Ee({type:new Tt(a),length:t,children:u})]}function uv(n,e,t=new Map){var i,a;if(((i=n==null?void 0:n.length)!==null&&i!==void 0?i:0)>0&&(n==null?void 0:n.length)===(e==null?void 0:e.length))for(let u=-1,f=n.length;++uEe({type:a.type})),i=Ee({type:new Tt(e.fields),nullCount:0,children:t});super(e,i)}}let qr=class Hn{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsMessage(e,t){return(t||new Hn).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsMessage(e,t){return e.setPosition(e.position()+He),(t||new Hn).__init(e.readInt32(e.position())+e.position(),e)}version(){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):ht.V1}headerType(){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb_pos+e):Ve.NONE}header(e){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__union(e,this.bb_pos+t):null}bodyLength(){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt64(this.bb_pos+e):BigInt("0")}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,12);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}static startMessage(e){e.startObject(5)}static addVersion(e,t){e.addFieldInt16(0,t,ht.V1)}static addHeaderType(e,t){e.addFieldInt8(1,t,Ve.NONE)}static addHeader(e,t){e.addFieldOffset(2,t,0)}static addBodyLength(e,t){e.addFieldInt64(3,t,BigInt("0"))}static addCustomMetadata(e,t){e.addFieldOffset(4,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endMessage(e){return e.endObject()}static finishMessageBuffer(e,t){e.finish(t)}static finishSizePrefixedMessageBuffer(e,t){e.finish(t,void 0,!0)}static createMessage(e,t,i,a,u,f){return Hn.startMessage(e),Hn.addVersion(e,t),Hn.addHeaderType(e,i),Hn.addHeader(e,a),Hn.addBodyLength(e,u),Hn.addCustomMetadata(e,f),Hn.endMessage(e)}};class d1 extends Re{visit(e,t){return e==null||t==null?void 0:super.visit(e,t)}visitNull(e,t){return vm.startNull(t),vm.endNull(t)}visitInt(e,t){return en.startInt(t),en.addBitWidth(t,e.bitWidth),en.addIsSigned(t,e.isSigned),en.endInt(t)}visitFloat(e,t){return Kn.startFloatingPoint(t),Kn.addPrecision(t,e.precision),Kn.endFloatingPoint(t)}visitBinary(e,t){return hm.startBinary(t),hm.endBinary(t)}visitLargeBinary(e,t){return mm.startLargeBinary(t),mm.endLargeBinary(t)}visitBool(e,t){return pm.startBool(t),pm.endBool(t)}visitUtf8(e,t){return xm.startUtf8(t),xm.endUtf8(t)}visitLargeUtf8(e,t){return ym.startLargeUtf8(t),ym.endLargeUtf8(t)}visitDecimal(e,t){return ci.startDecimal(t),ci.addScale(t,e.scale),ci.addPrecision(t,e.precision),ci.addBitWidth(t,e.bitWidth),ci.endDecimal(t)}visitDate(e,t){return hl.startDate(t),hl.addUnit(t,e.unit),hl.endDate(t)}visitTime(e,t){return hn.startTime(t),hn.addUnit(t,e.unit),hn.addBitWidth(t,e.bitWidth),hn.endTime(t)}visitTimestamp(e,t){const i=e.timezone&&t.createString(e.timezone)||void 0;return pn.startTimestamp(t),pn.addUnit(t,e.unit),i!==void 0&&pn.addTimezone(t,i),pn.endTimestamp(t)}visitInterval(e,t){return Jn.startInterval(t),Jn.addUnit(t,e.unit),Jn.endInterval(t)}visitDuration(e,t){return pl.startDuration(t),pl.addUnit(t,e.unit),pl.endDuration(t)}visitList(e,t){return gm.startList(t),gm.endList(t)}visitStruct(e,t){return ks.startStruct_(t),ks.endStruct_(t)}visitUnion(e,t){Vt.startTypeIdsVector(t,e.typeIds.length);const i=Vt.createTypeIdsVector(t,e.typeIds);return Vt.startUnion(t),Vt.addMode(t,e.mode),Vt.addTypeIds(t,i),Vt.endUnion(t)}visitDictionary(e,t){const i=this.visit(e.indices,t);return wr.startDictionaryEncoding(t),wr.addId(t,BigInt(e.id)),wr.addIsOrdered(t,e.isOrdered),i!==void 0&&wr.addIndexType(t,i),wr.endDictionaryEncoding(t)}visitFixedSizeBinary(e,t){return ml.startFixedSizeBinary(t),ml.addByteWidth(t,e.byteWidth),ml.endFixedSizeBinary(t)}visitFixedSizeList(e,t){return yl.startFixedSizeList(t),yl.addListSize(t,e.listSize),yl.endFixedSizeList(t)}visitMap(e,t){return gl.startMap(t),gl.addKeysSorted(t,e.keysSorted),gl.endMap(t)}}const ad=new d1;function f1(n,e=new Map){return new We(p1(n,e),xl(n.metadata),e)}function dv(n){return new Rn(n.count,fv(n.columns),hv(n.columns))}function h1(n){return new kr(dv(n.data),n.id,n.isDelta)}function p1(n,e){return(n.fields||[]).filter(Boolean).map(t=>nt.fromJSON(t,e))}function Dm(n,e){return(n.children||[]).filter(Boolean).map(t=>nt.fromJSON(t,e))}function fv(n){return(n||[]).reduce((e,t)=>[...e,new Ai(t.count,m1(t.VALIDITY)),...fv(t.children)],[])}function hv(n,e=[]){for(let t=-1,i=(n||[]).length;++te+ +(t===0),0)}function y1(n,e){let t,i,a,u,f,h;return!e||!(u=n.dictionary)?(f=Fm(n,Dm(n,e)),a=new nt(n.name,f,n.nullable,xl(n.metadata))):e.has(t=u.id)?(i=(i=u.indexType)?Cm(i):new Lo,h=new Mi(e.get(t),i,t,u.isOrdered),a=new nt(n.name,h,n.nullable,xl(n.metadata))):(i=(i=u.indexType)?Cm(i):new Lo,e.set(t,f=Fm(n,Dm(n,e))),h=new Mi(f,i,t,u.isOrdered),a=new nt(n.name,h,n.nullable,xl(n.metadata))),a||null}function xl(n=[]){return new Map(n.map(({key:e,value:t})=>[e,t]))}function Cm(n){return new Ds(n.isSigned,n.bitWidth)}function Fm(n,e){const t=n.type.name;switch(t){case"NONE":return new ss;case"null":return new ss;case"binary":return new kl;case"largebinary":return new Il;case"utf8":return new Ml;case"largeutf8":return new Dl;case"bool":return new Cl;case"list":return new Rl((e||[])[0]);case"struct":return new Tt(e||[]);case"struct_":return new Tt(e||[])}switch(t){case"int":{const i=n.type;return new Ds(i.isSigned,i.bitWidth)}case"floatingpoint":{const i=n.type;return new jl(Dt[i.precision])}case"decimal":{const i=n.type;return new Fl(i.scale,i.precision,i.bitWidth)}case"date":{const i=n.type;return new Ol(gn[i.unit])}case"time":{const i=n.type;return new Tl(_e[i.unit],i.bitWidth)}case"timestamp":{const i=n.type;return new Al(_e[i.unit],i.timezone)}case"interval":{const i=n.type;return new Bl(nr[i.unit])}case"duration":{const i=n.type;return new El(_e[i.unit])}case"union":{const i=n.type,[a,...u]=(i.mode+"").toLowerCase(),f=a.toUpperCase()+u.join("");return new Ll(Ht[f],i.typeIds||[],e||[])}case"fixedsizebinary":{const i=n.type;return new Ul(i.byteWidth)}case"fixedsizelist":{const i=n.type;return new $l(i.listSize,(e||[])[0])}case"map":{const i=n.type;return new Pl((e||[])[0],i.keysSorted)}}throw new Error(`Unrecognized type: "${t}"`)}var g1=Iy,v1=ki;class Bn{static fromJSON(e,t){const i=new Bn(0,ht.V5,t);return i._createHeader=x1(e,t),i}static decode(e){e=new v1($e(e));const t=qr.getRootAsMessage(e),i=t.bodyLength(),a=t.version(),u=t.headerType(),f=new Bn(i,a,u);return f._createHeader=b1(t,u),f}static encode(e){const t=new g1;let i=-1;return e.isSchema()?i=We.encode(t,e.header()):e.isRecordBatch()?i=Rn.encode(t,e.header()):e.isDictionaryBatch()&&(i=kr.encode(t,e.header())),qr.startMessage(t),qr.addVersion(t,ht.V5),qr.addHeader(t,i),qr.addHeaderType(t,e.headerType),qr.addBodyLength(t,BigInt(e.bodyLength)),qr.finishMessageBuffer(t,qr.endMessage(t)),t.asUint8Array()}static from(e,t=0){if(e instanceof We)return new Bn(0,ht.V5,Ve.Schema,e);if(e instanceof Rn)return new Bn(t,ht.V5,Ve.RecordBatch,e);if(e instanceof kr)return new Bn(t,ht.V5,Ve.DictionaryBatch,e);throw new Error(`Unrecognized Message header: ${e}`)}get type(){return this.headerType}get version(){return this._version}get headerType(){return this._headerType}get bodyLength(){return this._bodyLength}header(){return this._createHeader()}isSchema(){return this.headerType===Ve.Schema}isRecordBatch(){return this.headerType===Ve.RecordBatch}isDictionaryBatch(){return this.headerType===Ve.DictionaryBatch}constructor(e,t,i,a){this._version=t,this._headerType=i,this.body=new Uint8Array(0),a&&(this._createHeader=()=>a),this._bodyLength=tt(e)}}class Rn{get nodes(){return this._nodes}get length(){return this._length}get buffers(){return this._buffers}constructor(e,t,i){this._nodes=t,this._buffers=i,this._length=tt(e)}}class kr{get id(){return this._id}get data(){return this._data}get isDelta(){return this._isDelta}get length(){return this.data.length}get nodes(){return this.data.nodes}get buffers(){return this.data.buffers}constructor(e,t,i=!1){this._data=e,this._isDelta=i,this._id=tt(t)}}class _r{constructor(e,t){this.offset=tt(e),this.length=tt(t)}}class Ai{constructor(e,t){this.length=tt(e),this.nullCount=tt(t)}}function x1(n,e){return(()=>{switch(e){case Ve.Schema:return We.fromJSON(n);case Ve.RecordBatch:return Rn.fromJSON(n);case Ve.DictionaryBatch:return kr.fromJSON(n)}throw new Error(`Unrecognized Message type: { name: ${Ve[e]}, type: ${e} }`)})}function b1(n,e){return(()=>{switch(e){case Ve.Schema:return We.decode(n.header(new Gn),new Map,n.version());case Ve.RecordBatch:return Rn.decode(n.header(new yr),n.version());case Ve.DictionaryBatch:return kr.decode(n.header(new li),n.version())}throw new Error(`Unrecognized Message type: { name: ${Ve[e]}, type: ${e} }`)})}nt.encode=F1;nt.decode=D1;nt.fromJSON=y1;We.encode=C1;We.decode=w1;We.fromJSON=f1;Rn.encode=O1;Rn.decode=S1;Rn.fromJSON=dv;kr.encode=T1;kr.decode=_1;kr.fromJSON=h1;Ai.encode=A1;Ai.decode=j1;_r.encode=B1;_r.decode=N1;function w1(n,e=new Map,t=ht.V5){const i=M1(n,e);return new We(i,bl(n),e,t)}function S1(n,e=ht.V5){if(n.compression()!==null)throw new Error("Record batch compression not implemented");return new Rn(n.length(),k1(n),I1(n,e))}function _1(n,e=ht.V5){return new kr(Rn.decode(n.data(),e),n.id(),n.isDelta())}function N1(n){return new _r(n.offset(),n.length())}function j1(n){return new Ai(n.length(),n.nullCount())}function k1(n){const e=[];for(let t,i=-1,a=-1,u=n.nodesLength();++int.encode(n,u));Gn.startFieldsVector(n,t.length);const i=Gn.createFieldsVector(n,t),a=e.metadata&&e.metadata.size>0?Gn.createCustomMetadataVector(n,[...e.metadata].map(([u,f])=>{const h=n.createString(`${u}`),m=n.createString(`${f}`);return gt.startKeyValue(n),gt.addKey(n,h),gt.addValue(n,m),gt.endKeyValue(n)})):-1;return Gn.startSchema(n),Gn.addFields(n,i),Gn.addEndianness(n,E1?Ii.Little:Ii.Big),a!==-1&&Gn.addCustomMetadata(n,a),Gn.endSchema(n)}function F1(n,e){let t=-1,i=-1,a=-1;const u=e.type;let f=e.typeId;me.isDictionary(u)?(f=u.dictionary.typeId,a=ad.visit(u,n),i=ad.visit(u.dictionary,n)):i=ad.visit(u,n);const h=(u.children||[]).map(v=>nt.encode(n,v)),m=dn.createChildrenVector(n,h),g=e.metadata&&e.metadata.size>0?dn.createCustomMetadataVector(n,[...e.metadata].map(([v,x])=>{const b=n.createString(`${v}`),w=n.createString(`${x}`);return gt.startKeyValue(n),gt.addKey(n,b),gt.addValue(n,w),gt.endKeyValue(n)})):-1;return e.name&&(t=n.createString(e.name)),dn.startField(n),dn.addType(n,i),dn.addTypeType(n,f),dn.addChildren(n,m),dn.addNullable(n,!!e.nullable),t!==-1&&dn.addName(n,t),a!==-1&&dn.addDictionary(n,a),g!==-1&&dn.addCustomMetadata(n,g),dn.endField(n)}function O1(n,e){const t=e.nodes||[],i=e.buffers||[];yr.startNodesVector(n,t.length);for(const f of t.slice().reverse())Ai.encode(n,f);const a=n.endVector();yr.startBuffersVector(n,i.length);for(const f of i.slice().reverse())_r.encode(n,f);const u=n.endVector();return yr.startRecordBatch(n),yr.addLength(n,BigInt(e.length)),yr.addNodes(n,a),yr.addBuffers(n,u),yr.endRecordBatch(n)}function T1(n,e){const t=Rn.encode(n,e.data);return li.startDictionaryBatch(n),li.addId(n,BigInt(e.id)),li.addIsDelta(n,e.isDelta),li.addData(n,t),li.endDictionaryBatch(n)}function A1(n,e){return Cy.createFieldNode(n,BigInt(e.length),BigInt(e.nullCount))}function B1(n,e){return Dy.createBuffer(n,BigInt(e.offset),BigInt(e.length))}const E1=(()=>{const n=new ArrayBuffer(2);return new DataView(n).setInt16(0,256,!0),new Int16Array(n)[0]===256})(),Xd=n=>`Expected ${Ve[n]} Message in stream, but was null or length 0.`,ef=n=>`Header pointer of flatbuffer-encoded ${Ve[n]} Message is null or length 0.`,pv=(n,e)=>`Expected to read ${n} metadata bytes, but only read ${e}.`,mv=(n,e)=>`Expected to read ${n} bytes for message body, but only read ${e}.`;class yv{constructor(e){this.source=e instanceof Hl?e:new Hl(e)}[Symbol.iterator](){return this}next(){let e;return(e=this.readMetadataLength()).done||e.value===-1&&(e=this.readMetadataLength()).done||(e=this.readMetadata(e.value)).done?at:e}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}readMessage(e){let t;if((t=this.next()).done)return null;if(e!=null&&t.value.headerType!==e)throw new Error(Xd(e));return t.value}readMessageBody(e){if(e<=0)return new Uint8Array(0);const t=$e(this.source.read(e));if(t.byteLength[...a,...u.VALIDITY&&[u.VALIDITY]||[],...u.TYPE_ID&&[u.TYPE_ID]||[],...u.OFFSET&&[u.OFFSET]||[],...u.DATA&&[u.DATA]||[],...t(u.children)],[])}}readMessage(e){let t;if((t=this.next()).done)return null;if(e!=null&&t.value.headerType!==e)throw new Error(Xd(e));return t.value}readSchema(){const e=Ve.Schema,t=this.readMessage(e),i=t==null?void 0:t.header();if(!t||!i)throw new Error(ef(e));return i}}const iu=4,Cd="ARROW1",Yl=new Uint8Array(Cd.length);for(let n=0;nthis):this}readRecordBatch(e){return this._impl.isFile()?this._impl.readRecordBatch(e):null}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}toDOMStream(){return fn.toDOMStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this})}toNodeStream(){return fn.toNodeStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this},{objectMode:!0})}static throughNode(e){throw new Error('"throughNode" not available in this environment')}static throughDOM(e,t){throw new Error('"throughDOM" not available in this environment')}static from(e){return e instanceof jr?e:bd(e)?V1(e):wy(e)?G1(e):Ao(e)?Fe(this,void 0,void 0,function*(){return yield jr.from(yield e)}):Sy(e)||Rd(e)||Ny(e)||Ed(e)?H1(new Ci(e)):W1(new Hl(e))}static readAll(e){return e instanceof jr?e.isSync()?Bm(e):Em(e):bd(e)||ArrayBuffer.isView(e)||nu(e)||by(e)?Bm(e):Em(e)}}class Ql extends jr{constructor(e){super(e),this._impl=e}readAll(){return[...this]}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return qn(this,arguments,function*(){yield Ae(yield*fl(xi(this[Symbol.iterator]())))})}}class Kl extends jr{constructor(e){super(e),this._impl=e}readAll(){return Fe(this,void 0,void 0,function*(){var e,t,i,a;const u=new Array;try{for(var f=!0,h=xi(this),m;m=yield h.next(),e=m.done,!e;f=!0){a=m.value,f=!1;const g=a;u.push(g)}}catch(g){t={error:g}}finally{try{!f&&!e&&(i=h.return)&&(yield i.call(h))}finally{if(t)throw t.error}}return u})}[Symbol.iterator](){throw new Error("AsyncRecordBatchStreamReader is not Iterable")}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}}class vv extends Ql{constructor(e){super(e),this._impl=e}}class $1 extends Kl{constructor(e){super(e),this._impl=e}}class xv{get numDictionaries(){return this._dictionaryIndex}get numRecordBatches(){return this._recordBatchIndex}constructor(e=new Map){this.closed=!1,this.autoDestroy=!0,this._dictionaryIndex=0,this._recordBatchIndex=0,this.dictionaries=e}isSync(){return!1}isAsync(){return!1}isFile(){return!1}isStream(){return!1}reset(e){return this._dictionaryIndex=0,this._recordBatchIndex=0,this.schema=e,this.dictionaries=new Map,this}_loadRecordBatch(e,t){const i=this._loadVectors(e,t,this.schema.fields),a=Ee({type:new Tt(this.schema.fields),length:e.length,children:i});return new An(this.schema,a)}_loadDictionaryBatch(e,t){const{id:i,isDelta:a}=e,{dictionaries:u,schema:f}=this,h=u.get(i),m=f.dictionaries.get(i),g=this._loadVectors(e.data,t,[m]);return(h&&a?h.concat(new Je(g)):new Je(g)).memoize()}_loadVectors(e,t,i){return new ov(t,e.nodes,e.buffers,this.dictionaries,this.schema.metadataVersion).visitMany(i)}}class Jl extends xv{constructor(e,t){super(t),this._reader=bd(e)?new L1(this._handle=e):new yv(this._handle=e)}isSync(){return!0}isStream(){return!0}[Symbol.iterator](){return this}cancel(){!this.closed&&(this.closed=!0)&&(this.reset()._reader.return(),this._reader=null,this.dictionaries=null)}open(e){return this.closed||(this.autoDestroy=wv(this,e),this.schema||(this.schema=this._reader.readSchema())||this.cancel()),this}throw(e){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.throw(e):at}return(e){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.return(e):at}next(){if(this.closed)return at;let e;const{_reader:t}=this;for(;e=this._readNextMessageAndValidate();)if(e.isSchema())this.reset(e.header());else if(e.isRecordBatch()){this._recordBatchIndex++;const i=e.header(),a=t.readMessageBody(e.bodyLength);return{done:!1,value:this._loadRecordBatch(i,a)}}else if(e.isDictionaryBatch()){this._dictionaryIndex++;const i=e.header(),a=t.readMessageBody(e.bodyLength),u=this._loadDictionaryBatch(i,a);this.dictionaries.set(i.id,u)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new cv(this.schema)}):this.return()}_readNextMessageAndValidate(e){return this._reader.readMessage(e)}}class ql extends xv{constructor(e,t){super(t),this._reader=new R1(this._handle=e)}isAsync(){return!0}isStream(){return!0}[Symbol.asyncIterator](){return this}cancel(){return Fe(this,void 0,void 0,function*(){!this.closed&&(this.closed=!0)&&(yield this.reset()._reader.return(),this._reader=null,this.dictionaries=null)})}open(e){return Fe(this,void 0,void 0,function*(){return this.closed||(this.autoDestroy=wv(this,e),this.schema||(this.schema=yield this._reader.readSchema())||(yield this.cancel())),this})}throw(e){return Fe(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.throw(e):at})}return(e){return Fe(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.return(e):at})}next(){return Fe(this,void 0,void 0,function*(){if(this.closed)return at;let e;const{_reader:t}=this;for(;e=yield this._readNextMessageAndValidate();)if(e.isSchema())yield this.reset(e.header());else if(e.isRecordBatch()){this._recordBatchIndex++;const i=e.header(),a=yield t.readMessageBody(e.bodyLength);return{done:!1,value:this._loadRecordBatch(i,a)}}else if(e.isDictionaryBatch()){this._dictionaryIndex++;const i=e.header(),a=yield t.readMessageBody(e.bodyLength),u=this._loadDictionaryBatch(i,a);this.dictionaries.set(i.id,u)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new cv(this.schema)}):yield this.return()})}_readNextMessageAndValidate(e){return Fe(this,void 0,void 0,function*(){return yield this._reader.readMessage(e)})}}class bv extends Jl{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(e,t){super(e instanceof Im?e:new Im(e),t)}isSync(){return!0}isFile(){return!0}open(e){if(!this.closed&&!this._footer){this.schema=(this._footer=this._readFooter()).schema;for(const t of this._footer.dictionaryBatches())t&&this._readDictionaryBatch(this._dictionaryIndex++)}return super.open(e)}readRecordBatch(e){var t;if(this.closed)return null;this._footer||this.open();const i=(t=this._footer)===null||t===void 0?void 0:t.getRecordBatch(e);if(i&&this._handle.seek(i.offset)){const a=this._reader.readMessage(Ve.RecordBatch);if(a!=null&&a.isRecordBatch()){const u=a.header(),f=this._reader.readMessageBody(a.bodyLength);return this._loadRecordBatch(u,f)}}return null}_readDictionaryBatch(e){var t;const i=(t=this._footer)===null||t===void 0?void 0:t.getDictionaryBatch(e);if(i&&this._handle.seek(i.offset)){const a=this._reader.readMessage(Ve.DictionaryBatch);if(a!=null&&a.isDictionaryBatch()){const u=a.header(),f=this._reader.readMessageBody(a.bodyLength),h=this._loadDictionaryBatch(u,f);this.dictionaries.set(u.id,h)}}}_readFooter(){const{_handle:e}=this,t=e.size-gv,i=e.readInt32(t),a=e.readAt(t-i,i);return Qd.decode(a)}_readNextMessageAndValidate(e){var t;if(this._footer||this.open(),this._footer&&this._recordBatchIndexsuper.open}});return Fe(this,void 0,void 0,function*(){if(!this.closed&&!this._footer){this.schema=(this._footer=yield this._readFooter()).schema;for(const i of this._footer.dictionaryBatches())i&&(yield this._readDictionaryBatch(this._dictionaryIndex++))}return yield t.open.call(this,e)})}readRecordBatch(e){return Fe(this,void 0,void 0,function*(){var t;if(this.closed)return null;this._footer||(yield this.open());const i=(t=this._footer)===null||t===void 0?void 0:t.getRecordBatch(e);if(i&&(yield this._handle.seek(i.offset))){const a=yield this._reader.readMessage(Ve.RecordBatch);if(a!=null&&a.isRecordBatch()){const u=a.header(),f=yield this._reader.readMessageBody(a.bodyLength);return this._loadRecordBatch(u,f)}}return null})}_readDictionaryBatch(e){return Fe(this,void 0,void 0,function*(){var t;const i=(t=this._footer)===null||t===void 0?void 0:t.getDictionaryBatch(e);if(i&&(yield this._handle.seek(i.offset))){const a=yield this._reader.readMessage(Ve.DictionaryBatch);if(a!=null&&a.isDictionaryBatch()){const u=a.header(),f=yield this._reader.readMessageBody(a.bodyLength),h=this._loadDictionaryBatch(u,f);this.dictionaries.set(u.id,h)}}})}_readFooter(){return Fe(this,void 0,void 0,function*(){const{_handle:e}=this;e._pending&&(yield e._pending);const t=e.size-gv,i=yield e.readInt32(t),a=yield e.readAt(t-i,i);return Qd.decode(a)})}_readNextMessageAndValidate(e){return Fe(this,void 0,void 0,function*(){if(this._footer||(yield this.open()),this._footer&&this._recordBatchIndex=4?tf(e)?new vv(new bv(n.read())):new Ql(new Jl(n)):new Ql(new Jl((function*(){})()))}function H1(n){return Fe(this,void 0,void 0,function*(){const e=yield n.peek(Wo+7&-8);return e&&e.byteLength>=4?tf(e)?new vv(new bv(yield n.read())):new Kl(new ql(n)):new Kl(new ql((function(){return qn(this,arguments,function*(){})})()))})}function G1(n){return Fe(this,void 0,void 0,function*(){const{size:e}=yield n.stat(),t=new Gl(n,e);return e>=U1&&tf(yield t.readAt(0,Wo+7&-8))?new $1(new P1(t)):new Kl(new ql(t))})}function Sv(n){const e=jr.from(n);return Ao(e)?e.then(t=>Sv(t)):e.isAsync()?e.readAll().then(t=>new mn(t)):new mn(e.readAll())}function Y1(n){if(n==null)return null;if(typeof n=="bigint"){const e=Number(n);return Number.isSafeInteger(e)?e:n.toString()}if(n instanceof Date){const e=n.toISOString();return e.endsWith("T00:00:00.000Z")?e.slice(0,10):e}return typeof n=="object"?String(n):n}function Q1(n){const e=Sv(n),t=e.schema.fields.map(a=>a.name),i=new Array(e.numRows);for(let a=0;a({...e,charts:e.charts.map(t=>{var f,h;const i=t.query,a=(f=t.interactions)==null?void 0:f.brush,u=(h=t.interactions)==null?void 0:h.select;return{...t,query:{...i,metrics:Zr(i.metrics)??[],dimensions:Zr(i.dimensions),filters:Zr(i.filters),segments:Zr(i.segments),order_by:Zr(i.order_by),orderBy:Zr(i.orderBy)},interactions:t.interactions?{...t.interactions,brush:typeof a=="object"?{...a,fields:Zr(a.fields)}:a,select:typeof u=="object"?{...u,fields:Zr(u.fields)}:u}:void 0}})}))}}const J1="application/vnd.apache.arrow.stream";class q1{constructor(e){Mn(this,"active",0);Mn(this,"waiters",[]);this.max=e}async run(e){var t;this.active>=this.max&&await new Promise(i=>this.waiters.push(i)),this.active+=1;try{return await e()}finally{this.active-=1,(t=this.waiters.shift())==null||t()}}}function Z1(n){var t,i,a,u,f;const e={};return(t=n.metrics)!=null&&t.length&&(e.metrics=n.metrics),(i=n.dimensions)!=null&&i.length&&(e.dimensions=n.dimensions),(a=n.filters)!=null&&a.length&&(e.filters=n.filters),(u=n.segments)!=null&&u.length&&(e.segments=n.segments),(f=n.orderBy)!=null&&f.length&&(e.order_by=n.orderBy),n.limit!=null&&(e.limit=n.limit),n.offset!=null&&(e.offset=n.offset),n.ungrouped&&(e.ungrouped=!0),n.parameters&&(e.parameters=n.parameters),n.usePreaggregations!=null&&(e.use_preaggregations=n.usePreaggregations),n.timezone&&n.timezone!=="UTC"&&(e.timezone=n.timezone),e}class X1{constructor(e={}){Mn(this,"baseUrl");Mn(this,"token");Mn(this,"sessionToken");Mn(this,"transport");Mn(this,"usePreaggregations");Mn(this,"gate");Mn(this,"onUnauthorized");this.baseUrl=(e.baseUrl??"").replace(/\/$/,""),this.token=e.token,this.transport=e.transport??"json",this.usePreaggregations=e.usePreaggregations??!0,this.gate=new q1(e.maxConcurrency??6),this.onUnauthorized=e.onUnauthorized}body(e){return Z1({usePreaggregations:this.usePreaggregations,...e})}headers(e){const t={...e};return this.sessionToken?t.Authorization=`Sidemantic-Session ${this.sessionToken}`:this.token&&(t.Authorization=`Bearer ${this.token}`),t}isCrossOrigin(){return!this.baseUrl||typeof globalThis.location>"u"?!1:new URL(this.baseUrl,globalThis.location.href).origin!==globalThis.location.origin}url(e){return`${this.baseUrl}${e}`}async getJson(e){const t=await fetch(this.url(e),{headers:this.headers(),credentials:"include"});if(!t.ok)throw new Error(await this.errorText(t,e));return await t.json()}async errorText(e,t){var a;e.status===401&&((a=this.onUnauthorized)==null||a.call(this));let i="";try{const u=await e.json();i=u.error??u.detail??""}catch{}return`${t} failed (${e.status})${i?`: ${i}`:""}`}async health(){try{return(await fetch(this.url("/health"),{headers:this.headers(),credentials:"include"})).ok}catch{return!1}}async getCatalog(){try{const t=await fetch(this.url("/describe"),{headers:this.headers(),credentials:"include"});if(t.ok){const i=vb(await t.json());try{return bb(i,await this.getJson("/graph"))}catch{return i}}}catch{}const e=await this.getJson("/graph");return xb(e)}async getDashboard(){try{const e=await fetch(this.url("/dashboard"),{headers:this.headers()});if(e.status===404)return null;if(!e.ok)throw new Error(await this.errorText(e,"/dashboard"));if(!(e.headers.get("content-type")??"").includes("application/json"))return null;const t=await e.json();return typeof t.title=="string"&&Array.isArray(t.tabs)?K1(t):null}catch{return null}}async compile(e){const t=await fetch(this.url("/compile"),{method:"POST",headers:this.headers({"Content-Type":"application/json"}),credentials:"include",body:JSON.stringify(this.body(e))});if(!t.ok)throw new Error(await this.errorText(t,"/compile"));return(await t.json()).sql}async runQuery(e){return this.gate.run(()=>this.transport==="arrow"?this.runQueryArrow(e):this.runQueryJson(e))}async runQueryJson(e){const t=await fetch(this.url("/query"),{method:"POST",headers:this.headers({"Content-Type":"application/json"}),credentials:"include",body:JSON.stringify(this.body(e))});if(!t.ok)throw new Error(await this.errorText(t,"/query"));const i=await t.json(),a=i.rows??[];return{columns:a.length?Object.keys(a[0]):[],rows:a,rowCount:i.row_count??a.length,sql:i.sql??""}}async runQueryArrow(e){const t=await fetch(this.url("/query?format=arrow"),{method:"POST",headers:this.headers({"Content-Type":"application/json",Accept:J1}),credentials:"include",body:JSON.stringify(this.body(e))});if(!t.ok)throw new Error(await this.errorText(t,"/query"));const i=new Uint8Array(await t.arrayBuffer()),{columns:a,rows:u}=Q1(i),f=t.headers.get("X-Sidemantic-Sql")??"";return{columns:a,rows:u,rowCount:u.length,sql:f}}async createBrowserSession(e){var a;const t=this.isCrossOrigin(),i=await fetch(this.url("/auth/session"),{method:"POST",headers:{Authorization:`Bearer ${e}`,...t?{"X-Sidemantic-Session-Mode":"header"}:{}},credentials:"include"});if(i.status===404||i.ok&&!((a=i.headers.get("content-type"))!=null&&a.includes("application/json"))){this.token=e;return}if(!i.ok)throw new Error(await this.errorText(i,"/auth/session"));if(t){const u=await i.json();if(!u.session_token)throw new Error("/auth/session did not return a cross-origin session token");this.sessionToken=u.session_token}this.token=void 0}}function _v({brand:n,toolbar:e,filters:t,rail:i,children:a,drawer:u,showRail:f=!0,openRailRequest:h}){const[m,g]=D.useState(()=>typeof window<"u"&&window.matchMedia("(max-width: 767px)").matches),[v,x]=D.useState(()=>typeof window>"u"||!window.matchMedia("(max-width: 767px)").matches),b=D.useId(),w=D.useRef(null),j=D.useRef(null),C=f&&v;return D.useEffect(()=>{const O=window.matchMedia("(max-width: 767px)"),H=()=>{g(O.matches),x(!O.matches)};return O.addEventListener("change",H),()=>O.removeEventListener("change",H)},[]),D.useEffect(()=>{h&&!m&&x(!0)},[h,m]),D.useEffect(()=>{if(!m||!v)return;const O=j.current,H=document.body.style.overflow;document.body.style.overflow="hidden",window.requestAnimationFrame(()=>{var R,T;return(T=(R=w.current)==null?void 0:R.querySelector("button"))==null?void 0:T.focus()});function L(R){var U;if(R.key==="Escape"){R.preventDefault(),x(!1);return}if(R.key!=="Tab")return;const T=(U=w.current)==null?void 0:U.querySelectorAll('button:not(:disabled), select:not(:disabled), input:not(:disabled), [href], [tabindex]:not([tabindex="-1"])');if(!(T!=null&&T.length))return;const E=T[0],I=T[T.length-1];R.shiftKey&&document.activeElement===E?(R.preventDefault(),I.focus()):!R.shiftKey&&document.activeElement===I&&(R.preventDefault(),E.focus())}return document.addEventListener("keydown",L,!0),()=>{document.body.style.overflow=H,document.removeEventListener("keydown",L,!0),O==null||O.focus()}},[m,v]),c.jsxs("div",{className:"flex h-[100dvh] min-w-0 flex-col overflow-hidden bg-bg text-ink",children:[c.jsxs("header",{className:"relative z-40 flex shrink-0 flex-col gap-2 border-b border-line bg-surface px-3 py-2 md:flex-row md:items-center md:justify-between md:gap-3",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[f?c.jsx("button",{ref:j,type:"button","aria-label":m?"Open catalog":v?"Collapse sidebar":"Expand sidebar","aria-expanded":v,"aria-controls":b,onClick:()=>x(O=>!O),className:"grid size-7 shrink-0 place-items-center border border-line text-faint hover:border-faint hover:text-ink",children:v?"‹":"›"}):null,n]}),c.jsx("div",{className:"flex w-full min-w-0 flex-wrap items-center gap-2 overflow-visible md:w-auto md:shrink-0 md:flex-nowrap",children:e})]}),t?c.jsx("div",{className:"flex min-h-9 shrink-0 flex-wrap items-center gap-2 overflow-x-auto border-b border-line bg-surface px-3 py-2 md:h-9 md:flex-nowrap md:py-0",children:t}):null,c.jsxs("div",{className:`grid min-h-0 min-w-0 flex-1 grid-cols-1 ${C?"md:grid-cols-[260px_minmax(0,1fr)]":"md:grid-cols-1"}`,children:[f&&C?c.jsxs(c.Fragment,{children:[m?c.jsx("button",{type:"button","aria-label":"Close catalog",className:"fixed inset-0 z-40 bg-black/35 backdrop-blur-[2px]",onClick:()=>x(!1)}):null,c.jsxs("aside",{id:b,ref:w,role:m?"dialog":void 0,"aria-modal":m?"true":void 0,"aria-label":m?"Data catalog":void 0,onClick:O=>{m&&O.target.closest("[data-catalog-metric], [data-catalog-dimension]")&&x(!1)},onChange:()=>m&&x(!1),className:"fixed inset-y-0 left-0 z-50 min-h-0 w-[min(88vw,320px)] overflow-y-auto bg-surface shadow-[var(--shadow)] md:static md:z-auto md:w-auto md:border-r md:border-line md:shadow-none",children:[m?c.jsxs("div",{"data-testid":"catalog-drawer-header",className:"sticky top-0 z-10 flex items-center justify-between border-b border-line bg-surface px-4 py-3",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-sm font-semibold text-ink",children:"Catalog"}),c.jsx("p",{className:"text-xs text-muted",children:"Choose a model and fields"})]}),c.jsx("button",{type:"button","aria-label":"Close catalog",onClick:()=>x(!1),className:"grid size-10 place-items-center rounded-full bg-surface-soft text-muted hover:bg-line hover:text-ink",children:c.jsx("span",{"aria-hidden":"true",className:"text-xl leading-none",children:"×"})})]}):null,i]})]}):null,c.jsxs("main",{className:"relative min-h-0 min-w-0 overflow-hidden",children:[c.jsx("div",{className:`h-full overflow-y-auto ${u?"pb-8":""}`,children:a}),u]})]})]})}function eS({dashboardTitle:n,modelLabel:e,onHome:t}){const i=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-sm font-semibold text-ink",children:n??"Sidemantic"}),n===void 0&&e?c.jsx("span",{className:"truncate text-2xs text-faint",children:e}):null]});return n!==void 0?c.jsx("span",{className:"flex min-w-0 items-baseline gap-2",children:i}):c.jsx("button",{type:"button",onClick:t,"aria-label":"Home",className:"flex min-w-0 items-baseline gap-2",children:i})}const tS=new Set(["second","minute","hour","day","week","month","quarter","year"]);function il(n){return n===void 0?[]:Array.isArray(n)?n:[n]}function ol(n,e){return n.models.flatMap(t=>t.dimensions).find(t=>e===t.ref||e.startsWith(`${t.ref}__`))}function nS(n,e){const t=n.split("__").at(-1);return t&&tS.has(t)?t:e}function rS(n){var a;const e=(a=n.defaults)==null?void 0:a.query;if(!e||typeof e!="object")return;const t=e,i=t.use_preaggregations??t.usePreaggregations;return typeof i=="boolean"?i:void 0}function sS(n,e){var u;const t=(u=n.defaults)==null?void 0:u.query,i=t&&typeof t=="object"?t:{},a=e.query.interaction_preaggregations??e.query.interactionPreaggregations??e.interaction_preaggregations??e.interactionPreaggregations??i.interaction_preaggregations??i.interactionPreaggregations;return typeof a=="boolean"?a:void 0}function Cs(n,e,t){var T,E,I,U,G,V,Q;if(!(e!=null&&e.tabs.length))return null;const i=e.tabs.find(z=>z.id===t)??e.tabs[0],a=i.charts[0];if(!a)return null;const u=il(a.query.dimensions),f=il(a.query.metrics),h=f.map(z=>{var ee;return(ee=n.graphMetrics.find(X=>X.ref===z))==null?void 0:ee.ownerModel}).find(z=>!!z),m=((T=f.find(z=>z.includes(".")))==null?void 0:T.split(".")[0])??h??((E=u.find(z=>z.includes(".")))==null?void 0:E.split(".")[0]),g=n.models.find(z=>z.name===m)??n.models[0];if(!g)return null;const v=[...n.models.flatMap(z=>z.metrics),...ji(n,g.name)],x=f.map(z=>v.find(ee=>ee.ref===z)).filter(z=>!!z),b=u.map(z=>ol(n,z)).filter((z,ee,X)=>!!z&&X.findIndex(ie=>(ie==null?void 0:ie.ref)===(z==null?void 0:z.ref))===ee),w=(I=a.encoding)==null?void 0:I.y,C=(Array.isArray(w)?w:w?[w]:[]).find(z=>x.some(ee=>ee.ref===z))??((U=x[0])==null?void 0:U.ref)??((G=g.metrics[0])==null?void 0:G.ref)??"",O=(V=a.encoding)==null?void 0:V.x,H=(O&&((Q=ol(n,O))==null?void 0:Q.type)==="time"?O:void 0)??u.find(z=>{var ee;return((ee=ol(n,z))==null?void 0:ee.type)==="time"}),L=g.defaultGrain??"month",R=H?ol(n,H):g.timeDimension;return{id:i.id,label:i.label??i.id,title:a.title??e.title,model:g,metrics:x.length?x:g.metrics,dimensions:b.length?b:g.dimensions,timeDimension:R,selectedMetric:C,grain:H?nS(H,L):L,filters:il(a.query.filters),segments:il(a.query.segments),usePreaggregations:sS(e,a)??a.query.use_preaggregations??a.query.usePreaggregations??rS(e)}}const Fd=["second","minute","hour","day","week","month","quarter","year"];function iS(n,e){if(n!=null&&n.length){const i=new Set(n.map(u=>u.toLowerCase())),a=Fd.filter(u=>i.has(u));if(a.length)return a}const t=["day","week","month","quarter","year"];return e&&!t.includes(e)?Fd.filter(i=>i===e||t.includes(i)):t}function Ni(n){return n.toISOString().slice(0,10)}function nf(n){return n.slice(0,10)}function Oi(n){const e=n.trim();return/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:/[zZ]|[+-]\d{2}:?\d{2}$/.test(e)?e:`${e.replace(" ","T")}Z`}function Fs(n){return new Date(`${nf(n)}T00:00:00Z`)}function Uo(n,e){const t=Fs(n);return t.setUTCDate(t.getUTCDate()+e),Ni(t)}function oS(n){return Math.round((Fs(n.to).getTime()-Fs(n.from).getTime())/864e5)+1}function aS(n){if(n.from.includes("T")||n.to.includes("T")){const a=Date.parse(Oi(n.from)),f=Date.parse(Oi(n.to))-a;return{from:new Date(a-f).toISOString().slice(0,19),to:new Date(a).toISOString().slice(0,19)}}const e=oS(n),t=Uo(n.from,-1);return{from:Uo(t,-(e-1)),to:t}}function Rm(n){if(n.includes("T")){const f=new Date(Oi(n)),h=f.getUTCFullYear()-1,m=f.getUTCMonth(),g=new Date(Date.UTC(h,m+1,0)).getUTCDate();return new Date(Date.UTC(h,m,Math.min(f.getUTCDate(),g),f.getUTCHours(),f.getUTCMinutes(),f.getUTCSeconds())).toISOString().slice(0,19)}const e=Fs(n),t=e.getUTCFullYear()-1,i=e.getUTCMonth(),a=e.getUTCDate(),u=new Date(Date.UTC(t,i+1,0)).getUTCDate();return Ni(new Date(Date.UTC(t,i,Math.min(a,u))))}function lS(n){return{from:Rm(n.from),to:Rm(n.to)}}function uS(n,e){const t=n.trim(),i=t.slice(0,10);if(e!=="second"&&e!=="minute"&&e!=="hour")return i||n;const a=t.slice(10).match(/(\d{2}):(\d{2})(?::(\d{2}))?/);if(!a)return i||n;const u=e==="second"&&a[3]?`${a[1]}:${a[2]}:${a[3]}`:`${a[1]}:${a[2]}`;return`${i} ${u}`}const cS=[{key:"7d",label:"Last 7 days",days:7},{key:"28d",label:"Last 28 days",days:28},{key:"90d",label:"Last 90 days",days:90},{key:"180d",label:"Last 180 days",days:180},{key:"365d",label:"Last 12 months",days:365}];function dS(n,e=new Date){const t=Ni(e);return{from:Uo(t,-(n-1)),to:t}}function fS(n,e){return e.from.includes("T")||e.to.includes("T")?[`${n} >= cast('${e.from}' as timestamp)`,`${n} < cast('${e.to}' as timestamp)`]:[`${n} >= cast('${e.from}' as date)`,`${n} < cast('${Uo(e.to,1)}' as date)`]}function Lm(n,e,t){if(t==="second"||t==="minute"||t==="hour"){const f=t==="second"?1e3:t==="minute"?6e4:36e5;return Math.round((Date.parse(Oi(e))-Date.parse(Oi(n)))/f)}const i=Fs(n),a=Fs(e),u=(a.getUTCFullYear()-i.getUTCFullYear())*12+(a.getUTCMonth()-i.getUTCMonth());switch(t){case"week":return Math.round((a.getTime()-i.getTime())/(7*864e5));case"month":return u;case"quarter":return Math.round(u/3);case"year":return a.getUTCFullYear()-i.getUTCFullYear();default:return Math.round((a.getTime()-i.getTime())/864e5)}}function ld(n,e){return new Date(Date.parse(Oi(n))+e).toISOString().slice(0,19)}function hS(n,e){const t=nf(n),i=Fs(t);switch(e){case"second":return ld(n,1e3);case"minute":return ld(n,6e4);case"hour":return ld(n,36e5);case"day":return t;case"week":return Uo(n,6);case"month":return Ni(new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth()+1,0)));case"quarter":{const a=Math.floor(i.getUTCMonth()/3)*3+3;return Ni(new Date(Date.UTC(i.getUTCFullYear(),a,0)))}case"year":return Ni(new Date(Date.UTC(i.getUTCFullYear(),12,0)));default:return n}}function rf(n){return n.mode==="contains"?!n.pattern:n.values.length===0}function sf(n){return Object.fromEntries(n.map(e=>[e.ref,e.type]))}function ou(n){return sf(n.models.flatMap(e=>e.dimensions))}function Um(n,e){if((e==="numeric"||e==="number")&&n.trim()!==""&&Number.isFinite(Number(n)))return n;if(e==="boolean"){const t=n.toLowerCase();if(t==="true"||t==="false")return t}return Tn(n)}function Nv(n){return n.replaceAll("\\","\\\\").replaceAll("%","\\%").replaceAll("_","\\_")}function pS(n,e,t){const i=e.mode==="exclude",a=e.values.includes(er),u=e.values.filter(h=>h!==er);let f=null;if(u.length===1)f=`${n} ${i?"!=":"="} ${Um(u[0],t)}`;else if(u.length>1){const h=u.map(m=>Um(m,t)).join(", ");f=`${n} ${i?"NOT IN":"IN"} (${h})`}if(!i){const h=[];return f&&h.push(f),a&&h.push(`${n} IS NULL`),h.length===0?null:h.length===1?h[0]:`(${h.join(" OR ")})`}if(a){const h=[];return f&&h.push(f),h.push(`${n} IS NOT NULL`),h.length===1?h[0]:`(${h.join(" AND ")})`}return f?`(${f} OR ${n} IS NULL)`:null}function jv(n,e={}){var i;const t=[];for(const[a,u]of Object.entries(n)){if(a===e.excludeDim||rf(u))continue;const f=(i=e.types)==null?void 0:i[a];if(u.mode==="contains"){const m=Tn(`%${Nv(u.pattern??"")}%`);t.push(`CAST(${a} AS VARCHAR) ILIKE ${m} ESCAPE '\\'`);continue}const h=pS(a,u,f);h&&t.push(h)}return t}function Os(n,e={}){const t=jv(n,{types:e.types,excludeDim:e.excludeDim});return e.timeRef&&e.range&&t.push(...fS(e.timeRef,e.range)),t}function $m(n,e,t,i){return{metrics:n,filters:e,...t!=null&&t.length?{segments:t}:{},...i!=null?{usePreaggregations:i}:{}}}const mS={second:2e3,minute:2e3,hour:9600,day:4e3,week:800,month:240,quarter:120,year:60};function Pm(n,e,t,i,a,u,f=!1){const h=`${e}__${t}`,m=t==="second"||t==="minute",g=m&&!f;return{metrics:n,dimensions:[h],filters:i,...a!=null&&a.length?{segments:a}:{},...u!=null?{usePreaggregations:u}:{},orderBy:[`${h} ${g?"DESC":"ASC"}`],...!m||g?{limit:mS[t]??2e3}:{}}}function zm(n,e,t,i=6,a,u){return{metrics:[n],dimensions:[e],filters:t,...a!=null&&a.length?{segments:a}:{},...u!=null?{usePreaggregations:u}:{},orderBy:[`${n} DESC`],limit:i}}function yS(n,e,t=50,i,a){return{dimensions:[n],filters:e,...i!=null&&i.length?{segments:i}:{},...a!=null?{usePreaggregations:a}:{},orderBy:[`${n} ASC`],limit:t}}function gS(n,e,t,i,a=500){return{metrics:n,dimensions:e,filters:t,orderBy:i,limit:a}}function vS(n,e,t=50,i,a){return{dimensions:n.dimensions,metrics:n.metrics,filters:e,...i!=null&&i.length?{segments:i}:{},...a!=null?{usePreaggregations:a}:{},ungrouped:!0,limit:t}}function xS(n,e){const t=n??[];return t.includes(e)?t.filter(i=>i!==e):[...t,e]}function al(n,e,t){const i={...n};return rf(t)?delete i[e]:i[e]=t,i}function bS(n,e){switch(e.type){case"hydrate":return e.state;case"setView":return{...n,view:e.view};case"setDashboardTab":return{...n,view:"explore",dashboardTab:e.tab,model:e.model,selectedMetric:e.metric,grain:e.grain,filters:{},dateRange:void 0,pivotDims:[],pivotMetrics:[]};case"setModel":return{...n,model:e.model,selectedMetric:e.metric,grain:e.grain,filters:{},pivotDims:[],pivotMetrics:[]};case"setMetric":return{...n,selectedMetric:e.metric};case"toggleFilter":{const t=n.filters[e.dim],i=e.mode??(t&&t.mode!=="contains"?t.mode:"include"),a=t&&t.mode===i?t.values:[],u=xS(a,e.value);return{...n,filters:al(n.filters,e.dim,{mode:i,values:u})}}case"setFilterMode":{const t=n.filters[e.dim],i={mode:e.mode,values:(t==null?void 0:t.values)??[],pattern:t==null?void 0:t.pattern};return{...n,filters:al(n.filters,e.dim,i)}}case"setFilterPattern":{const t=n.filters[e.dim],i={mode:"contains",values:(t==null?void 0:t.values)??[],pattern:e.pattern};return{...n,filters:al(n.filters,e.dim,i)}}case"removeFilterValue":{const t=n.filters[e.dim];if(!t)return n;const i=t.values.filter(a=>a!==e.value);return{...n,filters:al(n.filters,e.dim,{...t,values:i})}}case"removeFilterDim":{const t={...n.filters};return delete t[e.dim],{...n,filters:t}}case"clearFilters":return{...n,filters:{}};case"setGrain":return{...n,grain:e.grain};case"setTimezone":return{...n,timezone:e.timezone};case"setDateRange":return{...n,dateRange:e.range};case"setContextColumn":return{...n,contextColumn:e.column};case"setComparison":return{...n,comparison:e.comparison,comparisonRange:e.comparison==="custom"?e.range:void 0};case"setPivotDims":return{...n,pivotDims:e.dims};case"setPivotMetrics":return{...n,pivotMetrics:e.metrics};case"reset":return{...e.initial,view:n.view};default:return n}}function wS(n){return n.models.find(e=>e.timeDimension)??n.models[0]}function kv(n,e){var t,i;return((t=n==null?void 0:n.metrics[0])==null?void 0:t.ref)??(n?(i=ji(e,n.name)[0])==null?void 0:i.ref:void 0)??""}function Iv(n,e,t){const i=Cs(n,e,t),a=(i==null?void 0:i.model)??wS(n),u=(i==null?void 0:i.selectedMetric)??kv(a,n);return{view:i?"explore":"home",dashboardTab:i==null?void 0:i.id,model:(a==null?void 0:a.name)??"",selectedMetric:u,filters:{},grain:(i==null?void 0:i.grain)??(a==null?void 0:a.defaultGrain)??"month",timezone:"UTC",dateRange:void 0,contextColumn:"none",comparison:"previous",comparisonRange:void 0,pivotDims:[],pivotMetrics:[]}}function SS(n,e,t){const i=new URLSearchParams(t),a=i.get("metric"),u=i.get("grain"),f=a===n.selectedMetric&&e.metrics.some(m=>m.ref===a),h=u===n.grain;return{...n,view:"explore",dashboardTab:e.id,model:e.model.name,selectedMetric:f?n.selectedMetric:e.selectedMetric,grain:h?n.grain:e.grain}}const _S=["home","explore","pivot"],NS=new Set(Fd),jS=new Set(["none","pctTotal","delta","deltaPct"]),kS=new Set(["off","previous","year","custom"]),IS="none",MS="previous",DS="UTC";function CS(n){return n!=null&&/^[A-Za-z][A-Za-z0-9/_+-]{0,63}$/.test(n)}function ud(n){if(n)try{return JSON.parse(n)}catch{return}}function Zl(n){return Array.isArray(n)&&n.every(e=>typeof e=="string")}function ll(n){return n!=null&&/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2})?$/.test(n)&&!Number.isNaN(Date.parse(n))}const FS=new Set(["include","exclude","contains"]);function OS(n){if(Zl(n))return{mode:"include",values:n};if(typeof n!="object"||n===null||Array.isArray(n))return null;const e=n;if(!FS.has(e.mode))return null;const t=e.mode,i=Zl(e.values)?e.values:[],a=typeof e.pattern=="string"?e.pattern:void 0,u={mode:t,values:i,pattern:a};return rf(u)?null:u}function TS(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;const e={};for(const[t,i]of Object.entries(n)){const a=OS(i);a&&(e[t]=a)}return e}function AS(n){const e={};for(const[t,i]of Object.entries(n))e[t]=i.mode==="include"?i.values:i;return e}function BS(n){const e=new URLSearchParams;return e.set("view",n.view),n.dashboardTab&&e.set("tab",n.dashboardTab),n.model&&e.set("model",n.model),n.selectedMetric&&e.set("metric",n.selectedMetric),n.grain&&e.set("grain",n.grain),n.timezone&&n.timezone!==DS&&e.set("tz",n.timezone),n.dateRange&&(e.set("from",n.dateRange.from),e.set("to",n.dateRange.to)),n.contextColumn!==IS&&e.set("ctx",n.contextColumn),n.comparison!==MS&&e.set("cmp",n.comparison),n.comparison==="custom"&&n.comparisonRange&&(e.set("cfrom",n.comparisonRange.from),e.set("cto",n.comparisonRange.to)),Object.keys(n.filters).length&&e.set("filters",JSON.stringify(AS(n.filters))),n.pivotDims.length&&e.set("pdims",JSON.stringify(n.pivotDims)),n.pivotMetrics.length&&e.set("pmetrics",JSON.stringify(n.pivotMetrics)),e.toString()}function ES(n,e){const t=new URLSearchParams(n),i={...e},a=t.get("view");a&&_S.includes(a)&&(i.view=a);const u=t.get("tab");u&&(i.dashboardTab=u);const f=t.get("model");f&&(i.model=f);const h=t.get("metric");h&&(i.selectedMetric=h);const m=t.get("grain");m&&NS.has(m)&&(i.grain=m);const g=t.get("tz");CS(g)&&(i.timezone=g);const v=t.get("from"),x=t.get("to");ll(v)&&ll(x)&&Date.parse(v)<=Date.parse(x)&&(i.dateRange={from:v,to:x});const b=t.get("ctx");b&&jS.has(b)&&(i.contextColumn=b);const w=t.get("cmp");w&&kS.has(w)&&(i.comparison=w);const j=t.get("cfrom"),C=t.get("cto");i.comparison==="custom"&&ll(j)&&ll(C)&&Date.parse(j)<=Date.parse(C)&&(i.comparisonRange={from:j,to:C});const O=TS(ud(t.get("filters")));O&&(i.filters=O);const H=ud(t.get("pdims"));Zl(H)&&(i.pivotDims=H);const L=ud(t.get("pmetrics"));return Zl(L)&&(i.pivotMetrics=L),i}const Mv=D.createContext(null);function RS({catalog:n,backend:e,dashboard:t,children:i}){const a=D.useMemo(()=>Iv(n,t),[n,t]),[u,f]=D.useReducer(bS,void 0,()=>{const m=ES(window.location.search,a),g=Cs(n,t,m.dashboardTab);return g?SS(m,g,window.location.search):m});D.useEffect(()=>{const m=BS(u),g=`${window.location.pathname}${m?`?${m}`:""}`;window.history.replaceState(null,"",g)},[u]);const h=D.useMemo(()=>({state:u,dispatch:f,catalog:n,backend:e,initial:a,dashboard:t}),[u,n,e,a,t]);return c.jsx(Mv.Provider,{value:h,children:i})}function ls(){const n=D.useContext(Mv);if(!n)throw new Error("useExplorer must be used within ExplorerProvider");return n}const Is={active:0,listeners:new Set};function Dv(){for(const n of Is.listeners)n()}function LS(){Is.active+=1,Dv()}function US(){Is.active=Math.max(0,Is.active-1),Dv()}function Cv(){return D.useSyncExternalStore(n=>(Is.listeners.add(n),()=>Is.listeners.delete(n)),()=>Is.active>0,()=>!1)}const $S=80;function Zn(n,e){const[t,i]=D.useState({loading:!1}),a=D.useRef(0),u=e?JSON.stringify(e):null;return D.useEffect(()=>{if(!e){i({loading:!1});return}const f=++a.current;i(m=>({result:m.result,loading:!0}));const h=setTimeout(()=>{LS(),n.runQuery(e).then(m=>{f===a.current&&i({result:m,loading:!1})}).catch(m=>{f===a.current&&i({loading:!1,error:m instanceof Error?m.message:String(m)})}).finally(()=>US())},$S);return()=>clearTimeout(h)},[u,n]),t}const PS=[{mode:"include",label:"Include"},{mode:"exclude",label:"Exclude"},{mode:"contains",label:"Contains"}],zS=50,Vm=200;function Wm(n,e){const[t,i]=D.useState(n);return D.useEffect(()=>{const a=setTimeout(()=>i(n),e);return()=>clearTimeout(a)},[n,e]),t}function Fv({dim:n,model:e,onClose:t}){var W,_;const{state:i,dispatch:a,backend:u,catalog:f,dashboard:h}=ls(),m=D.useMemo(()=>Cs(f,h,i.dashboardTab),[f,h,i.dashboardTab]),g=i.filters[n.ref],[v,x]=D.useState((g==null?void 0:g.mode)??"include"),b=D.useMemo(()=>new Set((g==null?void 0:g.mode)!=="contains"?(g==null?void 0:g.values)??[]:[]),[g]),w=D.useRef(null),j=D.useRef(null),C=D.useId(),[O,H]=D.useState(""),L=Wm(O,Vm),R=(g==null?void 0:g.mode)==="contains"?g.pattern??"":"",[T,E]=D.useState(R),I=Wm(T,Vm);D.useEffect(()=>{var te;const F=document.activeElement;return(te=j.current)==null||te.focus(),()=>{var pe;return(pe=F==null?void 0:F.focus)==null?void 0:pe.call(F)}},[]),D.useEffect(()=>{function F(pe){pe.key==="Escape"&&(pe.stopPropagation(),t())}function te(pe){w.current&&!w.current.contains(pe.target)&&t()}return document.addEventListener("keydown",F,!0),document.addEventListener("mousedown",te,!0),()=>{document.removeEventListener("keydown",F,!0),document.removeEventListener("mousedown",te,!0)}},[t]),D.useEffect(()=>{v==="contains"&&I!==R&&a({type:"setFilterPattern",dim:n.ref,pattern:I})},[I,v,n.ref,a]);const U=((W=m==null?void 0:m.timeDimension)==null?void 0:W.ref)??((_=e.timeDimension)==null?void 0:_.ref),G=D.useMemo(()=>ou(f),[f]),V=D.useMemo(()=>{const F=[...(m==null?void 0:m.filters)??[],...Os(i.filters,{timeRef:U,range:i.dateRange,excludeDim:n.ref,types:G})];if(L.trim()){const te=Tn(`%${Nv(L.trim())}%`);F.push(`CAST(${n.ref} AS VARCHAR) ILIKE ${te} ESCAPE '\\'`)}return F},[m,i.filters,U,i.dateRange,n.ref,L,G]),Q=v!=="contains",{result:z,loading:ee,error:X}=Zn(u,Q?yS(n.ref,V,zS,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations):null),ie=Sr(n.ref),ae=D.useMemo(()=>z?z.rows.map(F=>{const te=F[ie];return te==null?er:String(te)}):[],[z,ie]),re=!!z&&z.rows.length>0&&!z.columns.includes(ie),se=Q&&(ee||re);function A(F){x(F),g&&a({type:"setFilterMode",dim:n.ref,mode:F}),F==="contains"&&E(R)}function Y(F){var fe;if(F.key!=="Tab")return;const te=(fe=w.current)==null?void 0:fe.querySelectorAll('button, input, [href], select, textarea, [tabindex]:not([tabindex="-1"])');if(!te||te.length===0)return;const pe=te[0],ne=te[te.length-1];F.shiftKey&&document.activeElement===pe?(F.preventDefault(),ne.focus()):!F.shiftKey&&document.activeElement===ne&&(F.preventDefault(),pe.focus())}return c.jsxs("div",{ref:w,role:"dialog","aria-modal":"true","aria-labelledby":C,onKeyDown:Y,className:"absolute left-0 z-50 mt-1 w-64 border border-line bg-surface p-2 text-2xs shadow-lg",children:[c.jsxs("div",{id:C,className:"mb-2 flex items-baseline justify-between gap-2",children:[c.jsx("span",{className:"truncate font-semibold text-ink",children:n.label}),c.jsx("button",{type:"button","aria-label":"Close filter editor",onClick:t,className:"grid size-4 place-items-center rounded-full bg-surface-soft text-faint hover:bg-line hover:text-ink",children:"×"})]}),c.jsx("div",{role:"group","aria-label":"Filter mode",className:"mb-2 grid grid-cols-3 gap-px border border-line bg-line",children:PS.map(({mode:F,label:te})=>c.jsx("button",{type:"button","aria-pressed":v===F,onClick:()=>A(F),className:`px-1.5 py-1 text-center ${v===F?"bg-accent-soft font-medium text-accent":"bg-surface text-muted hover:bg-surface-soft"}`,children:te},F))}),v==="contains"?c.jsx("input",{ref:j,type:"text","aria-label":`${n.label} contains`,placeholder:"Substring…",value:T,onChange:F=>E(F.target.value),className:"w-full border border-line bg-surface px-1.5 py-1 text-2xs text-ink placeholder:text-faint"}):c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:j,type:"text","aria-label":`Search ${n.label} values`,placeholder:"Search values…",value:O,onChange:F=>H(F.target.value),className:"w-full border border-line bg-surface px-1.5 py-1 text-2xs text-ink placeholder:text-faint"}),c.jsx("div",{className:"mt-2 max-h-56 overflow-y-auto",role:"group","aria-label":`${n.label} values`,children:X?c.jsx("p",{className:"px-1 py-2 text-danger",children:X}):se?c.jsx("div",{className:"space-y-1.5 p-1",children:[0,1,2,3,4].map(F=>c.jsx("div",{className:"skeleton h-4 w-full"},F))}):ae.length===0?c.jsx("p",{className:"px-1 py-2 text-faint",children:"No values"}):ae.map(F=>{const te=b.has(F);return c.jsxs("label",{className:"flex cursor-pointer items-center gap-2 px-1 py-1 hover:bg-surface-soft",children:[c.jsx("input",{type:"checkbox",checked:te,onChange:()=>a({type:"toggleFilter",dim:n.ref,value:F,mode:v}),className:"size-3 accent-[var(--accent)]"}),c.jsx("span",{className:"min-w-0 truncate text-ink",children:rs(F)})]},F)})})]}),c.jsxs("div",{className:"mt-2 flex items-center justify-between border-t border-line pt-2",children:[c.jsx("button",{type:"button",onClick:()=>a({type:"removeFilterDim",dim:n.ref}),className:"text-muted underline-offset-2 hover:text-ink hover:underline",children:"Clear"}),c.jsx("button",{type:"button",onClick:t,className:"border border-line px-2 py-1 text-muted hover:bg-surface-soft",children:"Done"})]})]})}function VS({model:n}){const e=n.dimensions.filter(m=>m.type!=="time"),[t,i]=D.useState(!1),[a,u]=D.useState(null),f=D.useRef(null);D.useEffect(()=>{if(!t)return;function m(v){v.key==="Escape"&&h()}function g(v){a||f.current&&!f.current.contains(v.target)&&h()}return document.addEventListener("keydown",m,!0),document.addEventListener("mousedown",g,!0),()=>{document.removeEventListener("keydown",m,!0),document.removeEventListener("mousedown",g,!0)}},[t,a]);function h(){i(!1),u(null)}return e.length===0?null:c.jsxs("span",{ref:f,className:"relative inline-flex",children:[c.jsx("button",{type:"button","aria-haspopup":"dialog","aria-expanded":t,onClick:()=>t?h():i(!0),className:"inline-flex h-7 shrink-0 items-center rounded-full border border-dashed border-line px-3 text-xs text-muted hover:border-faint hover:text-ink",children:"+ Filter"}),t&&!a?c.jsx("div",{role:"menu","aria-label":"Add a filter for a dimension",className:"absolute left-0 z-50 mt-1 max-h-64 w-48 overflow-y-auto rounded-xl border border-line bg-surface p-1.5 text-2xs shadow-[var(--shadow)]",children:e.map(m=>c.jsx("button",{type:"button",role:"menuitem",onClick:()=>u(m),className:"block w-full truncate px-1.5 py-1 text-left text-muted hover:bg-surface-soft hover:text-ink",children:m.label},m.ref))}):null,t&&a?c.jsx(Fv,{dim:a,model:n,onClose:h}):null]})}function cd(n,e){return n.includes(e)?n.filter(t=>t!==e):[...n,e]}function Hm({metric:n,selected:e,multiple:t,onSelect:i}){return c.jsxs("button",{type:"button","data-catalog-metric":n.ref,"data-selected":e||void 0,"aria-pressed":e,title:n.description,onClick:i,className:"flex w-full items-center justify-between gap-2 border-l-2 px-3 py-1 text-left text-xs hover:bg-surface-soft data-[selected=true]:border-l-accent data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent border-l-transparent text-muted",children:[c.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[t?c.jsx("span",{"aria-hidden":"true",className:"w-3 shrink-0 text-center text-accent",children:e?"✓":""}):null,c.jsx("span",{className:"truncate",children:n.label})]}),n.agg?c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:n.agg}):null]})}function WS({dimension:n,selected:e,onSelect:t}){return c.jsxs("button",{type:"button","data-catalog-dimension":n.ref,"data-selected":e||void 0,"aria-pressed":e,title:n.description,onClick:t,className:"flex w-full items-center justify-between gap-2 border-l-2 border-l-transparent px-3 py-1 text-left text-xs text-muted hover:bg-surface-soft data-[selected=true]:border-l-accent data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent",children:[c.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[c.jsx("span",{"aria-hidden":"true",className:"w-3 shrink-0 text-center",children:e?"✓":""}),c.jsx("span",{className:"truncate",children:n.label})]}),c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:n.type==="time"?"time":""})]})}function HS(){const{state:n,dispatch:e,catalog:t}=ls(),i=t.models.find(h=>h.name===n.model),a=ji(t,n.model),u=n.view==="pivot",f=n.pivotMetrics.length?n.pivotMetrics:n.selectedMetric?[n.selectedMetric]:[];return c.jsxs("nav",{"aria-label":"Semantic layer catalog",className:"flex flex-col gap-4 py-3 text-sm",children:[c.jsxs("section",{className:"px-3",children:[c.jsx("h2",{className:"mb-1 text-xs font-medium text-muted",children:"Model"}),c.jsx("select",{"aria-label":"Model",value:n.model,onChange:h=>{var v,x;const m=t.models.find(b=>b.name===h.target.value),g=((v=m==null?void 0:m.metrics[0])==null?void 0:v.ref)??((x=ji(t,h.target.value)[0])==null?void 0:x.ref)??"";e({type:"setModel",model:h.target.value,metric:g,grain:(m==null?void 0:m.defaultGrain)??"month"})},className:"w-full border border-line bg-surface px-2 py-1 text-xs text-ink",children:t.models.map(h=>c.jsx("option",{value:h.name,children:h.label},h.name))})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-1 px-3 text-xs font-medium text-muted",children:"Metrics"}),c.jsx("div",{children:((i==null?void 0:i.metrics)??[]).map(h=>c.jsx(Hm,{metric:h,selected:u?f.includes(h.ref):n.selectedMetric===h.ref,multiple:u,onSelect:()=>e(u?{type:"setPivotMetrics",metrics:cd(f,h.ref)}:{type:"setMetric",metric:h.ref})},h.ref))}),a.length?c.jsxs(c.Fragment,{children:[c.jsx("h3",{className:"mb-1 mt-3 px-3 text-xs font-medium text-muted",children:"Shared metrics"}),c.jsx("div",{children:a.map(h=>c.jsx(Hm,{metric:h,selected:u?f.includes(h.ref):n.selectedMetric===h.ref,multiple:u,onSelect:()=>e(u?{type:"setPivotMetrics",metrics:cd(f,h.ref)}:{type:"setMetric",metric:h.ref})},h.ref))})]}):null]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-1 px-3 text-xs font-medium text-muted",children:"Dimensions"}),u?c.jsx("div",{children:((i==null?void 0:i.dimensions)??[]).map(h=>c.jsx(WS,{dimension:h,selected:n.pivotDims.includes(h.ref),onSelect:()=>e({type:"setPivotDims",dims:cd(n.pivotDims,h.ref)})},h.ref))}):c.jsx("ul",{className:"px-3 text-xs text-muted",children:((i==null?void 0:i.dimensions)??[]).map(h=>c.jsxs("li",{className:"flex items-center justify-between gap-2 py-0.5",title:h.description,children:[c.jsx("span",{className:"truncate",children:h.label}),c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:h.type==="time"?"time":""})]},h.ref))})]})]})}class GS extends D.Component{constructor(){super(...arguments);Mn(this,"state",{})}static getDerivedStateFromError(t){return{error:t}}render(){return this.state.error?c.jsx("div",{className:"p-4",children:c.jsxs("div",{className:"border border-danger/40 bg-surface p-4",children:[c.jsx("p",{className:"text-sm font-semibold text-danger",children:"Something went wrong rendering this view."}),c.jsx("p",{className:"mt-1 break-words text-xs text-muted",children:this.state.error.message}),c.jsxs("div",{className:"mt-3 flex gap-2",children:[c.jsx("button",{type:"button",onClick:()=>this.setState({error:void 0}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Retry"}),c.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Reload"})]})]})}):this.props.children}}const YS=[{key:"off",label:"Off"},{key:"previous",label:"Previous period"},{key:"year",label:"Previous year"},{key:"custom",label:"Custom range"}];function Ov({range:n,disabled:e,onChange:t,comparison:i,comparisonRange:a,onComparisonChange:u}){const f=D.useRef(null),[h,m]=D.useState((n==null?void 0:n.from)??""),[g,v]=D.useState((n==null?void 0:n.to)??""),[x,b]=D.useState((a==null?void 0:a.from)??""),[w,j]=D.useState((a==null?void 0:a.to)??"");function C(){f.current&&(f.current.open=!1)}function O(T){t(T),C()}function H(T){T==="custom"?u("custom",x&&w?{from:x,to:w}:void 0):u(T)}const L=n?`${n.from} → ${n.to}`:"All time",R=!n;return c.jsxs("details",{ref:f,className:"relative text-xs",onToggle:T=>{e&&(T.currentTarget.open=!1)},children:[c.jsxs("summary",{"aria-disabled":e||void 0,tabIndex:e?-1:void 0,onClick:T=>e&&T.preventDefault(),onKeyDown:T=>{e&&(T.key==="Enter"||T.key===" ")&&T.preventDefault()},className:`flex h-7 cursor-pointer items-center gap-1.5 rounded-full border border-line bg-surface px-3 text-ink ${e?"cursor-not-allowed opacity-50":""}`,children:[c.jsx("span",{className:"text-faint",children:"Range"}),c.jsx("span",{className:"tnum",children:L}),c.jsx("span",{"aria-hidden":"true",className:"text-faint",children:"▾"})]}),c.jsxs("div",{className:"absolute right-0 z-50 mt-1 w-64 rounded-xl border border-line bg-surface p-1.5 shadow-[var(--shadow)]",children:[c.jsx("button",{type:"button",onClick:()=>O(void 0),className:"w-full rounded-lg px-2.5 py-1.5 text-left text-xs text-muted hover:bg-surface-soft hover:text-ink",children:"All time"}),c.jsx("div",{className:"grid grid-cols-2",children:cS.map(T=>c.jsx("button",{type:"button",onClick:()=>O(dS(T.days)),className:"rounded-lg px-2.5 py-1.5 text-left text-xs text-muted hover:bg-surface-soft hover:text-ink",children:T.label},T.key))}),c.jsxs("div",{className:"mt-2 px-1 pb-1",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("input",{type:"date","aria-label":"From date",value:h,onChange:T=>m(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"}),c.jsx("span",{className:"text-faint",children:"→"}),c.jsx("input",{type:"date","aria-label":"To date",value:g,onChange:T=>v(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"})]}),c.jsx("button",{type:"button",disabled:!h||!g,onClick:()=>O({from:h,to:g}),className:"mt-1.5 inline-flex h-7 w-full items-center justify-center rounded-full border border-accent bg-accent-soft text-xs font-medium text-accent hover:bg-accent hover:text-surface disabled:pointer-events-none disabled:opacity-50",children:"Apply custom range"})]}),c.jsxs("div",{className:"mt-1 px-1 pb-1","data-testid":"comparison-picker",children:[c.jsx("p",{className:"mb-1 px-1.5 text-2xs text-faint",children:"Compare to"}),c.jsx("div",{className:`grid grid-cols-2 ${R?"opacity-50":""}`,children:YS.map(T=>c.jsx("button",{type:"button",disabled:R,"data-comparison":T.key,"data-active":i===T.key||void 0,onClick:()=>H(T.key),className:"rounded-lg px-2.5 py-1.5 text-left text-xs text-muted hover:bg-surface-soft hover:text-ink data-[active=true]:bg-accent-soft data-[active=true]:text-accent",children:T.label},T.key))}),i==="custom"&&!R?c.jsxs("div",{className:"mt-1.5",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("input",{type:"date","aria-label":"Comparison from date",value:x,onChange:T=>b(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"}),c.jsx("span",{className:"text-faint",children:"→"}),c.jsx("input",{type:"date","aria-label":"Comparison to date",value:w,onChange:T=>j(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"})]}),c.jsx("button",{type:"button",disabled:!x||!w,onClick:()=>u("custom",{from:x,to:w}),className:"mt-1.5 inline-flex h-7 w-full items-center justify-center rounded-full border border-accent bg-accent-soft text-xs font-medium text-accent hover:bg-accent hover:text-surface disabled:pointer-events-none disabled:opacity-50",children:"Apply comparison"})]}):null]})]})]})}function Od(n){const[e,t]=D.useState(!1);if(!("dim"in n))return c.jsxs("span",{"data-dimension":n.dimension,"data-value":n.value,className:"inline-flex max-w-full items-center gap-1 rounded-full bg-surface-soft px-2 py-0.5 text-2xs leading-4 text-muted",children:[c.jsxs("span",{className:"truncate",children:[c.jsxs("span",{className:"text-faint",children:[n.dimensionLabel??n.dimension,":"]})," ",n.value]}),n.onRemove?c.jsx("button",{type:"button","aria-label":`Remove filter ${n.value}`,onClick:n.onRemove,className:"-mr-0.5 px-0.5 text-faint hover:text-ink",children:"×"}):null]});const{dim:i,model:a,filter:u,onRemove:f}=n;return c.jsxs("span",{className:"relative inline-flex max-w-full items-center","data-dimension":i.ref,"data-mode":u.mode,children:[c.jsxs("span",{className:"inline-flex max-w-full items-center gap-1 rounded-full bg-surface-soft px-2 py-0.5 text-2xs leading-4 text-muted",children:[c.jsxs("button",{type:"button","aria-label":`Edit filter ${i.label}`,"aria-haspopup":"dialog","aria-expanded":e,onClick:()=>t(h=>!h),className:"min-w-0 truncate text-left hover:text-ink",children:[c.jsx("span",{className:"text-faint",children:i.label})," ",yb(u)]}),c.jsx("button",{type:"button","aria-label":`Remove filter ${i.label}`,onClick:f,className:"grid size-3.5 shrink-0 place-items-center rounded-full bg-surface-soft text-faint hover:bg-line hover:text-ink",children:"×"})]}),e?c.jsx(Fv,{dim:i,model:a,onClose:()=>t(!1)}):null]})}function Td({grain:n,options:e,disabled:t,onChange:i}){return c.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-faint",children:[c.jsx("span",{className:"hidden sm:inline",children:"Grain"}),c.jsx("select",{"aria-label":"Time grain",value:n,disabled:t,onChange:a=>i(a.target.value),className:"h-7 rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50",children:e.map(a=>c.jsx("option",{value:a,children:Le(a)},a))})]})}const QS=["UTC","America/Los_Angeles","America/Denver","America/Chicago","America/New_York","America/Sao_Paulo","Europe/London","Europe/Berlin","Europe/Paris","Europe/Moscow","Asia/Dubai","Asia/Kolkata","Asia/Singapore","Asia/Shanghai","Asia/Tokyo","Australia/Sydney"];let ul=null;function Gm(){if(ul)return ul;const n=typeof Intl.supportedValuesOf=="function"?Intl.supportedValuesOf("timeZone"):[];return ul=[...new Set(["UTC",...n])].sort(),ul}function KS(n){if(!n)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:n}),!0}catch{return!1}}function JS(n,e=new Date){var t;try{const u=(((t=new Intl.DateTimeFormat("en-US",{timeZone:n,timeZoneName:"shortOffset"}).formatToParts(e).find(g=>g.type==="timeZoneName"))==null?void 0:t.value)??"").match(/([+-])(\d{1,2})(?::(\d{2}))?/);if(!u)return n==="UTC"?"+00:00":"";const f=u[1],h=u[2].padStart(2,"0"),m=u[3]??"00";return`${f}${h}:${m}`}catch{return""}}const Ym="__search__";function qS({timezone:n,disabled:e,onChange:t}){const i=D.useId(),[a,u]=D.useState(!1),[f,h]=D.useState(""),m=D.useMemo(()=>{const b=new Set(QS);return n&&b.add(n),[...b]},[n]),g=D.useMemo(()=>a?Gm():[],[a]);function v(b){const w=b.trim();KS(w)&&(t(w),u(!1),h(""))}if(a)return c.jsxs("label",{className:"flex items-center gap-1.5 text-2xs text-faint",children:[c.jsx("span",{className:"hidden sm:inline",children:"Zone"}),c.jsx("input",{type:"text",list:i,autoFocus:!0,"aria-label":"Search timezone",placeholder:"Region/City…",value:f,disabled:e,onChange:b=>{h(b.target.value),Gm().includes(b.target.value)&&v(b.target.value)},onKeyDown:b=>{b.key==="Enter"?v(f):b.key==="Escape"&&(u(!1),h(""))},onBlur:()=>{u(!1),h("")},className:"h-7 w-36 rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50"}),c.jsx("datalist",{id:i,children:g.map(b=>c.jsx("option",{value:b},b))})]});const x=JS(n);return c.jsxs("label",{className:"flex items-center gap-1.5 text-2xs text-faint",children:[c.jsx("span",{className:"hidden sm:inline",children:"Zone"}),c.jsxs("select",{"aria-label":"Timezone",value:n,disabled:e,onChange:b=>{b.target.value===Ym?u(!0):t(b.target.value)},className:"h-7 max-w-[11rem] rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50",children:[m.map(b=>c.jsxs("option",{value:b,children:[b,b==="UTC"?"":x&&b===n?` (${x})`:""]},b)),c.jsx("option",{value:Ym,children:"Search…"})]})]})}function ZS(n,e,t){if(t==="count")return n.length;const i=n.map(u=>typeof u[e]=="number"?u[e]:Number(u[e])).filter(Number.isFinite);if(i.length===0)return Number.NaN;if(t==="min")return Math.min(...i);if(t==="max")return Math.max(...i);const a=i.reduce((u,f)=>u+f,0);return t==="avg"?a/i.length:a}const XS={sum:"Σ",avg:"avg",min:"min",max:"max",count:"n"};function Ho({columns:n,rows:e,loading:t,sortKey:i,sortDir:a,onSort:u,renderCell:f,pageSize:h=50,searchable:m,totals:g,stickyHeader:v=!0}){const[x,b]=D.useState(0),[w,j]=D.useState(""),C=D.useMemo(()=>{const I=w.trim().toLowerCase();return!m||!I?e:e.filter(U=>n.some(G=>String(U[G.key]??"").toLowerCase().includes(I)))},[e,n,w,m]),{paginate:O,pageCount:H,safePage:L,start:R,visibleRows:T}=fb(C,x,h);D.useEffect(()=>{b(0)},[e,h,i,a,w]);const E=g&&n.some(I=>g[I.key]);return c.jsxs("div",{children:[m?c.jsxs("div",{className:"mb-2 flex items-center justify-end gap-2",children:[w?c.jsxs("span",{className:"whitespace-nowrap text-2xs text-faint tnum",children:[C.length.toLocaleString()," of ",e.length.toLocaleString()]}):null,c.jsx("input",{type:"search","aria-label":"Search rows",placeholder:"Search…",value:w,onChange:I=>j(I.target.value),className:"h-7 w-full max-w-64 rounded-full border border-line bg-surface px-2.5 text-xs text-ink placeholder:text-faint"})]}):null,c.jsx("div",{className:"overflow-auto border border-line bg-surface",children:c.jsxs("table",{className:"w-max min-w-full border-collapse text-xs","data-testid":"pivot-table",children:[c.jsx("thead",{children:c.jsx("tr",{className:"bg-surface-soft",children:n.map(I=>{const U=i===I.key;return c.jsx("th",{className:`max-w-80 whitespace-nowrap border-b border-line bg-surface-soft px-3 py-1.5 font-semibold text-faint ${I.numeric?"min-w-32 text-right":"min-w-40 text-left"} ${v?"sticky top-0 z-10":""}`,children:I.sortable&&u?c.jsxs("button",{type:"button",onClick:()=>u(I.key),"aria-label":`Sort by ${I.label}${U?`, currently ${a==="asc"?"ascending":"descending"}`:""}`,className:`table-sort inline-flex max-w-full items-center gap-1 whitespace-nowrap hover:text-ink ${U?"text-ink":""}`,children:[c.jsx("span",{className:"truncate",children:I.label}),c.jsx("span",{"aria-hidden":"true",className:"text-[9px]",children:U?a==="asc"?"▲":"▼":"↕"})]}):c.jsx("span",{className:"block truncate",title:I.label,children:I.label})},I.key)})})}),c.jsx("tbody",{children:t&&C.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:n.length,className:"px-3 py-6 text-center text-faint",children:"Loading…"})}):C.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:n.length,className:"px-3 py-6 text-center text-faint",children:w?"No matching rows":"No rows"})}):T.map((I,U)=>c.jsx("tr",{className:"hover:bg-surface-soft",children:n.map(G=>{const V=f(G,I[G.key]);return c.jsx("td",{className:`max-w-80 whitespace-nowrap border-b border-line px-3 py-1.5 text-muted ${G.numeric?"min-w-32 text-right font-mono tnum text-ink":"min-w-40"}`,children:c.jsx("span",{className:"block max-w-80 truncate",title:V,children:V})},G.key)})},R+U))}),E&&C.length>0?c.jsx("tfoot",{children:c.jsx("tr",{className:"bg-surface-soft","data-testid":"table-totals",children:n.map(I=>{const U=g==null?void 0:g[I.key];if(!U)return c.jsx("td",{className:"border-t border-line px-3 py-1.5"},I.key);const G=ZS(C,I.key,U),V=U==="count"?G.toLocaleString():Number.isFinite(G)?f(I,G):"—";return c.jsxs("td",{"data-total":U,className:`whitespace-nowrap border-t border-line px-3 py-1.5 font-mono tnum font-medium text-ink ${I.numeric?"text-right":"text-left"}`,children:[c.jsx("span",{"aria-hidden":"true",className:"mr-1 text-2xs text-faint",children:XS[U]}),V]},I.key)})})}):null]})}),O?c.jsxs("div",{"data-testid":"pivot-table-pager",className:"mt-1.5 flex items-center justify-between gap-3 text-2xs text-faint",children:[c.jsxs("span",{className:"tnum",children:[R+1,"–",Math.min(R+h,C.length)," of ",C.length.toLocaleString(),t?" · Updating…":""]}),c.jsxs("div",{className:"flex gap-1",children:[c.jsx("button",{type:"button",disabled:L===0,onClick:()=>b(I=>Math.max(0,I-1)),className:"table-pager-button px-2 py-1 text-muted hover:text-ink disabled:cursor-not-allowed disabled:opacity-40",children:"Prev"}),c.jsx("button",{type:"button",disabled:L>=H-1,onClick:()=>b(I=>Math.min(H-1,I+1)),className:"table-pager-button px-2 py-1 text-muted hover:text-ink disabled:cursor-not-allowed disabled:opacity-40",children:"Next"})]})]}):null]})}function e_(n,e){const t=e.filter(i=>n.some(a=>a.ref===i));return t.length?t:n.slice(0,6).map(i=>i.ref)}function t_(){var L,R;const[n,e]=D.useState(!1),{state:t,catalog:i,backend:a,dashboard:u}=ls(),f=i.models.find(T=>T.name===t.model),h=D.useMemo(()=>Cs(i,u,t.dashboardTab),[i,u,t.dashboardTab]),m=(h==null?void 0:h.dimensions)??(f==null?void 0:f.dimensions)??[],g=e_(m,t.pivotDims),v=((L=h==null?void 0:h.timeDimension)==null?void 0:L.ref)??((R=f==null?void 0:f.timeDimension)==null?void 0:R.ref),x=D.useMemo(()=>ou(i),[i]),b=D.useMemo(()=>[...(h==null?void 0:h.filters)??[],...Os(t.filters,{timeRef:v,range:t.dateRange,types:x})],[h,t.filters,v,t.dateRange,x]),w=n&&f?vS({dimensions:g,metrics:[]},b,50,h==null?void 0:h.segments,h==null?void 0:h.usePreaggregations):null,{result:j,loading:C,error:O}=Zn(a,w),H=[...g.map(T=>{var E;return{key:Sr(T),label:((E=m.find(I=>I.ref===T))==null?void 0:E.label)??Le(T)}})];return c.jsxs("section",{"data-testid":"row-preview-drawer","data-open":n||void 0,className:"absolute inset-x-0 bottom-0 z-30 border-t border-line bg-surface shadow-[0_-8px_24px_rgba(0,0,0,0.16)]",children:[c.jsxs("button",{type:"button","aria-expanded":n,onClick:()=>e(T=>!T),className:"flex h-8 w-full items-center justify-between px-3 text-left text-xs font-medium text-muted hover:bg-surface-soft hover:text-ink",children:[c.jsx("span",{children:"Rows preview"}),c.jsx("span",{"aria-hidden":"true",children:n?"▼":"▲"})]}),n?c.jsx("div",{className:"max-h-[45vh] overflow-auto border-t border-line",children:O?c.jsx("p",{role:"alert",className:"p-3 text-xs text-danger",children:O}):H.length===0?c.jsx("p",{className:"p-3 text-xs text-faint",children:"No preview fields are available."}):c.jsx(Ho,{columns:H,rows:(j==null?void 0:j.rows)??[],loading:C,pageSize:10,renderCell:(T,E)=>E==null||E===""?"—":String(E)})}):null]})}function of({tone:n,title:e,message:t}){const i=n==="danger";return c.jsx("div",{className:`grid min-h-[200px] place-items-center border bg-surface p-6 text-center ${i?"border-danger/40":"border-line"}`,"data-state":n,role:i?"alert":"status","aria-live":i?"assertive":"polite",children:c.jsxs("div",{className:"max-w-md",children:[n==="loading"?c.jsx("span",{"aria-hidden":"true",className:"motion-safe:animate-pulse inline-block size-2 rounded-full bg-accent"}):null,e?c.jsx("h3",{className:`text-sm font-semibold ${i?"text-danger":"text-ink"}`,children:e}):null,c.jsx("p",{className:`mt-1 text-xs ${i?"text-danger":"text-muted"}`,children:t})]})})}function af({title:n="Loading",message:e="Loading metrics…"}){return c.jsx(of,{tone:"loading",title:n,message:e})}function Xn({title:n="No results",message:e}){return c.jsx(of,{tone:"muted",title:n,message:e})}function Bi({title:n="Query failed",message:e}){return c.jsx(of,{tone:"danger",title:n,message:e})}function dd({status:n}){const e=n==="ok"?"bg-success":n==="loading"?"bg-faint animate-pulse":"bg-line";return c.jsx("span",{"aria-hidden":"true",className:`inline-block size-2 rounded-full ${e}`})}const Tv="sidemantic-theme";function lf(){var e;const n=localStorage.getItem(Tv);return n==="light"||n==="dark"?n:(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}function Av(n){document.documentElement.dataset.theme=n}function n_(){Av(lf())}function r_(){const n=lf()==="dark"?"light":"dark";return localStorage.setItem(Tv,n),Av(n),n}function $o(){const[n,e]=D.useState(lf());return c.jsx("button",{type:"button","aria-label":n==="dark"?"Switch to light theme":"Switch to dark theme",title:n==="dark"?"Light theme":"Dark theme",onClick:()=>e(r_()),className:"grid size-7 place-items-center border border-line bg-surface text-faint hover:border-faint hover:text-ink",children:n==="dark"?c.jsxs("svg",{viewBox:"0 0 24 24",className:"size-3.5",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[c.jsx("circle",{cx:"12",cy:"12",r:"4"}),c.jsx("path",{d:"M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"})]}):c.jsx("svg",{viewBox:"0 0 24 24",className:"size-3.5",fill:"none",stroke:"currentColor",strokeWidth:"2",children:c.jsx("path",{d:"M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"})})})}const _o=[{key:"explore",label:"Explore"},{key:"pivot",label:"Pivot"}];function Bv({view:n,onChange:e}){const t=D.useRef(null);function i(a){const u=Math.max(0,_o.findIndex(h=>h.key===n)),f=_o[(u+a+_o.length)%_o.length];e(f.key),window.requestAnimationFrame(()=>{var h,m;return(m=(h=t.current)==null?void 0:h.querySelector(`[data-view="${f.key}"]`))==null?void 0:m.focus()})}return c.jsx("div",{ref:t,role:"tablist","aria-label":"View",className:"inline-flex items-center gap-0.5 rounded-full border border-line bg-surface p-px",children:_o.map(a=>c.jsx("button",{role:"tab",type:"button","aria-selected":n===a.key,tabIndex:n===a.key?0:-1,"data-view":a.key,"data-selected":n===a.key||void 0,onClick:()=>e(a.key),onKeyDown:u=>{u.key==="ArrowLeft"?(u.preventDefault(),i(-1)):u.key==="ArrowRight"&&(u.preventDefault(),i(1))},className:"inline-flex h-6 items-center rounded-full px-2.5 text-xs font-medium text-muted hover:bg-surface-soft hover:text-ink data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent",children:a.label},a.key))})}const Ev="dashboard_filters",Rv="dashboard_ranges",Lv="dashboard_filter_sources",Uv="dashboard_range_sources",$v="dashboard_chart_filters",Pv="dashboard_chart_ranges";function s_(n,e){if(n==="/explore")return!0;const t=new URLSearchParams(e).get("view");return t==="explore"||t==="pivot"}function uf(n,e){var i,a;if(!e||!(n.query.dimensions??[]).includes(e))return!1;const t=(i=n.interactions)==null?void 0:i.select;return t===!0?!0:t?!((a=t.fields)!=null&&a.length)||t.fields.includes(e):!1}function i_(n){return(n.query.dimensions??[]).find(e=>uf(n,e))}function o_(n,e){var i,a;if(!e||!(n.query.dimensions??[]).includes(e))return!1;const t=(i=n.interactions)==null?void 0:i.brush;return t===!0?!0:!t||t.channel&&t.channel!=="x"?!1:!((a=t.fields)!=null&&a.length)||t.fields.includes(e)}function Xl(n){return n==null?er:String(n)}function a_(n){let e=n.trim().replaceAll(/[^A-Za-z0-9_]/g,"_").replaceAll(/^_+|_+$/g,"")||"field";return/^\d/.test(e)&&(e=`field_${e}`),e}function xr(n,e){const t=Sr(n),i=a_(n);return i!==t&&e.includes(i)?i:e.includes(t)?t:e.find(a=>a.endsWith(t))??t}function l_(n){var t;const e=(t=n.encoding)==null?void 0:t.y;return Array.isArray(e)&&e.length?e:typeof e=="string"?[e]:n.query.metrics.slice(0,1)}function u_(n,e,t,i,a){return Object.fromEntries([[e,t],...i.map((u,f)=>[u,a[f]])].filter(u=>typeof u[1]=="string"&&uf(n,u[0])))}function c_(n,e,t){return[e,...t].some(i=>uf(n,i))}const d_=new Set(["second","minute","hour","day","week","month","quarter","year"]);function Ms(n){const e=n.lastIndexOf("__");if(e<0)return null;const t=n.slice(e+2);return d_.has(t)?{baseDimension:n.slice(0,e),grain:t}:null}function zv(n,e){var u,f;if(n.type&&n.type!=="auto")return n.type;const t=((u=n.encoding)==null?void 0:u.x)??((f=n.query.dimensions)==null?void 0:f[0])??"",i=Ms(t);return(e[t]??(i?e[i.baseDimension]:void 0))==="time"?"line":"bar"}function Vv(n,e){const t=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/.test(n)?`${n}Z`:n,i=new Date(t);return Number.isFinite(i.getTime())?(e==="second"?i.setUTCSeconds(i.getUTCSeconds()+1):e==="minute"?i.setUTCMinutes(i.getUTCMinutes()+1):e==="hour"?i.setUTCHours(i.getUTCHours()+1):e==="day"?i.setUTCDate(i.getUTCDate()+1):e==="week"?i.setUTCDate(i.getUTCDate()+7):e==="month"?i.setUTCMonth(i.getUTCMonth()+1):e==="quarter"?i.setUTCMonth(i.getUTCMonth()+3):e==="year"&&i.setUTCFullYear(i.getUTCFullYear()+1),/^\d{4}-\d{2}-\d{2}$/.test(n)?i.toISOString().slice(0,10):i.toISOString()):null}function Wv(n,e){const t=Ms(n);if(t){const i=Vv(e.to,t.grain);return i?`${t.baseDimension} >= ${Tn(e.from)} AND ${t.baseDimension} < ${Tn(i)}`:`${t.baseDimension} >= ${Tn(e.from)} AND ${t.baseDimension} <= ${Tn(e.to)}`}return`${n} >= ${Tn(e.from)} AND ${n} <= ${Tn(e.to)}`}function f_(n,e,t){const i=Ms(n);return i?e===er?[`${i.baseDimension} IS NULL`]:[Wv(n,{from:e,to:e})]:jv({[n]:{mode:"include",values:[e]}},{types:t})}function eu(n,e){const t=n.tabs.find(i=>i.charts.includes(e));return`${(t==null?void 0:t.id)??"dashboard"}:${e.id}`}function cf(n,e,t){var f,h,m,g,v;const i=((h=(f=n.defaults)==null?void 0:f.interactions)==null?void 0:h.scope)??"dashboard";if(i==="dashboard")return t;if(i==="chart"){const x=eu(n,e);return{filters:{...Object.fromEntries(Object.entries(t.filters).filter(([b])=>t.filterSources[b]===x)),...((m=t.chartFilters)==null?void 0:m[x])??{}},ranges:{...Object.fromEntries(Object.entries(t.ranges).filter(([b])=>t.rangeSources[b]===x)),...((g=t.chartRanges)==null?void 0:g[x])??{}}}}const a=((v=n.tabs.find(x=>x.charts.includes(e)))==null?void 0:v.charts)??[e],u=new Set(a.flatMap(x=>x.query.dimensions??[]));return{filters:Object.fromEntries(Object.entries(t.filters).filter(([x])=>u.has(x))),ranges:Object.fromEntries(Object.entries(t.ranges).filter(([x])=>u.has(x)))}}function h_(n,e,t,i,a={},u={filterSources:{},rangeSources:{}}){var b,w,j,C,O,H;const f=cf(n,e,{filters:t,ranges:a,...u}),h=((b=e.encoding)==null?void 0:b.x)??((w=e.query.dimensions)==null?void 0:w[0])??"",m=e.query.order_by??e.query.orderBy,g=h&&["line","area"].includes(zv(e,i))?[`${h} ASC`]:void 0,v={metrics:e.query.metrics,dimensions:e.query.dimensions,filters:[...e.query.filters??[],...Object.entries(f.filters).flatMap(([L,R])=>f_(L,R,i)),...Object.entries(f.ranges).map(([L,R])=>Wv(L,R))],segments:e.query.segments,orderBy:m??g,limit:e.query.limit??500},x=e.query.use_preaggregations??e.query.usePreaggregations??((C=(j=n.defaults)==null?void 0:j.query)==null?void 0:C.use_preaggregations)??((H=(O=n.defaults)==null?void 0:O.query)==null?void 0:H.usePreaggregations);return x!==void 0&&(v.usePreaggregations=x),v}function Qm(n){const e=/^(\d{4}-\d{2}-\d{2})/.exec(n);return(e==null?void 0:e[1])??null}function Km(n,e){const t=Qm(e.from);if(!t)return null;const i=Ms(n);if(!i){const f=Qm(e.to);return f?{from:t,to:f}:null}const a=Vv(e.to,i.grain);if(!a)return null;const u=new Date(a);return u.setUTCMilliseconds(u.getUTCMilliseconds()-1),{from:t,to:u.toISOString().slice(0,10)}}function p_(n,e,t,i={},a){var T,E,I;const u=(T=e.encoding)==null?void 0:T.y,f=(Array.isArray(u)?u[0]:u)??e.query.metrics[0]??"",h=e.query.dimensions??[],m=a==null?void 0:a.graphMetrics.find(U=>U.ref===f),g=f.includes(".")?f.split(".")[0]:((E=h[0])==null?void 0:E.split(".")[0])??(m==null?void 0:m.ownerModel)??(m==null?void 0:m.model)??"",v=cf(n,e,t),x=Object.entries(v.filters).flatMap(([U,G])=>{const V=Ms(U);return V?[{dimension:U,value:G,baseDimension:V.baseDimension}]:[]}),b=Object.fromEntries(Object.entries(v.filters).flatMap(([U,G])=>{const V=Ms(U);return V?G===er?[[V.baseDimension,[G]]]:[]:[[U,[G]]]})),w=new URLSearchParams({view:"explore",model:g,metric:f});Object.keys(b).length&&w.set("filters",JSON.stringify(b));const j=((I=e.encoding)==null?void 0:I.x)??h[0],C=x.find(({baseDimension:U,value:G})=>G!==er&&(!g||U.startsWith(`${g}.`))),O=Object.keys(v.ranges),H=[j,...O].find((U,G,V)=>{if(!U||V.indexOf(U)!==G||!v.ranges[U])return!1;const Q=Ms(U);return((i[U]??(Q?i[Q.baseDimension]:void 0))==="time"||!!Q)&&(!g||U.startsWith(`${g}.`))}),L=H?v.ranges[H]:void 0,R=C?Km(C.dimension,{from:C.value,to:C.value}):H&&L?Km(H,L):null;return R&&(w.set("from",R.from),w.set("to",R.to)),`/explore?${w}`}function m_(n,e,t,i){const a=new Map;for(const u of n){const f=Number(u[t]);if(!Number.isFinite(f))continue;const h=i.map(b=>Xl(u[b])),m=JSON.stringify(h),g=h.length?h.map(rs).join(" · "):"Current",v=a.get(m)??{label:g,filterValues:h,data:[]},x=Xl(u[e]);v.data.push({label:rs(x),filterValue:x,value:f}),a.set(m,v)}return[...a.values()]}function y_(n,e,t,i){const a=[],u=new Set,f=new Map;for(const h of n){if(h[e]==null)continue;const m=String(h[e]),g=Number(h[t]);if(!Number.isFinite(g))continue;u.has(m)||(u.add(m),a.push(m));const v=i.map(j=>Xl(h[j])),x=JSON.stringify(v),b=v.length?v.map(rs).join(" · "):"Current",w=f.get(x)??{label:b,values:new Map};w.values.set(m,g),f.set(x,w)}return[...f.values()].map(h=>({label:h.label,points:a.map(m=>({x:m,y:h.values.get(m)??Number.NaN}))}))}function df(n,e){if(typeof n!="object"||n===null||Array.isArray(n))return{};const t={};for(const[i,a]of Object.entries(n))e.has(i)&&typeof a=="string"&&(t[i]=a);return t}function ff(n,e){if(typeof n!="object"||n===null||Array.isArray(n))return{};const t={};for(const[i,a]of Object.entries(n)){if(!e.has(i)||typeof a!="object"||a===null||Array.isArray(a))continue;const u=a;typeof u.from=="string"&&typeof u.to=="string"&&(t[i]={from:u.from,to:u.to})}return t}function tu(n,e){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).filter(t=>e.has(t[0])&&typeof t[1]=="string"))}function Hv(n,e){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).flatMap(([t,i])=>{const a=e.get(t);if(!a)return[];const u=df(i,a);return Object.keys(u).length?[[t,u]]:[]}))}function Gv(n,e){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).flatMap(([t,i])=>{const a=e.get(t);if(!a)return[];const u=ff(i,a);return Object.keys(u).length?[[t,u]]:[]}))}function Yv(n){return new Set(n.tabs.flatMap(e=>e.charts.flatMap(t=>t.query.dimensions??[])))}function Qv(n){return new Map(n.tabs.flatMap(e=>e.charts.map(t=>[eu(n,t),new Set(t.query.dimensions??[])])))}function g_(n,e){var j;const t=new URLSearchParams(n),i=((j=e.tabs[0])==null?void 0:j.id)??"",a=t.get("tab"),u=e.tabs.some(C=>C.id===a)?a??i:i;let f,h,m,g,v,x;try{f=JSON.parse(t.get(Ev)??"{}")}catch{f={}}try{h=JSON.parse(t.get(Rv)??"{}")}catch{h={}}try{m=JSON.parse(t.get(Lv)??"{}")}catch{m={}}try{g=JSON.parse(t.get(Uv)??"{}")}catch{g={}}try{v=JSON.parse(t.get($v)??"{}")}catch{v={}}try{x=JSON.parse(t.get(Pv)??"{}")}catch{x={}}const b=Yv(e),w=Qv(e);return{tab:u,filters:df(f,b),ranges:ff(h,b),filterSources:tu(m,b),rangeSources:tu(g,b),chartFilters:Hv(v,w),chartRanges:Gv(x,w)}}function v_(n,e){var u;const t=new URLSearchParams;n.tab&&n.tab!==((u=e.tabs[0])==null?void 0:u.id)&&t.set("tab",n.tab),Object.keys(n.filters).length&&t.set(Ev,JSON.stringify(n.filters)),Object.keys(n.ranges).length&&t.set(Rv,JSON.stringify(n.ranges));const i=Object.fromEntries(Object.entries(n.filterSources).filter(([f])=>f in n.filters)),a=Object.fromEntries(Object.entries(n.rangeSources).filter(([f])=>f in n.ranges));return Object.keys(i).length&&t.set(Lv,JSON.stringify(i)),Object.keys(a).length&&t.set(Uv,JSON.stringify(a)),Object.keys(n.chartFilters??{}).length&&t.set($v,JSON.stringify(n.chartFilters)),Object.keys(n.chartRanges??{}).length&&t.set(Pv,JSON.stringify(n.chartRanges)),t.toString()}function Kv(n){return`sidemantic-dashboard-views:${`${n.schema??"sidemantic.dashboard.v1"}:${n.title}`}`}function x_(n){try{const e=JSON.parse(localStorage.getItem(Kv(n))??"[]");if(!Array.isArray(e))return[];const t=Yv(n);return e.flatMap(i=>{var m;if(typeof i!="object"||i===null||Array.isArray(i))return[];const a=i;if(typeof a.name!="string"||!a.name.trim())return[];if(typeof a.state!="object"||a.state===null||Array.isArray(a.state))return[];const u=a.state,f=n.tabs.some(g=>g.id===u.tab)?String(u.tab):((m=n.tabs[0])==null?void 0:m.id)??"",h=Qv(n);return[{name:a.name,state:{tab:f,filters:df(u.filters,t),ranges:ff(u.ranges,t),filterSources:tu(u.filterSources,t),rangeSources:tu(u.rangeSources,t),chartFilters:Hv(u.chartFilters,h),chartRanges:Gv(u.chartRanges,h)}}]})}catch{return[]}}function b_(n,e){try{return localStorage.setItem(Kv(n),JSON.stringify(e)),!0}catch{return!1}}function Jm(n){if(n==null)return"";const e=String(n);return/[",\r\n]/.test(e)?`"${e.replaceAll('"','""')}"`:e}function w_(n,e){return[n.map(Jm).join(","),...e.map(t=>n.map(i=>Jm(t[i])).join(","))].join(`\r -`)}function S_(n){var e;return((e=n.label)==null?void 0:e.trim())||n.id}function fd(n,e){return`${n} ${e}${n===1?"":"s"}`}function __(){const{catalog:n,dispatch:e}=ls(),t=i=>{const a=n.models.find(h=>h.name===i),u=kv(a,n),f=(a==null?void 0:a.defaultGrain)??"month";e({type:"setModel",model:i,metric:u,grain:f}),e({type:"setView",view:"explore"})};return c.jsxs("div",{className:"mx-auto w-full max-w-5xl p-6",children:[c.jsxs("div",{className:"mb-4",children:[c.jsx("h1",{className:"text-base font-semibold text-ink",children:"Explore"}),c.jsxs("p",{className:"text-2xs text-muted",children:[fd(n.models.length,"model")," · pick one to explore"]})]}),c.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3",children:n.models.map(i=>c.jsxs("button",{type:"button","data-testid":"explore-card","data-model":i.name,onClick:()=>t(i.name),className:"flex min-h-32 flex-col gap-2 rounded-xl border border-line bg-surface p-4 text-left shadow-[var(--shadow-sm)] transition-colors hover:border-line-strong",children:[c.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[c.jsx("span",{className:"truncate text-sm font-medium text-ink",children:i.label}),i.timeDimension?c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:"time series"}):null]}),i.description?c.jsx("p",{className:"line-clamp-2 text-2xs text-muted",children:i.description}):null,c.jsx("div",{className:"mt-auto flex flex-wrap gap-1 pt-1",children:i.metrics.slice(0,3).map(a=>c.jsx("span",{className:"rounded-full bg-surface-soft px-2 py-0.5 text-2xs text-muted",children:a.label},a.ref))}),c.jsxs("div",{className:"text-2xs text-faint",children:[fd(i.metrics.length,"metric")," · ",fd(i.dimensions.length,"dimension")]})]},i.name))})]})}const N_="600px";function j_(n){for(let e=n.parentElement;e;e=e.parentElement){const t=getComputedStyle(e).overflowY;if(t==="auto"||t==="scroll")return e}return null}function k_(n,e,t=N_){if(typeof IntersectionObserver>"u")return e(),()=>{};const i=new IntersectionObserver(a=>{a.some(u=>u.isIntersecting)&&(i.disconnect(),e())},{root:j_(n),rootMargin:t});return i.observe(n),()=>i.disconnect()}const I_={positive:"text-success",negative:"text-danger",neutral:"text-faint"};function Jv({dimension:n,title:e,metricLabel:t,rows:i,selectedValues:a=[],loading:u,formatMetric:f,onToggle:h,contextColumn:m="none",contextOptions:g,onContextColumn:v,collapsedLimit:x=6,expanded:b=!1,onExpandedChange:w,containerRef:j}){const C=new Set(a),O=b?i:i.slice(0,x),H=Math.max(1,...O.map(E=>Math.abs(E.metric))),L=b||i.length>x,R=m!=="none",T=R?"grid-cols-[minmax(0,1fr)_auto_auto]":"grid-cols-[minmax(0,1fr)_auto]";return c.jsxs("section",{ref:j,"data-testid":"dimension-leaderboard","data-dimension":n,"data-expanded":b||void 0,"aria-label":`${e}, ranked by ${t}`,className:"flex min-h-40 flex-col border-b border-r border-line bg-surface data-[expanded=true]:col-span-full",children:[c.jsxs("header",{className:"flex items-center justify-between gap-3 px-3 pb-2 pt-2.5",children:[c.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[c.jsx("h3",{className:"truncate text-sm font-semibold text-ink",children:e}),c.jsxs("p",{className:"sr-only",children:["Ranked by ",t]})]}),g&&v?c.jsx("div",{role:"group","aria-label":"Context column","data-testid":"leaderboard-context-toggle",className:"flex shrink-0 overflow-hidden border border-line text-2xs",children:g.map(E=>c.jsx("button",{type:"button",title:E.title,"aria-pressed":m===E.key,"data-context":E.key,"data-active":m===E.key||void 0,onClick:()=>v(E.key),className:"border-l border-line px-1.5 py-0.5 font-mono text-faint first:border-l-0 hover:bg-surface-soft data-[active=true]:bg-accent-soft data-[active=true]:text-accent",children:E.label},E.key))}):null]}),c.jsx("div",{"data-testid":"leaderboard-rows",children:u&&i.length===0?c.jsx("div",{className:"space-y-2 p-3",children:[0,1,2,3].map(E=>c.jsx("div",{className:"skeleton h-5 w-full"},E))}):i.length===0?c.jsx("p",{className:"px-3 py-4 text-xs text-faint",children:"No values"}):O.map(E=>{var V,Q,z;const I=E.metric<0?"negative":"positive",U=C.has(E.value),G=`${Math.round(Math.abs(E.metric)/H*100)}%`;return c.jsxs("button",{type:"button","data-dimension":n,"data-value":E.value,"data-selected":U||void 0,"data-tone":I,onClick:()=>h==null?void 0:h(E.value),"aria-pressed":U,className:`leaderboard-row relative grid w-full ${T} items-center gap-3 overflow-hidden border-0 bg-transparent px-3 py-1 text-left text-xs text-ink data-[selected=true]:bg-chart-primary-selected`,children:[c.jsx("span",{"aria-hidden":"true",className:`absolute inset-y-0 left-0 ${I==="negative"?"bg-danger-soft":"bg-chart-primary-soft"}`,style:{width:G}}),c.jsx("span",{className:"relative min-w-0 truncate text-muted",children:rs(E.value)}),c.jsx("strong",{className:"relative tnum font-semibold text-ink",children:f(E.metric)}),R?c.jsx("span",{"data-testid":"leaderboard-context","data-tone":((V=E.context)==null?void 0:V.tone)??"neutral",className:`relative w-14 text-right font-mono tnum text-2xs ${I_[((Q=E.context)==null?void 0:Q.tone)??"neutral"]}`,children:((z=E.context)==null?void 0:z.label)??"—"}):null]},`${n}:${E.value}`)})}),L&&!u?c.jsx("button",{type:"button","data-action":b?"leaderboard-back":"leaderboard-expand","aria-expanded":b,onClick:()=>w==null?void 0:w(!b),className:"leaderboard-expand border-0 border-t border-line bg-transparent px-3 py-1 text-left text-xs font-normal text-faint hover:text-accent",children:b?"← All dimensions":`Expand table (${i.length})`}):null]})}const M_=[{key:"none",label:"—",title:"No context column"},{key:"pctTotal",label:"%",title:"Share of total"},{key:"delta",label:"Δ",title:"Absolute change vs comparison period"},{key:"deltaPct",label:"Δ%",title:"Percent change vs comparison period"}],D_=[],C_=[];function F_({dim:n,model:e,timeDimensionRef:t,rankMetric:i,contextColumn:a,metricTotal:u,comparisonRange:f,baseFilters:h=D_,baseSegments:m=C_,usePreaggregations:g,limit:v=6,expanded:x=!1,onExpandedChange:b}){var pe;const{state:w,dispatch:j,backend:C,catalog:O}=ls(),H=D.useRef(null),[L,R]=D.useState(!1);D.useEffect(()=>{if(!(L||!H.current))return k_(H.current,()=>R(!0))},[L]);const T=t??((pe=e.timeDimension)==null?void 0:pe.ref),E=D.useMemo(()=>ou(O),[O]),I=D.useMemo(()=>[...h,...Os(w.filters,{timeRef:T,range:w.dateRange,excludeDim:n.ref,types:E})],[h,w.filters,T,w.dateRange,n.ref,E]),{result:U,loading:G,error:V}=Zn(C,L?zm(i.ref,n.ref,I,v,m,g):null),Q=w.filters[n.ref],z=(Q==null?void 0:Q.mode)==="include"?Q.values:void 0,ee=[i.ref,n.ref],X=Fn(n.ref,ee),ie=a==="delta"||a==="deltaPct",ae=D.useMemo(()=>{if(!U||!U.columns.includes(X))return null;const ne=[];let fe=!1;for(const Te of U.rows){const Ue=Te[X];Ue==null?fe=!0:ne.push(String(Ue))}const Ce=[];return ne.length&&Ce.push(`CAST(${n.ref} AS VARCHAR) IN (${ne.map(Tn).join(", ")})`),fe&&Ce.push(`${n.ref} IS NULL`),Ce.length?Ce.length===1?Ce[0]:`(${Ce.join(" OR ")})`:null},[U,X,n.ref]),re=D.useMemo(()=>ie&&f&&T&&ae?[...h,...Os(w.filters,{timeRef:T,range:f,excludeDim:n.ref,types:E}),ae]:null,[ie,f,T,w.filters,n.ref,E,ae,h]),se=Zn(C,re?zm(i.ref,n.ref,re,v,m,g):null),A=Fn(i.ref,ee),Y=!!U&&U.rows.length>0&&!U.columns.includes(A),W=D.useMemo(()=>{const ne=new Map;if(!se.result||!se.result.columns.includes(A))return ne;for(const fe of se.result.rows){const Ce=fe[X],Te=Ce==null?er:String(Ce);ne.set(Te,Number(fe[A]))}return ne},[se.result,X,A]),_={format:i.format,type:i.type};function F(ne,fe){switch(a){case"pctTotal":return u===void 0?void 0:hb(fe,u);case"delta":return pb(fe,W.get(ne),_);case"deltaPct":return mb(fe,W.get(ne));default:return}}const te=U&&!Y?U.rows.map(ne=>{const fe=ne[X],Ce=fe==null?er:String(fe),Te=Number(ne[A]??0);return{value:Ce,metric:Te,context:F(Ce,Te)}}):[];return V?c.jsx(Bi,{title:n.label,message:V}):c.jsx(Jv,{dimension:n.ref,title:n.label,metricLabel:i.label,rows:te,containerRef:H,loading:!L||G||Y,selectedValues:z,formatMetric:ne=>Wt(ne,_),onToggle:ne=>j({type:"toggleFilter",dim:n.ref,value:ne}),contextColumn:a,contextOptions:M_,onContextColumn:ne=>j({type:"setContextColumn",column:ne}),collapsedLimit:v,expanded:x,onExpandedChange:b})}function Dr(){const[n,e]=D.useState(null);return{tip:n,handlers:i=>({onMouseEnter:a=>e({content:i,x:a.clientX,y:a.clientY}),onMouseMove:a=>e({content:i,x:a.clientX,y:a.clientY}),onMouseLeave:()=>e(null)})}}function rr({tip:n,position:e="fixed",offset:t=12,className:i,style:a}){return n?c.jsx("div",{role:"tooltip",style:{position:e,left:n.x+t,top:n.y+t,pointerEvents:"none",zIndex:50,...a},className:i||"rounded-lg border border-line bg-surface px-2.5 py-1.5 text-xs text-ink shadow-[var(--shadow)]",children:n.content}):null}function os({title:n,rows:e}){return c.jsxs("div",{className:"min-w-28",children:[n?c.jsx("div",{className:"mb-0.5 font-mono text-faint",children:n}):null,e.map((t,i)=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs("span",{className:"flex items-center gap-1 text-muted",children:[t.swatch?c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-sm",style:{background:t.swatch}}):null,t.label]}),c.jsx("span",{className:"font-mono tnum font-medium text-ink",children:t.value})]},i))]})}function qv({values:n,labels:e,height:t=44,ariaLabel:i,formatValue:a=h=>h.toLocaleString(void 0,{maximumFractionDigits:2}),onHover:u,onBrush:f}){const h=D.useRef(null),m=D.useId(),g=D.useRef(null),v=D.useRef(null),[x,b]=D.useState(200),[w,j]=D.useState(null),[C,O]=D.useState(null),[H,L]=D.useState(null);D.useEffect(()=>{const W=h.current;if(!W||typeof ResizeObserver>"u")return;const _=new ResizeObserver(F=>{for(const te of F)b(Math.max(40,te.contentRect.width))});return _.observe(W),()=>_.disconnect()},[]);const R=n.map((W,_)=>({index:_,value:W})).filter(W=>Number.isFinite(W.value));if(R.length<2)return c.jsx("svg",{ref:g,role:"img","aria-label":i||"No trend data",className:"h-11 w-full",viewBox:`0 0 ${x} ${t}`});const T=3,E=Math.min(...R.map(W=>W.value)),U=Math.max(...R.map(W=>W.value))-E||1,G=R.map((W,_)=>({...W,x:T+_/(R.length-1)*(x-T*2),y:T+(1-(W.value-E)/U)*(t-T*2)})),V=G.map(({x:W,y:_})=>`${W.toFixed(1)},${_.toFixed(1)}`).join(" L "),Q=`M ${G[0].x.toFixed(1)},${t-T} L ${V} L ${G.at(-1).x.toFixed(1)},${t-T} Z`,z=G.at(-1),ee=i||`Trend of ${R.length} points, latest ${a(z.value)}`;function X(W){var F;const _=(F=g.current)==null?void 0:F.getBoundingClientRect();return _?Math.max(T,Math.min(x-T,(W.clientX-_.left)/_.width*x)):T}function ie(W){return Math.max(0,Math.min(G.length-1,Math.round((W-T)/(x-T*2)*(G.length-1))))}function ae(W){const _=X(W),F=ie(_),te=G[F];j(F),L({content:`${e!=null&&e[te.index]?`${e[te.index]}: `:""}${a(te.value)}`,x:W.clientX,y:W.clientY}),u==null||u({index:te.index,label:e==null?void 0:e[te.index],value:te.value}),v.current!==null&&O({a:v.current,b:_})}function re(W){if(!f||!(e!=null&&e.length))return;W.currentTarget.setPointerCapture(W.pointerId);const _=X(W);v.current=_,O({a:_,b:_})}function se(W){if(v.current===null||!f||!(e!=null&&e.length))return;W.currentTarget.hasPointerCapture(W.pointerId)&&W.currentTarget.releasePointerCapture(W.pointerId);const _=X(W);if(Math.abs(_-v.current)>6){const F=G[ie(Math.min(v.current,_))],te=G[ie(Math.max(v.current,_))];f({from:e[F.index],to:e[te.index]})}v.current=null,O(null)}function A(){j(null),L(null),u==null||u(null),v.current===null&&O(null)}const Y=w===null?null:G[w];return c.jsxs("span",{ref:h,className:"relative block w-full",children:[c.jsxs("svg",{ref:g,role:"img","aria-label":ee,className:`h-11 w-full overflow-hidden text-chart-primary ${f?"touch-none select-none":""}`,viewBox:`0 0 ${x} ${t}`,preserveAspectRatio:"none",onPointerMove:ae,onPointerDown:re,onPointerUp:se,onPointerCancel:A,onPointerLeave:A,onDoubleClick:()=>f==null?void 0:f(null),children:[c.jsx("defs",{children:c.jsxs("linearGradient",{id:m,x1:"0",y1:"0",x2:"0",y2:"1",children:[c.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:.16}),c.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:0})]})}),c.jsx("path",{d:Q,fill:`url(#${m})`}),c.jsx("path",{d:`M ${V}`,fill:"none",stroke:"currentColor",strokeWidth:1.5,vectorEffect:"non-scaling-stroke"}),C?c.jsx("rect",{x:Math.min(C.a,C.b),y:0,width:Math.abs(C.b-C.a),height:t,fill:"currentColor",opacity:.12}):null,Y?c.jsxs(c.Fragment,{children:[c.jsx("line",{x1:Y.x,x2:Y.x,y1:0,y2:t,stroke:"currentColor",strokeWidth:1,opacity:.45}),c.jsx("circle",{cx:Y.x,cy:Y.y,r:2.5,fill:"currentColor"})]}):c.jsx("circle",{cx:z.x,cy:z.y,r:2.25,fill:"currentColor"})]}),c.jsx(rr,{tip:H})]})}const O_={positive:"text-success",negative:"text-danger",neutral:"text-faint"},T_={positive:"▲",negative:"▼",neutral:"·"};function Nr({metric:n,label:e,value:t,valueText:i,format:a,delta:u,comparison:f,sparkValues:h=[],sparkLabels:m,selected:g,loading:v,onSelect:x,onSparkHover:b,onSparkBrush:w}){const[j,C]=D.useState(null),O=c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[c.jsx("span",{className:"truncate text-xs font-medium text-muted",children:e}),j!=null&&j.label?c.jsx("span",{className:"shrink-0 font-mono text-2xs text-faint",children:j.label}):null]}),c.jsx("div",{className:"font-mono tnum text-[19px] font-semibold leading-tight tracking-tight text-ink",children:v?c.jsx("span",{className:"skeleton inline-block h-6 w-24 align-middle"}):j?pt(j.value,a):i??pt(t,a)}),u||f?c.jsxs("div",{className:"flex items-baseline gap-1 text-2xs",children:[u?c.jsxs("span",{"data-tone":u.tone,className:`font-mono tnum font-medium ${O_[u.tone]}`,children:[c.jsx("span",{"aria-hidden":"true",className:"mr-0.5 text-[8px]",children:T_[u.tone]}),u.label]}):null,f?c.jsx("span",{className:"truncate text-faint",children:f}):null]}):null]}),H="group flex w-full flex-col gap-1.5 overflow-hidden rounded-xl border border-line bg-surface px-3.5 pt-3 text-left shadow-[var(--shadow-sm)] transition-colors hover:border-line-strong data-[selected=true]:border-accent",L=c.jsx("div",{className:"-mx-3.5 mt-auto",children:c.jsx(qv,{values:h,labels:m,onHover:R=>{C(R),b==null||b(R)},onBrush:w,formatValue:R=>pt(R,a)})});return x?c.jsxs("article",{"data-metric":n,"data-selected":g||void 0,className:H,children:[c.jsx("button",{type:"button","data-metric":n,"aria-pressed":!!g,onClick:()=>x(n),className:"-m-1 flex flex-col gap-1 border-0 bg-transparent p-1 text-left transition hover:opacity-75",children:O}),L]}):c.jsxs("article",{"data-metric":n,"data-selected":g||void 0,className:H,children:[O,L]})}const cl=280,qt={top:14,right:18,bottom:26,left:60},qm=["var(--accent)","var(--danger)","#0f9f8f","#d98921","#a66dd4","#3b82c4"];function hd(n){return qm[n%qm.length]}function Zm(n,e,t){return Math.min(Math.max(n,e),t)}function Go({points:n,seriesLabel:e="Current",additionalSeries:t=[],comparison:i,formatValue:a,formatAxis:u=a,formatLabel:f=v=>v,comparisonLabel:h="Previous",ariaLabel:m,onBrush:g}){var Fr;const v=D.useRef(null),x=D.useRef(null),b=D.useRef(!1),w=D.useRef(null),[j,C]=D.useState(820),[O,H]=D.useState(null),[L,R]=D.useState(null);D.useEffect(()=>{const ue=v.current;if(!ue)return;const Oe=new ResizeObserver(rt=>{for(const Nt of rt)C(Math.max(320,Nt.contentRect.width))});return Oe.observe(ue),()=>Oe.disconnect()},[]);const T=n.length,E=[{label:e,points:n},...t],I=[...E.flatMap(ue=>ue.points),...i??[]].map(ue=>ue.y).filter(Number.isFinite),U=T<2||I.length===0,G=U?0:Math.min(0,...I),V=U?1:Math.max(...I),Q=V-G||1,z=j-qt.left-qt.right,ee=cl-qt.top-qt.bottom,X=ue=>qt.left+(T<=1?0:ue/(T-1)*z),ie=ue=>qt.top+(1-(ue-G)/Q)*ee,ae=ue=>Zm(Math.round((ue-qt.left)/z*(T-1)),0,T-1),re=ue=>{const Oe=[];let rt=[];return ue.forEach((Nt,Un)=>{Number.isFinite(Nt.y)?rt.push(`${X(Un).toFixed(1)},${ie(Nt.y).toFixed(1)}`):rt.length&&(Oe.push(rt.join(" L ")),rt=[])}),rt.length&&Oe.push(rt.join(" L ")),Oe.map(Nt=>`M ${Nt}`).join(" ")},se=U||n.some(ue=>!Number.isFinite(ue.y))?"":`M ${X(0).toFixed(1)},${ie(G).toFixed(1)} L ${n.map((ue,Oe)=>`${X(Oe).toFixed(1)},${ie(ue.y).toFixed(1)}`).join(" L ")} L ${X(T-1).toFixed(1)},${ie(G).toFixed(1)} Z`;function A(ue){var rt;const Oe=(rt=x.current)==null?void 0:rt.getBoundingClientRect();return Oe?ue.clientX-Oe.left:0}function Y(ue){if(U)return;const Oe=A(ue);H(ae(Oe)),b.current&&w.current&&(w.current={a:w.current.a,b:Oe},R({...w.current}))}function W(ue){if(U||!g)return;ue.currentTarget.setPointerCapture(ue.pointerId),b.current=!0;const Oe=A(ue);w.current={a:Oe,b:Oe},R({...w.current})}function _(ue){ue.currentTarget.hasPointerCapture(ue.pointerId)&&ue.currentTarget.releasePointerCapture(ue.pointerId);const Oe=w.current;if(b.current&&Oe&&g){const rt=ae(Math.min(Oe.a,Oe.b)),Nt=ae(Math.max(Oe.a,Oe.b));Nt>rt&&g({from:n[rt].x,to:n[Nt].x})}b.current=!1,w.current=null,R(null)}function F(){H(null),b.current=!1,w.current=null,R(null)}const te=Math.max(1,Math.ceil(T/8)),pe=[V,G+Q*.66,G+Q*.33,G],ne=O!=null&&O>=0&&O{const rt=ue.points[ne];return rt&&Number.isFinite(rt.y)?[{...ue,point:rt,index:Oe}]:[]}),lt=ne!=null?(i==null?void 0:i[ne])??null:null,wt=lt&&Number.isFinite(lt.y)?lt:null,Bs=ne!=null?Zm(X(ne),80,j-80):0,xn=Ce&&wt&&wt.y!==0?(Ce.y-wt.y)/Math.abs(wt.y)*100:null,Cr=m??(U?"Time series chart: not enough data to plot.":`Time series chart, ${T} points from ${f(n[0].x)} to ${f(n[T-1].x)}.`);return c.jsxs("div",{className:"relative text-chart-primary",children:[c.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-x-3 gap-y-0.5 px-3 pt-2 text-2xs text-faint",children:[E.map((ue,Oe)=>c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"inline-block h-0.5 w-3",style:{backgroundColor:hd(Oe)}})," ",ue.label]},`${ue.label}-${Oe}`)),i!=null&&i.length?c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"inline-block h-0 w-3 border-t border-dashed border-faint"})," ",h]}):null]}),c.jsx("div",{ref:v,className:"w-full",children:U?c.jsx("div",{className:"grid h-[280px] place-items-center text-xs text-faint",children:"Not enough data to chart."}):c.jsxs("svg",{ref:x,width:j,height:cl,role:"img","aria-label":Cr,className:"block touch-none select-none",onPointerMove:Y,onPointerDown:W,onPointerUp:_,onPointerLeave:F,onPointerCancel:F,onDoubleClick:()=>g==null?void 0:g(null),children:[c.jsx("defs",{children:c.jsxs("linearGradient",{id:"ts-fill",x1:"0",y1:"0",x2:"0",y2:"1",children:[c.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:.18}),c.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:0})]})}),pe.map((ue,Oe)=>c.jsxs("g",{children:[c.jsx("line",{x1:qt.left,x2:j-qt.right,y1:ie(ue),y2:ie(ue),className:"stroke-line"}),c.jsx("text",{x:qt.left-8,y:ie(ue)+3,textAnchor:"end",className:"fill-faint font-mono text-[10px]",children:u(ue)})]},Oe)),i&&i.length>=2?c.jsx("path",{d:re(i),fill:"none",className:"stroke-faint",strokeWidth:1.25,strokeDasharray:"4 3"}):null,se?c.jsx("path",{d:se,fill:"url(#ts-fill)"}):null,E.map((ue,Oe)=>c.jsx("path",{d:re(ue.points),fill:"none",stroke:hd(Oe),strokeWidth:1.75},`${ue.label}-${Oe}`)),L?c.jsx("rect",{x:Math.min(L.a,L.b),y:qt.top,width:Math.abs(L.b-L.a),height:ee,className:"fill-chart-primary",opacity:.12}):null,ne!=null&&Ue.length?c.jsxs("g",{children:[c.jsx("line",{x1:X(ne),x2:X(ne),y1:qt.top,y2:cl-qt.bottom,className:"stroke-faint",strokeDasharray:"3 3"}),wt?c.jsx("circle",{cx:X(ne),cy:ie(wt.y),r:3,className:"fill-faint"}):null,Ue.map(ue=>c.jsx("circle",{cx:X(ne),cy:ie(ue.point.y),r:3.5,fill:hd(ue.index)},`${ue.label}-${ue.index}`))]}):null,n.map((ue,Oe)=>Oe%te===0||Oe===T-1?c.jsx("text",{x:X(Oe),y:cl-8,textAnchor:"middle",className:"fill-faint font-mono text-[10px]",children:f(ue.x)},ue.x):null)]})}),Ue.length&&Te?c.jsxs("div",{className:"pointer-events-none absolute top-8 z-20 -translate-x-1/2 whitespace-nowrap border border-line bg-surface px-2 py-1.5 text-2xs shadow-[var(--shadow)]",style:{left:Bs},children:[c.jsx("div",{className:"mb-0.5 font-mono text-faint",children:f(Te)}),Ue.map(ue=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"text-muted",children:ue.label}),c.jsx("span",{className:"font-mono tnum font-medium text-ink",children:a(ue.point.y)})]},`${ue.label}-${ue.index}`)),wt?c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"text-muted",children:h}),c.jsx("span",{className:"font-mono tnum text-muted",children:a(wt.y)})]}):null,xn!=null?c.jsxs("div",{className:`mt-0.5 text-right font-mono ${xn>0?"text-success":xn<0?"text-danger":"text-faint"}`,children:[xn.toLocaleString(void 0,{maximumFractionDigits:1,signDisplay:"exceptZero"}),"%"]}):null]}):null]})}const A_={positive:"text-success",negative:"text-danger",neutral:"text-faint"};function B_({metric:n,points:e,comparisonPoints:t,total:i,prevTotal:a,hasTime:u,loading:f,activeRange:h,comparisonLabel:m="Prev period",formatLabel:g,onBrush:v}){const x={format:n.format,type:n.type},b=a!==void 0?yy(i,a):null,w=`${n.label} over time. Total ${pt(i,x)}${b?`, ${b.label} versus the ${m.toLowerCase()}`:""}.`;return c.jsxs("section",{className:"flex flex-col gap-2",children:[c.jsxs("header",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-0.5 px-0.5",children:[c.jsx("h2",{className:"text-xs font-medium text-muted",children:n.label}),c.jsx("span",{className:"font-mono tnum text-xl font-semibold text-ink",children:pt(i,x)}),b?c.jsxs("span",{className:`text-xs ${A_[b.tone]}`,children:[b.label," vs ",m.toLowerCase()]}):null,u?null:c.jsx("span",{className:"text-2xs text-faint",children:"No time dimension"}),h?c.jsx("button",{type:"button",onClick:()=>v(null),className:"ml-auto inline-flex h-7 items-center rounded-full border border-line bg-surface px-3 text-xs text-muted hover:border-line-strong hover:text-ink",children:"Reset zoom"}):null]}),u?f&&e.length<2?c.jsx("div",{className:"skeleton h-[280px] w-full"}):c.jsx(Go,{points:e,comparison:t,formatValue:j=>pt(j,x),formatAxis:j=>Wt(j,x),formatLabel:g,comparisonLabel:m,ariaLabel:w,onBrush:v}):null]})}const E_=new Set(["and","as","asc","by","case","cast","count","date_trunc","desc","else","end","from","group","in","is","join","left","limit","not","null","on","or","order","over","partition","select","sum","then","when","where","with"]);function R_(n){const e=[];let t=0;for(;ta).map(([a,u])=>`-- ${a} +]`}concat(...e){const t=this.schema,i=this.data.concat(e.flatMap(({data:a})=>a));return new mn(t,i.map(a=>new An(t,a)))}slice(e,t){const i=this.schema;[e,t]=Jg({length:this.numRows},e,t);const a=ev(this.data,this._offsets,e,t);return new mn(i,a.map(u=>new An(i,u)))}getChild(e){return this.getChildAt(this.schema.fields.findIndex(t=>t.name===e))}getChildAt(e){if(e>-1&&ei.children[e]);if(t.length===0){const{type:i}=this.schema.fields[e],a=Ee({type:i,length:0,nullCount:0});t.push(a._changeLengthAndBackfillNullBitmap(this.numRows))}return new Je(t)}return null}setChild(e,t){var i;return this.setChildAt((i=this.schema.fields)===null||i===void 0?void 0:i.findIndex(a=>a.name===e),t)}setChildAt(e,t){let i=this.schema,a=[...this.batches];if(e>-1&&ethis.getChildAt(g));[u[e],h[e]]=[f,t],[i,a]=od(i,h)}return new mn(i,a)}select(e){const t=this.schema.fields.reduce((i,a,u)=>i.set(a.name,u),new Map);return this.selectAt(e.map(i=>t.get(i)).filter(i=>i>-1))}selectAt(e){const t=this.schema.selectAt(e),i=this.batches.map(a=>a.selectAt(e));return new mn(t,i)}assign(e){const t=this.schema.fields,[i,a]=e.schema.fields.reduce((h,m,g)=>{const[v,x]=h,b=t.findIndex(w=>w.name===m.name);return~b?x[b]=g:v.push(g),h},[[],[]]),u=this.schema.assign(e.schema),f=[...t.map((h,m)=>[m,a[m]]).map(([h,m])=>m===void 0?this.getChildAt(h):e.getChildAt(m)),...i.map(h=>e.getChildAt(h))].filter(Boolean);return new mn(...od(u,f))}}cv=Symbol.toStringTag;mn[cv]=(n=>(n.schema=null,n.batches=[],n._offsets=new Uint32Array([0]),n._nullCount=-1,n[Symbol.isConcatSpreadable]=!0,n.isValid=zl(Gd),n.get=zl(Gt.getVisitFn(D.Struct)),n.set=tv(vn.getVisitFn(D.Struct)),n.indexOf=nv(Vl.getVisitFn(D.Struct)),"Table"))(mn.prototype);var dv;let An=class Oo{constructor(...e){switch(e.length){case 2:{if([this.schema]=e,!(this.schema instanceof We))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");if([,this.data=Ee({nullCount:0,type:new Tt(this.schema.fields),children:this.schema.fields.map(t=>Ee({type:t.type,nullCount:0}))})]=e,!(this.data instanceof Ye))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");[this.schema,this.data]=Mm(this.schema,this.data.children);break}case 1:{const[t]=e,{fields:i,children:a,length:u}=Object.keys(t).reduce((m,g,v)=>(m.children[v]=t[g],m.length=Math.max(m.length,t[g].length),m.fields[v]=nt.new({name:g,type:t[g].type,nullable:!0}),m),{length:0,fields:new Array,children:new Array}),f=new We(i),h=Ee({type:new Tt(i),length:u,children:a,nullCount:0});[this.schema,this.data]=Mm(f,h.children,u);break}default:throw new TypeError("RecordBatch constructor expects an Object mapping names to child Data, or a [Schema, Data] pair.")}}get dictionaries(){return this._dictionaries||(this._dictionaries=fv(this.schema.fields,this.data.children))}get numCols(){return this.schema.fields.length}get numRows(){return this.data.length}get nullCount(){return this.data.nullCount}isValid(e){return this.data.getValid(e)}get(e){return Gt.visit(this.data,e)}at(e){return this.get(Vd(e,this.numRows))}set(e,t){return vn.visit(this.data,e,t)}indexOf(e,t){return Vl.visit(this.data,e,t)}[Symbol.iterator](){return Yd.visit(new Je([this.data]))}toArray(){return[...this]}concat(...e){return new mn(this.schema,[this,...e])}slice(e,t){const[i]=new Je([this.data]).slice(e,t).data;return new Oo(this.schema,i)}getChild(e){var t;return this.getChildAt((t=this.schema.fields)===null||t===void 0?void 0:t.findIndex(i=>i.name===e))}getChildAt(e){return e>-1&&ea.name===e),t)}setChildAt(e,t){let i=this.schema,a=this.data;if(e>-1&&eh.name===u);~f&&(a[f]=this.data.children[f])}return new Oo(t,Ee({type:i,length:this.numRows,children:a}))}selectAt(e){const t=this.schema.selectAt(e),i=e.map(u=>this.data.children[u]).filter(Boolean),a=Ee({type:new Tt(t.fields),length:this.numRows,children:i});return new Oo(t,a)}};dv=Symbol.toStringTag;An[dv]=(n=>(n._nullCount=-1,n[Symbol.isConcatSpreadable]=!0,"RecordBatch"))(An.prototype);function Mm(n,e,t=e.reduce((i,a)=>Math.max(i,a.length),0)){var i;const a=[...n.fields],u=[...e],f=(t+63&-64)>>3;for(const[h,m]of n.fields.entries()){const g=e[h];(!g||g.length!==t)&&(a[h]=m.clone({nullable:!0}),u[h]=(i=g==null?void 0:g._changeLengthAndBackfillNullBitmap(t))!==null&&i!==void 0?i:Ee({type:m.type,length:t,nullCount:t,nullBitmap:new Uint8Array(f)}))}return[n.assign(a),Ee({type:new Tt(a),length:t,children:u})]}function fv(n,e,t=new Map){var i,a;if(((i=n==null?void 0:n.length)!==null&&i!==void 0?i:0)>0&&(n==null?void 0:n.length)===(e==null?void 0:e.length))for(let u=-1,f=n.length;++uEe({type:a.type})),i=Ee({type:new Tt(e.fields),nullCount:0,children:t});super(e,i)}}let qr=class Hn{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsMessage(e,t){return(t||new Hn).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsMessage(e,t){return e.setPosition(e.position()+He),(t||new Hn).__init(e.readInt32(e.position())+e.position(),e)}version(){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt16(this.bb_pos+e):ht.V1}headerType(){const e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb_pos+e):Ve.NONE}header(e){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__union(e,this.bb_pos+t):null}bodyLength(){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt64(this.bb_pos+e):BigInt("0")}customMetadata(e,t){const i=this.bb.__offset(this.bb_pos,12);return i?(t||new gt).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+e*4),this.bb):null}customMetadataLength(){const e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}static startMessage(e){e.startObject(5)}static addVersion(e,t){e.addFieldInt16(0,t,ht.V1)}static addHeaderType(e,t){e.addFieldInt8(1,t,Ve.NONE)}static addHeader(e,t){e.addFieldOffset(2,t,0)}static addBodyLength(e,t){e.addFieldInt64(3,t,BigInt("0"))}static addCustomMetadata(e,t){e.addFieldOffset(4,t,0)}static createCustomMetadataVector(e,t){e.startVector(4,t.length,4);for(let i=t.length-1;i>=0;i--)e.addOffset(t[i]);return e.endVector()}static startCustomMetadataVector(e,t){e.startVector(4,t,4)}static endMessage(e){return e.endObject()}static finishMessageBuffer(e,t){e.finish(t)}static finishSizePrefixedMessageBuffer(e,t){e.finish(t,void 0,!0)}static createMessage(e,t,i,a,u,f){return Hn.startMessage(e),Hn.addVersion(e,t),Hn.addHeaderType(e,i),Hn.addHeader(e,a),Hn.addBodyLength(e,u),Hn.addCustomMetadata(e,f),Hn.endMessage(e)}};class p1 extends Re{visit(e,t){return e==null||t==null?void 0:super.visit(e,t)}visitNull(e,t){return vm.startNull(t),vm.endNull(t)}visitInt(e,t){return en.startInt(t),en.addBitWidth(t,e.bitWidth),en.addIsSigned(t,e.isSigned),en.endInt(t)}visitFloat(e,t){return Kn.startFloatingPoint(t),Kn.addPrecision(t,e.precision),Kn.endFloatingPoint(t)}visitBinary(e,t){return hm.startBinary(t),hm.endBinary(t)}visitLargeBinary(e,t){return mm.startLargeBinary(t),mm.endLargeBinary(t)}visitBool(e,t){return pm.startBool(t),pm.endBool(t)}visitUtf8(e,t){return xm.startUtf8(t),xm.endUtf8(t)}visitLargeUtf8(e,t){return ym.startLargeUtf8(t),ym.endLargeUtf8(t)}visitDecimal(e,t){return ci.startDecimal(t),ci.addScale(t,e.scale),ci.addPrecision(t,e.precision),ci.addBitWidth(t,e.bitWidth),ci.endDecimal(t)}visitDate(e,t){return hl.startDate(t),hl.addUnit(t,e.unit),hl.endDate(t)}visitTime(e,t){return hn.startTime(t),hn.addUnit(t,e.unit),hn.addBitWidth(t,e.bitWidth),hn.endTime(t)}visitTimestamp(e,t){const i=e.timezone&&t.createString(e.timezone)||void 0;return pn.startTimestamp(t),pn.addUnit(t,e.unit),i!==void 0&&pn.addTimezone(t,i),pn.endTimestamp(t)}visitInterval(e,t){return Jn.startInterval(t),Jn.addUnit(t,e.unit),Jn.endInterval(t)}visitDuration(e,t){return pl.startDuration(t),pl.addUnit(t,e.unit),pl.endDuration(t)}visitList(e,t){return gm.startList(t),gm.endList(t)}visitStruct(e,t){return ks.startStruct_(t),ks.endStruct_(t)}visitUnion(e,t){Vt.startTypeIdsVector(t,e.typeIds.length);const i=Vt.createTypeIdsVector(t,e.typeIds);return Vt.startUnion(t),Vt.addMode(t,e.mode),Vt.addTypeIds(t,i),Vt.endUnion(t)}visitDictionary(e,t){const i=this.visit(e.indices,t);return wr.startDictionaryEncoding(t),wr.addId(t,BigInt(e.id)),wr.addIsOrdered(t,e.isOrdered),i!==void 0&&wr.addIndexType(t,i),wr.endDictionaryEncoding(t)}visitFixedSizeBinary(e,t){return ml.startFixedSizeBinary(t),ml.addByteWidth(t,e.byteWidth),ml.endFixedSizeBinary(t)}visitFixedSizeList(e,t){return yl.startFixedSizeList(t),yl.addListSize(t,e.listSize),yl.endFixedSizeList(t)}visitMap(e,t){return gl.startMap(t),gl.addKeysSorted(t,e.keysSorted),gl.endMap(t)}}const ad=new p1;function m1(n,e=new Map){return new We(g1(n,e),xl(n.metadata),e)}function pv(n){return new Rn(n.count,mv(n.columns),yv(n.columns))}function y1(n){return new kr(pv(n.data),n.id,n.isDelta)}function g1(n,e){return(n.fields||[]).filter(Boolean).map(t=>nt.fromJSON(t,e))}function Dm(n,e){return(n.children||[]).filter(Boolean).map(t=>nt.fromJSON(t,e))}function mv(n){return(n||[]).reduce((e,t)=>[...e,new Ai(t.count,v1(t.VALIDITY)),...mv(t.children)],[])}function yv(n,e=[]){for(let t=-1,i=(n||[]).length;++te+ +(t===0),0)}function x1(n,e){let t,i,a,u,f,h;return!e||!(u=n.dictionary)?(f=Fm(n,Dm(n,e)),a=new nt(n.name,f,n.nullable,xl(n.metadata))):e.has(t=u.id)?(i=(i=u.indexType)?Cm(i):new Lo,h=new Mi(e.get(t),i,t,u.isOrdered),a=new nt(n.name,h,n.nullable,xl(n.metadata))):(i=(i=u.indexType)?Cm(i):new Lo,e.set(t,f=Fm(n,Dm(n,e))),h=new Mi(f,i,t,u.isOrdered),a=new nt(n.name,h,n.nullable,xl(n.metadata))),a||null}function xl(n=[]){return new Map(n.map(({key:e,value:t})=>[e,t]))}function Cm(n){return new Ds(n.isSigned,n.bitWidth)}function Fm(n,e){const t=n.type.name;switch(t){case"NONE":return new ss;case"null":return new ss;case"binary":return new kl;case"largebinary":return new Il;case"utf8":return new Ml;case"largeutf8":return new Dl;case"bool":return new Cl;case"list":return new Rl((e||[])[0]);case"struct":return new Tt(e||[]);case"struct_":return new Tt(e||[])}switch(t){case"int":{const i=n.type;return new Ds(i.isSigned,i.bitWidth)}case"floatingpoint":{const i=n.type;return new jl(Dt[i.precision])}case"decimal":{const i=n.type;return new Fl(i.scale,i.precision,i.bitWidth)}case"date":{const i=n.type;return new Ol(gn[i.unit])}case"time":{const i=n.type;return new Tl(_e[i.unit],i.bitWidth)}case"timestamp":{const i=n.type;return new Al(_e[i.unit],i.timezone)}case"interval":{const i=n.type;return new Bl(nr[i.unit])}case"duration":{const i=n.type;return new El(_e[i.unit])}case"union":{const i=n.type,[a,...u]=(i.mode+"").toLowerCase(),f=a.toUpperCase()+u.join("");return new Ll(Ht[f],i.typeIds||[],e||[])}case"fixedsizebinary":{const i=n.type;return new Ul(i.byteWidth)}case"fixedsizelist":{const i=n.type;return new $l(i.listSize,(e||[])[0])}case"map":{const i=n.type;return new Pl((e||[])[0],i.keysSorted)}}throw new Error(`Unrecognized type: "${t}"`)}var b1=Cy,w1=ki;class Bn{static fromJSON(e,t){const i=new Bn(0,ht.V5,t);return i._createHeader=S1(e,t),i}static decode(e){e=new w1($e(e));const t=qr.getRootAsMessage(e),i=t.bodyLength(),a=t.version(),u=t.headerType(),f=new Bn(i,a,u);return f._createHeader=_1(t,u),f}static encode(e){const t=new b1;let i=-1;return e.isSchema()?i=We.encode(t,e.header()):e.isRecordBatch()?i=Rn.encode(t,e.header()):e.isDictionaryBatch()&&(i=kr.encode(t,e.header())),qr.startMessage(t),qr.addVersion(t,ht.V5),qr.addHeader(t,i),qr.addHeaderType(t,e.headerType),qr.addBodyLength(t,BigInt(e.bodyLength)),qr.finishMessageBuffer(t,qr.endMessage(t)),t.asUint8Array()}static from(e,t=0){if(e instanceof We)return new Bn(0,ht.V5,Ve.Schema,e);if(e instanceof Rn)return new Bn(t,ht.V5,Ve.RecordBatch,e);if(e instanceof kr)return new Bn(t,ht.V5,Ve.DictionaryBatch,e);throw new Error(`Unrecognized Message header: ${e}`)}get type(){return this.headerType}get version(){return this._version}get headerType(){return this._headerType}get bodyLength(){return this._bodyLength}header(){return this._createHeader()}isSchema(){return this.headerType===Ve.Schema}isRecordBatch(){return this.headerType===Ve.RecordBatch}isDictionaryBatch(){return this.headerType===Ve.DictionaryBatch}constructor(e,t,i,a){this._version=t,this._headerType=i,this.body=new Uint8Array(0),a&&(this._createHeader=()=>a),this._bodyLength=tt(e)}}class Rn{get nodes(){return this._nodes}get length(){return this._length}get buffers(){return this._buffers}constructor(e,t,i){this._nodes=t,this._buffers=i,this._length=tt(e)}}class kr{get id(){return this._id}get data(){return this._data}get isDelta(){return this._isDelta}get length(){return this.data.length}get nodes(){return this.data.nodes}get buffers(){return this.data.buffers}constructor(e,t,i=!1){this._data=e,this._isDelta=i,this._id=tt(t)}}class _r{constructor(e,t){this.offset=tt(e),this.length=tt(t)}}class Ai{constructor(e,t){this.length=tt(e),this.nullCount=tt(t)}}function S1(n,e){return(()=>{switch(e){case Ve.Schema:return We.fromJSON(n);case Ve.RecordBatch:return Rn.fromJSON(n);case Ve.DictionaryBatch:return kr.fromJSON(n)}throw new Error(`Unrecognized Message type: { name: ${Ve[e]}, type: ${e} }`)})}function _1(n,e){return(()=>{switch(e){case Ve.Schema:return We.decode(n.header(new Gn),new Map,n.version());case Ve.RecordBatch:return Rn.decode(n.header(new yr),n.version());case Ve.DictionaryBatch:return kr.decode(n.header(new li),n.version())}throw new Error(`Unrecognized Message type: { name: ${Ve[e]}, type: ${e} }`)})}nt.encode=A1;nt.decode=O1;nt.fromJSON=x1;We.encode=T1;We.decode=N1;We.fromJSON=m1;Rn.encode=B1;Rn.decode=j1;Rn.fromJSON=pv;kr.encode=E1;kr.decode=k1;kr.fromJSON=y1;Ai.encode=R1;Ai.decode=M1;_r.encode=L1;_r.decode=I1;function N1(n,e=new Map,t=ht.V5){const i=F1(n,e);return new We(i,bl(n),e,t)}function j1(n,e=ht.V5){if(n.compression()!==null)throw new Error("Record batch compression not implemented");return new Rn(n.length(),D1(n),C1(n,e))}function k1(n,e=ht.V5){return new kr(Rn.decode(n.data(),e),n.id(),n.isDelta())}function I1(n){return new _r(n.offset(),n.length())}function M1(n){return new Ai(n.length(),n.nullCount())}function D1(n){const e=[];for(let t,i=-1,a=-1,u=n.nodesLength();++int.encode(n,u));Gn.startFieldsVector(n,t.length);const i=Gn.createFieldsVector(n,t),a=e.metadata&&e.metadata.size>0?Gn.createCustomMetadataVector(n,[...e.metadata].map(([u,f])=>{const h=n.createString(`${u}`),m=n.createString(`${f}`);return gt.startKeyValue(n),gt.addKey(n,h),gt.addValue(n,m),gt.endKeyValue(n)})):-1;return Gn.startSchema(n),Gn.addFields(n,i),Gn.addEndianness(n,U1?Ii.Little:Ii.Big),a!==-1&&Gn.addCustomMetadata(n,a),Gn.endSchema(n)}function A1(n,e){let t=-1,i=-1,a=-1;const u=e.type;let f=e.typeId;me.isDictionary(u)?(f=u.dictionary.typeId,a=ad.visit(u,n),i=ad.visit(u.dictionary,n)):i=ad.visit(u,n);const h=(u.children||[]).map(v=>nt.encode(n,v)),m=dn.createChildrenVector(n,h),g=e.metadata&&e.metadata.size>0?dn.createCustomMetadataVector(n,[...e.metadata].map(([v,x])=>{const b=n.createString(`${v}`),w=n.createString(`${x}`);return gt.startKeyValue(n),gt.addKey(n,b),gt.addValue(n,w),gt.endKeyValue(n)})):-1;return e.name&&(t=n.createString(e.name)),dn.startField(n),dn.addType(n,i),dn.addTypeType(n,f),dn.addChildren(n,m),dn.addNullable(n,!!e.nullable),t!==-1&&dn.addName(n,t),a!==-1&&dn.addDictionary(n,a),g!==-1&&dn.addCustomMetadata(n,g),dn.endField(n)}function B1(n,e){const t=e.nodes||[],i=e.buffers||[];yr.startNodesVector(n,t.length);for(const f of t.slice().reverse())Ai.encode(n,f);const a=n.endVector();yr.startBuffersVector(n,i.length);for(const f of i.slice().reverse())_r.encode(n,f);const u=n.endVector();return yr.startRecordBatch(n),yr.addLength(n,BigInt(e.length)),yr.addNodes(n,a),yr.addBuffers(n,u),yr.endRecordBatch(n)}function E1(n,e){const t=Rn.encode(n,e.data);return li.startDictionaryBatch(n),li.addId(n,BigInt(e.id)),li.addIsDelta(n,e.isDelta),li.addData(n,t),li.endDictionaryBatch(n)}function R1(n,e){return Ty.createFieldNode(n,BigInt(e.length),BigInt(e.nullCount))}function L1(n,e){return Oy.createBuffer(n,BigInt(e.offset),BigInt(e.length))}const U1=(()=>{const n=new ArrayBuffer(2);return new DataView(n).setInt16(0,256,!0),new Int16Array(n)[0]===256})(),Xd=n=>`Expected ${Ve[n]} Message in stream, but was null or length 0.`,ef=n=>`Header pointer of flatbuffer-encoded ${Ve[n]} Message is null or length 0.`,gv=(n,e)=>`Expected to read ${n} metadata bytes, but only read ${e}.`,vv=(n,e)=>`Expected to read ${n} bytes for message body, but only read ${e}.`;class xv{constructor(e){this.source=e instanceof Hl?e:new Hl(e)}[Symbol.iterator](){return this}next(){let e;return(e=this.readMetadataLength()).done||e.value===-1&&(e=this.readMetadataLength()).done||(e=this.readMetadata(e.value)).done?at:e}throw(e){return this.source.throw(e)}return(e){return this.source.return(e)}readMessage(e){let t;if((t=this.next()).done)return null;if(e!=null&&t.value.headerType!==e)throw new Error(Xd(e));return t.value}readMessageBody(e){if(e<=0)return new Uint8Array(0);const t=$e(this.source.read(e));if(t.byteLength[...a,...u.VALIDITY&&[u.VALIDITY]||[],...u.TYPE_ID&&[u.TYPE_ID]||[],...u.OFFSET&&[u.OFFSET]||[],...u.DATA&&[u.DATA]||[],...t(u.children)],[])}}readMessage(e){let t;if((t=this.next()).done)return null;if(e!=null&&t.value.headerType!==e)throw new Error(Xd(e));return t.value}readSchema(){const e=Ve.Schema,t=this.readMessage(e),i=t==null?void 0:t.header();if(!t||!i)throw new Error(ef(e));return i}}const iu=4,Cd="ARROW1",Yl=new Uint8Array(Cd.length);for(let n=0;nthis):this}readRecordBatch(e){return this._impl.isFile()?this._impl.readRecordBatch(e):null}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}toDOMStream(){return fn.toDOMStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this})}toNodeStream(){return fn.toNodeStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this},{objectMode:!0})}static throughNode(e){throw new Error('"throughNode" not available in this environment')}static throughDOM(e,t){throw new Error('"throughDOM" not available in this environment')}static from(e){return e instanceof jr?e:bd(e)?G1(e):Ny(e)?K1(e):Ao(e)?Fe(this,void 0,void 0,function*(){return yield jr.from(yield e)}):jy(e)||Rd(e)||Iy(e)||Ed(e)?Q1(new Ci(e)):Y1(new Hl(e))}static readAll(e){return e instanceof jr?e.isSync()?Bm(e):Em(e):bd(e)||ArrayBuffer.isView(e)||nu(e)||_y(e)?Bm(e):Em(e)}}class Ql extends jr{constructor(e){super(e),this._impl=e}readAll(){return[...this]}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return qn(this,arguments,function*(){yield Ae(yield*fl(xi(this[Symbol.iterator]())))})}}class Kl extends jr{constructor(e){super(e),this._impl=e}readAll(){return Fe(this,void 0,void 0,function*(){var e,t,i,a;const u=new Array;try{for(var f=!0,h=xi(this),m;m=yield h.next(),e=m.done,!e;f=!0){a=m.value,f=!1;const g=a;u.push(g)}}catch(g){t={error:g}}finally{try{!f&&!e&&(i=h.return)&&(yield i.call(h))}finally{if(t)throw t.error}}return u})}[Symbol.iterator](){throw new Error("AsyncRecordBatchStreamReader is not Iterable")}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}}class wv extends Ql{constructor(e){super(e),this._impl=e}}class V1 extends Kl{constructor(e){super(e),this._impl=e}}class Sv{get numDictionaries(){return this._dictionaryIndex}get numRecordBatches(){return this._recordBatchIndex}constructor(e=new Map){this.closed=!1,this.autoDestroy=!0,this._dictionaryIndex=0,this._recordBatchIndex=0,this.dictionaries=e}isSync(){return!1}isAsync(){return!1}isFile(){return!1}isStream(){return!1}reset(e){return this._dictionaryIndex=0,this._recordBatchIndex=0,this.schema=e,this.dictionaries=new Map,this}_loadRecordBatch(e,t){const i=this._loadVectors(e,t,this.schema.fields),a=Ee({type:new Tt(this.schema.fields),length:e.length,children:i});return new An(this.schema,a)}_loadDictionaryBatch(e,t){const{id:i,isDelta:a}=e,{dictionaries:u,schema:f}=this,h=u.get(i),m=f.dictionaries.get(i),g=this._loadVectors(e.data,t,[m]);return(h&&a?h.concat(new Je(g)):new Je(g)).memoize()}_loadVectors(e,t,i){return new uv(t,e.nodes,e.buffers,this.dictionaries,this.schema.metadataVersion).visitMany(i)}}class Jl extends Sv{constructor(e,t){super(t),this._reader=bd(e)?new P1(this._handle=e):new xv(this._handle=e)}isSync(){return!0}isStream(){return!0}[Symbol.iterator](){return this}cancel(){!this.closed&&(this.closed=!0)&&(this.reset()._reader.return(),this._reader=null,this.dictionaries=null)}open(e){return this.closed||(this.autoDestroy=Nv(this,e),this.schema||(this.schema=this._reader.readSchema())||this.cancel()),this}throw(e){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.throw(e):at}return(e){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.return(e):at}next(){if(this.closed)return at;let e;const{_reader:t}=this;for(;e=this._readNextMessageAndValidate();)if(e.isSchema())this.reset(e.header());else if(e.isRecordBatch()){this._recordBatchIndex++;const i=e.header(),a=t.readMessageBody(e.bodyLength);return{done:!1,value:this._loadRecordBatch(i,a)}}else if(e.isDictionaryBatch()){this._dictionaryIndex++;const i=e.header(),a=t.readMessageBody(e.bodyLength),u=this._loadDictionaryBatch(i,a);this.dictionaries.set(i.id,u)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new hv(this.schema)}):this.return()}_readNextMessageAndValidate(e){return this._reader.readMessage(e)}}class ql extends Sv{constructor(e,t){super(t),this._reader=new $1(this._handle=e)}isAsync(){return!0}isStream(){return!0}[Symbol.asyncIterator](){return this}cancel(){return Fe(this,void 0,void 0,function*(){!this.closed&&(this.closed=!0)&&(yield this.reset()._reader.return(),this._reader=null,this.dictionaries=null)})}open(e){return Fe(this,void 0,void 0,function*(){return this.closed||(this.autoDestroy=Nv(this,e),this.schema||(this.schema=yield this._reader.readSchema())||(yield this.cancel())),this})}throw(e){return Fe(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.throw(e):at})}return(e){return Fe(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.return(e):at})}next(){return Fe(this,void 0,void 0,function*(){if(this.closed)return at;let e;const{_reader:t}=this;for(;e=yield this._readNextMessageAndValidate();)if(e.isSchema())yield this.reset(e.header());else if(e.isRecordBatch()){this._recordBatchIndex++;const i=e.header(),a=yield t.readMessageBody(e.bodyLength);return{done:!1,value:this._loadRecordBatch(i,a)}}else if(e.isDictionaryBatch()){this._dictionaryIndex++;const i=e.header(),a=yield t.readMessageBody(e.bodyLength),u=this._loadDictionaryBatch(i,a);this.dictionaries.set(i.id,u)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new hv(this.schema)}):yield this.return()})}_readNextMessageAndValidate(e){return Fe(this,void 0,void 0,function*(){return yield this._reader.readMessage(e)})}}class _v extends Jl{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(e,t){super(e instanceof Im?e:new Im(e),t)}isSync(){return!0}isFile(){return!0}open(e){if(!this.closed&&!this._footer){this.schema=(this._footer=this._readFooter()).schema;for(const t of this._footer.dictionaryBatches())t&&this._readDictionaryBatch(this._dictionaryIndex++)}return super.open(e)}readRecordBatch(e){var t;if(this.closed)return null;this._footer||this.open();const i=(t=this._footer)===null||t===void 0?void 0:t.getRecordBatch(e);if(i&&this._handle.seek(i.offset)){const a=this._reader.readMessage(Ve.RecordBatch);if(a!=null&&a.isRecordBatch()){const u=a.header(),f=this._reader.readMessageBody(a.bodyLength);return this._loadRecordBatch(u,f)}}return null}_readDictionaryBatch(e){var t;const i=(t=this._footer)===null||t===void 0?void 0:t.getDictionaryBatch(e);if(i&&this._handle.seek(i.offset)){const a=this._reader.readMessage(Ve.DictionaryBatch);if(a!=null&&a.isDictionaryBatch()){const u=a.header(),f=this._reader.readMessageBody(a.bodyLength),h=this._loadDictionaryBatch(u,f);this.dictionaries.set(u.id,h)}}}_readFooter(){const{_handle:e}=this,t=e.size-bv,i=e.readInt32(t),a=e.readAt(t-i,i);return Qd.decode(a)}_readNextMessageAndValidate(e){var t;if(this._footer||this.open(),this._footer&&this._recordBatchIndexsuper.open}});return Fe(this,void 0,void 0,function*(){if(!this.closed&&!this._footer){this.schema=(this._footer=yield this._readFooter()).schema;for(const i of this._footer.dictionaryBatches())i&&(yield this._readDictionaryBatch(this._dictionaryIndex++))}return yield t.open.call(this,e)})}readRecordBatch(e){return Fe(this,void 0,void 0,function*(){var t;if(this.closed)return null;this._footer||(yield this.open());const i=(t=this._footer)===null||t===void 0?void 0:t.getRecordBatch(e);if(i&&(yield this._handle.seek(i.offset))){const a=yield this._reader.readMessage(Ve.RecordBatch);if(a!=null&&a.isRecordBatch()){const u=a.header(),f=yield this._reader.readMessageBody(a.bodyLength);return this._loadRecordBatch(u,f)}}return null})}_readDictionaryBatch(e){return Fe(this,void 0,void 0,function*(){var t;const i=(t=this._footer)===null||t===void 0?void 0:t.getDictionaryBatch(e);if(i&&(yield this._handle.seek(i.offset))){const a=yield this._reader.readMessage(Ve.DictionaryBatch);if(a!=null&&a.isDictionaryBatch()){const u=a.header(),f=yield this._reader.readMessageBody(a.bodyLength),h=this._loadDictionaryBatch(u,f);this.dictionaries.set(u.id,h)}}})}_readFooter(){return Fe(this,void 0,void 0,function*(){const{_handle:e}=this;e._pending&&(yield e._pending);const t=e.size-bv,i=yield e.readInt32(t),a=yield e.readAt(t-i,i);return Qd.decode(a)})}_readNextMessageAndValidate(e){return Fe(this,void 0,void 0,function*(){if(this._footer||(yield this.open()),this._footer&&this._recordBatchIndex=4?tf(e)?new wv(new _v(n.read())):new Ql(new Jl(n)):new Ql(new Jl((function*(){})()))}function Q1(n){return Fe(this,void 0,void 0,function*(){const e=yield n.peek(Wo+7&-8);return e&&e.byteLength>=4?tf(e)?new wv(new _v(yield n.read())):new Kl(new ql(n)):new Kl(new ql((function(){return qn(this,arguments,function*(){})})()))})}function K1(n){return Fe(this,void 0,void 0,function*(){const{size:e}=yield n.stat(),t=new Gl(n,e);return e>=z1&&tf(yield t.readAt(0,Wo+7&-8))?new V1(new W1(t)):new Kl(new ql(t))})}function jv(n){const e=jr.from(n);return Ao(e)?e.then(t=>jv(t)):e.isAsync()?e.readAll().then(t=>new mn(t)):new mn(e.readAll())}function J1(n){if(n==null)return null;if(typeof n=="bigint"){const e=Number(n);return Number.isSafeInteger(e)?e:n.toString()}if(n instanceof Date){const e=n.toISOString();return e.endsWith("T00:00:00.000Z")?e.slice(0,10):e}return typeof n=="object"?String(n):n}function q1(n){const e=jv(n),t=e.schema.fields.map(a=>a.name),i=new Array(e.numRows);for(let a=0;a({...e,charts:e.charts.map(t=>{var f,h;const i=t.query,a=(f=t.interactions)==null?void 0:f.brush,u=(h=t.interactions)==null?void 0:h.select;return{...t,query:{...i,metrics:Zr(i.metrics)??[],dimensions:Zr(i.dimensions),filters:Zr(i.filters),segments:Zr(i.segments),order_by:Zr(i.order_by),orderBy:Zr(i.orderBy)},interactions:t.interactions?{...t.interactions,brush:typeof a=="object"?{...a,fields:Zr(a.fields)}:a,select:typeof u=="object"?{...u,fields:Zr(u.fields)}:u}:void 0}})}))}}const X1="application/vnd.apache.arrow.stream";class eS{constructor(e){Mn(this,"active",0);Mn(this,"waiters",[]);this.max=e}async run(e){var t;this.active>=this.max&&await new Promise(i=>this.waiters.push(i)),this.active+=1;try{return await e()}finally{this.active-=1,(t=this.waiters.shift())==null||t()}}}function tS(n){var t,i,a,u,f;const e={};return(t=n.metrics)!=null&&t.length&&(e.metrics=n.metrics),(i=n.dimensions)!=null&&i.length&&(e.dimensions=n.dimensions),(a=n.filters)!=null&&a.length&&(e.filters=n.filters),(u=n.segments)!=null&&u.length&&(e.segments=n.segments),(f=n.orderBy)!=null&&f.length&&(e.order_by=n.orderBy),n.limit!=null&&(e.limit=n.limit),n.offset!=null&&(e.offset=n.offset),n.ungrouped&&(e.ungrouped=!0),n.parameters&&(e.parameters=n.parameters),n.usePreaggregations!=null&&(e.use_preaggregations=n.usePreaggregations),n.timezone&&n.timezone!=="UTC"&&(e.timezone=n.timezone),e}class nS{constructor(e={}){Mn(this,"baseUrl");Mn(this,"token");Mn(this,"sessionToken");Mn(this,"transport");Mn(this,"usePreaggregations");Mn(this,"gate");Mn(this,"onUnauthorized");this.baseUrl=(e.baseUrl??"").replace(/\/$/,""),this.token=e.token,this.transport=e.transport??"json",this.usePreaggregations=e.usePreaggregations??!0,this.gate=new eS(e.maxConcurrency??6),this.onUnauthorized=e.onUnauthorized}body(e){return tS({usePreaggregations:this.usePreaggregations,...e})}headers(e){const t={...e};return this.sessionToken?t.Authorization=`Sidemantic-Session ${this.sessionToken}`:this.token&&(t.Authorization=`Bearer ${this.token}`),t}isCrossOrigin(){return!this.baseUrl||typeof globalThis.location>"u"?!1:new URL(this.baseUrl,globalThis.location.href).origin!==globalThis.location.origin}url(e){return`${this.baseUrl}${e}`}async getJson(e){const t=await fetch(this.url(e),{headers:this.headers(),credentials:"include"});if(!t.ok)throw new Error(await this.errorText(t,e));return await t.json()}async errorText(e,t){var a;e.status===401&&((a=this.onUnauthorized)==null||a.call(this));let i="";try{const u=await e.json();i=u.error??u.detail??""}catch{}return`${t} failed (${e.status})${i?`: ${i}`:""}`}async health(){try{return(await fetch(this.url("/health"),{headers:this.headers(),credentials:"include"})).ok}catch{return!1}}async getCatalog(){try{const t=await fetch(this.url("/describe"),{headers:this.headers(),credentials:"include"});if(t.ok){const i=wb(await t.json());try{return _b(i,await this.getJson("/graph"))}catch{return i}}}catch{}const e=await this.getJson("/graph");return Sb(e)}async getDashboard(){try{const e=await fetch(this.url("/dashboard"),{headers:this.headers()});if(e.status===404)return null;if(!e.ok)throw new Error(await this.errorText(e,"/dashboard"));if(!(e.headers.get("content-type")??"").includes("application/json"))return null;const t=await e.json();return typeof t.title=="string"&&Array.isArray(t.tabs)?Z1(t):null}catch{return null}}async compile(e){const t=await fetch(this.url("/compile"),{method:"POST",headers:this.headers({"Content-Type":"application/json"}),credentials:"include",body:JSON.stringify(this.body(e))});if(!t.ok)throw new Error(await this.errorText(t,"/compile"));return(await t.json()).sql}async runQuery(e){return this.gate.run(()=>this.transport==="arrow"?this.runQueryArrow(e):this.runQueryJson(e))}async runQueryJson(e){const t=await fetch(this.url("/query"),{method:"POST",headers:this.headers({"Content-Type":"application/json"}),credentials:"include",body:JSON.stringify(this.body(e))});if(!t.ok)throw new Error(await this.errorText(t,"/query"));const i=await t.json(),a=i.rows??[];return{columns:a.length?Object.keys(a[0]):[],rows:a,rowCount:i.row_count??a.length,sql:i.sql??""}}async runQueryArrow(e){const t=await fetch(this.url("/query?format=arrow"),{method:"POST",headers:this.headers({"Content-Type":"application/json",Accept:X1}),credentials:"include",body:JSON.stringify(this.body(e))});if(!t.ok)throw new Error(await this.errorText(t,"/query"));const i=new Uint8Array(await t.arrayBuffer()),{columns:a,rows:u}=q1(i),f=t.headers.get("X-Sidemantic-Sql")??"";return{columns:a,rows:u,rowCount:u.length,sql:f}}async createBrowserSession(e){var a;const t=this.isCrossOrigin(),i=await fetch(this.url("/auth/session"),{method:"POST",headers:{Authorization:`Bearer ${e}`,...t?{"X-Sidemantic-Session-Mode":"header"}:{}},credentials:"include"});if(i.status===404||i.ok&&!((a=i.headers.get("content-type"))!=null&&a.includes("application/json"))){this.token=e;return}if(!i.ok)throw new Error(await this.errorText(i,"/auth/session"));if(t){const u=await i.json();if(!u.session_token)throw new Error("/auth/session did not return a cross-origin session token");this.sessionToken=u.session_token}this.token=void 0}}function kv({brand:n,toolbar:e,filters:t,rail:i,children:a,drawer:u,showRail:f=!0,openRailRequest:h}){const[m,g]=M.useState(()=>typeof window<"u"&&window.matchMedia("(max-width: 767px)").matches),[v,x]=M.useState(()=>typeof window>"u"||!window.matchMedia("(max-width: 767px)").matches),b=M.useId(),w=M.useRef(null),j=M.useRef(null),C=f&&v;return M.useEffect(()=>{const O=window.matchMedia("(max-width: 767px)"),H=()=>{g(O.matches),x(!O.matches)};return O.addEventListener("change",H),()=>O.removeEventListener("change",H)},[]),M.useEffect(()=>{h&&!m&&x(!0)},[h,m]),M.useEffect(()=>{if(!m||!v)return;const O=j.current,H=document.body.style.overflow;document.body.style.overflow="hidden",window.requestAnimationFrame(()=>{var R,T;return(T=(R=w.current)==null?void 0:R.querySelector("button"))==null?void 0:T.focus()});function L(R){var U;if(R.key==="Escape"){R.preventDefault(),x(!1);return}if(R.key!=="Tab")return;const T=(U=w.current)==null?void 0:U.querySelectorAll('button:not(:disabled), select:not(:disabled), input:not(:disabled), [href], [tabindex]:not([tabindex="-1"])');if(!(T!=null&&T.length))return;const E=T[0],I=T[T.length-1];R.shiftKey&&document.activeElement===E?(R.preventDefault(),I.focus()):!R.shiftKey&&document.activeElement===I&&(R.preventDefault(),E.focus())}return document.addEventListener("keydown",L,!0),()=>{document.body.style.overflow=H,document.removeEventListener("keydown",L,!0),O==null||O.focus()}},[m,v]),c.jsxs("div",{className:"flex h-[100dvh] min-w-0 flex-col overflow-hidden bg-bg text-ink",children:[c.jsxs("header",{className:"relative z-40 flex shrink-0 flex-col gap-2 border-b border-line bg-surface px-3 py-2 md:flex-row md:items-center md:justify-between md:gap-3",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[f?c.jsx("button",{ref:j,type:"button","aria-label":m?"Open catalog":v?"Collapse sidebar":"Expand sidebar","aria-expanded":v,"aria-controls":b,onClick:()=>x(O=>!O),className:"grid size-7 shrink-0 place-items-center border border-line text-faint hover:border-faint hover:text-ink",children:v?"‹":"›"}):null,n]}),c.jsx("div",{className:"flex w-full min-w-0 flex-wrap items-center gap-2 overflow-visible md:w-auto md:shrink-0 md:flex-nowrap",children:e})]}),t?c.jsx("div",{className:"flex min-h-9 shrink-0 flex-wrap items-center gap-2 overflow-x-auto border-b border-line bg-surface px-3 py-2 md:h-9 md:flex-nowrap md:py-0",children:t}):null,c.jsxs("div",{className:`grid min-h-0 min-w-0 flex-1 grid-cols-1 ${C?"md:grid-cols-[260px_minmax(0,1fr)]":"md:grid-cols-1"}`,children:[f&&C?c.jsxs(c.Fragment,{children:[m?c.jsx("button",{type:"button","aria-label":"Close catalog",className:"fixed inset-0 z-40 bg-black/35 backdrop-blur-[2px]",onClick:()=>x(!1)}):null,c.jsxs("aside",{id:b,ref:w,role:m?"dialog":void 0,"aria-modal":m?"true":void 0,"aria-label":m?"Data catalog":void 0,onClick:O=>{m&&O.target.closest("[data-catalog-metric], [data-catalog-dimension]")&&x(!1)},onChange:()=>m&&x(!1),className:"fixed inset-y-0 left-0 z-50 min-h-0 w-[min(88vw,320px)] overflow-y-auto bg-surface shadow-[var(--shadow)] md:static md:z-auto md:w-auto md:border-r md:border-line md:shadow-none",children:[m?c.jsxs("div",{"data-testid":"catalog-drawer-header",className:"sticky top-0 z-10 flex items-center justify-between border-b border-line bg-surface px-4 py-3",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-sm font-semibold text-ink",children:"Catalog"}),c.jsx("p",{className:"text-xs text-muted",children:"Choose a model and fields"})]}),c.jsx("button",{type:"button","aria-label":"Close catalog",onClick:()=>x(!1),className:"grid size-10 place-items-center rounded-full bg-surface-soft text-muted hover:bg-line hover:text-ink",children:c.jsx("span",{"aria-hidden":"true",className:"text-xl leading-none",children:"×"})})]}):null,i]})]}):null,c.jsxs("main",{className:"relative min-h-0 min-w-0 overflow-hidden",children:[c.jsx("div",{className:`h-full overflow-y-auto ${u?"pb-8":""}`,children:a}),u]})]})]})}function rS({dashboardTitle:n,modelLabel:e,onHome:t}){const i=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-sm font-semibold text-ink",children:n??"Sidemantic"}),n===void 0&&e?c.jsx("span",{className:"truncate text-2xs text-faint",children:e}):null]});return n!==void 0?c.jsx("span",{className:"flex min-w-0 items-baseline gap-2",children:i}):c.jsx("button",{type:"button",onClick:t,"aria-label":"Home",className:"flex min-w-0 items-baseline gap-2",children:i})}const sS=new Set(["second","minute","hour","day","week","month","quarter","year"]);function il(n){return n===void 0?[]:Array.isArray(n)?n:[n]}function ol(n,e){return n.models.flatMap(t=>t.dimensions).find(t=>e===t.ref||e.startsWith(`${t.ref}__`))}function iS(n,e){const t=n.split("__").at(-1);return t&&sS.has(t)?t:e}function oS(n){var a;const e=(a=n.defaults)==null?void 0:a.query;if(!e||typeof e!="object")return;const t=e,i=t.use_preaggregations??t.usePreaggregations;return typeof i=="boolean"?i:void 0}function aS(n,e){var u;const t=(u=n.defaults)==null?void 0:u.query,i=t&&typeof t=="object"?t:{},a=e.query.interaction_preaggregations??e.query.interactionPreaggregations??e.interaction_preaggregations??e.interactionPreaggregations??i.interaction_preaggregations??i.interactionPreaggregations;return typeof a=="boolean"?a:void 0}function Cs(n,e,t){var T,E,I,U,G,V,Q;if(!(e!=null&&e.tabs.length))return null;const i=e.tabs.find(z=>z.id===t)??e.tabs[0],a=i.charts[0];if(!a)return null;const u=il(a.query.dimensions),f=il(a.query.metrics),h=f.map(z=>{var ee;return(ee=n.graphMetrics.find(X=>X.ref===z))==null?void 0:ee.ownerModel}).find(z=>!!z),m=((T=f.find(z=>z.includes(".")))==null?void 0:T.split(".")[0])??h??((E=u.find(z=>z.includes(".")))==null?void 0:E.split(".")[0]),g=n.models.find(z=>z.name===m)??n.models[0];if(!g)return null;const v=[...n.models.flatMap(z=>z.metrics),...ji(n,g.name)],x=f.map(z=>v.find(ee=>ee.ref===z)).filter(z=>!!z),b=u.map(z=>ol(n,z)).filter((z,ee,X)=>!!z&&X.findIndex(ie=>(ie==null?void 0:ie.ref)===(z==null?void 0:z.ref))===ee),w=(I=a.encoding)==null?void 0:I.y,C=(Array.isArray(w)?w:w?[w]:[]).find(z=>x.some(ee=>ee.ref===z))??((U=x[0])==null?void 0:U.ref)??((G=g.metrics[0])==null?void 0:G.ref)??"",O=(V=a.encoding)==null?void 0:V.x,H=(O&&((Q=ol(n,O))==null?void 0:Q.type)==="time"?O:void 0)??u.find(z=>{var ee;return((ee=ol(n,z))==null?void 0:ee.type)==="time"}),L=g.defaultGrain??"month",R=H?ol(n,H):g.timeDimension;return{id:i.id,label:i.label??i.id,title:a.title??e.title,model:g,metrics:x.length?x:g.metrics,dimensions:b.length?b:g.dimensions,timeDimension:R,selectedMetric:C,grain:H?iS(H,L):L,filters:il(a.query.filters),segments:il(a.query.segments),usePreaggregations:aS(e,a)??a.query.use_preaggregations??a.query.usePreaggregations??oS(e)}}const Fd=["second","minute","hour","day","week","month","quarter","year"];function lS(n,e){if(n!=null&&n.length){const i=new Set(n.map(u=>u.toLowerCase())),a=Fd.filter(u=>i.has(u));if(a.length)return a}const t=["day","week","month","quarter","year"];return e&&!t.includes(e)?Fd.filter(i=>i===e||t.includes(i)):t}function Ni(n){return n.toISOString().slice(0,10)}function nf(n){return n.slice(0,10)}function Oi(n){const e=n.trim();return/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:/[zZ]|[+-]\d{2}:?\d{2}$/.test(e)?e:`${e.replace(" ","T")}Z`}function Fs(n){return new Date(`${nf(n)}T00:00:00Z`)}function Uo(n,e){const t=Fs(n);return t.setUTCDate(t.getUTCDate()+e),Ni(t)}function uS(n){return Math.round((Fs(n.to).getTime()-Fs(n.from).getTime())/864e5)+1}function cS(n){if(n.from.includes("T")||n.to.includes("T")){const a=Date.parse(Oi(n.from)),f=Date.parse(Oi(n.to))-a;return{from:new Date(a-f).toISOString().slice(0,19),to:new Date(a).toISOString().slice(0,19)}}const e=uS(n),t=Uo(n.from,-1);return{from:Uo(t,-(e-1)),to:t}}function Rm(n){if(n.includes("T")){const f=new Date(Oi(n)),h=f.getUTCFullYear()-1,m=f.getUTCMonth(),g=new Date(Date.UTC(h,m+1,0)).getUTCDate();return new Date(Date.UTC(h,m,Math.min(f.getUTCDate(),g),f.getUTCHours(),f.getUTCMinutes(),f.getUTCSeconds())).toISOString().slice(0,19)}const e=Fs(n),t=e.getUTCFullYear()-1,i=e.getUTCMonth(),a=e.getUTCDate(),u=new Date(Date.UTC(t,i+1,0)).getUTCDate();return Ni(new Date(Date.UTC(t,i,Math.min(a,u))))}function dS(n){return{from:Rm(n.from),to:Rm(n.to)}}function fS(n,e){const t=n.trim(),i=t.slice(0,10);if(e!=="second"&&e!=="minute"&&e!=="hour")return i||n;const a=t.slice(10).match(/(\d{2}):(\d{2})(?::(\d{2}))?/);if(!a)return i||n;const u=e==="second"&&a[3]?`${a[1]}:${a[2]}:${a[3]}`:`${a[1]}:${a[2]}`;return`${i} ${u}`}const hS=[{key:"7d",label:"Last 7 days",days:7},{key:"28d",label:"Last 28 days",days:28},{key:"90d",label:"Last 90 days",days:90},{key:"180d",label:"Last 180 days",days:180},{key:"365d",label:"Last 12 months",days:365}];function pS(n,e=new Date){const t=Ni(e);return{from:Uo(t,-(n-1)),to:t}}function mS(n,e){return e.from.includes("T")||e.to.includes("T")?[`${n} >= cast('${e.from}' as timestamp)`,`${n} < cast('${e.to}' as timestamp)`]:[`${n} >= cast('${e.from}' as date)`,`${n} < cast('${Uo(e.to,1)}' as date)`]}function Lm(n,e,t){if(t==="second"||t==="minute"||t==="hour"){const f=t==="second"?1e3:t==="minute"?6e4:36e5;return Math.round((Date.parse(Oi(e))-Date.parse(Oi(n)))/f)}const i=Fs(n),a=Fs(e),u=(a.getUTCFullYear()-i.getUTCFullYear())*12+(a.getUTCMonth()-i.getUTCMonth());switch(t){case"week":return Math.round((a.getTime()-i.getTime())/(7*864e5));case"month":return u;case"quarter":return Math.round(u/3);case"year":return a.getUTCFullYear()-i.getUTCFullYear();default:return Math.round((a.getTime()-i.getTime())/864e5)}}function ld(n,e){return new Date(Date.parse(Oi(n))+e).toISOString().slice(0,19)}function yS(n,e){const t=nf(n),i=Fs(t);switch(e){case"second":return ld(n,1e3);case"minute":return ld(n,6e4);case"hour":return ld(n,36e5);case"day":return t;case"week":return Uo(n,6);case"month":return Ni(new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth()+1,0)));case"quarter":{const a=Math.floor(i.getUTCMonth()/3)*3+3;return Ni(new Date(Date.UTC(i.getUTCFullYear(),a,0)))}case"year":return Ni(new Date(Date.UTC(i.getUTCFullYear(),12,0)));default:return n}}function rf(n){return n.mode==="contains"?!n.pattern:n.values.length===0}function sf(n){return Object.fromEntries(n.map(e=>[e.ref,e.type]))}function ou(n){return sf(n.models.flatMap(e=>e.dimensions))}function Um(n,e){if((e==="numeric"||e==="number")&&n.trim()!==""&&Number.isFinite(Number(n)))return n;if(e==="boolean"){const t=n.toLowerCase();if(t==="true"||t==="false")return t}return Tn(n)}function Iv(n){return n.replaceAll("\\","\\\\").replaceAll("%","\\%").replaceAll("_","\\_")}function gS(n,e,t){const i=e.mode==="exclude",a=e.values.includes(er),u=e.values.filter(h=>h!==er);let f=null;if(u.length===1)f=`${n} ${i?"!=":"="} ${Um(u[0],t)}`;else if(u.length>1){const h=u.map(m=>Um(m,t)).join(", ");f=`${n} ${i?"NOT IN":"IN"} (${h})`}if(!i){const h=[];return f&&h.push(f),a&&h.push(`${n} IS NULL`),h.length===0?null:h.length===1?h[0]:`(${h.join(" OR ")})`}if(a){const h=[];return f&&h.push(f),h.push(`${n} IS NOT NULL`),h.length===1?h[0]:`(${h.join(" AND ")})`}return f?`(${f} OR ${n} IS NULL)`:null}function Mv(n,e={}){var i;const t=[];for(const[a,u]of Object.entries(n)){if(a===e.excludeDim||rf(u))continue;const f=(i=e.types)==null?void 0:i[a];if(u.mode==="contains"){const m=Tn(`%${Iv(u.pattern??"")}%`);t.push(`CAST(${a} AS VARCHAR) ILIKE ${m} ESCAPE '\\'`);continue}const h=gS(a,u,f);h&&t.push(h)}return t}function Os(n,e={}){const t=Mv(n,{types:e.types,excludeDim:e.excludeDim});return e.timeRef&&e.range&&t.push(...mS(e.timeRef,e.range)),t}function $m(n,e,t,i){return{metrics:n,filters:e,...t!=null&&t.length?{segments:t}:{},...i!=null?{usePreaggregations:i}:{}}}const vS={second:2e3,minute:2e3,hour:9600,day:4e3,week:800,month:240,quarter:120,year:60};function Pm(n,e,t,i,a,u,f=!1){const h=`${e}__${t}`,m=t==="second"||t==="minute",g=m&&!f;return{metrics:n,dimensions:[h],filters:i,...a!=null&&a.length?{segments:a}:{},...u!=null?{usePreaggregations:u}:{},orderBy:[`${h} ${g?"DESC":"ASC"}`],...!m||g?{limit:vS[t]??2e3}:{}}}function zm(n,e,t,i=6,a,u){return{metrics:[n],dimensions:[e],filters:t,...a!=null&&a.length?{segments:a}:{},...u!=null?{usePreaggregations:u}:{},orderBy:[`${n} DESC`],limit:i}}function xS(n,e,t=50,i,a){return{dimensions:[n],filters:e,...i!=null&&i.length?{segments:i}:{},...a!=null?{usePreaggregations:a}:{},orderBy:[`${n} ASC`],limit:t}}function bS(n,e,t,i,a=500){return{metrics:n,dimensions:e,filters:t,orderBy:i,limit:a}}function wS(n,e,t=50,i,a){return{dimensions:n.dimensions,metrics:n.metrics,filters:e,...i!=null&&i.length?{segments:i}:{},...a!=null?{usePreaggregations:a}:{},ungrouped:!0,limit:t}}function SS(n,e){const t=n??[];return t.includes(e)?t.filter(i=>i!==e):[...t,e]}function al(n,e,t){const i={...n};return rf(t)?delete i[e]:i[e]=t,i}function _S(n,e){switch(e.type){case"hydrate":return e.state;case"setView":return{...n,view:e.view};case"setDashboardTab":return{...n,view:"explore",dashboardTab:e.tab,model:e.model,selectedMetric:e.metric,grain:e.grain,filters:{},dateRange:void 0,pivotDims:[],pivotMetrics:[]};case"setModel":return{...n,model:e.model,selectedMetric:e.metric,grain:e.grain,filters:{},pivotDims:[],pivotMetrics:[]};case"setMetric":return{...n,selectedMetric:e.metric};case"toggleFilter":{const t=n.filters[e.dim],i=e.mode??(t&&t.mode!=="contains"?t.mode:"include"),a=t&&t.mode===i?t.values:[],u=SS(a,e.value);return{...n,filters:al(n.filters,e.dim,{mode:i,values:u})}}case"setFilterMode":{const t=n.filters[e.dim],i={mode:e.mode,values:(t==null?void 0:t.values)??[],pattern:t==null?void 0:t.pattern};return{...n,filters:al(n.filters,e.dim,i)}}case"setFilterPattern":{const t=n.filters[e.dim],i={mode:"contains",values:(t==null?void 0:t.values)??[],pattern:e.pattern};return{...n,filters:al(n.filters,e.dim,i)}}case"removeFilterValue":{const t=n.filters[e.dim];if(!t)return n;const i=t.values.filter(a=>a!==e.value);return{...n,filters:al(n.filters,e.dim,{...t,values:i})}}case"removeFilterDim":{const t={...n.filters};return delete t[e.dim],{...n,filters:t}}case"clearFilters":return{...n,filters:{}};case"setGrain":return{...n,grain:e.grain};case"setTimezone":return{...n,timezone:e.timezone};case"setDateRange":return{...n,dateRange:e.range};case"setContextColumn":return{...n,contextColumn:e.column};case"setComparison":return{...n,comparison:e.comparison,comparisonRange:e.comparison==="custom"?e.range:void 0};case"setPivotDims":return{...n,pivotDims:e.dims};case"setPivotMetrics":return{...n,pivotMetrics:e.metrics};case"reset":return{...e.initial,view:n.view};default:return n}}function NS(n){return n.models.find(e=>e.timeDimension)??n.models[0]}function Dv(n,e){var t,i;return((t=n==null?void 0:n.metrics[0])==null?void 0:t.ref)??(n?(i=ji(e,n.name)[0])==null?void 0:i.ref:void 0)??""}function Cv(n,e,t){const i=Cs(n,e,t),a=(i==null?void 0:i.model)??NS(n),u=(i==null?void 0:i.selectedMetric)??Dv(a,n);return{view:i?"explore":"home",dashboardTab:i==null?void 0:i.id,model:(a==null?void 0:a.name)??"",selectedMetric:u,filters:{},grain:(i==null?void 0:i.grain)??(a==null?void 0:a.defaultGrain)??"month",timezone:"UTC",dateRange:void 0,contextColumn:"none",comparison:"previous",comparisonRange:void 0,pivotDims:[],pivotMetrics:[]}}function jS(n,e,t){const i=new URLSearchParams(t),a=i.get("metric"),u=i.get("grain"),f=a===n.selectedMetric&&e.metrics.some(m=>m.ref===a),h=u===n.grain;return{...n,view:"explore",dashboardTab:e.id,model:e.model.name,selectedMetric:f?n.selectedMetric:e.selectedMetric,grain:h?n.grain:e.grain}}const kS=["home","explore","pivot"],IS=new Set(Fd),MS=new Set(["none","pctTotal","delta","deltaPct"]),DS=new Set(["off","previous","year","custom"]),CS="none",FS="previous",OS="UTC";function TS(n){return n!=null&&/^[A-Za-z][A-Za-z0-9/_+-]{0,63}$/.test(n)}function ud(n){if(n)try{return JSON.parse(n)}catch{return}}function Zl(n){return Array.isArray(n)&&n.every(e=>typeof e=="string")}function ll(n){return n!=null&&/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2})?$/.test(n)&&!Number.isNaN(Date.parse(n))}const AS=new Set(["include","exclude","contains"]);function BS(n){if(Zl(n))return{mode:"include",values:n};if(typeof n!="object"||n===null||Array.isArray(n))return null;const e=n;if(!AS.has(e.mode))return null;const t=e.mode,i=Zl(e.values)?e.values:[],a=typeof e.pattern=="string"?e.pattern:void 0,u={mode:t,values:i,pattern:a};return rf(u)?null:u}function ES(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;const e={};for(const[t,i]of Object.entries(n)){const a=BS(i);a&&(e[t]=a)}return e}function RS(n){const e={};for(const[t,i]of Object.entries(n))e[t]=i.mode==="include"?i.values:i;return e}function LS(n){const e=new URLSearchParams;return e.set("view",n.view),n.dashboardTab&&e.set("tab",n.dashboardTab),n.model&&e.set("model",n.model),n.selectedMetric&&e.set("metric",n.selectedMetric),n.grain&&e.set("grain",n.grain),n.timezone&&n.timezone!==OS&&e.set("tz",n.timezone),n.dateRange&&(e.set("from",n.dateRange.from),e.set("to",n.dateRange.to)),n.contextColumn!==CS&&e.set("ctx",n.contextColumn),n.comparison!==FS&&e.set("cmp",n.comparison),n.comparison==="custom"&&n.comparisonRange&&(e.set("cfrom",n.comparisonRange.from),e.set("cto",n.comparisonRange.to)),Object.keys(n.filters).length&&e.set("filters",JSON.stringify(RS(n.filters))),n.pivotDims.length&&e.set("pdims",JSON.stringify(n.pivotDims)),n.pivotMetrics.length&&e.set("pmetrics",JSON.stringify(n.pivotMetrics)),e.toString()}function US(n,e){const t=new URLSearchParams(n),i={...e},a=t.get("view");a&&kS.includes(a)&&(i.view=a);const u=t.get("tab");u&&(i.dashboardTab=u);const f=t.get("model");f&&(i.model=f);const h=t.get("metric");h&&(i.selectedMetric=h);const m=t.get("grain");m&&IS.has(m)&&(i.grain=m);const g=t.get("tz");TS(g)&&(i.timezone=g);const v=t.get("from"),x=t.get("to");ll(v)&&ll(x)&&Date.parse(v)<=Date.parse(x)&&(i.dateRange={from:v,to:x});const b=t.get("ctx");b&&MS.has(b)&&(i.contextColumn=b);const w=t.get("cmp");w&&DS.has(w)&&(i.comparison=w);const j=t.get("cfrom"),C=t.get("cto");i.comparison==="custom"&&ll(j)&&ll(C)&&Date.parse(j)<=Date.parse(C)&&(i.comparisonRange={from:j,to:C});const O=ES(ud(t.get("filters")));O&&(i.filters=O);const H=ud(t.get("pdims"));Zl(H)&&(i.pivotDims=H);const L=ud(t.get("pmetrics"));return Zl(L)&&(i.pivotMetrics=L),i}const Fv=M.createContext(null);function Vm(n){const e=LS(n);return e?`?${e}`:""}function Wm(n,e,t,i){const a=US(n,i),u=Cs(e,t,a.dashboardTab);return u?jS(a,u,n):a}const Hm=n=>n.startsWith("?")?n.slice(1):n;function $S({catalog:n,backend:e,dashboard:t,initialSearch:i,onSearchChange:a,children:u}){const f=M.useMemo(()=>Cv(n,t),[n,t]),[h,m]=M.useReducer(_S,void 0,()=>{const b=i??(typeof window>"u"?"":window.location.search);return Wm(b,n,t,f)}),g=M.useRef(i);M.useEffect(()=>{i===void 0||i===g.current||(g.current=i,Hm(i)!==Hm(Vm(h))&&m({type:"hydrate",state:Wm(i,n,t,f)}))},[i,h,n,t,f]);const v=M.useRef(a);v.current=a,M.useEffect(()=>{const b=Vm(h),w=v.current;if(w){w(b);return}typeof window>"u"||window.history.replaceState(null,"",`${window.location.pathname}${b}`)},[h]);const x=M.useMemo(()=>({state:h,dispatch:m,catalog:n,backend:e,initial:f,dashboard:t}),[h,n,e,f,t]);return c.jsx(Fv.Provider,{value:x,children:u})}function ls(){const n=M.useContext(Fv);if(!n)throw new Error("useExplorer must be used within ExplorerProvider");return n}const Is={active:0,listeners:new Set};function Ov(){for(const n of Is.listeners)n()}function PS(){Is.active+=1,Ov()}function zS(){Is.active=Math.max(0,Is.active-1),Ov()}function Tv(){return M.useSyncExternalStore(n=>(Is.listeners.add(n),()=>Is.listeners.delete(n)),()=>Is.active>0,()=>!1)}const VS=80;function Zn(n,e){const[t,i]=M.useState({loading:!1}),a=M.useRef(0),u=e?JSON.stringify(e):null;return M.useEffect(()=>{if(!e){i({loading:!1});return}const f=++a.current;i(m=>({result:m.result,loading:!0}));const h=setTimeout(()=>{PS(),n.runQuery(e).then(m=>{f===a.current&&i({result:m,loading:!1})}).catch(m=>{f===a.current&&i({loading:!1,error:m instanceof Error?m.message:String(m)})}).finally(()=>zS())},VS);return()=>clearTimeout(h)},[u,n]),t}const WS=[{mode:"include",label:"Include"},{mode:"exclude",label:"Exclude"},{mode:"contains",label:"Contains"}],HS=50,Gm=200;function Ym(n,e){const[t,i]=M.useState(n);return M.useEffect(()=>{const a=setTimeout(()=>i(n),e);return()=>clearTimeout(a)},[n,e]),t}function Av({dim:n,model:e,onClose:t}){var W,_;const{state:i,dispatch:a,backend:u,catalog:f,dashboard:h}=ls(),m=M.useMemo(()=>Cs(f,h,i.dashboardTab),[f,h,i.dashboardTab]),g=i.filters[n.ref],[v,x]=M.useState((g==null?void 0:g.mode)??"include"),b=M.useMemo(()=>new Set((g==null?void 0:g.mode)!=="contains"?(g==null?void 0:g.values)??[]:[]),[g]),w=M.useRef(null),j=M.useRef(null),C=M.useId(),[O,H]=M.useState(""),L=Ym(O,Gm),R=(g==null?void 0:g.mode)==="contains"?g.pattern??"":"",[T,E]=M.useState(R),I=Ym(T,Gm);M.useEffect(()=>{var te;const F=document.activeElement;return(te=j.current)==null||te.focus(),()=>{var pe;return(pe=F==null?void 0:F.focus)==null?void 0:pe.call(F)}},[]),M.useEffect(()=>{function F(pe){pe.key==="Escape"&&(pe.stopPropagation(),t())}function te(pe){w.current&&!w.current.contains(pe.target)&&t()}return document.addEventListener("keydown",F,!0),document.addEventListener("mousedown",te,!0),()=>{document.removeEventListener("keydown",F,!0),document.removeEventListener("mousedown",te,!0)}},[t]),M.useEffect(()=>{v==="contains"&&I!==R&&a({type:"setFilterPattern",dim:n.ref,pattern:I})},[I,v,n.ref,a]);const U=((W=m==null?void 0:m.timeDimension)==null?void 0:W.ref)??((_=e.timeDimension)==null?void 0:_.ref),G=M.useMemo(()=>ou(f),[f]),V=M.useMemo(()=>{const F=[...(m==null?void 0:m.filters)??[],...Os(i.filters,{timeRef:U,range:i.dateRange,excludeDim:n.ref,types:G})];if(L.trim()){const te=Tn(`%${Iv(L.trim())}%`);F.push(`CAST(${n.ref} AS VARCHAR) ILIKE ${te} ESCAPE '\\'`)}return F},[m,i.filters,U,i.dateRange,n.ref,L,G]),Q=v!=="contains",{result:z,loading:ee,error:X}=Zn(u,Q?xS(n.ref,V,HS,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations):null),ie=Sr(n.ref),ae=M.useMemo(()=>z?z.rows.map(F=>{const te=F[ie];return te==null?er:String(te)}):[],[z,ie]),re=!!z&&z.rows.length>0&&!z.columns.includes(ie),se=Q&&(ee||re);function A(F){x(F),g&&a({type:"setFilterMode",dim:n.ref,mode:F}),F==="contains"&&E(R)}function Y(F){var fe;if(F.key!=="Tab")return;const te=(fe=w.current)==null?void 0:fe.querySelectorAll('button, input, [href], select, textarea, [tabindex]:not([tabindex="-1"])');if(!te||te.length===0)return;const pe=te[0],ne=te[te.length-1];F.shiftKey&&document.activeElement===pe?(F.preventDefault(),ne.focus()):!F.shiftKey&&document.activeElement===ne&&(F.preventDefault(),pe.focus())}return c.jsxs("div",{ref:w,role:"dialog","aria-modal":"true","aria-labelledby":C,onKeyDown:Y,className:"absolute left-0 z-50 mt-1 w-64 border border-line bg-surface p-2 text-2xs shadow-lg",children:[c.jsxs("div",{id:C,className:"mb-2 flex items-baseline justify-between gap-2",children:[c.jsx("span",{className:"truncate font-semibold text-ink",children:n.label}),c.jsx("button",{type:"button","aria-label":"Close filter editor",onClick:t,className:"grid size-4 place-items-center rounded-full bg-surface-soft text-faint hover:bg-line hover:text-ink",children:"×"})]}),c.jsx("div",{role:"group","aria-label":"Filter mode",className:"mb-2 grid grid-cols-3 gap-px border border-line bg-line",children:WS.map(({mode:F,label:te})=>c.jsx("button",{type:"button","aria-pressed":v===F,onClick:()=>A(F),className:`px-1.5 py-1 text-center ${v===F?"bg-accent-soft font-medium text-accent":"bg-surface text-muted hover:bg-surface-soft"}`,children:te},F))}),v==="contains"?c.jsx("input",{ref:j,type:"text","aria-label":`${n.label} contains`,placeholder:"Substring…",value:T,onChange:F=>E(F.target.value),className:"w-full border border-line bg-surface px-1.5 py-1 text-2xs text-ink placeholder:text-faint"}):c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:j,type:"text","aria-label":`Search ${n.label} values`,placeholder:"Search values…",value:O,onChange:F=>H(F.target.value),className:"w-full border border-line bg-surface px-1.5 py-1 text-2xs text-ink placeholder:text-faint"}),c.jsx("div",{className:"mt-2 max-h-56 overflow-y-auto",role:"group","aria-label":`${n.label} values`,children:X?c.jsx("p",{className:"px-1 py-2 text-danger",children:X}):se?c.jsx("div",{className:"space-y-1.5 p-1",children:[0,1,2,3,4].map(F=>c.jsx("div",{className:"skeleton h-4 w-full"},F))}):ae.length===0?c.jsx("p",{className:"px-1 py-2 text-faint",children:"No values"}):ae.map(F=>{const te=b.has(F);return c.jsxs("label",{className:"flex cursor-pointer items-center gap-2 px-1 py-1 hover:bg-surface-soft",children:[c.jsx("input",{type:"checkbox",checked:te,onChange:()=>a({type:"toggleFilter",dim:n.ref,value:F,mode:v}),className:"size-3 accent-[var(--accent)]"}),c.jsx("span",{className:"min-w-0 truncate text-ink",children:rs(F)})]},F)})})]}),c.jsxs("div",{className:"mt-2 flex items-center justify-between border-t border-line pt-2",children:[c.jsx("button",{type:"button",onClick:()=>a({type:"removeFilterDim",dim:n.ref}),className:"text-muted underline-offset-2 hover:text-ink hover:underline",children:"Clear"}),c.jsx("button",{type:"button",onClick:t,className:"border border-line px-2 py-1 text-muted hover:bg-surface-soft",children:"Done"})]})]})}function GS({model:n}){const e=n.dimensions.filter(m=>m.type!=="time"),[t,i]=M.useState(!1),[a,u]=M.useState(null),f=M.useRef(null);M.useEffect(()=>{if(!t)return;function m(v){v.key==="Escape"&&h()}function g(v){a||f.current&&!f.current.contains(v.target)&&h()}return document.addEventListener("keydown",m,!0),document.addEventListener("mousedown",g,!0),()=>{document.removeEventListener("keydown",m,!0),document.removeEventListener("mousedown",g,!0)}},[t,a]);function h(){i(!1),u(null)}return e.length===0?null:c.jsxs("span",{ref:f,className:"relative inline-flex",children:[c.jsx("button",{type:"button","aria-haspopup":"dialog","aria-expanded":t,onClick:()=>t?h():i(!0),className:"inline-flex h-7 shrink-0 items-center rounded-full border border-dashed border-line px-3 text-xs text-muted hover:border-faint hover:text-ink",children:"+ Filter"}),t&&!a?c.jsx("div",{role:"menu","aria-label":"Add a filter for a dimension",className:"absolute left-0 z-50 mt-1 max-h-64 w-48 overflow-y-auto rounded-xl border border-line bg-surface p-1.5 text-2xs shadow-[var(--shadow)]",children:e.map(m=>c.jsx("button",{type:"button",role:"menuitem",onClick:()=>u(m),className:"block w-full truncate px-1.5 py-1 text-left text-muted hover:bg-surface-soft hover:text-ink",children:m.label},m.ref))}):null,t&&a?c.jsx(Av,{dim:a,model:n,onClose:h}):null]})}function cd(n,e){return n.includes(e)?n.filter(t=>t!==e):[...n,e]}function Qm({metric:n,selected:e,multiple:t,onSelect:i}){return c.jsxs("button",{type:"button","data-catalog-metric":n.ref,"data-selected":e||void 0,"aria-pressed":e,title:n.description,onClick:i,className:"flex w-full items-center justify-between gap-2 border-l-2 px-3 py-1 text-left text-xs hover:bg-surface-soft data-[selected=true]:border-l-accent data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent border-l-transparent text-muted",children:[c.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[t?c.jsx("span",{"aria-hidden":"true",className:"w-3 shrink-0 text-center text-accent",children:e?"✓":""}):null,c.jsx("span",{className:"truncate",children:n.label})]}),n.agg?c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:n.agg}):null]})}function YS({dimension:n,selected:e,onSelect:t}){return c.jsxs("button",{type:"button","data-catalog-dimension":n.ref,"data-selected":e||void 0,"aria-pressed":e,title:n.description,onClick:t,className:"flex w-full items-center justify-between gap-2 border-l-2 border-l-transparent px-3 py-1 text-left text-xs text-muted hover:bg-surface-soft data-[selected=true]:border-l-accent data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent",children:[c.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[c.jsx("span",{"aria-hidden":"true",className:"w-3 shrink-0 text-center",children:e?"✓":""}),c.jsx("span",{className:"truncate",children:n.label})]}),c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:n.type==="time"?"time":""})]})}function QS(){const{state:n,dispatch:e,catalog:t}=ls(),i=t.models.find(h=>h.name===n.model),a=ji(t,n.model),u=n.view==="pivot",f=n.pivotMetrics.length?n.pivotMetrics:n.selectedMetric?[n.selectedMetric]:[];return c.jsxs("nav",{"aria-label":"Semantic layer catalog",className:"flex flex-col gap-4 py-3 text-sm",children:[c.jsxs("section",{className:"px-3",children:[c.jsx("h2",{className:"mb-1 text-xs font-medium text-muted",children:"Model"}),c.jsx("select",{"aria-label":"Model",value:n.model,onChange:h=>{var v,x;const m=t.models.find(b=>b.name===h.target.value),g=((v=m==null?void 0:m.metrics[0])==null?void 0:v.ref)??((x=ji(t,h.target.value)[0])==null?void 0:x.ref)??"";e({type:"setModel",model:h.target.value,metric:g,grain:(m==null?void 0:m.defaultGrain)??"month"})},className:"w-full border border-line bg-surface px-2 py-1 text-xs text-ink",children:t.models.map(h=>c.jsx("option",{value:h.name,children:h.label},h.name))})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-1 px-3 text-xs font-medium text-muted",children:"Metrics"}),c.jsx("div",{children:((i==null?void 0:i.metrics)??[]).map(h=>c.jsx(Qm,{metric:h,selected:u?f.includes(h.ref):n.selectedMetric===h.ref,multiple:u,onSelect:()=>e(u?{type:"setPivotMetrics",metrics:cd(f,h.ref)}:{type:"setMetric",metric:h.ref})},h.ref))}),a.length?c.jsxs(c.Fragment,{children:[c.jsx("h3",{className:"mb-1 mt-3 px-3 text-xs font-medium text-muted",children:"Shared metrics"}),c.jsx("div",{children:a.map(h=>c.jsx(Qm,{metric:h,selected:u?f.includes(h.ref):n.selectedMetric===h.ref,multiple:u,onSelect:()=>e(u?{type:"setPivotMetrics",metrics:cd(f,h.ref)}:{type:"setMetric",metric:h.ref})},h.ref))})]}):null]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-1 px-3 text-xs font-medium text-muted",children:"Dimensions"}),u?c.jsx("div",{children:((i==null?void 0:i.dimensions)??[]).map(h=>c.jsx(YS,{dimension:h,selected:n.pivotDims.includes(h.ref),onSelect:()=>e({type:"setPivotDims",dims:cd(n.pivotDims,h.ref)})},h.ref))}):c.jsx("ul",{className:"px-3 text-xs text-muted",children:((i==null?void 0:i.dimensions)??[]).map(h=>c.jsxs("li",{className:"flex items-center justify-between gap-2 py-0.5",title:h.description,children:[c.jsx("span",{className:"truncate",children:h.label}),c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:h.type==="time"?"time":""})]},h.ref))})]})]})}class KS extends M.Component{constructor(){super(...arguments);Mn(this,"state",{})}static getDerivedStateFromError(t){return{error:t}}render(){return this.state.error?c.jsx("div",{className:"p-4",children:c.jsxs("div",{className:"border border-danger/40 bg-surface p-4",children:[c.jsx("p",{className:"text-sm font-semibold text-danger",children:"Something went wrong rendering this view."}),c.jsx("p",{className:"mt-1 break-words text-xs text-muted",children:this.state.error.message}),c.jsxs("div",{className:"mt-3 flex gap-2",children:[c.jsx("button",{type:"button",onClick:()=>this.setState({error:void 0}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Retry"}),c.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Reload"})]})]})}):this.props.children}}const JS=[{key:"off",label:"Off"},{key:"previous",label:"Previous period"},{key:"year",label:"Previous year"},{key:"custom",label:"Custom range"}];function Bv({range:n,disabled:e,onChange:t,comparison:i,comparisonRange:a,onComparisonChange:u}){const f=M.useRef(null),[h,m]=M.useState((n==null?void 0:n.from)??""),[g,v]=M.useState((n==null?void 0:n.to)??""),[x,b]=M.useState((a==null?void 0:a.from)??""),[w,j]=M.useState((a==null?void 0:a.to)??"");function C(){f.current&&(f.current.open=!1)}function O(T){t(T),C()}function H(T){T==="custom"?u("custom",x&&w?{from:x,to:w}:void 0):u(T)}const L=n?`${n.from} → ${n.to}`:"All time",R=!n;return c.jsxs("details",{ref:f,className:"relative text-xs",onToggle:T=>{e&&(T.currentTarget.open=!1)},children:[c.jsxs("summary",{"aria-disabled":e||void 0,tabIndex:e?-1:void 0,onClick:T=>e&&T.preventDefault(),onKeyDown:T=>{e&&(T.key==="Enter"||T.key===" ")&&T.preventDefault()},className:`flex h-7 cursor-pointer items-center gap-1.5 rounded-full border border-line bg-surface px-3 text-ink ${e?"cursor-not-allowed opacity-50":""}`,children:[c.jsx("span",{className:"text-faint",children:"Range"}),c.jsx("span",{className:"tnum",children:L}),c.jsx("span",{"aria-hidden":"true",className:"text-faint",children:"▾"})]}),c.jsxs("div",{className:"absolute right-0 z-50 mt-1 w-64 rounded-xl border border-line bg-surface p-1.5 shadow-[var(--shadow)]",children:[c.jsx("button",{type:"button",onClick:()=>O(void 0),className:"w-full rounded-lg px-2.5 py-1.5 text-left text-xs text-muted hover:bg-surface-soft hover:text-ink",children:"All time"}),c.jsx("div",{className:"grid grid-cols-2",children:hS.map(T=>c.jsx("button",{type:"button",onClick:()=>O(pS(T.days)),className:"rounded-lg px-2.5 py-1.5 text-left text-xs text-muted hover:bg-surface-soft hover:text-ink",children:T.label},T.key))}),c.jsxs("div",{className:"mt-2 px-1 pb-1",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("input",{type:"date","aria-label":"From date",value:h,onChange:T=>m(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"}),c.jsx("span",{className:"text-faint",children:"→"}),c.jsx("input",{type:"date","aria-label":"To date",value:g,onChange:T=>v(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"})]}),c.jsx("button",{type:"button",disabled:!h||!g,onClick:()=>O({from:h,to:g}),className:"mt-1.5 inline-flex h-7 w-full items-center justify-center rounded-full border border-accent bg-accent-soft text-xs font-medium text-accent hover:bg-accent hover:text-surface disabled:pointer-events-none disabled:opacity-50",children:"Apply custom range"})]}),c.jsxs("div",{className:"mt-1 px-1 pb-1","data-testid":"comparison-picker",children:[c.jsx("p",{className:"mb-1 px-1.5 text-2xs text-faint",children:"Compare to"}),c.jsx("div",{className:`grid grid-cols-2 ${R?"opacity-50":""}`,children:JS.map(T=>c.jsx("button",{type:"button",disabled:R,"data-comparison":T.key,"data-active":i===T.key||void 0,onClick:()=>H(T.key),className:"rounded-lg px-2.5 py-1.5 text-left text-xs text-muted hover:bg-surface-soft hover:text-ink data-[active=true]:bg-accent-soft data-[active=true]:text-accent",children:T.label},T.key))}),i==="custom"&&!R?c.jsxs("div",{className:"mt-1.5",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("input",{type:"date","aria-label":"Comparison from date",value:x,onChange:T=>b(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"}),c.jsx("span",{className:"text-faint",children:"→"}),c.jsx("input",{type:"date","aria-label":"Comparison to date",value:w,onChange:T=>j(T.target.value),className:"h-7 min-w-0 flex-1 rounded-lg border border-line bg-surface px-2 text-xs text-ink"})]}),c.jsx("button",{type:"button",disabled:!x||!w,onClick:()=>u("custom",{from:x,to:w}),className:"mt-1.5 inline-flex h-7 w-full items-center justify-center rounded-full border border-accent bg-accent-soft text-xs font-medium text-accent hover:bg-accent hover:text-surface disabled:pointer-events-none disabled:opacity-50",children:"Apply comparison"})]}):null]})]})]})}function Od(n){const[e,t]=M.useState(!1);if(!("dim"in n))return c.jsxs("span",{"data-dimension":n.dimension,"data-value":n.value,className:"inline-flex max-w-full items-center gap-1 rounded-full bg-surface-soft px-2 py-0.5 text-2xs leading-4 text-muted",children:[c.jsxs("span",{className:"truncate",children:[c.jsxs("span",{className:"text-faint",children:[n.dimensionLabel??n.dimension,":"]})," ",n.value]}),n.onRemove?c.jsx("button",{type:"button","aria-label":`Remove filter ${n.value}`,onClick:n.onRemove,className:"-mr-0.5 px-0.5 text-faint hover:text-ink",children:"×"}):null]});const{dim:i,model:a,filter:u,onRemove:f}=n;return c.jsxs("span",{className:"relative inline-flex max-w-full items-center","data-dimension":i.ref,"data-mode":u.mode,children:[c.jsxs("span",{className:"inline-flex max-w-full items-center gap-1 rounded-full bg-surface-soft px-2 py-0.5 text-2xs leading-4 text-muted",children:[c.jsxs("button",{type:"button","aria-label":`Edit filter ${i.label}`,"aria-haspopup":"dialog","aria-expanded":e,onClick:()=>t(h=>!h),className:"min-w-0 truncate text-left hover:text-ink",children:[c.jsx("span",{className:"text-faint",children:i.label})," ",xb(u)]}),c.jsx("button",{type:"button","aria-label":`Remove filter ${i.label}`,onClick:f,className:"grid size-3.5 shrink-0 place-items-center rounded-full bg-surface-soft text-faint hover:bg-line hover:text-ink",children:"×"})]}),e?c.jsx(Av,{dim:i,model:a,onClose:()=>t(!1)}):null]})}function Td({grain:n,options:e,disabled:t,onChange:i}){return c.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-faint",children:[c.jsx("span",{className:"hidden sm:inline",children:"Grain"}),c.jsx("select",{"aria-label":"Time grain",value:n,disabled:t,onChange:a=>i(a.target.value),className:"h-7 rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50",children:e.map(a=>c.jsx("option",{value:a,children:Le(a)},a))})]})}const qS=["UTC","America/Los_Angeles","America/Denver","America/Chicago","America/New_York","America/Sao_Paulo","Europe/London","Europe/Berlin","Europe/Paris","Europe/Moscow","Asia/Dubai","Asia/Kolkata","Asia/Singapore","Asia/Shanghai","Asia/Tokyo","Australia/Sydney"];let ul=null;function Km(){if(ul)return ul;const n=typeof Intl.supportedValuesOf=="function"?Intl.supportedValuesOf("timeZone"):[];return ul=[...new Set(["UTC",...n])].sort(),ul}function ZS(n){if(!n)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:n}),!0}catch{return!1}}function XS(n,e=new Date){var t;try{const u=(((t=new Intl.DateTimeFormat("en-US",{timeZone:n,timeZoneName:"shortOffset"}).formatToParts(e).find(g=>g.type==="timeZoneName"))==null?void 0:t.value)??"").match(/([+-])(\d{1,2})(?::(\d{2}))?/);if(!u)return n==="UTC"?"+00:00":"";const f=u[1],h=u[2].padStart(2,"0"),m=u[3]??"00";return`${f}${h}:${m}`}catch{return""}}const Jm="__search__";function e_({timezone:n,disabled:e,onChange:t}){const i=M.useId(),[a,u]=M.useState(!1),[f,h]=M.useState(""),m=M.useMemo(()=>{const b=new Set(qS);return n&&b.add(n),[...b]},[n]),g=M.useMemo(()=>a?Km():[],[a]);function v(b){const w=b.trim();ZS(w)&&(t(w),u(!1),h(""))}if(a)return c.jsxs("label",{className:"flex items-center gap-1.5 text-2xs text-faint",children:[c.jsx("span",{className:"hidden sm:inline",children:"Zone"}),c.jsx("input",{type:"text",list:i,autoFocus:!0,"aria-label":"Search timezone",placeholder:"Region/City…",value:f,disabled:e,onChange:b=>{h(b.target.value),Km().includes(b.target.value)&&v(b.target.value)},onKeyDown:b=>{b.key==="Enter"?v(f):b.key==="Escape"&&(u(!1),h(""))},onBlur:()=>{u(!1),h("")},className:"h-7 w-36 rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50"}),c.jsx("datalist",{id:i,children:g.map(b=>c.jsx("option",{value:b},b))})]});const x=XS(n);return c.jsxs("label",{className:"flex items-center gap-1.5 text-2xs text-faint",children:[c.jsx("span",{className:"hidden sm:inline",children:"Zone"}),c.jsxs("select",{"aria-label":"Timezone",value:n,disabled:e,onChange:b=>{b.target.value===Jm?u(!0):t(b.target.value)},className:"h-7 max-w-[11rem] rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50",children:[m.map(b=>c.jsxs("option",{value:b,children:[b,b==="UTC"?"":x&&b===n?` (${x})`:""]},b)),c.jsx("option",{value:Jm,children:"Search…"})]})]})}function t_(n,e,t){if(t==="count")return n.length;const i=n.map(u=>typeof u[e]=="number"?u[e]:Number(u[e])).filter(Number.isFinite);if(i.length===0)return Number.NaN;if(t==="min")return Math.min(...i);if(t==="max")return Math.max(...i);const a=i.reduce((u,f)=>u+f,0);return t==="avg"?a/i.length:a}const n_={sum:"Σ",avg:"avg",min:"min",max:"max",count:"n"};function Ho({columns:n,rows:e,loading:t,sortKey:i,sortDir:a,onSort:u,renderCell:f,pageSize:h=50,searchable:m,totals:g,stickyHeader:v=!0}){const[x,b]=M.useState(0),[w,j]=M.useState(""),C=M.useMemo(()=>{const I=w.trim().toLowerCase();return!m||!I?e:e.filter(U=>n.some(G=>String(U[G.key]??"").toLowerCase().includes(I)))},[e,n,w,m]),{paginate:O,pageCount:H,safePage:L,start:R,visibleRows:T}=mb(C,x,h);M.useEffect(()=>{b(0)},[e,h,i,a,w]);const E=g&&n.some(I=>g[I.key]);return c.jsxs("div",{children:[m?c.jsxs("div",{className:"mb-2 flex items-center justify-end gap-2",children:[w?c.jsxs("span",{className:"whitespace-nowrap text-2xs text-faint tnum",children:[C.length.toLocaleString()," of ",e.length.toLocaleString()]}):null,c.jsx("input",{type:"search","aria-label":"Search rows",placeholder:"Search…",value:w,onChange:I=>j(I.target.value),className:"h-7 w-full max-w-64 rounded-full border border-line bg-surface px-2.5 text-xs text-ink placeholder:text-faint"})]}):null,c.jsx("div",{className:"overflow-auto border border-line bg-surface",children:c.jsxs("table",{className:"w-max min-w-full border-collapse text-xs","data-testid":"pivot-table",children:[c.jsx("thead",{children:c.jsx("tr",{className:"bg-surface-soft",children:n.map(I=>{const U=i===I.key;return c.jsx("th",{className:`max-w-80 whitespace-nowrap border-b border-line bg-surface-soft px-3 py-1.5 font-semibold text-faint ${I.numeric?"min-w-32 text-right":"min-w-40 text-left"} ${v?"sticky top-0 z-10":""}`,children:I.sortable&&u?c.jsxs("button",{type:"button",onClick:()=>u(I.key),"aria-label":`Sort by ${I.label}${U?`, currently ${a==="asc"?"ascending":"descending"}`:""}`,className:`table-sort inline-flex max-w-full items-center gap-1 whitespace-nowrap hover:text-ink ${U?"text-ink":""}`,children:[c.jsx("span",{className:"truncate",children:I.label}),c.jsx("span",{"aria-hidden":"true",className:"text-[9px]",children:U?a==="asc"?"▲":"▼":"↕"})]}):c.jsx("span",{className:"block truncate",title:I.label,children:I.label})},I.key)})})}),c.jsx("tbody",{children:t&&C.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:n.length,className:"px-3 py-6 text-center text-faint",children:"Loading…"})}):C.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:n.length,className:"px-3 py-6 text-center text-faint",children:w?"No matching rows":"No rows"})}):T.map((I,U)=>c.jsx("tr",{className:"hover:bg-surface-soft",children:n.map(G=>{const V=f(G,I[G.key]);return c.jsx("td",{className:`max-w-80 whitespace-nowrap border-b border-line px-3 py-1.5 text-muted ${G.numeric?"min-w-32 text-right font-mono tnum text-ink":"min-w-40"}`,children:c.jsx("span",{className:"block max-w-80 truncate",title:V,children:V})},G.key)})},R+U))}),E&&C.length>0?c.jsx("tfoot",{children:c.jsx("tr",{className:"bg-surface-soft","data-testid":"table-totals",children:n.map(I=>{const U=g==null?void 0:g[I.key];if(!U)return c.jsx("td",{className:"border-t border-line px-3 py-1.5"},I.key);const G=t_(C,I.key,U),V=U==="count"?G.toLocaleString():Number.isFinite(G)?f(I,G):"—";return c.jsxs("td",{"data-total":U,className:`whitespace-nowrap border-t border-line px-3 py-1.5 font-mono tnum font-medium text-ink ${I.numeric?"text-right":"text-left"}`,children:[c.jsx("span",{"aria-hidden":"true",className:"mr-1 text-2xs text-faint",children:n_[U]}),V]},I.key)})})}):null]})}),O?c.jsxs("div",{"data-testid":"pivot-table-pager",className:"mt-1.5 flex items-center justify-between gap-3 text-2xs text-faint",children:[c.jsxs("span",{className:"tnum",children:[R+1,"–",Math.min(R+h,C.length)," of ",C.length.toLocaleString(),t?" · Updating…":""]}),c.jsxs("div",{className:"flex gap-1",children:[c.jsx("button",{type:"button",disabled:L===0,onClick:()=>b(I=>Math.max(0,I-1)),className:"table-pager-button px-2 py-1 text-muted hover:text-ink disabled:cursor-not-allowed disabled:opacity-40",children:"Prev"}),c.jsx("button",{type:"button",disabled:L>=H-1,onClick:()=>b(I=>Math.min(H-1,I+1)),className:"table-pager-button px-2 py-1 text-muted hover:text-ink disabled:cursor-not-allowed disabled:opacity-40",children:"Next"})]})]}):null]})}function r_(n,e){const t=e.filter(i=>n.some(a=>a.ref===i));return t.length?t:n.slice(0,6).map(i=>i.ref)}function s_(){var L,R;const[n,e]=M.useState(!1),{state:t,catalog:i,backend:a,dashboard:u}=ls(),f=i.models.find(T=>T.name===t.model),h=M.useMemo(()=>Cs(i,u,t.dashboardTab),[i,u,t.dashboardTab]),m=(h==null?void 0:h.dimensions)??(f==null?void 0:f.dimensions)??[],g=r_(m,t.pivotDims),v=((L=h==null?void 0:h.timeDimension)==null?void 0:L.ref)??((R=f==null?void 0:f.timeDimension)==null?void 0:R.ref),x=M.useMemo(()=>ou(i),[i]),b=M.useMemo(()=>[...(h==null?void 0:h.filters)??[],...Os(t.filters,{timeRef:v,range:t.dateRange,types:x})],[h,t.filters,v,t.dateRange,x]),w=n&&f?wS({dimensions:g,metrics:[]},b,50,h==null?void 0:h.segments,h==null?void 0:h.usePreaggregations):null,{result:j,loading:C,error:O}=Zn(a,w),H=[...g.map(T=>{var E;return{key:Sr(T),label:((E=m.find(I=>I.ref===T))==null?void 0:E.label)??Le(T)}})];return c.jsxs("section",{"data-testid":"row-preview-drawer","data-open":n||void 0,className:"absolute inset-x-0 bottom-0 z-30 border-t border-line bg-surface shadow-[0_-8px_24px_rgba(0,0,0,0.16)]",children:[c.jsxs("button",{type:"button","aria-expanded":n,onClick:()=>e(T=>!T),className:"flex h-8 w-full items-center justify-between px-3 text-left text-xs font-medium text-muted hover:bg-surface-soft hover:text-ink",children:[c.jsx("span",{children:"Rows preview"}),c.jsx("span",{"aria-hidden":"true",children:n?"▼":"▲"})]}),n?c.jsx("div",{className:"max-h-[45vh] overflow-auto border-t border-line",children:O?c.jsx("p",{role:"alert",className:"p-3 text-xs text-danger",children:O}):H.length===0?c.jsx("p",{className:"p-3 text-xs text-faint",children:"No preview fields are available."}):c.jsx(Ho,{columns:H,rows:(j==null?void 0:j.rows)??[],loading:C,pageSize:10,renderCell:(T,E)=>E==null||E===""?"—":String(E)})}):null]})}function of({tone:n,title:e,message:t}){const i=n==="danger";return c.jsx("div",{className:`grid min-h-[200px] place-items-center border bg-surface p-6 text-center ${i?"border-danger/40":"border-line"}`,"data-state":n,role:i?"alert":"status","aria-live":i?"assertive":"polite",children:c.jsxs("div",{className:"max-w-md",children:[n==="loading"?c.jsx("span",{"aria-hidden":"true",className:"motion-safe:animate-pulse inline-block size-2 rounded-full bg-accent"}):null,e?c.jsx("h3",{className:`text-sm font-semibold ${i?"text-danger":"text-ink"}`,children:e}):null,c.jsx("p",{className:`mt-1 text-xs ${i?"text-danger":"text-muted"}`,children:t})]})})}function af({title:n="Loading",message:e="Loading metrics…"}){return c.jsx(of,{tone:"loading",title:n,message:e})}function Xn({title:n="No results",message:e}){return c.jsx(of,{tone:"muted",title:n,message:e})}function Bi({title:n="Query failed",message:e}){return c.jsx(of,{tone:"danger",title:n,message:e})}function dd({status:n}){const e=n==="ok"?"bg-success":n==="loading"?"bg-faint animate-pulse":"bg-line";return c.jsx("span",{"aria-hidden":"true",className:`inline-block size-2 rounded-full ${e}`})}const Ev="sidemantic-theme";function lf(){var e;const n=localStorage.getItem(Ev);return n==="light"||n==="dark"?n:(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}function Rv(n){document.documentElement.dataset.theme=n}function i_(){Rv(lf())}function o_(){const n=lf()==="dark"?"light":"dark";return localStorage.setItem(Ev,n),Rv(n),n}function $o(){const[n,e]=M.useState(lf());return c.jsx("button",{type:"button","aria-label":n==="dark"?"Switch to light theme":"Switch to dark theme",title:n==="dark"?"Light theme":"Dark theme",onClick:()=>e(o_()),className:"grid size-7 place-items-center border border-line bg-surface text-faint hover:border-faint hover:text-ink",children:n==="dark"?c.jsxs("svg",{viewBox:"0 0 24 24",className:"size-3.5",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[c.jsx("circle",{cx:"12",cy:"12",r:"4"}),c.jsx("path",{d:"M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"})]}):c.jsx("svg",{viewBox:"0 0 24 24",className:"size-3.5",fill:"none",stroke:"currentColor",strokeWidth:"2",children:c.jsx("path",{d:"M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"})})})}const _o=[{key:"explore",label:"Explore"},{key:"pivot",label:"Pivot"}];function Lv({view:n,onChange:e}){const t=M.useRef(null);function i(a){const u=Math.max(0,_o.findIndex(h=>h.key===n)),f=_o[(u+a+_o.length)%_o.length];e(f.key),window.requestAnimationFrame(()=>{var h,m;return(m=(h=t.current)==null?void 0:h.querySelector(`[data-view="${f.key}"]`))==null?void 0:m.focus()})}return c.jsx("div",{ref:t,role:"tablist","aria-label":"View",className:"inline-flex items-center gap-0.5 rounded-full border border-line bg-surface p-px",children:_o.map(a=>c.jsx("button",{role:"tab",type:"button","aria-selected":n===a.key,tabIndex:n===a.key?0:-1,"data-view":a.key,"data-selected":n===a.key||void 0,onClick:()=>e(a.key),onKeyDown:u=>{u.key==="ArrowLeft"?(u.preventDefault(),i(-1)):u.key==="ArrowRight"&&(u.preventDefault(),i(1))},className:"inline-flex h-6 items-center rounded-full px-2.5 text-xs font-medium text-muted hover:bg-surface-soft hover:text-ink data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent",children:a.label},a.key))})}const Uv="dashboard_filters",$v="dashboard_ranges",Pv="dashboard_filter_sources",zv="dashboard_range_sources",Vv="dashboard_chart_filters",Wv="dashboard_chart_ranges";function a_(n,e){if(n==="/explore")return!0;const t=new URLSearchParams(e).get("view");return t==="explore"||t==="pivot"}function uf(n,e){var i,a;if(!e||!(n.query.dimensions??[]).includes(e))return!1;const t=(i=n.interactions)==null?void 0:i.select;return t===!0?!0:t?!((a=t.fields)!=null&&a.length)||t.fields.includes(e):!1}function l_(n){return(n.query.dimensions??[]).find(e=>uf(n,e))}function u_(n,e){var i,a;if(!e||!(n.query.dimensions??[]).includes(e))return!1;const t=(i=n.interactions)==null?void 0:i.brush;return t===!0?!0:!t||t.channel&&t.channel!=="x"?!1:!((a=t.fields)!=null&&a.length)||t.fields.includes(e)}function Xl(n){return n==null?er:String(n)}function c_(n){let e=n.trim().replaceAll(/[^A-Za-z0-9_]/g,"_").replaceAll(/^_+|_+$/g,"")||"field";return/^\d/.test(e)&&(e=`field_${e}`),e}function xr(n,e){const t=Sr(n),i=c_(n);return i!==t&&e.includes(i)?i:e.includes(t)?t:e.find(a=>a.endsWith(t))??t}function d_(n){var t;const e=(t=n.encoding)==null?void 0:t.y;return Array.isArray(e)&&e.length?e:typeof e=="string"?[e]:n.query.metrics.slice(0,1)}function f_(n,e,t,i,a){return Object.fromEntries([[e,t],...i.map((u,f)=>[u,a[f]])].filter(u=>typeof u[1]=="string"&&uf(n,u[0])))}function h_(n,e,t){return[e,...t].some(i=>uf(n,i))}const p_=new Set(["second","minute","hour","day","week","month","quarter","year"]);function Ms(n){const e=n.lastIndexOf("__");if(e<0)return null;const t=n.slice(e+2);return p_.has(t)?{baseDimension:n.slice(0,e),grain:t}:null}function Hv(n,e){var u,f;if(n.type&&n.type!=="auto")return n.type;const t=((u=n.encoding)==null?void 0:u.x)??((f=n.query.dimensions)==null?void 0:f[0])??"",i=Ms(t);return(e[t]??(i?e[i.baseDimension]:void 0))==="time"?"line":"bar"}function Gv(n,e){const t=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/.test(n)?`${n}Z`:n,i=new Date(t);return Number.isFinite(i.getTime())?(e==="second"?i.setUTCSeconds(i.getUTCSeconds()+1):e==="minute"?i.setUTCMinutes(i.getUTCMinutes()+1):e==="hour"?i.setUTCHours(i.getUTCHours()+1):e==="day"?i.setUTCDate(i.getUTCDate()+1):e==="week"?i.setUTCDate(i.getUTCDate()+7):e==="month"?i.setUTCMonth(i.getUTCMonth()+1):e==="quarter"?i.setUTCMonth(i.getUTCMonth()+3):e==="year"&&i.setUTCFullYear(i.getUTCFullYear()+1),/^\d{4}-\d{2}-\d{2}$/.test(n)?i.toISOString().slice(0,10):i.toISOString()):null}function Yv(n,e){const t=Ms(n);if(t){const i=Gv(e.to,t.grain);return i?`${t.baseDimension} >= ${Tn(e.from)} AND ${t.baseDimension} < ${Tn(i)}`:`${t.baseDimension} >= ${Tn(e.from)} AND ${t.baseDimension} <= ${Tn(e.to)}`}return`${n} >= ${Tn(e.from)} AND ${n} <= ${Tn(e.to)}`}function m_(n,e,t){const i=Ms(n);return i?e===er?[`${i.baseDimension} IS NULL`]:[Yv(n,{from:e,to:e})]:Mv({[n]:{mode:"include",values:[e]}},{types:t})}function eu(n,e){const t=n.tabs.find(i=>i.charts.includes(e));return`${(t==null?void 0:t.id)??"dashboard"}:${e.id}`}function cf(n,e,t){var f,h,m,g,v;const i=((h=(f=n.defaults)==null?void 0:f.interactions)==null?void 0:h.scope)??"dashboard";if(i==="dashboard")return t;if(i==="chart"){const x=eu(n,e);return{filters:{...Object.fromEntries(Object.entries(t.filters).filter(([b])=>t.filterSources[b]===x)),...((m=t.chartFilters)==null?void 0:m[x])??{}},ranges:{...Object.fromEntries(Object.entries(t.ranges).filter(([b])=>t.rangeSources[b]===x)),...((g=t.chartRanges)==null?void 0:g[x])??{}}}}const a=((v=n.tabs.find(x=>x.charts.includes(e)))==null?void 0:v.charts)??[e],u=new Set(a.flatMap(x=>x.query.dimensions??[]));return{filters:Object.fromEntries(Object.entries(t.filters).filter(([x])=>u.has(x))),ranges:Object.fromEntries(Object.entries(t.ranges).filter(([x])=>u.has(x)))}}function y_(n,e,t,i,a={},u={filterSources:{},rangeSources:{}}){var b,w,j,C,O,H;const f=cf(n,e,{filters:t,ranges:a,...u}),h=((b=e.encoding)==null?void 0:b.x)??((w=e.query.dimensions)==null?void 0:w[0])??"",m=e.query.order_by??e.query.orderBy,g=h&&["line","area"].includes(Hv(e,i))?[`${h} ASC`]:void 0,v={metrics:e.query.metrics,dimensions:e.query.dimensions,filters:[...e.query.filters??[],...Object.entries(f.filters).flatMap(([L,R])=>m_(L,R,i)),...Object.entries(f.ranges).map(([L,R])=>Yv(L,R))],segments:e.query.segments,orderBy:m??g,limit:e.query.limit??500},x=e.query.use_preaggregations??e.query.usePreaggregations??((C=(j=n.defaults)==null?void 0:j.query)==null?void 0:C.use_preaggregations)??((H=(O=n.defaults)==null?void 0:O.query)==null?void 0:H.usePreaggregations);return x!==void 0&&(v.usePreaggregations=x),v}function qm(n){const e=/^(\d{4}-\d{2}-\d{2})/.exec(n);return(e==null?void 0:e[1])??null}function Zm(n,e){const t=qm(e.from);if(!t)return null;const i=Ms(n);if(!i){const f=qm(e.to);return f?{from:t,to:f}:null}const a=Gv(e.to,i.grain);if(!a)return null;const u=new Date(a);return u.setUTCMilliseconds(u.getUTCMilliseconds()-1),{from:t,to:u.toISOString().slice(0,10)}}function g_(n,e,t,i={},a){var T,E,I;const u=(T=e.encoding)==null?void 0:T.y,f=(Array.isArray(u)?u[0]:u)??e.query.metrics[0]??"",h=e.query.dimensions??[],m=a==null?void 0:a.graphMetrics.find(U=>U.ref===f),g=f.includes(".")?f.split(".")[0]:((E=h[0])==null?void 0:E.split(".")[0])??(m==null?void 0:m.ownerModel)??(m==null?void 0:m.model)??"",v=cf(n,e,t),x=Object.entries(v.filters).flatMap(([U,G])=>{const V=Ms(U);return V?[{dimension:U,value:G,baseDimension:V.baseDimension}]:[]}),b=Object.fromEntries(Object.entries(v.filters).flatMap(([U,G])=>{const V=Ms(U);return V?G===er?[[V.baseDimension,[G]]]:[]:[[U,[G]]]})),w=new URLSearchParams({view:"explore",model:g,metric:f});Object.keys(b).length&&w.set("filters",JSON.stringify(b));const j=((I=e.encoding)==null?void 0:I.x)??h[0],C=x.find(({baseDimension:U,value:G})=>G!==er&&(!g||U.startsWith(`${g}.`))),O=Object.keys(v.ranges),H=[j,...O].find((U,G,V)=>{if(!U||V.indexOf(U)!==G||!v.ranges[U])return!1;const Q=Ms(U);return((i[U]??(Q?i[Q.baseDimension]:void 0))==="time"||!!Q)&&(!g||U.startsWith(`${g}.`))}),L=H?v.ranges[H]:void 0,R=C?Zm(C.dimension,{from:C.value,to:C.value}):H&&L?Zm(H,L):null;return R&&(w.set("from",R.from),w.set("to",R.to)),`/explore?${w}`}function v_(n,e,t,i){const a=new Map;for(const u of n){const f=Number(u[t]);if(!Number.isFinite(f))continue;const h=i.map(b=>Xl(u[b])),m=JSON.stringify(h),g=h.length?h.map(rs).join(" · "):"Current",v=a.get(m)??{label:g,filterValues:h,data:[]},x=Xl(u[e]);v.data.push({label:rs(x),filterValue:x,value:f}),a.set(m,v)}return[...a.values()]}function x_(n,e,t,i){const a=[],u=new Set,f=new Map;for(const h of n){if(h[e]==null)continue;const m=String(h[e]),g=Number(h[t]);if(!Number.isFinite(g))continue;u.has(m)||(u.add(m),a.push(m));const v=i.map(j=>Xl(h[j])),x=JSON.stringify(v),b=v.length?v.map(rs).join(" · "):"Current",w=f.get(x)??{label:b,values:new Map};w.values.set(m,g),f.set(x,w)}return[...f.values()].map(h=>({label:h.label,points:a.map(m=>({x:m,y:h.values.get(m)??Number.NaN}))}))}function df(n,e){if(typeof n!="object"||n===null||Array.isArray(n))return{};const t={};for(const[i,a]of Object.entries(n))e.has(i)&&typeof a=="string"&&(t[i]=a);return t}function ff(n,e){if(typeof n!="object"||n===null||Array.isArray(n))return{};const t={};for(const[i,a]of Object.entries(n)){if(!e.has(i)||typeof a!="object"||a===null||Array.isArray(a))continue;const u=a;typeof u.from=="string"&&typeof u.to=="string"&&(t[i]={from:u.from,to:u.to})}return t}function tu(n,e){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).filter(t=>e.has(t[0])&&typeof t[1]=="string"))}function Qv(n,e){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).flatMap(([t,i])=>{const a=e.get(t);if(!a)return[];const u=df(i,a);return Object.keys(u).length?[[t,u]]:[]}))}function Kv(n,e){return typeof n!="object"||n===null||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).flatMap(([t,i])=>{const a=e.get(t);if(!a)return[];const u=ff(i,a);return Object.keys(u).length?[[t,u]]:[]}))}function Jv(n){return new Set(n.tabs.flatMap(e=>e.charts.flatMap(t=>t.query.dimensions??[])))}function qv(n){return new Map(n.tabs.flatMap(e=>e.charts.map(t=>[eu(n,t),new Set(t.query.dimensions??[])])))}function b_(n,e){var j;const t=new URLSearchParams(n),i=((j=e.tabs[0])==null?void 0:j.id)??"",a=t.get("tab"),u=e.tabs.some(C=>C.id===a)?a??i:i;let f,h,m,g,v,x;try{f=JSON.parse(t.get(Uv)??"{}")}catch{f={}}try{h=JSON.parse(t.get($v)??"{}")}catch{h={}}try{m=JSON.parse(t.get(Pv)??"{}")}catch{m={}}try{g=JSON.parse(t.get(zv)??"{}")}catch{g={}}try{v=JSON.parse(t.get(Vv)??"{}")}catch{v={}}try{x=JSON.parse(t.get(Wv)??"{}")}catch{x={}}const b=Jv(e),w=qv(e);return{tab:u,filters:df(f,b),ranges:ff(h,b),filterSources:tu(m,b),rangeSources:tu(g,b),chartFilters:Qv(v,w),chartRanges:Kv(x,w)}}function w_(n,e){var u;const t=new URLSearchParams;n.tab&&n.tab!==((u=e.tabs[0])==null?void 0:u.id)&&t.set("tab",n.tab),Object.keys(n.filters).length&&t.set(Uv,JSON.stringify(n.filters)),Object.keys(n.ranges).length&&t.set($v,JSON.stringify(n.ranges));const i=Object.fromEntries(Object.entries(n.filterSources).filter(([f])=>f in n.filters)),a=Object.fromEntries(Object.entries(n.rangeSources).filter(([f])=>f in n.ranges));return Object.keys(i).length&&t.set(Pv,JSON.stringify(i)),Object.keys(a).length&&t.set(zv,JSON.stringify(a)),Object.keys(n.chartFilters??{}).length&&t.set(Vv,JSON.stringify(n.chartFilters)),Object.keys(n.chartRanges??{}).length&&t.set(Wv,JSON.stringify(n.chartRanges)),t.toString()}function Zv(n){return`sidemantic-dashboard-views:${`${n.schema??"sidemantic.dashboard.v1"}:${n.title}`}`}function S_(n){try{const e=JSON.parse(localStorage.getItem(Zv(n))??"[]");if(!Array.isArray(e))return[];const t=Jv(n);return e.flatMap(i=>{var m;if(typeof i!="object"||i===null||Array.isArray(i))return[];const a=i;if(typeof a.name!="string"||!a.name.trim())return[];if(typeof a.state!="object"||a.state===null||Array.isArray(a.state))return[];const u=a.state,f=n.tabs.some(g=>g.id===u.tab)?String(u.tab):((m=n.tabs[0])==null?void 0:m.id)??"",h=qv(n);return[{name:a.name,state:{tab:f,filters:df(u.filters,t),ranges:ff(u.ranges,t),filterSources:tu(u.filterSources,t),rangeSources:tu(u.rangeSources,t),chartFilters:Qv(u.chartFilters,h),chartRanges:Kv(u.chartRanges,h)}}]})}catch{return[]}}function __(n,e){try{return localStorage.setItem(Zv(n),JSON.stringify(e)),!0}catch{return!1}}function Xm(n){if(n==null)return"";const e=String(n);return/[",\r\n]/.test(e)?`"${e.replaceAll('"','""')}"`:e}function N_(n,e){return[n.map(Xm).join(","),...e.map(t=>n.map(i=>Xm(t[i])).join(","))].join(`\r +`)}function j_(n){var e;return((e=n.label)==null?void 0:e.trim())||n.id}function fd(n,e){return`${n} ${e}${n===1?"":"s"}`}function k_(){const{catalog:n,dispatch:e}=ls(),t=i=>{const a=n.models.find(h=>h.name===i),u=Dv(a,n),f=(a==null?void 0:a.defaultGrain)??"month";e({type:"setModel",model:i,metric:u,grain:f}),e({type:"setView",view:"explore"})};return c.jsxs("div",{className:"mx-auto w-full max-w-5xl p-6",children:[c.jsxs("div",{className:"mb-4",children:[c.jsx("h1",{className:"text-base font-semibold text-ink",children:"Explore"}),c.jsxs("p",{className:"text-2xs text-muted",children:[fd(n.models.length,"model")," · pick one to explore"]})]}),c.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3",children:n.models.map(i=>c.jsxs("button",{type:"button","data-testid":"explore-card","data-model":i.name,onClick:()=>t(i.name),className:"flex min-h-32 flex-col gap-2 rounded-xl border border-line bg-surface p-4 text-left shadow-[var(--shadow-sm)] transition-colors hover:border-line-strong",children:[c.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[c.jsx("span",{className:"truncate text-sm font-medium text-ink",children:i.label}),i.timeDimension?c.jsx("span",{className:"shrink-0 text-2xs text-faint",children:"time series"}):null]}),i.description?c.jsx("p",{className:"line-clamp-2 text-2xs text-muted",children:i.description}):null,c.jsx("div",{className:"mt-auto flex flex-wrap gap-1 pt-1",children:i.metrics.slice(0,3).map(a=>c.jsx("span",{className:"rounded-full bg-surface-soft px-2 py-0.5 text-2xs text-muted",children:a.label},a.ref))}),c.jsxs("div",{className:"text-2xs text-faint",children:[fd(i.metrics.length,"metric")," · ",fd(i.dimensions.length,"dimension")]})]},i.name))})]})}const I_="600px";function M_(n){for(let e=n.parentElement;e;e=e.parentElement){const t=getComputedStyle(e).overflowY;if(t==="auto"||t==="scroll")return e}return null}function D_(n,e,t=I_){if(typeof IntersectionObserver>"u")return e(),()=>{};const i=new IntersectionObserver(a=>{a.some(u=>u.isIntersecting)&&(i.disconnect(),e())},{root:M_(n),rootMargin:t});return i.observe(n),()=>i.disconnect()}const C_={positive:"text-success",negative:"text-danger",neutral:"text-faint"};function Xv({dimension:n,title:e,metricLabel:t,rows:i,selectedValues:a=[],loading:u,formatMetric:f,onToggle:h,contextColumn:m="none",contextOptions:g,onContextColumn:v,collapsedLimit:x=6,expanded:b=!1,onExpandedChange:w,containerRef:j}){const C=new Set(a),O=b?i:i.slice(0,x),H=Math.max(1,...O.map(E=>Math.abs(E.metric))),L=b||i.length>x,R=m!=="none",T=R?"grid-cols-[minmax(0,1fr)_auto_auto]":"grid-cols-[minmax(0,1fr)_auto]";return c.jsxs("section",{ref:j,"data-testid":"dimension-leaderboard","data-dimension":n,"data-expanded":b||void 0,"aria-label":`${e}, ranked by ${t}`,className:"flex min-h-40 flex-col border-b border-r border-line bg-surface data-[expanded=true]:col-span-full",children:[c.jsxs("header",{className:"flex items-center justify-between gap-3 px-3 pb-2 pt-2.5",children:[c.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[c.jsx("h3",{className:"truncate text-sm font-semibold text-ink",children:e}),c.jsxs("p",{className:"sr-only",children:["Ranked by ",t]})]}),g&&v?c.jsx("div",{role:"group","aria-label":"Context column","data-testid":"leaderboard-context-toggle",className:"flex shrink-0 overflow-hidden border border-line text-2xs",children:g.map(E=>c.jsx("button",{type:"button",title:E.title,"aria-pressed":m===E.key,"data-context":E.key,"data-active":m===E.key||void 0,onClick:()=>v(E.key),className:"border-l border-line px-1.5 py-0.5 font-mono text-faint first:border-l-0 hover:bg-surface-soft data-[active=true]:bg-accent-soft data-[active=true]:text-accent",children:E.label},E.key))}):null]}),c.jsx("div",{"data-testid":"leaderboard-rows",children:u&&i.length===0?c.jsx("div",{className:"space-y-2 p-3",children:[0,1,2,3].map(E=>c.jsx("div",{className:"skeleton h-5 w-full"},E))}):i.length===0?c.jsx("p",{className:"px-3 py-4 text-xs text-faint",children:"No values"}):O.map(E=>{var V,Q,z;const I=E.metric<0?"negative":"positive",U=C.has(E.value),G=`${Math.round(Math.abs(E.metric)/H*100)}%`;return c.jsxs("button",{type:"button","data-dimension":n,"data-value":E.value,"data-selected":U||void 0,"data-tone":I,onClick:()=>h==null?void 0:h(E.value),"aria-pressed":U,className:`leaderboard-row relative grid w-full ${T} items-center gap-3 overflow-hidden border-0 bg-transparent px-3 py-1 text-left text-xs text-ink data-[selected=true]:bg-chart-primary-selected`,children:[c.jsx("span",{"aria-hidden":"true",className:`absolute inset-y-0 left-0 ${I==="negative"?"bg-danger-soft":"bg-chart-primary-soft"}`,style:{width:G}}),c.jsx("span",{className:"relative min-w-0 truncate text-muted",children:rs(E.value)}),c.jsx("strong",{className:"relative tnum font-semibold text-ink",children:f(E.metric)}),R?c.jsx("span",{"data-testid":"leaderboard-context","data-tone":((V=E.context)==null?void 0:V.tone)??"neutral",className:`relative w-14 text-right font-mono tnum text-2xs ${C_[((Q=E.context)==null?void 0:Q.tone)??"neutral"]}`,children:((z=E.context)==null?void 0:z.label)??"—"}):null]},`${n}:${E.value}`)})}),L&&!u?c.jsx("button",{type:"button","data-action":b?"leaderboard-back":"leaderboard-expand","aria-expanded":b,onClick:()=>w==null?void 0:w(!b),className:"leaderboard-expand border-0 border-t border-line bg-transparent px-3 py-1 text-left text-xs font-normal text-faint hover:text-accent",children:b?"← All dimensions":`Expand table (${i.length})`}):null]})}const F_=[{key:"none",label:"—",title:"No context column"},{key:"pctTotal",label:"%",title:"Share of total"},{key:"delta",label:"Δ",title:"Absolute change vs comparison period"},{key:"deltaPct",label:"Δ%",title:"Percent change vs comparison period"}],O_=[],T_=[];function A_({dim:n,model:e,timeDimensionRef:t,rankMetric:i,contextColumn:a,metricTotal:u,comparisonRange:f,baseFilters:h=O_,baseSegments:m=T_,usePreaggregations:g,limit:v=6,expanded:x=!1,onExpandedChange:b}){var pe;const{state:w,dispatch:j,backend:C,catalog:O}=ls(),H=M.useRef(null),[L,R]=M.useState(!1);M.useEffect(()=>{if(!(L||!H.current))return D_(H.current,()=>R(!0))},[L]);const T=t??((pe=e.timeDimension)==null?void 0:pe.ref),E=M.useMemo(()=>ou(O),[O]),I=M.useMemo(()=>[...h,...Os(w.filters,{timeRef:T,range:w.dateRange,excludeDim:n.ref,types:E})],[h,w.filters,T,w.dateRange,n.ref,E]),{result:U,loading:G,error:V}=Zn(C,L?zm(i.ref,n.ref,I,v,m,g):null),Q=w.filters[n.ref],z=(Q==null?void 0:Q.mode)==="include"?Q.values:void 0,ee=[i.ref,n.ref],X=Fn(n.ref,ee),ie=a==="delta"||a==="deltaPct",ae=M.useMemo(()=>{if(!U||!U.columns.includes(X))return null;const ne=[];let fe=!1;for(const Te of U.rows){const Ue=Te[X];Ue==null?fe=!0:ne.push(String(Ue))}const Ce=[];return ne.length&&Ce.push(`CAST(${n.ref} AS VARCHAR) IN (${ne.map(Tn).join(", ")})`),fe&&Ce.push(`${n.ref} IS NULL`),Ce.length?Ce.length===1?Ce[0]:`(${Ce.join(" OR ")})`:null},[U,X,n.ref]),re=M.useMemo(()=>ie&&f&&T&&ae?[...h,...Os(w.filters,{timeRef:T,range:f,excludeDim:n.ref,types:E}),ae]:null,[ie,f,T,w.filters,n.ref,E,ae,h]),se=Zn(C,re?zm(i.ref,n.ref,re,v,m,g):null),A=Fn(i.ref,ee),Y=!!U&&U.rows.length>0&&!U.columns.includes(A),W=M.useMemo(()=>{const ne=new Map;if(!se.result||!se.result.columns.includes(A))return ne;for(const fe of se.result.rows){const Ce=fe[X],Te=Ce==null?er:String(Ce);ne.set(Te,Number(fe[A]))}return ne},[se.result,X,A]),_={format:i.format,type:i.type};function F(ne,fe){switch(a){case"pctTotal":return u===void 0?void 0:yb(fe,u);case"delta":return gb(fe,W.get(ne),_);case"deltaPct":return vb(fe,W.get(ne));default:return}}const te=U&&!Y?U.rows.map(ne=>{const fe=ne[X],Ce=fe==null?er:String(fe),Te=Number(ne[A]??0);return{value:Ce,metric:Te,context:F(Ce,Te)}}):[];return V?c.jsx(Bi,{title:n.label,message:V}):c.jsx(Xv,{dimension:n.ref,title:n.label,metricLabel:i.label,rows:te,containerRef:H,loading:!L||G||Y,selectedValues:z,formatMetric:ne=>Wt(ne,_),onToggle:ne=>j({type:"toggleFilter",dim:n.ref,value:ne}),contextColumn:a,contextOptions:F_,onContextColumn:ne=>j({type:"setContextColumn",column:ne}),collapsedLimit:v,expanded:x,onExpandedChange:b})}function Dr(){const[n,e]=M.useState(null);return{tip:n,handlers:i=>({onMouseEnter:a=>e({content:i,x:a.clientX,y:a.clientY}),onMouseMove:a=>e({content:i,x:a.clientX,y:a.clientY}),onMouseLeave:()=>e(null)})}}function rr({tip:n,position:e="fixed",offset:t=12,className:i,style:a}){return n?c.jsx("div",{role:"tooltip",style:{position:e,left:n.x+t,top:n.y+t,pointerEvents:"none",zIndex:50,...a},className:i||"rounded-lg border border-line bg-surface px-2.5 py-1.5 text-xs text-ink shadow-[var(--shadow)]",children:n.content}):null}function os({title:n,rows:e}){return c.jsxs("div",{className:"min-w-28",children:[n?c.jsx("div",{className:"mb-0.5 font-mono text-faint",children:n}):null,e.map((t,i)=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs("span",{className:"flex items-center gap-1 text-muted",children:[t.swatch?c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-sm",style:{background:t.swatch}}):null,t.label]}),c.jsx("span",{className:"font-mono tnum font-medium text-ink",children:t.value})]},i))]})}function e0({values:n,labels:e,height:t=44,ariaLabel:i,formatValue:a=h=>h.toLocaleString(void 0,{maximumFractionDigits:2}),onHover:u,onBrush:f}){const h=M.useRef(null),m=M.useId(),g=M.useRef(null),v=M.useRef(null),[x,b]=M.useState(200),[w,j]=M.useState(null),[C,O]=M.useState(null),[H,L]=M.useState(null);M.useEffect(()=>{const W=h.current;if(!W||typeof ResizeObserver>"u")return;const _=new ResizeObserver(F=>{for(const te of F)b(Math.max(40,te.contentRect.width))});return _.observe(W),()=>_.disconnect()},[]);const R=n.map((W,_)=>({index:_,value:W})).filter(W=>Number.isFinite(W.value));if(R.length<2)return c.jsx("svg",{ref:g,role:"img","aria-label":i||"No trend data",className:"h-11 w-full",viewBox:`0 0 ${x} ${t}`});const T=3,E=Math.min(...R.map(W=>W.value)),U=Math.max(...R.map(W=>W.value))-E||1,G=R.map((W,_)=>({...W,x:T+_/(R.length-1)*(x-T*2),y:T+(1-(W.value-E)/U)*(t-T*2)})),V=G.map(({x:W,y:_})=>`${W.toFixed(1)},${_.toFixed(1)}`).join(" L "),Q=`M ${G[0].x.toFixed(1)},${t-T} L ${V} L ${G.at(-1).x.toFixed(1)},${t-T} Z`,z=G.at(-1),ee=i||`Trend of ${R.length} points, latest ${a(z.value)}`;function X(W){var F;const _=(F=g.current)==null?void 0:F.getBoundingClientRect();return _?Math.max(T,Math.min(x-T,(W.clientX-_.left)/_.width*x)):T}function ie(W){return Math.max(0,Math.min(G.length-1,Math.round((W-T)/(x-T*2)*(G.length-1))))}function ae(W){const _=X(W),F=ie(_),te=G[F];j(F),L({content:`${e!=null&&e[te.index]?`${e[te.index]}: `:""}${a(te.value)}`,x:W.clientX,y:W.clientY}),u==null||u({index:te.index,label:e==null?void 0:e[te.index],value:te.value}),v.current!==null&&O({a:v.current,b:_})}function re(W){if(!f||!(e!=null&&e.length))return;W.currentTarget.setPointerCapture(W.pointerId);const _=X(W);v.current=_,O({a:_,b:_})}function se(W){if(v.current===null||!f||!(e!=null&&e.length))return;W.currentTarget.hasPointerCapture(W.pointerId)&&W.currentTarget.releasePointerCapture(W.pointerId);const _=X(W);if(Math.abs(_-v.current)>6){const F=G[ie(Math.min(v.current,_))],te=G[ie(Math.max(v.current,_))];f({from:e[F.index],to:e[te.index]})}v.current=null,O(null)}function A(){j(null),L(null),u==null||u(null),v.current===null&&O(null)}const Y=w===null?null:G[w];return c.jsxs("span",{ref:h,className:"relative block w-full",children:[c.jsxs("svg",{ref:g,role:"img","aria-label":ee,className:`h-11 w-full overflow-hidden text-chart-primary ${f?"touch-none select-none":""}`,viewBox:`0 0 ${x} ${t}`,preserveAspectRatio:"none",onPointerMove:ae,onPointerDown:re,onPointerUp:se,onPointerCancel:A,onPointerLeave:A,onDoubleClick:()=>f==null?void 0:f(null),children:[c.jsx("defs",{children:c.jsxs("linearGradient",{id:m,x1:"0",y1:"0",x2:"0",y2:"1",children:[c.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:.16}),c.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:0})]})}),c.jsx("path",{d:Q,fill:`url(#${m})`}),c.jsx("path",{d:`M ${V}`,fill:"none",stroke:"currentColor",strokeWidth:1.5,vectorEffect:"non-scaling-stroke"}),C?c.jsx("rect",{x:Math.min(C.a,C.b),y:0,width:Math.abs(C.b-C.a),height:t,fill:"currentColor",opacity:.12}):null,Y?c.jsxs(c.Fragment,{children:[c.jsx("line",{x1:Y.x,x2:Y.x,y1:0,y2:t,stroke:"currentColor",strokeWidth:1,opacity:.45}),c.jsx("circle",{cx:Y.x,cy:Y.y,r:2.5,fill:"currentColor"})]}):c.jsx("circle",{cx:z.x,cy:z.y,r:2.25,fill:"currentColor"})]}),c.jsx(rr,{tip:H})]})}const B_={positive:"text-success",negative:"text-danger",neutral:"text-faint"},E_={positive:"▲",negative:"▼",neutral:"·"};function Nr({metric:n,label:e,value:t,valueText:i,format:a,delta:u,comparison:f,sparkValues:h=[],sparkLabels:m,selected:g,loading:v,onSelect:x,onSparkHover:b,onSparkBrush:w}){const[j,C]=M.useState(null),O=c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[c.jsx("span",{className:"truncate text-xs font-medium text-muted",children:e}),j!=null&&j.label?c.jsx("span",{className:"shrink-0 font-mono text-2xs text-faint",children:j.label}):null]}),c.jsx("div",{className:"font-mono tnum text-[19px] font-semibold leading-tight tracking-tight text-ink",children:v?c.jsx("span",{className:"skeleton inline-block h-6 w-24 align-middle"}):j?pt(j.value,a):i??pt(t,a)}),u||f?c.jsxs("div",{className:"flex items-baseline gap-1 text-2xs",children:[u?c.jsxs("span",{"data-tone":u.tone,className:`font-mono tnum font-medium ${B_[u.tone]}`,children:[c.jsx("span",{"aria-hidden":"true",className:"mr-0.5 text-[8px]",children:E_[u.tone]}),u.label]}):null,f?c.jsx("span",{className:"truncate text-faint",children:f}):null]}):null]}),H="group flex w-full flex-col gap-1.5 overflow-hidden rounded-xl border border-line bg-surface px-3.5 pt-3 text-left shadow-[var(--shadow-sm)] transition-colors hover:border-line-strong data-[selected=true]:border-accent",L=c.jsx("div",{className:"-mx-3.5 mt-auto",children:c.jsx(e0,{values:h,labels:m,onHover:R=>{C(R),b==null||b(R)},onBrush:w,formatValue:R=>pt(R,a)})});return x?c.jsxs("article",{"data-metric":n,"data-selected":g||void 0,className:H,children:[c.jsx("button",{type:"button","data-metric":n,"aria-pressed":!!g,onClick:()=>x(n),className:"-m-1 flex flex-col gap-1 border-0 bg-transparent p-1 text-left transition hover:opacity-75",children:O}),L]}):c.jsxs("article",{"data-metric":n,"data-selected":g||void 0,className:H,children:[O,L]})}const cl=280,qt={top:14,right:18,bottom:26,left:60},ey=["var(--accent)","var(--danger)","#0f9f8f","#d98921","#a66dd4","#3b82c4"];function hd(n){return ey[n%ey.length]}function ty(n,e,t){return Math.min(Math.max(n,e),t)}function Go({points:n,seriesLabel:e="Current",additionalSeries:t=[],comparison:i,formatValue:a,formatAxis:u=a,formatLabel:f=v=>v,comparisonLabel:h="Previous",ariaLabel:m,onBrush:g}){var Fr;const v=M.useRef(null),x=M.useRef(null),b=M.useRef(!1),w=M.useRef(null),[j,C]=M.useState(820),[O,H]=M.useState(null),[L,R]=M.useState(null);M.useEffect(()=>{const ue=v.current;if(!ue)return;const Oe=new ResizeObserver(rt=>{for(const Nt of rt)C(Math.max(320,Nt.contentRect.width))});return Oe.observe(ue),()=>Oe.disconnect()},[]);const T=n.length,E=[{label:e,points:n},...t],I=[...E.flatMap(ue=>ue.points),...i??[]].map(ue=>ue.y).filter(Number.isFinite),U=T<2||I.length===0,G=U?0:Math.min(0,...I),V=U?1:Math.max(...I),Q=V-G||1,z=j-qt.left-qt.right,ee=cl-qt.top-qt.bottom,X=ue=>qt.left+(T<=1?0:ue/(T-1)*z),ie=ue=>qt.top+(1-(ue-G)/Q)*ee,ae=ue=>ty(Math.round((ue-qt.left)/z*(T-1)),0,T-1),re=ue=>{const Oe=[];let rt=[];return ue.forEach((Nt,Un)=>{Number.isFinite(Nt.y)?rt.push(`${X(Un).toFixed(1)},${ie(Nt.y).toFixed(1)}`):rt.length&&(Oe.push(rt.join(" L ")),rt=[])}),rt.length&&Oe.push(rt.join(" L ")),Oe.map(Nt=>`M ${Nt}`).join(" ")},se=U||n.some(ue=>!Number.isFinite(ue.y))?"":`M ${X(0).toFixed(1)},${ie(G).toFixed(1)} L ${n.map((ue,Oe)=>`${X(Oe).toFixed(1)},${ie(ue.y).toFixed(1)}`).join(" L ")} L ${X(T-1).toFixed(1)},${ie(G).toFixed(1)} Z`;function A(ue){var rt;const Oe=(rt=x.current)==null?void 0:rt.getBoundingClientRect();return Oe?ue.clientX-Oe.left:0}function Y(ue){if(U)return;const Oe=A(ue);H(ae(Oe)),b.current&&w.current&&(w.current={a:w.current.a,b:Oe},R({...w.current}))}function W(ue){if(U||!g)return;ue.currentTarget.setPointerCapture(ue.pointerId),b.current=!0;const Oe=A(ue);w.current={a:Oe,b:Oe},R({...w.current})}function _(ue){ue.currentTarget.hasPointerCapture(ue.pointerId)&&ue.currentTarget.releasePointerCapture(ue.pointerId);const Oe=w.current;if(b.current&&Oe&&g){const rt=ae(Math.min(Oe.a,Oe.b)),Nt=ae(Math.max(Oe.a,Oe.b));Nt>rt&&g({from:n[rt].x,to:n[Nt].x})}b.current=!1,w.current=null,R(null)}function F(){H(null),b.current=!1,w.current=null,R(null)}const te=Math.max(1,Math.ceil(T/8)),pe=[V,G+Q*.66,G+Q*.33,G],ne=O!=null&&O>=0&&O{const rt=ue.points[ne];return rt&&Number.isFinite(rt.y)?[{...ue,point:rt,index:Oe}]:[]}),lt=ne!=null?(i==null?void 0:i[ne])??null:null,wt=lt&&Number.isFinite(lt.y)?lt:null,Bs=ne!=null?ty(X(ne),80,j-80):0,xn=Ce&&wt&&wt.y!==0?(Ce.y-wt.y)/Math.abs(wt.y)*100:null,Cr=m??(U?"Time series chart: not enough data to plot.":`Time series chart, ${T} points from ${f(n[0].x)} to ${f(n[T-1].x)}.`);return c.jsxs("div",{className:"relative text-chart-primary",children:[c.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-x-3 gap-y-0.5 px-3 pt-2 text-2xs text-faint",children:[E.map((ue,Oe)=>c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"inline-block h-0.5 w-3",style:{backgroundColor:hd(Oe)}})," ",ue.label]},`${ue.label}-${Oe}`)),i!=null&&i.length?c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"inline-block h-0 w-3 border-t border-dashed border-faint"})," ",h]}):null]}),c.jsx("div",{ref:v,className:"w-full",children:U?c.jsx("div",{className:"grid h-[280px] place-items-center text-xs text-faint",children:"Not enough data to chart."}):c.jsxs("svg",{ref:x,width:j,height:cl,role:"img","aria-label":Cr,className:"block touch-none select-none",onPointerMove:Y,onPointerDown:W,onPointerUp:_,onPointerLeave:F,onPointerCancel:F,onDoubleClick:()=>g==null?void 0:g(null),children:[c.jsx("defs",{children:c.jsxs("linearGradient",{id:"ts-fill",x1:"0",y1:"0",x2:"0",y2:"1",children:[c.jsx("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:.18}),c.jsx("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:0})]})}),pe.map((ue,Oe)=>c.jsxs("g",{children:[c.jsx("line",{x1:qt.left,x2:j-qt.right,y1:ie(ue),y2:ie(ue),className:"stroke-line"}),c.jsx("text",{x:qt.left-8,y:ie(ue)+3,textAnchor:"end",className:"fill-faint font-mono text-[10px]",children:u(ue)})]},Oe)),i&&i.length>=2?c.jsx("path",{d:re(i),fill:"none",className:"stroke-faint",strokeWidth:1.25,strokeDasharray:"4 3"}):null,se?c.jsx("path",{d:se,fill:"url(#ts-fill)"}):null,E.map((ue,Oe)=>c.jsx("path",{d:re(ue.points),fill:"none",stroke:hd(Oe),strokeWidth:1.75},`${ue.label}-${Oe}`)),L?c.jsx("rect",{x:Math.min(L.a,L.b),y:qt.top,width:Math.abs(L.b-L.a),height:ee,className:"fill-chart-primary",opacity:.12}):null,ne!=null&&Ue.length?c.jsxs("g",{children:[c.jsx("line",{x1:X(ne),x2:X(ne),y1:qt.top,y2:cl-qt.bottom,className:"stroke-faint",strokeDasharray:"3 3"}),wt?c.jsx("circle",{cx:X(ne),cy:ie(wt.y),r:3,className:"fill-faint"}):null,Ue.map(ue=>c.jsx("circle",{cx:X(ne),cy:ie(ue.point.y),r:3.5,fill:hd(ue.index)},`${ue.label}-${ue.index}`))]}):null,n.map((ue,Oe)=>Oe%te===0||Oe===T-1?c.jsx("text",{x:X(Oe),y:cl-8,textAnchor:"middle",className:"fill-faint font-mono text-[10px]",children:f(ue.x)},ue.x):null)]})}),Ue.length&&Te?c.jsxs("div",{className:"pointer-events-none absolute top-8 z-20 -translate-x-1/2 whitespace-nowrap border border-line bg-surface px-2 py-1.5 text-2xs shadow-[var(--shadow)]",style:{left:Bs},children:[c.jsx("div",{className:"mb-0.5 font-mono text-faint",children:f(Te)}),Ue.map(ue=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"text-muted",children:ue.label}),c.jsx("span",{className:"font-mono tnum font-medium text-ink",children:a(ue.point.y)})]},`${ue.label}-${ue.index}`)),wt?c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"text-muted",children:h}),c.jsx("span",{className:"font-mono tnum text-muted",children:a(wt.y)})]}):null,xn!=null?c.jsxs("div",{className:`mt-0.5 text-right font-mono ${xn>0?"text-success":xn<0?"text-danger":"text-faint"}`,children:[xn.toLocaleString(void 0,{maximumFractionDigits:1,signDisplay:"exceptZero"}),"%"]}):null]}):null]})}const R_={positive:"text-success",negative:"text-danger",neutral:"text-faint"};function L_({metric:n,points:e,comparisonPoints:t,total:i,prevTotal:a,hasTime:u,loading:f,activeRange:h,comparisonLabel:m="Prev period",formatLabel:g,onBrush:v}){const x={format:n.format,type:n.type},b=a!==void 0?xy(i,a):null,w=`${n.label} over time. Total ${pt(i,x)}${b?`, ${b.label} versus the ${m.toLowerCase()}`:""}.`;return c.jsxs("section",{className:"flex flex-col gap-2",children:[c.jsxs("header",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-0.5 px-0.5",children:[c.jsx("h2",{className:"text-xs font-medium text-muted",children:n.label}),c.jsx("span",{className:"font-mono tnum text-xl font-semibold text-ink",children:pt(i,x)}),b?c.jsxs("span",{className:`text-xs ${R_[b.tone]}`,children:[b.label," vs ",m.toLowerCase()]}):null,u?null:c.jsx("span",{className:"text-2xs text-faint",children:"No time dimension"}),h?c.jsx("button",{type:"button",onClick:()=>v(null),className:"ml-auto inline-flex h-7 items-center rounded-full border border-line bg-surface px-3 text-xs text-muted hover:border-line-strong hover:text-ink",children:"Reset zoom"}):null]}),u?f&&e.length<2?c.jsx("div",{className:"skeleton h-[280px] w-full"}):c.jsx(Go,{points:e,comparison:t,formatValue:j=>pt(j,x),formatAxis:j=>Wt(j,x),formatLabel:g,comparisonLabel:m,ariaLabel:w,onBrush:v}):null]})}const U_=new Set(["and","as","asc","by","case","cast","count","date_trunc","desc","else","end","from","group","in","is","join","left","limit","not","null","on","or","order","over","partition","select","sum","then","when","where","with"]);function $_(n){const e=[];let t=0;for(;ta).map(([a,u])=>`-- ${a} ${u}`).join(` -`),i=R_(t||"No queries yet.");return c.jsxs("details",{className:"border border-line bg-surface",children:[c.jsx("summary",{className:"cursor-pointer px-3 py-2 text-xs font-medium text-muted",children:"Generated SQL"}),Object.keys(e).length>0?c.jsx("div",{"data-testid":"query-inputs",className:"grid gap-px border-t border-line bg-line sm:grid-cols-2",children:Object.entries(e).map(([a,u])=>u?c.jsxs("section",{className:"min-w-0 bg-surface px-3 py-2 text-2xs",children:[c.jsx("h3",{className:"mb-1 font-semibold text-ink",children:a}),[["Metrics",u.metrics],["Dimensions",u.dimensions],["Filters",u.filters]].map(([f,h])=>h!=null&&h.length?c.jsxs("p",{className:"truncate text-muted",title:h.join(", "),children:[c.jsxs("strong",{className:"font-medium text-faint",children:[f,":"]})," ",h.join(", ")]},f):null)]},a):null)}):null,c.jsx("pre",{"data-testid":"query-debug",className:"max-h-72 overflow-auto whitespace-pre-wrap border-t border-line px-3 py-2 font-mono text-2xs text-muted",children:i.map((a,u)=>Xm[a.kind]?c.jsx("span",{className:Xm[a.kind],"data-token":a.kind,children:a.value},u):a.value)})]})}function L_(n){return{format:n==null?void 0:n.format,type:n==null?void 0:n.type}}function U_(n,e){return n&&e.some(t=>t.ref===n)?n:null}function ey(n,e){return[...n].sort((t,i)=>String(t[e]??"").localeCompare(String(i[e]??"")))}function $_(n,e){return{from:e==="second"||e==="minute"||e==="hour"?n.from.replace(" ","T"):nf(n.from),to:hS(n.to,e)}}function P_(){var Cr,Fr,ue,Oe,rt,Nt,Un,sr,Es,Ei;const{state:n,dispatch:e,catalog:t,backend:i,dashboard:a}=ls(),[u,f]=D.useState(null),h=t.models.find(Se=>Se.name===n.model),m=D.useMemo(()=>Cs(t,a,n.dashboardTab),[t,a,n.dashboardTab]);D.useEffect(()=>{f(null)},[n.dashboardTab,n.model]);const g=(m==null?void 0:m.metrics)??(h==null?void 0:h.metrics)??[],v=new Set(g.map(Se=>Se.ref)),x=ji(t,n.model).filter(Se=>!m||v.has(Se.ref)),b=((Cr=m==null?void 0:m.timeDimension)==null?void 0:Cr.ref)??((Fr=h==null?void 0:h.timeDimension)==null?void 0:Fr.ref),w=g.find(Se=>Se.ref===n.selectedMetric)??x.find(Se=>Se.ref===n.selectedMetric)??g[0],j=!!w&&g.some(Se=>Se.ref===w.ref),C=D.useMemo(()=>{const Se=g.map(bn=>bn.ref);return w&&!j?[...Se,w.ref]:Se},[g,w,j]),O=D.useMemo(()=>ou(t),[t]),H=D.useMemo(()=>[...(m==null?void 0:m.filters)??[],...Os(n.filters,{timeRef:b,range:n.dateRange,types:O})],[m,n.filters,b,n.dateRange,O]),L=D.useMemo(()=>n.comparison==="off"||!n.dateRange?null:n.comparison==="year"?lS(n.dateRange):n.comparison==="custom"?n.comparisonRange??null:aS(n.dateRange),[n.comparison,n.dateRange,n.comparisonRange]),R=D.useMemo(()=>L&&b?[...(m==null?void 0:m.filters)??[],...Os(n.filters,{timeRef:b,range:L,types:O})]:null,[m,n.filters,b,L,O]),T=n.timezone,E=Se=>Se?{...Se,timezone:T}:null,I=Zn(i,C.length?E($m(C,H,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations)):null),U=Zn(i,C.length&&b?E(Pm(C,b,n.grain,H,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations,!!n.dateRange)):null),G=Zn(i,C.length&&R?E($m(C,R,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations)):null),V=Zn(i,w&&b&&R?E(Pm([w.ref],b,n.grain,R,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations,!0)):null),Q=I.error??U.error??G.error??V.error;if(!h)return c.jsx("div",{className:"p-4",children:c.jsx(Xn,{message:"No model available in this semantic layer."})});const z=((m==null?void 0:m.dimensions)??h.dimensions).filter(Se=>Se.type!=="time"),ee=U_(u,z),X=n.comparison==="year"?"Prev year":n.comparison==="custom"?"Comparison":"Prev period",ie=b?`${b}__${n.grain}`:"",ae=ie?[...C,ie]:C,re=w&&ie?[w.ref,ie]:[],se=g[0]?Fn(g[0].ref,C):w?Fn(w.ref,C):null,A=Se=>!Se||!se||Se.columns.includes(se),Y=A(I.result)?(ue=I.result)==null?void 0:ue.rows[0]:void 0,W=A(G.result)?(Oe=G.result)==null?void 0:Oe.rows[0]:void 0,_=A(U.result)?((rt=U.result)==null?void 0:rt.rows)??[]:[],F=w?Fn(w.ref,C):"",te=w?Fn(w.ref,ae):"",pe=w?Fn(w.ref,re):"",ne=ie?Fn(ie,ae):"",fe=ie?Fn(ie,re):"",Ce=ne?ey(_,ne):_,Te=Y&&F?Number(Y[F]):NaN,Ue=W&&F?Number(W[F]):void 0,lt=te?Ce.map(Se=>({x:String(Se[ne]??""),y:Number(Se[te])})):[],wt=fe?ey(((Nt=V.result)==null?void 0:Nt.rows)??[],fe):[],Bs=pe&<.length>0&&wt.length>0?(()=>{const Se=String(wt[0][fe]??""),bn=lt[0].x,cs=new Map;for(const tn of wt)cs.set(Lm(Se,String(tn[fe]??""),n.grain),Number(tn[pe]));return lt.map(tn=>({x:tn.x,y:cs.get(Lm(bn,tn.x,n.grain))??NaN}))})():[];function xn(Se){e(Se?{type:"setDateRange",range:$_(Se,n.grain)}:{type:"setDateRange",range:void 0})}return c.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[Q?c.jsx(Bi,{message:Q}):null,c.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6","data-testid":"metric-totals",children:g.length===0?c.jsx("div",{className:"col-span-full",children:c.jsx(Xn,{message:"This model has no metrics."})}):g.map(Se=>{const bn=Fn(Se.ref,C),cs=Fn(Se.ref,ae),tn=Y?Number(Y[bn]):NaN,ds=W?Number(W[bn]):void 0,Yo=Ce.map(ir=>Number(ir[cs])).filter(Number.isFinite);return c.jsx(Nr,{metric:Se.ref,label:Se.label,valueText:pt(tn,L_(Se)),delta:ds!==void 0?yy(tn,ds):null,sparkValues:Yo,selected:n.selectedMetric===Se.ref,loading:I.loading&&!Y,onSelect:ir=>e({type:"setMetric",metric:ir})},Se.ref)})}),w?c.jsx(B_,{metric:w,points:lt,comparisonPoints:L?Bs:void 0,total:Te,prevTotal:L?Ue:void 0,hasTime:!!b,loading:U.loading,activeRange:n.dateRange,comparisonLabel:X,formatLabel:Se=>uS(Se,n.grain),onBrush:xn}):null,c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(220px,1fr))] gap-0 border-l border-t border-line",children:w&&z.length?z.filter(Se=>ee===null||ee===Se.ref).map(Se=>c.jsx(F_,{dim:Se,model:h,timeDimensionRef:b,rankMetric:w,contextColumn:n.contextColumn,metricTotal:Number.isFinite(Te)?Te:void 0,comparisonRange:L??void 0,baseFilters:m==null?void 0:m.filters,baseSegments:m==null?void 0:m.segments,usePreaggregations:m==null?void 0:m.usePreaggregations,expanded:ee===Se.ref,onExpandedChange:bn=>f(bn?Se.ref:null)},Se.ref)):c.jsx(Xn,{message:"No categorical dimensions to break down."})}),c.jsx(au,{queries:{Totals:(Un=I.result)==null?void 0:Un.sql,Series:(sr=U.result)==null?void 0:sr.sql,Comparison:(Es=G.result)==null?void 0:Es.sql,"Prev series":(Ei=V.result)==null?void 0:Ei.sql}})]})}function z_(){var ie,ae;const{state:n,catalog:e,backend:t}=ls(),i=e.models.find(re=>re.name===n.model),a=(i==null?void 0:i.dimensions)??[],u=ji(e,n.model),f=D.useMemo(()=>[...(i==null?void 0:i.metrics)??[],...u],[i,u]),h=(ie=i==null?void 0:i.timeDimension)==null?void 0:ie.ref,m=re=>a.some(se=>se.ref===re),g=re=>f.some(se=>se.ref===re),v=n.pivotDims.filter(m),x=n.pivotMetrics.filter(g),b=g(n.selectedMetric)?n.selectedMetric:(ae=i==null?void 0:i.metrics[0])==null?void 0:ae.ref,w=x.length?x:b?[b]:[],[j,C]=D.useState(null),O=D.useMemo(()=>sf(a),[a]),H=D.useMemo(()=>Os(n.filters,{timeRef:h,range:n.dateRange,types:O}),[n.filters,h,n.dateRange,O]),L=j??(w[0]?{ref:w[0],dir:"desc"}:null),R=L?[`${L.ref} ${L.dir.toUpperCase()}`]:void 0,T=w.length||v.length?gS(w,v,H,R,500):null,E=T?{...T,timezone:n.timezone}:null,{result:I,loading:U,error:G}=Zn(t,E),V=D.useMemo(()=>new Map(f.map(re=>[re.ref,re])),[f]),Q=D.useMemo(()=>{const re=new Map;for(const se of[...v,...w])re.set(Sr(se),se);return re},[v,w]),z=[...v.map(re=>{var se;return{key:Sr(re),label:((se=a.find(A=>A.ref===re))==null?void 0:se.label)??Le(re),numeric:!1}}),...w.map(re=>{var se;return{key:Sr(re),label:((se=V.get(re))==null?void 0:se.label)??Le(re),numeric:!0,sortable:!0}})];function ee(re){const se=Q.get(re);se&&C(A=>A&&A.ref===se?{ref:se,dir:A.dir==="desc"?"asc":"desc"}:{ref:se,dir:"desc"})}function X(re,se){if(re.numeric){const A=V.get(Q.get(re.key)??"");return pt(se,{format:A==null?void 0:A.format,type:A==null?void 0:A.type})}return se==null||se===""?"—":String(se)}return i?c.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[G?c.jsx(Bi,{message:G}):z.length===0?c.jsx(Xn,{title:"Nothing selected",message:"Pick at least one metric or dimension above."}):c.jsx(Ho,{columns:z,rows:(I==null?void 0:I.rows)??[],loading:U,sortKey:L?Sr(L.ref):void 0,sortDir:L==null?void 0:L.dir,onSort:ee,renderCell:X}),c.jsx(au,{queries:{Pivot:I==null?void 0:I.sql}})]}):c.jsx("div",{className:"p-4",children:c.jsx(Xn,{message:"No model available."})})}const Dn={top:12,right:14,bottom:26,left:44};function V_(n,e,t=4){if(!(e>n))return[n];const i=(e-n)/(t-1);return Array.from({length:t},(a,u)=>n+i*u)}function Zv({data:n,height:e=200,ariaLabel:t,selectedLabel:i,onSelect:a}){const u=D.useRef(null),[f,h]=D.useState(640),{tip:m,handlers:g}=Dr();D.useEffect(()=>{const I=u.current;if(!I||typeof ResizeObserver>"u")return;const U=new ResizeObserver(G=>{for(const V of G)h(Math.max(160,V.contentRect.width))});return U.observe(I),()=>U.disconnect()},[]);const v=n.map(I=>Number.isFinite(I.value)?I.value:0),x=Math.min(0,...v),b=Math.max(0,...v),w=b-x||1,j=f-Dn.left-Dn.right,C=e-Dn.top-Dn.bottom,O=I=>Dn.top+(1-(I-x)/w)*C,H=O(0),L=j/Math.max(n.length,1),R=Math.max(8,Math.min(48,L*.62)),T=V_(x,b,4),E=t||`Bar chart, ${n.length} categories, up to ${Wt(b)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:u,role:"img","aria-label":E,className:"h-[200px] w-full overflow-hidden",viewBox:`0 0 ${f} ${e}`,children:[T.map((I,U)=>{const G=O(I);return c.jsxs("g",{children:[c.jsx("line",{x1:Dn.left,x2:f-Dn.right,y1:G,y2:G,className:"stroke-line"}),c.jsx("text",{x:Dn.left-6,y:G+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(I)})]},U)}),c.jsx("line",{x1:Dn.left,x2:f-Dn.right,y1:H,y2:H,className:"stroke-line"}),n.map((I,U)=>{const G=I.filterValue??I.label,V=v[U]??0,Q=O(V),z=Math.abs(Q-H),ee=Dn.left+L*U+(L-R)/2,X=Math.min(Q,H);return c.jsxs("g",{role:a?"button":void 0,tabIndex:a?0:void 0,"aria-label":a?`Filter to ${I.label}`:void 0,"aria-pressed":a?i===G:void 0,onClick:a?()=>a(G):void 0,onKeyDown:a?ie=>{(ie.key==="Enter"||ie.key===" ")&&a(G)}:void 0,className:a?"cursor-pointer":void 0,children:[c.jsx("rect",{x:ee,y:X,width:R,height:z,"data-label":I.label,"data-value":V,"data-tone":V<0?"negative":"positive",className:i===G?"fill-accent":V<0?"fill-danger":"fill-chart-primary",...g(`${I.label}: ${pt(V)}`)}),c.jsx("text",{x:ee+R/2,y:e-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:I.label.slice(0,8)})]},`${G}-${U}`)})]}),c.jsx(rr,{tip:m})]})}const pd=7;function yn(n){return`var(--viz-${(n%pd+pd)%pd+1})`}function Ts(n,e,t=4){if(!(e>n))return[n];const i=(e-n)/(t-1);return Array.from({length:t},(a,u)=>n+i*u)}function us(n,e,t){if(!n||typeof ResizeObserver>"u")return()=>{};const i=new ResizeObserver(a=>{for(const u of a)t(Math.max(e,u.contentRect.width))});return i.observe(n),()=>i.disconnect()}const Pt={top:12,right:14,bottom:30,left:48};function Xv({points:n,height:e=240,xLabel:t,yLabel:i,formatX:a=Wt,formatY:u=Wt,ariaLabel:f}){const h=D.useRef(null),[m,g]=D.useState(640),{tip:v,handlers:x}=Dr();D.useEffect(()=>us(h.current,200,g),[]);const b=n.filter(z=>Number.isFinite(z.x)&&Number.isFinite(z.y));if(b.length===0)return c.jsx("div",{className:"grid h-[240px] place-items-center text-xs text-faint",children:"No points to chart."});const w=[...new Set(b.map(z=>z.series??""))],j=b.map(z=>z.x),C=b.map(z=>z.y),O=Math.min(...j),H=Math.max(...j),L=Math.min(...C),R=Math.max(...C),T=H-O||1,E=R-L||1,I=m-Pt.left-Pt.right,U=e-Pt.top-Pt.bottom,G=z=>Pt.left+(z-O)/T*I,V=z=>Pt.top+(1-(z-L)/E)*U,Q=f||`Scatter plot, ${b.length} points${t&&i?` of ${i} by ${t}`:""}`;return c.jsxs(c.Fragment,{children:[w.length>1?c.jsx("div",{className:"mb-1 flex flex-wrap items-center gap-3 text-2xs text-faint",children:w.map((z,ee)=>c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-full",style:{background:yn(ee)}}),z||"(default)"]},z||"(default)"))}):null,c.jsxs("svg",{ref:h,role:"img","aria-label":Q,className:"w-full overflow-hidden",style:{height:e},viewBox:`0 0 ${m} ${e}`,children:[Ts(L,R,4).map((z,ee)=>{const X=V(z);return c.jsxs("g",{children:[c.jsx("line",{x1:Pt.left,x2:m-Pt.right,y1:X,y2:X,className:"stroke-line"}),c.jsx("text",{x:Pt.left-6,y:X+3,textAnchor:"end",className:"fill-faint text-[10px]",children:u(z)})]},`y${ee}`)}),Ts(O,H,5).map((z,ee)=>{const X=G(z);return c.jsxs("g",{children:[c.jsx("line",{x1:X,x2:X,y1:Pt.top,y2:e-Pt.bottom,className:"stroke-line"}),c.jsx("text",{x:X,y:e-14,textAnchor:"middle",className:"fill-faint text-[10px]",children:a(z)})]},`x${ee}`)}),t?c.jsx("text",{x:Pt.left+I/2,y:e-2,textAnchor:"middle",className:"fill-muted text-[10px]",children:t}):null,i?c.jsx("text",{x:10,y:Pt.top+U/2,textAnchor:"middle",transform:`rotate(-90 10 ${Pt.top+U/2})`,className:"fill-muted text-[10px]",children:i}):null,b.map((z,ee)=>c.jsx("circle",{cx:G(z.x),cy:V(z.y),r:3.5,fill:yn(w.indexOf(z.series??"")),fillOpacity:.75,"data-x":z.x,"data-y":z.y,"data-label":z.label,...x(c.jsx(os,{title:z.label??z.series,rows:[{label:t??"x",value:a(z.x)},{label:i??"y",value:u(z.y)}]}))},ee))]}),c.jsx(rr,{tip:v})]})}function W_(){const n=Cv();return c.jsx("span",{className:"text-2xs text-faint",children:n?"Querying…":"Live data"})}function md(n,e){for(const i of n.models){const a=i.metrics.find(u=>u.ref===e);if(a)return{format:a.format,type:a.type}}const t=n.graphMetrics.find(i=>i.ref===e);return{format:t==null?void 0:t.format,type:t==null?void 0:t.type}}function H_(n){return sf(n.models.flatMap(e=>e.dimensions))}function G_(n){var t;const e=(t=n.encoding)==null?void 0:t.y;return(Array.isArray(e)?e[0]:e)??n.query.metrics[0]??""}function Y_({chart:n,columns:e,rows:t}){const i=w_(e,t);return c.jsx("a",{href:`data:text/csv;charset=utf-8,${encodeURIComponent(i)}`,download:`${n.id}.csv`,className:"border border-line px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Export CSV"})}function Q_({chart:n,columns:e,rows:t,loading:i,onDrill:a}){const u=e.map(g=>({key:g,label:Le(g),numeric:n.query.metrics.some(v=>xr(v,e)===g)})),f=i_(n),h=f?xr(f,e):void 0,m=!!f;return c.jsxs("div",{className:"border-t border-line bg-surface-soft p-3","data-testid":`chart-details-${n.id}`,children:[c.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[c.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wide text-faint",children:"Drill details"}),m&&f&&h?c.jsxs("span",{className:"text-2xs text-faint",children:["Choose a ",Le(f)," value to filter every chart."]}):null]}),c.jsx(Ho,{columns:u,rows:t,loading:i,pageSize:20,renderCell:(g,v)=>String(v??"—")}),m&&f&&h&&t.length?c.jsx("div",{className:"mt-2 flex flex-wrap gap-1","aria-label":`Drill by ${Le(f)}`,children:t.slice(0,12).map((g,v)=>{const x=Xl(g[h]);return c.jsxs("button",{type:"button",onClick:()=>a(f,x),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-accent hover:text-ink",children:["Filter to ",rs(x)]},`${String(x)}-${v}`)})}):null]})}function K_({document:n,chart:e,catalog:t,backend:i,state:a,setFilters:u,setRange:f}){var z,ee,X,ie,ae,re,se;const[h,m]=D.useState(!1),g=D.useMemo(()=>H_(t),[t]),v=D.useMemo(()=>h_(n,e,a.filters,g,a.ranges,a),[e,n,a,g]),x=Zn(i,v),b=((z=x.result)==null?void 0:z.rows)??[],w=((ee=x.result)==null?void 0:ee.columns)??[],j=e.query.dimensions??[],C=((X=e.encoding)==null?void 0:X.x)??j[0]??"",O=l_(e),H=O[0]??G_(e),L=xr(C,w),R=cf(n,e,a),T=zv(e,g),E=o_(e,C),I=((ie=e.title)==null?void 0:ie.trim())||Le(e.id),U=[(ae=e.encoding)==null?void 0:ae.color,...j.filter(A=>A!==C)].filter((A,Y,W)=>!!A&&W.indexOf(A)===Y),G=c_(e,C,U),V=U.map(A=>xr(A,w));let Q;if(x.loading&&!x.result)Q=c.jsx(af,{title:`Loading ${I}`});else if(x.error)Q=c.jsx(Bi,{title:`Could not load ${I}`,message:x.error});else if(!b.length)Q=c.jsx(Xn,{title:I,message:"The query returned no rows."});else if(j.length)if(T==="scatter"||T==="point"){const A=(re=e.encoding)!=null&&re.color?xr(e.encoding.color,w):V[0];Q=c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3",children:O.map(Y=>{const W=xr(Y,w),_=b.map(F=>({x:Number(F[L]),y:Number(F[W]),label:String(F[L]??""),series:A?String(F[A]??""):void 0}));return c.jsxs("div",{className:"min-w-0",children:[O.length>1?c.jsx("h3",{className:"mb-1 text-2xs font-semibold text-muted",children:Le(Y)}):null,c.jsx(Xv,{points:_,xLabel:Le(C),yLabel:Le(Y),formatY:F=>pt(F,md(t,Y)),ariaLabel:`${I}, ${Le(Y)} by ${Le(C)}, ${_.length} points`})]},Y)})})}else T==="line"||T==="area"?Q=c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3",children:O.map(A=>{const Y=y_(b,L,xr(A,w),V),W=Y[0]??{label:"Current",points:[]},_=md(t,A);return c.jsxs("div",{className:"min-w-0",children:[O.length>1?c.jsx("h3",{className:"mb-1 text-2xs font-semibold text-muted",children:Le(A)}):null,c.jsx(Go,{points:W.points,seriesLabel:W.label,additionalSeries:Y.slice(1),formatValue:F=>pt(F,_),ariaLabel:`${I}, ${Le(A)}, ${Y.length} series and ${W.points.length} buckets`,onBrush:E?F=>f(C,F):void 0})]},A)})}):Q=c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3",children:O.map(A=>{const Y=xr(A,w),W=m_(b,L,Y,V);return W.map((_,F)=>{const te=_.data.slice(0,30),pe=O.length>1||W.length>1,ne=[O.length>1?Le(A):"",W.length>1?_.label:""].filter(Boolean).join(" · ");return c.jsxs("div",{className:"min-w-0",children:[pe?c.jsx("h3",{className:"mb-1 text-2xs font-semibold text-muted",children:ne}):null,c.jsx(Zv,{data:te,ariaLabel:`${I}, ${ne||Le(A)}, ${te.length} categories`,selectedLabel:R.filters[C],onSelect:G?fe=>{u(u_(e,C,fe,U,_.filterValues)),m(!0)}:void 0})]},`${A}-${_.label}-${F}`)})})});else{const A=b[0];Q=c.jsx("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:e.query.metrics.map(Y=>c.jsx(Nr,{metric:Y,label:Le(Y),value:A[xr(Y,w)],format:md(t,Y)},Y))})}return c.jsxs("article",{className:"min-w-0 overflow-hidden border border-line bg-surface","data-testid":"dashboard-chart","data-chart-id":e.id,children:[c.jsxs("header",{className:"flex min-h-12 flex-wrap items-center justify-between gap-2 border-b border-line px-3 py-2",children:[c.jsxs("div",{className:"min-w-0",children:[c.jsx("h2",{className:"truncate text-sm font-semibold text-ink",children:I}),c.jsxs("p",{className:"text-2xs text-faint",children:[Le(H),C?` by ${Le(C)}`:""]})]}),c.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.jsx("button",{type:"button","aria-expanded":h,onClick:()=>m(A=>!A),className:"border border-line px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:h?"Hide details":"Drill details"}),c.jsx("a",{href:p_(n,e,a,g,t),className:"border border-line px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Explore from here"}),c.jsx(Y_,{chart:e,columns:w,rows:b})]})]}),c.jsx("div",{className:"min-h-64 overflow-hidden p-3",children:Q}),h?c.jsx(Q_,{chart:e,columns:w,rows:b,loading:x.loading,onDrill:(A,Y)=>u({[A]:Y})}):null,(se=x.result)!=null&&se.sql?c.jsx("div",{className:"border-t border-line px-3 py-2",children:c.jsx(au,{queries:{Query:x.result.sql}})}):null]})}function J_({document:n,state:e,onLoad:t}){const[i,a]=D.useState(""),[u,f]=D.useState(()=>x_(n)),[h,m]=D.useState(!1);function g(v){f(v),m(!b_(n,v))}return c.jsxs("details",{className:"relative",children:[c.jsx("summary",{className:"cursor-pointer list-none border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Saved views"}),c.jsxs("div",{className:"absolute right-0 z-50 mt-1 w-72 border border-line bg-surface p-3 shadow-[var(--shadow)]",children:[c.jsx("p",{className:"mb-2 text-2xs text-faint",children:"Stored only in this browser. Nothing is written to the server."}),c.jsxs("div",{className:"flex gap-1",children:[c.jsx("input",{value:i,onChange:v=>a(v.target.value),placeholder:"View name","aria-label":"Saved view name",className:"min-w-0 flex-1 border border-line bg-bg px-2 py-1 text-xs text-ink"}),c.jsx("button",{type:"button",disabled:!i.trim(),onClick:()=>{const v=[...u.filter(x=>x.name!==i.trim()),{name:i.trim(),state:e}];g(v),a("")},className:"border border-line px-2 py-1 text-2xs text-muted hover:text-ink disabled:opacity-40",children:"Save"})]}),h?c.jsx("p",{role:"alert",className:"mt-2 text-2xs text-danger",children:"Browser storage is unavailable."}):null,c.jsx("div",{className:"mt-2 flex flex-col gap-1",children:u.length?u.map(v=>c.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-line pt-1",children:[c.jsx("button",{type:"button",onClick:()=>t(v.state),className:"min-w-0 flex-1 truncate text-left text-xs text-muted hover:text-ink",children:v.name}),c.jsx("button",{type:"button","aria-label":`Delete saved view ${v.name}`,onClick:()=>g(u.filter(x=>x.name!==v.name)),className:"text-2xs text-faint hover:text-danger",children:"Delete"})]},v.name)):c.jsx("span",{className:"text-2xs text-faint",children:"No local views yet."})})]})]})}function q_(){const[n,e]=D.useState(!1);return c.jsx("button",{type:"button",title:"Copies the active tab, filters, and brushed ranges. Data is queried live; local saved views are not shared.",onClick:async()=>{await navigator.clipboard.writeText(window.location.href),e(!0),window.setTimeout(()=>e(!1),1200)},className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:n?"Share URL copied":"Copy share URL"})}function Z_({document:n,catalog:e,backend:t}){const[i,a]=D.useState(()=>g_(window.location.search,n)),u=n.tabs.find(b=>b.id===i.tab)??n.tabs[0];D.useEffect(()=>{window.document.title=n.title},[n.title]),D.useEffect(()=>{const b=v_(i,n);window.history.replaceState(null,"",`${window.location.pathname}${b?`?${b}`:""}`)},[n,i]);function f(b,w){var C,O;const j=eu(n,b);if((((O=(C=n.defaults)==null?void 0:C.interactions)==null?void 0:O.scope)??"dashboard")==="chart"){a(H=>{var L;return{...H,chartFilters:{...H.chartFilters??{},[j]:{...((L=H.chartFilters)==null?void 0:L[j])??{},...w}}}});return}a(H=>({...H,filters:{...H.filters,...w},filterSources:{...H.filterSources,...Object.fromEntries(Object.keys(w).map(L=>[L,j]))}}))}function h(b,w,j){var O,H;const C=eu(n,b);if((((H=(O=n.defaults)==null?void 0:O.interactions)==null?void 0:H.scope)??"dashboard")==="chart"){a(L=>{const R={...L.chartRanges??{}},T={...R[C]??{}};return j?T[w]=j:delete T[w],Object.keys(T).length?R[C]=T:delete R[C],{...L,chartRanges:R}});return}a(L=>{const R={...L.ranges},T={...L.rangeSources};return j?(R[w]=j,T[w]=C):(delete R[w],delete T[w]),{...L,ranges:R,rangeSources:T}})}const m=c.jsxs(c.Fragment,{children:[c.jsx(J_,{document:n,state:i,onLoad:a}),c.jsx(q_,{}),c.jsx($o,{}),c.jsx(W_,{})]}),g=Object.entries(i.chartFilters??{}).flatMap(([b,w])=>Object.entries(w).map(([j,C])=>({source:b,dimension:j,value:C}))),v=Object.entries(i.chartRanges??{}).flatMap(([b,w])=>Object.entries(w).map(([j,C])=>({source:b,dimension:j,range:C}))),x=Object.entries(i.filters).length||Object.entries(i.ranges).length||g.length||v.length?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"shrink-0 text-2xs font-semibold uppercase tracking-wide text-faint",children:"Filters"}),Object.entries(i.filters).map(([b,w])=>c.jsxs("button",{type:"button","aria-label":`Remove filter ${Le(b)} ${w}`,onClick:()=>a(j=>{const C={...j.filters},O={...j.filterSources};return delete C[b],delete O[b],{...j,filters:C,filterSources:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(b)," = ",w," ×"]},b)),Object.entries(i.ranges).map(([b,w])=>c.jsxs("button",{type:"button","aria-label":`Remove range ${Le(b)} ${w.from} to ${w.to}`,onClick:()=>a(j=>{const C={...j.ranges},O={...j.rangeSources};return delete C[b],delete O[b],{...j,ranges:C,rangeSources:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(b),": ",w.from,"–",w.to," ×"]},`range-${b}`)),g.map(({source:b,dimension:w,value:j})=>c.jsxs("button",{type:"button","aria-label":`Remove filter ${Le(w)} ${j} from ${b}`,onClick:()=>a(C=>{const O={...C.chartFilters??{}},H={...O[b]??{}};return delete H[w],Object.keys(H).length?O[b]=H:delete O[b],{...C,chartFilters:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(w)," = ",j," · ",b," ×"]},`chart-filter-${b}-${w}`)),v.map(({source:b,dimension:w,range:j})=>c.jsxs("button",{type:"button","aria-label":`Remove range ${Le(w)} ${j.from} to ${j.to} from ${b}`,onClick:()=>a(C=>{const O={...C.chartRanges??{}},H={...O[b]??{}};return delete H[w],Object.keys(H).length?O[b]=H:delete O[b],{...C,chartRanges:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(w),": ",j.from,"–",j.to," · ",b," ×"]},`chart-range-${b}-${w}`)),c.jsx("button",{type:"button",onClick:()=>a(b=>({...b,filters:{},ranges:{},filterSources:{},rangeSources:{},chartFilters:{},chartRanges:{}})),className:"text-2xs text-muted hover:text-ink",children:"Clear all"})]}):void 0;return c.jsx(_v,{brand:c.jsxs("div",{className:"min-w-0",children:[c.jsx("h1",{className:"truncate text-sm font-semibold text-ink",children:n.title}),c.jsx("p",{className:"text-2xs text-faint",children:"Declarative dashboard"})]}),toolbar:m,filters:x,rail:null,showRail:!1,children:c.jsxs("div",{"data-testid":"dashboard-document",className:"flex min-h-full flex-col",children:[c.jsx("nav",{className:"flex shrink-0 gap-1 overflow-x-auto border-b border-line bg-surface px-3 pt-2","aria-label":"Dashboard tabs",children:n.tabs.map(b=>c.jsx("button",{type:"button",role:"tab","aria-selected":b.id===(u==null?void 0:u.id),"data-tab-id":b.id,onClick:()=>a(w=>{var j,C;return w.tab===b.id?w:(((C=(j=n.defaults)==null?void 0:j.interactions)==null?void 0:C.scope)??"dashboard")==="dashboard"?{...w,tab:b.id}:{...w,tab:b.id,filters:{},ranges:{},filterSources:{},rangeSources:{},chartFilters:{},chartRanges:{}}}),className:"border border-b-0 border-line px-3 py-2 text-xs text-muted aria-selected:border-accent aria-selected:bg-bg aria-selected:text-ink",children:S_(b)},b.id))}),u?c.jsx("section",{className:"grid min-w-0 grid-cols-1 gap-3 p-3 xl:grid-cols-2","data-testid":"dashboard-chart-grid","data-tab-id":u.id,children:u.charts.map(b=>c.jsx(K_,{document:n,chart:b,catalog:e,backend:t,state:i,setFilters:w=>f(b,w),setRange:(w,j)=>h(b,w,j)},b.id))}):c.jsx(Xn,{title:"No dashboard tabs",message:"This dashboard document has no tabs to render."})]})})}function ty(){const n=Cv();return c.jsxs("span",{role:"status","aria-live":"polite","aria-atomic":"true",className:"flex items-center gap-1.5 text-2xs text-faint",title:n?"Updating data":"Data is up to date",children:[n?c.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",className:"spinner size-3.5 text-accent",fill:"none",stroke:"currentColor",strokeWidth:"3",children:c.jsx("path",{d:"M12 3a9 9 0 1 0 9 9",strokeLinecap:"round"})}):c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-full bg-accent"}),c.jsx("span",{className:"sr-only",children:n?"Updating data":"Data is up to date"})]})}function X_(){const[n,e]=D.useState(!1);return c.jsx("button",{type:"button",onClick:async()=>{await navigator.clipboard.writeText(window.location.href),e(!0),window.setTimeout(()=>e(!1),1200)},className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:n?"Copied":"Copy link"})}function dl({children:n}){return c.jsx("div",{className:"grid h-screen place-items-center bg-bg p-6",children:n})}function e2({backend:n,onAuthenticated:e}){const[t,i]=D.useState(""),[a,u]=D.useState(null),[f,h]=D.useState(!1);return c.jsxs("div",{className:"w-full max-w-sm border border-line bg-surface p-6 shadow-sm",children:[c.jsx("h1",{className:"text-base font-semibold text-ink",children:"Connect to Sidemantic"}),c.jsx("p",{className:"mt-2 text-xs leading-5 text-muted",children:"Enter the API bearer once. It is exchanged for a short-lived, HttpOnly browser session where supported, and is never placed in the URL or browser storage."}),c.jsxs("form",{className:"mt-5 space-y-3",onSubmit:async m=>{m.preventDefault(),h(!0),u(null);try{await n.createBrowserSession(t),i(""),e()}catch(g){u(g instanceof Error?g.message:String(g))}finally{h(!1)}},children:[c.jsx("label",{className:"block text-xs font-medium text-ink",htmlFor:"api-token",children:"API bearer token"}),c.jsx("input",{id:"api-token",type:"password",autoComplete:"off",required:!0,value:t,onChange:m=>i(m.target.value),className:"w-full border border-line bg-bg px-3 py-2 text-sm text-ink outline-none focus:border-accent"}),a?c.jsx("p",{className:"text-xs text-red-700",children:a}):null,c.jsx("button",{type:"submit",disabled:f||!t,className:"w-full bg-accent px-3 py-2 text-xs font-semibold text-white disabled:opacity-50",children:f?"Connecting…":"Connect"})]})]})}function t2(){const{state:n,dispatch:e,catalog:t,initial:i,dashboard:a}=ls(),u=!!a,f=n.view==="home"&&!u,h=t.models.find(R=>R.name===n.model),m=D.useMemo(()=>Cs(t,a,n.dashboardTab),[t,a,n.dashboardTab]),g=D.useMemo(()=>a?Iv(t,a,n.dashboardTab):i,[t,a,i,n.dashboardTab]),v=n.dateRange!=null||Object.keys(n.filters).length>0,x=(m==null?void 0:m.timeDimension)??(h==null?void 0:h.timeDimension),b=!!x,w=iS(x==null?void 0:x.supportedGranularities,n.grain),j=D.useMemo(()=>{const R=new Map;for(const T of t.models)for(const E of T.dimensions)R.set(E.ref,{dim:E,model:T});return R},[t]),C=Object.entries(n.filters).flatMap(([R,T])=>{const E=j.get(R);return E?[c.jsx(Od,{dim:E.dim,model:E.model,filter:T,onRemove:()=>e({type:"removeFilterDim",dim:R})},R)]:[]}),O=c.jsx(eS,{dashboardTitle:a==null?void 0:a.title,modelLabel:!f&&!u?h==null?void 0:h.label:void 0,onHome:()=>e({type:"setView",view:"home"})}),H=f?c.jsxs(c.Fragment,{children:[c.jsx($o,{}),c.jsx(ty,{})]}):c.jsxs(c.Fragment,{children:[a?c.jsx("div",{className:"flex items-center border border-line bg-surface",role:"tablist","aria-label":"Dashboard tabs",children:a.tabs.map(R=>{const T=R.id===n.dashboardTab;return c.jsx("button",{type:"button",role:"tab","aria-selected":T,className:`px-2 py-1 text-2xs ${T?"bg-accent text-white":"text-muted hover:text-ink"}`,onClick:()=>{const E=Cs(t,a,R.id);E&&e({type:"setDashboardTab",tab:E.id,model:E.model.name,metric:E.selectedMetric,grain:E.grain})},children:R.label??R.id},R.id)})}):c.jsx(Bv,{view:n.view,onChange:R=>e({type:"setView",view:R})}),c.jsx(Ov,{range:n.dateRange,disabled:!b,onChange:R=>e({type:"setDateRange",range:R}),comparison:n.comparison,comparisonRange:n.comparisonRange,onComparisonChange:(R,T)=>e({type:"setComparison",comparison:R,range:T})}),c.jsx(Td,{grain:n.grain,options:w,disabled:!b,onChange:R=>e({type:"setGrain",grain:R})}),c.jsx(qS,{timezone:n.timezone,disabled:!b,onChange:R=>e({type:"setTimezone",timezone:R})}),v?c.jsx("button",{type:"button",onClick:()=>e({type:"reset",initial:g}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Reset"}):null,c.jsx(X_,{}),c.jsx($o,{}),c.jsx(ty,{})]}),L=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"shrink-0 text-xs font-medium text-muted",children:"Filters"}),C.length?C:c.jsx("span",{className:"text-2xs text-faint",children:"None"}),h?c.jsx(VS,{model:h}):null,C.length?c.jsx("button",{type:"button",onClick:()=>e({type:"clearFilters"}),className:"shrink-0 text-2xs text-muted underline-offset-2 hover:text-ink hover:underline",children:"Clear"}):null]});return c.jsx(_v,{brand:O,toolbar:H,filters:f?void 0:L,rail:c.jsx(HS,{}),showRail:!f&&!u,openRailRequest:n.view==="pivot",drawer:f?void 0:c.jsx(t_,{}),children:c.jsxs(GS,{children:[n.view==="home"?c.jsx(__,{}):null,n.view==="explore"?c.jsx(P_,{}):null,n.view==="pivot"?c.jsx(z_,{}):null]},n.view)})}function n2(){const[n,e]=D.useState(!1),t=D.useMemo(()=>new X1({transport:"json",onUnauthorized:()=>e(!0)}),[]),[i,a]=D.useState(null),[u,f]=D.useState(null),[h,m]=D.useState(0),g=s_(window.location.pathname,window.location.search);return D.useEffect(()=>{let v=!0;return Promise.all([t.getCatalog(),g?Promise.resolve(null):t.getDashboard()]).then(([x,b])=>v&&a({catalog:x,dashboard:b})).catch(x=>v&&f(x instanceof Error?x.message:String(x))),()=>{v=!1}},[t,g,h]),n?c.jsx(dl,{children:c.jsx(e2,{backend:t,onAuthenticated:()=>{e(!1),f(null),m(v=>v+1)}})}):u?c.jsx(dl,{children:c.jsx(Bi,{title:"Could not load semantic layer",message:u})}):i?i.catalog.models.length?i.dashboard?c.jsx(Z_,{document:i.dashboard,catalog:i.catalog,backend:t}):c.jsx(RS,{catalog:i.catalog,backend:t,children:c.jsx(t2,{})}):c.jsx(dl,{children:c.jsx(Xn,{title:"Empty semantic layer",message:"No models were found."})}):c.jsx(dl,{children:c.jsx(af,{title:"Loading semantic layer",message:"Reading models and metrics…"})})}const Zt={top:14,right:48,bottom:26,left:48};function r2({data:n,barLabel:e="Bars",lineLabel:t="Line",height:i=220,formatBar:a=pt,formatLine:u=pt,ariaLabel:f}){const h=D.useRef(null),[m,g]=D.useState(640),{tip:v,handlers:x}=Dr();if(D.useEffect(()=>us(h.current,240,g),[]),n.length===0)return c.jsx("div",{className:"grid h-[220px] place-items-center text-xs text-faint",children:"No data to chart."});const b=n.map(ae=>Number.isFinite(ae.bar)?ae.bar:0),w=n.map(ae=>Number.isFinite(ae.line)?ae.line:0),j=Math.min(0,...b),C=Math.max(0,...b),O=C-j||1,H=Math.min(...w),L=Math.max(...w),R=L-H||1,T=m-Zt.left-Zt.right,E=i-Zt.top-Zt.bottom,I=ae=>Zt.top+(1-(ae-j)/O)*E,U=ae=>Zt.top+(1-(ae-H)/R)*E,G=T/n.length,V=Math.max(8,Math.min(48,G*.55)),Q=ae=>Zt.left+G*ae+G/2,z=I(0),ee=n.map((ae,re)=>`${Q(re).toFixed(1)},${U(w[re]).toFixed(1)}`).join(" L "),X=yn(1),ie=f||`Combo chart, ${n.length} categories: ${e} bars with a ${t} line`;return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"mb-1 flex items-center gap-3 text-2xs text-faint",children:[c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block h-2 w-3 bg-chart-primary"})," ",e]}),c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block h-0.5 w-3",style:{background:X}})," ",t]})]}),c.jsxs("svg",{ref:h,role:"img","aria-label":ie,className:"w-full overflow-hidden",style:{height:i},viewBox:`0 0 ${m} ${i}`,children:[Ts(j,C,4).map((ae,re)=>{const se=I(ae);return c.jsxs("g",{children:[c.jsx("line",{x1:Zt.left,x2:m-Zt.right,y1:se,y2:se,className:"stroke-line"}),c.jsx("text",{x:Zt.left-6,y:se+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(ae)})]},re)}),Ts(H,L,4).map((ae,re)=>c.jsx("text",{x:m-Zt.right+6,y:U(ae)+3,textAnchor:"start",className:"text-[10px]",fill:X,children:u(ae)},re)),c.jsx("line",{x1:Zt.left,x2:m-Zt.right,y1:z,y2:z,className:"stroke-line"}),n.map((ae,re)=>{const se=b[re],A=I(se);return c.jsxs("g",{children:[c.jsx("rect",{x:Q(re)-V/2,y:Math.min(A,z),width:V,height:Math.abs(A-z),"data-label":ae.label,"data-bar":se,"data-line":w[re],className:se<0?"fill-danger":"fill-chart-primary",...x(c.jsx(os,{title:ae.label,rows:[{label:e,value:a(se),swatch:"var(--chart-primary)"},{label:t,value:u(w[re]),swatch:X}]}))}),c.jsx("text",{x:Q(re),y:i-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:ae.label.slice(0,8)})]},ae.label)}),c.jsx("path",{d:`M ${ee}`,fill:"none",stroke:X,strokeWidth:1.75}),n.map((ae,re)=>c.jsx("circle",{cx:Q(re),cy:U(w[re]),r:3,fill:X,...x(c.jsx(os,{title:ae.label,rows:[{label:e,value:a(b[re]),swatch:"var(--chart-primary)"},{label:t,value:u(w[re]),swatch:X}]}))},ae.label))]}),c.jsx(rr,{tip:v})]})}const s2={primary:"border-accent bg-accent-soft font-medium text-accent hover:bg-accent hover:text-surface",secondary:"border-line bg-surface text-ink hover:bg-surface-soft",ghost:"border-transparent bg-transparent text-muted hover:bg-surface-soft hover:text-ink",danger:"border-danger bg-danger-soft font-medium text-danger hover:bg-danger hover:text-surface"};function No({variant:n="secondary",size:e="md",type:t="button",className:i,...a}){const u=e==="sm"?"h-6 px-2.5 text-2xs":"h-7 px-3 text-xs";return c.jsx("button",{type:t,"data-variant":n,className:`inline-flex items-center justify-center rounded-full border ${u} ${s2[n]} disabled:pointer-events-none disabled:opacity-50 ${i??""}`,...a})}function i2(n,e){const t=e.trim().toLowerCase();return t?n.filter(i=>i.value.toLowerCase().includes(t)||(i.label??"").toLowerCase().includes(t)):n}function ny(n){const{options:e,placeholder:t="Search…",ariaLabel:i,disabled:a,maxVisible:u=50}=n,f=D.useId(),h=D.useRef(null),[m,g]=D.useState(!1),[v,x]=D.useState(""),[b,w]=D.useState(0),j=D.useMemo(()=>i2(e,v).slice(0,u),[e,v,u]),C=n.multiple?n.values:n.value!=null?[n.value]:[],O=new Set(C),H=I=>{var U;return((U=e.find(G=>G.value===I))==null?void 0:U.label)??I};D.useEffect(()=>{if(!m)return;function I(U){h.current&&!h.current.contains(U.target)&&g(!1)}return document.addEventListener("mousedown",I,!0),()=>document.removeEventListener("mousedown",I,!0)},[m]);function L(I){if(I){if(n.multiple){const U=O.has(I.value)?n.values.filter(G=>G!==I.value):[...n.values,I.value];n.onChange(U);return}n.onChange(I.value),x(""),g(!1)}}function R(){n.multiple?n.onChange([]):n.onChange(null),x("")}function T(I){I.key==="ArrowDown"?(I.preventDefault(),g(!0),w(U=>Math.min(U+1,j.length-1))):I.key==="ArrowUp"?(I.preventDefault(),w(U=>Math.max(U-1,0))):I.key==="Enter"?(I.preventDefault(),m&&L(j[b])):I.key==="Escape"?g(!1):I.key==="Backspace"&&n.multiple&&!v&&n.values.length&&n.onChange(n.values.slice(0,-1))}const E=!n.multiple&&n.value!=null?H(n.value):t;return c.jsxs("div",{ref:h,className:"relative inline-flex min-w-40 flex-wrap items-center gap-1 text-xs",children:[n.multiple?n.values.map(I=>c.jsxs("span",{"data-chip":I,className:"inline-flex items-center gap-1 rounded-full bg-surface-soft px-2 py-0.5 leading-4 text-muted",children:[c.jsx("span",{className:"max-w-32 truncate",children:H(I)}),c.jsx("button",{type:"button","aria-label":`Remove ${H(I)}`,disabled:a,onClick:()=>n.onChange(n.values.filter(U=>U!==I)),className:"text-faint hover:text-ink",children:"×"})]},I)):null,c.jsxs("span",{className:"relative min-w-28 flex-1",children:[c.jsx("input",{type:"text",role:"combobox","aria-expanded":m,"aria-controls":f,"aria-autocomplete":"list","aria-activedescendant":m&&j[b]?`${f}-${b}`:void 0,"aria-label":i,disabled:a,placeholder:E,value:v,onChange:I=>{x(I.target.value),w(0),g(!0)},onFocus:()=>g(!0),onKeyDown:T,className:"h-7 w-full rounded-full border border-line bg-surface px-3 text-ink placeholder:text-faint disabled:opacity-50"}),C.length>0?c.jsx("button",{type:"button","aria-label":"Clear selection",disabled:a,onClick:R,className:"absolute right-1 top-1/2 -translate-y-1/2 px-1 text-faint hover:text-ink",children:"×"}):null]}),m?c.jsxs("ul",{id:f,role:"listbox","aria-multiselectable":n.multiple||void 0,className:"absolute left-0 top-full z-50 mt-1 max-h-56 w-full min-w-40 overflow-y-auto rounded-xl border border-line bg-surface p-1.5 shadow-[var(--shadow)]",children:[j.length===0?c.jsx("li",{className:"px-1.5 py-1 text-faint",children:"No matches"}):null,j.map((I,U)=>c.jsxs("li",{id:`${f}-${U}`,role:"option","aria-selected":O.has(I.value),"data-active":U===b||void 0,onMouseEnter:()=>w(U),onMouseDown:G=>{G.preventDefault(),L(I)},className:"cursor-pointer truncate rounded-md px-2 py-1 text-muted data-[active=true]:bg-surface-soft data-[active=true]:text-ink",children:[I.label??I.value,O.has(I.value)?c.jsx("span",{className:"float-right text-accent",children:"✓"}):null]},I.value))]}):null]})}function o2({title:n,eyebrow:e="Sidemantic",status:t,toolbar:i,children:a}){return c.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-5 text-ink sm:px-6",children:[c.jsxs("header",{className:"flex flex-wrap items-end justify-between gap-4 border-b border-line pb-4",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-xs font-medium text-faint",children:e}),c.jsx("h1",{className:"mt-1 text-2xl font-semibold text-ink",children:n})]}),t?c.jsx("div",{className:"text-sm text-muted",children:t}):null]}),i?c.jsx("section",{className:"flex flex-wrap gap-2 py-3",children:i}):null,c.jsx("section",{className:"grid gap-4 py-4",children:a})]})}const a2=["Su","Mo","Tu","We","Th","Fr","Sa"],ry=["January","February","March","April","May","June","July","August","September","October","November","December"];function e0(n,e,t){return`${String(n).padStart(4,"0")}-${String(e+1).padStart(2,"0")}-${String(t).padStart(2,"0")}`}function l2(n,e){const t=new Date(Date.UTC(n,e,1)),i=new Date(t);i.setUTCDate(1-t.getUTCDay());const a=[],u=new Date(i);do{const f=[];for(let h=0;h<7;h+=1)f.push({iso:e0(u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()),day:u.getUTCDate(),inMonth:u.getUTCMonth()===e}),u.setUTCDate(u.getUTCDate()+1);a.push(f)}while(u.getUTCMonth()===e);return a}function yd(){const n=new Date;return e0(n.getFullYear(),n.getMonth(),n.getDate())}function sy(n){var T;const{inline:e,ariaLabel:t,disabled:i}=n,a=n.mode==="range",u=a?((T=n.value)==null?void 0:T.from)??null:n.value,[f,h]=D.useState(()=>Number((u??yd()).slice(0,4))),[m,g]=D.useState(()=>Number((u??yd()).slice(5,7))-1),[v,x]=D.useState(null),b=D.useRef(null);function w(E){const I=new Date(Date.UTC(f,m+E,1));h(I.getUTCFullYear()),g(I.getUTCMonth())}function j(E){if(!a){n.onChange(E),b.current&&(b.current.open=!1);return}if(!v){x(E);return}const[I,U]=v<=E?[v,E]:[E,v];n.onChange({from:I,to:U}),x(null),b.current&&(b.current.open=!1)}function C(E){return a?v?E===v:n.value!=null&&E>=n.value.from&&E<=n.value.to:E===n.value}function O(E){return a?v?E===v:n.value!=null&&(E===n.value.from||E===n.value.to):E===n.value}const H=yd(),L=c.jsxs("div",{className:"w-56 select-none rounded-xl border border-line bg-surface p-2.5 text-2xs","aria-label":t??"Calendar",children:[c.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[c.jsx("button",{type:"button","aria-label":"Previous month",onClick:()=>w(-1),className:"px-1.5 py-0.5 text-muted hover:bg-surface-soft hover:text-ink",children:"‹"}),c.jsxs("span",{className:"font-medium text-ink",children:[ry[m]," ",f]}),c.jsx("button",{type:"button","aria-label":"Next month",onClick:()=>w(1),className:"px-1.5 py-0.5 text-muted hover:bg-surface-soft hover:text-ink",children:"›"})]}),c.jsx("div",{className:"grid grid-cols-7 text-center text-faint",children:a2.map(E=>c.jsx("span",{className:"py-0.5",children:E},E))}),c.jsx("div",{role:"grid","aria-label":`${ry[m]} ${f}`,children:l2(f,m).map((E,I)=>c.jsx("div",{role:"row",className:"grid grid-cols-7",children:E.map(U=>c.jsx("button",{type:"button",role:"gridcell","aria-selected":C(U.iso),"data-date":U.iso,onClick:()=>j(U.iso),className:`py-1 text-center tnum ${O(U.iso)?"bg-accent text-surface":C(U.iso)?"bg-accent-soft text-accent":U.inMonth?"text-ink hover:bg-surface-soft":"text-faint hover:bg-surface-soft"} ${U.iso===H?"underline underline-offset-2":""}`,children:U.day},U.iso))},I))}),a&&v?c.jsxs("p",{className:"mt-1 text-faint",children:["Start ",v," — pick an end date."]}):null,n.value!=null?c.jsx("button",{type:"button",onClick:()=>n.onChange(null),className:"mt-1 w-full rounded-lg border border-line px-2 py-1 text-left text-muted hover:bg-surface-soft",children:"Clear"}):null]});if(e)return L;const R=a?n.value?`${n.value.from} → ${n.value.to}`:"Any dates":n.value??"Any date";return c.jsxs("details",{ref:b,className:"relative inline-block text-xs",children:[c.jsxs("summary",{className:`flex cursor-pointer items-center h-7 gap-1.5 rounded-full border border-line bg-surface px-3 text-ink ${i?"pointer-events-none opacity-50":""}`,children:[c.jsx("span",{className:"text-faint",children:t??"Date"}),c.jsx("span",{className:"tnum",children:R}),c.jsx("span",{"aria-hidden":"true",className:"text-faint",children:"▾"})]}),c.jsx("div",{className:"absolute left-0 z-50 mt-1 shadow-[var(--shadow)]",children:L})]})}function u2({result:n,pageSize:e=10}){const t=(n==null?void 0:n.columns)??[];return c.jsx(Ho,{columns:t.map(i=>({key:i,label:Le(i),numeric:n==null?void 0:n.sample_rows.some(a=>typeof a[i]=="number")})),rows:(n==null?void 0:n.sample_rows)??[],pageSize:e,renderCell:(i,a)=>pt(a)})}function c2({data:n,height:e=200,ariaLabel:t}){return c.jsx("div",{style:{minHeight:e},children:c.jsx(Go,{points:n.map(({label:i,value:a})=>({x:i,y:a})),formatValue:i=>pt(i),ariaLabel:t})})}const t0=Math.PI*2;function d2(n){const e=n.map((a,u)=>({...a,colorIndex:u})).filter(a=>Number.isFinite(a.value)&&a.value>0),t=e.reduce((a,u)=>a+u.value,0);if(t<=0)return[];let i=-Math.PI/2;return e.map(a=>{const u=a.value/t,f=i;return i+=u*t0,{label:a.label,value:a.value,share:u,startAngle:f,endAngle:i,colorIndex:a.colorIndex}})}function f2(n,e,t,i,a,u){const f=Math.min(u-a,t0-1e-4),h=a+f,m=f>Math.PI?1:0,g=n+i*Math.cos(a),v=e+i*Math.sin(a),x=n+i*Math.cos(h),b=e+i*Math.sin(h),w=n+t*Math.cos(h),j=e+t*Math.sin(h),C=n+t*Math.cos(a),O=e+t*Math.sin(a);return[`M ${g.toFixed(2)} ${v.toFixed(2)}`,`A ${i} ${i} 0 ${m} 1 ${x.toFixed(2)} ${b.toFixed(2)}`,`L ${w.toFixed(2)} ${j.toFixed(2)}`,`A ${t} ${t} 0 ${m} 0 ${C.toFixed(2)} ${O.toFixed(2)}`,"Z"].join(" ")}function h2({data:n,height:e=200,centerLabel:t="Total",format:i=pt,ariaLabel:a}){const u=D.useRef(null),[f,h]=D.useState(360),{tip:m,handlers:g}=Dr();D.useEffect(()=>us(u.current,220,h),[]);const v=d2(n),x=v.reduce((L,R)=>L+R.value,0),b=Math.min(e,f*.55),w=b/2,j=e/2,C=b/2-6,O=Math.max(C*.62,C-34),H=a||`Donut chart, ${v.length} segments totaling ${Wt(x)}`;return v.length===0?c.jsx("div",{className:"grid h-[200px] place-items-center text-xs text-faint",children:"No positive values to chart."}):c.jsxs("div",{ref:u,className:"flex w-full items-center gap-4",style:{height:e},children:[c.jsxs("svg",{role:"img","aria-label":H,width:b,height:e,className:"shrink-0 overflow-hidden",children:[v.map(L=>c.jsx("path",{d:f2(w,j,O,C,L.startAngle,L.endAngle),fill:yn(L.colorIndex),stroke:"var(--surface)",strokeWidth:1,"data-label":L.label,"data-value":L.value,...g(c.jsx(os,{title:L.label,rows:[{label:"Value",value:i(L.value),swatch:yn(L.colorIndex)},{label:"Share",value:`${(L.share*100).toFixed(1)}%`}]}))},L.label)),c.jsx("text",{x:w,y:j-4,textAnchor:"middle",className:"fill-ink font-mono tnum text-sm font-medium",children:Wt(x)}),c.jsx("text",{x:w,y:j+12,textAnchor:"middle",className:"fill-faint text-[10px]",children:t})]}),c.jsx("ul",{className:"min-w-0 flex-1 space-y-1 text-2xs",children:v.map(L=>c.jsxs("li",{className:"flex items-center gap-2","data-label":L.label,children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 shrink-0",style:{background:yn(L.colorIndex)}}),c.jsx("span",{className:"truncate text-muted",children:L.label}),c.jsx("span",{className:"ml-auto font-mono tnum text-ink",children:i(L.value)}),c.jsxs("span",{className:"w-10 text-right font-mono tnum text-faint",children:[(L.share*100).toFixed(1),"%"]})]},L.label))}),c.jsx(rr,{tip:m})]})}const pr={top:8,right:8,bottom:26,left:76};function iy(n,e,t){if(t!=null&&t.length)return t;const i=[];for(const a of n)i.includes(a[e])||i.push(a[e]);return i}function p2({cells:n,xLabels:e,yLabels:t,height:i=240,format:a=pt,ariaLabel:u}){const f=D.useRef(null),[h,m]=D.useState(640),{tip:g,handlers:v}=Dr();D.useEffect(()=>us(f.current,240,m),[]);const x=iy(n,"x",e),b=iy(n,"y",t);if(x.length===0||b.length===0)return c.jsx("div",{className:"grid h-[240px] place-items-center text-xs text-faint",children:"No cells to chart."});const w=new Map(n.map(I=>[`${I.x}\0${I.y}`,I.value])),j=n.map(I=>Math.abs(I.value)).filter(Number.isFinite),C=Math.max(...j,0)||1,O=h-pr.left-pr.right,H=i-pr.top-pr.bottom,L=O/x.length,R=H/b.length,T=Math.max(1,Math.ceil(x.length/Math.max(1,Math.floor(O/56)))),E=u||`Heatmap, ${x.length} by ${b.length} cells`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:f,role:"img","aria-label":E,className:"w-full overflow-hidden",style:{height:i},viewBox:`0 0 ${h} ${i}`,children:[b.map((I,U)=>c.jsx("text",{x:pr.left-6,y:pr.top+U*R+R/2+3,textAnchor:"end",className:"fill-muted text-[10px]",children:I.slice(0,12)},I)),x.map((I,U)=>U%T===0?c.jsx("text",{x:pr.left+U*L+L/2,y:i-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:I.slice(0,8)},I):null),b.map((I,U)=>x.map((G,V)=>{const Q=w.get(`${G}\0${I}`),z=Q!=null&&Number.isFinite(Q),ee=z?.06+.94*(Math.abs(Q)/C):0;return c.jsx("rect",{x:pr.left+V*L+.5,y:pr.top+U*R+.5,width:Math.max(1,L-1),height:Math.max(1,R-1),"data-x":G,"data-y":I,"data-value":z?Q:void 0,className:z&&Q<0?"fill-danger":"fill-chart-primary",fillOpacity:z?ee:.03,...v(c.jsx(os,{title:`${I} / ${G}`,rows:[{label:"Value",value:z?a(Q):"no data"}]}))},`${G}\0${I}`)}))]}),c.jsx(rr,{tip:g})]})}function m2(n,e){const t=n.filter(Number.isFinite);if(t.length===0)return[];const i=Math.min(...t),a=Math.max(...t),u=Math.max(1,Math.floor(e??Math.min(40,Math.ceil(Math.log2(t.length)+1))));if(i===a)return[{x0:i,x1:a,count:t.length}];const f=(a-i)/u,h=Array.from({length:u},(m,g)=>({x0:i+g*f,x1:i+(g+1)*f,count:0}));for(const m of t){const g=Math.min(u-1,Math.floor((m-i)/f));h[g].count+=1}return h}const Cn={top:12,right:14,bottom:26,left:44};function y2({values:n,bins:e,height:t=200,format:i=Wt,ariaLabel:a}){const u=D.useRef(null),[f,h]=D.useState(640),{tip:m,handlers:g}=Dr();D.useEffect(()=>us(u.current,160,h),[]);const v=m2(n,e);if(v.length===0)return c.jsx("div",{className:"grid h-[200px] place-items-center text-xs text-faint",children:"No numeric values to chart."});const x=Math.max(...v.map(R=>R.count),1),b=f-Cn.left-Cn.right,w=t-Cn.top-Cn.bottom,j=R=>Cn.top+(1-R/x)*w,C=b/v.length,O=Ts(0,x,4),H=Math.max(1,Math.ceil(v.length/6)),L=a||`Histogram, ${v.length} bins from ${i(v[0].x0)} to ${i(v[v.length-1].x1)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:u,role:"img","aria-label":L,className:"w-full overflow-hidden",style:{height:t},viewBox:`0 0 ${f} ${t}`,children:[O.map((R,T)=>{const E=j(R);return c.jsxs("g",{children:[c.jsx("line",{x1:Cn.left,x2:f-Cn.right,y1:E,y2:E,className:"stroke-line"}),c.jsx("text",{x:Cn.left-6,y:E+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(R)})]},T)}),v.map((R,T)=>{const E=Cn.left+C*T,I=j(R.count);return c.jsx("rect",{x:E+.5,y:I,width:Math.max(1,C-1),height:Cn.top+w-I,"data-x0":R.x0,"data-x1":R.x1,"data-count":R.count,className:"fill-chart-primary",...g(c.jsx(os,{title:`${i(R.x0)} – ${i(R.x1)}`,rows:[{label:"Count",value:R.count.toLocaleString()}]}))},T)}),v.map((R,T)=>T%H===0?c.jsx("text",{x:Cn.left+C*T,y:t-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:i(R.x0)},T):null)]}),c.jsx(rr,{tip:m})]})}function g2(n){let e=2166136261;for(let t=0;t>>0}function v2(n){let e=n||1;return()=>{e|=0,e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function x2(n,e,{width:t=640,height:i=320,iterations:a=150}={}){if(n.length===0)return[];const u=v2(g2(n.map(G=>G.id).join("\0"))),f=new Map(n.map((G,V)=>[G.id,V])),h=n.map(()=>u()*t),m=n.map(()=>u()*i),g=n.map(()=>0),v=n.map(()=>0),x=n.map(()=>0),b=[];for(const G of e){const V=f.get(G.source),Q=f.get(G.target);V==null||Q==null||V===Q||(b.push([V,Q]),x[V]+=1,x[Q]+=1)}const w=t*i,j=Math.sqrt(w/n.length);let C=Math.max(t,i)/8;const O=C/(a+1);for(let G=0;G({...G,x:H+(h[V]-L)/I*(t-H*2),y:H+(m[V]-T)/U*(i-H*2),degree:x[V]}))}function b2({nodes:n,links:e,height:t=320,ariaLabel:i}){const a=D.useRef(null),[u,f]=D.useState(640),{tip:h,handlers:m}=Dr();D.useEffect(()=>us(a.current,240,f),[]);const g=D.useMemo(()=>x2(n,e,{width:u,height:t}),[n,e,u,t]),v=D.useMemo(()=>new Map(g.map(j=>[j.id,j])),[g]),x=D.useMemo(()=>[...new Set(n.map(j=>j.group??""))],[n]),b=Math.max(...e.map(j=>j.weight??1),1);if(g.length===0)return c.jsx("div",{className:"grid h-[320px] place-items-center text-xs text-faint",children:"No nodes to chart."});const w=i||`Network graph, ${n.length} nodes and ${e.length} links`;return c.jsxs(c.Fragment,{children:[x.length>1?c.jsx("div",{className:"mb-1 flex flex-wrap items-center gap-3 text-2xs text-faint",children:x.map((j,C)=>c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-full",style:{background:yn(C)}}),j||"(default)"]},j||"(default)"))}):null,c.jsxs("svg",{ref:a,role:"img","aria-label":w,className:"w-full overflow-hidden",style:{height:t},viewBox:`0 0 ${u} ${t}`,children:[e.map((j,C)=>{const O=v.get(j.source),H=v.get(j.target);return!O||!H?null:c.jsx("line",{x1:O.x,y1:O.y,x2:H.x,y2:H.y,className:"stroke-line",strokeWidth:.75+2.25*((j.weight??1)/b),"data-source":j.source,"data-target":j.target},C)}),g.map(j=>{const C=5+Math.min(9,j.degree*1.5);return c.jsxs("g",{children:[c.jsx("circle",{cx:j.x,cy:j.y,r:C,fill:yn(x.indexOf(j.group??"")),stroke:"var(--surface)",strokeWidth:1.5,"data-id":j.id,"data-degree":j.degree,...m(c.jsx(os,{title:j.label??j.id,rows:[{label:"Connections",value:String(j.degree)},...j.group?[{label:"Group",value:j.group,swatch:yn(x.indexOf(j.group))}]:[]]}))}),c.jsx("text",{x:j.x,y:j.y-C-4,textAnchor:"middle",className:"pointer-events-none fill-muted text-[10px]",children:(j.label??j.id).slice(0,14)})]},j.id)})]}),c.jsx(rr,{tip:h})]})}function wl({value:n,options:e,onChange:t,label:i,ariaLabel:a,placeholder:u,disabled:f}){return c.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-faint",children:[i?c.jsx("span",{className:"hidden sm:inline",children:i}):null,c.jsxs("select",{"aria-label":a??i,value:n,disabled:f,onChange:h=>t(h.target.value),className:"h-7 rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50",children:[u?c.jsx("option",{value:"",disabled:!0,children:u}):null,e.map(h=>c.jsx("option",{value:h.value,children:h.label??h.value},h.value))]})]})}const un={top:12,right:14,bottom:26,left:48};function w2(n,e,t){return Math.min(Math.max(n,e),t)}function S2({labels:n,series:e,height:t=240,format:i=pt,formatLabel:a=f=>f,ariaLabel:u}){const f=D.useRef(null),[h,m]=D.useState(640),[g,v]=D.useState(null);D.useEffect(()=>us(f.current,240,m),[]);const x=n.length;if(x<2||e.length===0)return c.jsx("div",{className:"grid h-[240px] place-items-center text-xs text-faint",children:"Not enough data to chart."});const b=e.map(V=>({name:V.name,values:n.map((Q,z)=>{const ee=V.values[z];return Number.isFinite(ee)&&ee>0?ee:0})})),w=[];let j=n.map(()=>0);for(const V of b){const Q=V.values.map((z,ee)=>j[ee]+z);w.push(Q),j=Q}const C=Math.max(...j,1),O=h-un.left-un.right,H=t-un.top-un.bottom,L=V=>un.left+V/(x-1)*O,R=V=>un.top+(1-V/C)*H,T=Math.max(1,Math.ceil(x/8)),E=u||`Stacked area chart, ${e.length} series over ${x} points`;function I(V){const Q=w[V],z=V===0?n.map(()=>0):w[V-1],ee=Q.map((ie,ae)=>`${L(ae).toFixed(1)},${R(ie).toFixed(1)}`).join(" L "),X=[...z.keys()].reverse().map(ie=>`${L(ie).toFixed(1)},${R(z[ie]).toFixed(1)}`).join(" L ");return`M ${ee} L ${X} Z`}function U(V){const Q=V.currentTarget.getBoundingClientRect(),z=(V.clientX-Q.left)/Q.width*h,ee=Math.round((z-un.left)/O*(x-1));v(ee>=0&&eec.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2",style:{background:yn(Q)}}),V.name]},V.name))}),c.jsxs("svg",{role:"img","aria-label":E,className:"w-full overflow-hidden",style:{height:t},viewBox:`0 0 ${h} ${t}`,onMouseMove:U,onMouseLeave:()=>v(null),children:[Ts(0,C,4).map((V,Q)=>{const z=R(V);return c.jsxs("g",{children:[c.jsx("line",{x1:un.left,x2:h-un.right,y1:z,y2:z,className:"stroke-line"}),c.jsx("text",{x:un.left-6,y:z+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(V)})]},Q)}),b.map((V,Q)=>c.jsx("path",{d:I(Q),fill:yn(Q),fillOpacity:.8,"data-series":V.name},V.name)),g!=null?c.jsx("line",{x1:L(g),x2:L(g),y1:un.top,y2:t-un.bottom,className:"stroke-faint",strokeDasharray:"3 3"}):null,n.map((V,Q)=>Q%T===0||Q===x-1?c.jsx("text",{x:L(Q),y:t-8,textAnchor:"middle",className:"fill-faint font-mono text-[10px]",children:a(V)},V):null)]}),g!=null?c.jsxs("div",{className:"pointer-events-none absolute top-8 z-20 -translate-x-1/2 whitespace-nowrap border border-line bg-surface px-2 py-1.5 text-2xs shadow-[var(--shadow)]",style:{left:G},children:[c.jsx("div",{className:"mb-0.5 font-mono text-faint",children:a(n[g])}),b.map((V,Q)=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs("span",{className:"flex items-center gap-1 text-muted",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2",style:{background:yn(Q)}}),V.name]}),c.jsx("span",{className:"font-mono tnum text-ink",children:i(V.values[g])})]},V.name))]}):null]})}function _2({checked:n,onChange:e,label:t,ariaLabel:i,disabled:a}){return c.jsxs("label",{className:`flex items-center gap-1.5 text-xs ${a?"opacity-50":""}`,children:[c.jsx("button",{type:"button",role:"switch","aria-checked":n,"aria-label":i??t,disabled:a,onClick:()=>e(!n),"data-checked":n||void 0,className:`relative h-4 w-7 shrink-0 rounded-full border transition-colors ${n?"border-accent bg-accent":"border-line bg-surface-soft"}`,children:c.jsx("span",{"aria-hidden":"true",className:`absolute top-1/2 size-3 -translate-y-1/2 rounded-full bg-surface shadow transition-[left] ${n?"left-[14px]":"left-[2px]"}`})}),t?c.jsx("span",{className:"text-muted",children:t}):null]})}function N2({tabs:n,active:e,onChange:t,ariaLabel:i="Tabs"}){return c.jsx("div",{role:"tablist","aria-label":i,className:"inline-flex items-center gap-0.5 rounded-full border border-line bg-surface p-px",children:n.map(a=>c.jsx("button",{role:"tab",type:"button","aria-selected":e===a.key,"data-tab":a.key,"data-selected":e===a.key||void 0,onClick:()=>t(a.key),className:"inline-flex h-6 items-center rounded-full px-2.5 text-xs font-medium text-muted hover:bg-surface-soft hover:text-ink data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent",children:a.label},a.key))})}function j2({content:n,children:e,className:t}){const{tip:i,handlers:a}=Dr();return c.jsxs(c.Fragment,{children:[c.jsx("span",{className:t??"inline-flex",...a(n),children:e}),c.jsx(rr,{tip:i})]})}function k2(n){let e=0;return n.map(t=>{const i=Number.isFinite(t.value)?t.value:0;if(t.isTotal)return e=i,{...t,value:i,start:0,end:i};const a=e;return e+=i,{...t,value:i,start:a,end:e}})}const cn={top:12,right:14,bottom:26,left:48};function I2({data:n,height:e=220,format:t=pt,ariaLabel:i}){const a=D.useRef(null),[u,f]=D.useState(640),{tip:h,handlers:m}=Dr();D.useEffect(()=>us(a.current,200,f),[]);const g=k2(n);if(g.length===0)return c.jsx("div",{className:"grid h-[220px] place-items-center text-xs text-faint",children:"No steps to chart."});const v=g.flatMap(E=>[E.start,E.end]),x=Math.min(0,...v),b=Math.max(0,...v),w=b-x||1,j=u-cn.left-cn.right,C=e-cn.top-cn.bottom,O=E=>cn.top+(1-(E-x)/w)*C,H=j/g.length,L=Math.max(10,Math.min(56,H*.62)),R=Ts(x,b,4),T=i||`Waterfall chart, ${g.length} steps ending at ${t(g[g.length-1].end)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:a,role:"img","aria-label":T,className:"w-full overflow-hidden",style:{height:e},viewBox:`0 0 ${u} ${e}`,children:[R.map((E,I)=>{const U=O(E);return c.jsxs("g",{children:[c.jsx("line",{x1:cn.left,x2:u-cn.right,y1:U,y2:U,className:"stroke-line"}),c.jsx("text",{x:cn.left-6,y:U+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(E)})]},I)}),c.jsx("line",{x1:cn.left,x2:u-cn.right,y1:O(0),y2:O(0),className:"stroke-faint"}),g.map((E,I)=>{const U=cn.left+H*I+(H-L)/2,G=O(E.start),V=O(E.end),Q=E.isTotal?"total":E.value<0?"negative":"positive",z=E.isTotal?"fill-faint":E.value<0?"fill-danger":"fill-chart-primary",ee=g[I+1];return c.jsxs("g",{children:[c.jsx("rect",{x:U,y:Math.min(G,V),width:L,height:Math.max(1,Math.abs(V-G)),"data-label":E.label,"data-value":E.value,"data-tone":Q,className:z,...m(c.jsx(os,{title:E.label,rows:E.isTotal?[{label:"Total",value:t(E.end)}]:[{label:"Change",value:t(E.value)},{label:"Running",value:t(E.end)}]}))}),ee?c.jsx("line",{x1:U+L,x2:cn.left+H*(I+1)+(H-L)/2,y1:V,y2:V,className:"stroke-faint",strokeDasharray:"3 3"}):null,c.jsx("text",{x:U+L/2,y:e-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:E.label.slice(0,9)})]},`${E.label}-${I}`)})]}),c.jsx(rr,{tip:h})]})}function oy(n){return n==null?"∅":String(n)}function M2(n){const e=typeof n=="number"?n:Number(n);return Number.isFinite(e)?e:Number.NaN}function D2(n,e){const t=[],i=[],a=new Map;for(const u of n){const f=oy(u[e.x]),h=oy(u[e.series]);t.includes(f)||t.push(f),i.includes(h)||i.push(h),a.set(`${h}\0${f}`,M2(u[e.y]))}return{labels:t,series:i.map(u=>({name:u,values:t.map(f=>a.get(`${u}\0${f}`)??0)}))}}const C2=[{dimension:"orders.region",title:"Customer Region",rows:[["East",83262],["South",80579],["West",71561],["North",52889]].map(([n,e])=>({value:String(n),metric:Number(e)}))},{dimension:"orders.status",title:"Order Status",rows:[["completed",170379],["cancelled",64637],["pending",53275]].map(([n,e])=>({value:String(n),metric:Number(e)}))},{dimension:"products.category",title:"Product Category",rows:[["Electronics",202015],["Furniture",83848],["Office Supplies",2428]].map(([n,e])=>({value:String(n),metric:Number(e)}))},{dimension:"customers.name",title:"Top Customers",rows:[["Bob Smith",46690],["Carol Davis",42227],["Henry Taylor",41633],["Grace Lee",41035],["Frank Brown",33890],["David Wilson",29928],["Alice Johnson",27114],["Emma Martinez",24802]].map(([n,e])=>({value:String(n),metric:Number(e)}))}],F2=[{key:"region",label:"Region",sortable:!0},{key:"revenue",label:"Revenue",numeric:!0,sortable:!0},{key:"orders",label:"Orders",numeric:!0,sortable:!0}],ay=Array.from({length:17},(n,e)=>({region:["East","South","West","North"][e%4],revenue:91e3-e*2875,orders:420-e*11})),hf=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug"],O2=hf.flatMap((n,e)=>[{month:n,plan:"Basic",revenue:120+e*26},{month:n,plan:"Pro",revenue:60+e*24},{month:n,plan:"Enterprise",revenue:e<2?0:10+e*12}]),T2=Array.from({length:48},(n,e)=>({x:e+1,y:(e+1)*1.6+Math.sin(e*78.233)*43758.5453%18,label:`Account ${e+1}`,series:e%2?"Returning":"New"})),A2=Array.from({length:400},(n,e)=>Math.abs(Math.sin(e*12.9898)*43758.5453%1)*100),B2=["East","South","West","North"].flatMap((n,e)=>hf.map((t,i)=>({x:t,y:n,value:(e+1)*(i+1)*7-(i%4===3?80:0)}))),ly=[{value:"orders.revenue",label:"Revenue"},{value:"orders.count",label:"Order count"},{value:"customers.count",label:"Customer count"},{value:"orders.margin",label:"Gross margin"}];function E2(){const[n,e]=D.useState("orders.revenue"),[t,i]=D.useState({}),[a,u]=D.useState(null),[f,h]=D.useState({"orders.region":["East","West"],"orders.status":["completed"]}),[m,g]=D.useState({from:"2025-01-01",to:"2025-06-30"}),[v,x]=D.useState("month"),[b,w]=D.useState("explore"),[j,C]=D.useState("previous"),[O,H]=D.useState("orders.revenue"),[L,R]=D.useState(["orders.revenue","orders.count"]),[T,E]=D.useState("apple"),[I,U]=D.useState(!0),[G,V]=D.useState("explore"),[Q,z]=D.useState("2025-06-15"),[ee,X]=D.useState({from:"2025-06-01",to:"2025-06-21"}),ie=D.useMemo(()=>D2(O2,{x:"month",y:"revenue",series:"plan"}),[]),[ae,re]=D.useState({key:"revenue",dir:"desc"}),se=D.useMemo(()=>[...ay].sort((A,Y)=>{const W=A[ae.key],_=Y[ae.key],F=typeof W=="number"&&typeof _=="number"?W-_:String(W).localeCompare(String(_));return ae.dir==="asc"?F:-F}),[ae]);return c.jsxs("main",{className:"min-h-screen bg-bg text-ink",children:[c.jsxs("header",{className:"sticky top-0 z-20 flex items-center justify-between border-b border-line bg-surface px-4 py-3",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-sm font-semibold",children:"Sidemantic component gallery"}),c.jsxs("p",{className:"text-2xs text-faint",children:["Canonical React primitives · ",c.jsx("a",{className:"text-accent hover:underline",href:"/typography",children:"typography workbench →"})]})]}),c.jsx($o,{})]}),c.jsxs("div",{className:"space-y-8 p-4",children:[c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Metric cards"}),c.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-3",children:[c.jsx(Nr,{metric:"orders.revenue",label:"Revenue",value:288291,format:{format:"currency"},selected:n==="orders.revenue",sparkValues:[31,42,38,55,60,74],onSelect:e}),c.jsx(Nr,{metric:"orders.count",label:"Order Count",value:447,selected:n==="orders.count",sparkValues:[21,34,28,41,44,51],onSelect:e}),c.jsx(Nr,{metric:"orders.margin",label:"Gross Margin",value:.324,format:{format:"percent"},delta:{label:"+1.1pt",tone:"positive"},comparison:"vs previous month",sparkValues:[24,26,29,27,31,32],selected:n==="orders.margin",onSelect:e})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Leaderboard cards"}),c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(220px,1fr))] gap-0 border-l border-t border-line",children:C2.filter(A=>a===null||a===A.dimension).map(A=>c.jsx(Jv,{dimension:A.dimension,title:A.title,metricLabel:"Total Revenue",rows:A.rows,selectedValues:t[A.dimension],formatMetric:Y=>pt(Y,{format:"currency"}),onToggle:Y=>i(W=>{const _=W[A.dimension]??[];return{...W,[A.dimension]:_.includes(Y)?_.filter(F=>F!==Y):[..._,Y]}}),expanded:a===A.dimension,onExpandedChange:Y=>u(Y?A.dimension:null)},A.dimension))})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Filters and controls"}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{"data-testid":"gallery-filter-pills",className:"flex min-h-8 flex-wrap items-center gap-2",children:[Object.entries(f).flatMap(([A,Y])=>Y.map(W=>c.jsx(Od,{dimension:A,value:W,onRemove:()=>h(_=>({..._,[A]:_[A].filter(F=>F!==W)}))},`${A}:${W}`))),Object.values(f).every(A=>A.length===0)?c.jsx("span",{className:"text-2xs text-faint",children:"No active filters"}):null]}),c.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[c.jsx(Ov,{range:m,onChange:g,comparison:j,onComparisonChange:C}),c.jsx(Td,{grain:v,options:["day","week","month","quarter","year"],onChange:x}),c.jsx(Bv,{view:b,onChange:w}),c.jsxs("span",{className:"inline-flex items-center gap-1.5 text-2xs text-muted",children:[c.jsx(dd,{status:"ok"})," Ready"]}),c.jsxs("span",{className:"inline-flex items-center gap-1.5 text-2xs text-muted",children:[c.jsx(dd,{status:"loading"})," Updating"]}),c.jsx("button",{type:"button",onClick:()=>h({"orders.region":["East","West"],"orders.status":["completed"]}),className:"inline-flex h-7 items-center rounded-full border border-line px-3 text-xs text-muted hover:bg-surface-soft",children:"Reset filters"})]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Charts"}),c.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Sparkline"}),c.jsx(qv,{values:[31,42,38,55,60,74,69,83],labels:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug"],ariaLabel:"Eight month revenue trend"})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Column chart"}),c.jsx(Zv,{data:[{label:"East",value:83},{label:"South",value:81},{label:"West",value:72},{label:"Returns",value:-18}]})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Line chart compatibility export"}),c.jsx(c2,{data:[{label:"Jan",value:31},{label:"Feb",value:42},{label:"Mar",value:38},{label:"Apr",value:55},{label:"May",value:60}]})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Interactive time series"}),c.jsx(Go,{points:[31,42,38,55,60,74].map((A,Y)=>({x:`2025-0${Y+1}-01`,y:A})),comparison:[27,35,33,48,52,61].map((A,Y)=>({x:`2024-0${Y+1}-01`,y:A})),formatValue:A=>`$${A.toLocaleString()}k`})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Donut"}),c.jsx(h2,{data:[{label:"iOS",value:4200},{label:"Android",value:3100},{label:"Web",value:1900},{label:"Other",value:400}]})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Stacked area (long rows via rowsToSeries)"}),c.jsx(S2,{labels:ie.labels,series:ie.series,height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Bar + line combo (dual axis)"}),c.jsx(r2,{data:hf.map((A,Y)=>({label:A,bar:200+Y*42,line:.02+Y*.004})),barLabel:"Revenue",lineLabel:"Conversion",formatLine:A=>`${(A*100).toFixed(1)}%`,height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Histogram"}),c.jsx(y2,{values:A2,bins:20})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Scatter"}),c.jsx(Xv,{points:T2,xLabel:"Sessions",yLabel:"Orders",height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Heatmap"}),c.jsx(p2,{cells:B2,height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Waterfall"}),c.jsx(I2,{data:[{label:"Gross",value:1e3,isTotal:!0},{label:"Refunds",value:-140},{label:"Discounts",value:-90},{label:"Upsells",value:130},{label:"Net",value:900,isTotal:!0}],height:200})]}),c.jsxs("article",{className:"min-w-0 xl:col-span-2",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Network"}),c.jsx(b2,{nodes:[{id:"orders",group:"fact"},{id:"payments",group:"fact"},{id:"customers",group:"dimension"},{id:"products",group:"dimension"},{id:"regions",group:"dimension"}],links:[{source:"orders",target:"customers",weight:3},{source:"orders",target:"products",weight:2},{source:"orders",target:"regions"},{source:"payments",target:"orders",weight:2},{source:"payments",target:"customers"}],height:260})]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Inputs"}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[c.jsx(No,{variant:"primary",children:"Primary"}),c.jsx(No,{children:"Secondary"}),c.jsx(No,{variant:"ghost",children:"Ghost"}),c.jsx(No,{variant:"danger",children:"Danger"}),c.jsx(No,{size:"sm",children:"Small"}),c.jsx(wl,{label:"Fruit",value:T,onChange:E,options:[{value:"apple",label:"Apple"},{value:"banana",label:"Banana"},{value:"cherry",label:"Cherry"}]}),c.jsx(_2,{checked:I,onChange:U,label:"Compact rows"}),c.jsx(N2,{tabs:[{key:"explore",label:"Explore"},{key:"pivot",label:"Pivot"},{key:"sql",label:"SQL"}],active:G,onChange:V}),c.jsx(j2,{content:"Revenue in USD, net of refunds",children:c.jsx("span",{className:"cursor-help text-2xs text-muted underline decoration-dotted",children:"What is revenue?"})})]}),c.jsxs("div",{className:"flex flex-wrap items-start gap-3",children:[c.jsx(ny,{value:O,onChange:H,options:ly,ariaLabel:"Metric"}),c.jsx(ny,{multiple:!0,values:L,onChange:R,options:ly,ariaLabel:"Metrics"}),c.jsx(sy,{mode:"single",value:Q,onChange:z,ariaLabel:"Date"}),c.jsx(sy,{mode:"range",value:ee,onChange:X,ariaLabel:"Range"})]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Analytical table"}),c.jsx(Ho,{columns:F2,rows:se,pageSize:6,sortKey:ae.key,sortDir:ae.dir,onSort:A=>re(Y=>({key:A,dir:Y.key===A&&Y.dir==="desc"?"asc":"desc"})),renderCell:(A,Y)=>A.numeric?Number(Y).toLocaleString():String(Y),searchable:!0,totals:{region:"count",revenue:"sum",orders:"sum"}}),c.jsxs("div",{className:"mt-3",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold text-muted",children:"Distribution-friendly data preview"}),c.jsx(u2,{result:{columns:["region","revenue","orders"],sample_rows:ay.slice(0,8)},pageSize:4})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Query inspection"}),c.jsx(au,{inputs:{Revenue:{metrics:["orders.revenue"],dimensions:["orders.region"],filters:["orders.status = 'completed'"]}},queries:{Revenue:`SELECT orders.region, SUM(orders.revenue) AS revenue +`),i=$_(t||"No queries yet.");return c.jsxs("details",{className:"border border-line bg-surface",children:[c.jsx("summary",{className:"cursor-pointer px-3 py-2 text-xs font-medium text-muted",children:"Generated SQL"}),Object.keys(e).length>0?c.jsx("div",{"data-testid":"query-inputs",className:"grid gap-px border-t border-line bg-line sm:grid-cols-2",children:Object.entries(e).map(([a,u])=>u?c.jsxs("section",{className:"min-w-0 bg-surface px-3 py-2 text-2xs",children:[c.jsx("h3",{className:"mb-1 font-semibold text-ink",children:a}),[["Metrics",u.metrics],["Dimensions",u.dimensions],["Filters",u.filters]].map(([f,h])=>h!=null&&h.length?c.jsxs("p",{className:"truncate text-muted",title:h.join(", "),children:[c.jsxs("strong",{className:"font-medium text-faint",children:[f,":"]})," ",h.join(", ")]},f):null)]},a):null)}):null,c.jsx("pre",{"data-testid":"query-debug",className:"max-h-72 overflow-auto whitespace-pre-wrap border-t border-line px-3 py-2 font-mono text-2xs text-muted",children:i.map((a,u)=>ny[a.kind]?c.jsx("span",{className:ny[a.kind],"data-token":a.kind,children:a.value},u):a.value)})]})}function P_(n){return{format:n==null?void 0:n.format,type:n==null?void 0:n.type}}function z_(n,e){return n&&e.some(t=>t.ref===n)?n:null}function ry(n,e){return[...n].sort((t,i)=>String(t[e]??"").localeCompare(String(i[e]??"")))}function V_(n,e){return{from:e==="second"||e==="minute"||e==="hour"?n.from.replace(" ","T"):nf(n.from),to:yS(n.to,e)}}function W_(){var Cr,Fr,ue,Oe,rt,Nt,Un,sr,Es,Ei;const{state:n,dispatch:e,catalog:t,backend:i,dashboard:a}=ls(),[u,f]=M.useState(null),h=t.models.find(Se=>Se.name===n.model),m=M.useMemo(()=>Cs(t,a,n.dashboardTab),[t,a,n.dashboardTab]);M.useEffect(()=>{f(null)},[n.dashboardTab,n.model]);const g=(m==null?void 0:m.metrics)??(h==null?void 0:h.metrics)??[],v=new Set(g.map(Se=>Se.ref)),x=ji(t,n.model).filter(Se=>!m||v.has(Se.ref)),b=((Cr=m==null?void 0:m.timeDimension)==null?void 0:Cr.ref)??((Fr=h==null?void 0:h.timeDimension)==null?void 0:Fr.ref),w=g.find(Se=>Se.ref===n.selectedMetric)??x.find(Se=>Se.ref===n.selectedMetric)??g[0],j=!!w&&g.some(Se=>Se.ref===w.ref),C=M.useMemo(()=>{const Se=g.map(bn=>bn.ref);return w&&!j?[...Se,w.ref]:Se},[g,w,j]),O=M.useMemo(()=>ou(t),[t]),H=M.useMemo(()=>[...(m==null?void 0:m.filters)??[],...Os(n.filters,{timeRef:b,range:n.dateRange,types:O})],[m,n.filters,b,n.dateRange,O]),L=M.useMemo(()=>n.comparison==="off"||!n.dateRange?null:n.comparison==="year"?dS(n.dateRange):n.comparison==="custom"?n.comparisonRange??null:cS(n.dateRange),[n.comparison,n.dateRange,n.comparisonRange]),R=M.useMemo(()=>L&&b?[...(m==null?void 0:m.filters)??[],...Os(n.filters,{timeRef:b,range:L,types:O})]:null,[m,n.filters,b,L,O]),T=n.timezone,E=Se=>Se?{...Se,timezone:T}:null,I=Zn(i,C.length?E($m(C,H,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations)):null),U=Zn(i,C.length&&b?E(Pm(C,b,n.grain,H,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations,!!n.dateRange)):null),G=Zn(i,C.length&&R?E($m(C,R,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations)):null),V=Zn(i,w&&b&&R?E(Pm([w.ref],b,n.grain,R,m==null?void 0:m.segments,m==null?void 0:m.usePreaggregations,!0)):null),Q=I.error??U.error??G.error??V.error;if(!h)return c.jsx("div",{className:"p-4",children:c.jsx(Xn,{message:"No model available in this semantic layer."})});const z=((m==null?void 0:m.dimensions)??h.dimensions).filter(Se=>Se.type!=="time"),ee=z_(u,z),X=n.comparison==="year"?"Prev year":n.comparison==="custom"?"Comparison":"Prev period",ie=b?`${b}__${n.grain}`:"",ae=ie?[...C,ie]:C,re=w&&ie?[w.ref,ie]:[],se=g[0]?Fn(g[0].ref,C):w?Fn(w.ref,C):null,A=Se=>!Se||!se||Se.columns.includes(se),Y=A(I.result)?(ue=I.result)==null?void 0:ue.rows[0]:void 0,W=A(G.result)?(Oe=G.result)==null?void 0:Oe.rows[0]:void 0,_=A(U.result)?((rt=U.result)==null?void 0:rt.rows)??[]:[],F=w?Fn(w.ref,C):"",te=w?Fn(w.ref,ae):"",pe=w?Fn(w.ref,re):"",ne=ie?Fn(ie,ae):"",fe=ie?Fn(ie,re):"",Ce=ne?ry(_,ne):_,Te=Y&&F?Number(Y[F]):NaN,Ue=W&&F?Number(W[F]):void 0,lt=te?Ce.map(Se=>({x:String(Se[ne]??""),y:Number(Se[te])})):[],wt=fe?ry(((Nt=V.result)==null?void 0:Nt.rows)??[],fe):[],Bs=pe&<.length>0&&wt.length>0?(()=>{const Se=String(wt[0][fe]??""),bn=lt[0].x,cs=new Map;for(const tn of wt)cs.set(Lm(Se,String(tn[fe]??""),n.grain),Number(tn[pe]));return lt.map(tn=>({x:tn.x,y:cs.get(Lm(bn,tn.x,n.grain))??NaN}))})():[];function xn(Se){e(Se?{type:"setDateRange",range:V_(Se,n.grain)}:{type:"setDateRange",range:void 0})}return c.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[Q?c.jsx(Bi,{message:Q}):null,c.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6","data-testid":"metric-totals",children:g.length===0?c.jsx("div",{className:"col-span-full",children:c.jsx(Xn,{message:"This model has no metrics."})}):g.map(Se=>{const bn=Fn(Se.ref,C),cs=Fn(Se.ref,ae),tn=Y?Number(Y[bn]):NaN,ds=W?Number(W[bn]):void 0,Yo=Ce.map(ir=>Number(ir[cs])).filter(Number.isFinite);return c.jsx(Nr,{metric:Se.ref,label:Se.label,valueText:pt(tn,P_(Se)),delta:ds!==void 0?xy(tn,ds):null,sparkValues:Yo,selected:n.selectedMetric===Se.ref,loading:I.loading&&!Y,onSelect:ir=>e({type:"setMetric",metric:ir})},Se.ref)})}),w?c.jsx(L_,{metric:w,points:lt,comparisonPoints:L?Bs:void 0,total:Te,prevTotal:L?Ue:void 0,hasTime:!!b,loading:U.loading,activeRange:n.dateRange,comparisonLabel:X,formatLabel:Se=>fS(Se,n.grain),onBrush:xn}):null,c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(220px,1fr))] gap-0 border-l border-t border-line",children:w&&z.length?z.filter(Se=>ee===null||ee===Se.ref).map(Se=>c.jsx(A_,{dim:Se,model:h,timeDimensionRef:b,rankMetric:w,contextColumn:n.contextColumn,metricTotal:Number.isFinite(Te)?Te:void 0,comparisonRange:L??void 0,baseFilters:m==null?void 0:m.filters,baseSegments:m==null?void 0:m.segments,usePreaggregations:m==null?void 0:m.usePreaggregations,expanded:ee===Se.ref,onExpandedChange:bn=>f(bn?Se.ref:null)},Se.ref)):c.jsx(Xn,{message:"No categorical dimensions to break down."})}),c.jsx(au,{queries:{Totals:(Un=I.result)==null?void 0:Un.sql,Series:(sr=U.result)==null?void 0:sr.sql,Comparison:(Es=G.result)==null?void 0:Es.sql,"Prev series":(Ei=V.result)==null?void 0:Ei.sql}})]})}function H_(){var ie,ae;const{state:n,catalog:e,backend:t}=ls(),i=e.models.find(re=>re.name===n.model),a=(i==null?void 0:i.dimensions)??[],u=ji(e,n.model),f=M.useMemo(()=>[...(i==null?void 0:i.metrics)??[],...u],[i,u]),h=(ie=i==null?void 0:i.timeDimension)==null?void 0:ie.ref,m=re=>a.some(se=>se.ref===re),g=re=>f.some(se=>se.ref===re),v=n.pivotDims.filter(m),x=n.pivotMetrics.filter(g),b=g(n.selectedMetric)?n.selectedMetric:(ae=i==null?void 0:i.metrics[0])==null?void 0:ae.ref,w=x.length?x:b?[b]:[],[j,C]=M.useState(null),O=M.useMemo(()=>sf(a),[a]),H=M.useMemo(()=>Os(n.filters,{timeRef:h,range:n.dateRange,types:O}),[n.filters,h,n.dateRange,O]),L=j??(w[0]?{ref:w[0],dir:"desc"}:null),R=L?[`${L.ref} ${L.dir.toUpperCase()}`]:void 0,T=w.length||v.length?bS(w,v,H,R,500):null,E=T?{...T,timezone:n.timezone}:null,{result:I,loading:U,error:G}=Zn(t,E),V=M.useMemo(()=>new Map(f.map(re=>[re.ref,re])),[f]),Q=M.useMemo(()=>{const re=new Map;for(const se of[...v,...w])re.set(Sr(se),se);return re},[v,w]),z=[...v.map(re=>{var se;return{key:Sr(re),label:((se=a.find(A=>A.ref===re))==null?void 0:se.label)??Le(re),numeric:!1}}),...w.map(re=>{var se;return{key:Sr(re),label:((se=V.get(re))==null?void 0:se.label)??Le(re),numeric:!0,sortable:!0}})];function ee(re){const se=Q.get(re);se&&C(A=>A&&A.ref===se?{ref:se,dir:A.dir==="desc"?"asc":"desc"}:{ref:se,dir:"desc"})}function X(re,se){if(re.numeric){const A=V.get(Q.get(re.key)??"");return pt(se,{format:A==null?void 0:A.format,type:A==null?void 0:A.type})}return se==null||se===""?"—":String(se)}return i?c.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[G?c.jsx(Bi,{message:G}):z.length===0?c.jsx(Xn,{title:"Nothing selected",message:"Pick at least one metric or dimension above."}):c.jsx(Ho,{columns:z,rows:(I==null?void 0:I.rows)??[],loading:U,sortKey:L?Sr(L.ref):void 0,sortDir:L==null?void 0:L.dir,onSort:ee,renderCell:X}),c.jsx(au,{queries:{Pivot:I==null?void 0:I.sql}})]}):c.jsx("div",{className:"p-4",children:c.jsx(Xn,{message:"No model available."})})}const Dn={top:12,right:14,bottom:26,left:44};function G_(n,e,t=4){if(!(e>n))return[n];const i=(e-n)/(t-1);return Array.from({length:t},(a,u)=>n+i*u)}function t0({data:n,height:e=200,ariaLabel:t,selectedLabel:i,onSelect:a}){const u=M.useRef(null),[f,h]=M.useState(640),{tip:m,handlers:g}=Dr();M.useEffect(()=>{const I=u.current;if(!I||typeof ResizeObserver>"u")return;const U=new ResizeObserver(G=>{for(const V of G)h(Math.max(160,V.contentRect.width))});return U.observe(I),()=>U.disconnect()},[]);const v=n.map(I=>Number.isFinite(I.value)?I.value:0),x=Math.min(0,...v),b=Math.max(0,...v),w=b-x||1,j=f-Dn.left-Dn.right,C=e-Dn.top-Dn.bottom,O=I=>Dn.top+(1-(I-x)/w)*C,H=O(0),L=j/Math.max(n.length,1),R=Math.max(8,Math.min(48,L*.62)),T=G_(x,b,4),E=t||`Bar chart, ${n.length} categories, up to ${Wt(b)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:u,role:"img","aria-label":E,className:"h-[200px] w-full overflow-hidden",viewBox:`0 0 ${f} ${e}`,children:[T.map((I,U)=>{const G=O(I);return c.jsxs("g",{children:[c.jsx("line",{x1:Dn.left,x2:f-Dn.right,y1:G,y2:G,className:"stroke-line"}),c.jsx("text",{x:Dn.left-6,y:G+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(I)})]},U)}),c.jsx("line",{x1:Dn.left,x2:f-Dn.right,y1:H,y2:H,className:"stroke-line"}),n.map((I,U)=>{const G=I.filterValue??I.label,V=v[U]??0,Q=O(V),z=Math.abs(Q-H),ee=Dn.left+L*U+(L-R)/2,X=Math.min(Q,H);return c.jsxs("g",{role:a?"button":void 0,tabIndex:a?0:void 0,"aria-label":a?`Filter to ${I.label}`:void 0,"aria-pressed":a?i===G:void 0,onClick:a?()=>a(G):void 0,onKeyDown:a?ie=>{(ie.key==="Enter"||ie.key===" ")&&a(G)}:void 0,className:a?"cursor-pointer":void 0,children:[c.jsx("rect",{x:ee,y:X,width:R,height:z,"data-label":I.label,"data-value":V,"data-tone":V<0?"negative":"positive",className:i===G?"fill-accent":V<0?"fill-danger":"fill-chart-primary",...g(`${I.label}: ${pt(V)}`)}),c.jsx("text",{x:ee+R/2,y:e-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:I.label.slice(0,8)})]},`${G}-${U}`)})]}),c.jsx(rr,{tip:m})]})}const pd=7;function yn(n){return`var(--viz-${(n%pd+pd)%pd+1})`}function Ts(n,e,t=4){if(!(e>n))return[n];const i=(e-n)/(t-1);return Array.from({length:t},(a,u)=>n+i*u)}function us(n,e,t){if(!n||typeof ResizeObserver>"u")return()=>{};const i=new ResizeObserver(a=>{for(const u of a)t(Math.max(e,u.contentRect.width))});return i.observe(n),()=>i.disconnect()}const Pt={top:12,right:14,bottom:30,left:48};function n0({points:n,height:e=240,xLabel:t,yLabel:i,formatX:a=Wt,formatY:u=Wt,ariaLabel:f}){const h=M.useRef(null),[m,g]=M.useState(640),{tip:v,handlers:x}=Dr();M.useEffect(()=>us(h.current,200,g),[]);const b=n.filter(z=>Number.isFinite(z.x)&&Number.isFinite(z.y));if(b.length===0)return c.jsx("div",{className:"grid h-[240px] place-items-center text-xs text-faint",children:"No points to chart."});const w=[...new Set(b.map(z=>z.series??""))],j=b.map(z=>z.x),C=b.map(z=>z.y),O=Math.min(...j),H=Math.max(...j),L=Math.min(...C),R=Math.max(...C),T=H-O||1,E=R-L||1,I=m-Pt.left-Pt.right,U=e-Pt.top-Pt.bottom,G=z=>Pt.left+(z-O)/T*I,V=z=>Pt.top+(1-(z-L)/E)*U,Q=f||`Scatter plot, ${b.length} points${t&&i?` of ${i} by ${t}`:""}`;return c.jsxs(c.Fragment,{children:[w.length>1?c.jsx("div",{className:"mb-1 flex flex-wrap items-center gap-3 text-2xs text-faint",children:w.map((z,ee)=>c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-full",style:{background:yn(ee)}}),z||"(default)"]},z||"(default)"))}):null,c.jsxs("svg",{ref:h,role:"img","aria-label":Q,className:"w-full overflow-hidden",style:{height:e},viewBox:`0 0 ${m} ${e}`,children:[Ts(L,R,4).map((z,ee)=>{const X=V(z);return c.jsxs("g",{children:[c.jsx("line",{x1:Pt.left,x2:m-Pt.right,y1:X,y2:X,className:"stroke-line"}),c.jsx("text",{x:Pt.left-6,y:X+3,textAnchor:"end",className:"fill-faint text-[10px]",children:u(z)})]},`y${ee}`)}),Ts(O,H,5).map((z,ee)=>{const X=G(z);return c.jsxs("g",{children:[c.jsx("line",{x1:X,x2:X,y1:Pt.top,y2:e-Pt.bottom,className:"stroke-line"}),c.jsx("text",{x:X,y:e-14,textAnchor:"middle",className:"fill-faint text-[10px]",children:a(z)})]},`x${ee}`)}),t?c.jsx("text",{x:Pt.left+I/2,y:e-2,textAnchor:"middle",className:"fill-muted text-[10px]",children:t}):null,i?c.jsx("text",{x:10,y:Pt.top+U/2,textAnchor:"middle",transform:`rotate(-90 10 ${Pt.top+U/2})`,className:"fill-muted text-[10px]",children:i}):null,b.map((z,ee)=>c.jsx("circle",{cx:G(z.x),cy:V(z.y),r:3.5,fill:yn(w.indexOf(z.series??"")),fillOpacity:.75,"data-x":z.x,"data-y":z.y,"data-label":z.label,...x(c.jsx(os,{title:z.label??z.series,rows:[{label:t??"x",value:a(z.x)},{label:i??"y",value:u(z.y)}]}))},ee))]}),c.jsx(rr,{tip:v})]})}function Y_(){const n=Tv();return c.jsx("span",{className:"text-2xs text-faint",children:n?"Querying…":"Live data"})}function md(n,e){for(const i of n.models){const a=i.metrics.find(u=>u.ref===e);if(a)return{format:a.format,type:a.type}}const t=n.graphMetrics.find(i=>i.ref===e);return{format:t==null?void 0:t.format,type:t==null?void 0:t.type}}function Q_(n){return sf(n.models.flatMap(e=>e.dimensions))}function K_(n){var t;const e=(t=n.encoding)==null?void 0:t.y;return(Array.isArray(e)?e[0]:e)??n.query.metrics[0]??""}function J_({chart:n,columns:e,rows:t}){const i=N_(e,t);return c.jsx("a",{href:`data:text/csv;charset=utf-8,${encodeURIComponent(i)}`,download:`${n.id}.csv`,className:"border border-line px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Export CSV"})}function q_({chart:n,columns:e,rows:t,loading:i,onDrill:a}){const u=e.map(g=>({key:g,label:Le(g),numeric:n.query.metrics.some(v=>xr(v,e)===g)})),f=l_(n),h=f?xr(f,e):void 0,m=!!f;return c.jsxs("div",{className:"border-t border-line bg-surface-soft p-3","data-testid":`chart-details-${n.id}`,children:[c.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[c.jsx("span",{className:"text-2xs font-semibold uppercase tracking-wide text-faint",children:"Drill details"}),m&&f&&h?c.jsxs("span",{className:"text-2xs text-faint",children:["Choose a ",Le(f)," value to filter every chart."]}):null]}),c.jsx(Ho,{columns:u,rows:t,loading:i,pageSize:20,renderCell:(g,v)=>String(v??"—")}),m&&f&&h&&t.length?c.jsx("div",{className:"mt-2 flex flex-wrap gap-1","aria-label":`Drill by ${Le(f)}`,children:t.slice(0,12).map((g,v)=>{const x=Xl(g[h]);return c.jsxs("button",{type:"button",onClick:()=>a(f,x),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-accent hover:text-ink",children:["Filter to ",rs(x)]},`${String(x)}-${v}`)})}):null]})}function Z_({document:n,chart:e,catalog:t,backend:i,state:a,setFilters:u,setRange:f}){var z,ee,X,ie,ae,re,se;const[h,m]=M.useState(!1),g=M.useMemo(()=>Q_(t),[t]),v=M.useMemo(()=>y_(n,e,a.filters,g,a.ranges,a),[e,n,a,g]),x=Zn(i,v),b=((z=x.result)==null?void 0:z.rows)??[],w=((ee=x.result)==null?void 0:ee.columns)??[],j=e.query.dimensions??[],C=((X=e.encoding)==null?void 0:X.x)??j[0]??"",O=d_(e),H=O[0]??K_(e),L=xr(C,w),R=cf(n,e,a),T=Hv(e,g),E=u_(e,C),I=((ie=e.title)==null?void 0:ie.trim())||Le(e.id),U=[(ae=e.encoding)==null?void 0:ae.color,...j.filter(A=>A!==C)].filter((A,Y,W)=>!!A&&W.indexOf(A)===Y),G=h_(e,C,U),V=U.map(A=>xr(A,w));let Q;if(x.loading&&!x.result)Q=c.jsx(af,{title:`Loading ${I}`});else if(x.error)Q=c.jsx(Bi,{title:`Could not load ${I}`,message:x.error});else if(!b.length)Q=c.jsx(Xn,{title:I,message:"The query returned no rows."});else if(j.length)if(T==="scatter"||T==="point"){const A=(re=e.encoding)!=null&&re.color?xr(e.encoding.color,w):V[0];Q=c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3",children:O.map(Y=>{const W=xr(Y,w),_=b.map(F=>({x:Number(F[L]),y:Number(F[W]),label:String(F[L]??""),series:A?String(F[A]??""):void 0}));return c.jsxs("div",{className:"min-w-0",children:[O.length>1?c.jsx("h3",{className:"mb-1 text-2xs font-semibold text-muted",children:Le(Y)}):null,c.jsx(n0,{points:_,xLabel:Le(C),yLabel:Le(Y),formatY:F=>pt(F,md(t,Y)),ariaLabel:`${I}, ${Le(Y)} by ${Le(C)}, ${_.length} points`})]},Y)})})}else T==="line"||T==="area"?Q=c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3",children:O.map(A=>{const Y=x_(b,L,xr(A,w),V),W=Y[0]??{label:"Current",points:[]},_=md(t,A);return c.jsxs("div",{className:"min-w-0",children:[O.length>1?c.jsx("h3",{className:"mb-1 text-2xs font-semibold text-muted",children:Le(A)}):null,c.jsx(Go,{points:W.points,seriesLabel:W.label,additionalSeries:Y.slice(1),formatValue:F=>pt(F,_),ariaLabel:`${I}, ${Le(A)}, ${Y.length} series and ${W.points.length} buckets`,onBrush:E?F=>f(C,F):void 0})]},A)})}):Q=c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(260px,1fr))] gap-3",children:O.map(A=>{const Y=xr(A,w),W=v_(b,L,Y,V);return W.map((_,F)=>{const te=_.data.slice(0,30),pe=O.length>1||W.length>1,ne=[O.length>1?Le(A):"",W.length>1?_.label:""].filter(Boolean).join(" · ");return c.jsxs("div",{className:"min-w-0",children:[pe?c.jsx("h3",{className:"mb-1 text-2xs font-semibold text-muted",children:ne}):null,c.jsx(t0,{data:te,ariaLabel:`${I}, ${ne||Le(A)}, ${te.length} categories`,selectedLabel:R.filters[C],onSelect:G?fe=>{u(f_(e,C,fe,U,_.filterValues)),m(!0)}:void 0})]},`${A}-${_.label}-${F}`)})})});else{const A=b[0];Q=c.jsx("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:e.query.metrics.map(Y=>c.jsx(Nr,{metric:Y,label:Le(Y),value:A[xr(Y,w)],format:md(t,Y)},Y))})}return c.jsxs("article",{className:"min-w-0 overflow-hidden border border-line bg-surface","data-testid":"dashboard-chart","data-chart-id":e.id,children:[c.jsxs("header",{className:"flex min-h-12 flex-wrap items-center justify-between gap-2 border-b border-line px-3 py-2",children:[c.jsxs("div",{className:"min-w-0",children:[c.jsx("h2",{className:"truncate text-sm font-semibold text-ink",children:I}),c.jsxs("p",{className:"text-2xs text-faint",children:[Le(H),C?` by ${Le(C)}`:""]})]}),c.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.jsx("button",{type:"button","aria-expanded":h,onClick:()=>m(A=>!A),className:"border border-line px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:h?"Hide details":"Drill details"}),c.jsx("a",{href:g_(n,e,a,g,t),className:"border border-line px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Explore from here"}),c.jsx(J_,{chart:e,columns:w,rows:b})]})]}),c.jsx("div",{className:"min-h-64 overflow-hidden p-3",children:Q}),h?c.jsx(q_,{chart:e,columns:w,rows:b,loading:x.loading,onDrill:(A,Y)=>u({[A]:Y})}):null,(se=x.result)!=null&&se.sql?c.jsx("div",{className:"border-t border-line px-3 py-2",children:c.jsx(au,{queries:{Query:x.result.sql}})}):null]})}function X_({document:n,state:e,onLoad:t}){const[i,a]=M.useState(""),[u,f]=M.useState(()=>S_(n)),[h,m]=M.useState(!1);function g(v){f(v),m(!__(n,v))}return c.jsxs("details",{className:"relative",children:[c.jsx("summary",{className:"cursor-pointer list-none border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Saved views"}),c.jsxs("div",{className:"absolute right-0 z-50 mt-1 w-72 border border-line bg-surface p-3 shadow-[var(--shadow)]",children:[c.jsx("p",{className:"mb-2 text-2xs text-faint",children:"Stored only in this browser. Nothing is written to the server."}),c.jsxs("div",{className:"flex gap-1",children:[c.jsx("input",{value:i,onChange:v=>a(v.target.value),placeholder:"View name","aria-label":"Saved view name",className:"min-w-0 flex-1 border border-line bg-bg px-2 py-1 text-xs text-ink"}),c.jsx("button",{type:"button",disabled:!i.trim(),onClick:()=>{const v=[...u.filter(x=>x.name!==i.trim()),{name:i.trim(),state:e}];g(v),a("")},className:"border border-line px-2 py-1 text-2xs text-muted hover:text-ink disabled:opacity-40",children:"Save"})]}),h?c.jsx("p",{role:"alert",className:"mt-2 text-2xs text-danger",children:"Browser storage is unavailable."}):null,c.jsx("div",{className:"mt-2 flex flex-col gap-1",children:u.length?u.map(v=>c.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-line pt-1",children:[c.jsx("button",{type:"button",onClick:()=>t(v.state),className:"min-w-0 flex-1 truncate text-left text-xs text-muted hover:text-ink",children:v.name}),c.jsx("button",{type:"button","aria-label":`Delete saved view ${v.name}`,onClick:()=>g(u.filter(x=>x.name!==v.name)),className:"text-2xs text-faint hover:text-danger",children:"Delete"})]},v.name)):c.jsx("span",{className:"text-2xs text-faint",children:"No local views yet."})})]})]})}function e2(){const[n,e]=M.useState(!1);return c.jsx("button",{type:"button",title:"Copies the active tab, filters, and brushed ranges. Data is queried live; local saved views are not shared.",onClick:async()=>{await navigator.clipboard.writeText(window.location.href),e(!0),window.setTimeout(()=>e(!1),1200)},className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:n?"Share URL copied":"Copy share URL"})}function t2({document:n,catalog:e,backend:t}){const[i,a]=M.useState(()=>b_(window.location.search,n)),u=n.tabs.find(b=>b.id===i.tab)??n.tabs[0];M.useEffect(()=>{window.document.title=n.title},[n.title]),M.useEffect(()=>{const b=w_(i,n);window.history.replaceState(null,"",`${window.location.pathname}${b?`?${b}`:""}`)},[n,i]);function f(b,w){var C,O;const j=eu(n,b);if((((O=(C=n.defaults)==null?void 0:C.interactions)==null?void 0:O.scope)??"dashboard")==="chart"){a(H=>{var L;return{...H,chartFilters:{...H.chartFilters??{},[j]:{...((L=H.chartFilters)==null?void 0:L[j])??{},...w}}}});return}a(H=>({...H,filters:{...H.filters,...w},filterSources:{...H.filterSources,...Object.fromEntries(Object.keys(w).map(L=>[L,j]))}}))}function h(b,w,j){var O,H;const C=eu(n,b);if((((H=(O=n.defaults)==null?void 0:O.interactions)==null?void 0:H.scope)??"dashboard")==="chart"){a(L=>{const R={...L.chartRanges??{}},T={...R[C]??{}};return j?T[w]=j:delete T[w],Object.keys(T).length?R[C]=T:delete R[C],{...L,chartRanges:R}});return}a(L=>{const R={...L.ranges},T={...L.rangeSources};return j?(R[w]=j,T[w]=C):(delete R[w],delete T[w]),{...L,ranges:R,rangeSources:T}})}const m=c.jsxs(c.Fragment,{children:[c.jsx(X_,{document:n,state:i,onLoad:a}),c.jsx(e2,{}),c.jsx($o,{}),c.jsx(Y_,{})]}),g=Object.entries(i.chartFilters??{}).flatMap(([b,w])=>Object.entries(w).map(([j,C])=>({source:b,dimension:j,value:C}))),v=Object.entries(i.chartRanges??{}).flatMap(([b,w])=>Object.entries(w).map(([j,C])=>({source:b,dimension:j,range:C}))),x=Object.entries(i.filters).length||Object.entries(i.ranges).length||g.length||v.length?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"shrink-0 text-2xs font-semibold uppercase tracking-wide text-faint",children:"Filters"}),Object.entries(i.filters).map(([b,w])=>c.jsxs("button",{type:"button","aria-label":`Remove filter ${Le(b)} ${w}`,onClick:()=>a(j=>{const C={...j.filters},O={...j.filterSources};return delete C[b],delete O[b],{...j,filters:C,filterSources:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(b)," = ",w," ×"]},b)),Object.entries(i.ranges).map(([b,w])=>c.jsxs("button",{type:"button","aria-label":`Remove range ${Le(b)} ${w.from} to ${w.to}`,onClick:()=>a(j=>{const C={...j.ranges},O={...j.rangeSources};return delete C[b],delete O[b],{...j,ranges:C,rangeSources:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(b),": ",w.from,"–",w.to," ×"]},`range-${b}`)),g.map(({source:b,dimension:w,value:j})=>c.jsxs("button",{type:"button","aria-label":`Remove filter ${Le(w)} ${j} from ${b}`,onClick:()=>a(C=>{const O={...C.chartFilters??{}},H={...O[b]??{}};return delete H[w],Object.keys(H).length?O[b]=H:delete O[b],{...C,chartFilters:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(w)," = ",j," · ",b," ×"]},`chart-filter-${b}-${w}`)),v.map(({source:b,dimension:w,range:j})=>c.jsxs("button",{type:"button","aria-label":`Remove range ${Le(w)} ${j.from} to ${j.to} from ${b}`,onClick:()=>a(C=>{const O={...C.chartRanges??{}},H={...O[b]??{}};return delete H[w],Object.keys(H).length?O[b]=H:delete O[b],{...C,chartRanges:O}}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-danger",children:[Le(w),": ",j.from,"–",j.to," · ",b," ×"]},`chart-range-${b}-${w}`)),c.jsx("button",{type:"button",onClick:()=>a(b=>({...b,filters:{},ranges:{},filterSources:{},rangeSources:{},chartFilters:{},chartRanges:{}})),className:"text-2xs text-muted hover:text-ink",children:"Clear all"})]}):void 0;return c.jsx(kv,{brand:c.jsxs("div",{className:"min-w-0",children:[c.jsx("h1",{className:"truncate text-sm font-semibold text-ink",children:n.title}),c.jsx("p",{className:"text-2xs text-faint",children:"Declarative dashboard"})]}),toolbar:m,filters:x,rail:null,showRail:!1,children:c.jsxs("div",{"data-testid":"dashboard-document",className:"flex min-h-full flex-col",children:[c.jsx("nav",{className:"flex shrink-0 gap-1 overflow-x-auto border-b border-line bg-surface px-3 pt-2","aria-label":"Dashboard tabs",children:n.tabs.map(b=>c.jsx("button",{type:"button",role:"tab","aria-selected":b.id===(u==null?void 0:u.id),"data-tab-id":b.id,onClick:()=>a(w=>{var j,C;return w.tab===b.id?w:(((C=(j=n.defaults)==null?void 0:j.interactions)==null?void 0:C.scope)??"dashboard")==="dashboard"?{...w,tab:b.id}:{...w,tab:b.id,filters:{},ranges:{},filterSources:{},rangeSources:{},chartFilters:{},chartRanges:{}}}),className:"border border-b-0 border-line px-3 py-2 text-xs text-muted aria-selected:border-accent aria-selected:bg-bg aria-selected:text-ink",children:j_(b)},b.id))}),u?c.jsx("section",{className:"grid min-w-0 grid-cols-1 gap-3 p-3 xl:grid-cols-2","data-testid":"dashboard-chart-grid","data-tab-id":u.id,children:u.charts.map(b=>c.jsx(Z_,{document:n,chart:b,catalog:e,backend:t,state:i,setFilters:w=>f(b,w),setRange:(w,j)=>h(b,w,j)},b.id))}):c.jsx(Xn,{title:"No dashboard tabs",message:"This dashboard document has no tabs to render."})]})})}function sy(){const n=Tv();return c.jsxs("span",{role:"status","aria-live":"polite","aria-atomic":"true",className:"flex items-center gap-1.5 text-2xs text-faint",title:n?"Updating data":"Data is up to date",children:[n?c.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",className:"spinner size-3.5 text-accent",fill:"none",stroke:"currentColor",strokeWidth:"3",children:c.jsx("path",{d:"M12 3a9 9 0 1 0 9 9",strokeLinecap:"round"})}):c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-full bg-accent"}),c.jsx("span",{className:"sr-only",children:n?"Updating data":"Data is up to date"})]})}function n2(){const[n,e]=M.useState(!1);return c.jsx("button",{type:"button",onClick:async()=>{await navigator.clipboard.writeText(window.location.href),e(!0),window.setTimeout(()=>e(!1),1200)},className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:n?"Copied":"Copy link"})}function dl({children:n}){return c.jsx("div",{className:"grid h-screen place-items-center bg-bg p-6",children:n})}function r2({backend:n,onAuthenticated:e}){const[t,i]=M.useState(""),[a,u]=M.useState(null),[f,h]=M.useState(!1);return c.jsxs("div",{className:"w-full max-w-sm border border-line bg-surface p-6 shadow-sm",children:[c.jsx("h1",{className:"text-base font-semibold text-ink",children:"Connect to Sidemantic"}),c.jsx("p",{className:"mt-2 text-xs leading-5 text-muted",children:"Enter the API bearer once. It is exchanged for a short-lived, HttpOnly browser session where supported, and is never placed in the URL or browser storage."}),c.jsxs("form",{className:"mt-5 space-y-3",onSubmit:async m=>{m.preventDefault(),h(!0),u(null);try{await n.createBrowserSession(t),i(""),e()}catch(g){u(g instanceof Error?g.message:String(g))}finally{h(!1)}},children:[c.jsx("label",{className:"block text-xs font-medium text-ink",htmlFor:"api-token",children:"API bearer token"}),c.jsx("input",{id:"api-token",type:"password",autoComplete:"off",required:!0,value:t,onChange:m=>i(m.target.value),className:"w-full border border-line bg-bg px-3 py-2 text-sm text-ink outline-none focus:border-accent"}),a?c.jsx("p",{className:"text-xs text-red-700",children:a}):null,c.jsx("button",{type:"submit",disabled:f||!t,className:"w-full bg-accent px-3 py-2 text-xs font-semibold text-white disabled:opacity-50",children:f?"Connecting…":"Connect"})]})]})}function s2(){const{state:n,dispatch:e,catalog:t,initial:i,dashboard:a}=ls(),u=!!a,f=n.view==="home"&&!u,h=t.models.find(R=>R.name===n.model),m=M.useMemo(()=>Cs(t,a,n.dashboardTab),[t,a,n.dashboardTab]),g=M.useMemo(()=>a?Cv(t,a,n.dashboardTab):i,[t,a,i,n.dashboardTab]),v=n.dateRange!=null||Object.keys(n.filters).length>0,x=(m==null?void 0:m.timeDimension)??(h==null?void 0:h.timeDimension),b=!!x,w=lS(x==null?void 0:x.supportedGranularities,n.grain),j=M.useMemo(()=>{const R=new Map;for(const T of t.models)for(const E of T.dimensions)R.set(E.ref,{dim:E,model:T});return R},[t]),C=Object.entries(n.filters).flatMap(([R,T])=>{const E=j.get(R);return E?[c.jsx(Od,{dim:E.dim,model:E.model,filter:T,onRemove:()=>e({type:"removeFilterDim",dim:R})},R)]:[]}),O=c.jsx(rS,{dashboardTitle:a==null?void 0:a.title,modelLabel:!f&&!u?h==null?void 0:h.label:void 0,onHome:()=>e({type:"setView",view:"home"})}),H=f?c.jsxs(c.Fragment,{children:[c.jsx($o,{}),c.jsx(sy,{})]}):c.jsxs(c.Fragment,{children:[a?c.jsx("div",{className:"flex items-center border border-line bg-surface",role:"tablist","aria-label":"Dashboard tabs",children:a.tabs.map(R=>{const T=R.id===n.dashboardTab;return c.jsx("button",{type:"button",role:"tab","aria-selected":T,className:`px-2 py-1 text-2xs ${T?"bg-accent text-white":"text-muted hover:text-ink"}`,onClick:()=>{const E=Cs(t,a,R.id);E&&e({type:"setDashboardTab",tab:E.id,model:E.model.name,metric:E.selectedMetric,grain:E.grain})},children:R.label??R.id},R.id)})}):c.jsx(Lv,{view:n.view,onChange:R=>e({type:"setView",view:R})}),c.jsx(Bv,{range:n.dateRange,disabled:!b,onChange:R=>e({type:"setDateRange",range:R}),comparison:n.comparison,comparisonRange:n.comparisonRange,onComparisonChange:(R,T)=>e({type:"setComparison",comparison:R,range:T})}),c.jsx(Td,{grain:n.grain,options:w,disabled:!b,onChange:R=>e({type:"setGrain",grain:R})}),c.jsx(e_,{timezone:n.timezone,disabled:!b,onChange:R=>e({type:"setTimezone",timezone:R})}),v?c.jsx("button",{type:"button",onClick:()=>e({type:"reset",initial:g}),className:"border border-line bg-surface px-2 py-1 text-2xs text-muted hover:border-faint hover:text-ink",children:"Reset"}):null,c.jsx(n2,{}),c.jsx($o,{}),c.jsx(sy,{})]}),L=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"shrink-0 text-xs font-medium text-muted",children:"Filters"}),C.length?C:c.jsx("span",{className:"text-2xs text-faint",children:"None"}),h?c.jsx(GS,{model:h}):null,C.length?c.jsx("button",{type:"button",onClick:()=>e({type:"clearFilters"}),className:"shrink-0 text-2xs text-muted underline-offset-2 hover:text-ink hover:underline",children:"Clear"}):null]});return c.jsx(kv,{brand:O,toolbar:H,filters:f?void 0:L,rail:c.jsx(QS,{}),showRail:!f&&!u,openRailRequest:n.view==="pivot",drawer:f?void 0:c.jsx(s_,{}),children:c.jsxs(KS,{children:[n.view==="home"?c.jsx(k_,{}):null,n.view==="explore"?c.jsx(W_,{}):null,n.view==="pivot"?c.jsx(H_,{}):null]},n.view)})}function i2(){const[n,e]=M.useState(!1),t=M.useMemo(()=>new nS({transport:"json",onUnauthorized:()=>e(!0)}),[]),[i,a]=M.useState(null),[u,f]=M.useState(null),[h,m]=M.useState(0),g=a_(window.location.pathname,window.location.search);return M.useEffect(()=>{let v=!0;return Promise.all([t.getCatalog(),g?Promise.resolve(null):t.getDashboard()]).then(([x,b])=>v&&a({catalog:x,dashboard:b})).catch(x=>v&&f(x instanceof Error?x.message:String(x))),()=>{v=!1}},[t,g,h]),n?c.jsx(dl,{children:c.jsx(r2,{backend:t,onAuthenticated:()=>{e(!1),f(null),m(v=>v+1)}})}):u?c.jsx(dl,{children:c.jsx(Bi,{title:"Could not load semantic layer",message:u})}):i?i.catalog.models.length?i.dashboard?c.jsx(t2,{document:i.dashboard,catalog:i.catalog,backend:t}):c.jsx($S,{catalog:i.catalog,backend:t,children:c.jsx(s2,{})}):c.jsx(dl,{children:c.jsx(Xn,{title:"Empty semantic layer",message:"No models were found."})}):c.jsx(dl,{children:c.jsx(af,{title:"Loading semantic layer",message:"Reading models and metrics…"})})}const Zt={top:14,right:48,bottom:26,left:48};function o2({data:n,barLabel:e="Bars",lineLabel:t="Line",height:i=220,formatBar:a=pt,formatLine:u=pt,ariaLabel:f}){const h=M.useRef(null),[m,g]=M.useState(640),{tip:v,handlers:x}=Dr();if(M.useEffect(()=>us(h.current,240,g),[]),n.length===0)return c.jsx("div",{className:"grid h-[220px] place-items-center text-xs text-faint",children:"No data to chart."});const b=n.map(ae=>Number.isFinite(ae.bar)?ae.bar:0),w=n.map(ae=>Number.isFinite(ae.line)?ae.line:0),j=Math.min(0,...b),C=Math.max(0,...b),O=C-j||1,H=Math.min(...w),L=Math.max(...w),R=L-H||1,T=m-Zt.left-Zt.right,E=i-Zt.top-Zt.bottom,I=ae=>Zt.top+(1-(ae-j)/O)*E,U=ae=>Zt.top+(1-(ae-H)/R)*E,G=T/n.length,V=Math.max(8,Math.min(48,G*.55)),Q=ae=>Zt.left+G*ae+G/2,z=I(0),ee=n.map((ae,re)=>`${Q(re).toFixed(1)},${U(w[re]).toFixed(1)}`).join(" L "),X=yn(1),ie=f||`Combo chart, ${n.length} categories: ${e} bars with a ${t} line`;return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"mb-1 flex items-center gap-3 text-2xs text-faint",children:[c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block h-2 w-3 bg-chart-primary"})," ",e]}),c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block h-0.5 w-3",style:{background:X}})," ",t]})]}),c.jsxs("svg",{ref:h,role:"img","aria-label":ie,className:"w-full overflow-hidden",style:{height:i},viewBox:`0 0 ${m} ${i}`,children:[Ts(j,C,4).map((ae,re)=>{const se=I(ae);return c.jsxs("g",{children:[c.jsx("line",{x1:Zt.left,x2:m-Zt.right,y1:se,y2:se,className:"stroke-line"}),c.jsx("text",{x:Zt.left-6,y:se+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(ae)})]},re)}),Ts(H,L,4).map((ae,re)=>c.jsx("text",{x:m-Zt.right+6,y:U(ae)+3,textAnchor:"start",className:"text-[10px]",fill:X,children:u(ae)},re)),c.jsx("line",{x1:Zt.left,x2:m-Zt.right,y1:z,y2:z,className:"stroke-line"}),n.map((ae,re)=>{const se=b[re],A=I(se);return c.jsxs("g",{children:[c.jsx("rect",{x:Q(re)-V/2,y:Math.min(A,z),width:V,height:Math.abs(A-z),"data-label":ae.label,"data-bar":se,"data-line":w[re],className:se<0?"fill-danger":"fill-chart-primary",...x(c.jsx(os,{title:ae.label,rows:[{label:e,value:a(se),swatch:"var(--chart-primary)"},{label:t,value:u(w[re]),swatch:X}]}))}),c.jsx("text",{x:Q(re),y:i-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:ae.label.slice(0,8)})]},ae.label)}),c.jsx("path",{d:`M ${ee}`,fill:"none",stroke:X,strokeWidth:1.75}),n.map((ae,re)=>c.jsx("circle",{cx:Q(re),cy:U(w[re]),r:3,fill:X,...x(c.jsx(os,{title:ae.label,rows:[{label:e,value:a(b[re]),swatch:"var(--chart-primary)"},{label:t,value:u(w[re]),swatch:X}]}))},ae.label))]}),c.jsx(rr,{tip:v})]})}const a2={primary:"border-accent bg-accent-soft font-medium text-accent hover:bg-accent hover:text-surface",secondary:"border-line bg-surface text-ink hover:bg-surface-soft",ghost:"border-transparent bg-transparent text-muted hover:bg-surface-soft hover:text-ink",danger:"border-danger bg-danger-soft font-medium text-danger hover:bg-danger hover:text-surface"};function No({variant:n="secondary",size:e="md",type:t="button",className:i,...a}){const u=e==="sm"?"h-6 px-2.5 text-2xs":"h-7 px-3 text-xs";return c.jsx("button",{type:t,"data-variant":n,className:`inline-flex items-center justify-center rounded-full border ${u} ${a2[n]} disabled:pointer-events-none disabled:opacity-50 ${i??""}`,...a})}function l2(n,e){const t=e.trim().toLowerCase();return t?n.filter(i=>i.value.toLowerCase().includes(t)||(i.label??"").toLowerCase().includes(t)):n}function iy(n){const{options:e,placeholder:t="Search…",ariaLabel:i,disabled:a,maxVisible:u=50}=n,f=M.useId(),h=M.useRef(null),[m,g]=M.useState(!1),[v,x]=M.useState(""),[b,w]=M.useState(0),j=M.useMemo(()=>l2(e,v).slice(0,u),[e,v,u]),C=n.multiple?n.values:n.value!=null?[n.value]:[],O=new Set(C),H=I=>{var U;return((U=e.find(G=>G.value===I))==null?void 0:U.label)??I};M.useEffect(()=>{if(!m)return;function I(U){h.current&&!h.current.contains(U.target)&&g(!1)}return document.addEventListener("mousedown",I,!0),()=>document.removeEventListener("mousedown",I,!0)},[m]);function L(I){if(I){if(n.multiple){const U=O.has(I.value)?n.values.filter(G=>G!==I.value):[...n.values,I.value];n.onChange(U);return}n.onChange(I.value),x(""),g(!1)}}function R(){n.multiple?n.onChange([]):n.onChange(null),x("")}function T(I){I.key==="ArrowDown"?(I.preventDefault(),g(!0),w(U=>Math.min(U+1,j.length-1))):I.key==="ArrowUp"?(I.preventDefault(),w(U=>Math.max(U-1,0))):I.key==="Enter"?(I.preventDefault(),m&&L(j[b])):I.key==="Escape"?g(!1):I.key==="Backspace"&&n.multiple&&!v&&n.values.length&&n.onChange(n.values.slice(0,-1))}const E=!n.multiple&&n.value!=null?H(n.value):t;return c.jsxs("div",{ref:h,className:"relative inline-flex min-w-40 flex-wrap items-center gap-1 text-xs",children:[n.multiple?n.values.map(I=>c.jsxs("span",{"data-chip":I,className:"inline-flex items-center gap-1 rounded-full bg-surface-soft px-2 py-0.5 leading-4 text-muted",children:[c.jsx("span",{className:"max-w-32 truncate",children:H(I)}),c.jsx("button",{type:"button","aria-label":`Remove ${H(I)}`,disabled:a,onClick:()=>n.onChange(n.values.filter(U=>U!==I)),className:"text-faint hover:text-ink",children:"×"})]},I)):null,c.jsxs("span",{className:"relative min-w-28 flex-1",children:[c.jsx("input",{type:"text",role:"combobox","aria-expanded":m,"aria-controls":f,"aria-autocomplete":"list","aria-activedescendant":m&&j[b]?`${f}-${b}`:void 0,"aria-label":i,disabled:a,placeholder:E,value:v,onChange:I=>{x(I.target.value),w(0),g(!0)},onFocus:()=>g(!0),onKeyDown:T,className:"h-7 w-full rounded-full border border-line bg-surface px-3 text-ink placeholder:text-faint disabled:opacity-50"}),C.length>0?c.jsx("button",{type:"button","aria-label":"Clear selection",disabled:a,onClick:R,className:"absolute right-1 top-1/2 -translate-y-1/2 px-1 text-faint hover:text-ink",children:"×"}):null]}),m?c.jsxs("ul",{id:f,role:"listbox","aria-multiselectable":n.multiple||void 0,className:"absolute left-0 top-full z-50 mt-1 max-h-56 w-full min-w-40 overflow-y-auto rounded-xl border border-line bg-surface p-1.5 shadow-[var(--shadow)]",children:[j.length===0?c.jsx("li",{className:"px-1.5 py-1 text-faint",children:"No matches"}):null,j.map((I,U)=>c.jsxs("li",{id:`${f}-${U}`,role:"option","aria-selected":O.has(I.value),"data-active":U===b||void 0,onMouseEnter:()=>w(U),onMouseDown:G=>{G.preventDefault(),L(I)},className:"cursor-pointer truncate rounded-md px-2 py-1 text-muted data-[active=true]:bg-surface-soft data-[active=true]:text-ink",children:[I.label??I.value,O.has(I.value)?c.jsx("span",{className:"float-right text-accent",children:"✓"}):null]},I.value))]}):null]})}function u2({title:n,eyebrow:e="Sidemantic",status:t,toolbar:i,children:a}){return c.jsxs("main",{className:"mx-auto max-w-6xl px-4 py-5 text-ink sm:px-6",children:[c.jsxs("header",{className:"flex flex-wrap items-end justify-between gap-4 border-b border-line pb-4",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-xs font-medium text-faint",children:e}),c.jsx("h1",{className:"mt-1 text-2xl font-semibold text-ink",children:n})]}),t?c.jsx("div",{className:"text-sm text-muted",children:t}):null]}),i?c.jsx("section",{className:"flex flex-wrap gap-2 py-3",children:i}):null,c.jsx("section",{className:"grid gap-4 py-4",children:a})]})}const c2=["Su","Mo","Tu","We","Th","Fr","Sa"],oy=["January","February","March","April","May","June","July","August","September","October","November","December"];function r0(n,e,t){return`${String(n).padStart(4,"0")}-${String(e+1).padStart(2,"0")}-${String(t).padStart(2,"0")}`}function d2(n,e){const t=new Date(Date.UTC(n,e,1)),i=new Date(t);i.setUTCDate(1-t.getUTCDay());const a=[],u=new Date(i);do{const f=[];for(let h=0;h<7;h+=1)f.push({iso:r0(u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()),day:u.getUTCDate(),inMonth:u.getUTCMonth()===e}),u.setUTCDate(u.getUTCDate()+1);a.push(f)}while(u.getUTCMonth()===e);return a}function yd(){const n=new Date;return r0(n.getFullYear(),n.getMonth(),n.getDate())}function ay(n){var T;const{inline:e,ariaLabel:t,disabled:i}=n,a=n.mode==="range",u=a?((T=n.value)==null?void 0:T.from)??null:n.value,[f,h]=M.useState(()=>Number((u??yd()).slice(0,4))),[m,g]=M.useState(()=>Number((u??yd()).slice(5,7))-1),[v,x]=M.useState(null),b=M.useRef(null);function w(E){const I=new Date(Date.UTC(f,m+E,1));h(I.getUTCFullYear()),g(I.getUTCMonth())}function j(E){if(!a){n.onChange(E),b.current&&(b.current.open=!1);return}if(!v){x(E);return}const[I,U]=v<=E?[v,E]:[E,v];n.onChange({from:I,to:U}),x(null),b.current&&(b.current.open=!1)}function C(E){return a?v?E===v:n.value!=null&&E>=n.value.from&&E<=n.value.to:E===n.value}function O(E){return a?v?E===v:n.value!=null&&(E===n.value.from||E===n.value.to):E===n.value}const H=yd(),L=c.jsxs("div",{className:"w-56 select-none rounded-xl border border-line bg-surface p-2.5 text-2xs","aria-label":t??"Calendar",children:[c.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[c.jsx("button",{type:"button","aria-label":"Previous month",onClick:()=>w(-1),className:"px-1.5 py-0.5 text-muted hover:bg-surface-soft hover:text-ink",children:"‹"}),c.jsxs("span",{className:"font-medium text-ink",children:[oy[m]," ",f]}),c.jsx("button",{type:"button","aria-label":"Next month",onClick:()=>w(1),className:"px-1.5 py-0.5 text-muted hover:bg-surface-soft hover:text-ink",children:"›"})]}),c.jsx("div",{className:"grid grid-cols-7 text-center text-faint",children:c2.map(E=>c.jsx("span",{className:"py-0.5",children:E},E))}),c.jsx("div",{role:"grid","aria-label":`${oy[m]} ${f}`,children:d2(f,m).map((E,I)=>c.jsx("div",{role:"row",className:"grid grid-cols-7",children:E.map(U=>c.jsx("button",{type:"button",role:"gridcell","aria-selected":C(U.iso),"data-date":U.iso,onClick:()=>j(U.iso),className:`py-1 text-center tnum ${O(U.iso)?"bg-accent text-surface":C(U.iso)?"bg-accent-soft text-accent":U.inMonth?"text-ink hover:bg-surface-soft":"text-faint hover:bg-surface-soft"} ${U.iso===H?"underline underline-offset-2":""}`,children:U.day},U.iso))},I))}),a&&v?c.jsxs("p",{className:"mt-1 text-faint",children:["Start ",v," — pick an end date."]}):null,n.value!=null?c.jsx("button",{type:"button",onClick:()=>n.onChange(null),className:"mt-1 w-full rounded-lg border border-line px-2 py-1 text-left text-muted hover:bg-surface-soft",children:"Clear"}):null]});if(e)return L;const R=a?n.value?`${n.value.from} → ${n.value.to}`:"Any dates":n.value??"Any date";return c.jsxs("details",{ref:b,className:"relative inline-block text-xs",children:[c.jsxs("summary",{className:`flex cursor-pointer items-center h-7 gap-1.5 rounded-full border border-line bg-surface px-3 text-ink ${i?"pointer-events-none opacity-50":""}`,children:[c.jsx("span",{className:"text-faint",children:t??"Date"}),c.jsx("span",{className:"tnum",children:R}),c.jsx("span",{"aria-hidden":"true",className:"text-faint",children:"▾"})]}),c.jsx("div",{className:"absolute left-0 z-50 mt-1 shadow-[var(--shadow)]",children:L})]})}function f2({result:n,pageSize:e=10}){const t=(n==null?void 0:n.columns)??[];return c.jsx(Ho,{columns:t.map(i=>({key:i,label:Le(i),numeric:n==null?void 0:n.sample_rows.some(a=>typeof a[i]=="number")})),rows:(n==null?void 0:n.sample_rows)??[],pageSize:e,renderCell:(i,a)=>pt(a)})}function h2({data:n,height:e=200,ariaLabel:t}){return c.jsx("div",{style:{minHeight:e},children:c.jsx(Go,{points:n.map(({label:i,value:a})=>({x:i,y:a})),formatValue:i=>pt(i),ariaLabel:t})})}const s0=Math.PI*2;function p2(n){const e=n.map((a,u)=>({...a,colorIndex:u})).filter(a=>Number.isFinite(a.value)&&a.value>0),t=e.reduce((a,u)=>a+u.value,0);if(t<=0)return[];let i=-Math.PI/2;return e.map(a=>{const u=a.value/t,f=i;return i+=u*s0,{label:a.label,value:a.value,share:u,startAngle:f,endAngle:i,colorIndex:a.colorIndex}})}function m2(n,e,t,i,a,u){const f=Math.min(u-a,s0-1e-4),h=a+f,m=f>Math.PI?1:0,g=n+i*Math.cos(a),v=e+i*Math.sin(a),x=n+i*Math.cos(h),b=e+i*Math.sin(h),w=n+t*Math.cos(h),j=e+t*Math.sin(h),C=n+t*Math.cos(a),O=e+t*Math.sin(a);return[`M ${g.toFixed(2)} ${v.toFixed(2)}`,`A ${i} ${i} 0 ${m} 1 ${x.toFixed(2)} ${b.toFixed(2)}`,`L ${w.toFixed(2)} ${j.toFixed(2)}`,`A ${t} ${t} 0 ${m} 0 ${C.toFixed(2)} ${O.toFixed(2)}`,"Z"].join(" ")}function y2({data:n,height:e=200,centerLabel:t="Total",format:i=pt,ariaLabel:a}){const u=M.useRef(null),[f,h]=M.useState(360),{tip:m,handlers:g}=Dr();M.useEffect(()=>us(u.current,220,h),[]);const v=p2(n),x=v.reduce((L,R)=>L+R.value,0),b=Math.min(e,f*.55),w=b/2,j=e/2,C=b/2-6,O=Math.max(C*.62,C-34),H=a||`Donut chart, ${v.length} segments totaling ${Wt(x)}`;return v.length===0?c.jsx("div",{className:"grid h-[200px] place-items-center text-xs text-faint",children:"No positive values to chart."}):c.jsxs("div",{ref:u,className:"flex w-full items-center gap-4",style:{height:e},children:[c.jsxs("svg",{role:"img","aria-label":H,width:b,height:e,className:"shrink-0 overflow-hidden",children:[v.map(L=>c.jsx("path",{d:m2(w,j,O,C,L.startAngle,L.endAngle),fill:yn(L.colorIndex),stroke:"var(--surface)",strokeWidth:1,"data-label":L.label,"data-value":L.value,...g(c.jsx(os,{title:L.label,rows:[{label:"Value",value:i(L.value),swatch:yn(L.colorIndex)},{label:"Share",value:`${(L.share*100).toFixed(1)}%`}]}))},L.label)),c.jsx("text",{x:w,y:j-4,textAnchor:"middle",className:"fill-ink font-mono tnum text-sm font-medium",children:Wt(x)}),c.jsx("text",{x:w,y:j+12,textAnchor:"middle",className:"fill-faint text-[10px]",children:t})]}),c.jsx("ul",{className:"min-w-0 flex-1 space-y-1 text-2xs",children:v.map(L=>c.jsxs("li",{className:"flex items-center gap-2","data-label":L.label,children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 shrink-0",style:{background:yn(L.colorIndex)}}),c.jsx("span",{className:"truncate text-muted",children:L.label}),c.jsx("span",{className:"ml-auto font-mono tnum text-ink",children:i(L.value)}),c.jsxs("span",{className:"w-10 text-right font-mono tnum text-faint",children:[(L.share*100).toFixed(1),"%"]})]},L.label))}),c.jsx(rr,{tip:m})]})}const pr={top:8,right:8,bottom:26,left:76};function ly(n,e,t){if(t!=null&&t.length)return t;const i=[];for(const a of n)i.includes(a[e])||i.push(a[e]);return i}function g2({cells:n,xLabels:e,yLabels:t,height:i=240,format:a=pt,ariaLabel:u}){const f=M.useRef(null),[h,m]=M.useState(640),{tip:g,handlers:v}=Dr();M.useEffect(()=>us(f.current,240,m),[]);const x=ly(n,"x",e),b=ly(n,"y",t);if(x.length===0||b.length===0)return c.jsx("div",{className:"grid h-[240px] place-items-center text-xs text-faint",children:"No cells to chart."});const w=new Map(n.map(I=>[`${I.x}\0${I.y}`,I.value])),j=n.map(I=>Math.abs(I.value)).filter(Number.isFinite),C=Math.max(...j,0)||1,O=h-pr.left-pr.right,H=i-pr.top-pr.bottom,L=O/x.length,R=H/b.length,T=Math.max(1,Math.ceil(x.length/Math.max(1,Math.floor(O/56)))),E=u||`Heatmap, ${x.length} by ${b.length} cells`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:f,role:"img","aria-label":E,className:"w-full overflow-hidden",style:{height:i},viewBox:`0 0 ${h} ${i}`,children:[b.map((I,U)=>c.jsx("text",{x:pr.left-6,y:pr.top+U*R+R/2+3,textAnchor:"end",className:"fill-muted text-[10px]",children:I.slice(0,12)},I)),x.map((I,U)=>U%T===0?c.jsx("text",{x:pr.left+U*L+L/2,y:i-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:I.slice(0,8)},I):null),b.map((I,U)=>x.map((G,V)=>{const Q=w.get(`${G}\0${I}`),z=Q!=null&&Number.isFinite(Q),ee=z?.06+.94*(Math.abs(Q)/C):0;return c.jsx("rect",{x:pr.left+V*L+.5,y:pr.top+U*R+.5,width:Math.max(1,L-1),height:Math.max(1,R-1),"data-x":G,"data-y":I,"data-value":z?Q:void 0,className:z&&Q<0?"fill-danger":"fill-chart-primary",fillOpacity:z?ee:.03,...v(c.jsx(os,{title:`${I} / ${G}`,rows:[{label:"Value",value:z?a(Q):"no data"}]}))},`${G}\0${I}`)}))]}),c.jsx(rr,{tip:g})]})}function v2(n,e){const t=n.filter(Number.isFinite);if(t.length===0)return[];const i=Math.min(...t),a=Math.max(...t),u=Math.max(1,Math.floor(e??Math.min(40,Math.ceil(Math.log2(t.length)+1))));if(i===a)return[{x0:i,x1:a,count:t.length}];const f=(a-i)/u,h=Array.from({length:u},(m,g)=>({x0:i+g*f,x1:i+(g+1)*f,count:0}));for(const m of t){const g=Math.min(u-1,Math.floor((m-i)/f));h[g].count+=1}return h}const Cn={top:12,right:14,bottom:26,left:44};function x2({values:n,bins:e,height:t=200,format:i=Wt,ariaLabel:a}){const u=M.useRef(null),[f,h]=M.useState(640),{tip:m,handlers:g}=Dr();M.useEffect(()=>us(u.current,160,h),[]);const v=v2(n,e);if(v.length===0)return c.jsx("div",{className:"grid h-[200px] place-items-center text-xs text-faint",children:"No numeric values to chart."});const x=Math.max(...v.map(R=>R.count),1),b=f-Cn.left-Cn.right,w=t-Cn.top-Cn.bottom,j=R=>Cn.top+(1-R/x)*w,C=b/v.length,O=Ts(0,x,4),H=Math.max(1,Math.ceil(v.length/6)),L=a||`Histogram, ${v.length} bins from ${i(v[0].x0)} to ${i(v[v.length-1].x1)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:u,role:"img","aria-label":L,className:"w-full overflow-hidden",style:{height:t},viewBox:`0 0 ${f} ${t}`,children:[O.map((R,T)=>{const E=j(R);return c.jsxs("g",{children:[c.jsx("line",{x1:Cn.left,x2:f-Cn.right,y1:E,y2:E,className:"stroke-line"}),c.jsx("text",{x:Cn.left-6,y:E+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(R)})]},T)}),v.map((R,T)=>{const E=Cn.left+C*T,I=j(R.count);return c.jsx("rect",{x:E+.5,y:I,width:Math.max(1,C-1),height:Cn.top+w-I,"data-x0":R.x0,"data-x1":R.x1,"data-count":R.count,className:"fill-chart-primary",...g(c.jsx(os,{title:`${i(R.x0)} – ${i(R.x1)}`,rows:[{label:"Count",value:R.count.toLocaleString()}]}))},T)}),v.map((R,T)=>T%H===0?c.jsx("text",{x:Cn.left+C*T,y:t-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:i(R.x0)},T):null)]}),c.jsx(rr,{tip:m})]})}function b2(n){let e=2166136261;for(let t=0;t>>0}function w2(n){let e=n||1;return()=>{e|=0,e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function S2(n,e,{width:t=640,height:i=320,iterations:a=150}={}){if(n.length===0)return[];const u=w2(b2(n.map(G=>G.id).join("\0"))),f=new Map(n.map((G,V)=>[G.id,V])),h=n.map(()=>u()*t),m=n.map(()=>u()*i),g=n.map(()=>0),v=n.map(()=>0),x=n.map(()=>0),b=[];for(const G of e){const V=f.get(G.source),Q=f.get(G.target);V==null||Q==null||V===Q||(b.push([V,Q]),x[V]+=1,x[Q]+=1)}const w=t*i,j=Math.sqrt(w/n.length);let C=Math.max(t,i)/8;const O=C/(a+1);for(let G=0;G({...G,x:H+(h[V]-L)/I*(t-H*2),y:H+(m[V]-T)/U*(i-H*2),degree:x[V]}))}function _2({nodes:n,links:e,height:t=320,ariaLabel:i}){const a=M.useRef(null),[u,f]=M.useState(640),{tip:h,handlers:m}=Dr();M.useEffect(()=>us(a.current,240,f),[]);const g=M.useMemo(()=>S2(n,e,{width:u,height:t}),[n,e,u,t]),v=M.useMemo(()=>new Map(g.map(j=>[j.id,j])),[g]),x=M.useMemo(()=>[...new Set(n.map(j=>j.group??""))],[n]),b=Math.max(...e.map(j=>j.weight??1),1);if(g.length===0)return c.jsx("div",{className:"grid h-[320px] place-items-center text-xs text-faint",children:"No nodes to chart."});const w=i||`Network graph, ${n.length} nodes and ${e.length} links`;return c.jsxs(c.Fragment,{children:[x.length>1?c.jsx("div",{className:"mb-1 flex flex-wrap items-center gap-3 text-2xs text-faint",children:x.map((j,C)=>c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2 rounded-full",style:{background:yn(C)}}),j||"(default)"]},j||"(default)"))}):null,c.jsxs("svg",{ref:a,role:"img","aria-label":w,className:"w-full overflow-hidden",style:{height:t},viewBox:`0 0 ${u} ${t}`,children:[e.map((j,C)=>{const O=v.get(j.source),H=v.get(j.target);return!O||!H?null:c.jsx("line",{x1:O.x,y1:O.y,x2:H.x,y2:H.y,className:"stroke-line",strokeWidth:.75+2.25*((j.weight??1)/b),"data-source":j.source,"data-target":j.target},C)}),g.map(j=>{const C=5+Math.min(9,j.degree*1.5);return c.jsxs("g",{children:[c.jsx("circle",{cx:j.x,cy:j.y,r:C,fill:yn(x.indexOf(j.group??"")),stroke:"var(--surface)",strokeWidth:1.5,"data-id":j.id,"data-degree":j.degree,...m(c.jsx(os,{title:j.label??j.id,rows:[{label:"Connections",value:String(j.degree)},...j.group?[{label:"Group",value:j.group,swatch:yn(x.indexOf(j.group))}]:[]]}))}),c.jsx("text",{x:j.x,y:j.y-C-4,textAnchor:"middle",className:"pointer-events-none fill-muted text-[10px]",children:(j.label??j.id).slice(0,14)})]},j.id)})]}),c.jsx(rr,{tip:h})]})}function wl({value:n,options:e,onChange:t,label:i,ariaLabel:a,placeholder:u,disabled:f}){return c.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-faint",children:[i?c.jsx("span",{className:"hidden sm:inline",children:i}):null,c.jsxs("select",{"aria-label":a??i,value:n,disabled:f,onChange:h=>t(h.target.value),className:"h-7 rounded-full border border-line bg-surface px-2.5 text-xs text-ink disabled:opacity-50",children:[u?c.jsx("option",{value:"",disabled:!0,children:u}):null,e.map(h=>c.jsx("option",{value:h.value,children:h.label??h.value},h.value))]})]})}const un={top:12,right:14,bottom:26,left:48};function N2(n,e,t){return Math.min(Math.max(n,e),t)}function j2({labels:n,series:e,height:t=240,format:i=pt,formatLabel:a=f=>f,ariaLabel:u}){const f=M.useRef(null),[h,m]=M.useState(640),[g,v]=M.useState(null);M.useEffect(()=>us(f.current,240,m),[]);const x=n.length;if(x<2||e.length===0)return c.jsx("div",{className:"grid h-[240px] place-items-center text-xs text-faint",children:"Not enough data to chart."});const b=e.map(V=>({name:V.name,values:n.map((Q,z)=>{const ee=V.values[z];return Number.isFinite(ee)&&ee>0?ee:0})})),w=[];let j=n.map(()=>0);for(const V of b){const Q=V.values.map((z,ee)=>j[ee]+z);w.push(Q),j=Q}const C=Math.max(...j,1),O=h-un.left-un.right,H=t-un.top-un.bottom,L=V=>un.left+V/(x-1)*O,R=V=>un.top+(1-V/C)*H,T=Math.max(1,Math.ceil(x/8)),E=u||`Stacked area chart, ${e.length} series over ${x} points`;function I(V){const Q=w[V],z=V===0?n.map(()=>0):w[V-1],ee=Q.map((ie,ae)=>`${L(ae).toFixed(1)},${R(ie).toFixed(1)}`).join(" L "),X=[...z.keys()].reverse().map(ie=>`${L(ie).toFixed(1)},${R(z[ie]).toFixed(1)}`).join(" L ");return`M ${ee} L ${X} Z`}function U(V){const Q=V.currentTarget.getBoundingClientRect(),z=(V.clientX-Q.left)/Q.width*h,ee=Math.round((z-un.left)/O*(x-1));v(ee>=0&&eec.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2",style:{background:yn(Q)}}),V.name]},V.name))}),c.jsxs("svg",{role:"img","aria-label":E,className:"w-full overflow-hidden",style:{height:t},viewBox:`0 0 ${h} ${t}`,onMouseMove:U,onMouseLeave:()=>v(null),children:[Ts(0,C,4).map((V,Q)=>{const z=R(V);return c.jsxs("g",{children:[c.jsx("line",{x1:un.left,x2:h-un.right,y1:z,y2:z,className:"stroke-line"}),c.jsx("text",{x:un.left-6,y:z+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(V)})]},Q)}),b.map((V,Q)=>c.jsx("path",{d:I(Q),fill:yn(Q),fillOpacity:.8,"data-series":V.name},V.name)),g!=null?c.jsx("line",{x1:L(g),x2:L(g),y1:un.top,y2:t-un.bottom,className:"stroke-faint",strokeDasharray:"3 3"}):null,n.map((V,Q)=>Q%T===0||Q===x-1?c.jsx("text",{x:L(Q),y:t-8,textAnchor:"middle",className:"fill-faint font-mono text-[10px]",children:a(V)},V):null)]}),g!=null?c.jsxs("div",{className:"pointer-events-none absolute top-8 z-20 -translate-x-1/2 whitespace-nowrap border border-line bg-surface px-2 py-1.5 text-2xs shadow-[var(--shadow)]",style:{left:G},children:[c.jsx("div",{className:"mb-0.5 font-mono text-faint",children:a(n[g])}),b.map((V,Q)=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs("span",{className:"flex items-center gap-1 text-muted",children:[c.jsx("span",{"aria-hidden":"true",className:"inline-block size-2",style:{background:yn(Q)}}),V.name]}),c.jsx("span",{className:"font-mono tnum text-ink",children:i(V.values[g])})]},V.name))]}):null]})}function k2({checked:n,onChange:e,label:t,ariaLabel:i,disabled:a}){return c.jsxs("label",{className:`flex items-center gap-1.5 text-xs ${a?"opacity-50":""}`,children:[c.jsx("button",{type:"button",role:"switch","aria-checked":n,"aria-label":i??t,disabled:a,onClick:()=>e(!n),"data-checked":n||void 0,className:`relative h-4 w-7 shrink-0 rounded-full border transition-colors ${n?"border-accent bg-accent":"border-line bg-surface-soft"}`,children:c.jsx("span",{"aria-hidden":"true",className:`absolute top-1/2 size-3 -translate-y-1/2 rounded-full bg-surface shadow transition-[left] ${n?"left-[14px]":"left-[2px]"}`})}),t?c.jsx("span",{className:"text-muted",children:t}):null]})}function I2({tabs:n,active:e,onChange:t,ariaLabel:i="Tabs"}){return c.jsx("div",{role:"tablist","aria-label":i,className:"inline-flex items-center gap-0.5 rounded-full border border-line bg-surface p-px",children:n.map(a=>c.jsx("button",{role:"tab",type:"button","aria-selected":e===a.key,"data-tab":a.key,"data-selected":e===a.key||void 0,onClick:()=>t(a.key),className:"inline-flex h-6 items-center rounded-full px-2.5 text-xs font-medium text-muted hover:bg-surface-soft hover:text-ink data-[selected=true]:bg-accent-soft data-[selected=true]:text-accent",children:a.label},a.key))})}function M2({content:n,children:e,className:t}){const{tip:i,handlers:a}=Dr();return c.jsxs(c.Fragment,{children:[c.jsx("span",{className:t??"inline-flex",...a(n),children:e}),c.jsx(rr,{tip:i})]})}function D2(n){let e=0;return n.map(t=>{const i=Number.isFinite(t.value)?t.value:0;if(t.isTotal)return e=i,{...t,value:i,start:0,end:i};const a=e;return e+=i,{...t,value:i,start:a,end:e}})}const cn={top:12,right:14,bottom:26,left:48};function C2({data:n,height:e=220,format:t=pt,ariaLabel:i}){const a=M.useRef(null),[u,f]=M.useState(640),{tip:h,handlers:m}=Dr();M.useEffect(()=>us(a.current,200,f),[]);const g=D2(n);if(g.length===0)return c.jsx("div",{className:"grid h-[220px] place-items-center text-xs text-faint",children:"No steps to chart."});const v=g.flatMap(E=>[E.start,E.end]),x=Math.min(0,...v),b=Math.max(0,...v),w=b-x||1,j=u-cn.left-cn.right,C=e-cn.top-cn.bottom,O=E=>cn.top+(1-(E-x)/w)*C,H=j/g.length,L=Math.max(10,Math.min(56,H*.62)),R=Ts(x,b,4),T=i||`Waterfall chart, ${g.length} steps ending at ${t(g[g.length-1].end)}`;return c.jsxs(c.Fragment,{children:[c.jsxs("svg",{ref:a,role:"img","aria-label":T,className:"w-full overflow-hidden",style:{height:e},viewBox:`0 0 ${u} ${e}`,children:[R.map((E,I)=>{const U=O(E);return c.jsxs("g",{children:[c.jsx("line",{x1:cn.left,x2:u-cn.right,y1:U,y2:U,className:"stroke-line"}),c.jsx("text",{x:cn.left-6,y:U+3,textAnchor:"end",className:"fill-faint text-[10px]",children:Wt(E)})]},I)}),c.jsx("line",{x1:cn.left,x2:u-cn.right,y1:O(0),y2:O(0),className:"stroke-faint"}),g.map((E,I)=>{const U=cn.left+H*I+(H-L)/2,G=O(E.start),V=O(E.end),Q=E.isTotal?"total":E.value<0?"negative":"positive",z=E.isTotal?"fill-faint":E.value<0?"fill-danger":"fill-chart-primary",ee=g[I+1];return c.jsxs("g",{children:[c.jsx("rect",{x:U,y:Math.min(G,V),width:L,height:Math.max(1,Math.abs(V-G)),"data-label":E.label,"data-value":E.value,"data-tone":Q,className:z,...m(c.jsx(os,{title:E.label,rows:E.isTotal?[{label:"Total",value:t(E.end)}]:[{label:"Change",value:t(E.value)},{label:"Running",value:t(E.end)}]}))}),ee?c.jsx("line",{x1:U+L,x2:cn.left+H*(I+1)+(H-L)/2,y1:V,y2:V,className:"stroke-faint",strokeDasharray:"3 3"}):null,c.jsx("text",{x:U+L/2,y:e-8,textAnchor:"middle",className:"fill-muted text-[10px]",children:E.label.slice(0,9)})]},`${E.label}-${I}`)})]}),c.jsx(rr,{tip:h})]})}function uy(n){return n==null?"∅":String(n)}function F2(n){const e=typeof n=="number"?n:Number(n);return Number.isFinite(e)?e:Number.NaN}function O2(n,e){const t=[],i=[],a=new Map;for(const u of n){const f=uy(u[e.x]),h=uy(u[e.series]);t.includes(f)||t.push(f),i.includes(h)||i.push(h),a.set(`${h}\0${f}`,F2(u[e.y]))}return{labels:t,series:i.map(u=>({name:u,values:t.map(f=>a.get(`${u}\0${f}`)??0)}))}}const T2=[{dimension:"orders.region",title:"Customer Region",rows:[["East",83262],["South",80579],["West",71561],["North",52889]].map(([n,e])=>({value:String(n),metric:Number(e)}))},{dimension:"orders.status",title:"Order Status",rows:[["completed",170379],["cancelled",64637],["pending",53275]].map(([n,e])=>({value:String(n),metric:Number(e)}))},{dimension:"products.category",title:"Product Category",rows:[["Electronics",202015],["Furniture",83848],["Office Supplies",2428]].map(([n,e])=>({value:String(n),metric:Number(e)}))},{dimension:"customers.name",title:"Top Customers",rows:[["Bob Smith",46690],["Carol Davis",42227],["Henry Taylor",41633],["Grace Lee",41035],["Frank Brown",33890],["David Wilson",29928],["Alice Johnson",27114],["Emma Martinez",24802]].map(([n,e])=>({value:String(n),metric:Number(e)}))}],A2=[{key:"region",label:"Region",sortable:!0},{key:"revenue",label:"Revenue",numeric:!0,sortable:!0},{key:"orders",label:"Orders",numeric:!0,sortable:!0}],cy=Array.from({length:17},(n,e)=>({region:["East","South","West","North"][e%4],revenue:91e3-e*2875,orders:420-e*11})),hf=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug"],B2=hf.flatMap((n,e)=>[{month:n,plan:"Basic",revenue:120+e*26},{month:n,plan:"Pro",revenue:60+e*24},{month:n,plan:"Enterprise",revenue:e<2?0:10+e*12}]),E2=Array.from({length:48},(n,e)=>({x:e+1,y:(e+1)*1.6+Math.sin(e*78.233)*43758.5453%18,label:`Account ${e+1}`,series:e%2?"Returning":"New"})),R2=Array.from({length:400},(n,e)=>Math.abs(Math.sin(e*12.9898)*43758.5453%1)*100),L2=["East","South","West","North"].flatMap((n,e)=>hf.map((t,i)=>({x:t,y:n,value:(e+1)*(i+1)*7-(i%4===3?80:0)}))),dy=[{value:"orders.revenue",label:"Revenue"},{value:"orders.count",label:"Order count"},{value:"customers.count",label:"Customer count"},{value:"orders.margin",label:"Gross margin"}];function U2(){const[n,e]=M.useState("orders.revenue"),[t,i]=M.useState({}),[a,u]=M.useState(null),[f,h]=M.useState({"orders.region":["East","West"],"orders.status":["completed"]}),[m,g]=M.useState({from:"2025-01-01",to:"2025-06-30"}),[v,x]=M.useState("month"),[b,w]=M.useState("explore"),[j,C]=M.useState("previous"),[O,H]=M.useState("orders.revenue"),[L,R]=M.useState(["orders.revenue","orders.count"]),[T,E]=M.useState("apple"),[I,U]=M.useState(!0),[G,V]=M.useState("explore"),[Q,z]=M.useState("2025-06-15"),[ee,X]=M.useState({from:"2025-06-01",to:"2025-06-21"}),ie=M.useMemo(()=>O2(B2,{x:"month",y:"revenue",series:"plan"}),[]),[ae,re]=M.useState({key:"revenue",dir:"desc"}),se=M.useMemo(()=>[...cy].sort((A,Y)=>{const W=A[ae.key],_=Y[ae.key],F=typeof W=="number"&&typeof _=="number"?W-_:String(W).localeCompare(String(_));return ae.dir==="asc"?F:-F}),[ae]);return c.jsxs("main",{className:"min-h-screen bg-bg text-ink",children:[c.jsxs("header",{className:"sticky top-0 z-20 flex items-center justify-between border-b border-line bg-surface px-4 py-3",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-sm font-semibold",children:"Sidemantic component gallery"}),c.jsxs("p",{className:"text-2xs text-faint",children:["Canonical React primitives · ",c.jsx("a",{className:"text-accent hover:underline",href:"/typography",children:"typography workbench →"})]})]}),c.jsx($o,{})]}),c.jsxs("div",{className:"space-y-8 p-4",children:[c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Metric cards"}),c.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-3",children:[c.jsx(Nr,{metric:"orders.revenue",label:"Revenue",value:288291,format:{format:"currency"},selected:n==="orders.revenue",sparkValues:[31,42,38,55,60,74],onSelect:e}),c.jsx(Nr,{metric:"orders.count",label:"Order Count",value:447,selected:n==="orders.count",sparkValues:[21,34,28,41,44,51],onSelect:e}),c.jsx(Nr,{metric:"orders.margin",label:"Gross Margin",value:.324,format:{format:"percent"},delta:{label:"+1.1pt",tone:"positive"},comparison:"vs previous month",sparkValues:[24,26,29,27,31,32],selected:n==="orders.margin",onSelect:e})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Leaderboard cards"}),c.jsx("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(220px,1fr))] gap-0 border-l border-t border-line",children:T2.filter(A=>a===null||a===A.dimension).map(A=>c.jsx(Xv,{dimension:A.dimension,title:A.title,metricLabel:"Total Revenue",rows:A.rows,selectedValues:t[A.dimension],formatMetric:Y=>pt(Y,{format:"currency"}),onToggle:Y=>i(W=>{const _=W[A.dimension]??[];return{...W,[A.dimension]:_.includes(Y)?_.filter(F=>F!==Y):[..._,Y]}}),expanded:a===A.dimension,onExpandedChange:Y=>u(Y?A.dimension:null)},A.dimension))})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Filters and controls"}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{"data-testid":"gallery-filter-pills",className:"flex min-h-8 flex-wrap items-center gap-2",children:[Object.entries(f).flatMap(([A,Y])=>Y.map(W=>c.jsx(Od,{dimension:A,value:W,onRemove:()=>h(_=>({..._,[A]:_[A].filter(F=>F!==W)}))},`${A}:${W}`))),Object.values(f).every(A=>A.length===0)?c.jsx("span",{className:"text-2xs text-faint",children:"No active filters"}):null]}),c.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[c.jsx(Bv,{range:m,onChange:g,comparison:j,onComparisonChange:C}),c.jsx(Td,{grain:v,options:["day","week","month","quarter","year"],onChange:x}),c.jsx(Lv,{view:b,onChange:w}),c.jsxs("span",{className:"inline-flex items-center gap-1.5 text-2xs text-muted",children:[c.jsx(dd,{status:"ok"})," Ready"]}),c.jsxs("span",{className:"inline-flex items-center gap-1.5 text-2xs text-muted",children:[c.jsx(dd,{status:"loading"})," Updating"]}),c.jsx("button",{type:"button",onClick:()=>h({"orders.region":["East","West"],"orders.status":["completed"]}),className:"inline-flex h-7 items-center rounded-full border border-line px-3 text-xs text-muted hover:bg-surface-soft",children:"Reset filters"})]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Charts"}),c.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Sparkline"}),c.jsx(e0,{values:[31,42,38,55,60,74,69,83],labels:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug"],ariaLabel:"Eight month revenue trend"})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Column chart"}),c.jsx(t0,{data:[{label:"East",value:83},{label:"South",value:81},{label:"West",value:72},{label:"Returns",value:-18}]})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Line chart compatibility export"}),c.jsx(h2,{data:[{label:"Jan",value:31},{label:"Feb",value:42},{label:"Mar",value:38},{label:"Apr",value:55},{label:"May",value:60}]})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Interactive time series"}),c.jsx(Go,{points:[31,42,38,55,60,74].map((A,Y)=>({x:`2025-0${Y+1}-01`,y:A})),comparison:[27,35,33,48,52,61].map((A,Y)=>({x:`2024-0${Y+1}-01`,y:A})),formatValue:A=>`$${A.toLocaleString()}k`})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Donut"}),c.jsx(y2,{data:[{label:"iOS",value:4200},{label:"Android",value:3100},{label:"Web",value:1900},{label:"Other",value:400}]})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Stacked area (long rows via rowsToSeries)"}),c.jsx(j2,{labels:ie.labels,series:ie.series,height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Bar + line combo (dual axis)"}),c.jsx(o2,{data:hf.map((A,Y)=>({label:A,bar:200+Y*42,line:.02+Y*.004})),barLabel:"Revenue",lineLabel:"Conversion",formatLine:A=>`${(A*100).toFixed(1)}%`,height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Histogram"}),c.jsx(x2,{values:R2,bins:20})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Scatter"}),c.jsx(n0,{points:E2,xLabel:"Sessions",yLabel:"Orders",height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Heatmap"}),c.jsx(g2,{cells:L2,height:200})]}),c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Waterfall"}),c.jsx(C2,{data:[{label:"Gross",value:1e3,isTotal:!0},{label:"Refunds",value:-140},{label:"Discounts",value:-90},{label:"Upsells",value:130},{label:"Net",value:900,isTotal:!0}],height:200})]}),c.jsxs("article",{className:"min-w-0 xl:col-span-2",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold",children:"Network"}),c.jsx(_2,{nodes:[{id:"orders",group:"fact"},{id:"payments",group:"fact"},{id:"customers",group:"dimension"},{id:"products",group:"dimension"},{id:"regions",group:"dimension"}],links:[{source:"orders",target:"customers",weight:3},{source:"orders",target:"products",weight:2},{source:"orders",target:"regions"},{source:"payments",target:"orders",weight:2},{source:"payments",target:"customers"}],height:260})]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Inputs"}),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[c.jsx(No,{variant:"primary",children:"Primary"}),c.jsx(No,{children:"Secondary"}),c.jsx(No,{variant:"ghost",children:"Ghost"}),c.jsx(No,{variant:"danger",children:"Danger"}),c.jsx(No,{size:"sm",children:"Small"}),c.jsx(wl,{label:"Fruit",value:T,onChange:E,options:[{value:"apple",label:"Apple"},{value:"banana",label:"Banana"},{value:"cherry",label:"Cherry"}]}),c.jsx(k2,{checked:I,onChange:U,label:"Compact rows"}),c.jsx(I2,{tabs:[{key:"explore",label:"Explore"},{key:"pivot",label:"Pivot"},{key:"sql",label:"SQL"}],active:G,onChange:V}),c.jsx(M2,{content:"Revenue in USD, net of refunds",children:c.jsx("span",{className:"cursor-help text-2xs text-muted underline decoration-dotted",children:"What is revenue?"})})]}),c.jsxs("div",{className:"flex flex-wrap items-start gap-3",children:[c.jsx(iy,{value:O,onChange:H,options:dy,ariaLabel:"Metric"}),c.jsx(iy,{multiple:!0,values:L,onChange:R,options:dy,ariaLabel:"Metrics"}),c.jsx(ay,{mode:"single",value:Q,onChange:z,ariaLabel:"Date"}),c.jsx(ay,{mode:"range",value:ee,onChange:X,ariaLabel:"Range"})]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Analytical table"}),c.jsx(Ho,{columns:A2,rows:se,pageSize:6,sortKey:ae.key,sortDir:ae.dir,onSort:A=>re(Y=>({key:A,dir:Y.key===A&&Y.dir==="desc"?"asc":"desc"})),renderCell:(A,Y)=>A.numeric?Number(Y).toLocaleString():String(Y),searchable:!0,totals:{region:"count",revenue:"sum",orders:"sum"}}),c.jsxs("div",{className:"mt-3",children:[c.jsx("h3",{className:"mb-2 text-xs font-semibold text-muted",children:"Distribution-friendly data preview"}),c.jsx(f2,{result:{columns:["region","revenue","orders"],sample_rows:cy.slice(0,8)},pageSize:4})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Query inspection"}),c.jsx(au,{inputs:{Revenue:{metrics:["orders.revenue"],dimensions:["orders.region"],filters:["orders.status = 'completed'"]}},queries:{Revenue:`SELECT orders.region, SUM(orders.revenue) AS revenue FROM orders WHERE orders.status = 'completed' GROUP BY orders.region -ORDER BY revenue DESC`}})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"States"}),c.jsxs("div",{className:"grid gap-2 lg:grid-cols-3",children:[c.jsx(af,{message:"Loading metric results…"}),c.jsx(Xn,{message:"No matching rows."}),c.jsx(Bi,{message:"The query could not be completed."})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Dashboard shell"}),c.jsx("div",{children:c.jsx(o2,{eyebrow:"Embedded shell example",title:"Revenue overview",status:c.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[c.jsx(dd,{status:"ok"})," Connected"]}),toolbar:c.jsxs(c.Fragment,{children:[c.jsx(Od,{dimension:"orders.region",value:"East"}),c.jsx(Td,{grain:v,options:["day","month","quarter"],onChange:x})]}),children:c.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[c.jsx(Nr,{metric:"orders.revenue",label:"Revenue",value:288291,format:{format:"currency"},sparkValues:[31,42,38,55,60]}),c.jsx(Xn,{title:"Optional panel",message:"Shell content is composed from the same primitives."})]})})})]})]})]})}function ns(n){return`https://api.fontshare.com/v2/css?f[]=${n}&display=swap`}const uy=[{value:"system",label:"System (SF Pro)",stack:"system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif"},{value:"geist",label:"Geist",gf:"Geist:wght@400;500;600",stack:"'Geist', system-ui, sans-serif"},{value:"inter",label:"Inter",gf:"Inter:wght@400;500;600",stack:"'Inter', system-ui, sans-serif"},{value:"instrument",label:"Instrument Sans",gf:"Instrument+Sans:wght@400;500;600",stack:"'Instrument Sans', system-ui, sans-serif"},{value:"plex",label:"IBM Plex Sans",gf:"IBM+Plex+Sans:wght@400;500;600",stack:"'IBM Plex Sans', system-ui, sans-serif"},{value:"schibsted",label:"Schibsted Grotesk",gf:"Schibsted+Grotesk:wght@400;500;600",stack:"'Schibsted Grotesk', system-ui, sans-serif"},{value:"figtree",label:"Figtree",gf:"Figtree:wght@400;500;600",stack:"'Figtree', system-ui, sans-serif"},{value:"manrope",label:"Manrope",gf:"Manrope:wght@400;500;600",stack:"'Manrope', system-ui, sans-serif"},{value:"publicsans",label:"Public Sans",gf:"Public+Sans:wght@400;500;600",stack:"'Public Sans', system-ui, sans-serif"},{value:"spacegrotesk",label:"Space Grotesk",gf:"Space+Grotesk:wght@400;500;600",stack:"'Space Grotesk', system-ui, sans-serif"},{value:"satoshi",label:"Satoshi ✦",url:ns("satoshi@400,500,700"),stack:"'Satoshi', system-ui, sans-serif"},{value:"generalsans",label:"General Sans ✦",url:ns("general-sans@400,500,600"),stack:"'General Sans', system-ui, sans-serif"},{value:"switzer",label:"Switzer ✦",url:ns("switzer@400,500,600"),stack:"'Switzer', system-ui, sans-serif"},{value:"cabinet",label:"Cabinet Grotesk ✦",url:ns("cabinet-grotesk@400,500,700"),stack:"'Cabinet Grotesk', system-ui, sans-serif"},{value:"bricolage",label:"Bricolage Grotesque ✦",gf:"Bricolage+Grotesque:wght@400;500;600",stack:"'Bricolage Grotesque', system-ui, sans-serif"},{value:"familjen",label:"Familjen Grotesk ✦",gf:"Familjen+Grotesk:wght@400;500;600",stack:"'Familjen Grotesk', system-ui, sans-serif"},{value:"hanken",label:"Hanken Grotesk ✦",gf:"Hanken+Grotesk:wght@400;500;600",stack:"'Hanken Grotesk', system-ui, sans-serif"},{value:"reddit",label:"Reddit Sans ✦",gf:"Reddit+Sans:wght@400;500;600",stack:"'Reddit Sans', system-ui, sans-serif"},{value:"chivo",label:"Chivo ✦",gf:"Chivo:wght@400;500;600",stack:"'Chivo', system-ui, sans-serif"},{value:"hostgrotesk",label:"Host Grotesk ✦",gf:"Host+Grotesk:wght@400;500;600",stack:"'Host Grotesk', system-ui, sans-serif"},{value:"sora",label:"Sora ✦",gf:"Sora:wght@400;500;600",stack:"'Sora', system-ui, sans-serif"}],cy=[{value:"system",label:"System (SF Mono)",stack:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"},{value:"geistmono",label:"Geist Mono",gf:"Geist+Mono:wght@400;500",stack:"'Geist Mono', ui-monospace, monospace"},{value:"jetbrains",label:"JetBrains Mono",gf:"JetBrains+Mono:wght@400;500",stack:"'JetBrains Mono', ui-monospace, monospace"},{value:"plexmono",label:"IBM Plex Mono",gf:"IBM+Plex+Mono:wght@400;500",stack:"'IBM Plex Mono', ui-monospace, monospace"},{value:"firacode",label:"Fira Code",gf:"Fira+Code:wght@400;500",stack:"'Fira Code', ui-monospace, monospace"},{value:"splinemono",label:"Spline Sans Mono",gf:"Spline+Sans+Mono:wght@400;500",stack:"'Spline Sans Mono', ui-monospace, monospace"},{value:"dmmono",label:"DM Mono",gf:"DM+Mono:wght@400;500",stack:"'DM Mono', ui-monospace, monospace"},{value:"martianmono",label:"Martian Mono ✦",gf:"Martian+Mono:wght@400;500",stack:"'Martian Mono', ui-monospace, monospace"},{value:"fragment",label:"Fragment Mono ✦",gf:"Fragment+Mono",stack:"'Fragment Mono', ui-monospace, monospace"},{value:"redhatmono",label:"Red Hat Mono ✦",gf:"Red+Hat+Mono:wght@400;500",stack:"'Red Hat Mono', ui-monospace, monospace"},{value:"chivomono",label:"Chivo Mono ✦",gf:"Chivo+Mono:wght@400;500",stack:"'Chivo Mono', ui-monospace, monospace"},{value:"azeret",label:"Azeret Mono ✦",gf:"Azeret+Mono:wght@400;500",stack:"'Azeret Mono', ui-monospace, monospace"},{value:"spacemono",label:"Space Mono ✦",gf:"Space+Mono:wght@400;700",stack:"'Space Mono', ui-monospace, monospace"}],dy=[{value:"sans",label:"Same as sans",stack:""},{value:"newsreader",label:"Newsreader (serif)",gf:"Newsreader:opsz,wght@6..72,400..700",stack:"'Newsreader', Georgia, serif"},{value:"sourceserif",label:"Source Serif 4",gf:"Source+Serif+4:opsz,wght@8..60,400..700",stack:"'Source Serif 4', Georgia, serif"},{value:"fraunces",label:"Fraunces",gf:"Fraunces:opsz,wght@9..144,400..700",stack:"'Fraunces', Georgia, serif"},{value:"instrumentserif",label:"Instrument Serif",gf:"Instrument+Serif",stack:"'Instrument Serif', Georgia, serif"},{value:"spacegrotesk",label:"Space Grotesk",gf:"Space+Grotesk:wght@400;500;600",stack:"'Space Grotesk', system-ui, sans-serif"},{value:"clash",label:"Clash Display ✦",url:ns("clash-display@400,500,600"),stack:"'Clash Display', system-ui, sans-serif"},{value:"cabinetdisplay",label:"Cabinet Grotesk ✦",url:ns("cabinet-grotesk@500,700,800"),stack:"'Cabinet Grotesk', system-ui, sans-serif"},{value:"sentient",label:"Sentient (serif) ✦",url:ns("sentient@400,500,700"),stack:"'Sentient', Georgia, serif"},{value:"gambetta",label:"Gambetta (serif) ✦",url:ns("gambetta@400,500,700"),stack:"'Gambetta', Georgia, serif"},{value:"bricolagedisplay",label:"Bricolage Grotesque ✦",gf:"Bricolage+Grotesque:opsz,wght@12..96,400..700",stack:"'Bricolage Grotesque', system-ui, sans-serif"},{value:"youngserif",label:"Young Serif ✦",gf:"Young+Serif",stack:"'Young Serif', Georgia, serif"},{value:"unbounded",label:"Unbounded ✦",gf:"Unbounded:wght@400;500;600",stack:"'Unbounded', system-ui, sans-serif"}],R2=[{label:"Geist / Geist Mono",sans:"geist",mono:"geistmono",display:"sans"},{label:"Inter / JetBrains",sans:"inter",mono:"jetbrains",display:"sans"},{label:"IBM Plex",sans:"plex",mono:"plexmono",display:"sans"},{label:"Instrument / Spline",sans:"instrument",mono:"splinemono",display:"sans"},{label:"Schibsted / Fira",sans:"schibsted",mono:"firacode",display:"sans"},{label:"Editorial: Geist + Newsreader",sans:"geist",mono:"geistmono",display:"newsreader"},{label:"Satoshi / Martian ✦",sans:"satoshi",mono:"martianmono",display:"sans"},{label:"General Sans / Fragment ✦",sans:"generalsans",mono:"fragment",display:"sans"},{label:"Switzer + Clash headings ✦",sans:"switzer",mono:"redhatmono",display:"clash"},{label:"Cabinet + Gambetta ✦",sans:"cabinet",mono:"chivomono",display:"gambetta"},{label:"Bricolage all the way ✦",sans:"bricolage",mono:"spacemono",display:"bricolagedisplay"}],fy=new Set;function gd(n){if(!n)return;const e=n.url??(n.gf?`https://fonts.googleapis.com/css2?family=${n.gf}&display=swap`:void 0);if(!e||fy.has(e))return;fy.add(e);const t=document.createElement("link");t.rel="stylesheet",t.href=e,document.head.appendChild(t)}function vd(n,e){return n.find(t=>t.value===e)??n[0]}const L2=[{px:"8",cls:"text-[8px]",usage:"MetricCard delta arrow glyph",sample:"▲"},{px:"9",cls:"text-[9px]",usage:"DataTable sort direction glyph",sample:"▲▼"},{px:"10",cls:"text-[10px]",usage:"Chart axis labels (all 9 charts)",sample:"Jan Feb Mar 12.4k 18.2k"},{px:"11",cls:"text-2xs",usage:"Captions, chips, table body, helper text (58 uses)",sample:"Canonical React primitives · updated 2h ago"},{px:"12",cls:"text-xs",usage:"Controls, labels, leaderboard rows — the workhorse (70 uses)",sample:"Revenue by region, last 28 days"},{px:"13",cls:"text-sm",usage:"Section titles, panel headers (9 uses); also the body default",sample:"Customer Region"},{px:"14",cls:"text-base",usage:"Explore index page title (1 use)",sample:"Explore"},{px:"19",cls:"text-[19px]",usage:"MetricCard value",sample:"$288,291"},{px:"20",cls:"text-xl",usage:"MetricTimeSeries headline total",sample:"$1,282,392"},{px:"24",cls:"text-2xl",usage:"DashboardShell page title",sample:"Revenue overview"}],U2=[{name:"A — Current",note:"11 / 12 / 13 base. Dense, reads small on 27″ displays.",caption:11,label:12,body:13,section:13,value:19,headline:20,title:24},{name:"B — One up",note:"12 / 13 / 14 base. Same hierarchy, comfortably legible.",caption:12,label:13,body:14,section:14,value:22,headline:24,title:28},{name:"C — Quiet UI, loud numbers",note:"Keeps the dense chrome, doubles down on data: bigger values and titles.",caption:11,label:12,body:13,section:13,value:24,headline:28,title:30}],$2=[31,42,38,55,60,74],P2=Array.from({length:12},(n,e)=>({x:`2025-${String(e+1).padStart(2,"0")}-01`,y:96e3+e*14e3+e%3*9e3})),z2=`select region, sum(revenue) as revenue +ORDER BY revenue DESC`}})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"States"}),c.jsxs("div",{className:"grid gap-2 lg:grid-cols-3",children:[c.jsx(af,{message:"Loading metric results…"}),c.jsx(Xn,{message:"No matching rows."}),c.jsx(Bi,{message:"The query could not be completed."})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-2 text-xs font-medium text-muted",children:"Dashboard shell"}),c.jsx("div",{children:c.jsx(u2,{eyebrow:"Embedded shell example",title:"Revenue overview",status:c.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[c.jsx(dd,{status:"ok"})," Connected"]}),toolbar:c.jsxs(c.Fragment,{children:[c.jsx(Od,{dimension:"orders.region",value:"East"}),c.jsx(Td,{grain:v,options:["day","month","quarter"],onChange:x})]}),children:c.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[c.jsx(Nr,{metric:"orders.revenue",label:"Revenue",value:288291,format:{format:"currency"},sparkValues:[31,42,38,55,60]}),c.jsx(Xn,{title:"Optional panel",message:"Shell content is composed from the same primitives."})]})})})]})]})]})}function ns(n){return`https://api.fontshare.com/v2/css?f[]=${n}&display=swap`}const fy=[{value:"system",label:"System (SF Pro)",stack:"system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif"},{value:"geist",label:"Geist",gf:"Geist:wght@400;500;600",stack:"'Geist', system-ui, sans-serif"},{value:"inter",label:"Inter",gf:"Inter:wght@400;500;600",stack:"'Inter', system-ui, sans-serif"},{value:"instrument",label:"Instrument Sans",gf:"Instrument+Sans:wght@400;500;600",stack:"'Instrument Sans', system-ui, sans-serif"},{value:"plex",label:"IBM Plex Sans",gf:"IBM+Plex+Sans:wght@400;500;600",stack:"'IBM Plex Sans', system-ui, sans-serif"},{value:"schibsted",label:"Schibsted Grotesk",gf:"Schibsted+Grotesk:wght@400;500;600",stack:"'Schibsted Grotesk', system-ui, sans-serif"},{value:"figtree",label:"Figtree",gf:"Figtree:wght@400;500;600",stack:"'Figtree', system-ui, sans-serif"},{value:"manrope",label:"Manrope",gf:"Manrope:wght@400;500;600",stack:"'Manrope', system-ui, sans-serif"},{value:"publicsans",label:"Public Sans",gf:"Public+Sans:wght@400;500;600",stack:"'Public Sans', system-ui, sans-serif"},{value:"spacegrotesk",label:"Space Grotesk",gf:"Space+Grotesk:wght@400;500;600",stack:"'Space Grotesk', system-ui, sans-serif"},{value:"satoshi",label:"Satoshi ✦",url:ns("satoshi@400,500,700"),stack:"'Satoshi', system-ui, sans-serif"},{value:"generalsans",label:"General Sans ✦",url:ns("general-sans@400,500,600"),stack:"'General Sans', system-ui, sans-serif"},{value:"switzer",label:"Switzer ✦",url:ns("switzer@400,500,600"),stack:"'Switzer', system-ui, sans-serif"},{value:"cabinet",label:"Cabinet Grotesk ✦",url:ns("cabinet-grotesk@400,500,700"),stack:"'Cabinet Grotesk', system-ui, sans-serif"},{value:"bricolage",label:"Bricolage Grotesque ✦",gf:"Bricolage+Grotesque:wght@400;500;600",stack:"'Bricolage Grotesque', system-ui, sans-serif"},{value:"familjen",label:"Familjen Grotesk ✦",gf:"Familjen+Grotesk:wght@400;500;600",stack:"'Familjen Grotesk', system-ui, sans-serif"},{value:"hanken",label:"Hanken Grotesk ✦",gf:"Hanken+Grotesk:wght@400;500;600",stack:"'Hanken Grotesk', system-ui, sans-serif"},{value:"reddit",label:"Reddit Sans ✦",gf:"Reddit+Sans:wght@400;500;600",stack:"'Reddit Sans', system-ui, sans-serif"},{value:"chivo",label:"Chivo ✦",gf:"Chivo:wght@400;500;600",stack:"'Chivo', system-ui, sans-serif"},{value:"hostgrotesk",label:"Host Grotesk ✦",gf:"Host+Grotesk:wght@400;500;600",stack:"'Host Grotesk', system-ui, sans-serif"},{value:"sora",label:"Sora ✦",gf:"Sora:wght@400;500;600",stack:"'Sora', system-ui, sans-serif"}],hy=[{value:"system",label:"System (SF Mono)",stack:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"},{value:"geistmono",label:"Geist Mono",gf:"Geist+Mono:wght@400;500",stack:"'Geist Mono', ui-monospace, monospace"},{value:"jetbrains",label:"JetBrains Mono",gf:"JetBrains+Mono:wght@400;500",stack:"'JetBrains Mono', ui-monospace, monospace"},{value:"plexmono",label:"IBM Plex Mono",gf:"IBM+Plex+Mono:wght@400;500",stack:"'IBM Plex Mono', ui-monospace, monospace"},{value:"firacode",label:"Fira Code",gf:"Fira+Code:wght@400;500",stack:"'Fira Code', ui-monospace, monospace"},{value:"splinemono",label:"Spline Sans Mono",gf:"Spline+Sans+Mono:wght@400;500",stack:"'Spline Sans Mono', ui-monospace, monospace"},{value:"dmmono",label:"DM Mono",gf:"DM+Mono:wght@400;500",stack:"'DM Mono', ui-monospace, monospace"},{value:"martianmono",label:"Martian Mono ✦",gf:"Martian+Mono:wght@400;500",stack:"'Martian Mono', ui-monospace, monospace"},{value:"fragment",label:"Fragment Mono ✦",gf:"Fragment+Mono",stack:"'Fragment Mono', ui-monospace, monospace"},{value:"redhatmono",label:"Red Hat Mono ✦",gf:"Red+Hat+Mono:wght@400;500",stack:"'Red Hat Mono', ui-monospace, monospace"},{value:"chivomono",label:"Chivo Mono ✦",gf:"Chivo+Mono:wght@400;500",stack:"'Chivo Mono', ui-monospace, monospace"},{value:"azeret",label:"Azeret Mono ✦",gf:"Azeret+Mono:wght@400;500",stack:"'Azeret Mono', ui-monospace, monospace"},{value:"spacemono",label:"Space Mono ✦",gf:"Space+Mono:wght@400;700",stack:"'Space Mono', ui-monospace, monospace"}],py=[{value:"sans",label:"Same as sans",stack:""},{value:"newsreader",label:"Newsreader (serif)",gf:"Newsreader:opsz,wght@6..72,400..700",stack:"'Newsreader', Georgia, serif"},{value:"sourceserif",label:"Source Serif 4",gf:"Source+Serif+4:opsz,wght@8..60,400..700",stack:"'Source Serif 4', Georgia, serif"},{value:"fraunces",label:"Fraunces",gf:"Fraunces:opsz,wght@9..144,400..700",stack:"'Fraunces', Georgia, serif"},{value:"instrumentserif",label:"Instrument Serif",gf:"Instrument+Serif",stack:"'Instrument Serif', Georgia, serif"},{value:"spacegrotesk",label:"Space Grotesk",gf:"Space+Grotesk:wght@400;500;600",stack:"'Space Grotesk', system-ui, sans-serif"},{value:"clash",label:"Clash Display ✦",url:ns("clash-display@400,500,600"),stack:"'Clash Display', system-ui, sans-serif"},{value:"cabinetdisplay",label:"Cabinet Grotesk ✦",url:ns("cabinet-grotesk@500,700,800"),stack:"'Cabinet Grotesk', system-ui, sans-serif"},{value:"sentient",label:"Sentient (serif) ✦",url:ns("sentient@400,500,700"),stack:"'Sentient', Georgia, serif"},{value:"gambetta",label:"Gambetta (serif) ✦",url:ns("gambetta@400,500,700"),stack:"'Gambetta', Georgia, serif"},{value:"bricolagedisplay",label:"Bricolage Grotesque ✦",gf:"Bricolage+Grotesque:opsz,wght@12..96,400..700",stack:"'Bricolage Grotesque', system-ui, sans-serif"},{value:"youngserif",label:"Young Serif ✦",gf:"Young+Serif",stack:"'Young Serif', Georgia, serif"},{value:"unbounded",label:"Unbounded ✦",gf:"Unbounded:wght@400;500;600",stack:"'Unbounded', system-ui, sans-serif"}],$2=[{label:"Geist / Geist Mono",sans:"geist",mono:"geistmono",display:"sans"},{label:"Inter / JetBrains",sans:"inter",mono:"jetbrains",display:"sans"},{label:"IBM Plex",sans:"plex",mono:"plexmono",display:"sans"},{label:"Instrument / Spline",sans:"instrument",mono:"splinemono",display:"sans"},{label:"Schibsted / Fira",sans:"schibsted",mono:"firacode",display:"sans"},{label:"Editorial: Geist + Newsreader",sans:"geist",mono:"geistmono",display:"newsreader"},{label:"Satoshi / Martian ✦",sans:"satoshi",mono:"martianmono",display:"sans"},{label:"General Sans / Fragment ✦",sans:"generalsans",mono:"fragment",display:"sans"},{label:"Switzer + Clash headings ✦",sans:"switzer",mono:"redhatmono",display:"clash"},{label:"Cabinet + Gambetta ✦",sans:"cabinet",mono:"chivomono",display:"gambetta"},{label:"Bricolage all the way ✦",sans:"bricolage",mono:"spacemono",display:"bricolagedisplay"}],my=new Set;function gd(n){if(!n)return;const e=n.url??(n.gf?`https://fonts.googleapis.com/css2?family=${n.gf}&display=swap`:void 0);if(!e||my.has(e))return;my.add(e);const t=document.createElement("link");t.rel="stylesheet",t.href=e,document.head.appendChild(t)}function vd(n,e){return n.find(t=>t.value===e)??n[0]}const P2=[{px:"8",cls:"text-[8px]",usage:"MetricCard delta arrow glyph",sample:"▲"},{px:"9",cls:"text-[9px]",usage:"DataTable sort direction glyph",sample:"▲▼"},{px:"10",cls:"text-[10px]",usage:"Chart axis labels (all 9 charts)",sample:"Jan Feb Mar 12.4k 18.2k"},{px:"11",cls:"text-2xs",usage:"Captions, chips, table body, helper text (58 uses)",sample:"Canonical React primitives · updated 2h ago"},{px:"12",cls:"text-xs",usage:"Controls, labels, leaderboard rows — the workhorse (70 uses)",sample:"Revenue by region, last 28 days"},{px:"13",cls:"text-sm",usage:"Section titles, panel headers (9 uses); also the body default",sample:"Customer Region"},{px:"14",cls:"text-base",usage:"Explore index page title (1 use)",sample:"Explore"},{px:"19",cls:"text-[19px]",usage:"MetricCard value",sample:"$288,291"},{px:"20",cls:"text-xl",usage:"MetricTimeSeries headline total",sample:"$1,282,392"},{px:"24",cls:"text-2xl",usage:"DashboardShell page title",sample:"Revenue overview"}],z2=[{name:"A — Current",note:"11 / 12 / 13 base. Dense, reads small on 27″ displays.",caption:11,label:12,body:13,section:13,value:19,headline:20,title:24},{name:"B — One up",note:"12 / 13 / 14 base. Same hierarchy, comfortably legible.",caption:12,label:13,body:14,section:14,value:22,headline:24,title:28},{name:"C — Quiet UI, loud numbers",note:"Keeps the dense chrome, doubles down on data: bigger values and titles.",caption:11,label:12,body:13,section:13,value:24,headline:28,title:30}],V2=[31,42,38,55,60,74],W2=Array.from({length:12},(n,e)=>({x:`2025-${String(e+1).padStart(2,"0")}-01`,y:96e3+e*14e3+e%3*9e3})),H2=`select region, sum(revenue) as revenue from orders where created_at >= date '2025-01-01' group by all -order by revenue desc`;function hy({family:n,size:e}){return c.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-6 gap-y-1",style:{fontFamily:n},children:[c.jsx("span",{className:`${e} font-normal`,children:"Regular 400 — Revenue by payment method"}),c.jsx("span",{className:`${e} font-medium`,children:"Medium 500 — Revenue by payment method"}),c.jsx("span",{className:`${e} font-semibold`,children:"Semibold 600 — Revenue by payment method"})]})}function V2(){const[n,e]=D.useState("geist"),[t,i]=D.useState("geistmono"),[a,u]=D.useState("sans"),f=vd(uy,n),h=vd(cy,t),m=vd(dy,a),g=m.stack||f.stack;D.useEffect(()=>{gd(f),gd(h),gd(m)},[f,h,m]);const v={"--font-sans":f.stack,"--font-mono":h.stack,"--font-display":g,fontFamily:"var(--font-sans)"};return c.jsxs("main",{className:"min-h-screen bg-bg text-ink",children:[c.jsxs("header",{className:"sticky top-0 z-20 flex items-center justify-between gap-3 border-b border-line bg-surface px-4 py-3",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-sm font-semibold",children:"Typography workbench"}),c.jsxs("p",{className:"text-2xs text-faint",children:["Pick faces, judge them on real components · ",c.jsx("a",{className:"text-accent hover:underline",href:"/components",children:"component gallery →"})]})]}),c.jsx($o,{})]}),c.jsxs("div",{className:"space-y-10 p-4",children:[c.jsx("section",{children:c.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[c.jsx(wl,{label:"Sans",value:n,options:uy.map(({value:x,label:b})=>({value:x,label:b})),onChange:e}),c.jsx(wl,{label:"Mono",value:t,options:cy.map(({value:x,label:b})=>({value:x,label:b})),onChange:i}),c.jsx(wl,{label:"Headings",value:a,options:dy.map(({value:x,label:b})=>({value:x,label:b})),onChange:u}),c.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:R2.map(x=>{const b=x.sans===n&&x.mono===t&&x.display===a;return c.jsx("button",{type:"button","data-selected":b||void 0,onClick:()=>{e(x.sans),i(x.mono),u(x.display)},className:`inline-flex h-7 items-center rounded-full border px-3 text-xs transition-colors ${b?"border-accent text-accent":"border-line bg-surface text-muted hover:border-line-strong"}`,children:x.label},x.label)})})]})}),c.jsxs("div",{style:v,className:"space-y-10",children:[c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"In context"}),c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-2xs text-faint",children:"Acme Analytics · production"}),c.jsx("h1",{className:"mt-1 text-2xl font-semibold text-ink",children:"Revenue overview"}),c.jsx("div",{className:"text-sm text-muted",children:"Updated 2 minutes ago · 448,214 rows scanned"})]}),c.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-3",children:[c.jsx(Nr,{metric:"t.revenue",label:"Revenue",value:288291,format:{format:"currency"},delta:{label:"+12.4%",tone:"positive"},comparison:"vs previous month",sparkValues:$2,selected:!0,onSelect:()=>{}}),c.jsx(Nr,{metric:"t.orders",label:"Order Count",value:447,delta:{label:"-2.1%",tone:"negative"},comparison:"vs previous month",sparkValues:[21,34,28,41,44,38],onSelect:()=>{}}),c.jsx(Nr,{metric:"t.margin",label:"Gross Margin",value:.324,format:{format:"percent"},delta:{label:"+1.1pt",tone:"positive"},comparison:"vs previous month",sparkValues:[24,26,29,27,31,32],onSelect:()=>{}})]}),c.jsx(Go,{points:P2,formatValue:x=>`$${Math.round(x).toLocaleString("en-US")}`,formatAxis:x=>`$${Math.round(x/1e3)}k`,formatLabel:x=>x.slice(0,7),ariaLabel:"Twelve month revenue trend"}),c.jsxs("div",{className:"max-w-xl",children:[c.jsx("h3",{className:"text-sm font-semibold text-ink",children:"How the comparison works"}),c.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"The overlay shifts the previous period onto the current axis so both lines share a scale. Deltas are computed on the visible range only — zooming recomputes them. Hover any point for the exact pair of values; the quiet gray line is always the older period."})]}),c.jsx("pre",{className:"overflow-x-auto font-mono text-xs leading-5 text-muted",children:z2})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Numerals — mono, tabular"}),c.jsxs("div",{className:"flex flex-wrap gap-12",children:[c.jsx("div",{className:"font-mono tnum text-sm text-ink",children:["$1,204,918.24","$984,003.10","$88,214.00","$1,111,111.11"].map(x=>c.jsx("div",{className:"text-right",children:x},x))}),c.jsx("div",{className:"font-mono tnum text-sm text-ink",children:["2025-06-30 23:59:59","2025-07-01 00:00:00","2025-12-31 08:15:42"].map(x=>c.jsx("div",{children:x},x))}),c.jsxs("div",{className:"font-mono text-sm text-ink",children:["0O · 1lI · 5S · 8B · ","->"," ","=>"," ","!="," ",">="]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Weights in use — 400 / 500 / 600 (no bold anywhere)"}),c.jsxs("div",{className:"space-y-2 text-ink",children:[c.jsx(hy,{family:"var(--font-sans)",size:"text-sm"}),c.jsx(hy,{family:"var(--font-sans)",size:"text-xs"}),c.jsx("div",{className:"text-xl font-semibold",style:{fontFamily:"var(--font-display)"},children:"Display 600 — Quarterly revenue, all regions"})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Current ramp — every size in the app and where it appears"}),c.jsx("div",{className:"space-y-1.5",children:L2.map(x=>c.jsxs("div",{className:"grid grid-cols-[3rem_7rem_1fr_1.2fr] items-baseline gap-3",children:[c.jsxs("span",{className:"font-mono tnum text-2xs text-faint",children:[x.px,"px"]}),c.jsx("span",{className:"font-mono text-2xs text-faint",children:x.cls}),c.jsx("span",{className:"truncate text-ink",style:{fontSize:`${x.px}px`,lineHeight:1.3},children:x.sample}),c.jsx("span",{className:"text-2xs text-faint",children:x.usage})]},x.px))})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Size ramp candidates"}),c.jsx("div",{className:"grid grid-cols-1 gap-8 lg:grid-cols-3",children:U2.map(x=>c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"text-sm font-semibold text-ink",children:x.name}),c.jsx("p",{className:"mt-0.5 text-2xs text-faint",children:x.note}),c.jsxs("div",{className:"mt-3 space-y-2",children:[c.jsxs("div",{className:"text-faint",style:{fontSize:x.caption,lineHeight:1.3},children:["Caption ",x.caption,"px · vs previous month"]}),c.jsxs("div",{className:"text-muted",style:{fontSize:x.label,lineHeight:1.35},children:["Label ",x.label,"px · Revenue by region"]}),c.jsxs("div",{className:"text-ink",style:{fontSize:x.body,lineHeight:1.45},children:["Body ",x.body,"px · The overlay shifts the previous period onto the current axis so both lines share a scale."]}),c.jsxs("div",{className:"font-semibold text-ink",style:{fontSize:x.section,lineHeight:1.35},children:["Section title ",x.section,"px"]}),c.jsx("div",{className:"font-mono tnum font-semibold text-ink",style:{fontSize:x.value,lineHeight:1.15},children:"$288,291"}),c.jsx("div",{className:"font-mono tnum font-semibold text-ink",style:{fontSize:x.headline,lineHeight:1.15},children:"$1,282,392"}),c.jsx("div",{className:"font-semibold text-ink",style:{fontFamily:"var(--font-display)",fontSize:x.title,lineHeight:1.2,letterSpacing:"-0.025em"},children:"Revenue overview"})]})]},x.name))})]})]})]})]})}n_();const n0=document.getElementById("root");if(!n0)throw new Error("Missing #root element");ub.createRoot(n0).render(c.jsx(D.StrictMode,{children:window.location.pathname==="/components"?c.jsx(E2,{}):window.location.pathname==="/typography"?c.jsx(V2,{}):c.jsx(n2,{})})); +order by revenue desc`;function yy({family:n,size:e}){return c.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-6 gap-y-1",style:{fontFamily:n},children:[c.jsx("span",{className:`${e} font-normal`,children:"Regular 400 — Revenue by payment method"}),c.jsx("span",{className:`${e} font-medium`,children:"Medium 500 — Revenue by payment method"}),c.jsx("span",{className:`${e} font-semibold`,children:"Semibold 600 — Revenue by payment method"})]})}function G2(){const[n,e]=M.useState("geist"),[t,i]=M.useState("geistmono"),[a,u]=M.useState("sans"),f=vd(fy,n),h=vd(hy,t),m=vd(py,a),g=m.stack||f.stack;M.useEffect(()=>{gd(f),gd(h),gd(m)},[f,h,m]);const v={"--font-sans":f.stack,"--font-mono":h.stack,"--font-display":g,fontFamily:"var(--font-sans)"};return c.jsxs("main",{className:"min-h-screen bg-bg text-ink",children:[c.jsxs("header",{className:"sticky top-0 z-20 flex items-center justify-between gap-3 border-b border-line bg-surface px-4 py-3",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-sm font-semibold",children:"Typography workbench"}),c.jsxs("p",{className:"text-2xs text-faint",children:["Pick faces, judge them on real components · ",c.jsx("a",{className:"text-accent hover:underline",href:"/components",children:"component gallery →"})]})]}),c.jsx($o,{})]}),c.jsxs("div",{className:"space-y-10 p-4",children:[c.jsx("section",{children:c.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[c.jsx(wl,{label:"Sans",value:n,options:fy.map(({value:x,label:b})=>({value:x,label:b})),onChange:e}),c.jsx(wl,{label:"Mono",value:t,options:hy.map(({value:x,label:b})=>({value:x,label:b})),onChange:i}),c.jsx(wl,{label:"Headings",value:a,options:py.map(({value:x,label:b})=>({value:x,label:b})),onChange:u}),c.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:$2.map(x=>{const b=x.sans===n&&x.mono===t&&x.display===a;return c.jsx("button",{type:"button","data-selected":b||void 0,onClick:()=>{e(x.sans),i(x.mono),u(x.display)},className:`inline-flex h-7 items-center rounded-full border px-3 text-xs transition-colors ${b?"border-accent text-accent":"border-line bg-surface text-muted hover:border-line-strong"}`,children:x.label},x.label)})})]})}),c.jsxs("div",{style:v,className:"space-y-10",children:[c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"In context"}),c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{children:[c.jsx("p",{className:"text-2xs text-faint",children:"Acme Analytics · production"}),c.jsx("h1",{className:"mt-1 text-2xl font-semibold text-ink",children:"Revenue overview"}),c.jsx("div",{className:"text-sm text-muted",children:"Updated 2 minutes ago · 448,214 rows scanned"})]}),c.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-3",children:[c.jsx(Nr,{metric:"t.revenue",label:"Revenue",value:288291,format:{format:"currency"},delta:{label:"+12.4%",tone:"positive"},comparison:"vs previous month",sparkValues:V2,selected:!0,onSelect:()=>{}}),c.jsx(Nr,{metric:"t.orders",label:"Order Count",value:447,delta:{label:"-2.1%",tone:"negative"},comparison:"vs previous month",sparkValues:[21,34,28,41,44,38],onSelect:()=>{}}),c.jsx(Nr,{metric:"t.margin",label:"Gross Margin",value:.324,format:{format:"percent"},delta:{label:"+1.1pt",tone:"positive"},comparison:"vs previous month",sparkValues:[24,26,29,27,31,32],onSelect:()=>{}})]}),c.jsx(Go,{points:W2,formatValue:x=>`$${Math.round(x).toLocaleString("en-US")}`,formatAxis:x=>`$${Math.round(x/1e3)}k`,formatLabel:x=>x.slice(0,7),ariaLabel:"Twelve month revenue trend"}),c.jsxs("div",{className:"max-w-xl",children:[c.jsx("h3",{className:"text-sm font-semibold text-ink",children:"How the comparison works"}),c.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"The overlay shifts the previous period onto the current axis so both lines share a scale. Deltas are computed on the visible range only — zooming recomputes them. Hover any point for the exact pair of values; the quiet gray line is always the older period."})]}),c.jsx("pre",{className:"overflow-x-auto font-mono text-xs leading-5 text-muted",children:H2})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Numerals — mono, tabular"}),c.jsxs("div",{className:"flex flex-wrap gap-12",children:[c.jsx("div",{className:"font-mono tnum text-sm text-ink",children:["$1,204,918.24","$984,003.10","$88,214.00","$1,111,111.11"].map(x=>c.jsx("div",{className:"text-right",children:x},x))}),c.jsx("div",{className:"font-mono tnum text-sm text-ink",children:["2025-06-30 23:59:59","2025-07-01 00:00:00","2025-12-31 08:15:42"].map(x=>c.jsx("div",{children:x},x))}),c.jsxs("div",{className:"font-mono text-sm text-ink",children:["0O · 1lI · 5S · 8B · ","->"," ","=>"," ","!="," ",">="]})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Weights in use — 400 / 500 / 600 (no bold anywhere)"}),c.jsxs("div",{className:"space-y-2 text-ink",children:[c.jsx(yy,{family:"var(--font-sans)",size:"text-sm"}),c.jsx(yy,{family:"var(--font-sans)",size:"text-xs"}),c.jsx("div",{className:"text-xl font-semibold",style:{fontFamily:"var(--font-display)"},children:"Display 600 — Quarterly revenue, all regions"})]})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Current ramp — every size in the app and where it appears"}),c.jsx("div",{className:"space-y-1.5",children:P2.map(x=>c.jsxs("div",{className:"grid grid-cols-[3rem_7rem_1fr_1.2fr] items-baseline gap-3",children:[c.jsxs("span",{className:"font-mono tnum text-2xs text-faint",children:[x.px,"px"]}),c.jsx("span",{className:"font-mono text-2xs text-faint",children:x.cls}),c.jsx("span",{className:"truncate text-ink",style:{fontSize:`${x.px}px`,lineHeight:1.3},children:x.sample}),c.jsx("span",{className:"text-2xs text-faint",children:x.usage})]},x.px))})]}),c.jsxs("section",{children:[c.jsx("h2",{className:"mb-3 text-xs font-medium text-muted",children:"Size ramp candidates"}),c.jsx("div",{className:"grid grid-cols-1 gap-8 lg:grid-cols-3",children:z2.map(x=>c.jsxs("article",{className:"min-w-0",children:[c.jsx("h3",{className:"text-sm font-semibold text-ink",children:x.name}),c.jsx("p",{className:"mt-0.5 text-2xs text-faint",children:x.note}),c.jsxs("div",{className:"mt-3 space-y-2",children:[c.jsxs("div",{className:"text-faint",style:{fontSize:x.caption,lineHeight:1.3},children:["Caption ",x.caption,"px · vs previous month"]}),c.jsxs("div",{className:"text-muted",style:{fontSize:x.label,lineHeight:1.35},children:["Label ",x.label,"px · Revenue by region"]}),c.jsxs("div",{className:"text-ink",style:{fontSize:x.body,lineHeight:1.45},children:["Body ",x.body,"px · The overlay shifts the previous period onto the current axis so both lines share a scale."]}),c.jsxs("div",{className:"font-semibold text-ink",style:{fontSize:x.section,lineHeight:1.35},children:["Section title ",x.section,"px"]}),c.jsx("div",{className:"font-mono tnum font-semibold text-ink",style:{fontSize:x.value,lineHeight:1.15},children:"$288,291"}),c.jsx("div",{className:"font-mono tnum font-semibold text-ink",style:{fontSize:x.headline,lineHeight:1.15},children:"$1,282,392"}),c.jsx("div",{className:"font-semibold text-ink",style:{fontFamily:"var(--font-display)",fontSize:x.title,lineHeight:1.2,letterSpacing:"-0.025em"},children:"Revenue overview"})]})]},x.name))})]})]})]})]})}i_();const i0=document.getElementById("root");if(!i0)throw new Error("Missing #root element");fb.createRoot(i0).render(c.jsx(M.StrictMode,{children:window.location.pathname==="/components"?c.jsx(U2,{}):window.location.pathname==="/typography"?c.jsx(G2,{}):c.jsx(i2,{})})); diff --git a/sidemantic/ui/static/index.html b/sidemantic/ui/static/index.html index bb523053..228aea02 100644 --- a/sidemantic/ui/static/index.html +++ b/sidemantic/ui/static/index.html @@ -4,7 +4,7 @@ Sidemantic - + diff --git a/webapp/README.md b/webapp/README.md index fc70015c..286290a8 100644 --- a/webapp/README.md +++ b/webapp/README.md @@ -88,3 +88,17 @@ The built bundle is served by either backend from a single process: Both copies are committed (synced by `scripts/build_webapp.py`), so neither backend build needs a JS toolchain. Both backends serve `/describe`, so the UI gets the rich (typed) catalog on either — it only falls back to the names-only `/graph` catalog against a backend that doesn't expose `/describe`. + +### Host-owned URL state + +`ExplorerProvider` reads `window.location.search` and rewrites the URL with `history.replaceState` +by default. A host app that renders on the server, or whose router owns history, can take both over: + +- `initialSearch` — the query string to hydrate from. Supplying it means the initial render never + touches `window`, so the explorer renders on a server without a client-only gate. Changing it + after mount re-hydrates the explorer, so router navigation (deep links, Back/Forward) flows in; + the provider ignores changes that merely echo its own `onSearchChange` back. +- `onSearchChange` — receives the mirrored query string (`"?view=explore&..."`) on every state + change instead of `history.replaceState`, for the host router to apply. + +Omit both and the standalone browser behavior is unchanged. diff --git a/webapp/src/state/ExplorerContext.test.tsx b/webapp/src/state/ExplorerContext.test.tsx new file mode 100644 index 00000000..1363359f --- /dev/null +++ b/webapp/src/state/ExplorerContext.test.tsx @@ -0,0 +1,79 @@ +import { describe, expect, test } from "bun:test"; +import { renderToStaticMarkup } from "react-dom/server"; +import type { SidemanticBackend } from "../data/backend"; +import type { Catalog } from "../data/types"; +import { ExplorerProvider, searchForState, stateForSearch, useExplorer } from "./ExplorerContext"; +import { initialStateFromCatalog } from "./explorerState"; + +// This suite runs without a DOM, so it is exactly the environment a host's server render sees: +// touching `window` during render would throw here. +const catalog: Catalog = { + models: [ + { + name: "orders", + label: "Orders", + metrics: [{ ref: "orders.revenue", name: "revenue", model: "orders", label: "Revenue" }], + dimensions: [ + { ref: "orders.created_at", name: "created_at", model: "orders", label: "Created", type: "time" }, + { ref: "orders.region", name: "region", model: "orders", label: "Region", type: "categorical" }, + ], + timeDimension: { ref: "orders.created_at", name: "created_at", model: "orders", label: "Created", type: "time" }, + defaultGrain: "month", + }, + ], + graphMetrics: [], +}; + +const backend = { + health: async () => true, + getCatalog: async () => catalog, + getDashboard: async () => null, + compile: async () => "", + runQuery: async () => ({ columns: [], rows: [], rowCount: 0, sql: "" }), +} satisfies SidemanticBackend; + +function Probe() { + const { state } = useExplorer(); + return {`${state.view}|${state.model}|${state.selectedMetric}|${state.grain}`}; +} + +function render(initialSearch?: string) { + return renderToStaticMarkup( + + + , + ); +} + +describe("ExplorerProvider hydration", () => { + test("renders without a window when no search is supplied, landing on the catalog default", () => { + expect(render()).toContain("home|orders|orders.revenue|month"); + }); + + test("hydrates from a host-supplied search instead of window.location", () => { + expect(render("?view=pivot&grain=week")).toContain("pivot|orders|orders.revenue|week"); + }); + + test("accepts a search without the leading question mark", () => { + expect(render("view=explore")).toContain("explore|orders|orders.revenue|month"); + }); +}); + +test("searchForState mirrors state as a location.search-shaped string", () => { + expect(searchForState(initialStateFromCatalog(catalog))).toBe("?view=home&model=orders&metric=orders.revenue&grain=month"); +}); + +describe("stateForSearch", () => { + const initial = initialStateFromCatalog(catalog); + + test("decodes a search into the state the provider would mount with", () => { + const state = stateForSearch("?view=pivot&grain=week", catalog, null, initial); + expect(state.view).toBe("pivot"); + expect(state.grain).toBe("week"); + }); + + test("round-trips through searchForState, so a navigation echo mirrors its own state", () => { + const search = "?view=explore&model=orders&metric=orders.revenue&grain=day"; + expect(searchForState(stateForSearch(search, catalog, null, initial))).toBe(search); + }); +}); diff --git a/webapp/src/state/ExplorerContext.tsx b/webapp/src/state/ExplorerContext.tsx index a1b182ed..43e0e696 100644 --- a/webapp/src/state/ExplorerContext.tsx +++ b/webapp/src/state/ExplorerContext.tsx @@ -1,4 +1,4 @@ -import { createContext, useContext, useEffect, useMemo, useReducer, type ReactNode } from "react"; +import { createContext, useContext, useEffect, useMemo, useReducer, useRef, type ReactNode } from "react"; import type { SidemanticBackend } from "../data/backend"; import type { Catalog, DashboardSpec } from "../data/types"; import { dashboardTabConfig } from "../lib/dashboard"; @@ -22,15 +22,49 @@ type ExplorerContextValue = { const ExplorerContext = createContext(null); +/** The query string (`"?view=explore"`, or `""` when state is fully default) that mirrors a given + * explorer state — the same shape as `window.location.search`, so it round-trips through + * `initialSearch`. */ +export function searchForState(state: ExplorerState): string { + const query = encodeState(state); + return query ? `?${query}` : ""; +} + +/** Decode `search` (with or without the leading "?") into a full explorer state, applying any + * dashboard tab config it selects. Shared by the mount-time initializer and post-navigation + * re-hydration so both land on identical state. */ +export function stateForSearch( + search: string, + catalog: Catalog, + dashboard: DashboardSpec | null | undefined, + initial: ExplorerState, +): ExplorerState { + const decoded = decodeState(search, initial); + const configured = dashboardTabConfig(catalog, dashboard, decoded.dashboardTab); + if (!configured) return decoded; + return applyDashboardConfig(decoded, configured, search); +} + +const withoutQuestionMark = (search: string) => (search.startsWith("?") ? search.slice(1) : search); + export function ExplorerProvider({ catalog, backend, dashboard, + initialSearch, + onSearchChange, children, }: { catalog: Catalog; backend: SidemanticBackend; dashboard?: DashboardSpec | null; + /** Query string to hydrate the initial state from (with or without the leading "?"). Defaults to + * the browser's `window.location.search`; a host that server-renders can pass the request's + * query string so the first render never touches `window`. */ + initialSearch?: string; + /** Called with the mirrored query string ("?..." or "") on every state change, instead of + * rewriting the browser URL. Lets a host router own history. */ + onSearchChange?: (search: string) => void; children: ReactNode; }) { const initial = useMemo(() => initialStateFromCatalog(catalog, dashboard), [catalog, dashboard]); @@ -38,18 +72,39 @@ export function ExplorerProvider({ explorerReducer, undefined as never, () => { - const decoded = decodeState(window.location.search, initial); - const configured = dashboardTabConfig(catalog, dashboard, decoded.dashboardTab); - if (!configured) return decoded; - return applyDashboardConfig(decoded, configured, window.location.search); + // Without a host-supplied search, read the browser URL — and fall back to an empty query when + // there is no window at all (a bare server render), so hydration lands on the default state. + const search = initialSearch ?? (typeof window === "undefined" ? "" : window.location.search); + return stateForSearch(search, catalog, dashboard, initial); }, ); + // A host router that keeps this provider mounted can change `initialSearch` after mount (deep + // links, Back/Forward). Re-hydrate from it — unless it is our own `onSearchChange` echo arriving + // back through the host's URL, which already mirrors the current state. + const appliedSearchRef = useRef(initialSearch); + useEffect(() => { + if (initialSearch === undefined || initialSearch === appliedSearchRef.current) return; + appliedSearchRef.current = initialSearch; + if (withoutQuestionMark(initialSearch) === withoutQuestionMark(searchForState(state))) return; + dispatch({ type: "hydrate", state: stateForSearch(initialSearch, catalog, dashboard, initial) }); + }, [initialSearch, state, catalog, dashboard, initial]); + + // Held in a ref so an inline host callback doesn't re-run the sync on every render. + const onSearchChangeRef = useRef(onSearchChange); + onSearchChangeRef.current = onSearchChange; + // Sync selections + filters to the URL for deep-linkable, shareable views. useEffect(() => { - const query = encodeState(state); - const next = `${window.location.pathname}${query ? `?${query}` : ""}`; - window.history.replaceState(null, "", next); + const search = searchForState(state); + const notify = onSearchChangeRef.current; + // A host that owns the URL gets the query string and writes it however its router requires. + if (notify) { + notify(search); + return; + } + if (typeof window === "undefined") return; + window.history.replaceState(null, "", `${window.location.pathname}${search}`); }, [state]); const value = useMemo(