@graphysdk/viz-engine 0.0.1-plugins.6 → 0.0.1-plugins.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +15 -15
- package/dist/index.d.ts +50 -0
- package/dist/index.mjs +3856 -3387
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("date-fns"),re=require("arquero"),ae=require("lodash-es"),Pe=require("d3-time"),es=require("date-fns/differenceInDays"),oe=require("d3-scale"),oo=require("lodash-es/merge"),ue=require("d3-regression"),ts=require("humanize-duration"),ns=require("d3-delaunay");typeof window<"u"&&(window.__GRAPHY_SDK__??={},window.__GRAPHY_SDK__.vizEngine="0.0.1-plugins.6");const ao=e=>e.length>0;function h(e){return e!=null}function rr(e){if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function qe(e,t){return so(e,t)}function Rt(e,t){for(const n of Object.keys(t)){const r=t[n];if(r!==void 0&&r!==e[n])return{...e,...t}}return e}function so(e,t){let n=!1;const r={...e};for(const[o,a]of Object.entries(t)){const s=e[o];if(rr(a)&&rr(s)){const i=so(s,a);i!==s&&(r[o]=i,n=!0)}else a!==void 0&&a!==s&&(r[o]=a,n=!0)}return n?r:e}const pe=process.env.NODE_ENV!=="production";function Tt(e){return{pipe:t=>{const n=t(e);return Tt({...e,...n})},result:()=>e}}let Mt=!0;const rs=e=>{Mt=e},os=()=>Mt,as=()=>{let e=null;const t={hits:0,misses:0};return Object.assign((r,o)=>{if(!Mt)return pe&&(t.misses+=1),o();if(e&&co(e.args,r))return pe&&(t.hits+=1),e.out;pe&&(t.misses+=1);const a=o();return e={args:r,out:a},a},{stats:t,reset:()=>{e=null}})},io=()=>{const e=new WeakMap,t={hits:0,misses:0};return Object.assign((r,o,a)=>{if(!Mt)return pe&&(t.misses+=1),a();const s=e.get(r);if(s){for(const c of s)if(co(c.args,o))return pe&&(t.hits+=1),c.out}pe&&(t.misses+=1);const i=a();return s?s.push({args:o,out:i}):e.set(r,[{args:o,out:i}]),i},{stats:t})},ss=(...e)=>e.reduce((t,n)=>({hits:t.hits+n.hits,misses:t.misses+n.misses}),{hits:0,misses:0}),co=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0};class se{constructor(){this.memo=io(),this.singletonKey={}}get stats(){return this.memo.stats}compile(t){return this.memo(this.key(t),this.dependencies(t),()=>this.run(t))}key(t){return this.singletonKey}}function is(e){return{type:"mapping",mapping:e}}function un(e,t){return e[t]}function v(e){return h(e)?typeof e=="string"?e:"variable"in e?e.variable:null:null}function ee(e){if(!(!h(e)||typeof e=="string")&&"value"in e)return e.value}const lo="\0graphy\0_",A=e=>`${lo}${e}`,tn={x:A("constantX")},He={count:A("count"),mean:A("mean")},D={group:A("group")},uo={key:A("key")},g={x:A("x"),y:A("y"),xMin:A("xMin"),xMax:A("xMax"),yMin:A("yMin"),yMax:A("yMax"),yRaw:A("yRaw")},ie={color:A("color"),size:A("size"),alpha:A("alpha"),strokeWidth:A("strokeWidth"),lineType:A("lineType")},at={y:A("ruleY"),x:A("ruleX")};({...D,...g,...ie});const cs=new Set(Object.values(He)),ls=e=>e.startsWith(lo),us=e=>cs.has(e),ke=e=>e[D.group],ds=e=>{const{coordinate:t,coordSystem:n}=e;return"observation"in t?ms(e):n.type!=="cartesian"?null:"unit"in t?{x:t.unit.x,y:t.unit.y,mode:"unit"}:ps(t.data,e)},ms=({coordinate:e,layers:t,coordSystem:n,geomCompiler:r})=>{if(!("observation"in e))return null;const o=e.observation;for(const a of t){if(o.layerId!==void 0&&a.id!==o.layerId)continue;const s=v(a.mapping.x);if(s!==null)for(const i of a.data){if(i[s]!==o.anchorValue||ke(i)!==o.groupValue)continue;const c=r.resolveAnchorPosition(a.geom,i,n);if(c!==null)return{x:c.x,y:1-c.y,mode:"observation",observation:i}}}return null},ps=(e,{coordSystem:t,scales:n})=>{const r=or(n,"x"),o=or(n,"y");if(r===null||o===null)return null;const a=r.map(e.x),s=o.map(e.y);if(!Number.isFinite(a)||!Number.isFinite(s))return null;const i=t.type==="cartesian"&&t.mainAxis==="y";return{x:i?s:a,y:1-(i?a:s),mode:"data"}},or=(e,t)=>{const n=e[t];return n!==void 0&&n.kind==="position"?n:null},O=e=>e instanceof Date&&L.isValid(e),fs=e=>O(e)||e===null,Qe=e=>typeof e=="string",E=e=>typeof e=="number"&&!Number.isNaN(e)&&Number.isFinite(e);function dn(e){return e[ie.color]}function hs(e){return e[ie.alpha]}function mo(e){return e[ie.size]}function ys(e){return e[ie.strokeWidth]}function po(e){return e[ie.lineType]??"solid"}const nn=(e,t,n,r)=>{for(const o of t){if(e.layerId!==void 0&&o.id!==e.layerId)continue;const a=v(o.mapping.x);if(a===null)continue;const s=v(o.mapping.y);for(const i of o.data){if(i[a]!==e.anchorValue||ke(i)!==e.groupValue)continue;const c=r.resolveAnchorPosition(o.geom,i,n);if(c===null)continue;const l=s!==null?i[s]??null:null;if(E(l))return{...c,measurementValue:l,color:dn(i)}}}return null};class gs extends se{constructor(t){super(),this.geomCompiler=t}dependencies(t){return[t.annotations,t.layers,t.coordSystem,t.scales.x,t.scales.y]}run(t){const{geomCompiler:n}=this;return{differenceArrows:vs(t,n),shapes:t.annotations.shapes,freeformArrows:t.annotations.freeformArrows,textAnnotations:t.annotations.textAnnotations,stickers:Nt(t.annotations.stickers,t.layers,t.coordSystem,n),pinnedNumbers:Nt(t.annotations.pinnedNumbers,t.layers,t.coordSystem,n),comments:Nt(t.annotations.comments,t.layers,t.coordSystem,n),custom:bs(t,n)}}}const bs=({annotations:e,layers:t,coordSystem:n,scales:r},o)=>{const a=[];for(const s of e.custom){const i=[];let c=!1;for(const l of s.coordinates){const u=ds({coordinate:l,layers:t,coordSystem:n,scales:r,geomCompiler:o});if(u===null){c=!0;break}i.push(u)}c||a.push({id:s.id,type:s.type,params:s.params,zOrder:s.zOrder,targets:i})}return a},Nt=(e,t,n,r)=>{const o=[];for(const a of e){const s=nn(a.anchor,t,n,r);s!==null&&o.push({...a,anchor:s})}return o},vs=({annotations:e,layers:t,coordSystem:n},r)=>{if(n.type!=="cartesian")return[];const o=[];for(const a of e.differenceArrows){if(Ss(a.start,a.end))continue;const s=nn(a.start,t,n,r),i=nn(a.end,t,n,r);s===null||i===null||o.push({id:a.id,start:s,end:i,color:xs(a,s,i),size:a.size,label:a.label,labelCrossPosition:a.labelCrossPosition})}return o},Ss=(e,t)=>e.layerId===t.layerId&&e.anchorValue===t.anchorValue&&e.groupValue===t.groupValue,xs=(e,t,n)=>e.color!==null?e.color:e.start.groupValue!==e.end.groupValue||t.color===void 0||t.color!==n.color?null:t.color;function ws(e,t){const n=Ms(t);return{...e,background:As(e.background,n),border:Ts(e.border,n)}}function As(e,t){if(e.type==="tinted"){const n=e.color??t;if(!n)throw new Error("could not resolve color for tinted background");return{type:"tinted",color:n}}return e}function Ts(e,t){if(e.type==="tinted"||e.type==="gradient"){const n=e.color??t;if(!n)throw new Error(`could not resolve color for ${e.type} background`);return{...e,color:n}}return e}function Ms(e){const t=e.color,n=t?.domain[0];if(!n)return;const r=t.map(n);if(typeof r=="string")return r}class Ls extends se{dependencies(t){return[t.scales,t.config]}run(t){const{scales:n,config:r}=t;return{...r,appearance:ws(r.appearance,n)}}}class Vs extends se{dependencies(t){return[t.data,t.mapping]}run(t){let n=t.data,r=t.mapping;r.x===""&&(n=n.addConstantVariable(tn.x,"categorical",""),r={...r,x:tn.x});for(const o of Object.keys(r)){const a=ee(r[o]);if(a===void 0)continue;const s=A(`const_${o}`);n=n.addConstantVariable(s,ks(a),a),r={...r,[o]:s}}return{data:n,mapping:r}}}const ks=e=>typeof e=="number"?"numeric":e instanceof Date?"temporal":"categorical";class Ee{constructor(){this.perLayerMemo=io(),this.listMemo=as()}get stats(){return ss(this.perLayerMemo.stats,this.listMemo.stats)}compile(t){const n=this.dependencies(t),r=t.layers.map(o=>this.perLayerMemo(o,n,()=>this.compileLayer(o,t)));return this.listMemo(r,()=>r)}}class Es extends se{constructor(t){super(),this.registry=t}dependencies(t){return[t.coordSpec,t.scales,t.layers]}run(t){return this.registry.get(t.coordSpec.coordType).setup(t)}}class Is extends Ee{constructor(t){super(),this.registry=t}dependencies(t){return[t.coordSpec]}compileLayer(t,n){const r=this.registry.get(n.coordSpec.coordType),[o]=r.transform({coordSpec:n.coordSpec,layers:[t]});if(!o)throw new Error(`CoordCompiler: strategy '${n.coordSpec.coordType}' did not return a transformed layer`);return o}}class Cs{constructor(t){this.setupStage=new Es(t),this.transformStage=new Is(t)}get setupStats(){return this.setupStage.stats}get transformStats(){return this.transformStage.stats}setup(t){return this.setupStage.compile(t)}transform(t){return this.transformStage.compile(t)}}class Ie{constructor(t){this.label=t,this.items=new Map}register(t,n){return this.items.set(t,n),this}get(t){if(!this.items.has(t)){const n=[...this.items.keys()].map(r=>`'${r}'`).join(", ");throw new Error(`Unknown ${this.label}: '${t}' (available: ${n})`)}return this.items.get(t)}getAll(){return[...this.items.values()]}has(t){return this.items.has(t)}}class _s{constructor(){this.coordType="cartesian"}setup(t){if(t.coordSpec.coordType!=="cartesian")throw new Error(`Invalid coordinate type: ${t.coordSpec.coordType}`);return{coordSystem:{type:"cartesian",mainAxis:"x",axisMapping:{x:{position:"bottom",geometry:"linear"},y:{position:"right",geometry:"linear"}}},scales:t.scales}}transform(t){return t.layers}}const Fs={x:{point:g.x,lower:g.xMin,upper:g.xMax},y:{point:g.y,lower:g.yMin,upper:g.yMax}},ar=["point","lower","upper"];function Ds(e){return e.name??e.role}function $(e,t){return Fs[e][t]??A(`${e}_${t}`)}function fo(e){const t=[];for(const n of e){const r=Ds(n);t.includes(r)||t.push(r)}return t.sort((n,r)=>sr(n)-sr(r)),t.map(n=>[$("x",n),$("y",n)])}function sr(e){const t=ar.indexOf(e);return t===-1?ar.length:t}class Rs{constructor(t){this.geomRegistry=t,this.coordType="flip"}setup(t){if(t.coordSpec.coordType!=="flip")throw new Error(`Invalid coordinate type: ${t.coordSpec.coordType}`);return{coordSystem:{type:"cartesian",mainAxis:"y",axisMapping:{x:{position:"right",geometry:"linear"},y:{position:"bottom",geometry:"linear"}}},scales:Ns(t.scales,t.layers)}}transform(t){return t.layers.map(n=>{const r=this.geomRegistry.get(n.geom),o=fo(r.positionChannels);return Os(n,o)})}}const ir=A("flipSwap"),Ns=(e,t)=>Ps(t)?e.map(n=>n.scaledAesthetic!=="x"||n.scaleType!=="continuous"&&n.scaleType!=="datetime"&&n.scaleType!=="discrete"?n:{...n,reverse:!n.reverse}):e,Ps=e=>{for(const t of e){const n=v(t.mapping.x);if(!n||!t.data.hasVariable(n))continue;const r=t.data.getType(n);if(r==="categorical"||r==="temporal")return!0}return!1},Os=(e,t)=>{let n=e.data;for(const[r,o]of t){const a=n.hasVariable(r),s=n.hasVariable(o);a&&s?n=n.renameVariable(r,ir).renameVariable(o,r).renameVariable(ir,o):a?n=n.renameVariable(r,o):s&&(n=n.renameVariable(o,r))}return{...e,data:n}};class Bs{constructor(t){this.geomRegistry=t,this.coordType="polar"}setup(t){if(t.coordSpec.coordType!=="polar")throw new Error(`Invalid coordinate type: ${t.coordSpec.coordType}`);const{params:n}=t.coordSpec;return{coordSystem:{type:"polar",axisMapping:n.theta==="x"?{x:{position:"bottom",geometry:"circular"},y:{position:"left",geometry:"radial"}}:{x:{position:"left",geometry:"radial"},y:{position:"bottom",geometry:"circular"}},innerRadius:n.innerRadius,startAngle:n.startAngle*(Math.PI/180)},scales:t.scales}}transform(t){if(t.coordSpec.coordType!=="polar")throw new Error(`Invalid coordinate type: ${t.coordSpec.coordType}`);const{params:n}=t.coordSpec,r=$s(n),o=Gs(n);return t.layers.map(a=>{const s=this.geomRegistry.get(a.geom),i=fo(s.positionChannels),c=n.theta==="y"?Ys(a,i):a,l=Us(c,i,r,o),u=s.spatialKind==="points"?"polar-points":"arcs";return{...l,spatialMap:{kind:u}}})}}function $s(e){const t=e.startAngle*(Math.PI/180);return n=>n*2*Math.PI+t}function Gs(e){const{innerRadius:t}=e;return n=>t+n*(1-t)}function Us(e,t,n,r){let o=e.data;for(const[a,s]of t)o=cr(o,a,n),o=cr(o,s,r);return{...e,data:o}}function cr(e,t,n){if(!e.hasVariable(t))return e;const o=e.getValues(t,{type:"numeric"}).map(a=>a===null?null:n(a));return e.addVariable(t,"numeric",o)}function Ys(e,t){let n=e.data;for(const[r,o]of t){const a=n.hasVariable(r),s=n.hasVariable(o);if(!a&&!s)continue;const i=a?n.getValues(r):null,c=s?n.getValues(o):null;i&&(n=n.addVariable(o,"numeric",i)),c&&(n=n.addVariable(r,"numeric",c))}return{...e,data:n}}class Ws extends Ie{constructor(t){super("coord"),this.register("cartesian",new _s),this.register("flip",new Rs(t)),this.register("polar",new Bs(t))}}const Hs=new Set(["count","sum","mean","median"]);function ho(e,t){return Hs.has(e)?"numeric":t}const V=e=>(Array.isArray(e)?e:[e]).map(n=>n instanceof Date?n.toISOString():String(n??"<null>")).join("\0"),Ks="key",zs="value",lr="\0__rowMaskIndex",Ye={numeric:{type:"decimal"},categorical:{type:"text"},temporal:{type:"datetime"}},Xs={eq:(e,t)=>e[t.__variableName]===t.__value,neq:(e,t)=>e[t.__variableName]!==t.__value,gt:(e,t)=>e[t.__variableName]>t.__value,gte:(e,t)=>e[t.__variableName]>=t.__value,lt:(e,t)=>e[t.__variableName]<t.__value,lte:(e,t)=>e[t.__variableName]<=t.__value},yo=(e,t)=>e==="count"?{type:"integer"}:t;class M{constructor(t={}){const{table:n,variableMetadata:r}=this.parseVariableMap(t);this.table=n,this.variableMetadata=r}static fromTrusted(t,n){const r=Object.create(M.prototype);return r.table=t,r.variableMetadata=n,r}size(){return this.table.numRows()}getVariableNames(){return this.table.columnNames()}hasVariable(t){return this.table.column(t)!==void 0}addVariable(t,n,r,o){const a={...this.variableMetadata,[t]:{type:n,valueFormat:this.resolveAddedVariableFormat(t,n,o)}},s=this.normalizeRawValues(n,r),i=this.table.assign(re.table({[t]:s}));return M.fromTrusted(i,a)}addConstantVariable(t,n,r,o){const a={...this.variableMetadata,[t]:{type:n,valueFormat:this.resolveAddedVariableFormat(t,n,o)}},[s]=this.normalizeRawValues(n,[r]),i=this.table.assign(re.table({[t]:Array(this.size()).fill(s)}));return M.fromTrusted(i,a)}deriveVariable(t,n,r,o){const a=Array.from({length:this.size()},(s,i)=>r(this.table.object(i),i));return this.addVariable(t,n,a,o)}renameVariable(t,n){const r=this.variableMetadata[t];if(!r)throw new Error(`Variable ${t} not defined`);const o=this.table.rename({[t]:n}),{[t]:a,...s}=this.variableMetadata,i={...s,[n]:r};return M.fromTrusted(o,i)}selectVariables(...t){const n=this.table.select(...t),r=Object.fromEntries(Object.entries(this.variableMetadata).filter(([o])=>t.includes(o)));return M.fromTrusted(n,r)}getType(t){const n=this.variableMetadata[t];if(!n)throw new Error(`Variable ${t} not defined`);return n.type}getValueFormat(t){const n=this.variableMetadata[t];if(!n)throw new Error(`Variable ${t} not defined`);return n.valueFormat}groupVariableNamesByType(){const t={numeric:[],categorical:[],temporal:[]};for(const[n,{type:r}]of Object.entries(this.variableMetadata))t[r].push(n);return t}getValues(t,n){if(!this.hasVariable(t))throw new Error(`Variable '${t}' not defined`);const r=this.getType(t);if(n?.type!==void 0&&r!==n.type)throw new Error(`Variable '${t}' has type '${r}', expected '${n.type}'`);let o=this.table.array(t);return n?.distinct&&(o=this.getDistinctValues(r,o)),n?.skipNulls&&(o=this.skipNulls(o)),o}filter(t,n,r){const o=Xs[n],a=this.table.params({__variableName:t,__value:r}).filter(o);return M.fromTrusted(a,this.variableMetadata)}filterByMask(t){if(t.length!==this.size())throw new Error(`Row mask length ${t.length} does not match dataset size ${this.size()}`);const n=Array.from({length:t.length},(o,a)=>a),r=this.table.assign(re.table({[lr]:n})).params({__indexColumnName:lr,__mask:t}).filter((o,a)=>a.__mask[o[a.__indexColumnName]]===1).select(...this.table.columnNames());return M.fromTrusted(r,this.variableMetadata)}orderBy(t,n="asc"){const r=this.table.orderby(n==="asc"?t:re.desc(t));return M.fromTrusted(r,this.variableMetadata)}getFirst(){return this.size()===0?null:this.table.object(0)}getLast(){return this.size()===0?null:this.table.object(this.size()-1)}findLast(t){for(let n=this.size()-1;n>=0;n--){const r=this.table.object(n);if(t(r))return r}return null}groupBy(...t){const n=this.table.groupby(...t);return new js(t,n,this.variableMetadata)}rollup(t){const n=this.table.rollup(Object.fromEntries(Object.entries(t).map(([o,a])=>[o,re.op[a.aggregation](a.variableName)]))),r={};for(const[o,{variableName:a,aggregation:s}]of Object.entries(t)){const i=this.variableMetadata[a],c=i?.type??"numeric",l=i?.valueFormat??Ye[c],u=ho(s,c);r[o]={type:u,valueFormat:yo(s,l)}}return M.fromTrusted(n,r)}reshapeFromWideToLong({keep:t,reshape:n,keyName:r=Ks,valueName:o=zs}={}){const{numeric:a,categorical:s,temporal:i}=this.groupVariableNamesByType(),c=t??[...s,...i],l=n??a.filter(f=>!c.includes(f));if(c.includes(r)||c.includes(o))throw new Error(`The variables to keep includes the variables '${r}' or '${o}' to create the key and value variables`);if(l.length===0){const f={};for(const y of c){const b=this.variableMetadata[y];b&&(f[y]={type:b.type,values:[],valueFormat:b.valueFormat})}return f[r]={type:"categorical",values:[],valueFormat:{type:"text"}},f[o]={type:"numeric",values:[],valueFormat:{type:"decimal"}},new M(f)}if(l.filter(f=>this.variableMetadata[f]?.type!=="numeric").length>0)throw new Error("Only numeric variables can be reshaped");const m=this.table.select([...c,...l]).fold(l,{as:[r,o]}),p={};for(const f of c){const y=this.variableMetadata[f];y&&(p[f]=y)}return p[r]={type:"categorical",valueFormat:{type:"text"}},p[o]={type:"numeric",valueFormat:qs(this.variableMetadata,l,r)},M.fromTrusted(m,p)}print(){console.table(this.variableMetadata),this.table.print()}[Symbol.iterator](){return this.table[Symbol.iterator]()}resolveAddedVariableFormat(t,n,r){if(r!==void 0)return r;const o=this.variableMetadata[t];return o?o.valueFormat:Ye[n]}parseVariableMap(t){const n={},r={};for(const[a,{type:s,values:i,valueFormat:c}]of Object.entries(t))n[a]=i,r[a]={type:s,valueFormat:c??Ye[s]};return{table:re.table(n),variableMetadata:r}}normalizeRawValues(t,n){switch(t){case"numeric":return n.map(r=>typeof r!="number"||Number.isNaN(r)?null:r);case"categorical":return n.map(r=>typeof r!="string"?null:r);case"temporal":return n.map(r=>!(r instanceof Date)||!L.isValid(r)?null:r);default:{const r=t;throw new Error(`Cannot normalize raw value of unknown type: ${r}`)}}}skipNulls(t){return t.filter(n=>n!==null)}getDistinctValues(t,n){const r=t==="temporal",o=new Set,a=[];for(const s of n){const i=r&&s instanceof Date?s.getTime():s;o.has(i)||(o.add(i),a.push(s))}return a}}class js{constructor(t,n,r){this.groupedBy=t,this.grouped=n,this.variableMetadata=r}forEach(t){const n=this.grouped.partitions(),r=this.grouped.columnNames(),o=this.groupedBy.map(s=>this.grouped.column(s)).filter(s=>s!==void 0);let a=0;for(const s of n){const i=s[0];if(i===void 0)continue;const c=this.getStableKey(o,i),l=Object.fromEntries(r.map(d=>{const m=this.grouped.column(d);return[d,s.map(p=>m?.get(p))]})),u=re.table(l);t(M.fromTrusted(u,this.variableMetadata),c,a++)}}rollup(t){const n=this.grouped.rollup(Object.fromEntries(Object.entries(t).map(([o,a])=>[o,re.op[a.aggregation](a.variableName)]))),r=Object.fromEntries(this.groupedBy.map(o=>{const a=this.variableMetadata[o],s=a?.type??"categorical",i=a?.valueFormat??Ye[s];return[o,{type:s,valueFormat:i}]}));for(const[o,{variableName:a,aggregation:s}]of Object.entries(t)){const i=this.variableMetadata[a],c=i?.type??"numeric",l=i?.valueFormat??Ye[c],u=ho(s,c);r[o]={type:u,valueFormat:yo(s,l)}}return M.fromTrusted(n,r)}getStableKey(t,n){return V(t.map(r=>r.get(n)))}}function qs(e,t,n){const r=t.map(c=>e[c]?.valueFormat??{type:"decimal"}),[o,...a]=r;if(!o)return{type:"decimal"};for(const c of r)if(c.type==="lookup")throw new Error("Cannot reshape: a source column has a lookup format and lookups cannot nest");if(a.every(c=>ae.isEqual(c,o))||o.type==="lookup")return o;const i={};for(const[c,l]of t.entries()){const u=V([l]),d=r[c];d&&d.type!=="lookup"&&(i[u]=d)}return{type:"lookup",byVariable:n,cases:i,fallback:o}}class go{constructor(){this.currentYear=new Date().getUTCFullYear(),this.previousDate=null,this.previousYear=null}incrementYearIfNeeded(t){this.previousYear===null?this.previousYear=t.getUTCFullYear():this.previousDate!==null&&L.isBefore(new Date(this.currentYear,t.getUTCMonth(),t.getUTCDate()),new Date(this.currentYear,this.previousDate.getUTCMonth(),this.previousDate.getUTCDate()))&&this.previousYear++;const n=new Date(t.getTime());return n.setUTCFullYear(this.previousYear),this.previousDate=n,n}}const bo=e=>{const t=Object.entries(e);return!t.length||!t.some(([,n])=>!Ze(n))},Ze=e=>typeof e=="string"&&e.trim()===""||e===void 0||e===null||e==="-",Lt="en-GB",Qs=e=>e.type==="lookup",Zs=e=>e.type==="text",Je=e=>e.type==="date"||e.type==="datetime"||e.type==="year"||e.type==="month_year"||e.type==="month"||e.type==="day_month"||e.type==="weekly_date_range"||e.type==="weekly_date_range_with_year"||e.type==="quarter"||e.type==="time",vo=e=>e.type==="decimal"||e.type==="integer"||e.type==="percentage"||e.type==="duration"||e.type==="currency",So=e=>e.type==="currency",xo=e=>e.type==="month"||e.type==="day_month"||e.type==="weekly_date_range",wo=e=>{if(Qs(e))return wo(e.fallback);if(Je(e))return"temporal";if(vo(e))return"numeric";if(Zs(e))return"categorical";const t=e;throw new Error(`No data type found for value format: ${t.type}`)},We={k:1e3,m:1e6,b:1e9,t:1e12},mn=["k","m","b","t"],Js=new RegExp(`^-?(\\d{1,3}(,\\d{3})*|\\d+)\\.?\\d*(${mn.join("|")})?$`,"i"),ei=/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?%?$/,ye=e=>e===null||e instanceof Date||Array.isArray(e)||typeof e=="boolean"?!1:typeof e=="string"?Js.test(e)&&!Number.isNaN(Number(e.replace(new RegExp(`[,${mn.join("")}]`,"gi"),""))):!Number.isNaN(Number(e)),Ao=e=>ye(e)?!0:typeof e=="string"?ei.test(e):!1,ti=/^\d{4}-\d{2}-\d{2}(T|\s)\d{1,2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|\+00:00)?$/,ni=/^\s*(19\d{2}|2[01]\d{2})\s*$/,ri=[[/\bJan\b/i,"January"],[/\bFeb\b/i,"February"],[/\bMar\b/i,"March"],[/\bApr\b/i,"April"],[/\bJun\b/i,"June"],[/\bJul\b/i,"July"],[/\bAug\b/i,"August"],[/\bSept?\b/i,"September"],[/\bOct\b/i,"October"],[/\bNov\b/i,"November"],[/\bDec\b/i,"December"]],oi={"en-US":"MDY","en-GB":"DMY","pt-PT":"DMY",ar:"DMY"},To=["/","-","."," "],ur=[["d","M","yy"],["d","MM","yy"],["d","MMMM","yy"],["dd","M","yy"],["dd","MM","yy"],["dd","MMMM","yy"],["do","MMMM","yy"],["d","M","yyyy"],["d","MM","yyyy"],["d","MMMM","yyyy"],["dd","M","yyyy"],["dd","MM","yyyy"],["dd","MMMM","yyyy"],["do","MMMM","yyyy"]],dr=[["M","d","yy"],["M","dd","yy"],["MM","d","yy"],["MM","dd","yy"],["MMMM","d","yy"],["MMMM","dd","yy"],["MMMM","do","yy"],["M","d","yyyy"],["M","dd","yyyy"],["MM","d","yyyy"],["MM","dd","yyyy"],["MMMM","d","yyyy"],["MMMM","dd","yyyy"],["MMMM","do","yyyy"]],mr=[["yyyy","M","d"],["yyyy","M","dd"],["yyyy","MM","d"],["yyyy","MM","dd"],["yyyy","MMMM","d"],["yyyy","MMMM","dd"],["yyyy","MMMM","do"]],Mo=[["d","MMMM"],["dd","MMMM"],["do","MMMM"],["MMMM","d"],["MMMM","dd"],["MMMM","do"]],ai=[{dateFormat:"MMMM d, yyyy",type:"date"},{dateFormat:"MMMM dd, yyyy",type:"date"},{dateFormat:"MMMM do, yyyy",type:"date"},{dateFormat:"yyyy-MM",type:"month_year"}],Lo=1900,Vo=2199,si=3,ii=6,ci=5,li=1,ui=28,di=/\s*[–—]\s*|\s-\s/,mi=e=>typeof e=="number"?Number.isNaN(e)?!1:e>=Lo&&e<=Vo:typeof e=="string"?ni.test(e):!1,ko=(e,t)=>{const n=Ke(e);return ye(n)?hi(n):typeof n=="string"?!!Eo(n)||pn(n)&&L.isValid(new Date(n)):L.isValid(n)},Ke=e=>{if(typeof e!="string")return e;let t=e;for(const[n,r]of ri)t=t.replace(n,r);return t},Eo=(e,t=Lt)=>{const n=Ke(e);return pn(n)?{type:"datetime"}:Io(t).find(r=>!Je(r)||r.type==="month"&&n.length<si?!1:r.dateFormat&&L.isValid(L.parse(n,r.dateFormat,new Date)))},pn=e=>ti.test(e.trim()),pi=(e,t=Lt)=>{const[n,r]=e.split(di);if(!n||!r)return;const o=Ke(n).trim(),a=Ke(r).trim();return fi(t).find(s=>{if(!Je(s)||!s.dateFormat)return!1;const i=L.parse(o,s.dateFormat,new Date),c=L.parse(a,s.dateFormat,new Date);if(!L.isValid(i)||!L.isValid(c))return!1;const l=new go,u=l.incrementYearIfNeeded(i),d=l.incrementYearIfNeeded(c),m=L.differenceInDays(d,u);return L.isWithinInterval(new Date(u.getFullYear(),li,ui),{start:u,end:d})&&m===ci?!0:m===ii})},Io=e=>{const t={date:Co(e),year:[["yyyy"]],day_month:Mo,month_year:[["MMMM","yyyy"],["yyyy","MMMM"]],month:[["MMMM"]],quarter:[["QQQ","yyyy"],["yyyy","QQQ"]]};return[...ai,...Object.entries(t).flatMap(([n,r])=>r.flatMap(o=>To.map(a=>({dateFormat:o.join(a),type:n}))))]},Co=e=>oi[e]==="MDY"?[...dr,...ur,...mr]:[...ur,...dr,...mr],fi=e=>{const t={weekly_date_range:Mo,weekly_date_range_with_year:Co(e)};return Object.entries(t).flatMap(([n,r])=>r.flatMap(o=>To.map(a=>({dateFormat:o.join(a),type:n}))))},hi=e=>{const t=Number(e);if(!ae.isInteger(t))return!1;const n=new Date(t),r=new Date(t*1e3),o=a=>L.isValid(a)&&a.getFullYear()>=Lo&&a.getFullYear()<=Vo;return o(n)||o(r)},_o={$:"usd","£":"gbp","€":"eur","¥":"jpy","₹":"inr","₱":"php",P:"php","₩":"krw","₪":"ils","₫":"vnd","₽":"rub","฿":"thb",R$:"brl",Rp:"idr",RM:"myr","₦":"ngn",zł:"pln","₺":"try",kr:"dkk",Fr:"chf",R:"zar","د.إ":"aed","﷼":"sar",Ch$:"clp",NT$:"twd",HK$:"hkd",S$:"sgd",A$:"aud",C$:"cad",NZ$:"nzd",MX$:"mxn"},Fo=e=>{if(typeof e=="string"){const t=Do(e);return t.length?ye(t):!1}return ye(e)},yi=e=>{const t=Ro(e),n=t?_o[t]:void 0;if(!n)throw new Error("Could not get currency ISO");return n},Do=e=>{const t=Ro(e);let n=e;if(t){const r=e.indexOf(t);r===0?n=e.slice(t.length):r===e.length-t.length?n=e.slice(0,e.length-t.length):e[0]==="-"&&r===1&&(n=`-${e.slice(t.length+1)}`)}return ye(n)?n.split(",").join(""):""},Ro=e=>Object.keys(_o).sort((n,r)=>r.length-n.length).find(n=>e.includes(n)),gi=(e,t)=>{const n=typeof e=="string"?e.trim():e;if(ye(n))return{type:"decimal"};const r=typeof n=="string"&&Eo(n,t);if(r)return r;const o=typeof n=="string"&&pi(n,t);return o||(ko(e)?{type:"date"}:Ao(e)?{type:"percentage"}:Fo(e)&&typeof e=="string"?{type:"currency",iso:yi(e)}:{type:"text"})},bi=/\s*[–—]\s*|\s-\s/,vi=(e,t,n)=>{if(Ze(e))return null;switch(t.type){case"decimal":case"integer":case"duration":return No(e);case"percentage":return Si(e);case"currency":return xi(e);case"datetime":case"date":case"year":case"month_year":case"month":case"day_month":case"quarter":case"time":return fn(e,t.dateFormat,n);case"weekly_date_range":case"weekly_date_range_with_year":return wi(e,t.dateFormat,n);case"text":return Ai(e);case"lookup":throw new Error("Cannot parse: lookup value formats are produced by transforms, not raw input");default:{const r=t;throw new Error(`Unhandled value format: ${r.type}`)}}},fn=(e,t,n)=>{if(e instanceof Date)return L.isValid(e)?e:null;const r=Ke(String(e).trim());if(r.length===0)return null;const o=new Date;if(t){const s=L.parse(r,t,o);return L.isValid(s)?Pt(s):null}for(const s of Io(n)){if(!Je(s)||!s.dateFormat)continue;const i=L.parse(r,s.dateFormat,o);if(L.isValid(i))return Pt(i)}const a=new Date(r);return ko(a)?pn(r)?a:Pt(a):null},No=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;let t=e.trim();if(!ye(t))return null;let n=1;for(const r of mn)if(new RegExp(`${r}$`,"i").test(t)){n=We[r],t=t.slice(0,-1);break}return Number(t.split(",").join(""))*n},Si=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;const t=e.trim();if(!Ao(t))return null;const n=Number(t.replace(/%/g,"").replace(/,/g,""))/100;return Number.isNaN(n)?null:n},xi=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;const t=e.trim();return Fo(t)?No(Do(t)):null},wi=(e,t,n)=>{const r=String(e).trim().split(bi),[o,a]=[r[0]?.trim(),r[1]?.trim()];return!o||!a?null:fn(o,t,n)},Ai=e=>String(e).trim(),Pt=e=>new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())),Ti={type:"year",dateFormat:"yyyy"};class Mi extends se{dependencies(t){return[t]}run(t){const n=t._metadata?.parsingLocale??Lt,r={},o=ki(t),a=Li(t);for(const[s,i]of t.columns.entries()){if(i._metadata?.isHidden)continue;const c=o.get(i.key);if(Ze(c))continue;const l=s===a?Ti:gi(c,n),u=wo(l);r[i.key]=Vi(i.key,t.rows,l,u,n)}return new M(r)}}const Li=e=>{const t=Ei(e.rows,5);return e.columns.findIndex(n=>{const r=t.map(o=>o[n.key]).filter(o=>!Ze(o));return r.length>=2&&r.every(mi)})},Vi=(e,t,n,r,o)=>{const a=new go,s=t.reduce((i,c)=>{if(bo(c))return i;const l=vi(c[e],n,o);return xo(n)&&O(l)?i.push(a.incrementYearIfNeeded(l)):i.push(l),i},[]);return{type:r,values:s,valueFormat:n}},ki=e=>{const t=new Map,n=new Set(e.columns.map(r=>r.key));for(const r of e.rows){for(const o of n){const a=r[o];Ze(a)||(t.set(o,a),n.delete(o))}if(n.size===0)break}return t},Ei=(e,t)=>{const n=[];for(const r of e)if(bo(r)||n.push(r),n.length===t)return n;return n};class Ii{constructor(t){this.registry=t}compile(t,n){return this.registry.get(t).compile(n)}getPositionChannels(t){return this.registry.get(t).positionChannels}getSwatchShape(t){return this.registry.get(t).swatchShape}getSpatialKind(t){return this.registry.get(t).spatialKind}getVisualAesthetics(t){return this.registry.get(t).visualAesthetics}getHighlightStrategy(t){return this.registry.get(t).highlightStrategy}getDirectLabelPositions(t){return this.registry.get(t).directLabelPositions}getGridPolicies(t){return this.registry.get(t).gridPolicies}getIdentityKeyStrategy(t){return this.registry.get(t).identityKeyStrategy}emitsGrandTotal(t){return this.registry.get(t).emitsGrandTotal}emitsStackTotals(t){return this.registry.get(t).emitsStackTotals}supportsPerGroupHeadline(t){return this.registry.get(t).supportsPerGroupHeadline}resolveAnchorPosition(t,n,r){return this.registry.get(t).resolveAnchorPosition(n,r)}}class Ce{constructor(){this.requiredAesthetics=[],this.defaultParams={},this.positionChannels=[],this.visualAesthetics=["color","size","alpha","strokeWidth","lineType"],this.swatchShape="square",this.highlightStrategy=null,this.spatialKind="noop",this.directLabelPositions=[],this.gridPolicies={},this.identityKeyStrategy="fields",this.supportedCoordTypes=["cartesian","flip","polar"],this.emitsGrandTotal=!1,this.emitsStackTotals=!1,this.supportsPerGroupHeadline=!1}resolveAnchorPosition(t,n){return null}}const Vt=(e,t)=>{const n=v(t.x);return!n||!["numeric","temporal"].includes(e.getType(n))?e:e.orderBy(n,"asc")};class Ci extends Ce{constructor(){super(...arguments),this.type="area",this.requiredAesthetics=["x","y"],this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"},{axis:"y",role:"lower",valueKind:"value"},{axis:"y",role:"upper",valueKind:"value"}],this.swatchShape="area",this.highlightStrategy="overlay-anchor",this.spatialKind="buckets",this.directLabelPositions=["identity","stack","dodge","fill"],this.supportsPerGroupHeadline=!0}compile({data:t,mapping:n}){if(t=Vt(t,n),t.hasVariable(g.yMin)||(t=t.addConstantVariable(g.yMin,"numeric",0)),!t.hasVariable(g.yMax)){const r=v(n.y);h(r)&&t.hasVariable(r)&&(t=t.addVariable(g.yMax,"numeric",t.getValues(r,{type:"numeric"})))}return{data:t,mapping:{}}}}const Po=.7,_i=.1;function _e(e){return e[g.x]}function te(e){return e[g.y]}function ze(e){return e[g.xMin]}function Le(e){return e[g.xMax]}function ge(e){return e[g.yMin]}function j(e){return e[g.yMax]}function Oo(e){return e[g.yRaw]}class Fi extends Ce{constructor(){super(...arguments),this.type="bar",this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"},{axis:"x",role:"lower",valueKind:"bandOffset"},{axis:"x",role:"upper",valueKind:"bandOffset"},{axis:"y",role:"lower",valueKind:"value"},{axis:"y",role:"upper",valueKind:"value"}],this.swatchShape="square",this.highlightStrategy="observation-rerender",this.spatialKind="rects",this.directLabelPositions=["stack","fill"],this.gridPolicies={cartesian:{hideGridX:!0},flip:{hideGridX:!0},polar:{hideGridX:!0,hideGridY:!0}},this.emitsGrandTotal=!0,this.emitsStackTotals=!0,this.supportsPerGroupHeadline=!0}compile({data:t,mapping:n}){if(t=Vt(t,n),t.hasVariable(g.yMin)||(t=t.addConstantVariable(g.yMin,"numeric",0)),!t.hasVariable(g.yMax)){const o=v(n.y);h(o)&&t.hasVariable(o)&&(t=t.addVariable(g.yMax,"numeric",t.getValues(o,{type:"numeric"})))}const r=Po/2;return t=t.addConstantVariable(g.xMin,"numeric",-r).addConstantVariable(g.xMax,"numeric",r),{data:t,mapping:{}}}resolveAnchorPosition(t,n){if(n.type==="polar"){const s=ze(t),i=Le(t),c=ge(t),l=j(t);if(s===null||i===null||c===null||l===null)return null;const u=(s+i)/2,d=(c+l)/2;return{x:.5+.5*d*Math.sin(u),y:.5-.5*d*Math.cos(u),geom:"polar-bar"}}if(n.mainAxis==="x"){const s=ze(t),i=Le(t),c=j(t)??te(t);return s===null||i===null||c===null?null:{x:(s+i)/2,y:c,geom:"bar"}}const r=ge(t),o=j(t),a=Le(t)??_e(t);return r===null||o===null||a===null?null:{x:a,y:(r+o)/2,geom:"bar"}}}class Di extends Ce{constructor(){super(...arguments),this.type="line",this.requiredAesthetics=["x","y"],this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"}],this.swatchShape="line",this.highlightStrategy="overlay-anchor",this.spatialKind="buckets",this.directLabelPositions=["identity","stack","dodge","fill"],this.supportsPerGroupHeadline=!0}compile(t){return{data:Vt(t.data,t.mapping),mapping:{}}}resolveAnchorPosition(t,n){if(n.type==="polar")return null;const r=_e(t),o=te(t);return r===null||o===null?null:{x:r,y:o,geom:"line"}}}class Ri extends Ce{constructor(){super(...arguments),this.type="point",this.requiredAesthetics=["x","y"],this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"}],this.swatchShape="circle",this.highlightStrategy="overlay-anchor",this.spatialKind="points",this.identityKeyStrategy="index",this.supportsPerGroupHeadline=!0}compile({data:t}){return{data:t,mapping:{}}}}class Ni extends Ce{constructor(){super(...arguments),this.type="rule",this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"}],this.highlightStrategy=null,this.supportedCoordTypes=["cartesian","flip"]}compile({data:t,mapping:n}){const r=pr(n.y,t);if(r!==null)return{data:new M({[at.y]:{type:"numeric",values:[r.value],valueFormat:r.sourceFormat}}),mapping:{y:at.y,x:void 0}};const o=pr(n.x,t);return o!==null?{data:new M({[at.x]:{type:"numeric",values:[o.value],valueFormat:o.sourceFormat}}),mapping:{x:at.x,y:void 0}}:{data:new M,mapping:{x:void 0,y:void 0}}}validateMapping({layerId:t,mapping:n,computedVariables:r}){const o=r.has("x")||E(ee(n.x)),a=r.has("y")||E(ee(n.y));return o&&a?[{code:"INVALID_RULE_MAPPING",message:`Layer '${t}': rule geom requires exactly one of 'x' or 'y', both were provided`,layerId:t}]:!o&&!a?[{code:"INVALID_RULE_MAPPING",message:`Layer '${t}': rule geom requires a numeric value on 'x' or 'y'`,layerId:t}]:[]}}const pr=(e,t)=>{const n=ee(e);if(E(n))return{value:n,sourceFormat:void 0};const r=v(e);if(r===null||!us(r)||!t.hasVariable(r))return null;const[o]=t.getValues(r);return E(o)?{value:o,sourceFormat:t.getValueFormat(r)}:null};class Pi extends Ie{constructor(t){super("geom"),this.register("bar",new Fi),this.register("point",new Ri),this.register("line",new Di),this.register("area",new Ci),this.register("rule",new Ni);for(const n of t?.geoms??[])this.register(n.type,n)}}const hn=(e,t)=>{if(h(t.group)){const o=v(t.group);if(o!==null)return[o]}const n=new Set([v(t.x),v(t.y)].filter(h)),r=new Set;for(const o in t){if(o==="x"||o==="y")continue;const a=v(t[o]);h(a)&&(n.has(a)||e.getType(a)==="categorical"&&r.add(a))}return[...r]};class Oi{compute({data:t,mapping:n}){const r=hn(t,n);if(r.length===0)return{data:t.addConstantVariable(D.group,"categorical",null)};const o=t.size(),a=r.map(i=>t.getValues(i)),s=new Array(o);for(let i=0;i<o;i++)s[i]=V(a.map(c=>c[i]));return{data:t.addVariable(D.group,"categorical",s)}}}const Bo=new Set(["x","y","ySecondary"]),kt=new Set(["color","size","alpha","strokeWidth","lineType"]),Et=e=>Bo.has(e),Bi=e=>kt.has(e),$i=e=>Et(e)||Bi(e);function et(e){return e==="secondary"?"ySecondary":"y"}function q(e){return e==="ySecondary"?"y":e}const Gi=e=>{if(e===void 0)return{};const t={};for(const n of e.columns)n.label!==void 0&&(t[n.key]=n.label);return t},Ui=(e,t,n)=>{const r=be(t,"color");return r===null?{}:(e?.columns??[]).some(s=>s.key===r)?{}:n};function be(e,t){const n=q(t);for(const r of $o(t,e)){const o=v(r.mapping[n]);if(h(o))return o}return null}const yn=(e,t)=>e===null?null:t[e]??e,Yi=(e,t)=>e===null?null:t[String(e)]??null,ve=({layers:e,scaleType:t,variableName:n})=>{if(n===null)return Ot(t);for(const r of e){if(!r.data.hasVariable(n))continue;const o=r.data.getValueFormat(n),a=o.type==="lookup"?o.fallback:o;return Hi(a,t)?a:Ot(t)}return Ot(t)},Wi=(e,t)=>t!=="y"&&t!=="ySecondary"?!1:$o(t,e).some(n=>n.position==="fill");function $o(e,t){return e==="ySecondary"?t.filter(n=>n.yScaleType==="secondary"):e==="y"?t.filter(n=>n.yScaleType==="primary"):t}const Ot=e=>{switch(e){case"continuous":return{type:"decimal"};case"datetime":return{type:"date"};case"discrete":case"palette":case"identity":return{type:"text"}}},Hi=(e,t)=>{switch(t){case"continuous":return vo(e);case"datetime":return Je(e);case"discrete":case"palette":case"identity":return!0}},Ki=[{unit:"year",step:1e3},{unit:"year",step:100},{unit:"year",step:50},{unit:"year",step:20},{unit:"year",step:10},{unit:"year",step:5},{unit:"year",step:2},{unit:"year",step:1},{unit:"month",step:6},{unit:"month",step:3},{unit:"month",step:2},{unit:"month",step:1},{unit:"week",step:2},{unit:"week",step:1},{unit:"day",step:2},{unit:"day",step:1},{unit:"hour",step:12},{unit:"hour",step:6},{unit:"hour",step:3}],fr={year:0,quarter:1,month:2,week:3,day:4,hour:5},xe=40,zi=(e,t,n)=>{const r=n.unit==="quarter"?n.step*3:n.step;return Qi(n.unit).range(e,new Date(t.valueOf()+1),r)},Xi=({unit:e,step:t,start:n,stop:r})=>{const o=es.differenceInDays(r,n);switch(e){case"hour":return 24*o/t>xe;case"day":return o/t>xe;case"week":return o/(7*t)>xe;case"month":return o/(30*t)>xe;case"quarter":return o/(90*t)>xe;case"year":return o/(365*t)>xe}},ji=(e,t)=>{const n=!xo(t);switch(e.unit){case"year":return n?{type:"year"}:{type:"month"};case"quarter":return{type:"quarter"};case"month":return n?{type:"month_year"}:{type:"month"};case"week":return n?{type:"weekly_date_range_with_year"}:{type:"weekly_date_range"};case"day":return n?{type:"date"}:{type:"day_month"};case"hour":return n?{type:"datetime"}:{type:"time"}}},qi=(e,t)=>{const n=Zi(t);return n===null?!1:fr[e]>fr[n]},Qi=e=>{switch(e){case"hour":return Pe.utcHour;case"day":return Pe.utcDay;case"week":return Pe.utcMonday;case"month":case"quarter":return Pe.utcMonth;case"year":return Pe.utcYear}},Zi=e=>{switch(e.type){case"year":return"year";case"quarter":return"quarter";case"month_year":case"month":return"month";case"weekly_date_range":case"weekly_date_range_with_year":return"week";case"date":case"day_month":case"datetime":return"day";case"time":return"hour";default:return null}},Go={left:"right",right:"left",top:"bottom",bottom:"top"},Ji={x:!0,y:!0,ySecondary:!1},ec=20,hr=new Set(["top","bottom"]),tc={type:"percentage"};function nc(e,t){const{scales:n,config:r,layers:o,coordSystem:a,variableLabels:s,geomCompiler:i}=e;if(a.type==="polar"&&a.axisMapping.x.geometry!=="circular")return[];const c=oc(o,a.type,r,i),l=new Set(t.map(m=>m.position)),u=sc(Uo(r.axes.y.position,a.axisMapping.y.position),l),d=[];for(const m of Bo){const p=n[m];if(!h(p)||p.kind!=="position")continue;const f=rc({scaleAestheticKey:m,scale:p,config:r,layers:o,axisMapping:a.axisMapping,resolvedYPosition:u,gridOverrides:c,variableLabels:s});d.push(f)}return d}function rc(e){const{scaleAestheticKey:t,scale:n,config:r,layers:o,axisMapping:a,resolvedYPosition:s,gridOverrides:i,variableLabels:c}=e,l=q(t),{axisConfig:u,position:d}=ac(t,r,a,s),m=be(o,t),p=Wi(o,t)?tc:ve({layers:o,scaleType:n.spec.scaleType,variableName:m}),f=yn(m,c);return{scaleAestheticKey:t,aesthetic:l,position:d,geometry:a[t==="x"?"x":"y"].geometry,label:u.label??f,isVisible:u.isVisible,tickCandidates:cc(n,p),valueFormat:p,tickMode:u.ticks.mode,ticksVisible:u.ticks.isVisible,gridVisible:ic(u,i,t),scaleType:n.spec.scaleType,bandwidth:n.bandwidth??void 0}}function oc(e,t,n,r){const o=e.flatMap(c=>{const l=r.getGridPolicies(c.geom)[t];return l?[l]:[]}),a=o.some(c=>c.hideGridX),s=o.some(c=>c.hideGridY),i=o.some(c=>c.hideBorder);return{x:{gridVisible:yr(a,n.axes.x.grid.isVisible)},y:{gridVisible:yr(s,n.axes.y.grid.isVisible)},borderVisible:i?!1:void 0}}function yr(e,t){if(e&&t===null)return!1}function ac(e,t,n,r){switch(e){case"x":return{axisConfig:t.axes[e],position:Uo(t.axes[e].position,n[e].position)};case"y":return{axisConfig:t.axes[e],position:r};case"ySecondary":{const o=Go[r],a=ae.merge({isVisible:t.axes.y.isVisible,label:null,position:o,grid:t.axes.y.grid,ticks:t.axes.y.ticks},t.axes.ySecondary);return{axisConfig:a,position:a.position}}}}function Uo(e,t){return hr.has(e)===hr.has(t)?e:t}function sc(e,t){return t.has(e)?Go[e]:e}function ic(e,t,n){const{gridVisible:r}=n==="x"?t.x:t.y;return r??e.grid.isVisible??Ji[n]}const cc=(e,t)=>{if(e.spec.scaleType==="continuous"){const r=new Set,o=[];for(let a=1;a<=ec;a++){const s=e.generateTicks({count:a}),i=V(s);r.has(i)||(r.add(i),o.push({ticks:s.map(c=>St(e,c))}))}return o}return e.spec.scaleType==="datetime"?lc(e,t):[{ticks:e.generateTicks().map(r=>St(e,r))}]},lc=(e,t)=>{const[n,r]=e.domain;if(!O(n)||!O(r))return[{ticks:e.generateTicks().map(c=>St(e,c))}];const o=new Set,a=[],s=(i,c)=>{if(i.length===0)return;const l=V(i);o.has(l)||(o.add(l),a.push({ticks:i.map(u=>St(e,u)),valueFormat:c}))};for(const i of Ki)Xi({...i,start:n,stop:r})||qi(i.unit,t)||s(e.generateTicks({interval:i}),ji(i,t));return s(e.generateTicks({atInputs:!0})),a.sort((i,c)=>i.ticks.length-c.ticks.length),a},St=(e,t)=>({value:t,position:e.map(t)});function Xe(e,t){return t.type==="polar"&&e==="square"?"slice":e}function Yo({scale:e,aesthetics:t,layers:n,coordSystem:r}){const o=uc({layers:n,coordSystem:r,aesthetics:t}),a=Wo({layers:n,aesthetics:t});return e.domain.map(s=>({value:s,swatchShape:o(s),owner:a(s)}))}function uc({layers:e,coordSystem:t,aesthetics:n}){const r=Wo({layers:e,aesthetics:n}),o=e.find(s=>n.some(i=>h(s.mapping[i]))),a=o?Xe(o.swatchShape,t):"square";return s=>{const i=r(s);return i?Xe(i.layer.swatchShape,t):a}}function Wo({layers:e,aesthetics:t,layerFilter:n}){const r=new Map;for(const[o,a]of e.entries()){if(n&&!n(a))continue;const s=t.find(c=>h(a.mapping[c]));if(s===void 0)continue;const i=v(a.mapping[s]);if(!(i===null||!a.data.hasVariable(i)))for(const c of a.data.getValues(i,{distinct:!0})){const l=V(c);r.has(l)||r.set(l,{layer:a,layerIndex:o})}}return o=>r.get(V(o))}const gn=e=>{if(e.kind==="identity")return!1;const t=e.spec.scaleType;return t!=="continuous"&&t!=="datetime"};function dc({scales:e,layers:t,coordSystem:n,valueLabels:r}){const o=e.color;if(o===void 0||!gn(o))return[];if(!t.some(u=>h(u.mapping.color)))return[];const a=be(t,"color");if(Ho({colorVariableName:a,xVariableName:be(t,"x"),mapsColorAcrossMultipleLayers:pc(t)>1,isMergedWithAnotherAesthetic:mc(e,t,a)}))return[];const i=o.spec.scaleType,c=t.findIndex(u=>h(u.mapping.color));return Yo({scale:o,aesthetics:["color"],layers:t,coordSystem:n}).map(({value:u,swatchShape:d,owner:m})=>{const p=m?.layerIndex??c,f=t[p],y=f?v(f.mapping.color):null;return{value:u,color:String(o.map(u)),shape:d,layerIndex:p,valueFormat:ve({layers:f?[f]:t,scaleType:i,variableName:y}),label:Yi(u,r)}})}const Ho=({colorVariableName:e,xVariableName:t,mapsColorAcrossMultipleLayers:n,isMergedWithAnotherAesthetic:r})=>r?!1:e===null||ls(e)?!n:t!==null&&e===t;function mc(e,t,n){if(n===null)return!1;for(const r of kt){if(r==="color")continue;const o=e[r];if(!(o===void 0||!gn(o))&&be(t,r)===n)return!0}return!1}const pc=e=>e.filter(t=>h(t.mapping.color)).length;function fc(e,t,n,r){const o=t.findIndex(a=>r.supportsPerGroupHeadline(a.geom));if(o===-1)return[];if(e.length<2){const a=v(t[o]?.mapping.y);return[{value:null,swatch:null,layerIndex:o,groupLabelFormat:{type:"text"},label:yn(a,n)}]}return e.map(a=>({value:a.value,swatch:{color:a.color,shape:a.shape},layerIndex:a.layerIndex,groupLabelFormat:a.valueFormat,label:a.label}))}function gr(e,t,n){if(n===null||t===null)return[...e];const r=V(n);return e.filter((o,a)=>V(t[a]??null)===r)}const hc=(e,t)=>{switch(t){case"total":{const{sum:n,count:r}=br(e);return r===0?null:n}case"average":{const{sum:n,count:r}=br(e);return r===0?null:n/r}case"current":return e.at(-1)??null}},yc=(e,t)=>{if(e.length<2)return null;const n=e.at(-1),r=t==="previous"?e.at(-2):e.at(0);return n===void 0||r===void 0||n.cross===null||r.cross===null||r.cross===0?null:{variation:(n.cross-r.cross)/r.cross,against:r.main}},br=e=>e.reduce((t,n)=>n===null?t:{sum:t.sum+n,count:t.count+1},{sum:0,count:0});function gc(e){const{config:t,coordSystem:n}=e,r=t.headline.show;return r==="none"||r==="conversion"?null:n.type==="polar"?bc(e,r):vc(e,r)}function bc(e,t){if(t!=="total")return null;const{scales:n,layers:r}=e,o=r.find(c=>c.summary.grandTotal!==void 0);if(o===void 0)return null;const a=o.summary.grandTotal;if(a===void 0)return null;const s=v(o.mapping.y);if(s===null)return null;const i=ve({layers:[o],scaleType:n.y?.spec.scaleType??"continuous",variableName:s});return{kind:"grandTotal",value:a,valueFormat:i}}function vc(e,t){const{config:n,scales:r,layers:o,variableLabels:a,colorGroups:s,geomCompiler:i}=e;if(!o.some(u=>i.supportsPerGroupHeadline(u.geom)))return null;const c=fc(s,o,a,i);if(c.length===0)return null;const l=c.map(u=>Sc({group:u,show:t,compareWith:n.headline.compareWith,layers:o,scales:r})).filter(u=>u!==null);return l.length===0?null:{kind:"perGroup",items:l}}function Sc({group:e,show:t,compareWith:n,layers:r,scales:o}){const a=r[e.layerIndex];if(a===void 0)return null;const s=v(a.mapping.y);if(s===null||t==="total"&&a.position==="fill")return null;const i=v(a.mapping.x),c=v(a.mapping.color),l=a.yScaleType==="secondary"?o.ySecondary:o.y,u=ve({layers:[a],scaleType:l?.spec.scaleType??"continuous",variableName:s}),d=Ac(a.data,i),m=ve({layers:[a],scaleType:d?"datetime":o.x?.spec.scaleType??"discrete",variableName:i}),p=Tc(a.data,i),f=p.getValues(s,{type:"numeric"}),y=i!==null?p.getValues(i):[],b=c!==null?p.getValues(c):null,x=gr(f,b,e.value),S=gr(y,b,e.value);return{value:e.value,swatch:e.swatch,aggregate:hc(x,t),valueFormat:u,groupLabelFormat:e.groupLabelFormat,mainValueFormat:m,label:e.label,observationLabel:xc(t,d,S),comparison:wc(t,n,d,S,x)}}function xc(e,t,n){if(e==="current"){const a=n.at(-1);return a===void 0?null:{kind:"point",value:a}}if(!t)return null;const r=n.at(0),o=n.at(-1);return r===void 0||o===void 0?null:{kind:"range",from:r,to:o}}function wc(e,t,n,r,o){if(e!=="current"||!n)return null;const a=t==="none"?"first":t,s=r.map((i,c)=>({main:i,cross:o[c]??null}));return yc(s,a)}function Ac(e,t){return t!==null&&e.hasVariable(t)&&e.getType(t)==="temporal"}function Tc(e,t){return t===null||!["numeric","temporal"].includes(e.getType(t))?e:e.orderBy(t)}const Ko=["point","line","area","bar","rule"],zo=new Set(Ko);function Xo(e){return zo.has(e)}function Y(e){return e==="stack"||e==="fill"}const Mc=3;function Lc({scales:e,config:t,layers:n,coordSystem:r,variableLabels:o,colorGroups:a,geomCompiler:s}){if(t.legend.position==="none")return[];const i=new Map(a.map(b=>[V(b.value),b])),c=Ec({scales:e,layers:n,geomCompiler:s}),l=Dc(c),u=be(n,"x"),d=l.map(b=>{if(_c(b,u,n))return null;const x=Nc({group:b,variableLabels:o,layers:n,coordSystem:r,colorGroupsByValue:i});return x.items.length===0?null:{group:b,built:x}}).filter(h);if(d.length===0)return[];const m=Vc(d);if(t.legend.position==="auto"&&Gc(m,n,r))return[];const p=Uc(t.legend.position,m,n,r),f=Wc(t.legend.display,p,n,r,s),y=f==="direct"?zc(n):null;return d.map(({built:b})=>kc(b,p,f,y))}function Vc(e){return e.reduce((t,{group:n,built:r})=>{const o=n.some(a=>a.guideType!=="discrete");return t+(o?1:r.items.length)},0)}function kc(e,t,n,r){return n!=="direct"||r===null?{...e,position:t,display:n}:{...e,position:t,display:n,items:e.items.map(o=>({...o,normalizedY:r.get(String(o.value))??null}))}}function Ec(e){const{scales:t,layers:n,geomCompiler:r}=e,o=Ic(n,r),a=[];for(const s of kt){if(!o.has(s))continue;const i=t[s];if(i===void 0||i.kind==="identity"||!Cc(s,n))continue;const c=be(n,s),l=Kc(s,i);a.push({scaleAestheticKey:s,scale:i,variableName:c,guideType:l})}return a}function Ic(e,t){const n=new Set;for(const r of e)for(const o of t.getVisualAesthetics(r.geom))n.add(o);return n}function Cc(e,t){const n=q(e);return t.some(r=>h(r.mapping[n]))}function _c(e,t,n){const[r]=e;return r.scaleAestheticKey!=="color"?!1:Ho({colorVariableName:r.variableName,xVariableName:t,mapsColorAcrossMultipleLayers:Fc(r.scaleAestheticKey,n),isMergedWithAnotherAesthetic:e.length>1})}function Fc(e,t){const n=q(e);return t.filter(r=>h(r.mapping[n])).length>1}function Dc(e){const t=new Map;for(const n of e){const r=Hc(n),o=t.get(r);o?o.push(n):t.set(r,[n])}return[...t.values()]}function Rc(e,t,n){if(t==="lineType"){e.lineType=n;return}if(t==="color"){e.color=String(n);return}e[t]=n}function Nc({group:e,variableLabels:t,layers:n,coordSystem:r,colorGroupsByValue:o}){const a=e[0],s=e.map(u=>q(u.scaleAestheticKey)),i=Yo({scale:a.scale,aesthetics:s,layers:n,coordSystem:r}),c=yn(a.variableName,t),l=ve({layers:n,scaleType:a.scale.spec.scaleType,variableName:a.variableName});return{aesthetics:e.map(u=>u.scaleAestheticKey),title:c,items:i.map(u=>Pc(u,e,s,l,o))}}function Pc(e,t,n,r,o){const a={};for(const i of t)Rc(a,i.scaleAestheticKey,i.scale.map(e.value));const s=Bc(e,t,n,r,o);return{value:e.value,label:Oc(t,e,o),visual:a,normalizedY:null,swatchShape:e.swatchShape,valueFormat:s}}function Oc(e,t,n){return e[0].scaleAestheticKey!=="color"?null:n.get(V(t.value))?.label??null}function Bc(e,t,n,r,o){if(t[0].scaleAestheticKey==="color")return o.get(V(e.value))?.valueFormat??r;const a=e.owner?.layer,s=$c(a,n);return a===void 0||s===null?r:ve({layers:[a],scaleType:t[0].scale.spec.scaleType,variableName:s})}function $c(e,t){if(e===void 0)return null;for(const n of t){const r=e.mapping[n];if(r===void 0)continue;const o=v(r);if(o!==null)return o}return null}function Gc(e,t,n){if(e>1)return!1;const r=n.type==="polar";return pt(t,["line","area","bar"])||r}function Uc(e,t,n,r){if(e!=="auto")return e;if(r.type==="polar")return"top";const o=pt(n,["line","area"]),a=pt(n,["bar"]),s=pt(n,["bar"],c=>Y(c.position)),i=t>=Mc;return o&&a?"top":o?i?"right":"top":s?jo(r)?"top":i?"right":"top":"top"}function Yc(e,t){if(e.length!==1)return!1;const n=e[0];return n?t.getDirectLabelPositions(n.geom).includes(n.position):!1}function Wc(e,t,n,r,o){if(!(t==="right"&&!jo(r)))return"pill";switch(e){case"pill":return"pill";case"direct":return"direct";case"auto":return Yc(n,o)?"direct":"pill"}}function jo(e){return e.type==="cartesian"&&e.mainAxis==="y"}function pt(e,t,n){return e.some(r=>t.includes(r.geom)&&(n?.(r)??!0))}function Hc(e){const t=e.scale.domain.map(V);return JSON.stringify([e.variableName,e.guideType,...t])}function Kc(e,t){return gn(t)?"discrete":`continuous:${e}`}function zc(e){const t=e[0];if(!t)return new Map;const n=new Map;return t.data.groupBy(D.group).forEach(r=>{const o=r.findLast(l=>h(j(l))||h(te(l)));if(!o)return;const a=ke(o);if(!h(a))return;const s=ge(o),i=j(o)??te(o);if(!h(i))return;const c=h(s)?(s+i)/2:i;n.set(String(a),c)}),n}class Xc extends se{constructor(t){super(),this.geomCompiler=t}dependencies(t){return[t.scales,t.config.axes,t.config.legend,t.config.headline,t.config.panel,t.layers,t.coordSystem,t.originalData]}run(t){const n=Gi(t.originalData),r=dc({scales:t.scales,layers:t.layers,coordSystem:t.coordSystem,valueLabels:Ui(t.originalData,t.layers,n)}),o={scales:t.scales,config:t.config,layers:t.layers,coordSystem:t.coordSystem,variableLabels:n,colorGroups:r,geomCompiler:this.geomCompiler},a=gc(o),s=jc(a,Lc(o));return{axes:nc(o,s),legends:s,headline:a,panel:{border:{isVisible:t.config.panel.border.isVisible}},colorGroups:r}}}const jc=(e,t)=>e?.kind!=="perGroup"||t.some(r=>r.display==="direct")?t:[],It=e=>e[uo.key],qc=e=>V([ke(e)]),bn=(e,t)=>{const n=t!==null?e[t]??null:null;return V([n])},W=(e,t)=>{const n=ee(t);if(n!==void 0)return()=>n;const r=v(t);return h(r)?o=>{const a=o[r];if(a===void 0)return null;switch(e.getType(r)){case"numeric":return E(a)?a:null;case"categorical":return Qe(a)?a:null;case"temporal":return O(a)?a:null;default:return null}}:()=>null},vn=(e,t)=>W(e,t.x),qo=(e,t)=>W(e,t.y),Qc=(e,t)=>W(e,t.label),Qo=(e,t)=>W(e,t.color),Zc=(e,t)=>W(e,t.size),Jc=(e,t)=>W(e,t.alpha),el=(e,t)=>W(e,t.group),tl=(e,t)=>W(e,t.strokeWidth),vr={variable:g.yRaw};function tt(e,t){return Y(e)?vr:t.y??vr}function Sn(e){return W(e.data,tt(e.position,e.mapping))}const nl=["lt","lte","gt","gte","range"];function ft(e,t){if("and"in e){const n=e.and.map(r=>ft(r,t));return r=>{for(const o of n)if(!o(r))return!1;return!0}}if("or"in e){const n=e.or.map(r=>ft(r,t));return r=>{for(const o of n)if(o(r))return!0;return!1}}if("not"in e){const n=ft(e.not,t);return r=>!n(r)}return rl(e,t)}function ht(e,t){if("and"in e){for(const r of e.and)ht(r,t);return}if("or"in e){for(const r of e.or)ht(r,t);return}if("not"in e){ht(e.not,t);return}const n=ol(e);if(n!==null&&t.hasVariable(e.variable)&&t.getType(e.variable)==="categorical")throw new Error(`Highlight predicate uses ordering operator '${n}' on categorical variable '${e.variable}'. Use 'eq' or 'oneOf' instead.`)}const Sr=()=>!1;function rl(e,t){if(!t.hasVariable(e.variable))return Sr;const n=t.getType(e.variable);if("eq"in e){const r=ne(e.eq,n,t.parsingLocale);return o=>xr(t.readValue(o,e.variable),r)}if("oneOf"in e){const r=e.oneOf.map(o=>ne(o,n,t.parsingLocale));return o=>{const a=t.readValue(o,e.variable);for(const s of r)if(xr(a,s))return!0;return!1}}if("lt"in e){const r=ne(e.lt,n,t.parsingLocale);return o=>we(t.readValue(o,e.variable),r)==="less"}if("lte"in e){const r=ne(e.lte,n,t.parsingLocale);return o=>{const a=we(t.readValue(o,e.variable),r);return a==="less"||a==="equal"}}if("gt"in e){const r=ne(e.gt,n,t.parsingLocale);return o=>we(t.readValue(o,e.variable),r)==="greater"}if("gte"in e){const r=ne(e.gte,n,t.parsingLocale);return o=>{const a=we(t.readValue(o,e.variable),r);return a==="greater"||a==="equal"}}if("range"in e){const[r,o]=e.range,a=ne(r,n,t.parsingLocale),s=ne(o,n,t.parsingLocale);return i=>{const c=t.readValue(i,e.variable),l=we(c,a),u=we(c,s);return l==="incomparable"||u==="incomparable"?!1:(l==="greater"||l==="equal")&&(u==="less"||u==="equal")}}return Sr}function ol(e){for(const t of nl)if(t in e)return t;return null}function we(e,t){if(e===null||t===null)return"incomparable";if(O(e)&&O(t)){const n=e.getTime(),r=t.getTime();return n<r?"less":n>r?"greater":"equal"}return E(e)&&E(t)?e<t?"less":e>t?"greater":"equal":"incomparable"}function xr(e,t){return e===t?!0:O(e)&&O(t)?e.getTime()===t.getTime():!1}function ne(e,t,n){return t!=="temporal"||!Qe(e)?e:fn(e,void 0,n)}function Zo(e){return e===null?null:{strategy:e,composition:Jo()}}function Jo(){return{isDimmed:!1,matchedLayer:null,overlayCandidates:[]}}class al extends Ee{dependencies(t){return[t.highlights,t.config.parsingLocale]}compileLayer(t,n){const r=t.highlight;if(r===null)return t;const o=n.highlights.filter(({layerId:s})=>s===void 0||s===t.id);if(o.length===0)return t;const a=sl({layer:t,highlights:o,parsingLocale:n.config.parsingLocale,strategy:r.strategy});return{...t,highlight:{...r,composition:a}}}}function sl({layer:e,highlights:t,parsingLocale:n,strategy:r}){for(const T of t)ht(T.predicate,e.data);const o=v(e.mapping.x),a=il(e,n),s=t.map(T=>({predicate:ft(T.predicate,a),scope:T.scope})),i=s.some(({scope:T})=>T==="series"),c=s.some(({scope:T})=>T==="x-value"),l=r==="overlay-anchor",u=e.data.size(),d=i?new Array(u):null,m=c?new Array(u):null,p=l?new Array(u):null,f=new Uint8Array(u),y=new Set,b=new Set;let x=!1,S=0;for(const T of e.data){let Q,le;d!==null&&(Q=qc(T),d[S]=Q),m!==null&&(le=bn(T,o),m[S]=le),p!==null&&(p[S]=T);for(const{predicate:rt,scope:ot}of s)if(rt(T))switch(ot){case"series":Q!==void 0&&y.add(Q);break;case"x-value":le!==void 0&&b.add(le);break;case"data-point":f[S]=1,x=!0;break}S++}if(y.size===0&&b.size===0&&!x)return Jo();const w=new Uint8Array(u),k=[];let _=0;for(let T=0;T<u;T++){const Q=d?.[T],le=m?.[T],rt=Q!==void 0&&y.has(Q),ot=le!==void 0&&b.has(le),tr=f[T]===1;if(r==="observation-rerender")(rt||tr||ot)&&(w[T]=1,_++);else if(rt)w[T]=1,_++;else if(tr||ot){const nr=p?.[T];nr!==void 0&&k.push({observation:nr,observationIndex:T})}}const H=_>0?{...e,data:e.data.filterByMask(w)}:null;return{isDimmed:(r==="observation-rerender"||y.size>0)&&H!==null,matchedLayer:H,overlayCandidates:k}}function il(e,t){const n=v(e.mapping.y),r=Sn(e);return{hasVariable:o=>e.data.hasVariable(o),getType:o=>e.data.getType(o),readValue:(o,a)=>n!==null&&a===n?r(o):o[a]??null,parsingLocale:t}}const cl=["x","y","color","size","alpha","strokeWidth","lineType","label"],ea=(e,t,n,r=[])=>{const o=[];for(const a of cl){const s=dl(a,t,n);s===null||!e.hasVariable(s.valueVariable)||!e.hasVariable(s.formatVariable)||o.push({aesthetic:a,variable:s.valueVariable,valueFormat:e.getValueFormat(s.formatVariable)})}return{encodings:o,detailRows:ul(e,r)}},ll=e=>t=>({key:It(t),encodings:e.encodings.map(({aesthetic:n,variable:r,valueFormat:o})=>({aesthetic:n,value:t[r]??null,valueFormat:o}))});function ul(e,t){const n=[];for(const r of t)e.hasVariable(r.variable)&&n.push({label:r.label,variable:r.variable,valueFormat:e.getValueFormat(r.variable)});return n}function dl(e,t,n){if(e==="y"){const o=v(tt(n,t));return o===null?null:{valueVariable:o,formatVariable:v(t.y)??o}}const r=v(t[e]);return r===null?null:{valueVariable:r,formatVariable:r}}const ml=Object.values(g);function wr(e){const t=new M({});return{id:e.id,data:t,geom:e.geom,mapping:{},position:e.position,yScaleType:e.yScaleType,params:e.params,interactive:e.interactive,dataLabels:e.dataLabels,summary:{},highlight:null,semanticMap:ea(t,{},e.position),spatialMap:{kind:"noop"},swatchShape:"square",failed:!0}}function pl(e,t){let n;try{n=t()}catch{return wr(e)}return fl(n)?n:wr(e)}function fl(e){for(const t of ml)if(e.data.hasVariable(t)&&e.data.getType(t)==="numeric"){for(const n of e.data.getValues(t,{type:"numeric"}))if(n!==null&&!Number.isFinite(n))return!1}return!0}const hl=e=>e.kind==="index"?(t,n)=>String(n):t=>V(e.variables.map(n=>t[n])),yl=(e,t)=>{if(e==="index")return{kind:"index"};const n=v(t.x);return{kind:"fields",variables:n===null?[D.group]:[n,D.group]}},gl=(e,t,n)=>{const r=hl(yl(t,n));return e.deriveVariable(uo.key,"categorical",r)};class bl extends Ee{constructor(t,n,r,o,a){super(),this.transformCompiler=t,this.statCompiler=n,this.groupCompiler=r,this.geomCompiler=o,this.positionAdjusterCompiler=a}dependencies(t){return[t.data,t.mapping,Ar(t)]}compileLayer(t,n){return pl(t,()=>{const r=this.transformCompiler.compile({data:n.data,transforms:t.transforms}),o={...n.mapping,...t.mapping};return this.runLayerPipeline(t,r,o,Ar(n))})}runLayerPipeline(t,n,r,o){const a=Tt({data:n,mapping:r}).pipe(({data:c,mapping:l})=>{const u=this.statCompiler.compute(t.stat,{data:c,mapping:l,xScaleIsDiscrete:o});return{data:u.data,mapping:{...l,...u.mapping}}}).pipe(({data:c,mapping:l})=>({data:this.groupCompiler.compute({data:c,mapping:l}).data,mapping:l})).pipe(({data:c,mapping:l})=>{const u=this.geomCompiler.compile(t.geom,{data:c,mapping:l,params:t.params});return{data:u.data,mapping:{...l,...u.mapping},tooltipRows:u.tooltipRows??[]}}).pipe(({data:c,mapping:l})=>{const u=this.geomCompiler.getPositionChannels(t.geom),d=this.positionAdjusterCompiler.adjust(t.position,u,{data:c,mapping:l});return{data:d.data,mapping:{...l,...d.mapping}}}).pipe(({data:c,mapping:l})=>({data:gl(c,this.geomCompiler.getIdentityKeyStrategy(t.geom),l),mapping:l})).result(),{tooltipRows:s,...i}=a;return{...i,id:t.id,geom:t.geom,position:t.position,yScaleType:t.yScaleType,params:t.params,interactive:t.interactive,dataLabels:t.dataLabels,summary:{},highlight:Zo(this.geomCompiler.getHighlightStrategy(t.geom)),semanticMap:ea(i.data,i.mapping,t.position,s),spatialMap:{kind:this.geomCompiler.getSpatialKind(t.geom)},swatchShape:this.geomCompiler.getSwatchShape(t.geom),failed:!1}}}function Ar(e){return e.scales.some(t=>t.scaledAesthetic==="x"&&t.scaleType==="discrete")}class ta extends Error{constructor(t){const n=t.map(r=>`- ${r.message}`).join(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("date-fns"),ae=require("arquero"),ce=require("lodash-es"),$e=require("d3-time"),La=require("date-fns/differenceInDays"),ie=require("d3-scale"),Is=require("lodash-es/merge"),me=require("d3-regression"),Va=require("humanize-duration"),ka=require("d3-delaunay"),Ea=require("lodash-es/isEqual");typeof window<"u"&&(window.__GRAPHY_SDK__??={},window.__GRAPHY_SDK__.vizEngine="0.0.1-plugins.7");const Mn=e=>e.length>0;function h(e){return e!=null}function Er(e){if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function N(e,t){return Cs(e,t)}function jt(e,t){for(const n of Object.keys(t)){const r=t[n];if(r!==void 0&&r!==e[n])return{...e,...t}}return e}function Cs(e,t){let n=!1;const r={...e};for(const[s,o]of Object.entries(t)){const a=e[s];if(Er(o)&&Er(a)){const i=Cs(a,o);i!==a&&(r[s]=i,n=!0)}else o!==void 0&&o!==a&&(r[s]=o,n=!0)}return n?r:e}const ye=process.env.NODE_ENV!=="production";function Vt(e){return{pipe:t=>{const n=t(e);return Vt({...e,...n})},result:()=>e}}let kt=!0;const Ia=e=>{kt=e},Ca=()=>kt,Fa=()=>{let e=null;const t={hits:0,misses:0};return Object.assign((r,s)=>{if(!kt)return ye&&(t.misses+=1),s();if(e&&Ds(e.args,r))return ye&&(t.hits+=1),e.out;ye&&(t.misses+=1);const o=s();return e={args:r,out:o},o},{stats:t,reset:()=>{e=null}})},Fs=()=>{const e=new WeakMap,t={hits:0,misses:0};return Object.assign((r,s,o)=>{if(!kt)return ye&&(t.misses+=1),o();const a=e.get(r);if(a){for(const c of a)if(Ds(c.args,s))return ye&&(t.hits+=1),c.out}ye&&(t.misses+=1);const i=o();return a?a.push({args:s,out:i}):e.set(r,[{args:s,out:i}]),i},{stats:t})},Da=(...e)=>e.reduce((t,n)=>({hits:t.hits+n.hits,misses:t.misses+n.misses}),{hits:0,misses:0}),Ds=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0};class le{constructor(){this.memo=Fs(),this.singletonKey={}}get stats(){return this.memo.stats}compile(t){return this.memo(this.key(t),this.dependencies(t),()=>this.run(t))}key(t){return this.singletonKey}}function _a(e){return{type:"mapping",mapping:e}}function Ln(e,t){return e[t]}function v(e){return h(e)?typeof e=="string"?e:"variable"in e?e.variable:null:null}function re(e){if(!(!h(e)||typeof e=="string")&&"value"in e)return e.value}const _s="\0graphy\0_",A=e=>`${_s}${e}`,gn={x:A("constantX")},Ke={count:A("count"),mean:A("mean")},P={group:A("group")},Rs={key:A("key")},g={x:A("x"),y:A("y"),xMin:A("xMin"),xMax:A("xMax"),yMin:A("yMin"),yMax:A("yMax"),yRaw:A("yRaw")},ue={color:A("color"),size:A("size"),alpha:A("alpha"),strokeWidth:A("strokeWidth"),lineType:A("lineType")},it={y:A("ruleY"),x:A("ruleX")};({...P,...g,...ue});const Ra=new Set(Object.values(Ke)),Pa=e=>e.startsWith(_s),Na=e=>Ra.has(e),Ie=e=>e[P.group],Oa=e=>{const{coordinate:t,coordSystem:n}=e;return"observation"in t?$a(e):n.type!=="cartesian"?null:"unit"in t?{x:t.unit.x,y:t.unit.y,mode:"unit"}:Ba(t.data,e)},$a=({coordinate:e,layers:t,coordSystem:n,geomCompiler:r})=>{if(!("observation"in e))return null;const s=e.observation;for(const o of t){if(s.layerId!==void 0&&o.id!==s.layerId)continue;const a=v(o.mapping.x);if(a!==null)for(const i of o.data){if(i[a]!==s.anchorValue||Ie(i)!==s.groupValue)continue;const c=r.resolveAnchorPosition(o.geom,i,n);if(c!==null)return{x:c.x,y:1-c.y,mode:"observation",observation:i}}}return null},Ba=(e,{coordSystem:t,scales:n})=>{const r=Ir(n,"x"),s=Ir(n,"y");if(r===null||s===null)return null;const o=r.map(e.x),a=s.map(e.y);if(!Number.isFinite(o)||!Number.isFinite(a))return null;const i=t.type==="cartesian"&&t.mainAxis==="y";return{x:i?a:o,y:1-(i?o:a),mode:"data"}},Ir=(e,t)=>{const n=e[t];return n!==void 0&&n.kind==="position"?n:null},G=e=>e instanceof Date&&k.isValid(e),Ga=e=>G(e)||e===null,Ze=e=>typeof e=="string",F=e=>typeof e=="number"&&!Number.isNaN(e)&&Number.isFinite(e);function Vn(e){return e[ue.color]}function za(e){return e[ue.alpha]}function Ps(e){return e[ue.size]}function Ua(e){return e[ue.strokeWidth]}function Ns(e){return e[ue.lineType]??"solid"}const bn=(e,t,n,r)=>{for(const s of t){if(e.layerId!==void 0&&s.id!==e.layerId)continue;const o=v(s.mapping.x);if(o===null)continue;const a=v(s.mapping.y);for(const i of s.data){if(i[o]!==e.anchorValue||Ie(i)!==e.groupValue)continue;const c=r.resolveAnchorPosition(s.geom,i,n);if(c===null)continue;const l=a!==null?i[a]??null:null;if(F(l))return{...c,measurementValue:l,color:Vn(i)}}}return null};class Ya extends le{constructor(t){super(),this.geomCompiler=t}dependencies(t){return[t.annotations,t.layers,t.coordSystem,t.scales.x,t.scales.y]}run(t){const{geomCompiler:n}=this;return{differenceArrows:Ha(t,n),shapes:t.annotations.shapes,freeformArrows:t.annotations.freeformArrows,textAnnotations:t.annotations.textAnnotations,stickers:Qt(t.annotations.stickers,t.layers,t.coordSystem,n),pinnedNumbers:Qt(t.annotations.pinnedNumbers,t.layers,t.coordSystem,n),comments:Qt(t.annotations.comments,t.layers,t.coordSystem,n),custom:Wa(t,n)}}}const Wa=({annotations:e,layers:t,coordSystem:n,scales:r},s)=>{const o=[];for(const a of e.custom){const i=[];let c=!1;for(const l of a.coordinates){const u=Oa({coordinate:l,layers:t,coordSystem:n,scales:r,geomCompiler:s});if(u===null){c=!0;break}i.push(u)}c||o.push({id:a.id,type:a.type,params:a.params,zOrder:a.zOrder,targets:i})}return o},Qt=(e,t,n,r)=>{const s=[];for(const o of e){const a=bn(o.anchor,t,n,r);a!==null&&s.push({...o,anchor:a})}return s},Ha=({annotations:e,layers:t,coordSystem:n},r)=>{if(n.type!=="cartesian")return[];const s=[];for(const o of e.differenceArrows){if(Ka(o.start,o.end))continue;const a=bn(o.start,t,n,r),i=bn(o.end,t,n,r);a===null||i===null||s.push({id:o.id,start:a,end:i,color:Xa(o,a,i),size:o.size,label:o.label,labelCrossPosition:o.labelCrossPosition})}return s},Ka=(e,t)=>e.layerId===t.layerId&&e.anchorValue===t.anchorValue&&e.groupValue===t.groupValue,Xa=(e,t,n)=>e.color!==null?e.color:e.start.groupValue!==e.end.groupValue||t.color===void 0||t.color!==n.color?null:t.color;function qa(e,t){const n=Za(t);return{...e,background:ja(e.background,n),border:Qa(e.border,n)}}function ja(e,t){if(e.type==="tinted"){const n=e.color??t;if(!n)throw new Error("could not resolve color for tinted background");return{type:"tinted",color:n}}return e}function Qa(e,t){if(e.type==="tinted"||e.type==="gradient"){const n=e.color??t;if(!n)throw new Error(`could not resolve color for ${e.type} background`);return{...e,color:n}}return e}function Za(e){const t=e.color,n=t?.domain[0];if(!n)return;const r=t.map(n);if(typeof r=="string")return r}class Ja extends le{dependencies(t){return[t.scales,t.config]}run(t){const{scales:n,config:r}=t;return{...r,appearance:qa(r.appearance,n)}}}class ei extends le{dependencies(t){return[t.data,t.mapping]}run(t){let n=t.data,r=t.mapping;r.x===""&&(n=n.addConstantVariable(gn.x,"categorical",""),r={...r,x:gn.x});for(const s of Object.keys(r)){const o=re(r[s]);if(o===void 0)continue;const a=A(`const_${s}`);n=n.addConstantVariable(a,ti(o),o),r={...r,[s]:a}}return{data:n,mapping:r}}}const ti=e=>typeof e=="number"?"numeric":e instanceof Date?"temporal":"categorical";class Ce{constructor(){this.perLayerMemo=Fs(),this.listMemo=Fa()}get stats(){return Da(this.perLayerMemo.stats,this.listMemo.stats)}compile(t){const n=this.dependencies(t),r=t.layers.map(s=>this.perLayerMemo(s,n,()=>this.compileLayer(s,t)));return this.listMemo(r,()=>r)}}class ni extends le{constructor(t){super(),this.registry=t}dependencies(t){return[t.coordSpec,t.scales,t.layers]}run(t){return this.registry.get(t.coordSpec.coordType).setup(t)}}class ri extends Ce{constructor(t){super(),this.registry=t}dependencies(t){return[t.coordSpec]}compileLayer(t,n){const r=this.registry.get(n.coordSpec.coordType),[s]=r.transform({coordSpec:n.coordSpec,layers:[t]});if(!s)throw new Error(`CoordCompiler: strategy '${n.coordSpec.coordType}' did not return a transformed layer`);return s}}class si{constructor(t){this.setupStage=new ni(t),this.transformStage=new ri(t)}get setupStats(){return this.setupStage.stats}get transformStats(){return this.transformStage.stats}setup(t){return this.setupStage.compile(t)}transform(t){return this.transformStage.compile(t)}}class Fe{constructor(t){this.label=t,this.items=new Map}register(t,n){return this.items.set(t,n),this}get(t){if(!this.items.has(t)){const n=[...this.items.keys()].map(r=>`'${r}'`).join(", ");throw new Error(`Unknown ${this.label}: '${t}' (available: ${n})`)}return this.items.get(t)}getAll(){return[...this.items.values()]}has(t){return this.items.has(t)}}class oi{constructor(){this.coordType="cartesian"}setup(t){if(t.coordSpec.coordType!=="cartesian")throw new Error(`Invalid coordinate type: ${t.coordSpec.coordType}`);return{coordSystem:{type:"cartesian",mainAxis:"x",axisMapping:{x:{position:"bottom",geometry:"linear"},y:{position:"right",geometry:"linear"}}},scales:t.scales}}transform(t){return t.layers}}const ai={x:{point:g.x,lower:g.xMin,upper:g.xMax},y:{point:g.y,lower:g.yMin,upper:g.yMax}},Cr=["point","lower","upper"];function ii(e){return e.name??e.role}function U(e,t){return ai[e][t]??A(`${e}_${t}`)}function Os(e){const t=[];for(const n of e){const r=ii(n);t.includes(r)||t.push(r)}return t.sort((n,r)=>Fr(n)-Fr(r)),t.map(n=>[U("x",n),U("y",n)])}function Fr(e){const t=Cr.indexOf(e);return t===-1?Cr.length:t}class ci{constructor(t){this.geomRegistry=t,this.coordType="flip"}setup(t){if(t.coordSpec.coordType!=="flip")throw new Error(`Invalid coordinate type: ${t.coordSpec.coordType}`);return{coordSystem:{type:"cartesian",mainAxis:"y",axisMapping:{x:{position:"right",geometry:"linear"},y:{position:"bottom",geometry:"linear"}}},scales:li(t.scales,t.layers)}}transform(t){return t.layers.map(n=>{const r=this.geomRegistry.get(n.geom),s=Os(r.positionChannels);return di(n,s)})}}const Dr=A("flipSwap"),li=(e,t)=>ui(t)?e.map(n=>n.scaledAesthetic!=="x"||n.scaleType!=="continuous"&&n.scaleType!=="datetime"&&n.scaleType!=="discrete"?n:{...n,reverse:!n.reverse}):e,ui=e=>{for(const t of e){const n=v(t.mapping.x);if(!n||!t.data.hasVariable(n))continue;const r=t.data.getType(n);if(r==="categorical"||r==="temporal")return!0}return!1},di=(e,t)=>{let n=e.data;for(const[r,s]of t){const o=n.hasVariable(r),a=n.hasVariable(s);o&&a?n=n.renameVariable(r,Dr).renameVariable(s,r).renameVariable(Dr,s):o?n=n.renameVariable(r,s):a&&(n=n.renameVariable(s,r))}return{...e,data:n}};class pi{constructor(t){this.geomRegistry=t,this.coordType="polar"}setup(t){if(t.coordSpec.coordType!=="polar")throw new Error(`Invalid coordinate type: ${t.coordSpec.coordType}`);const{params:n}=t.coordSpec;return{coordSystem:{type:"polar",axisMapping:n.theta==="x"?{x:{position:"bottom",geometry:"circular"},y:{position:"left",geometry:"radial"}}:{x:{position:"left",geometry:"radial"},y:{position:"bottom",geometry:"circular"}},innerRadius:n.innerRadius,startAngle:n.startAngle*(Math.PI/180)},scales:t.scales}}transform(t){if(t.coordSpec.coordType!=="polar")throw new Error(`Invalid coordinate type: ${t.coordSpec.coordType}`);const{params:n}=t.coordSpec,r=mi(n),s=fi(n);return t.layers.map(o=>{const a=this.geomRegistry.get(o.geom),i=Os(a.positionChannels),c=n.theta==="y"?yi(o,i):o,l=hi(c,i,r,s),u=a.spatialKind==="points"?"polar-points":"arcs";return{...l,spatialMap:{kind:u}}})}}function mi(e){const t=e.startAngle*(Math.PI/180);return n=>n*2*Math.PI+t}function fi(e){const{innerRadius:t}=e;return n=>t+n*(1-t)}function hi(e,t,n,r){let s=e.data;for(const[o,a]of t)s=_r(s,o,n),s=_r(s,a,r);return{...e,data:s}}function _r(e,t,n){if(!e.hasVariable(t))return e;const s=e.getValues(t,{type:"numeric"}).map(o=>o===null?null:n(o));return e.addVariable(t,"numeric",s)}function yi(e,t){let n=e.data;for(const[r,s]of t){const o=n.hasVariable(r),a=n.hasVariable(s);if(!o&&!a)continue;const i=o?n.getValues(r):null,c=a?n.getValues(s):null;i&&(n=n.addVariable(s,"numeric",i)),c&&(n=n.addVariable(r,"numeric",c))}return{...e,data:n}}class gi extends Fe{constructor(t){super("coord"),this.register("cartesian",new oi),this.register("flip",new ci(t)),this.register("polar",new pi(t))}}const bi=new Set(["count","sum","mean","median"]);function $s(e,t){return bi.has(e)?"numeric":t}const E=e=>(Array.isArray(e)?e:[e]).map(n=>n instanceof Date?n.toISOString():String(n??"<null>")).join("\0"),vi="key",Si="value",Rr="\0__rowMaskIndex",We={numeric:{type:"decimal"},categorical:{type:"text"},temporal:{type:"datetime"}},xi={eq:(e,t)=>e[t.__variableName]===t.__value,neq:(e,t)=>e[t.__variableName]!==t.__value,gt:(e,t)=>e[t.__variableName]>t.__value,gte:(e,t)=>e[t.__variableName]>=t.__value,lt:(e,t)=>e[t.__variableName]<t.__value,lte:(e,t)=>e[t.__variableName]<=t.__value},Bs=(e,t)=>e==="count"?{type:"integer"}:t;class V{constructor(t={}){const{table:n,variableMetadata:r}=this.parseVariableMap(t);this.table=n,this.variableMetadata=r}static fromTrusted(t,n){const r=Object.create(V.prototype);return r.table=t,r.variableMetadata=n,r}size(){return this.table.numRows()}getVariableNames(){return this.table.columnNames()}hasVariable(t){return this.table.column(t)!==void 0}addVariable(t,n,r,s){const o={...this.variableMetadata,[t]:{type:n,valueFormat:this.resolveAddedVariableFormat(t,n,s)}},a=this.normalizeRawValues(n,r),i=this.table.assign(ae.table({[t]:a}));return V.fromTrusted(i,o)}addConstantVariable(t,n,r,s){const o={...this.variableMetadata,[t]:{type:n,valueFormat:this.resolveAddedVariableFormat(t,n,s)}},[a]=this.normalizeRawValues(n,[r]),i=this.table.assign(ae.table({[t]:Array(this.size()).fill(a)}));return V.fromTrusted(i,o)}deriveVariable(t,n,r,s){const o=Array.from({length:this.size()},(a,i)=>r(this.table.object(i),i));return this.addVariable(t,n,o,s)}renameVariable(t,n){const r=this.variableMetadata[t];if(!r)throw new Error(`Variable ${t} not defined`);const s=this.table.rename({[t]:n}),{[t]:o,...a}=this.variableMetadata,i={...a,[n]:r};return V.fromTrusted(s,i)}selectVariables(...t){const n=this.table.select(...t),r=Object.fromEntries(Object.entries(this.variableMetadata).filter(([s])=>t.includes(s)));return V.fromTrusted(n,r)}getType(t){const n=this.variableMetadata[t];if(!n)throw new Error(`Variable ${t} not defined`);return n.type}getValueFormat(t){const n=this.variableMetadata[t];if(!n)throw new Error(`Variable ${t} not defined`);return n.valueFormat}groupVariableNamesByType(){const t={numeric:[],categorical:[],temporal:[]};for(const[n,{type:r}]of Object.entries(this.variableMetadata))t[r].push(n);return t}getValues(t,n){if(!this.hasVariable(t))throw new Error(`Variable '${t}' not defined`);const r=this.getType(t);if(n?.type!==void 0&&r!==n.type)throw new Error(`Variable '${t}' has type '${r}', expected '${n.type}'`);let s=this.table.array(t);return n?.distinct&&(s=this.getDistinctValues(r,s)),n?.skipNulls&&(s=this.skipNulls(s)),s}filter(t,n,r){const s=xi[n],o=this.table.params({__variableName:t,__value:r}).filter(s);return V.fromTrusted(o,this.variableMetadata)}filterByMask(t){if(t.length!==this.size())throw new Error(`Row mask length ${t.length} does not match dataset size ${this.size()}`);const n=Array.from({length:t.length},(s,o)=>o),r=this.table.assign(ae.table({[Rr]:n})).params({__indexColumnName:Rr,__mask:t}).filter((s,o)=>o.__mask[s[o.__indexColumnName]]===1).select(...this.table.columnNames());return V.fromTrusted(r,this.variableMetadata)}orderBy(t,n="asc"){const r=this.table.orderby(n==="asc"?t:ae.desc(t));return V.fromTrusted(r,this.variableMetadata)}getFirst(){return this.size()===0?null:this.table.object(0)}getLast(){return this.size()===0?null:this.table.object(this.size()-1)}findLast(t){for(let n=this.size()-1;n>=0;n--){const r=this.table.object(n);if(t(r))return r}return null}groupBy(...t){const n=this.table.groupby(...t);return new wi(t,n,this.variableMetadata)}rollup(t){const n=this.table.rollup(Object.fromEntries(Object.entries(t).map(([s,o])=>[s,ae.op[o.aggregation](o.variableName)]))),r={};for(const[s,{variableName:o,aggregation:a}]of Object.entries(t)){const i=this.variableMetadata[o],c=i?.type??"numeric",l=i?.valueFormat??We[c],u=$s(a,c);r[s]={type:u,valueFormat:Bs(a,l)}}return V.fromTrusted(n,r)}reshapeFromWideToLong({keep:t,reshape:n,keyName:r=vi,valueName:s=Si}={}){const{numeric:o,categorical:a,temporal:i}=this.groupVariableNamesByType(),c=t??[...a,...i],l=n??o.filter(f=>!c.includes(f));if(c.includes(r)||c.includes(s))throw new Error(`The variables to keep includes the variables '${r}' or '${s}' to create the key and value variables`);if(l.length===0){const f={};for(const y of c){const b=this.variableMetadata[y];b&&(f[y]={type:b.type,values:[],valueFormat:b.valueFormat})}return f[r]={type:"categorical",values:[],valueFormat:{type:"text"}},f[s]={type:"numeric",values:[],valueFormat:{type:"decimal"}},new V(f)}if(l.filter(f=>this.variableMetadata[f]?.type!=="numeric").length>0)throw new Error("Only numeric variables can be reshaped");const p=this.table.select([...c,...l]).fold(l,{as:[r,s]}),m={};for(const f of c){const y=this.variableMetadata[f];y&&(m[f]=y)}return m[r]={type:"categorical",valueFormat:{type:"text"}},m[s]={type:"numeric",valueFormat:Ai(this.variableMetadata,l,r)},V.fromTrusted(p,m)}print(){console.table(this.variableMetadata),this.table.print()}[Symbol.iterator](){return this.table[Symbol.iterator]()}resolveAddedVariableFormat(t,n,r){if(r!==void 0)return r;const s=this.variableMetadata[t];return s?s.valueFormat:We[n]}parseVariableMap(t){const n={},r={};for(const[o,{type:a,values:i,valueFormat:c}]of Object.entries(t))n[o]=i,r[o]={type:a,valueFormat:c??We[a]};return{table:ae.table(n),variableMetadata:r}}normalizeRawValues(t,n){switch(t){case"numeric":return n.map(r=>typeof r!="number"||Number.isNaN(r)?null:r);case"categorical":return n.map(r=>typeof r!="string"?null:r);case"temporal":return n.map(r=>!(r instanceof Date)||!k.isValid(r)?null:r);default:{const r=t;throw new Error(`Cannot normalize raw value of unknown type: ${r}`)}}}skipNulls(t){return t.filter(n=>n!==null)}getDistinctValues(t,n){const r=t==="temporal",s=new Set,o=[];for(const a of n){const i=r&&a instanceof Date?a.getTime():a;s.has(i)||(s.add(i),o.push(a))}return o}}class wi{constructor(t,n,r){this.groupedBy=t,this.grouped=n,this.variableMetadata=r}forEach(t){const n=this.grouped.partitions(),r=this.grouped.columnNames(),s=this.groupedBy.map(a=>this.grouped.column(a)).filter(a=>a!==void 0);let o=0;for(const a of n){const i=a[0];if(i===void 0)continue;const c=this.getStableKey(s,i),l=Object.fromEntries(r.map(d=>{const p=this.grouped.column(d);return[d,a.map(m=>p?.get(m))]})),u=ae.table(l);t(V.fromTrusted(u,this.variableMetadata),c,o++)}}rollup(t){const n=this.grouped.rollup(Object.fromEntries(Object.entries(t).map(([s,o])=>[s,ae.op[o.aggregation](o.variableName)]))),r=Object.fromEntries(this.groupedBy.map(s=>{const o=this.variableMetadata[s],a=o?.type??"categorical",i=o?.valueFormat??We[a];return[s,{type:a,valueFormat:i}]}));for(const[s,{variableName:o,aggregation:a}]of Object.entries(t)){const i=this.variableMetadata[o],c=i?.type??"numeric",l=i?.valueFormat??We[c],u=$s(a,c);r[s]={type:u,valueFormat:Bs(a,l)}}return V.fromTrusted(n,r)}getStableKey(t,n){return E(t.map(r=>r.get(n)))}}function Ai(e,t,n){const r=t.map(c=>e[c]?.valueFormat??{type:"decimal"}),[s,...o]=r;if(!s)return{type:"decimal"};for(const c of r)if(c.type==="lookup")throw new Error("Cannot reshape: a source column has a lookup format and lookups cannot nest");if(o.every(c=>ce.isEqual(c,s))||s.type==="lookup")return s;const i={};for(const[c,l]of t.entries()){const u=E([l]),d=r[c];d&&d.type!=="lookup"&&(i[u]=d)}return{type:"lookup",byVariable:n,cases:i,fallback:s}}class Gs{constructor(){this.currentYear=new Date().getUTCFullYear(),this.previousDate=null,this.previousYear=null}incrementYearIfNeeded(t){this.previousYear===null?this.previousYear=t.getUTCFullYear():this.previousDate!==null&&k.isBefore(new Date(this.currentYear,t.getUTCMonth(),t.getUTCDate()),new Date(this.currentYear,this.previousDate.getUTCMonth(),this.previousDate.getUTCDate()))&&this.previousYear++;const n=new Date(t.getTime());return n.setUTCFullYear(this.previousYear),this.previousDate=n,n}}const zs=e=>{const t=Object.entries(e);return!t.length||!t.some(([,n])=>!Je(n))},Je=e=>typeof e=="string"&&e.trim()===""||e===void 0||e===null||e==="-",Et="en-GB",Ti=e=>e.type==="lookup",Mi=e=>e.type==="text",et=e=>e.type==="date"||e.type==="datetime"||e.type==="year"||e.type==="month_year"||e.type==="month"||e.type==="day_month"||e.type==="weekly_date_range"||e.type==="weekly_date_range_with_year"||e.type==="quarter"||e.type==="time",Us=e=>e.type==="decimal"||e.type==="integer"||e.type==="percentage"||e.type==="duration"||e.type==="currency",Ys=e=>e.type==="currency",Ws=e=>e.type==="month"||e.type==="day_month"||e.type==="weekly_date_range",Hs=e=>{if(Ti(e))return Hs(e.fallback);if(et(e))return"temporal";if(Us(e))return"numeric";if(Mi(e))return"categorical";const t=e;throw new Error(`No data type found for value format: ${t.type}`)},He={k:1e3,m:1e6,b:1e9,t:1e12},kn=["k","m","b","t"],Li=new RegExp(`^-?(\\d{1,3}(,\\d{3})*|\\d+)\\.?\\d*(${kn.join("|")})?$`,"i"),Vi=/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?%?$/,ve=e=>e===null||e instanceof Date||Array.isArray(e)||typeof e=="boolean"?!1:typeof e=="string"?Li.test(e)&&!Number.isNaN(Number(e.replace(new RegExp(`[,${kn.join("")}]`,"gi"),""))):!Number.isNaN(Number(e)),Ks=e=>ve(e)?!0:typeof e=="string"?Vi.test(e):!1,ki=/^\d{4}-\d{2}-\d{2}(T|\s)\d{1,2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|\+00:00)?$/,Ei=/^\s*(19\d{2}|2[01]\d{2})\s*$/,Ii=[[/\bJan\b/i,"January"],[/\bFeb\b/i,"February"],[/\bMar\b/i,"March"],[/\bApr\b/i,"April"],[/\bJun\b/i,"June"],[/\bJul\b/i,"July"],[/\bAug\b/i,"August"],[/\bSept?\b/i,"September"],[/\bOct\b/i,"October"],[/\bNov\b/i,"November"],[/\bDec\b/i,"December"]],Ci={"en-US":"MDY","en-GB":"DMY","pt-PT":"DMY",ar:"DMY"},Xs=["/","-","."," "],Pr=[["d","M","yy"],["d","MM","yy"],["d","MMMM","yy"],["dd","M","yy"],["dd","MM","yy"],["dd","MMMM","yy"],["do","MMMM","yy"],["d","M","yyyy"],["d","MM","yyyy"],["d","MMMM","yyyy"],["dd","M","yyyy"],["dd","MM","yyyy"],["dd","MMMM","yyyy"],["do","MMMM","yyyy"]],Nr=[["M","d","yy"],["M","dd","yy"],["MM","d","yy"],["MM","dd","yy"],["MMMM","d","yy"],["MMMM","dd","yy"],["MMMM","do","yy"],["M","d","yyyy"],["M","dd","yyyy"],["MM","d","yyyy"],["MM","dd","yyyy"],["MMMM","d","yyyy"],["MMMM","dd","yyyy"],["MMMM","do","yyyy"]],Or=[["yyyy","M","d"],["yyyy","M","dd"],["yyyy","MM","d"],["yyyy","MM","dd"],["yyyy","MMMM","d"],["yyyy","MMMM","dd"],["yyyy","MMMM","do"]],qs=[["d","MMMM"],["dd","MMMM"],["do","MMMM"],["MMMM","d"],["MMMM","dd"],["MMMM","do"]],Fi=[{dateFormat:"MMMM d, yyyy",type:"date"},{dateFormat:"MMMM dd, yyyy",type:"date"},{dateFormat:"MMMM do, yyyy",type:"date"},{dateFormat:"yyyy-MM",type:"month_year"}],js=1900,Qs=2199,Di=3,_i=6,Ri=5,Pi=1,Ni=28,Oi=/\s*[–—]\s*|\s-\s/,$i=e=>typeof e=="number"?Number.isNaN(e)?!1:e>=js&&e<=Qs:typeof e=="string"?Ei.test(e):!1,Zs=(e,t)=>{const n=Xe(e);return ve(n)?zi(n):typeof n=="string"?!!Js(n)||En(n)&&k.isValid(new Date(n)):k.isValid(n)},Xe=e=>{if(typeof e!="string")return e;let t=e;for(const[n,r]of Ii)t=t.replace(n,r);return t},Js=(e,t=Et)=>{const n=Xe(e);return En(n)?{type:"datetime"}:eo(t).find(r=>!et(r)||r.type==="month"&&n.length<Di?!1:r.dateFormat&&k.isValid(k.parse(n,r.dateFormat,new Date)))},En=e=>ki.test(e.trim()),Bi=(e,t=Et)=>{const[n,r]=e.split(Oi);if(!n||!r)return;const s=Xe(n).trim(),o=Xe(r).trim();return Gi(t).find(a=>{if(!et(a)||!a.dateFormat)return!1;const i=k.parse(s,a.dateFormat,new Date),c=k.parse(o,a.dateFormat,new Date);if(!k.isValid(i)||!k.isValid(c))return!1;const l=new Gs,u=l.incrementYearIfNeeded(i),d=l.incrementYearIfNeeded(c),p=k.differenceInDays(d,u);return k.isWithinInterval(new Date(u.getFullYear(),Pi,Ni),{start:u,end:d})&&p===Ri?!0:p===_i})},eo=e=>{const t={date:to(e),year:[["yyyy"]],day_month:qs,month_year:[["MMMM","yyyy"],["yyyy","MMMM"]],month:[["MMMM"]],quarter:[["QQQ","yyyy"],["yyyy","QQQ"]]};return[...Fi,...Object.entries(t).flatMap(([n,r])=>r.flatMap(s=>Xs.map(o=>({dateFormat:s.join(o),type:n}))))]},to=e=>Ci[e]==="MDY"?[...Nr,...Pr,...Or]:[...Pr,...Nr,...Or],Gi=e=>{const t={weekly_date_range:qs,weekly_date_range_with_year:to(e)};return Object.entries(t).flatMap(([n,r])=>r.flatMap(s=>Xs.map(o=>({dateFormat:s.join(o),type:n}))))},zi=e=>{const t=Number(e);if(!ce.isInteger(t))return!1;const n=new Date(t),r=new Date(t*1e3),s=o=>k.isValid(o)&&o.getFullYear()>=js&&o.getFullYear()<=Qs;return s(n)||s(r)},no={$:"usd","£":"gbp","€":"eur","¥":"jpy","₹":"inr","₱":"php",P:"php","₩":"krw","₪":"ils","₫":"vnd","₽":"rub","฿":"thb",R$:"brl",Rp:"idr",RM:"myr","₦":"ngn",zł:"pln","₺":"try",kr:"dkk",Fr:"chf",R:"zar","د.إ":"aed","﷼":"sar",Ch$:"clp",NT$:"twd",HK$:"hkd",S$:"sgd",A$:"aud",C$:"cad",NZ$:"nzd",MX$:"mxn"},ro=e=>{if(typeof e=="string"){const t=so(e);return t.length?ve(t):!1}return ve(e)},Ui=e=>{const t=oo(e),n=t?no[t]:void 0;if(!n)throw new Error("Could not get currency ISO");return n},so=e=>{const t=oo(e);let n=e;if(t){const r=e.indexOf(t);r===0?n=e.slice(t.length):r===e.length-t.length?n=e.slice(0,e.length-t.length):e[0]==="-"&&r===1&&(n=`-${e.slice(t.length+1)}`)}return ve(n)?n.split(",").join(""):""},oo=e=>Object.keys(no).sort((n,r)=>r.length-n.length).find(n=>e.includes(n)),Yi=(e,t)=>{const n=typeof e=="string"?e.trim():e;if(ve(n))return{type:"decimal"};const r=typeof n=="string"&&Js(n,t);if(r)return r;const s=typeof n=="string"&&Bi(n,t);return s||(Zs(e)?{type:"date"}:Ks(e)?{type:"percentage"}:ro(e)&&typeof e=="string"?{type:"currency",iso:Ui(e)}:{type:"text"})},Wi=/\s*[–—]\s*|\s-\s/,Hi=(e,t,n)=>{if(Je(e))return null;switch(t.type){case"decimal":case"integer":case"duration":return ao(e);case"percentage":return Ki(e);case"currency":return Xi(e);case"datetime":case"date":case"year":case"month_year":case"month":case"day_month":case"quarter":case"time":return In(e,t.dateFormat,n);case"weekly_date_range":case"weekly_date_range_with_year":return qi(e,t.dateFormat,n);case"text":return ji(e);case"lookup":throw new Error("Cannot parse: lookup value formats are produced by transforms, not raw input");default:{const r=t;throw new Error(`Unhandled value format: ${r.type}`)}}},In=(e,t,n)=>{if(e instanceof Date)return k.isValid(e)?e:null;const r=Xe(String(e).trim());if(r.length===0)return null;const s=new Date;if(t){const a=k.parse(r,t,s);return k.isValid(a)?Zt(a):null}for(const a of eo(n)){if(!et(a)||!a.dateFormat)continue;const i=k.parse(r,a.dateFormat,s);if(k.isValid(i))return Zt(i)}const o=new Date(r);return Zs(o)?En(r)?o:Zt(o):null},ao=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;let t=e.trim();if(!ve(t))return null;let n=1;for(const r of kn)if(new RegExp(`${r}$`,"i").test(t)){n=He[r],t=t.slice(0,-1);break}return Number(t.split(",").join(""))*n},Ki=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;const t=e.trim();if(!Ks(t))return null;const n=Number(t.replace(/%/g,"").replace(/,/g,""))/100;return Number.isNaN(n)?null:n},Xi=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;const t=e.trim();return ro(t)?ao(so(t)):null},qi=(e,t,n)=>{const r=String(e).trim().split(Wi),[s,o]=[r[0]?.trim(),r[1]?.trim()];return!s||!o?null:In(s,t,n)},ji=e=>String(e).trim(),Zt=e=>new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())),Qi={type:"year",dateFormat:"yyyy"};class Zi extends le{dependencies(t){return[t]}run(t){const n=t._metadata?.parsingLocale??Et,r={},s=tc(t),o=Ji(t);for(const[a,i]of t.columns.entries()){if(i._metadata?.isHidden)continue;const c=s.get(i.key);if(Je(c))continue;const l=a===o?Qi:Yi(c,n),u=Hs(l);r[i.key]=ec(i.key,t.rows,l,u,n)}return new V(r)}}const Ji=e=>{const t=nc(e.rows,5);return e.columns.findIndex(n=>{const r=t.map(s=>s[n.key]).filter(s=>!Je(s));return r.length>=2&&r.every($i)})},ec=(e,t,n,r,s)=>{const o=new Gs,a=t.reduce((i,c)=>{if(zs(c))return i;const l=Hi(c[e],n,s);return Ws(n)&&G(l)?i.push(o.incrementYearIfNeeded(l)):i.push(l),i},[]);return{type:r,values:a,valueFormat:n}},tc=e=>{const t=new Map,n=new Set(e.columns.map(r=>r.key));for(const r of e.rows){for(const s of n){const o=r[s];Je(o)||(t.set(s,o),n.delete(s))}if(n.size===0)break}return t},nc=(e,t)=>{const n=[];for(const r of e)if(zs(r)||n.push(r),n.length===t)return n;return n};class rc{constructor(t){this.registry=t}compile(t,n){return this.registry.get(t).compile(n)}getPositionChannels(t){return this.registry.get(t).positionChannels}getSwatchShape(t){return this.registry.get(t).swatchShape}getSpatialKind(t){return this.registry.get(t).spatialKind}getVisualAesthetics(t){return this.registry.get(t).visualAesthetics}getHighlightStrategy(t){return this.registry.get(t).highlightStrategy}getDirectLabelPositions(t){return this.registry.get(t).directLabelPositions}getGridPolicies(t){return this.registry.get(t).gridPolicies}getIdentityKeyStrategy(t){return this.registry.get(t).identityKeyStrategy}emitsGrandTotal(t){return this.registry.get(t).emitsGrandTotal}emitsStackTotals(t){return this.registry.get(t).emitsStackTotals}supportsPerGroupHeadline(t){return this.registry.get(t).supportsPerGroupHeadline}resolveAnchorPosition(t,n,r){return this.registry.get(t).resolveAnchorPosition(n,r)}}class De{constructor(){this.requiredAesthetics=[],this.defaultParams={},this.positionChannels=[],this.visualAesthetics=["color","size","alpha","strokeWidth","lineType"],this.swatchShape="square",this.highlightStrategy=null,this.spatialKind="noop",this.directLabelPositions=[],this.gridPolicies={},this.identityKeyStrategy="fields",this.supportedCoordTypes=["cartesian","flip","polar"],this.emitsGrandTotal=!1,this.emitsStackTotals=!1,this.supportsPerGroupHeadline=!1}resolveAnchorPosition(t,n){return null}}const It=(e,t)=>{const n=v(t.x);return!n||!["numeric","temporal"].includes(e.getType(n))?e:e.orderBy(n,"asc")};class sc extends De{constructor(){super(...arguments),this.type="area",this.requiredAesthetics=["x","y"],this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"},{axis:"y",role:"lower",valueKind:"value"},{axis:"y",role:"upper",valueKind:"value"}],this.swatchShape="area",this.highlightStrategy="overlay-anchor",this.spatialKind="buckets",this.directLabelPositions=["identity","stack","dodge","fill"],this.supportsPerGroupHeadline=!0}compile({data:t,mapping:n}){if(t=It(t,n),t.hasVariable(g.yMin)||(t=t.addConstantVariable(g.yMin,"numeric",0)),!t.hasVariable(g.yMax)){const r=v(n.y);h(r)&&t.hasVariable(r)&&(t=t.addVariable(g.yMax,"numeric",t.getValues(r,{type:"numeric"})))}return{data:t,mapping:{}}}}const io=.7,oc=.1;function _e(e){return e[g.x]}function se(e){return e[g.y]}function qe(e){return e[g.xMin]}function ke(e){return e[g.xMax]}function Se(e){return e[g.yMin]}function Z(e){return e[g.yMax]}function co(e){return e[g.yRaw]}class ac extends De{constructor(){super(...arguments),this.type="bar",this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"},{axis:"x",role:"lower",valueKind:"bandOffset"},{axis:"x",role:"upper",valueKind:"bandOffset"},{axis:"y",role:"lower",valueKind:"value"},{axis:"y",role:"upper",valueKind:"value"}],this.swatchShape="square",this.highlightStrategy="observation-rerender",this.spatialKind="rects",this.directLabelPositions=["stack","fill"],this.gridPolicies={cartesian:{hideGridX:!0},flip:{hideGridX:!0},polar:{hideGridX:!0,hideGridY:!0}},this.emitsGrandTotal=!0,this.emitsStackTotals=!0,this.supportsPerGroupHeadline=!0}compile({data:t,mapping:n}){if(t=It(t,n),t.hasVariable(g.yMin)||(t=t.addConstantVariable(g.yMin,"numeric",0)),!t.hasVariable(g.yMax)){const s=v(n.y);h(s)&&t.hasVariable(s)&&(t=t.addVariable(g.yMax,"numeric",t.getValues(s,{type:"numeric"})))}const r=io/2;return t=t.addConstantVariable(g.xMin,"numeric",-r).addConstantVariable(g.xMax,"numeric",r),{data:t,mapping:{}}}resolveAnchorPosition(t,n){if(n.type==="polar"){const a=qe(t),i=ke(t),c=Se(t),l=Z(t);if(a===null||i===null||c===null||l===null)return null;const u=(a+i)/2,d=(c+l)/2;return{x:.5+.5*d*Math.sin(u),y:.5-.5*d*Math.cos(u),geom:"polar-bar"}}if(n.mainAxis==="x"){const a=qe(t),i=ke(t),c=Z(t)??se(t);return a===null||i===null||c===null?null:{x:(a+i)/2,y:c,geom:"bar"}}const r=Se(t),s=Z(t),o=ke(t)??_e(t);return r===null||s===null||o===null?null:{x:o,y:(r+s)/2,geom:"bar"}}}class ic extends De{constructor(){super(...arguments),this.type="line",this.requiredAesthetics=["x","y"],this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"}],this.swatchShape="line",this.highlightStrategy="overlay-anchor",this.spatialKind="buckets",this.directLabelPositions=["identity","stack","dodge","fill"],this.supportsPerGroupHeadline=!0}compile(t){return{data:It(t.data,t.mapping),mapping:{}}}resolveAnchorPosition(t,n){if(n.type==="polar")return null;const r=_e(t),s=se(t);return r===null||s===null?null:{x:r,y:s,geom:"line"}}}class cc extends De{constructor(){super(...arguments),this.type="point",this.requiredAesthetics=["x","y"],this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"}],this.swatchShape="circle",this.highlightStrategy="overlay-anchor",this.spatialKind="points",this.identityKeyStrategy="index",this.supportsPerGroupHeadline=!0}compile({data:t}){return{data:t,mapping:{}}}}class lc extends De{constructor(){super(...arguments),this.type="rule",this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"}],this.highlightStrategy=null,this.supportedCoordTypes=["cartesian","flip"]}compile({data:t,mapping:n}){const r=$r(n.y,t);if(r!==null)return{data:new V({[it.y]:{type:"numeric",values:[r.value],valueFormat:r.sourceFormat}}),mapping:{y:it.y,x:void 0}};const s=$r(n.x,t);return s!==null?{data:new V({[it.x]:{type:"numeric",values:[s.value],valueFormat:s.sourceFormat}}),mapping:{x:it.x,y:void 0}}:{data:new V,mapping:{x:void 0,y:void 0}}}validateMapping({layerId:t,mapping:n,computedVariables:r}){const s=r.has("x")||F(re(n.x)),o=r.has("y")||F(re(n.y));return s&&o?[{code:"INVALID_RULE_MAPPING",message:`Layer '${t}': rule geom requires exactly one of 'x' or 'y', both were provided`,layerId:t}]:!s&&!o?[{code:"INVALID_RULE_MAPPING",message:`Layer '${t}': rule geom requires a numeric value on 'x' or 'y'`,layerId:t}]:[]}}const $r=(e,t)=>{const n=re(e);if(F(n))return{value:n,sourceFormat:void 0};const r=v(e);if(r===null||!Na(r)||!t.hasVariable(r))return null;const[s]=t.getValues(r);return F(s)?{value:s,sourceFormat:t.getValueFormat(r)}:null};class uc extends Fe{constructor(t){super("geom"),this.register("bar",new ac),this.register("point",new cc),this.register("line",new ic),this.register("area",new sc),this.register("rule",new lc);for(const n of t?.geoms??[])this.register(n.type,n)}}const Cn=(e,t)=>{if(h(t.group)){const s=v(t.group);if(s!==null)return[s]}const n=new Set([v(t.x),v(t.y)].filter(h)),r=new Set;for(const s in t){if(s==="x"||s==="y")continue;const o=v(t[s]);h(o)&&(n.has(o)||e.getType(o)==="categorical"&&r.add(o))}return[...r]};class dc{compute({data:t,mapping:n}){const r=Cn(t,n);if(r.length===0)return{data:t.addConstantVariable(P.group,"categorical",null)};const s=t.size(),o=r.map(i=>t.getValues(i)),a=new Array(s);for(let i=0;i<s;i++)a[i]=E(o.map(c=>c[i]));return{data:t.addVariable(P.group,"categorical",a)}}}const lo=new Set(["x","y","ySecondary"]),Ct=new Set(["color","size","alpha","strokeWidth","lineType"]),Ft=e=>lo.has(e),pc=e=>Ct.has(e),mc=e=>Ft(e)||pc(e);function tt(e){return e==="secondary"?"ySecondary":"y"}function J(e){return e==="ySecondary"?"y":e}const fc=e=>{if(e===void 0)return{};const t={};for(const n of e.columns)n.label!==void 0&&(t[n.key]=n.label);return t},hc=(e,t,n)=>{const r=xe(t,"color");return r===null?{}:(e?.columns??[]).some(a=>a.key===r)?{}:n};function xe(e,t){const n=J(t);for(const r of uo(t,e)){const s=v(r.mapping[n]);if(h(s))return s}return null}const Fn=(e,t)=>e===null?null:t[e]??e,yc=(e,t)=>e===null?null:t[String(e)]??null,we=({layers:e,scaleType:t,variableName:n})=>{if(n===null)return Jt(t);for(const r of e){if(!r.data.hasVariable(n))continue;const s=r.data.getValueFormat(n),o=s.type==="lookup"?s.fallback:s;return bc(o,t)?o:Jt(t)}return Jt(t)},gc=(e,t)=>t!=="y"&&t!=="ySecondary"?!1:uo(t,e).some(n=>n.position==="fill");function uo(e,t){return e==="ySecondary"?t.filter(n=>n.yScaleType==="secondary"):e==="y"?t.filter(n=>n.yScaleType==="primary"):t}const Jt=e=>{switch(e){case"continuous":return{type:"decimal"};case"datetime":return{type:"date"};case"discrete":case"palette":case"identity":return{type:"text"}}},bc=(e,t)=>{switch(t){case"continuous":return Us(e);case"datetime":return et(e);case"discrete":case"palette":case"identity":return!0}},vc=[{unit:"year",step:1e3},{unit:"year",step:100},{unit:"year",step:50},{unit:"year",step:20},{unit:"year",step:10},{unit:"year",step:5},{unit:"year",step:2},{unit:"year",step:1},{unit:"month",step:6},{unit:"month",step:3},{unit:"month",step:2},{unit:"month",step:1},{unit:"week",step:2},{unit:"week",step:1},{unit:"day",step:2},{unit:"day",step:1},{unit:"hour",step:12},{unit:"hour",step:6},{unit:"hour",step:3}],Br={year:0,quarter:1,month:2,week:3,day:4,hour:5},Ae=40,Sc=(e,t,n)=>{const r=n.unit==="quarter"?n.step*3:n.step;return Tc(n.unit).range(e,new Date(t.valueOf()+1),r)},xc=({unit:e,step:t,start:n,stop:r})=>{const s=La.differenceInDays(r,n);switch(e){case"hour":return 24*s/t>Ae;case"day":return s/t>Ae;case"week":return s/(7*t)>Ae;case"month":return s/(30*t)>Ae;case"quarter":return s/(90*t)>Ae;case"year":return s/(365*t)>Ae}},wc=(e,t)=>{const n=!Ws(t);switch(e.unit){case"year":return n?{type:"year"}:{type:"month"};case"quarter":return{type:"quarter"};case"month":return n?{type:"month_year"}:{type:"month"};case"week":return n?{type:"weekly_date_range_with_year"}:{type:"weekly_date_range"};case"day":return n?{type:"date"}:{type:"day_month"};case"hour":return n?{type:"datetime"}:{type:"time"}}},Ac=(e,t)=>{const n=Mc(t);return n===null?!1:Br[e]>Br[n]},Tc=e=>{switch(e){case"hour":return $e.utcHour;case"day":return $e.utcDay;case"week":return $e.utcMonday;case"month":case"quarter":return $e.utcMonth;case"year":return $e.utcYear}},Mc=e=>{switch(e.type){case"year":return"year";case"quarter":return"quarter";case"month_year":case"month":return"month";case"weekly_date_range":case"weekly_date_range_with_year":return"week";case"date":case"day_month":case"datetime":return"day";case"time":return"hour";default:return null}},po={left:"right",right:"left",top:"bottom",bottom:"top"},Lc={x:!0,y:!0,ySecondary:!1},Vc=20,Gr=new Set(["top","bottom"]),kc={type:"percentage"};function Ec(e,t){const{scales:n,config:r,layers:s,coordSystem:o,variableLabels:a,geomCompiler:i}=e;if(o.type==="polar"&&o.axisMapping.x.geometry!=="circular")return[];const c=Cc(s,o.type,r,i),l=new Set(t.map(p=>p.position)),u=Dc(mo(r.axes.y.position,o.axisMapping.y.position),l),d=[];for(const p of lo){const m=n[p];if(!h(m)||m.kind!=="position")continue;const f=Ic({scaleAestheticKey:p,scale:m,config:r,layers:s,axisMapping:o.axisMapping,resolvedYPosition:u,gridOverrides:c,variableLabels:a});d.push(f)}return d}function Ic(e){const{scaleAestheticKey:t,scale:n,config:r,layers:s,axisMapping:o,resolvedYPosition:a,gridOverrides:i,variableLabels:c}=e,l=J(t),{axisConfig:u,position:d}=Fc(t,r,o,a),p=xe(s,t),m=gc(s,t)?kc:we({layers:s,scaleType:n.spec.scaleType,variableName:p}),f=Fn(p,c);return{scaleAestheticKey:t,aesthetic:l,position:d,geometry:o[t==="x"?"x":"y"].geometry,label:u.label??f,isVisible:u.isVisible,tickCandidates:Rc(n,m),valueFormat:m,tickMode:u.ticks.mode,ticksVisible:u.ticks.isVisible,gridVisible:_c(u,i,t),scaleType:n.spec.scaleType,bandwidth:n.bandwidth??void 0}}function Cc(e,t,n,r){const s=e.flatMap(c=>{const l=r.getGridPolicies(c.geom)[t];return l?[l]:[]}),o=s.some(c=>c.hideGridX),a=s.some(c=>c.hideGridY),i=s.some(c=>c.hideBorder);return{x:{gridVisible:zr(o,n.axes.x.grid.isVisible)},y:{gridVisible:zr(a,n.axes.y.grid.isVisible)},borderVisible:i?!1:void 0}}function zr(e,t){if(e&&t===null)return!1}function Fc(e,t,n,r){switch(e){case"x":return{axisConfig:t.axes[e],position:mo(t.axes[e].position,n[e].position)};case"y":return{axisConfig:t.axes[e],position:r};case"ySecondary":{const s=po[r],o=ce.merge({isVisible:t.axes.y.isVisible,label:null,position:s,grid:t.axes.y.grid,ticks:t.axes.y.ticks},t.axes.ySecondary);return{axisConfig:o,position:o.position}}}}function mo(e,t){return Gr.has(e)===Gr.has(t)?e:t}function Dc(e,t){return t.has(e)?po[e]:e}function _c(e,t,n){const{gridVisible:r}=n==="x"?t.x:t.y;return r??e.grid.isVisible??Lc[n]}const Rc=(e,t)=>{if(e.spec.scaleType==="continuous"){const r=new Set,s=[];for(let o=1;o<=Vc;o++){const a=e.generateTicks({count:o}),i=E(a);r.has(i)||(r.add(i),s.push({ticks:a.map(c=>wt(e,c))}))}return s}return e.spec.scaleType==="datetime"?Pc(e,t):[{ticks:e.generateTicks().map(r=>wt(e,r))}]},Pc=(e,t)=>{const[n,r]=e.domain;if(!G(n)||!G(r))return[{ticks:e.generateTicks().map(c=>wt(e,c))}];const s=new Set,o=[],a=(i,c)=>{if(i.length===0)return;const l=E(i);s.has(l)||(s.add(l),o.push({ticks:i.map(u=>wt(e,u)),valueFormat:c}))};for(const i of vc)xc({...i,start:n,stop:r})||Ac(i.unit,t)||a(e.generateTicks({interval:i}),wc(i,t));return a(e.generateTicks({atInputs:!0})),o.sort((i,c)=>i.ticks.length-c.ticks.length),o},wt=(e,t)=>({value:t,position:e.map(t)});function je(e,t){return t.type==="polar"&&e==="square"?"slice":e}function fo({scale:e,aesthetics:t,layers:n,coordSystem:r}){const s=Nc({layers:n,coordSystem:r,aesthetics:t}),o=ho({layers:n,aesthetics:t});return e.domain.map(a=>({value:a,swatchShape:s(a),owner:o(a)}))}function Nc({layers:e,coordSystem:t,aesthetics:n}){const r=ho({layers:e,aesthetics:n}),s=e.find(a=>n.some(i=>h(a.mapping[i]))),o=s?je(s.swatchShape,t):"square";return a=>{const i=r(a);return i?je(i.layer.swatchShape,t):o}}function ho({layers:e,aesthetics:t,layerFilter:n}){const r=new Map;for(const[s,o]of e.entries()){if(n&&!n(o))continue;const a=t.find(c=>h(o.mapping[c]));if(a===void 0)continue;const i=v(o.mapping[a]);if(!(i===null||!o.data.hasVariable(i)))for(const c of o.data.getValues(i,{distinct:!0})){const l=E(c);r.has(l)||r.set(l,{layer:o,layerIndex:s})}}return s=>r.get(E(s))}const Dn=e=>{if(e.kind==="identity")return!1;const t=e.spec.scaleType;return t!=="continuous"&&t!=="datetime"};function Oc({scales:e,layers:t,coordSystem:n,valueLabels:r}){const s=e.color;if(s===void 0||!Dn(s))return[];if(!t.some(u=>h(u.mapping.color)))return[];const o=xe(t,"color");if(yo({colorVariableName:o,xVariableName:xe(t,"x"),mapsColorAcrossMultipleLayers:Bc(t)>1,isMergedWithAnotherAesthetic:$c(e,t,o)}))return[];const i=s.spec.scaleType,c=t.findIndex(u=>h(u.mapping.color));return fo({scale:s,aesthetics:["color"],layers:t,coordSystem:n}).map(({value:u,swatchShape:d,owner:p})=>{const m=p?.layerIndex??c,f=t[m],y=f?v(f.mapping.color):null;return{value:u,color:String(s.map(u)),shape:d,layerIndex:m,valueFormat:we({layers:f?[f]:t,scaleType:i,variableName:y}),label:yc(u,r)}})}const yo=({colorVariableName:e,xVariableName:t,mapsColorAcrossMultipleLayers:n,isMergedWithAnotherAesthetic:r})=>r?!1:e===null||Pa(e)?!n:t!==null&&e===t;function $c(e,t,n){if(n===null)return!1;for(const r of Ct){if(r==="color")continue;const s=e[r];if(!(s===void 0||!Dn(s))&&xe(t,r)===n)return!0}return!1}const Bc=e=>e.filter(t=>h(t.mapping.color)).length;function Gc(e,t,n,r){const s=t.findIndex(o=>r.supportsPerGroupHeadline(o.geom));if(s===-1)return[];if(e.length<2){const o=v(t[s]?.mapping.y);return[{value:null,swatch:null,layerIndex:s,groupLabelFormat:{type:"text"},label:Fn(o,n)}]}return e.map(o=>({value:o.value,swatch:{color:o.color,shape:o.shape},layerIndex:o.layerIndex,groupLabelFormat:o.valueFormat,label:o.label}))}function Ur(e,t,n){if(n===null||t===null)return[...e];const r=E(n);return e.filter((s,o)=>E(t[o]??null)===r)}const zc=(e,t)=>{switch(t){case"total":{const{sum:n,count:r}=Yr(e);return r===0?null:n}case"average":{const{sum:n,count:r}=Yr(e);return r===0?null:n/r}case"current":return e.at(-1)??null}},Uc=(e,t)=>{if(e.length<2)return null;const n=e.at(-1),r=t==="previous"?e.at(-2):e.at(0);return n===void 0||r===void 0||n.cross===null||r.cross===null||r.cross===0?null:{variation:(n.cross-r.cross)/r.cross,against:r.main}},Yr=e=>e.reduce((t,n)=>n===null?t:{sum:t.sum+n,count:t.count+1},{sum:0,count:0});function Yc(e){const{config:t,coordSystem:n}=e,r=t.headline.show;return r==="none"||r==="conversion"?null:n.type==="polar"?Wc(e,r):Hc(e,r)}function Wc(e,t){if(t!=="total")return null;const{scales:n,layers:r}=e,s=r.find(c=>c.summary.grandTotal!==void 0);if(s===void 0)return null;const o=s.summary.grandTotal;if(o===void 0)return null;const a=v(s.mapping.y);if(a===null)return null;const i=we({layers:[s],scaleType:n.y?.spec.scaleType??"continuous",variableName:a});return{kind:"grandTotal",value:o,valueFormat:i}}function Hc(e,t){const{config:n,scales:r,layers:s,variableLabels:o,colorGroups:a,geomCompiler:i}=e;if(!s.some(u=>i.supportsPerGroupHeadline(u.geom)))return null;const c=Gc(a,s,o,i);if(c.length===0)return null;const l=c.map(u=>Kc({group:u,show:t,compareWith:n.headline.compareWith,layers:s,scales:r})).filter(u=>u!==null);return l.length===0?null:{kind:"perGroup",items:l}}function Kc({group:e,show:t,compareWith:n,layers:r,scales:s}){const o=r[e.layerIndex];if(o===void 0)return null;const a=v(o.mapping.y);if(a===null||t==="total"&&o.position==="fill")return null;const i=v(o.mapping.x),c=v(o.mapping.color),l=o.yScaleType==="secondary"?s.ySecondary:s.y,u=we({layers:[o],scaleType:l?.spec.scaleType??"continuous",variableName:a}),d=jc(o.data,i),p=we({layers:[o],scaleType:d?"datetime":s.x?.spec.scaleType??"discrete",variableName:i}),m=Qc(o.data,i),f=m.getValues(a,{type:"numeric"}),y=i!==null?m.getValues(i):[],b=c!==null?m.getValues(c):null,x=Ur(f,b,e.value),S=Ur(y,b,e.value);return{value:e.value,swatch:e.swatch,aggregate:zc(x,t),valueFormat:u,groupLabelFormat:e.groupLabelFormat,mainValueFormat:p,label:e.label,observationLabel:Xc(t,d,S),comparison:qc(t,n,d,S,x)}}function Xc(e,t,n){if(e==="current"){const o=n.at(-1);return o===void 0?null:{kind:"point",value:o}}if(!t)return null;const r=n.at(0),s=n.at(-1);return r===void 0||s===void 0?null:{kind:"range",from:r,to:s}}function qc(e,t,n,r,s){if(e!=="current"||!n)return null;const o=t==="none"?"first":t,a=r.map((i,c)=>({main:i,cross:s[c]??null}));return Uc(a,o)}function jc(e,t){return t!==null&&e.hasVariable(t)&&e.getType(t)==="temporal"}function Qc(e,t){return t===null||!["numeric","temporal"].includes(e.getType(t))?e:e.orderBy(t)}const go=["point","line","area","bar","rule"],bo=new Set(go);function vo(e){return bo.has(e)}function H(e){return e==="stack"||e==="fill"}const Zc=3;function Jc({scales:e,config:t,layers:n,coordSystem:r,variableLabels:s,colorGroups:o,geomCompiler:a}){if(t.legend.position==="none")return[];const i=new Map(o.map(b=>[E(b.value),b])),c=nl({scales:e,layers:n,geomCompiler:a}),l=il(c),u=xe(n,"x"),d=l.map(b=>{if(ol(b,u,n))return null;const x=ll({group:b,variableLabels:s,layers:n,coordSystem:r,colorGroupsByValue:i});return x.items.length===0?null:{group:b,built:x}}).filter(h);if(d.length===0)return[];const p=el(d);if(t.legend.position==="auto"&&fl(p,n,r))return[];const m=hl(t.legend.position,p,n,r),f=gl(t.legend.display,m,n,r,a),y=f==="direct"?Sl(n):null;return d.map(({built:b})=>tl(b,m,f,y))}function el(e){return e.reduce((t,{group:n,built:r})=>{const s=n.some(o=>o.guideType!=="discrete");return t+(s?1:r.items.length)},0)}function tl(e,t,n,r){return n!=="direct"||r===null?{...e,position:t,display:n}:{...e,position:t,display:n,items:e.items.map(s=>({...s,normalizedY:r.get(String(s.value))??null}))}}function nl(e){const{scales:t,layers:n,geomCompiler:r}=e,s=rl(n,r),o=[];for(const a of Ct){if(!s.has(a))continue;const i=t[a];if(i===void 0||i.kind==="identity"||!sl(a,n))continue;const c=xe(n,a),l=vl(a,i);o.push({scaleAestheticKey:a,scale:i,variableName:c,guideType:l})}return o}function rl(e,t){const n=new Set;for(const r of e)for(const s of t.getVisualAesthetics(r.geom))n.add(s);return n}function sl(e,t){const n=J(e);return t.some(r=>h(r.mapping[n]))}function ol(e,t,n){const[r]=e;return r.scaleAestheticKey!=="color"?!1:yo({colorVariableName:r.variableName,xVariableName:t,mapsColorAcrossMultipleLayers:al(r.scaleAestheticKey,n),isMergedWithAnotherAesthetic:e.length>1})}function al(e,t){const n=J(e);return t.filter(r=>h(r.mapping[n])).length>1}function il(e){const t=new Map;for(const n of e){const r=bl(n),s=t.get(r);s?s.push(n):t.set(r,[n])}return[...t.values()]}function cl(e,t,n){if(t==="lineType"){e.lineType=n;return}if(t==="color"){e.color=String(n);return}e[t]=n}function ll({group:e,variableLabels:t,layers:n,coordSystem:r,colorGroupsByValue:s}){const o=e[0],a=e.map(u=>J(u.scaleAestheticKey)),i=fo({scale:o.scale,aesthetics:a,layers:n,coordSystem:r}),c=Fn(o.variableName,t),l=we({layers:n,scaleType:o.scale.spec.scaleType,variableName:o.variableName});return{aesthetics:e.map(u=>u.scaleAestheticKey),title:c,items:i.map(u=>ul(u,e,a,l,s))}}function ul(e,t,n,r,s){const o={};for(const i of t)cl(o,i.scaleAestheticKey,i.scale.map(e.value));const a=pl(e,t,n,r,s);return{value:e.value,label:dl(t,e,s),visual:o,normalizedY:null,swatchShape:e.swatchShape,valueFormat:a}}function dl(e,t,n){return e[0].scaleAestheticKey!=="color"?null:n.get(E(t.value))?.label??null}function pl(e,t,n,r,s){if(t[0].scaleAestheticKey==="color")return s.get(E(e.value))?.valueFormat??r;const o=e.owner?.layer,a=ml(o,n);return o===void 0||a===null?r:we({layers:[o],scaleType:t[0].scale.spec.scaleType,variableName:a})}function ml(e,t){if(e===void 0)return null;for(const n of t){const r=e.mapping[n];if(r===void 0)continue;const s=v(r);if(s!==null)return s}return null}function fl(e,t,n){if(e>1)return!1;const r=n.type==="polar";return ht(t,["line","area","bar"])||r}function hl(e,t,n,r){if(e!=="auto")return e;if(r.type==="polar")return"top";const s=ht(n,["line","area"]),o=ht(n,["bar"]),a=ht(n,["bar"],c=>H(c.position)),i=t>=Zc;return s&&o?"top":s?i?"right":"top":a?So(r)?"top":i?"right":"top":"top"}function yl(e,t){if(e.length!==1)return!1;const n=e[0];return n?t.getDirectLabelPositions(n.geom).includes(n.position):!1}function gl(e,t,n,r,s){if(!(t==="right"&&!So(r)))return"pill";switch(e){case"pill":return"pill";case"direct":return"direct";case"auto":return yl(n,s)?"direct":"pill"}}function So(e){return e.type==="cartesian"&&e.mainAxis==="y"}function ht(e,t,n){return e.some(r=>t.includes(r.geom)&&(n?.(r)??!0))}function bl(e){const t=e.scale.domain.map(E);return JSON.stringify([e.variableName,e.guideType,...t])}function vl(e,t){return Dn(t)?"discrete":`continuous:${e}`}function Sl(e){const t=e[0];if(!t)return new Map;const n=new Map;return t.data.groupBy(P.group).forEach(r=>{const s=r.findLast(l=>h(Z(l))||h(se(l)));if(!s)return;const o=Ie(s);if(!h(o))return;const a=Se(s),i=Z(s)??se(s);if(!h(i))return;const c=h(a)?(a+i)/2:i;n.set(String(o),c)}),n}class xl extends le{constructor(t){super(),this.geomCompiler=t}dependencies(t){return[t.scales,t.config.axes,t.config.legend,t.config.headline,t.config.panel,t.layers,t.coordSystem,t.originalData]}run(t){const n=fc(t.originalData),r=Oc({scales:t.scales,layers:t.layers,coordSystem:t.coordSystem,valueLabels:hc(t.originalData,t.layers,n)}),s={scales:t.scales,config:t.config,layers:t.layers,coordSystem:t.coordSystem,variableLabels:n,colorGroups:r,geomCompiler:this.geomCompiler},o=Yc(s),a=wl(o,Jc(s));return{axes:Ec(s,a),legends:a,headline:o,panel:{border:{isVisible:t.config.panel.border.isVisible}},colorGroups:r}}}const wl=(e,t)=>e?.kind!=="perGroup"||t.some(r=>r.display==="direct")?t:[],Dt=e=>e[Rs.key],Al=e=>E([Ie(e)]),_n=(e,t)=>{const n=t!==null?e[t]??null:null;return E([n])},K=(e,t)=>{const n=re(t);if(n!==void 0)return()=>n;const r=v(t);return h(r)?s=>{const o=s[r];if(o===void 0)return null;switch(e.getType(r)){case"numeric":return F(o)?o:null;case"categorical":return Ze(o)?o:null;case"temporal":return G(o)?o:null;default:return null}}:()=>null},Rn=(e,t)=>K(e,t.x),xo=(e,t)=>K(e,t.y),Tl=(e,t)=>K(e,t.label),wo=(e,t)=>K(e,t.color),Ml=(e,t)=>K(e,t.size),Ll=(e,t)=>K(e,t.alpha),Vl=(e,t)=>K(e,t.group),kl=(e,t)=>K(e,t.strokeWidth),Wr={variable:g.yRaw};function nt(e,t){return H(e)?Wr:t.y??Wr}function Pn(e){return K(e.data,nt(e.position,e.mapping))}const El=["lt","lte","gt","gte","range"];function yt(e,t){if("and"in e){const n=e.and.map(r=>yt(r,t));return r=>{for(const s of n)if(!s(r))return!1;return!0}}if("or"in e){const n=e.or.map(r=>yt(r,t));return r=>{for(const s of n)if(s(r))return!0;return!1}}if("not"in e){const n=yt(e.not,t);return r=>!n(r)}return Il(e,t)}function gt(e,t){if("and"in e){for(const r of e.and)gt(r,t);return}if("or"in e){for(const r of e.or)gt(r,t);return}if("not"in e){gt(e.not,t);return}const n=Cl(e);if(n!==null&&t.hasVariable(e.variable)&&t.getType(e.variable)==="categorical")throw new Error(`Highlight predicate uses ordering operator '${n}' on categorical variable '${e.variable}'. Use 'eq' or 'oneOf' instead.`)}const Hr=()=>!1;function Il(e,t){if(!t.hasVariable(e.variable))return Hr;const n=t.getType(e.variable);if("eq"in e){const r=oe(e.eq,n,t.parsingLocale);return s=>Kr(t.readValue(s,e.variable),r)}if("oneOf"in e){const r=e.oneOf.map(s=>oe(s,n,t.parsingLocale));return s=>{const o=t.readValue(s,e.variable);for(const a of r)if(Kr(o,a))return!0;return!1}}if("lt"in e){const r=oe(e.lt,n,t.parsingLocale);return s=>Te(t.readValue(s,e.variable),r)==="less"}if("lte"in e){const r=oe(e.lte,n,t.parsingLocale);return s=>{const o=Te(t.readValue(s,e.variable),r);return o==="less"||o==="equal"}}if("gt"in e){const r=oe(e.gt,n,t.parsingLocale);return s=>Te(t.readValue(s,e.variable),r)==="greater"}if("gte"in e){const r=oe(e.gte,n,t.parsingLocale);return s=>{const o=Te(t.readValue(s,e.variable),r);return o==="greater"||o==="equal"}}if("range"in e){const[r,s]=e.range,o=oe(r,n,t.parsingLocale),a=oe(s,n,t.parsingLocale);return i=>{const c=t.readValue(i,e.variable),l=Te(c,o),u=Te(c,a);return l==="incomparable"||u==="incomparable"?!1:(l==="greater"||l==="equal")&&(u==="less"||u==="equal")}}return Hr}function Cl(e){for(const t of El)if(t in e)return t;return null}function Te(e,t){if(e===null||t===null)return"incomparable";if(G(e)&&G(t)){const n=e.getTime(),r=t.getTime();return n<r?"less":n>r?"greater":"equal"}return F(e)&&F(t)?e<t?"less":e>t?"greater":"equal":"incomparable"}function Kr(e,t){return e===t?!0:G(e)&&G(t)?e.getTime()===t.getTime():!1}function oe(e,t,n){return t!=="temporal"||!Ze(e)?e:In(e,void 0,n)}function Ao(e){return e===null?null:{strategy:e,composition:To()}}function To(){return{isDimmed:!1,matchedLayer:null,overlayCandidates:[]}}class Fl extends Ce{dependencies(t){return[t.highlights,t.config.parsingLocale]}compileLayer(t,n){const r=t.highlight;if(r===null)return t;const s=n.highlights.filter(({layerId:a})=>a===void 0||a===t.id);if(s.length===0)return t;const o=Dl({layer:t,highlights:s,parsingLocale:n.config.parsingLocale,strategy:r.strategy});return{...t,highlight:{...r,composition:o}}}}function Dl({layer:e,highlights:t,parsingLocale:n,strategy:r}){for(const T of t)gt(T.predicate,e.data);const s=v(e.mapping.x),o=_l(e,n),a=t.map(T=>({predicate:yt(T.predicate,o),scope:T.scope})),i=a.some(({scope:T})=>T==="series"),c=a.some(({scope:T})=>T==="x-value"),l=r==="overlay-anchor",u=e.data.size(),d=i?new Array(u):null,p=c?new Array(u):null,m=l?new Array(u):null,f=new Uint8Array(u),y=new Set,b=new Set;let x=!1,S=0;for(const T of e.data){let ee,pe;d!==null&&(ee=Al(T),d[S]=ee),p!==null&&(pe=_n(T,s),p[S]=pe),m!==null&&(m[S]=T);for(const{predicate:ot,scope:at}of a)if(ot(T))switch(at){case"series":ee!==void 0&&y.add(ee);break;case"x-value":pe!==void 0&&b.add(pe);break;case"data-point":f[S]=1,x=!0;break}S++}if(y.size===0&&b.size===0&&!x)return To();const w=new Uint8Array(u),I=[];let _=0;for(let T=0;T<u;T++){const ee=d?.[T],pe=p?.[T],ot=ee!==void 0&&y.has(ee),at=pe!==void 0&&b.has(pe),Vr=f[T]===1;if(r==="observation-rerender")(ot||Vr||at)&&(w[T]=1,_++);else if(ot)w[T]=1,_++;else if(Vr||at){const kr=m?.[T];kr!==void 0&&I.push({observation:kr,observationIndex:T})}}const X=_>0?{...e,data:e.data.filterByMask(w)}:null;return{isDimmed:(r==="observation-rerender"||y.size>0)&&X!==null,matchedLayer:X,overlayCandidates:I}}function _l(e,t){const n=v(e.mapping.y),r=Pn(e);return{hasVariable:s=>e.data.hasVariable(s),getType:s=>e.data.getType(s),readValue:(s,o)=>n!==null&&o===n?r(s):s[o]??null,parsingLocale:t}}const Rl=["x","y","color","size","alpha","strokeWidth","lineType","label"],Mo=(e,t,n,r=[])=>{const s=[];for(const o of Rl){const a=Ol(o,t,n);a===null||!e.hasVariable(a.valueVariable)||!e.hasVariable(a.formatVariable)||s.push({aesthetic:o,variable:a.valueVariable,valueFormat:e.getValueFormat(a.formatVariable)})}return{encodings:s,detailRows:Nl(e,r)}},Pl=e=>t=>({key:Dt(t),encodings:e.encodings.map(({aesthetic:n,variable:r,valueFormat:s})=>({aesthetic:n,value:t[r]??null,valueFormat:s}))});function Nl(e,t){const n=[];for(const r of t)e.hasVariable(r.variable)&&n.push({label:r.label,variable:r.variable,valueFormat:e.getValueFormat(r.variable)});return n}function Ol(e,t,n){if(e==="y"){const s=v(nt(n,t));return s===null?null:{valueVariable:s,formatVariable:v(t.y)??s}}const r=v(t[e]);return r===null?null:{valueVariable:r,formatVariable:r}}const $l=Object.values(g);function Xr(e){const t=new V({});return{id:e.id,data:t,geom:e.geom,mapping:{},position:e.position,yScaleType:e.yScaleType,params:e.params,interactive:e.interactive,dataLabels:e.dataLabels,summary:{},highlight:null,semanticMap:Mo(t,{},e.position),spatialMap:{kind:"noop"},swatchShape:"square",failed:!0}}function Bl(e,t){let n;try{n=t()}catch{return Xr(e)}return Gl(n)?n:Xr(e)}function Gl(e){for(const t of $l)if(e.data.hasVariable(t)&&e.data.getType(t)==="numeric"){for(const n of e.data.getValues(t,{type:"numeric"}))if(n!==null&&!Number.isFinite(n))return!1}return!0}const zl=e=>e.kind==="index"?(t,n)=>String(n):t=>E(e.variables.map(n=>t[n])),Ul=(e,t)=>{if(e==="index")return{kind:"index"};const n=v(t.x);return{kind:"fields",variables:n===null?[P.group]:[n,P.group]}},Yl=(e,t,n)=>{const r=zl(Ul(t,n));return e.deriveVariable(Rs.key,"categorical",r)};class Wl extends Ce{constructor(t,n,r,s,o){super(),this.transformCompiler=t,this.statCompiler=n,this.groupCompiler=r,this.geomCompiler=s,this.positionAdjusterCompiler=o}dependencies(t){return[t.data,t.mapping,qr(t)]}compileLayer(t,n){return Bl(t,()=>{const r=this.transformCompiler.compile({data:n.data,transforms:t.transforms}),s={...n.mapping,...t.mapping};return this.runLayerPipeline(t,r,s,qr(n))})}runLayerPipeline(t,n,r,s){const o=Vt({data:n,mapping:r}).pipe(({data:c,mapping:l})=>{const u=this.statCompiler.compute(t.stat,{data:c,mapping:l,xScaleIsDiscrete:s});return{data:u.data,mapping:{...l,...u.mapping}}}).pipe(({data:c,mapping:l})=>({data:this.groupCompiler.compute({data:c,mapping:l}).data,mapping:l})).pipe(({data:c,mapping:l})=>{const u=this.geomCompiler.compile(t.geom,{data:c,mapping:l,params:t.params});return{data:u.data,mapping:{...l,...u.mapping},tooltipRows:u.tooltipRows??[]}}).pipe(({data:c,mapping:l})=>{const u=this.geomCompiler.getPositionChannels(t.geom),d=this.positionAdjusterCompiler.adjust(t.position,u,{data:c,mapping:l});return{data:d.data,mapping:{...l,...d.mapping}}}).pipe(({data:c,mapping:l})=>({data:Yl(c,this.geomCompiler.getIdentityKeyStrategy(t.geom),l),mapping:l})).result(),{tooltipRows:a,...i}=o;return{...i,id:t.id,geom:t.geom,position:t.position,yScaleType:t.yScaleType,params:t.params,interactive:t.interactive,dataLabels:t.dataLabels,summary:{},highlight:Ao(this.geomCompiler.getHighlightStrategy(t.geom)),semanticMap:Mo(i.data,i.mapping,t.position,a),spatialMap:{kind:this.geomCompiler.getSpatialKind(t.geom)},swatchShape:this.geomCompiler.getSwatchShape(t.geom),failed:!1}}}function qr(e){return e.scales.some(t=>t.scaledAesthetic==="x"&&t.scaleType==="discrete")}class Lo extends Error{constructor(t){const n=t.map(r=>`- ${r.message}`).join(`
|
|
2
2
|
`);super(`Spec validation failed:
|
|
3
3
|
${n}`),this.issues=t,this.name="SpecValidationError",console.warn(`Spec validation failed:
|
|
4
|
-
${n}`)}}class vl{constructor(t,n){this.transformCompiler=t,this.validator=n}check(t){const n=[];for(const r of t.layers){const o=this.transformCompiler.compile({data:t.data,transforms:r.transforms}),a={...t.mapping,...r.mapping};n.push(...this.validator.validate({layerId:r.id,geom:r.geom,stat:r.stat,effectiveMapping:a,data:o,coordType:t.coords.coordType}))}if(n.length>0)throw new ta(n)}}class Sl{constructor(t,n){this.geomRegistry=t,this.statRegistry=n}validate(t){return[...this.validateRequiredAesthetics(t),...this.validateVariableExistence(t),...this.validateGeomMapping(t),...this.validateCoordSupport(t)]}validateRequiredAesthetics({layerId:t,geom:n,stat:r,effectiveMapping:o}){const a=[],{requiredAesthetics:s}=this.geomRegistry.get(n),{computedVariables:i}=this.statRegistry.get(r.type);for(const c of s)i.has(c)||h(un(o,c))||a.push({code:"MISSING_AESTHETIC",message:`Layer '${t}': geom '${n}' requires aesthetic '${c}'`,layerId:t,aesthetic:c});return a}validateVariableExistence({layerId:t,stat:n,effectiveMapping:r,data:o}){const a=[],{computedVariables:s}=this.statRegistry.get(n.type);for(const[i,c]of Object.entries(r)){if(s.has(i))continue;const l=v(c);l!==null&&(o.hasVariable(l)||a.push({code:"UNKNOWN_VARIABLE",message:`Layer '${t}': aesthetic '${i}' references variable '${l}' which does not exist in the dataset`,layerId:t,aesthetic:i}))}return a}validateGeomMapping({layerId:t,geom:n,stat:r,effectiveMapping:o}){const a=this.geomRegistry.get(n);if(a.validateMapping===void 0)return[];const{computedVariables:s}=this.statRegistry.get(r.type);return a.validateMapping({layerId:t,mapping:o,computedVariables:s})}validateCoordSupport({layerId:t,geom:n,coordType:r}){const{supportedCoordTypes:o}=this.geomRegistry.get(n);return o.includes(r)?[]:[{code:"UNSUPPORTED_COORD",message:`Layer '${t}': geom '${n}' is not supported under '${r}' coords`,layerId:t}]}}const Tr=A("__ungrouped__"),xl=(e,t)=>t===null?!0:e.some(n=>n.axis===t.axis&&n.role===t.role&&n.valueKind===t.valueKind),na=(e,t,n="y")=>{const r=n==="y"?"x":"y",o=v(t[n]),a=v(t[r]);if(!o||!a)return null;const s=e.getValues(D.group,{type:"categorical",distinct:!0,skipNulls:!0}),i=s.length===0,c=i?[Tr]:s,l=e.getValues(a),u=e.getValues(o,{type:"numeric"}),d=e.getValues(D.group,{type:"categorical"}),m=e.size(),p=new Map;for(let f=0;f<m;f++){const y=l[f]??null,b=d[f],x=i?Tr:b;if(!h(x))continue;let S=p.get(y);S||(S=new Map,p.set(y,S)),S.set(x,f)}return{values:u,observationIndexByPartitionAndGroup:p,uniqueGroupKeys:c,observationCount:m}};class wl{constructor(t){this.registry=t}adjust(t,n,r){const o=this.registry.get(t),a=o.getConsumedChannel(r.axis??"y");return xl(n,a)?o.adjust(r):{data:r.data,mapping:{}}}}class Ct{getConsumedChannel(t){return null}}class Al extends Ct{constructor(){super(...arguments),this.type="dodge"}getConsumedChannel(t){return{axis:"x",role:"point",valueKind:"value"}}adjust({data:t,mapping:n}){if(!v(n.x))return{data:t,mapping:{}};const o=t.getValues(D.group,{type:"categorical",distinct:!0,skipNulls:!0});if(o.length===0)return{data:t,mapping:{}};const a=t.size(),s=t.getValues(D.group,{type:"categorical"}),i=Po/2,c=o.length>1?_i:0,l=oe.scaleBand().domain(o.map(String)).range([-i,i]).paddingInner(c).paddingOuter(0),u=l.bandwidth(),d=new Array(a).fill(null),m=new Array(a).fill(null);for(let f=0;f<a;f++){const y=s[f];if(!h(y))continue;const b=l(String(y));h(b)&&(d[f]=b,m[f]=b+u)}return{data:t.addVariable(g.xMin,"numeric",d).addVariable(g.xMax,"numeric",m),mapping:{}}}}class Tl extends Ct{constructor(){super(...arguments),this.type="fill"}getConsumedChannel(t){return{axis:t,role:"point",valueKind:"value"}}adjust({data:t,mapping:n,axis:r="y"}){const o=na(t,n,r);if(o===null)return{data:t,mapping:{}};const{values:a,observationIndexByPartitionAndGroup:s,uniqueGroupKeys:i,observationCount:c}=o,l=[...a],u=new Array(c).fill(0);for(const[,m]of s){let p=0,f=0;for(const x of i){const S=m.get(x);if(S===void 0)continue;const w=a[S];w!=null&&(w>=0?p+=w:f-=w)}let y=0,b=0;for(const x of i){const S=m.get(x);if(S===void 0)continue;const w=a[S];if(w===void 0)continue;if(w===null){u[S]=null,l[S]=null;continue}const k=w>=0?p:f;if(k===0){u[S]=0,l[S]=0;continue}const _=w/k;w>=0?(u[S]=y,l[S]=y+=_):(l[S]=b,u[S]=b+=_)}}let d=t.addVariable($(r,"lower"),"numeric",u).addVariable($(r,"upper"),"numeric",l);return r==="y"&&(d=d.addVariable(g.yRaw,"numeric",a)),{data:d,mapping:{}}}}class Ml extends Ct{constructor(){super(...arguments),this.type="identity"}adjust({data:t}){return{data:t,mapping:{}}}}class Ll extends Ct{constructor(){super(...arguments),this.type="stack"}getConsumedChannel(t){return{axis:t,role:"point",valueKind:"value"}}adjust({data:t,mapping:n,axis:r="y"}){const o=na(t,n,r);if(o===null)return{data:t,mapping:{}};const{values:a,observationIndexByPartitionAndGroup:s,uniqueGroupKeys:i,observationCount:c}=o,l=[...a],u=new Array(c).fill(0);for(const[,p]of s){let f=0,y=0;for(const b of i){const x=p.get(b);if(x===void 0)continue;const S=a[x];if(S!==void 0){if(S===null){u[x]=null,l[x]=null;continue}S>=0?(u[x]=f,l[x]=f+=S):(l[x]=y,u[x]=y+=S)}}}let d=t.addVariable($(r,"lower"),"numeric",u).addVariable($(r,"upper"),"numeric",l);r==="y"&&(d=d.addVariable(g.yRaw,"numeric",a));const m=v(n[r]);return m!==null&&(d=d.addVariable(m,"numeric",l)),{data:d,mapping:{}}}}class Vl extends Ie{constructor(){super("position"),this.register("identity",new Ml),this.register("stack",new Ll),this.register("fill",new Tl),this.register("dodge",new Al)}}function kl(e){let t=e.data;for(const n of e.channels)n.role==="point"&&(t=El(n.axis,t,e));for(const n of Cl(e.channels))t=_l(n,t,e);for(const n of e.channels)n.role==="scalar"&&(t=Il(n,t,e));return t}function xn(e,t){return e==="x"?"x":et(t)}function El(e,t,n){const r=v(n.mapping[e]),o=n.getPositionScale(xn(e,n.yScaleType));if(!r||!o)return t;const s=t.getValues(r).map(i=>h(i)?o.map(i):null);return t.addVariable($(e,"point"),"numeric",s)}function Il(e,t,n){const r=n.getPositionScale(xn(e.axis,n.yScaleType)),a=(e.aes?v(un(n.mapping,e.aes)):null)??$(e.axis,e.name);if(!r||!t.hasVariable(a))return t;const i=t.getValues(a,{type:"numeric"}).map(c=>h(c)?r.map(c):null);return t.addVariable($(e.axis,e.name),"numeric",i)}function Cl(e){const t=new Map;for(const n of e){if(n.role==="point"||n.role==="scalar")continue;const r=`${n.axis}:${n.valueKind}`,o=t.get(r)??{axis:n.axis,valueKind:n.valueKind,hasLower:!1,hasUpper:!1};n.role==="lower"&&(o.hasLower=!0),n.role==="upper"&&(o.hasUpper=!0),t.set(r,o)}return[...t.values()].filter(n=>n.hasLower&&n.hasUpper).map(({axis:n,valueKind:r})=>({axis:n,valueKind:r}))}function _l(e,t,n){const r=n.getPositionScale(xn(e.axis,n.yScaleType));if(!r)return t;const o=$(e.axis,"lower"),a=$(e.axis,"upper");return!t.hasVariable(o)||!t.hasVariable(a)?t:e.valueKind==="value"?Fl(t,r,o,a):Dl(e.axis,t,r,o,a)}function Fl(e,t,n,r){const o=e.getValues(n,{type:"numeric"}),a=e.getValues(r,{type:"numeric"}),s=e.size(),i=new Array(s),c=new Array(s);for(let l=0;l<s;l++){const u=o[l],d=a[l];h(u)&&h(d)?(i[l]=t.map(u),c[l]=t.map(d)):(i[l]=null,c[l]=null)}return e.addVariable(n,"numeric",i).addVariable(r,"numeric",c)}function Dl(e,t,n,r,o){const a=$(e,"point");if(!n.bandwidth||!t.hasVariable(a))return t;const s=n.bandwidth,i=t.getValues(a,{type:"numeric"}),c=t.getValues(r,{type:"numeric"}),l=t.getValues(o,{type:"numeric"}),u=t.size(),d=new Array(u),m=new Array(u);for(let p=0;p<u;p++){const f=i[p],y=c[p],b=l[p];h(f)&&h(y)&&h(b)?(d[p]=f+y*s,m[p]=f+b*s):(d[p]=null,m[p]=null)}return t.addVariable(r,"numeric",d).addVariable(o,"numeric",m)}function Rl(e,t){const n=e[t];return n?.kind==="position"?n:null}class Nl extends Ee{constructor(t){super(),this.geomRegistry=t}dependencies(t){return[t.scales.x,t.scales.y,t.scales.ySecondary]}compileLayer(t,n){const r=this.geomRegistry.get(t.geom),o=kl({channels:r.positionChannels,data:t.data,mapping:t.mapping,yScaleType:t.yScaleType,getPositionScale:a=>Rl(n.scales,a)});return{...t,data:o}}}class Pl extends se{constructor(t){super(),this.registry=t}dependencies(t){return[t.layers,t.scales]}run(t){this.validateScaleTypeCompatibility(t);const n=new Map;for(const a of t.scales)n.set(a.scaledAesthetic,a);const r=this.collectValues(t.layers,n),o={};for(const[a,s]of n){const i=r.get(a)??[],c=this.registry.get(s.scaleType);o[a]=c.compile(s,i)}return o}validateScaleTypeCompatibility(t){const n=[];for(const r of t.scales){const{compatibleDataTypes:o}=this.registry.get(r.scaleType),a=q(r.scaledAesthetic),s=t.layers.find(l=>h(l.mapping[a]));if(!s)continue;const i=v(s.mapping[a]);if(!h(i)||!s.data.hasVariable(i))continue;const c=s.data.getType(i);if(o.includes(c)||n.push({code:"INCOMPATIBLE_TYPE",message:`Scale '${r.scaledAesthetic}' (${r.scaleType}) is incompatible with variable '${i}' (${c})`,aesthetic:a}),r.scaledAesthetic==="lineType"&&c!=="categorical"){const l=c==="temporal"?"Bucket the variable into categorical periods (e.g. quarter, year) first.":"Bin the variable into categorical buckets first.";n.push({code:"INCOMPATIBLE_TYPE",message:`Scale 'lineType' is discrete-only and cannot be mapped to ${c} variable '${i}'. ${l}`,aesthetic:a})}}if(n.length>0)throw new ta(n)}collectValues(t,n){const r=new Map;for(const o of t)for(const[a,s]of Object.entries(o.mapping)){const i=a,c=i==="y"?et(o.yScaleType):i;if(!$i(c)||!n.has(c))continue;const l=this.resolveVariables(i,s,o.data);this.collectFromVariables(o.data,l,c,r)}return r}resolveVariables(t,n,r){if(t==="y"&&this.hasPositionAdjustedY(r))return[g.yMin,g.yMax];const o=v(n);return!o||!r.hasVariable(o)?[]:[o]}hasPositionAdjustedY(t){return t.hasVariable(g.yMin)&&t.hasVariable(g.yMax)}collectFromVariables(t,n,r,o){if(n.length===0)return;let a=[];for(const i of n)a=a.concat(t.getValues(i));const s=o.get(r);o.set(r,s?s.concat(a):a)}}class nt{createPositionScale(t,n){return{kind:"position",aesthetic:q(t.scaledAesthetic),spec:t,...n}}createVisualScale(t,n){return{kind:"visual",aesthetic:q(t.scaledAesthetic),spec:t,...n}}}class Ol extends nt{constructor(){super(...arguments),this.compatibleDataTypes=["numeric"]}compile(t,n){if(t.scaleType!=="continuous")throw new Error("ContinuousScale.compile received non-continuous spec");const r=Et(t.scaledAesthetic),o=this.computeDataDomain(n,t);return r?this.buildPositionScale(o,t):this.buildVisualScale(o,t)}computeDataDomain(t,n){let r=1/0,o=-1/0;for(const a of t)typeof a=="number"&&(a<r&&(r=a),a>o&&(o=a));return r===1/0?[0,0]:(n.zero&&(r>0&&(r=0),o<0&&(o=0)),[r,o])}createD3Scale(t,n,r){let o=[r.domainMin??t[0],r.domainMax??t[1]];const a=r.transform==="log"&&Bl(o),s=a?oe.scaleLog():r.transform==="sqrt"?oe.scaleSqrt():oe.scaleLinear();return r.nice&&!a&&(o=s.copy().domain(o).nice().domain()),s.domain([r.domainMin??o[0],r.domainMax??o[1]]).range(n).clamp(r.clamp)}buildPositionScale(t,n){const r=n.reverse?[1,0]:[0,1],o=this.createD3Scale(t,r,n);return this.createPositionScale(n,{map:o,domain:o.domain(),bandwidth:null,generateTicks:a=>a&&"count"in a?o.ticks(a.count):o.ticks()})}buildVisualScale(t,n){const r=n.range??[0,1],o=n.reverse?[r[1],r[0]]:r,a=this.createD3Scale(t,o,n);return this.createVisualScale(n,{map:a,domain:a.domain(),generateTicks:s=>s&&"count"in s?a.ticks(s.count):a.ticks()})}}const Bl=e=>{const[t,n]=e;return t>0&&n>0||t<0&&n<0};class $l extends nt{constructor(){super(...arguments),this.compatibleDataTypes=["temporal"]}compile(t,n){if(t.scaleType!=="datetime")throw new Error("DatetimeScale.compile received non-datetime spec");const r=Et(t.scaledAesthetic),o=this.computeDataDomain(n);if(!r)throw new Error("Datetime scale is not supported for non-position aesthetics");return this.buildScale(o,t,this.collectInputDates(n))}collectInputDates(t){const n=new Set,r=[];for(const o of t){if(!(o instanceof Date))continue;const a=o.getTime();n.has(a)||(n.add(a),r.push(o))}return r.sort((o,a)=>o.getTime()-a.getTime()),r}computeDataDomain(t){let n=1/0,r=-1/0;for(const o of t){if(!(o instanceof Date))continue;const a=o.getTime();a<n&&(n=a),a>r&&(r=a)}return n===1/0?[]:[new Date(n),new Date(r)]}createD3Scale(t,n,r){const o=Gl(t)?t:[],a=oe.scaleUtc().domain(o).range(n).clamp(r.clamp);if(r.nice&&a.nice(),h(r.domainMin)||h(r.domainMax)){const[s,i]=a.domain();s!==void 0&&i!==void 0&&a.domain([r.domainMin??s,r.domainMax??i])}return a}buildScale(t,n,r){const o=n.reverse?[1,0]:[0,1],a=this.createD3Scale(t,o,n),[s,i]=a.domain(),c=s&&i?r.filter(l=>l>=s&&l<=i):[];return this.createPositionScale(n,{map:a,domain:a.domain(),bandwidth:null,generateTicks:l=>l&&"atInputs"in l?c:l&&"interval"in l?s&&i?zi(s,i,l.interval):[]:a.ticks(l?.count)})}}const Gl=e=>e.length===2&&O(e[0])&&O(e[1]),Ae={transform:"linear",reverse:!1,nice:!0,zero:!1,domainMin:null,domainMax:null},Mr={size:[4,20],alpha:[.1,1],strokeWidth:[1,4]},st={domainMin:null,domainMax:null,nice:!1,reverse:!1},Ge={range:null,domain:null,padding:.1,reverse:!1},Ul={palette:{type:"default"}};class Yl extends nt{constructor(){super(...arguments),this.compatibleDataTypes=["categorical","numeric","temporal"]}compile(t,n){if(t.scaleType!=="discrete")throw new Error("DiscreteScale.compile received non-discrete spec");const r=Et(t.scaledAesthetic),o=this.computeDataDomain(n,t);return r?this.buildPositionScale(o,t):this.buildVisualScale(o,t)}computeDataDomain(t,n){if(n.domain!==null&&n.domain.length>0)return[...n.domain];const r=new Set,o=[];for(const a of t)r.has(a)||(r.add(a),o.push(a));return o}buildPositionScale(t,n){const r=t.map(String),o=n.padding??Ge.padding,a=n.reverse?[1,0]:[0,1],s=oe.scaleBand().domain(r).range(a).paddingInner(o).paddingOuter(o/2),i=s.bandwidth()/2;return this.createPositionScale(n,{map:c=>(s(String(c))??0)+i,domain:t,bandwidth:s.bandwidth(),generateTicks:()=>[...t]})}buildVisualScale(t,n){const r=t.map(String),o=n.range&&n.range.length>0?oe.scaleOrdinal().domain(r).range(n.range).unknown(n.range[0]):null;return this.createVisualScale(n,{map:a=>{const s=String(a);return o?o(s):s},domain:t,generateTicks:()=>t})}}class Wl extends nt{constructor(){super(...arguments),this.compatibleDataTypes=["numeric","categorical","temporal"]}compile(t){if(t.scaleType!=="identity")throw new Error("IdentityScale.compile received non-identity spec");return{kind:"identity",aesthetic:q(t.scaledAesthetic),spec:t,map:n=>n,domain:[],generateTicks:()=>[]}}}const ra=["grey","red","orange","yellow","green","cyan","blue","purple","pink"],oa=["cyan","pink","purple","red","orange","yellow","green","blue"],wn=["#B399FE","#FC7E91","#33B6E0","#FFC849","#25CDA5","#FA9B65","#D93C95","#845FD8","#3F8EEB","#58C8D8","#F35074","#6EA0DA"],K={red:"#E83562",orange:"#F38650",yellow:"#FBBC30",green:"#31FCB4",cyan:"#40F8FF",blue:"#279EFF",purple:"#B399FD",dark_purple:"#6D48D2",plum:"#C82184",pink:"#FC8497"},Hl=[K.purple,K.pink,K.yellow,K.blue,K.red,K.cyan,K.orange,K.plum,K.green,K.dark_purple],U={green:"#B2DDC9",cyan:"#A2D5E2",blue:"#AAC4FF",purple:"#B2A4FF",plum:"#DCA8C7",pink:"#FFCCD3",red:"#FFADAD",orange:"#FFDEB4",yellow:"#FDF7C3"},Kl=[U.green,U.purple,U.red,U.cyan,U.pink,U.blue,U.orange,U.plum,U.yellow],rn={grey900:"#1c1917",grey800:"#292524",grey700:"#44403c",grey600:"#57534e",grey500:"#78716c",grey400:"#a8a29e",grey300:"#d6d3d1",grey200:"#e7e5e4",grey100:"#f5f5f4",grey50:"#fafaf9",red900:"#7f1d1d",red800:"#991b1b",red700:"#b91c1c",red600:"#dc2626",red500:"#ef4444",red400:"#f87171",red300:"#fca5a5",red200:"#fecaca",red100:"#fee2e2",red50:"#fef2f2",orange900:"#7c2d12",orange800:"#9a3412",orange700:"#c2410c",orange600:"#ea580c",orange500:"#f97316",orange400:"#fb923c",orange300:"#fdba74",orange200:"#fed7aa",orange100:"#ffedd5",orange50:"#fff7ed",yellow900:"#553B0C",yellow800:"#6F4B08",yellow700:"#8D6300",yellow600:"#BD8A00",yellow500:"#E5B400",yellow400:"#FFC800",yellow300:"#FBDA2B",yellow200:"#FEED72",yellow100:"#FEF8B4",yellow50:"#FEFCE2",green900:"#064e3b",green800:"#065f46",green700:"#047857",green600:"#059669",green500:"#10b981",green400:"#34d399",green300:"#6ee7b7",green200:"#a7f3d0",green100:"#d1fae5",green50:"#ecfdf5",cyan900:"#164e63",cyan800:"#155e75",cyan700:"#0e7490",cyan600:"#0891B2",cyan500:"#06b6d4",cyan400:"#22d3ee",cyan300:"#67e8f9",cyan200:"#a5f3fc",cyan100:"#cffafe",cyan50:"#ecfeff",blue900:"#1e3a8a",blue800:"#1e40af",blue700:"#1d4ed8",blue600:"#2563eb",blue500:"#3b82f6",blue400:"#60a5fa",blue300:"#93c5fd",blue200:"#bfdbfe",blue100:"#dbeafe",blue50:"#eff6ff",purple900:"#4c1d95",purple800:"#5b21b6",purple700:"#6d28d9",purple600:"#7c3aed",purple500:"#8b5cf6",purple400:"#a78bfa",purple300:"#c4b5fd",purple200:"#ddd6fe",purple100:"#ede9fe",purple50:"#f5f3ff",pink900:"#751A5E",pink800:"#8F1972",pink700:"#AF1C8A",pink600:"#D326A8",pink500:"#E845BF",pink400:"#F979D9",pink300:"#FCABE8",pink200:"#FED0F3",pink100:"#FFE8F9",pink50:"#FFF4FC"},zl=[rn.grey200,U.green,U.red,rn.grey200],Lr={dark:{1:[500],2:[600,400],3:[600,400,200],4:[600,500,300,100],5:[700,600,400,200,50],6:[600,500,400,300,200,100],7:[600,500,400,300,200,100,50],default:[700,600,500,400,300,200,100,50]},light:{1:[600],2:[700,500],3:[800,600,400],4:[800,600,400,300],5:[800,700,600,500,400],6:[800,700,600,500,400,300],7:[900,800,700,600,500,400,300],default:[900,800,700,600,500,400,300,200]}},B={cyan:"#22D3EE",pink:"#F377EF",purple:"#6528F7",red:"#FB2576",orange:"#FF9300",yellow:"#FBFF00",green:"#06FF00",blue:"#0079FF"},it=[B.cyan,B.pink,B.purple,B.red,B.orange,B.yellow,B.green,B.blue],Xl=[B.cyan,B.green,B.red,B.cyan],ct={start:"#84D1FC",positive:"#84FC89",negative:"#FC8497",total:"#84D1FC"},jl=[ct.start,ct.positive,ct.negative,ct.total];function ql(e,t="light",n){return((n!==void 0?Lr[t][n]:void 0)??Lr[t].default).map(o=>rn[`${e}${o}`])}function Ql(e){const t=it.indexOf(B[e]);return t<=0?it:[...it.slice(t),...it.slice(0,t)]}function Zl(e,t){switch(e.type){case"default":return wn;case"graphy":return e.variant==="waterfall"?jl:Hl;case"pastel":return e.variant==="waterfall"?zl:Kl;case"neon":return e.variant==="waterfall"?Xl:Ql(e.base);case"mono":return ql(e.base,e.variant??"light",t);case"custom":return e.colors}}function Jl(e,t){if(!e)return Ul.palette;if(e.type==="custom"){const n=t[e.id];if(!n)throw new Error(`Custom palette with id "${e.id}" not found`);return{type:"custom",id:e.id,colors:n}}return e}class eu extends nt{constructor(){super(...arguments),this.compatibleDataTypes=["categorical","temporal"]}compile(t,n){if(t.scaleType!=="palette")throw new Error("PaletteScale.compile received non-palette spec");const r=this.computeDomain(n),o=Zl(t.palette,r.length),a=o.length>0?o:[...wn],s=oe.scaleOrdinal().domain(r.map(String)).range(a).unknown(a[0]);return this.createVisualScale(t,{map:i=>s(String(i)),domain:r,generateTicks:()=>r})}computeDomain(t){const n=new Set,r=[];for(const o of t)n.has(o)||(n.add(o),r.push(o));return r}}class tu extends Ie{constructor(){super("scale"),this.register("continuous",new Ol),this.register("discrete",new Yl),this.register("datetime",new $l),this.register("identity",new Wl),this.register("palette",new eu)}}const aa=e=>!("layers"in e),I={point:nu,line:ru,area:ou,bar:au,rule:su};function nu(e={}){return{type:"layer",geom:"point",mapping:e.aes,stat:e.stat,params:e.params,position:e.position,yScaleType:e.yScaleType,transforms:e.transforms,interactive:e.interactive,dataLabels:e.dataLabels}}function ru(e={}){return{type:"layer",geom:"line",mapping:e.aes,stat:e.stat,params:e.params,position:e.position,yScaleType:e.yScaleType,transforms:e.transforms,interactive:e.interactive,dataLabels:e.dataLabels}}function ou(e={}){return{type:"layer",geom:"area",mapping:e.aes,stat:e.stat,params:e.params,position:e.position,yScaleType:e.yScaleType,transforms:e.transforms,interactive:e.interactive,dataLabels:e.dataLabels}}function au(e={}){return{type:"layer",geom:"bar",mapping:e.aes,stat:e.stat,params:e.params,position:e.position,yScaleType:e.yScaleType,transforms:e.transforms,interactive:e.interactive,dataLabels:e.dataLabels}}function su(e={}){return{type:"layer",geom:"rule",mapping:e.aes,stat:e.stat,params:e.params,position:e.position,yScaleType:e.yScaleType,transforms:e.transforms,interactive:e.interactive,dataLabels:e.dataLabels}}const An={identity:cu,count:lu,smooth:iu,mean:uu};function iu(e){return{type:"smooth",method:e.method,order:e.order,bandwidth:e.bandwidth}}function cu(){return{type:"identity"}}function lu(){return{type:"count"}}function uu(){return{type:"mean"}}const fe={reshape:du,filter:mu,sort:pu,aggregate:fu,constant:hu};function du(e={}){return{type:"transform",transformType:"reshape",options:e}}function mu(e){return{type:"transform",transformType:"filter",options:e}}function pu(e){return{type:"transform",transformType:"sort",options:e}}function fu(e){return{type:"transform",transformType:"aggregate",options:e}}function hu(e){return{type:"transform",transformType:"constant",options:e}}const Vr="#%_ENCODED_%#",sa=e=>{if(!e.startsWith(Vr))return e;try{const{value:t}=JSON.parse(e.slice(Vr.length));return typeof t=="string"?t:e}catch{return e}},yu=({annotations:e,dataset:t,mapping:n})=>{const r=[],o=[],a=[],s=[],i=[],c=[],l=[],u=v(n.x);for(const d of e??[])switch(d.type){case"difference-arrow":{const m=gu(d,u,t);m!==null&&r.push(m);break}case"shape":{o.push(bu(d));break}case"arrow":{a.push(wu(d));break}case"highlight":break;case"text":{s.push(vu(d));break}case"sticker":{const m=Su(d,u,t);m!==null&&i.push(m);break}case"tooltip":{const m=xu(d,u,t);if(m===null)break;m.kind==="pinnedNumber"?c.push(m.value):l.push(m.value);break}default:{const m=d;throw new Error(`Unsupported annotation type: ${m.type}`)}}return{differenceArrows:r,shapes:o,freeformArrows:a,textAnnotations:s,stickers:i,pinnedNumbers:c,comments:l}},gu=(e,t,n)=>{const r=xt({dataset:n,input:e.start,anchorVariable:t}),o=xt({dataset:n,input:e.end,anchorVariable:t});return r===null||o===null?null:{id:e.id,start:r,end:o,label:e.show,color:e.color??null,size:e.size,labelCrossPosition:e.labelPosition}},bu=e=>({id:e.id,kind:e.shape,zOrder:e.layer==="abovePlot"?"foreground":"background",x:e.x,y:e.y,width:e.width,height:e.height,fillColor:e.fillColor,fillOpacity:e.fillOpacity,strokeWidth:e.strokeWidth,strokeColor:e.fillColor}),vu=e=>({id:e.id,content:e.content,x:e.x,y:e.y,width:e.width,backgroundColor:e.backgroundColor??null,backgroundColorStyle:e.backgroundColorStyle}),Su=(e,t,n)=>{const r=xt({dataset:n,input:e,anchorVariable:t});return r===null?null:{id:e.id,anchor:r,sticker:e.sticker}},xu=(e,t,n)=>{const r=xt({dataset:n,input:e,anchorVariable:t});return r===null?null:e.caption===null||e.caption===void 0?{kind:"pinnedNumber",value:{id:e.id,anchor:r}}:{kind:"comment",value:{id:e.id,anchor:r,content:e.caption}}},wu=e=>({id:e.id,start:{x:e.startX,y:e.startY},end:{x:e.endX,y:e.endY},color:e.color??null,thickness:e.thickness,startArrowheadStyle:e.startArrowheadStyle,endArrowheadStyle:e.endArrowheadStyle,lineStyle:e.lineStyle,hasStickerStyle:e.hasStickerStyle}),xt=({dataset:e,input:t,anchorVariable:n})=>{if(!h(t)||!h(t.columnKey))return null;const r=Au(t,n,e);return r===null?null:{anchorValue:r,groupValue:sa(t.columnKey)}},Au=(e,t,n)=>e.rowValue!==void 0?e.rowValue:t===null||!h(e.rowIndex)||!n.hasVariable(t)?null:n.getValues(t)[e.rowIndex]??null,ia=["lilac","neon_pink","blackberry","sun","iceland","sunset","ultraviolet","purple","ice_cream","mint","cool","fresh"];function ca(e){return{type:"config",config:e}}const Tu="#E5E5E5",Mu={x:"top",y:"left"},Lu=new Set(["pie","donut"]);function Vu(e){return ca({legend:_u(e.legend),axes:Du(e.axes),headline:Ru(e),numberFormat:Nu(e.appearance),content:Pu(e.content),appearance:ku(e.appearance,e.themeOverrides)}).config}function ku(e,t){const n=Cu(e?.border),r=e?.hasRoundedCorners===!1?0:void 0,o=Eu(e,t),a={};return e?.textScale!==void 0&&(a.textScale=e.textScale),n!==void 0&&(a.border=n),r!==void 0&&(a.cornerRadius=r),o!==void 0&&(a.background=o),e?.highlightStyle!==void 0&&(a.highlightStyle=e.highlightStyle==="grey"?"desaturate":"dim"),Object.keys(a).length>0?a:void 0}function Eu(e,t){if(e?.backgroundModifier==="tint")return{type:"tinted"};const n=t?.graphBackground;if(typeof n=="string")return{type:"solid",color:n}}const Iu=e=>ia.includes(e);function Cu(e){if(!e?.style)return;if(e.style==="none")return{type:"none"};const t=e.width??0;if(e.style==="grey")return{type:"solid",color:Tu,width:t};if(e.style==="preset")return e.color===void 0||!Iu(e.color)?void 0:{type:"preset",preset:e.color,width:t};if(e.color!==void 0)return e.style==="custom"?{type:"solid",color:e.color,width:t}:{type:e.style,color:e.color,width:t}}function _u(e){if(e)return{position:e.position}}function kr(e,t,n){return!t&&n===void 0?{}:{...t?.isHidden!==void 0?{isVisible:!t.isHidden}:void 0,...t?.label!==void 0?{label:t.label}:void 0,...t?.isReversed?{position:Mu[e]}:void 0,...t?.tickDisplayMode?{labels:{mode:t.tickDisplayMode}}:void 0,...n!==void 0?{grid:{isVisible:n}}:void 0}}function Fu(e){return{...e.label!==void 0?{label:e.label}:void 0}}function Du(e){if(e)return{x:kr("x",e.x,e.showGridLines),y:kr("y",e.y,e.showGridLines),...e.y2?{ySecondary:Fu(e.y2)}:void 0}}function Ru(e){const{headlineNumbers:t,options:n,type:r}=e,o=r!==void 0&&Lu.has(r)?n?.pieTotalPosition:void 0;if(t===void 0&&o===void 0)return;const a={};return t?.show!==void 0&&(a.show=t.show),t?.compareWith!==void 0&&(a.compareWith=t.compareWith),t?.size!==void 0&&(a.size=t.size),o!==void 0&&(a.show="total",a.position=o==="center"?"center":"above"),a}function Nu(e){if(e?.numberFormat)return{decimals:e.numberFormat.decimalPlaces,abbreviation:e.numberFormat.abbreviation}}function Pu(e){if(!e)return;const t={};e.title!==void 0&&(t.title=e.title),e.isTitleHidden!==void 0&&(t.isTitleVisible=!e.isTitleHidden),e.subtitle!==void 0&&(t.subtitle=e.subtitle),e.isSubtitleHidden!==void 0&&(t.isSubtitleVisible=!e.isSubtitleHidden),e.caption!==void 0&&(t.caption=e.caption),e.isCaptionHidden!==void 0&&(t.isCaptionVisible=!e.isCaptionHidden);const n=Ou(e.source);return n!==void 0&&(t.source=n),e.isSourceHidden!==void 0&&(t.isSourceVisible=!e.isSourceHidden),t}function Ou(e){if(!e)return;const t={};return e.label!==void 0&&(t.label=e.label),e.url!==void 0&&(t.url=e.url),Object.keys(t).length===0?void 0:t}const P={cartesian:(e={})=>({type:"coord",coordType:"cartesian",params:e}),flip:(e={})=>({type:"coord",coordType:"flip",params:e}),polar:(e={})=>({type:"coord",coordType:"polar",params:e})},Bu={showDataLabels:!1,format:"absolute",showStackTotals:!1,showCategoryLabels:!1,labelSource:{variable:g.yRaw}},yt={stat:{type:"identity"},position:"identity",params:{size:8}},Bt={stat:{type:"identity"},position:"identity",params:{lineWidth:"auto",interpolate:"linear",missingValues:"gap"}},$t={stat:{type:"identity"},position:"stack",params:{lineWidth:"auto",interpolate:"linear",missingValues:"zero"}},Gt={stat:{type:"identity"},position:"dodge",params:{}},Oe={stat:{type:"identity"},position:"identity",interactive:!1,params:{strokeWidth:1,lineType:"dashed",labelPosition:"start"}},Fe="primary";function $u(e,t){const n={...Bu};return e==="bar"&&t==="polar"&&(n.format="percentage"),n}function F(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"continuous",transform:t.transform,reverse:t.reverse,nice:t.nice,zero:t.zero,clamp:t.clamp,domainMin:t.domainMin??null,domainMax:t.domainMax??null,range:t.range}}function gt(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"datetime",domainMin:t.domainMin??null,domainMax:t.domainMax??null,nice:t.nice,reverse:t.reverse,clamp:t.clamp}}function z(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"discrete",range:t.range,domain:t.domain??null,padding:t.padding,reverse:t.reverse}}function Ue(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"identity"}}function bt(e,t){return{type:"scale",scaledAesthetic:e,scaleType:"inferred",options:t}}function la(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"palette",palette:t.palette}}const he={x:Object.assign(e=>bt("x",e),{continuous:e=>F("x",e),discrete:e=>z("x",e),datetime:e=>gt("x",e),log:e=>F("x",{...e,transform:"log"}),sqrt:e=>F("x",{...e,transform:"sqrt"})}),y:Object.assign(e=>bt("y",e),{continuous:e=>F("y",e),discrete:e=>z("y",e),datetime:e=>gt("y",e),log:e=>F("y",{...e,transform:"log"}),sqrt:e=>F("y",{...e,transform:"sqrt"})}),ySecondary:Object.assign(e=>bt("ySecondary",e),{continuous:e=>F("ySecondary",e),discrete:e=>z("ySecondary",e),datetime:e=>gt("ySecondary",e),log:e=>F("ySecondary",{...e,transform:"log"}),sqrt:e=>F("ySecondary",{...e,transform:"sqrt"})}),color:{continuous:e=>F("color",e),discrete:e=>z("color",e),palette:e=>la("color",e)},size:{continuous:e=>F("size",e),discrete:e=>z("size",e),identity:e=>Ue("size",e)},alpha:{continuous:e=>F("alpha",e),discrete:e=>z("alpha",e),identity:e=>Ue("alpha",e)},strokeWidth:{continuous:e=>F("strokeWidth",e),discrete:e=>z("strokeWidth",e),identity:e=>Ue("strokeWidth",e)},lineType:{discrete:e=>z("lineType",e),identity:e=>Ue("lineType",e)}},G="key",J="value",Er=A("lineSeriesLabel"),Ir=A("barSeriesLabel"),wt=A("constantY"),Gu=(e,t,n,r)=>Xu[t](e,n,r),Tn=e=>{const{numeric:t,categorical:n,temporal:r}=e.groupVariableNamesByType();return h(r[0])?r[0]:h(n[0])?n[0]:h(t[0])?t[0]:""},Mn=e=>{const t=Tn(e),{numeric:n}=e.groupVariableNamesByType(),r=n.filter(a=>a!==t);return r.length<=1?{dataset:e,mapping:{x:t,y:r[0]??""},seriesVariables:r}:{dataset:e.reshapeFromWideToLong({keep:[t],keyName:G,valueName:J}),mapping:{x:t,y:J,color:G},seriesVariables:r}},Ln=e=>{const t=e.appearance?.seriesStyles;if(!t||e.seriesVariables.length===0)return{mapping:{},scales:[]};if(!e.seriesVariables.some(o=>h(t[o]?.lineStyle)))return{mapping:{},scales:[]};if(e.seriesVariables.length===1){const o=e.seriesVariables[0];if(!o)return{mapping:{},scales:[]};const a=t[o]?.lineStyle;return a?{mapping:{lineType:{value:a}},scales:[]}:{mapping:{},scales:[]}}const r=e.seriesVariables.map(o=>t[o]?.lineStyle??"solid");return{mapping:{lineType:G},scales:[he.lineType.discrete({domain:e.seriesVariables,range:r})]}},Uu=e=>{const{categorical:t,temporal:n,numeric:r}=e.groupVariableNamesByType(),o=r[0];if(!h(o))throw new Error("No first numeric variable found");const a=r.slice(1);return a.length===0?{dataset:e.addConstantVariable(wt,"categorical",""),mapping:{x:o,y:wt,label:t[0]}}:a.length===1?{dataset:e,mapping:{x:o,y:a[0]??"",label:t[0]}}:{dataset:e.reshapeFromWideToLong({keep:[o,...t,...n],keyName:G,valueName:J}),mapping:{x:o,y:J,label:t[0],color:G}}},Yu=e=>{const{categorical:t,temporal:n,numeric:r}=e.groupVariableNamesByType();let o,a;if(h(t[0])&&h(r[0]))o=t[0],a=r[0];else if(h(n[0])&&h(r[0]))o=n[0],a=r[0];else if(h(r[0])&&h(r[1]))o=r[0],a=r[1];else throw new Error("No label or value variable found");return{x:"",y:a,color:o}},ua=(e,t,n)=>{const{dataset:r,mapping:o,seriesVariables:a}=Mn(e.dataset),s=Ln({appearance:n,seriesVariables:a}),i=[I.line({params:{lineWidth:t?.lineThickness,interpolate:t?.isSmoothLine?"catmull-rom":"linear",missingValues:t?.missingValues}})];return t?.showPoints&&i.push(I.point({params:{size:da(t.pointSize)},interactive:!1})),{dataset:r,layers:i,coords:P.cartesian(),mapping:{...o,...s.mapping},scales:s.scales,seriesVariables:a}},Wu=(e,t,n)=>{const{dataset:r,mapping:o,seriesVariables:a}=Mn(e.dataset),s=Ln({appearance:n,seriesVariables:a}),i=[I.area({position:"stack",params:{lineWidth:t?.lineThickness,interpolate:t?.isSmoothLine?"catmull-rom":"linear",missingValues:t?.missingValues}})];return t?.showPoints&&i.push(I.point({params:{size:da(t.pointSize)},position:"stack",interactive:!1})),{dataset:r,layers:i,coords:P.cartesian(),mapping:{...o,...s.mapping},scales:s.scales,seriesVariables:a}},de=(e,t,n,r,o)=>{const{dataset:a,mapping:s,seriesVariables:i}=Mn(e.dataset),c=[];if(r?.sortBars){const l=v(s.y);l!==null&&l!==""&&c.push(fe.sort({variableName:l,direction:"desc"}))}if(!o?.useSingleColorForBars){const l=Tn(e.dataset),{numeric:u}=e.dataset.groupVariableNamesByType();u.filter(m=>m!==l).length===1&&e.dataset.getType(l)==="categorical"&&(s.color=l)}return{dataset:a,layers:[I.bar({position:t})],coords:n,mapping:s,scales:[],transforms:c,seriesVariables:i}},Cr=(e,t)=>({dataset:e.dataset,layers:[I.bar({position:"fill"})],coords:P.polar({theta:"y",innerRadius:t==="donut"?.55:0}),mapping:Yu(e.dataset),scales:[],seriesVariables:[]}),Hu=e=>{const{dataset:t,mapping:n}=Uu(e.dataset);return{dataset:t,layers:[I.point()],coords:P.cartesian(),mapping:n,scales:[],seriesVariables:[]}},Ku=e=>{const{numeric:t,categorical:n}=e.dataset.groupVariableNamesByType(),r=t[0];if(!h(r))throw new Error("No first numeric variable found");const a=h(t[1])?e.dataset:e.dataset.addConstantVariable(wt,"categorical",""),s={x:r,y:t[1]??wt,size:t[2],label:n[0]},i=[];return h(s.size)&&i.push(he.size.continuous()),{dataset:a,layers:[I.point()],coords:P.cartesian(),mapping:s,scales:i,seriesVariables:[]}},Ut=(e,t,n)=>{const r=n?.seriesStyles?.[e]?.lineStyle;return I.line({transforms:[fe.constant({variableName:Er,type:"categorical",value:e})],aes:{y:e,color:Er,...r?{lineType:{value:r}}:{}},...t?{yScaleType:"secondary"}:void 0})},zu=(e,t,n)=>{const{numeric:r,categorical:o,temporal:a}=e.dataset.groupVariableNamesByType(),s=Tn(e.dataset),i=[...o,...a],c=r.filter(b=>b!==s),l=t?.comboType??"grouped-bars",u=l==="lines";if(c.length===1)return u?ua(e,t,n):de(e,"dodge",P.cartesian(),t,n);const d=e.axes?.hasDualYAxis===!0,m=u?[]:c.slice(0,-1),p=u?c:c.slice(-1),f=[],y=[];if(m.length>0){const b=l==="stacked-bars"?"stack":"dodge",x=m.length===1?m[0]:null;h(x)?f.push(I.bar({transforms:[fe.constant({variableName:Ir,type:"categorical",value:x})],aes:{y:x,color:Ir},position:b})):f.push(I.bar({transforms:[fe.reshape({keep:i,reshape:m,keyName:G,valueName:J})],aes:{y:J,color:G},position:b}))}if(u&&p.length>=2){const b=d?p.slice(0,-1):p,x=b.length===1?b[0]:null;if(h(x))f.push(Ut(x,!1,n));else{const S=Ln({appearance:n,seriesVariables:b});f.push(I.line({transforms:[fe.reshape({keep:i,reshape:b,keyName:G,valueName:J})],aes:{y:J,color:G,...S.mapping}})),y.push(...S.scales)}if(d){const S=p[p.length-1];h(S)&&f.push(Ut(S,!0,n))}}else for(const b of p)f.push(Ut(b,d,n));return{dataset:e.dataset,layers:f,coords:P.cartesian(),mapping:{x:s},scales:y,seriesVariables:c}},da=(e="auto")=>e==="auto"?yt.params.size:e,Be=e=>()=>{throw new Error(`Unsupported graph type: ${e}`)},Xu={line:(e,t,n)=>ua(e,t,n),areaStacked:(e,t,n)=>Wu(e,t,n),bar:(e,t,n)=>de(e,"dodge",P.flip(),t,n),barStacked:(e,t,n)=>de(e,"stack",P.flip(),t,n),barStackedFill:(e,t,n)=>de(e,"fill",P.flip(),t,n),column:(e,t,n)=>de(e,"dodge",P.cartesian(),t,n),columnStacked:(e,t,n)=>de(e,"stack",P.cartesian(),t,n),columnStackedFill:(e,t,n)=>de(e,"fill",P.cartesian(),t,n),pie:e=>Cr(e,"pie"),donut:e=>Cr(e,"donut"),scatter:e=>Hu(e),bubble:e=>Ku(e),combo:(e,t,n)=>zu(e,t,n),funnel:Be("funnel"),heatmap:Be("heatmap"),waterfall:Be("waterfall"),mekko:Be("mekko"),table:Be("table")},ma=["key",A("lineSeriesLabel"),A("barSeriesLabel")];function ju(e){const t=e.annotations??[],n=qu(e.mapping),r=Ju(e.convertedDataset,e.layers),o=[];for(const a of t){if(a.type!=="highlight")continue;const s=Qu({annotation:a,rowIdentityVariable:n,dataset:e.dataset,compiledVariableNames:r});s!==null&&o.push({type:"highlight",id:a.id,predicate:s,scope:a.highlight})}return o}function qu(e){const t=v(e.x);return t!==null&&t!==""?t:v(e.color)}function Qu({annotation:e,rowIdentityVariable:t,dataset:n,compiledVariableNames:r}){switch(e.highlight){case"x-value":return _r(e,t,n);case"series":return Fr(e,r);case"data-point":{const o=_r(e,t,n),a=Fr(e,r);return o===null&&a===null?null:o===null?a:a===null?o:{and:[o,a]}}}}function _r(e,t,n){if(t===null)return null;const r=ed(e,t,n);return r===null?null:{variable:t,eq:r}}function Fr(e,t){if(!Zu(t))return null;const n=e.columnKey;return h(n)?{or:ma.map(r=>({variable:r,eq:n}))}:null}function Zu(e){return ma.some(t=>e.includes(t))}function Ju(e,t){const n=[...e.getVariableNames()];for(const r of t)for(const o of r.transforms??[])o.transformType==="reshape"?n.push(o.options.keyName??G):o.transformType==="constant"&&n.push(o.options.variableName);return n}function ed(e,t,n){return e.rowValue!==void 0?e.rowValue:!h(e.rowIndex)||!n.getVariableNames().includes(t)?null:n.getValues(t)[e.rowIndex]??null}function td(e,t,n){const{theme:r,customPalettes:o}=n;if(o&&e&&o[e])return{type:"custom",id:e};if(e?.startsWith("preset:pastel"))return{type:"pastel",variant:Yt(t)};if(e?.startsWith("preset:graphy"))return{type:"graphy",variant:Yt(t)};const i="preset:mono:";if(e?.startsWith(i)){const l=e.slice(i.length);if(nd(l))return{type:"mono",base:l,variant:r}}const c="preset:neon:";if(e?.startsWith(c)){const l=e.slice(c.length);if(rd(l))return{type:"neon",base:l,variant:Yt(t)}}return{type:"default"}}function Yt(e){if(e==="waterfall")return"waterfall"}function nd(e){return ra.includes(e)}function rd(e){return oa.includes(e)}function od(e,t,n,r={}){const o=[];o.push(Dr("x",t?.x)),o.push(Dr("y",t?.y));const a=td(n?.paletteId,e,r);return o.push(he.color.palette({palette:a})),o}function Dr(e,t){return t?.scaleType==="logarithmic"||t?.min!==void 0||t?.max!==void 0?t.scaleType==="logarithmic"?he[e].log({domainMin:t.min??void 0,domainMax:t.max??void 0}):he[e]({domainMin:t.min??void 0,domainMax:t.max??void 0}):he[e]()}const ad=new Set(["column","columnStacked","columnStackedFill","bar","barStacked","barStackedFill","line","areaStacked","scatter","bubble","funnel","combo"]),sd=new Set(["column","columnStacked","columnStackedFill","bar","barStacked","barStackedFill","line","areaStacked","combo"]);function id(e,t,n){const r=t.type??"column",o={dataset:e,axes:t.axes},a=Gu(o,r,t.options??void 0,t.appearance??void 0);return{data:a.dataset,mapping:a.mapping,layers:cd(r,t,a.layers,a.coords,a.mapping,a.seriesVariables),scales:[...od(r,t.axes,t.appearance,n),...a.scales],transforms:a.transforms??[],highlights:ju({annotations:t.annotations,dataset:e,mapping:a.mapping,convertedDataset:a.dataset,layers:a.layers}),annotations:yu({annotations:t.annotations,dataset:e,mapping:a.mapping}),coords:a.coords,config:Vu(t)}}function cd(e,t,n,r,o,a){const s=pd(t.dataLabels),i=s===void 0?n:n.filter(l=>l.interactive!==!1).map(l=>({...l,dataLabels:{...s,...l.dataLabels}})),c=t.axes?.hasDualYAxis??!1;return[...i,...ld({type:e,trendline:t.referenceLines?.trendline,coords:r}),...ud({type:e,hasDualYAxis:c,goalLine:t.referenceLines?.goalLine,coords:r}),...md({type:e,hasDualYAxis:c,averageLine:t.referenceLines?.averageLine,coords:r,mapping:o,seriesVariables:a})]}function ld({type:e,trendline:t,coords:n}){return t===void 0?[]:ad.has(e)?n.coordType==="polar"?[]:[I.line({aes:{lineType:{value:"dashed"}},stat:An.smooth({method:t}),interactive:!1})]:[]}function ud({type:e,hasDualYAxis:t,goalLine:n,coords:r}){if(!dd(n))return[];if(r.coordType==="polar")return[];const o=r.coordType==="flip"?"end":"start";return[I.rule({aes:{y:{value:n.target}},params:{labelPosition:o,label:n.label??"Goal"},yScaleType:e==="combo"&&t?"secondary":"primary",interactive:!1})]}function dd(e){return e!==void 0&&Number.isFinite(e.target)}function md({type:e,hasDualYAxis:t,averageLine:n,coords:r,mapping:o,seriesVariables:a}){if(n===void 0)return[];if(!sd.has(e))return[];if(r.coordType==="polar")return[];const s=sa(n.columnKey);if(!a.includes(s))return[];const i=o.color===G,c=i?J:s,l=i?[fe.filter({variableName:G,operator:"eq",value:s})]:[];return[I.rule({aes:{y:c,color:void 0,group:void 0,lineType:void 0},stat:An.mean(),transforms:l,params:{label:"Average",labelPosition:r.coordType==="flip"?"end":"start"},yScaleType:e==="combo"&&t?"secondary":"primary",interactive:!1})]}function pd(e){if(!e)return;const t={};return e.showDataLabels!==void 0&&(t.showDataLabels=e.showDataLabels),e.dataLabelFormat!==void 0&&(t.format=e.dataLabelFormat),e.showStackTotals!==void 0&&(t.showStackTotals=e.showStackTotals),e.showCategoryLabels!==void 0&&(t.showCategoryLabels=e.showCategoryLabels),Object.keys(t).length===0?void 0:t}const Wt={color:null,size:"small",labelCrossPosition:.5},Te={kind:"rectangle",zOrder:"foreground",fillColor:"transparent",fillOpacity:1,strokeWidth:1,strokeColor:null},Rr={backgroundColor:null,backgroundColorStyle:"opaque"},Me={color:null,thickness:"medium",startArrowheadStyle:"none",endArrowheadStyle:"line-arrow",lineStyle:"solid",hasStickerStyle:!1},fd=(e,t)=>({differenceArrows:(e?.differenceArrows??[]).map(n=>bd(n,t)),shapes:(e?.shapes??[]).map(wd),freeformArrows:(e?.freeformArrows??[]).map(Ad),textAnnotations:(e?.textAnnotations??[]).map(gd),stickers:(e?.stickers??[]).map(n=>vd(n,t)),pinnedNumbers:(e?.pinnedNumbers??[]).map(n=>Sd(n,t)),comments:(e?.comments??[]).map(n=>xd(n,t)),custom:(e?.custom??[]).map(n=>hd(n,t))}),hd=(e,t)=>({id:e.id??crypto.randomUUID(),type:e.type,coordinates:e.coordinates.map(n=>yd(n,t)),params:e.params??{},zOrder:e.zOrder??null}),yd=(e,t)=>"observation"in e?{observation:Ve(e.observation,t)}:e,gd=e=>({id:e.id??crypto.randomUUID(),content:e.content,x:e.x,y:e.y,width:e.width,backgroundColor:e.backgroundColor??Rr.backgroundColor,backgroundColorStyle:e.backgroundColorStyle??Rr.backgroundColorStyle}),bd=(e,t)=>({id:e.id??crypto.randomUUID(),start:Ve(e.start,t),end:Ve(e.end,t),label:e.label,color:e.color??Wt.color,size:e.size??Wt.size,labelCrossPosition:e.labelCrossPosition??Wt.labelCrossPosition}),Ve=(e,t)=>{if(e.layerIndex===void 0)return{anchorValue:e.anchorValue,groupValue:e.groupValue};const n=t[e.layerIndex]?.id;if(n===void 0)throw new Error(`Annotation references layerIndex ${e.layerIndex} but only ${t.length} layer(s) are defined.`);return{layerId:n,anchorValue:e.anchorValue,groupValue:e.groupValue}},vd=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:Ve(e.anchor,t),sticker:e.sticker}),Sd=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:Ve(e.anchor,t)}),xd=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:Ve(e.anchor,t),content:e.content}),wd=e=>({id:e.id??crypto.randomUUID(),kind:e.kind??Te.kind,zOrder:e.zOrder??Te.zOrder,x:e.x,y:e.y,width:e.width,height:e.height,fillColor:e.fillColor??Te.fillColor,fillOpacity:e.fillOpacity??Te.fillOpacity,strokeWidth:e.strokeWidth??Te.strokeWidth,strokeColor:e.strokeColor??Te.strokeColor}),Ad=e=>({id:e.id??crypto.randomUUID(),start:e.start,end:e.end,color:e.color??Me.color,thickness:e.thickness??Me.thickness,startArrowheadStyle:e.startArrowheadStyle??Me.startArrowheadStyle,endArrowheadStyle:e.endArrowheadStyle??Me.endArrowheadStyle,lineStyle:e.lineStyle??Me.lineStyle,hasStickerStyle:e.hasStickerStyle??Me.hasStickerStyle}),Td={parsingLocale:"en-US",legend:{position:"auto",display:"auto"},axes:{x:{isVisible:!0,label:null,position:"bottom",grid:{isVisible:null},ticks:{isVisible:!0,mode:"auto"}},y:{isVisible:!0,label:null,position:"right",grid:{isVisible:null},ticks:{isVisible:!1,mode:"auto"}}},panel:{border:{isVisible:!0}},headline:{show:"none",compareWith:"none",size:"auto",position:"above"},numberFormat:{decimals:"auto",abbreviation:"auto"},content:{title:null,isTitleVisible:!0,subtitle:null,isSubtitleVisible:!0,caption:null,isCaptionVisible:!1,source:null,isSourceVisible:!1},appearance:{textScale:1,background:{type:"theme"},border:{type:"none"},cornerRadius:8,highlightStyle:"dim"}};function Md(e){return ae.merge({},Td,e)}const Ld={xLimits:null,yLimits:null},Ht={theta:"x",startAngle:0,innerRadius:0};function Vd(e){const t=e??{type:"coord",coordType:"cartesian"},n=oo({},Ld,t.params??{});switch(t.coordType){case"cartesian":case"flip":return{...t,params:n};case"polar":return{...t,params:{...n,theta:t.params?.theta??Ht.theta,startAngle:t.params?.startAngle??Ht.startAngle,innerRadius:t.params?.innerRadius??Ht.innerRadius}}}}function kd(e,t){return e.map(n=>{const r=n.layerIndex!==void 0?t[n.layerIndex]?.id:void 0;if(n.layerIndex!==void 0&&r===void 0)throw new Error(`Highlight references layerIndex ${n.layerIndex} but only ${t.length} layer(s) are defined.`);return{type:"highlight",id:n.id??crypto.randomUUID(),predicate:n.predicate,scope:n.scope??"data-point",...r!==void 0?{layerId:r}:{}}})}const Ed="linear",Id=3,Cd=.3;function De(e,t){const n=e??t,r=typeof n=="string"?n:n.type;if(r==="smooth"){const o=typeof n=="string"?void 0:n;return{type:"smooth",method:o?.method??Ed,order:o?.order??Id,bandwidth:o?.bandwidth??Cd}}return{type:r}}function _d(e,t,n){if(!Rd(n))return Nd(e,t,n);switch(n.geom){case"point":return Pd(e,t,n);case"line":return Od(e,t,n);case"area":return Bd(e,t,n);case"bar":return $d(e,t,n);case"rule":return Gd(e,t,n)}}function Fd(e,t,n){const r=n.map(o=>_d(e,t,o));return Ud(r)}const Dd=(e,t,n)=>n.label!==void 0?n.label:Yd(e,t,n),Rd=e=>Xo(e.geom);function Nd(e,t,n){const r=n.position??"identity";return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:De(n.stat,"identity"),position:r,yScaleType:n.yScaleType??Fe,params:n.params??{},transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Re(e,n,r,t)}}const Re=(e,t,n,r)=>{const o={...e,...t.mapping},a=Dd(t.geom,n,o);return{...$u(t.geom,r),...t.dataLabels,labelSource:a}};function Pd(e,t,n){const r=n.position??yt.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:De(n.stat,yt.stat.type),position:r,yScaleType:n.yScaleType??Fe,params:ae.merge({},yt.params,n.params),transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Re(e,n,r,t)}}function Od(e,t,n){const r=n.position??Bt.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:De(n.stat,Bt.stat.type),position:r,yScaleType:n.yScaleType??Fe,params:ae.merge({},Bt.params,n.params),transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Re(e,n,r,t)}}function Bd(e,t,n){const r=ae.merge({},$t.params,n.params);r.missingValues==="gap"&&(r.missingValues="zero");const o=n.position??$t.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:De(n.stat,$t.stat.type),position:o,yScaleType:n.yScaleType??Fe,params:r,transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Re(e,n,o,t)}}function $d(e,t,n){const r=n.position??Gt.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:De(n.stat,Gt.stat.type),position:r,yScaleType:n.yScaleType??Fe,params:{...Gt.params,...n.params},transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Re(e,n,r,t)}}function Gd(e,t,n){const r=n.position??Oe.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:De(n.stat,Oe.stat.type),position:n.position??Oe.position,yScaleType:n.yScaleType??Fe,params:ae.merge({},Oe.params,n.params),transforms:n.transforms??[],interactive:n.interactive??Oe.interactive,dataLabels:Re(e,n,r,t)}}const Ud=e=>{const t=new Set;for(const n of e)n.position==="fill"&&t.add(n.yScaleType);return t.size===0?e:e.map(n=>{if(n.geom!=="rule"||!t.has(n.yScaleType))return n;const r=ee(n.mapping.y);if(!E(r))return n;const o=Math.min(1,Math.max(0,r));return{...n,mapping:{...n.mapping,y:{value:o}}}})},Yd=(e,t,n)=>{if(e==="point"){const r=v(n.size);if(r!==null)return{variable:r}}return tt(t,n)};function Wd(e,...t){return e?t.includes(e.geom):!1}function Hd(e,t){return e.find(n=>n.id===t)}function pa(e,...t){return e.find(n=>t.includes(n.geom))}function Kd(e,t,n){const r=e.layers.findIndex(a=>a.id===t);if(r===-1)return e;const o=e.layers.map((a,s)=>s===r?n:a);return{...e,layers:o}}const fa={x:"position",y:"position",ySecondary:"position",color:"color-range",size:"continuous-range",alpha:"continuous-range",strokeWidth:"continuous-range",lineType:"discrete-only"},zd={numeric:{position:"continuous","color-range":"continuous","continuous-range":"continuous","discrete-only":"discrete"},categorical:{position:"discrete","color-range":"discrete","continuous-range":"discrete","discrete-only":"discrete"},temporal:{position:"datetime","color-range":"continuous","continuous-range":"continuous","discrete-only":"discrete"}};function ha(e,t,n,r,o){switch(e.scaleType){case"inferred":{const a=qd(e,t,n,r);return ha(a,t,n,r,o)}case"continuous":{const a=fa[e.scaledAesthetic],s=a==="continuous-range"&&e.scaledAesthetic in Mr?Mr[e.scaledAesthetic]:null,i=e.scaledAesthetic==="size"&&a==="continuous-range"?"sqrt":Ae.transform;return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,transform:e.transform??i,reverse:e.reverse??Ae.reverse,nice:e.nice??Ae.nice,zero:e.zero??Ae.zero,clamp:e.clamp??a!=="position",domainMin:e.domainMin??Ae.domainMin,domainMax:e.domainMax??Ae.domainMax,range:e.range??s??null}}case"datetime":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,domainMin:e.domainMin??st.domainMin,domainMax:e.domainMax??st.domainMax,nice:e.nice??st.nice,reverse:e.reverse??st.reverse,clamp:e.clamp??!1};case"discrete":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,range:e.range??Ge.range,domain:e.domain??Ge.domain,padding:e.padding??Ge.padding,reverse:e.reverse??Ge.reverse};case"palette":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,palette:Jl(e.palette,o)};case"identity":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType};default:{const a=e;throw new Error(`Unknown scale type: ${a.scaleType}`)}}}function Xd(e,t,n,r,o,a){const s=Zd(t,n),i=Jd(s),c=new Map;for(const u of i)c.set(u.scaledAesthetic,u);const l=[...c.values()].map(u=>ha(u,e,n,r,a));return o.coordType==="polar"?jd(l):l}const jd=e=>e.map(t=>t.scaleType==="discrete"?{...t,padding:0}:t);function qd(e,t,n,r){const o=q(e.scaledAesthetic),a=e.scaledAesthetic==="ySecondary"?Qd(n,r):r[o],s=pa(n,"bar");if(e.scaledAesthetic==="x"&&s)return z(e.scaledAesthetic,e.options);if(s&&e.scaledAesthetic===(s.yScaleType==="secondary"?"ySecondary":"y")){const d=e.options,m=s.position==="fill";return F(e.scaledAesthetic,{...d,zero:!0,...m&&{nice:!1}})}const i=v(a);if(!h(i)||!t.hasVariable(i))return F(e.scaledAesthetic,e.options);const c=t.getType(i),l=fa[e.scaledAesthetic];switch(zd[c][l]){case"discrete":return z(e.scaledAesthetic,e.options);case"datetime":return gt(e.scaledAesthetic,e.options);case"continuous":return F(e.scaledAesthetic,e.options);case"identity":default:return Ue(e.scaledAesthetic)}}function Qd(e,t){const n=e.find(r=>r.yScaleType==="secondary");return n?n.mapping.y??t.y:t.y}function Zd(e,t){return!t.some(o=>o.yScaleType==="secondary")||e.some(o=>o.scaledAesthetic==="ySecondary")?e:[...e,bt("ySecondary")]}function Jd(e){return e.some(n=>n.scaledAesthetic==="color")?e:[...e,la("color")]}function Nr(e,t){const n=Vd(e.coords),r=Fd(e.mapping,n.coordType,e.layers),o=Xd(e.data,e.scales,r,e.mapping,n,t),a=Md(e.config),s=kd(e.highlights,r),i=fd(e.annotations,r);return{data:e.data,mapping:e.mapping,layers:r,scales:o,transforms:e.transforms,highlights:s,annotations:i,coords:n,config:a}}class ya{compile({input:t,dataset:n,ctx:r}){const o=r.customPalettes??{};return aa(t)?Nr(id(n,t,r),o):Nr({...t,data:n},o)}}class em{constructor(t){this.registry=t}compute(t,n){return this.registry.get(t.type).compute({data:n.data,mapping:n.mapping,spec:t,xScaleIsDiscrete:n.xScaleIsDiscrete})}}class _t{compute(t){return t.data.size()===0?{data:t.data,mapping:{}}:this.computeStat(t)}}class tm extends _t{constructor(){super(...arguments),this.type="count",this.computedVariables=new Set(["y"])}computeStat({data:t,mapping:n}){const r=v(n.x);if(!h(r))throw new Error("'x' variable is required for 'count' stat");if(v(n.y)!==null)throw new Error("Cannot map 'y' variable together with 'count' stat");const a=[...new Set([r,...hn(t,n)])];return{data:t.groupBy(...a).rollup({[He.count]:{variableName:r,aggregation:"count"}}),mapping:{y:He.count}}}}class nm extends _t{constructor(){super(...arguments),this.type="identity",this.computedVariables=new Set}computeStat({data:t}){return{data:t,mapping:{}}}}class rm extends _t{constructor(){super(...arguments),this.type="mean",this.computedVariables=new Set(["y"])}computeStat({data:t,mapping:n}){const r=v(n.y);if(!h(r))throw new Error("'y' variable is required for 'mean' stat");return{data:t.rollup({[He.mean]:{variableName:r,aggregation:"mean"}}),mapping:{y:He.mean}}}}const om=2,ga=1440*60*1e3;class am extends _t{constructor(){super(...arguments),this.type="smooth",this.computedVariables=new Set}computeStat({data:t,mapping:n,spec:r,xScaleIsDiscrete:o}){if(r.type!=="smooth")throw new Error(`SmoothStat received a spec of type '${r.type}'`);const a=v(n.x),s=v(n.y);if(!h(a))throw new Error("'x' variable is required for 'smooth' stat");if(!h(s))throw new Error("'y' variable is required for 'smooth' stat");const i=t.getType(a),c=t.getType(s);if(c!=="numeric")throw new Error(`'smooth' stat requires a numeric 'y' (got '${c}' for variable '${s}')`);const l=hn(t,n),u=mm(a,i,s,l,t);return l.length===0?Pr({data:t,xVariable:a,xType:i,yVariable:s,spec:r,output:u,groupObservation:{},xScaleIsDiscrete:o}):t.groupBy(...l).forEach(d=>{const m=pm(d,l);Pr({data:d,xVariable:a,xType:i,yVariable:s,spec:r,output:u,groupObservation:m,xScaleIsDiscrete:o})}),{data:u.build(),mapping:{}}}}const Pr=({data:e,xVariable:t,xType:n,yVariable:r,spec:o,output:a,groupObservation:s,xScaleIsDiscrete:i})=>{const{observations:c,temporalOrigin:l}=sm({data:e,xVariable:t,yVariable:r,xType:n});c.length<om||(i?dm({observations:c,spec:o,output:a,groupObservation:s}):lm({observations:c,xType:n,temporalOrigin:l,spec:o,output:a,groupObservation:s}))},sm=({data:e,xVariable:t,yVariable:n,xType:r})=>{const o=e.getValues(t),a=e.getValues(n,{type:"numeric"}),s=r==="temporal"?im(o):null,i=[],c=new Map;for(let l=0;l<o.length;l++){const u=o[l],d=a[l];if(!h(u)||!h(d)||!Number.isFinite(d))continue;const m=cm({xValue:u,xType:r,categoryRank:c,temporalOrigin:s});m!==null&&i.push({x:m,y:d,originalX:u})}return{observations:i,temporalOrigin:s}},im=e=>{let t=null;for(const n of e){if(!O(n))continue;const r=n.getTime();(t===null||r<t)&&(t=r)}return t},cm=({xValue:e,xType:t,categoryRank:n,temporalOrigin:r})=>{switch(t){case"numeric":return!E(e)||!Number.isFinite(e)?null:e;case"temporal":{if(!O(e))return null;const o=e.getTime();return r===null?o:(o-r)/ga+1}case"categorical":{if(!Qe(e))return null;const o=n.get(e);if(o!==void 0)return o;const a=n.size+1;return n.set(e,a),a}default:{const o=t;throw new Error(`Unexpected xType: ${o}`)}}},lm=({observations:e,xType:t,temporalOrigin:n,spec:r,output:o,groupObservation:a})=>{const s=ba(r,e);for(const[i,c]of s){if(!Number.isFinite(i)||!Number.isFinite(c))continue;const l=t==="temporal"?um(i,n):i;o.push({x:l,y:c,groupObservation:a})}},um=(e,t)=>t===null?new Date(e):new Date((e-1)*ga+t),dm=({observations:e,spec:t,output:n,groupObservation:r})=>{const o=new Map;for(const i of e)o.has(i.x)||o.set(i.x,i.originalX);const a=[...o.keys()].sort((i,c)=>i-c);if(t.method==="loess"){const i=ba(t,e),c=new Map;for(const[l,u]of i)Number.isFinite(u)&&(c.has(l)||c.set(l,u));for(const l of a){const u=c.get(l),d=o.get(l);u===void 0||d===void 0||n.push({x:d,y:u,groupObservation:r})}return}const s=va(t,e);for(const i of a){const c=o.get(i),l=s.predict(i);c===void 0||!Number.isFinite(l)||n.push({x:c,y:l,groupObservation:r})}},ba=(e,t)=>e.method==="loess"?ue.regressionLoess().x(r=>r.x).y(r=>r.y).bandwidth(e.bandwidth)(t):va(e,t),va=(e,t)=>{const n=o=>o.x,r=o=>o.y;switch(e.method){case"linear":return ue.regressionLinear().x(n).y(r)(t);case"exponential":return ue.regressionExp().x(n).y(r)(t);case"logarithmic":return ue.regressionLog().x(n).y(r)(t);case"quadratic":return ue.regressionQuad().x(n).y(r)(t);case"power":return ue.regressionPow().x(n).y(r)(t);case"polynomial":return ue.regressionPoly().x(n).y(r).order(e.order)(t);case"loess":throw new Error("'loess' does not expose a 'predict' function")}},mm=(e,t,n,r,o)=>{const a=[],s=[],i=Object.fromEntries(r.map(c=>[c,[]]));return{push:({x:c,y:l,groupObservation:u})=>{a.push(c),s.push(l);for(const d of r)i[d]?.push(u[d]??null)},build:()=>{const c={[e]:{type:t,values:a,valueFormat:o.getValueFormat(e)},[n]:{type:"numeric",values:s,valueFormat:o.getValueFormat(n)}};for(const l of r)c[l]={type:o.getType(l),values:i[l]??[],valueFormat:o.getValueFormat(l)};return new M(c)}}},pm=(e,t)=>{const n={};for(const r of t){const o=e.getValues(r);n[r]=o[0]??null}return n};class fm extends Ie{constructor(){super("stat"),this.register("identity",new nm),this.register("count",new tm),this.register("smooth",new am),this.register("mean",new rm)}}const hm=({layer:e})=>{if(e.position==="stack")return;const t=v(e.mapping.y);if(t===null)return;let n=0,r=0;for(const o of e.data){const a=o[t];E(a)&&(n+=a,r+=Math.abs(a))}return{grandTotal:n,absoluteGrandTotal:r}},ym=({layer:e})=>{if(e.position!=="stack")return;const t=v(e.mapping.x);if(t===null||!e.data.hasVariable(g.yMin)||!e.data.hasVariable(g.yMax))return;const n=new Map;for(const o of e.data){const a=o[t],s=ge(o),i=j(o),c=ze(o),l=Le(o),u=Oo(o);if(!h(a)||!h(s)||!h(i)||!h(c)||!h(l)||!h(u))continue;const d=u>=0;if(Math.abs(u)===0)continue;const p=bn(o,t),f={yMin:s,yMax:i},y=n.get(p);if(y===void 0){n.set(p,{total:u,topPositive:d?f:null,bottomNegative:d?null:f,anchorXMin:c,anchorXMax:l});continue}y.total+=u,d?(y.topPositive===null||i>y.topPositive.yMax)&&(y.topPositive=f):(y.bottomNegative===null||s<y.bottomNegative.yMin)&&(y.bottomNegative=f)}const r=[];for(const[o,a]of n){const s=a.topPositive??a.bottomNegative;s!==null&&r.push({xKey:o,total:a.total,anchor:{xMin:a.anchorXMin,xMax:a.anchorXMax,yMin:s.yMin,yMax:s.yMax,direction:a.topPositive!==null?"positive":"negative"}})}return r};class gm extends Ee{constructor(t){super(),this.geomCompiler=t}dependencies(){return[]}compileLayer(t){const n={};if(this.geomCompiler.emitsStackTotals(t.geom)){const r=ym({layer:t});r!==void 0&&(n.stackTotals=r)}if(this.geomCompiler.emitsGrandTotal(t.geom)){const r=hm({layer:t});r!==void 0&&(n.grandTotal=r.grandTotal,n.absoluteGrandTotal=r.absoluteGrandTotal)}return{...t,summary:n}}}class bm extends se{constructor(t){super(),this.registry=t}key(t){return t.data}dependencies(t){return[t.transforms]}run(t){return t.transforms.reduce((n,r)=>this.registry.get(r.transformType).apply(n,r),t.data)}}class vm{constructor(){this.transformType="aggregate"}apply(t,n){const{options:r}=n,o={};for(const a of r.operations)o[a.as]={variableName:a.variableName,aggregation:a.op};return t.groupBy(...r.groupby).rollup(o)}}class Sm{constructor(){this.transformType="constant"}apply(t,n){const{options:r}=n;return t.addConstantVariable(r.variableName,r.type,r.value)}}class xm{constructor(){this.transformType="filter"}apply(t,n){const{options:r}=n;return t.filter(r.variableName,r.operator,r.value)}}class wm{constructor(){this.transformType="reshape"}apply(t,n){const{options:r}=n;return t.reshapeFromWideToLong({keep:r.keep,reshape:r.reshape,keyName:r.keyName,valueName:r.valueName})}}class Am{constructor(){this.transformType="sort"}apply(t,n){const{options:r}=n;return t.orderBy(r.variableName,r.direction??"asc")}}class Tm extends Ie{constructor(){super("transform"),this.register("aggregate",new vm),this.register("constant",new Sm),this.register("filter",new xm),this.register("reshape",new wm),this.register("sort",new Am)}}const Or={color:"categorical",size:"numeric",alpha:"numeric",strokeWidth:"numeric",lineType:"categorical"};class Mm extends Ee{constructor(t){super(),this.geomCompiler=t}dependencies(t){return[...kt].map(n=>t.scales[n])}compileLayer(t,n){const r=this.geomCompiler.getVisualAesthetics(t.geom),o=Lm(t.data,t.mapping,r,n.scales);return{...t,data:o}}}function Lm(e,t,n,r){let o=e;for(const a of n){const s=ie[a],i=ee(t[a]);if(i!==void 0){o=o.deriveVariable(s,Or[a],()=>i);continue}const c=v(t[a]),l=r[a];if(!l||l.kind!=="visual")continue;const u=Vm(a,c,l);u&&(o=o.deriveVariable(s,Or[a],u))}return o}const Vm=(e,t,n)=>{if(!t){if(e!=="color"||n.spec.scaleType!=="palette")return null;const r=n.map(null);return()=>r}return r=>h(r[t])?n.map(r[t]):null},km=["data","transform","constantMapping","layer","coordSetup","scale","positionMapper","visualMapper","coordTransform","summarise","guide","highlights","config","annotations"];class Sa{constructor(t,n,r,o,a,s,i,c,l,u,d,m,p,f,y){this.dataCompiler=t,this.specCompiler=n,this.transformCompiler=r,this.constantMappingCompiler=o,this.layerValidationCheck=a,this.layerCompiler=s,this.scaleCompiler=i,this.coordCompiler=c,this.positionMapperCompiler=l,this.visualMapperCompiler=u,this.guideCompiler=d,this.summariseCompiler=m,this.highlightsCompiler=p,this.configCompiler=f,this.annotationsCompiler=y,this.lastCompile=null,this.lastData=void 0,this.stages=[{name:"data",getStats:()=>this.dataCompiler.stats},{name:"transform",getStats:()=>this.transformCompiler.stats},{name:"constantMapping",getStats:()=>this.constantMappingCompiler.stats},{name:"layer",getStats:()=>this.layerCompiler.stats},{name:"coordSetup",getStats:()=>this.coordCompiler.setupStats},{name:"scale",getStats:()=>this.scaleCompiler.stats},{name:"positionMapper",getStats:()=>this.positionMapperCompiler.stats},{name:"visualMapper",getStats:()=>this.visualMapperCompiler.stats},{name:"coordTransform",getStats:()=>this.coordCompiler.transformStats},{name:"summarise",getStats:()=>this.summariseCompiler.stats},{name:"guide",getStats:()=>this.guideCompiler.stats},{name:"highlights",getStats:()=>this.highlightsCompiler.stats},{name:"config",getStats:()=>this.configCompiler.stats},{name:"annotations",getStats:()=>this.annotationsCompiler.stats}]}compile({input:t,data:n,ctx:r={}}){return this.trackCompile(()=>(this.lastData=n,this.runPipeline({spec:this.specCompiler.compile({input:t,ctx:r,dataset:this.dataCompiler.compile(n)})})))}recompile({spec:t,data:n}){return this.trackCompile(()=>n===void 0?this.runPipeline({spec:t}):(this.lastData=n,this.runPipeline({spec:Rt(t,{data:this.dataCompiler.compile(n)})})))}getCacheStats(){const t={};for(const{name:n,getStats:r}of this.stages)t[n]={...r()};return t}getLastCompile(){return this.lastCompile}trackCompile(t){if(!pe)return t();const n=this.getCacheStats(),r=performance.now(),o=t(),a=performance.now()-r,s={};for(const{name:i,getStats:c}of this.stages){const l=c();s[i]={hits:l.hits-n[i].hits,misses:l.misses-n[i].misses}}return this.lastCompile={stages:s,durationMs:a},o}runPipeline({spec:t}){return Tt({spec:t}).pipe(({spec:r})=>({spec:Rt(r,{data:this.transformCompiler.compile({data:r.data,transforms:r.transforms})})})).pipe(({spec:r})=>{const o=this.constantMappingCompiler.compile({data:r.data,mapping:r.mapping});return{spec:Rt(r,{data:o.data,mapping:o.mapping})}}).pipe(({spec:r})=>{const o={data:r.data,layers:r.layers,mapping:r.mapping,coords:r.coords,scales:r.scales};return this.layerValidationCheck.check({...o,coords:r.coords}),{layers:this.layerCompiler.compile(o)}}).pipe(({spec:r,layers:o})=>this.coordCompiler.setup({coordSpec:r.coords,scales:r.scales,layers:o})).pipe(({layers:r,scales:o})=>({scales:this.scaleCompiler.compile({layers:r,scales:o})})).pipe(({spec:r,scales:o})=>({config:this.configCompiler.compile({config:r.config,scales:o})})).pipe(({layers:r,scales:o})=>({layers:this.positionMapperCompiler.compile({layers:r,scales:o})})).pipe(({layers:r,scales:o})=>({layers:this.visualMapperCompiler.compile({layers:r,scales:o})})).pipe(({spec:r,layers:o})=>({layers:this.coordCompiler.transform({coordSpec:r.coords,layers:o})})).pipe(({layers:r})=>({layers:this.summariseCompiler.compile({layers:r})})).pipe(({spec:r,scales:o,layers:a,coordSystem:s})=>({guides:this.guideCompiler.compile({scales:o,config:r.config,layers:a,coordSystem:s,originalData:this.lastData})})).pipe(({spec:r,layers:o})=>({layers:this.highlightsCompiler.compile({layers:o,highlights:r.highlights,config:r.config})})).pipe(({spec:r,layers:o,coordSystem:a,scales:s})=>({annotations:this.annotationsCompiler.compile({annotations:r.annotations,layers:o,coordSystem:a,scales:s})})).result()}}const Em=e=>{const t=new Pi({geoms:e?.geoms}),n=new Ii(t),r=new fm,o=new tu,a=new bm(new Tm);return new Sa(new Mi,new ya,a,new Vs,new vl(a,new Sl(t,r)),new bl(a,new em(r),new Oi,n,new wl(new Vl)),new Pl(o),new Cs(new Ws(t)),new Nl(t),new Mm(n),new Xc(n),new gm(n),new al,new Ls,new gs(n))};function Im(e,t){return e.geom===t}const Vn="–",xa="n/a",N={timeZone:"UTC"},R=e=>t=>{if(!O(t))return Vn;try{return e(t)}catch{return xa}},ce=e=>t=>E(t)?e(t):Vn,kn=e=>t=>Qe(t)?t:Vn,Cm=2,_m=3,Fm=2,Dm=0,Rm=1,Nm=2,Pm=ts.humanizer({language:"en",spacer:"",delimiter:" ",languages:{en:{y:()=>"y",mo:()=>"mo",w:()=>"w",d:()=>"d",h:()=>"h",m:()=>"m",s:()=>"s",ms:()=>"ms"}}}),wa=({valueFormat:e,locale:t,numberFormat:n,intlOptions:r})=>ce(o=>{const a=typeof n.decimals=="number"?n.decimals:Cm,s=_n(o,a),{base:i,suffix:c}=Cn(o,n.abbreviation),l={...s,...So(e)?{style:"currency",currencyDisplay:"narrowSymbol",currency:e.iso}:{},...r};return`${Intl.NumberFormat(t,l).format(i)}${c}`}),En=({locale:e,numberFormat:t,intlOptions:n})=>ce(r=>{const{base:o,suffix:a}=Cn(r,t.abbreviation),i={..._n(o,t.decimals),...n};return`${Intl.NumberFormat(e,i).format(o)}${a}`}),In=e=>ce(t=>Pm(t)),Aa=({locale:e,intlOptions:t})=>ce(n=>Intl.NumberFormat(e,{maximumFractionDigits:0,...t}).format(n)),Ta=({locale:e,numberFormat:t,intlOptions:n})=>ce(r=>{const o=_n(r,t.decimals);return Intl.NumberFormat(e,{...o,...n,style:"percent"}).format(r)}),Cn=(e,t="none")=>{switch(t){case"none":return{base:e,suffix:""};case"auto":{const n=Om(e);return Cn(e,n)}default:return{base:e/We[t],suffix:t}}},_n=(e,t)=>{if(typeof t=="number")return{minimumFractionDigits:t,maximumFractionDigits:t};const n=Math.ceil(Math.log10(Math.abs(e))),r=n>=_m?Dm:n===Fm?Rm:Nm;return{minimumFractionDigits:t==="auto"?0:r,maximumFractionDigits:r}},Om=e=>{const t=Math.abs(e);return t>=We.b?"b":t>=We.m?"m":t>=We.k?"k":"none"},Bm=({locale:e,intlOptions:t})=>R(n=>Intl.DateTimeFormat(e,{dateStyle:"medium",...N,...t}).format(n)),$m=({locale:e,intlOptions:t})=>R(n=>{const r=Intl.DateTimeFormat(e,{dateStyle:"medium",timeStyle:"medium",...N,...t}).formatToParts(n);return Gm(r.map(Um))}),Ma=({locale:e,intlOptions:t})=>R(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"long",...N,...t}).format(n)),La=({locale:e,intlOptions:t})=>R(n=>Intl.DateTimeFormat(e,{month:"long",...N,...t}).format(n)),Fn=({locale:e,intlOptions:t})=>R(n=>Intl.DateTimeFormat(e,{month:"short",year:"numeric",...N,...t}).format(n)),Dn=e=>R(t=>`Q${Math.floor(t.getUTCMonth()/3)+1} ${t.getUTCFullYear()}`),Va=({locale:e,intlOptions:t})=>R(n=>{const r=L.addDays(n,6);return Intl.DateTimeFormat(e,{day:"numeric",month:"long",...N,...t,year:void 0}).formatRange(n,r)}),ka=({locale:e,intlOptions:t})=>R(n=>{const r=L.addDays(n,6);return Intl.DateTimeFormat(e,{dateStyle:"medium",...N,...t}).formatRange(n,r)}),Rn=({locale:e,intlOptions:t})=>R(n=>Intl.DateTimeFormat(e,{year:"numeric",...N,...t}).format(n)),Ea=({locale:e,intlOptions:t})=>R(n=>Intl.DateTimeFormat(e,{timeStyle:"short",...N,...t}).format(n)),Gm=e=>e.map(t=>t.value).join(""),Um=e=>e.type!=="literal"||e.value!==", "?e:{type:"literal",value:" • "},Ym=1,Wm=4,Hm=1,Br=1e3,Km=({valueFormat:e,locale:t,tickValues:n,intlOptions:r})=>ce(o=>{const s={...Pn(o,n),notation:"compact",...So(e)?{style:"currency",currencyDisplay:"narrowSymbol",currency:e.iso}:{},...r};return Nn(o,t,s)}),zm=({locale:e,tickValues:t,intlOptions:n})=>ce(r=>{const a={...Pn(r,t),notation:"compact",...n};return Nn(r,e,a)}),Xm=({locale:e,tickValues:t,intlOptions:n})=>ce(r=>{const a={...Pn(r,t),notation:"compact",...n,style:"percent"};return Nn(r,e,a)}),Nn=(e,t,n)=>Intl.NumberFormat(t,n).formatToParts(e).map(o=>o.type==="compact"?o.value.toLowerCase():o.value).join(""),Ia=e=>Math.abs(e)>Br?Ia(e/Br):Number.isInteger(e),jm=e=>{if(e.length<2)return!1;const[t,n]=e;return typeof t!="number"||typeof n!="number"?!1:Math.abs(n-t)<Ym},Pn=(e,t)=>Ia(e)?{minimumFractionDigits:0,maximumFractionDigits:0}:jm(t)?{minimumFractionDigits:0,maximumFractionDigits:Wm}:{minimumFractionDigits:0,maximumFractionDigits:Hm},qm=({locale:e,intlOptions:t})=>R(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"short",...N,...t}).format(n)),Qm=({locale:e,intlOptions:t})=>R(n=>Intl.DateTimeFormat(e,{month:"short",...N,...t}).format(n)),Zm=({locale:e,intlOptions:t})=>R(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"short",...N,...t}).format(n)),Jm=({locale:e,intlOptions:t})=>R(n=>Intl.DateTimeFormat(e,{timeStyle:"short",...N,...t}).format(n)),On=e=>{const{valueFormat:t}=e;switch(t.type){case"currency":return Km(e);case"date":case"datetime":return qm(e);case"day_month":case"weekly_date_range":case"weekly_date_range_with_year":return Zm(e);case"decimal":case"integer":return zm(e);case"duration":return In();case"month":return Qm(e);case"month_year":return Fn(e);case"percentage":return Xm(e);case"quarter":return Dn();case"text":return kn();case"time":return Jm(e);case"year":return Rn(e);case"lookup":return On({...e,valueFormat:t.fallback});default:{const n=t;throw new Error(`Unhandled value format: ${n.type}`)}}},ep=40,tp=60,$r=8,np=50,rp=1/3,op=1/4,Kt="…",ap=(e,t,n)=>{if(t<=0||e.length===0)return"";if(n(e)<=t)return e;if(n(Kt)>t)return"";let r=0,o=e.length-1,a=0;for(;r<=o;){const s=r+o>>>1,i=e.slice(0,s)+Kt;n(i)<=t?(a=s,r=s+1):o=s-1}return e.slice(0,a)+Kt},sp=e=>e.formattedAxis.position==="top"||e.formattedAxis.position==="bottom"?ip(e):cp(e),ip=({formattedAxis:e,bandwidthPx:t,panelRect:n,measureLabel:r})=>{const{widths:o,maxWidth:a,maxHeight:s}=Ca(e.ticks,r),i=t-$r;if(a<=i)return{...e,labelRotation:0,labelMaxWidthPx:null};if(t>=np){const l=an(i);return{...e,ticks:on(e.ticks,o,l,r),labelRotation:0,labelMaxWidthPx:l}}if(s+$r>t)return{...e,ticks:[],labelRotation:0,labelMaxWidthPx:null};const c=an(n.height*rp);return{...e,ticks:on(e.ticks,o,c,r),labelRotation:-90,labelMaxWidthPx:c}},cp=({formattedAxis:e,bandwidthPx:t,panelRect:n,measureLabel:r})=>{const{widths:o,maxWidth:a,maxHeight:s}=Ca(e.ticks,r);if(s>t)return{...e,ticks:[],labelRotation:0,labelMaxWidthPx:null};const i=an(n.width*op);return a<=i?{...e,labelRotation:0,labelMaxWidthPx:null}:{...e,ticks:on(e.ticks,o,i,r),labelRotation:0,labelMaxWidthPx:i}},Ca=(e,t)=>{const n=[];let r=0,o=0;for(const a of e){const{width:s,height:i}=t(a.formattedLabel);n.push(s),s>r&&(r=s),i>o&&(o=i)}return{widths:n,maxWidth:r,maxHeight:o}},on=(e,t,n,r)=>{const o=a=>r(a).width;return e.map((a,s)=>(t[s]??0)<=n?a:{...a,formattedLabel:ap(a.formattedLabel,n,o)})},an=e=>Math.max(0,Math.floor(e)),lp=(e,t,n,r)=>{if(e.length===0)return!0;const o=t==="top"||t==="bottom",a=o?tp:ep;let s=n-(e.length-1)*a;for(const i of e){const{width:c,height:l}=r(i);if(s-=o?c:l,s<0)return!1}return!0},up=({axis:e,availableSpacePx:t,measureLabel:n,resolveFormatter:r})=>{const{tickCandidates:o,position:a}=e;if(o.length===0)return[];const s=new Map,i=d=>{const m=s.get(d);if(m)return m;const p=o[d],f=p?dp(p.ticks,r(p)):[];return s.set(d,f),f};let c=0,l=o.length-1,u=-1;for(;c<=l;){const d=c+l>>>1,p=i(d).map(f=>f.formattedLabel);lp(p,a,t,n)?(u=d,c=d+1):l=d-1}return u>=0?i(u):i(0)},dp=(e,t)=>e.map(n=>({...n,formattedLabel:t(n.value)})),zt=6,Xt=6,jt=15,qt=5,Qt=15,Bn=(e,t)=>{switch(e){case"small":return{arrowStartGap:zt,arrowEndGap:Xt,offsetFromHigherObservation:jt,arrowheadSize:qt,curveRadius:Qt,strokeWidth:2,labelLineHeight:12*t,labelPaddingX:6,labelPaddingY:3,labelStrokeWidth:1,labelFontWeight:500};case"medium":return{arrowStartGap:zt*1.5,arrowEndGap:Xt*1.5,offsetFromHigherObservation:jt*1.25,arrowheadSize:qt*1.5,curveRadius:Qt*1.25,strokeWidth:3,labelLineHeight:16*t,labelPaddingX:8,labelPaddingY:4,labelStrokeWidth:1.5,labelFontWeight:500};case"large":return{arrowStartGap:zt*2,arrowEndGap:Xt*2,offsetFromHigherObservation:jt*1.75,arrowheadSize:qt*2.5,curveRadius:Qt*1.5,strokeWidth:5,labelLineHeight:20*t,labelPaddingX:10,labelPaddingY:5,labelStrokeWidth:2,labelFontWeight:600}}},mp=e=>{const t=C({...e,valueFormat:e.valueFormat.fallback}),n={};for(const[o,a]of Object.entries(e.valueFormat.cases))n[o]=C({...e,valueFormat:a});const r=e.valueFormat.byVariable;return(o,a)=>{if(a===void 0||a[r]===void 0)return t(o);const s=V(a[r]),i=n[s];return i!==void 0?i(o,a):t(o)}},C=e=>{switch(e.valueFormat.type){case"currency":return wa(e);case"date":return Bm(e);case"datetime":return $m(e);case"day_month":return Ma(e);case"decimal":return En(e);case"duration":return In();case"integer":return Aa(e);case"month":return La(e);case"month_year":return Fn(e);case"percentage":return Ta(e);case"quarter":return Dn();case"text":return kn();case"weekly_date_range":return Va(e);case"weekly_date_range_with_year":return ka(e);case"year":return Rn(e);case"time":return Ea(e);case"lookup":return mp({...e,valueFormat:e.valueFormat});default:{const t=e.valueFormat;throw new Error(`Unhandled value format: ${t.type}`)}}},Zt={abbreviation:"none",decimals:"auto"},_a=({locale:e,kind:t,startValue:n,endValue:r})=>{if(n===null||r===null)return xa;switch(t){case"absolute-difference":return En({locale:e,numberFormat:Zt,intlOptions:{signDisplay:"always"}})(r-n);case"relative-difference":{const o=r-n;if(o===0)return"0%";const a=o/n;return a===Number.POSITIVE_INFINITY?"∞":a===Number.NEGATIVE_INFINITY?"-∞":C({valueFormat:{type:"percentage"},locale:e,numberFormat:Zt,intlOptions:{signDisplay:"always"}})(a)}case"proportion":{if(r-n===0)return"=";const o=r/n;return o===Number.POSITIVE_INFINITY?"∞":o===Number.NEGATIVE_INFINITY?"-∞":`${C({valueFormat:{type:"decimal"},locale:e,numberFormat:Zt,intlOptions:{maximumFractionDigits:1}})(o)}x`}}},pp=e=>{const t=e.padding??0,n=Gr(e.rows,t),r=Gr(e.cols,t);return{rows:n.tracks,cols:r.tracks,placements:gp(e.placements,n.nameToIndex,r.nameToIndex),width:e.containerSize.width,height:e.containerSize.height}},fp=e=>{const t=Ur(e.rows,e.height),n=Ur(e.cols,e.width),r=Yr(t),o=Yr(n),a=new Map;for(const s of e.placements){const i=s.rowSpan??1,c=s.colSpan??1,l=o[s.col]??0,u=r[s.row]??0,d=Wr(n,s.col,c),m=Wr(t,s.row,i);a.set(s.name,{x:l,y:u,width:Math.max(0,d),height:Math.max(0,m)})}return a},Gr=(e,t)=>{const n=[],r=new Map;t>0&&n.push({type:"fixed",pixels:t});for(let o=0;o<e.length;o++){const a=e[o];if(!a)continue;r.set(a.name,n.length),n.push(hp(a));const s=yp(e,o);if(Fa(a)&&s){const i=a.gaps?.after??0,c=s.gaps?.before??0,l=Math.max(i,c);l>0&&n.push({type:"fixed",pixels:l})}}return t>0&&n.push({type:"fixed",pixels:t}),{tracks:n,nameToIndex:r}},hp=e=>typeof e.size=="number"?{type:"fixed",pixels:e.size}:{type:"flex",weight:e.size.flex},Fa=e=>typeof e.size=="number"?e.size>0:e.size.flex>0,yp=(e,t)=>{for(let n=t+1;n<e.length;n++){const r=e[n];if(r&&Fa(r))return r}},gp=(e,t,n)=>{const r=[];for(const o of e){const a=t.get(o.row),s=n.get(o.col);if(a===void 0||s===void 0)continue;const i=o.rowEnd!==void 0?t.get(o.rowEnd):a,c=o.colEnd!==void 0?n.get(o.colEnd):s;i===void 0||c===void 0||r.push({name:o.name,row:a,col:s,rowSpan:Math.max(1,i-a+1),colSpan:Math.max(1,c-s+1)})}return r},Ur=(e,t)=>{let n=0,r=0;for(const a of e)a.type==="fixed"?n+=a.pixels:r+=a.weight;const o=Math.max(0,t-n);return e.map(a=>a.type==="fixed"?a.pixels:r===0?0:a.weight/r*o)},Yr=e=>{const t=new Array(e.length);let n=0;for(let r=0;r<e.length;r++)t[r]=n,n+=e[r]??0;return t},Wr=(e,t,n)=>{let r=0;const o=Math.min(t+n,e.length);for(let a=t;a<o;a++)r+=e[a]??0;return r},Da=24,Z={header:{after:10,before:0},headline:{after:4,before:0},topLegend:{after:16,before:0},topAxisLabel:{after:4,before:0},topAxis:{after:0,before:0},panel:{after:0,before:0},bottomAxis:{after:4,before:0},bottomAxisLabel:{after:16,before:0},bottomLegend:{after:10,before:16}},lt={leftLegend:{after:10,before:0},leftAxis:{after:4,before:0},panel:{after:4,before:0},rightAxis:{after:10,before:0}},$n={top:0,right:0,bottom:0,left:0},bp=(e,t,n,r=$n)=>{const a=n.axes.top>0||n.axesLabels.top>0?n.axesLabels.top:Math.max(n.axesLabels.top,n.axesLabels.left,n.axesLabels.right);return pp({rows:[{name:"header",size:t.headerSize.height,gaps:Z.header},{name:"topLegend",size:n.legends.top,gaps:Z.topLegend},{name:"headline",size:n.headline,gaps:Z.headline},{name:"topAxisLabel",size:a,gaps:Z.topAxisLabel},{name:"topAxis",size:n.axes.top,gaps:Z.topAxis},{name:"topAnnotation",size:r.top},{name:"panel",size:{flex:1},gaps:Z.panel},{name:"bottomAxis",size:n.axes.bottom,gaps:Z.bottomAxis},{name:"bottomAxisLabel",size:n.axesLabels.bottom,gaps:Z.bottomAxisLabel},{name:"bottomLegend",size:n.legends.bottom,gaps:Z.bottomLegend},{name:"footer",size:t.footerSize.height}],cols:[{name:"leftLegend",size:n.legends.left,gaps:lt.leftLegend},{name:"leftAxis",size:n.axes.left,gaps:lt.leftAxis},{name:"panel",size:{flex:1},gaps:lt.panel},{name:"rightAnnotation",size:r.right},{name:"rightAxis",size:n.axes.right,gaps:lt.rightAxis},{name:"rightLegend",size:n.legends.right}],placements:[{name:"header",row:"header",col:"leftLegend",colEnd:"rightLegend"},{name:"headline",row:"headline",col:"leftLegend",colEnd:"rightLegend"},{name:"footer",row:"footer",col:"leftLegend",colEnd:"rightLegend"},{name:"plot",row:"topAxisLabel",rowEnd:"bottomAxisLabel",col:"leftAxis",colEnd:"rightAxis"},{name:"panel",row:"panel",col:"panel"},...vp(n.axes),...Sp(n.axesLabels,n.axes),...xp(n.legends)],containerSize:e,padding:Da})},vp=e=>{const t=[];return e.top>0&&t.push({name:"topAxis",row:"topAxis",col:"panel"}),e.bottom>0&&t.push({name:"bottomAxis",row:"bottomAxis",col:"panel"}),e.left>0&&t.push({name:"leftAxis",row:"panel",col:"leftAxis"}),e.right>0&&t.push({name:"rightAxis",row:"panel",col:"rightAxis"}),t},Sp=(e,t)=>{const n=[];return e.top>0||t.top>0?(e.top>0&&n.push({name:"topAxisLabel",row:"topAxisLabel",col:"panel"}),e.left>0&&n.push({name:"leftAxisLabel",row:"topAxis",col:"leftAxis"}),e.right>0&&n.push({name:"rightAxisLabel",row:"topAxis",col:"rightAxis"})):(e.left>0&&n.push({name:"leftAxisLabel",row:"topAxisLabel",col:"leftAxis"}),e.right>0&&n.push({name:"rightAxisLabel",row:"topAxisLabel",col:"rightAxis"})),e.bottom>0&&n.push({name:"bottomAxisLabel",row:"bottomAxisLabel",col:"panel"}),n},xp=e=>{const t=[];return e.top>0&&t.push({name:"topLegend",row:"topLegend",col:"leftAxis",colEnd:"rightAxis"}),e.bottom>0&&t.push({name:"bottomLegend",row:"bottomLegend",col:"leftAxis",colEnd:"rightAxis"}),e.left>0&&t.push({name:"leftLegend",row:"panel",col:"leftLegend"}),e.right>0&&t.push({name:"rightLegend",row:"panel",col:"rightLegend"}),t},wp=({annotations:e,mainAxis:t,panelRect:n,textScale:r,locale:o,measureLabel:a,currentOverflow:s})=>{if(e.differenceArrows.length===0)return $n;const i=t==="y",c=n.height+s.top,l=n.width+s.right;let u=0,d=0;for(const m of e.differenceArrows){const{start:p,end:f,size:y,label:b}=m;if(!Hr(p.x,p.y)||!Hr(f.x,f.y))continue;const x=Bn(y,r),S=x.offsetFromHigherObservation+x.arrowheadSize+x.arrowEndGap,w=_a({locale:o,kind:b,startValue:p.measurementValue,endValue:f.measurementValue}),k=a(w,y);if(i){const _=Math.max(p.x,f.x),H=S+k.width/2+x.labelPaddingX;d=Math.max(d,Kr(H,_,l))}else{const _=Math.max(p.y,f.y),H=S+x.labelLineHeight/2+x.labelPaddingY;u=Math.max(u,Kr(H,_,c))}}return{top:Math.ceil(u),right:Math.ceil(d),bottom:0,left:0}},Hr=(e,t)=>e>=0&&e<=1&&t>=0&&t<=1,Kr=(e,t,n)=>{if(t<=0)return 0;const r=(e-(1-t)*n)/t;return Math.max(0,r)},Ap=["top","right","bottom","left"],Jt=(e,t)=>{const n={};for(const r of Ap){const o=e.get(`${r}${t}`);o&&(n[r]=o)}return n},sn=["large","medium","small"],Tp=({size:e,availableWidth:t,measureStripWidth:n})=>{if(e!=="auto")return e;for(const r of sn)if(n(r)<=t)return r;return"small"},Mp=({size:e,availableWidth:t,measureStripWidth:n})=>{const r=e==="auto"?0:sn.indexOf(e);for(const o of sn.slice(r))if(n(o)<=t)return o;return null},Lp=({itemWidths:e,gap:t,availableWidth:n})=>{let r=0,o=0;for(const a of e){const s=o===0?a:r+t+a;if(s>n)break;r=s,o+=1}return o},Vp=({headline:e,containerSize:t,measurer:n})=>{if(Ra(e))return 0;const r=Na(e,t.width,n);return n.measureHeadline(e.formatted,r).height},kp=({headline:e,layout:t,containerSize:n,measurer:r,itemGap:o})=>{if(Ra(e)){const i=Ep(t.panel,e.innerRadius),c=Mp({size:e.size,availableWidth:i.width,measureStripWidth:Pa(e,r)});return c===null?null:{rect:i,resolvedSize:c,visibleItemCount:1}}const a=Na(e,n.width,r);if(e.formatted.kind!=="perGroup")return{rect:t.headline,resolvedSize:a,visibleItemCount:1};const s=Lp({itemWidths:r.measureHeadlineItemWidths(e.formatted,a),gap:o,availableWidth:t.headline.width});return s===0?null:{rect:t.headline,resolvedSize:a,visibleItemCount:s}},Ra=e=>e.formatted.kind==="grandTotal"&&e.position==="center"&&e.innerRadius>0,Ep=(e,t)=>{const n=Math.min(e.width,e.height)/2,r=t*n*Math.SQRT2,o=e.x+e.width/2,a=e.y+e.height/2;return{x:o-r/2,y:a-r/2,width:r,height:r}},Na=(e,t,n)=>Tp({size:e.size,availableWidth:t,measureStripWidth:Pa(e,n)}),Pa=(e,t)=>n=>t.measureHeadline(e.formatted,n).width,$e={x:0,y:0,width:0,height:0},Ip="0000";class Cp{constructor(t){this.measurer=t}compile(t){const n=Tt({axes:t.axes,numberFormat:t.numberFormat,formattedLegends:t.formattedLegends,containerSize:t.containerSize,externalMeasurements:t.externalMeasurements,annotationOverflow:$n,headline:t.headline,locale:t.formattingLocale??t.parsingLocale}).pipe(({axes:r,numberFormat:o,locale:a})=>{const s=r.filter(i=>i.geometry!=="linear").map(i=>Fp(i,jr(i,a,o)));return{cartesianAxes:r.filter(i=>i.geometry==="linear"),formattedPolarAxes:s,polarMargin:Dp(s,this.measurer.measureTickLabel)}}).pipe(({cartesianAxes:r,numberFormat:o,locale:a})=>({axisBundles:r.map(s=>({axis:s,resolveFormatter:jr(s,a,o),formatted:this.seedAxis(s)}))})).pipe(({axisBundles:r,formattedLegends:o,containerSize:a,externalMeasurements:s,annotationOverflow:i,headline:c,polarMargin:l})=>({layout:this.resolveLayout({axes:r.map(u=>u.formatted),formattedLegends:o,containerSize:a,externalMeasurements:s,annotationOverflow:i,headline:c,polarMargin:l})})).pipe(({axisBundles:r,layout:o})=>({axisBundles:r.map(a=>Xr(a.axis.position)?{...a,formatted:this.finalizeAxis(a.axis,a.resolveFormatter,o.panel)}:a)})).pipe(({axisBundles:r,formattedLegends:o,containerSize:a,externalMeasurements:s,annotationOverflow:i,headline:c,polarMargin:l})=>({layout:this.resolveLayout({axes:r.map(u=>u.formatted),formattedLegends:o,containerSize:a,externalMeasurements:s,annotationOverflow:i,headline:c,polarMargin:l})})).pipe(({axisBundles:r,layout:o})=>({formattedAxes:r.map(a=>Xr(a.axis.position)?a.formatted:this.finalizeAxis(a.axis,a.resolveFormatter,o.panel))})).pipe(({formattedAxes:r,formattedLegends:o,containerSize:a,externalMeasurements:s,annotationOverflow:i,headline:c,polarMargin:l})=>({layout:this.resolveLayout({axes:r,formattedLegends:o,containerSize:a,externalMeasurements:s,annotationOverflow:i,headline:c,polarMargin:l})})).pipe(({formattedAxes:r,formattedLegends:o,containerSize:a,externalMeasurements:s,layout:i,annotationOverflow:c,headline:l,polarMargin:u,locale:d})=>{const m=this.measureAnnotationOverflow(t,i.panel,d,c);return m===c?{formattedAxes:r,layout:i}:{formattedAxes:r,layout:this.resolveLayout({axes:r,formattedLegends:o,containerSize:a,externalMeasurements:s,annotationOverflow:m,headline:l,polarMargin:u})}}).result();return{formattedAxes:n.formattedAxes,layout:n.layout,formattedPolarAxes:n.formattedPolarAxes}}measureAnnotationOverflow(t,n,r,o){if(!t.annotations||t.annotations.differenceArrows.length===0||t.coordSystem?.type!=="cartesian")return o;const a=wp({annotations:t.annotations,mainAxis:t.coordSystem.mainAxis,panelRect:n,textScale:t.textScale??1,locale:r,measureLabel:this.measurer.measureDifferenceArrowLabel,currentOverflow:o});return a.top===o.top&&a.right===o.right?o:a}seedAxis(t){const{tickCandidates:n,...r}=t;return{...r,ticks:[{value:0,position:0,formattedLabel:Ip}],labelRotation:0,labelMaxWidthPx:null}}finalizeAxis(t,n,r){const a=t.position==="top"||t.position==="bottom"?r.width:r.height,s=up({axis:t,availableSpacePx:a,measureLabel:this.measurer.measureTickLabel,resolveFormatter:n}),{tickCandidates:i,...c}=t,l={...c,ticks:s,labelRotation:0,labelMaxWidthPx:null};if(t.scaleType==="discrete"&&t.bandwidth!==void 0){const u=t.bandwidth*a;return sp({formattedAxis:l,bandwidthPx:u,panelRect:r,measureLabel:this.measurer.measureTickLabel})}return l}resolveLayout({axes:t,formattedLegends:n,containerSize:r,externalMeasurements:o,annotationOverflow:a,headline:s,polarMargin:i}){const c=this.measureGuides(t,n,s,r,i),l=bp(r,o,c,a),u=fp(l);return{header:u.get("header")??$e,headline:u.get("headline")??$e,footer:u.get("footer")??$e,plot:u.get("plot")??$e,panel:u.get("panel")??$e,axes:Jt(u,"Axis"),axisLabels:Jt(u,"AxisLabel"),legends:Jt(u,"Legend")}}measureGuides(t,n,r,o,a){const s={...a},i={top:0,right:0,bottom:0,left:0};for(const l of t)l.isVisible&&(s[l.position]=this.measurer.measureAxis(l),l.label!==null&&(i[l.position]=this.measurer.measureAxisLabel(l)));const c={top:0,right:0,bottom:0,left:0};for(const l of n)c[l.position]=this.measurer.measureLegend(l);return{axes:s,axesLabels:i,legends:c,headline:this.measureHeadlineBand(r,o)}}measureHeadlineBand(t,n){return t===void 0?0:Vp({headline:t,containerSize:n,measurer:this.measurer})}}const zr=5,ut=8,Xr=e=>e==="left"||e==="right",_p=e=>{const[t,...n]=e.tickCandidates;if(t)return e.geometry==="circular"?t:n.reduce((r,o)=>Math.abs(o.ticks.length-zr)<Math.abs(r.ticks.length-zr)?o:r,t)},Fp=(e,t)=>{const{tickCandidates:n,...r}=e,o=_p(e);if(!o)return{...r,ticks:[],labelRotation:0,labelMaxWidthPx:null};const a=t(o),s=o.ticks.map(i=>({...i,formattedLabel:a(i.value)}));return{...r,ticks:s,labelRotation:0,labelMaxWidthPx:null}},Dp=(e,t)=>{const n=e.find(a=>a.geometry==="circular");if(!n||n.ticks.length===0)return{top:0,right:0,bottom:0,left:0};let r=0,o=0;for(const a of n.ticks){const s=t(a.formattedLabel);r=Math.max(r,s.width),o=Math.max(o,s.height)}return{top:o+ut,bottom:o+ut,left:r+ut,right:r+ut}},jr=(e,t,n)=>{const r=e.tickCandidates.flatMap(a=>a.ticks.map(s=>s.value)),o=new WeakMap;return a=>{const s=o.get(a);if(s)return s;const i=On({valueFormat:a.valueFormat??e.valueFormat,locale:t,numberFormat:n,tickValues:r});return o.set(a,i),i}};function Rp(e,t,n,r){const o=new Map;if(!n||n.kind!=="visual"||n.domain.length<=1)return o;const a=new Map(t.map(s=>[s.id,s.swatchShape]));for(const s of e){if(s.geom!=="rule"||s.stat.type!=="mean")continue;const i=s.transforms.find(y=>y.transformType==="filter"&&y.options.operator==="eq"),c=v(s.mapping.y);let l,u,d;if(i?.transformType==="filter"&&typeof i.options.value=="string")l="color",u=i.options.variableName,d=i.options.value;else if(c!==null)l="y",u=c,d=c;else continue;const m=Np(e,l,u);if(m===null)continue;const p=a.get(m.id);if(p===void 0)continue;const f=n.map(d);Qe(f)&&o.set(s.id,{shape:Xe(p,r),color:f})}return o}function Np(e,t,n){let r=null;for(const o of e)if(o.geom!=="rule"&&(r===null&&(r=o),v(o.mapping[t])===n))return o;return r}function je(e,t){return e==="x"?t.x:t.y}function Ft(e,t){return e==="x"?t.y:t.x}function Pp(e,t){return{main:je(e,t),cross:Ft(e,t)}}function Op(e){return e.type==="cartesian"}const Gn=12,Bp=4,$p=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=_e(n),o=j(n)??te(n);if(r===null||o===null||r<0||r>1||o<0||o>1)continue;const a=e.formatLabel(n);if(a==="")continue;const{width:s,height:i}=e.measureDataLabel("dataLabel",a),c=r*e.panelRect.width,l=(1-o)*e.panelRect.height-Gn-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:c,y:l,text:a,width:s,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},Gp={place:$p,getPercentageValueStrategy:e=>e.position==="fill"?"fill":Y(e.position)?"stack":"none"},en=4,dt=6,Up=e=>{const t=[],n=Y(e.layer.position),r=e.coordSystem.mainAxis==="y";if(e.layer.dataLabels.showDataLabels){const{entries:o,shouldRotate:a}=Wp({layer:e.layer,mainAxis:e.coordSystem.mainAxis,panelRect:e.panelRect,measureDataLabel:e.measureDataLabel,formatLabel:e.formatLabel,isFlipped:r,getObservationKey:e.getObservationKey});for(const s of o){const i=Xp({mainAxis:e.coordSystem.mainAxis,isStacked:n,isNegativeBar:s.isNegative,shouldRotate:a,bounds:s.bounds,labelWidth:s.labelWidth,labelHeight:s.labelHeight,panelWidth:e.panelRect.width,panelHeight:e.panelRect.height});i!==null&&t.push({layerId:e.layer.id,key:s.key,x:i.x,y:i.y,text:s.text,width:s.labelWidth,height:s.labelHeight,isRotated:i.isRotated,target:"observation",position:i.position})}}if(e.layer.dataLabels.showStackTotals){const o=Zp({layer:e.layer,mainAxis:e.coordSystem.mainAxis,panelRect:e.panelRect,measureDataLabel:e.measureDataLabel,formatAbsolute:e.formatAbsolute});for(const a of o)t.push(a)}return t},Yp={place:Up,getPercentageValueStrategy:e=>e.position==="fill"?"fill":Y(e.position)?"stack":"absoluteGrandTotal"},Wp=({layer:e,mainAxis:t,panelRect:n,measureDataLabel:r,formatLabel:o,isFlipped:a,getObservationKey:s})=>{const i=[];let c=!1;const l=v(e.mapping.y);for(const u of e.data){const d=Hp(t,u);if(d===null)continue;const m=o(u);if(m==="")continue;const{width:p,height:f}=r("dataLabel",m),y=Oa(d,n);p>y.width&&(c=!0);const b=l===null?null:u[l],x=E(b)&&b<0;i.push({key:s(u),isNegative:x,text:m,labelWidth:p,labelHeight:f,bounds:y})}return{entries:i,shouldRotate:!a&&c}},Oa=(e,t)=>({x:e.x*t.width,y:e.y*t.height,width:e.width*t.width,height:e.height*t.height}),Ba=(e,t,n,r,o)=>{if(e==="x"){let i=1-o,c=o-r;return c<0&&(i+=c,c=-c),{x:t,y:i,width:n-t,height:c}}let a=t,s=n-t;return s<0&&(a+=s,s=-s),{x:a,y:1-o,width:s,height:o-r}},Hp=(e,t)=>{const n=ze(t),r=Le(t),o=ge(t),a=j(t)??te(t);return n===null||r===null||o===null||a===null?null:Ba(e,n,r,o,a)},Kp=(e,t)=>{const{xMin:n,xMax:r,yMin:o,yMax:a}=t.anchor;return Ba(e,n,r,o,a)},zp=(e,t)=>e==="x"?t?"bottom":"top":t?"left":"right",$a=(e,t,n)=>n?{width:t,height:e}:{width:e,height:t},Xp=e=>e.isStacked?jp({bounds:e.bounds,labelWidth:e.labelWidth,labelHeight:e.labelHeight,isRotated:e.shouldRotate}):Qp({edge:zp(e.mainAxis,e.isNegativeBar),bounds:e.bounds,labelWidth:e.labelWidth,labelHeight:e.labelHeight,isRotated:e.shouldRotate,panelWidth:e.panelWidth,panelHeight:e.panelHeight}),jp=({bounds:e,labelWidth:t,labelHeight:n,isRotated:r})=>{const o=$a(t,n,r);return o.width>e.width||o.height>e.height?null:{x:e.x+e.width/2,y:e.y+e.height/2,isRotated:r,position:"inside"}},qp=(e,t,n,r)=>{switch(e){case"top":return{edgeCoord:t.y,outwardSign:-1,panelExtent:r};case"bottom":return{edgeCoord:t.y+t.height,outwardSign:1,panelExtent:r};case"left":return{edgeCoord:t.x,outwardSign:-1,panelExtent:n};case"right":return{edgeCoord:t.x+t.width,outwardSign:1,panelExtent:n}}},Qp=({edge:e,bounds:t,labelWidth:n,labelHeight:r,isRotated:o,panelWidth:a,panelHeight:s})=>{const i=e==="top"||e==="bottom",c=t.x+t.width/2,l=t.y+t.height/2,u=$a(n,r,o),d=i?u.height:u.width,m=i?u.width:u.height,p=i?t.height:t.width,f=i?t.width:t.height,y=d/2,{edgeCoord:b,outwardSign:x,panelExtent:S}=qp(e,t,a,s);if(d+en<p){if(m>f)return null;if(o)return{x:c,y:l,isRotated:!0,position:"inside"};const k=b-x*(y+en);return{...i?{x:c,y:k}:{x:k,y:l},isRotated:!1,position:"inside"}}const w=b+x*(y+en);return w-y<0||w+y>S?null:{...i?{x:c,y:w}:{x:w,y:l},isRotated:o,position:"outside"}},Zp=({layer:e,mainAxis:t,panelRect:n,measureDataLabel:r,formatAbsolute:o})=>{const a=[],s=e.summary.stackTotals;if(s===void 0||s.length===0)return a;const i=t==="y";for(const c of s){const l=Oa(Kp(t,c),n),u=o(c.total),{width:d,height:m}=r("stackTotal",u),p=c.anchor.direction==="positive";let f,y;i?(f=p?l.x+l.width+dt+d/2:l.x-dt-d/2,y=l.y+l.height/2):(f=l.x+l.width/2,y=p?l.y-dt-m/2:l.y+l.height+dt+m/2),a.push({layerId:e.id,key:`${e.id}:stack:${c.xKey}`,x:f,y,text:u,width:d,height:m,isRotated:!1,target:"aggregate",position:"outside"})}return a},Jp=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=_e(n),o=te(n);if(r===null||o===null||r<0||r>1||o<0||o>1)continue;const a=e.formatLabel(n);if(a==="")continue;const{width:s,height:i}=e.measureDataLabel("dataLabel",a),c=r*e.panelRect.width,l=(1-o)*e.panelRect.height-Gn-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:c,y:l,text:a,width:s,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},ef={place:Jp,getPercentageValueStrategy:()=>"none"},tf=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=_e(n),o=te(n);if(r===null||o===null||r<0||r>1||o<0||o>1)continue;const a=e.formatLabel(n);if(a==="")continue;const{width:s,height:i}=e.measureDataLabel("dataLabel",a),c=(mo(n)??e.layer.params.size)/2,l=r*e.panelRect.width,u=(1-o)*e.panelRect.height-c-Gn-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:l,y:u,text:a,width:s,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},nf={place:tf,getPercentageValueStrategy:()=>"none"};function Ga(e){return{startAngle:e[g.xMin],endAngle:e[g.xMax]}}function Ua(e){return{innerRadius:e[g.yMin],outerRadius:e[g.yMax]??e[g.y]}}const rf=" · ",of=e=>typeof e=="string"?e:e instanceof Date?e.toISOString():String(e),af=(e,t)=>{const n=v(t.x);return n!==null&&n!==tn.x?vn(e,t):o=>ke(o)},sf=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;const n=e.layer.dataLabels.showCategoryLabels?af(e.layer.data,e.layer.mapping):null,r=e.panelRect.width/2,o=e.panelRect.height/2,a=Math.min(e.panelRect.width,e.panelRect.height)/2;for(const s of e.layer.data){const{startAngle:i,endAngle:c}=Ga(s),{outerRadius:l}=Ua(s);if(i===null||c===null||l===null)continue;const u=e.formatLabel(s);if(u==="")continue;const d=n===null?null:n(s),m=d===null?u:`${of(d)}${rf}${u}`,{width:p,height:f}=e.measureDataLabel("dataLabel",m),y=(i+c)/2,b=Math.abs(Math.sin(y))*(p/2)+Math.abs(Math.cos(y))*(f/2),x=l*a+Bp+b,S=r+Math.sin(y)*x,w=o-Math.cos(y)*x,k=p/2,_=f/2;S-k<0||S+k>e.panelRect.width||w-_<0||w+_>e.panelRect.height||t.push({layerId:e.layer.id,key:e.getObservationKey(s),x:S,y:w,text:m,width:p,height:f,isRotated:!1,target:"observation",position:"outside"})}return t},cf={place:sf,getPercentageValueStrategy:()=>"absoluteGrandTotal"},lf={type:"decimal"};function Ya({layer:e,numberFormat:t,locale:n}){const r=v(e.mapping.y),o=r!==null&&e.data.hasVariable(r)?e.data.getValueFormat(r):lf;return C({valueFormat:o,locale:n,numberFormat:t})}const uf=({layer:e,coordSystem:t,axes:n,numberFormat:r,panelRect:o,measureDataLabel:a,formattingLocale:s,percentageValueStrategy:i})=>{const c=Ya({layer:e,numberFormat:r,locale:s});return{layer:e,coordSystem:t,panelRect:o,measureDataLabel:a,formatLabel:hf({layer:e,numberFormat:r,axes:n,locale:s,absoluteFormatter:c,percentageValueStrategy:i}),formatAbsolute:c,getObservationKey:df(e)}},df=e=>t=>`${e.id}:${It(t)}`,mf=(e,t)=>{switch(t){case"stack":return pf(e);case"fill":return ff(e);case"absoluteGrandTotal":return()=>e.summary.absoluteGrandTotal??null;case"none":return()=>null}},pf=e=>{const t=v(e.mapping.x);let n=null,r=!1;return o=>{const a=e.summary.stackTotals;if(a===void 0||a.length===0||t===null)return null;if(!r){n=new Map;for(const c of a)n.set(c.xKey,c);r=!0}const s=o[t];if(s==null)return null;const i=n?.get(bn(o,t));return i===void 0?null:i.total}},ff=e=>{const t=Sn(e);return n=>{const r=ge(n),o=j(n);if(!E(r)||!E(o))return null;const a=Math.abs(o-r);if(a===0)return null;const s=t(n);return E(s)?s/a:null}},hf=({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:o,percentageValueStrategy:a})=>{const s=W(e.data,e.dataLabels.labelSource),i=mf(e,a),c=yf({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:o}),l=C({valueFormat:{type:"percentage"},locale:r,numberFormat:t}),u=e.dataLabels.format==="percentage"&&Wa(e);return d=>{const m=s(d);if(m===null)return"";if(!u||!E(m))return c(m,d);const p=i(d);return p===null||p===0?c(m,d):l(m/p)}},yf=({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:o})=>{const a=e.dataLabels.labelSource,s=v(a);if(s!==null){if(Wa(e))return o;const i=gf(e,n,t,r,s);if(i!==null)return i}return C({valueFormat:bf(e.data,a),locale:r,numberFormat:t})},Wa=e=>{const t=v(e.dataLabels.labelSource);return t===null?!1:t===v(tt(e.position,e.mapping))},gf=(e,t,n,r,o)=>{const a=v(e.mapping.x);if(a===null||a!==o)return null;const s=t.find(i=>i.scaleAestheticKey==="x");return s===void 0?null:C({valueFormat:s.valueFormat,locale:r,numberFormat:n})},bf=(e,t)=>{const n=ee(t);if(n!==void 0)return typeof n=="number"?{type:"decimal"}:fs(n)?{type:"date"}:{type:"text"};const r=v(t);return r===null||!e.hasVariable(r)?{type:"text"}:e.getValueFormat(r)},vf={bar:{cartesian:Yp,polar:cf},line:{cartesian:ef},point:{cartesian:nf},area:{cartesian:Gp}},Sf=({layers:e,coordSystem:t,axes:n,numberFormat:r,parsingLocale:o,panelRect:a,measureDataLabel:s,formattingLocale:i})=>{const c=[],l=i??o,u=t.type;for(const d of e){if(!d.dataLabels.showDataLabels&&!d.dataLabels.showStackTotals)continue;const m=vf[d.geom]?.[u];if(m===void 0)continue;const p=uf({layer:d,coordSystem:t,axes:n,numberFormat:r,panelRect:a,measureDataLabel:s,formattingLocale:l,percentageValueStrategy:m.getPercentageValueStrategy(d)}),f=m.place(p);for(const y of f)c.push(y)}return{labels:c}},xf=(e,t,n,r)=>{const o=r.offsetFromHigherObservation+r.arrowheadSize+r.arrowEndGap;return e?Math.max(t.x,n.x)+o:Math.min(t.y,n.y)-o},wf=(e,t,n,{arrowStartGap:r,arrowEndGap:o,curveRadius:a})=>{const s={x:e.x,y:e.y-r},i={x:e.x,y:n},c={x:t.x,y:n},l={x:t.x,y:t.y-o},u=t.x>e.x?1:-1;return`
|
|
5
|
-
M ${
|
|
6
|
-
L ${i.x} ${i.y+
|
|
7
|
-
Q ${i.x} ${i.y} ${i.x+u*
|
|
8
|
-
L ${c.x-u*
|
|
9
|
-
Q ${c.x} ${c.y} ${c.x} ${c.y+
|
|
4
|
+
${n}`)}}class Hl{constructor(t,n){this.transformCompiler=t,this.validator=n}check(t){const n=[];for(const r of t.layers){const s=this.transformCompiler.compile({data:t.data,transforms:r.transforms}),o={...t.mapping,...r.mapping};n.push(...this.validator.validate({layerId:r.id,geom:r.geom,stat:r.stat,effectiveMapping:o,data:s,coordType:t.coords.coordType}))}if(n.length>0)throw new Lo(n)}}class Kl{constructor(t,n){this.geomRegistry=t,this.statRegistry=n}validate(t){return[...this.validateRequiredAesthetics(t),...this.validateVariableExistence(t),...this.validateGeomMapping(t),...this.validateCoordSupport(t)]}validateRequiredAesthetics({layerId:t,geom:n,stat:r,effectiveMapping:s}){const o=[],{requiredAesthetics:a}=this.geomRegistry.get(n),{computedVariables:i}=this.statRegistry.get(r.type);for(const c of a)i.has(c)||h(Ln(s,c))||o.push({code:"MISSING_AESTHETIC",message:`Layer '${t}': geom '${n}' requires aesthetic '${c}'`,layerId:t,aesthetic:c});return o}validateVariableExistence({layerId:t,stat:n,effectiveMapping:r,data:s}){const o=[],{computedVariables:a}=this.statRegistry.get(n.type);for(const[i,c]of Object.entries(r)){if(a.has(i))continue;const l=v(c);l!==null&&(s.hasVariable(l)||o.push({code:"UNKNOWN_VARIABLE",message:`Layer '${t}': aesthetic '${i}' references variable '${l}' which does not exist in the dataset`,layerId:t,aesthetic:i}))}return o}validateGeomMapping({layerId:t,geom:n,stat:r,effectiveMapping:s}){const o=this.geomRegistry.get(n);if(o.validateMapping===void 0)return[];const{computedVariables:a}=this.statRegistry.get(r.type);return o.validateMapping({layerId:t,mapping:s,computedVariables:a})}validateCoordSupport({layerId:t,geom:n,coordType:r}){const{supportedCoordTypes:s}=this.geomRegistry.get(n);return s.includes(r)?[]:[{code:"UNSUPPORTED_COORD",message:`Layer '${t}': geom '${n}' is not supported under '${r}' coords`,layerId:t}]}}const jr=A("__ungrouped__"),Xl=(e,t)=>t===null?!0:e.some(n=>n.axis===t.axis&&n.role===t.role&&n.valueKind===t.valueKind),Vo=(e,t,n="y")=>{const r=n==="y"?"x":"y",s=v(t[n]),o=v(t[r]);if(!s||!o)return null;const a=e.getValues(P.group,{type:"categorical",distinct:!0,skipNulls:!0}),i=a.length===0,c=i?[jr]:a,l=e.getValues(o),u=e.getValues(s,{type:"numeric"}),d=e.getValues(P.group,{type:"categorical"}),p=e.size(),m=new Map;for(let f=0;f<p;f++){const y=l[f]??null,b=d[f],x=i?jr:b;if(!h(x))continue;let S=m.get(y);S||(S=new Map,m.set(y,S)),S.set(x,f)}return{values:u,observationIndexByPartitionAndGroup:m,uniqueGroupKeys:c,observationCount:p}};class ql{constructor(t){this.registry=t}adjust(t,n,r){const s=this.registry.get(t),o=s.getConsumedChannel(r.axis??"y");return Xl(n,o)?s.adjust(r):{data:r.data,mapping:{}}}}class _t{getConsumedChannel(t){return null}}class jl extends _t{constructor(){super(...arguments),this.type="dodge"}getConsumedChannel(t){return{axis:"x",role:"point",valueKind:"value"}}adjust({data:t,mapping:n}){if(!v(n.x))return{data:t,mapping:{}};const s=t.getValues(P.group,{type:"categorical",distinct:!0,skipNulls:!0});if(s.length===0)return{data:t,mapping:{}};const o=t.size(),a=t.getValues(P.group,{type:"categorical"}),i=io/2,c=s.length>1?oc:0,l=ie.scaleBand().domain(s.map(String)).range([-i,i]).paddingInner(c).paddingOuter(0),u=l.bandwidth(),d=new Array(o).fill(null),p=new Array(o).fill(null);for(let f=0;f<o;f++){const y=a[f];if(!h(y))continue;const b=l(String(y));h(b)&&(d[f]=b,p[f]=b+u)}return{data:t.addVariable(g.xMin,"numeric",d).addVariable(g.xMax,"numeric",p),mapping:{}}}}class Ql extends _t{constructor(){super(...arguments),this.type="fill"}getConsumedChannel(t){return{axis:t,role:"point",valueKind:"value"}}adjust({data:t,mapping:n,axis:r="y"}){const s=Vo(t,n,r);if(s===null)return{data:t,mapping:{}};const{values:o,observationIndexByPartitionAndGroup:a,uniqueGroupKeys:i,observationCount:c}=s,l=[...o],u=new Array(c).fill(0);for(const[,p]of a){let m=0,f=0;for(const x of i){const S=p.get(x);if(S===void 0)continue;const w=o[S];w!=null&&(w>=0?m+=w:f-=w)}let y=0,b=0;for(const x of i){const S=p.get(x);if(S===void 0)continue;const w=o[S];if(w===void 0)continue;if(w===null){u[S]=null,l[S]=null;continue}const I=w>=0?m:f;if(I===0){u[S]=0,l[S]=0;continue}const _=w/I;w>=0?(u[S]=y,l[S]=y+=_):(l[S]=b,u[S]=b+=_)}}let d=t.addVariable(U(r,"lower"),"numeric",u).addVariable(U(r,"upper"),"numeric",l);return r==="y"&&(d=d.addVariable(g.yRaw,"numeric",o)),{data:d,mapping:{}}}}class Zl extends _t{constructor(){super(...arguments),this.type="identity"}adjust({data:t}){return{data:t,mapping:{}}}}class Jl extends _t{constructor(){super(...arguments),this.type="stack"}getConsumedChannel(t){return{axis:t,role:"point",valueKind:"value"}}adjust({data:t,mapping:n,axis:r="y"}){const s=Vo(t,n,r);if(s===null)return{data:t,mapping:{}};const{values:o,observationIndexByPartitionAndGroup:a,uniqueGroupKeys:i,observationCount:c}=s,l=[...o],u=new Array(c).fill(0);for(const[,m]of a){let f=0,y=0;for(const b of i){const x=m.get(b);if(x===void 0)continue;const S=o[x];if(S!==void 0){if(S===null){u[x]=null,l[x]=null;continue}S>=0?(u[x]=f,l[x]=f+=S):(l[x]=y,u[x]=y+=S)}}}let d=t.addVariable(U(r,"lower"),"numeric",u).addVariable(U(r,"upper"),"numeric",l);r==="y"&&(d=d.addVariable(g.yRaw,"numeric",o));const p=v(n[r]);return p!==null&&(d=d.addVariable(p,"numeric",l)),{data:d,mapping:{}}}}class eu extends Fe{constructor(){super("position"),this.register("identity",new Zl),this.register("stack",new Jl),this.register("fill",new Ql),this.register("dodge",new jl)}}function tu(e){let t=e.data;for(const n of e.channels)n.role==="point"&&(t=nu(n.axis,t,e));for(const n of su(e.channels))t=ou(n,t,e);for(const n of e.channels)n.role==="scalar"&&(t=ru(n,t,e));return t}function Nn(e,t){return e==="x"?"x":tt(t)}function nu(e,t,n){const r=v(n.mapping[e]),s=n.getPositionScale(Nn(e,n.yScaleType));if(!r||!s)return t;const a=t.getValues(r).map(i=>h(i)?s.map(i):null);return t.addVariable(U(e,"point"),"numeric",a)}function ru(e,t,n){const r=n.getPositionScale(Nn(e.axis,n.yScaleType)),o=(e.aes?v(Ln(n.mapping,e.aes)):null)??U(e.axis,e.name);if(!r||!t.hasVariable(o))return t;const i=t.getValues(o,{type:"numeric"}).map(c=>h(c)?r.map(c):null);return t.addVariable(U(e.axis,e.name),"numeric",i)}function su(e){const t=new Map;for(const n of e){if(n.role==="point"||n.role==="scalar")continue;const r=`${n.axis}:${n.valueKind}`,s=t.get(r)??{axis:n.axis,valueKind:n.valueKind,hasLower:!1,hasUpper:!1};n.role==="lower"&&(s.hasLower=!0),n.role==="upper"&&(s.hasUpper=!0),t.set(r,s)}return[...t.values()].filter(n=>n.hasLower&&n.hasUpper).map(({axis:n,valueKind:r})=>({axis:n,valueKind:r}))}function ou(e,t,n){const r=n.getPositionScale(Nn(e.axis,n.yScaleType));if(!r)return t;const s=U(e.axis,"lower"),o=U(e.axis,"upper");return!t.hasVariable(s)||!t.hasVariable(o)?t:e.valueKind==="value"?au(t,r,s,o):iu(e.axis,t,r,s,o)}function au(e,t,n,r){const s=e.getValues(n,{type:"numeric"}),o=e.getValues(r,{type:"numeric"}),a=e.size(),i=new Array(a),c=new Array(a);for(let l=0;l<a;l++){const u=s[l],d=o[l];h(u)&&h(d)?(i[l]=t.map(u),c[l]=t.map(d)):(i[l]=null,c[l]=null)}return e.addVariable(n,"numeric",i).addVariable(r,"numeric",c)}function iu(e,t,n,r,s){const o=U(e,"point");if(!n.bandwidth||!t.hasVariable(o))return t;const a=n.bandwidth,i=t.getValues(o,{type:"numeric"}),c=t.getValues(r,{type:"numeric"}),l=t.getValues(s,{type:"numeric"}),u=t.size(),d=new Array(u),p=new Array(u);for(let m=0;m<u;m++){const f=i[m],y=c[m],b=l[m];h(f)&&h(y)&&h(b)?(d[m]=f+y*a,p[m]=f+b*a):(d[m]=null,p[m]=null)}return t.addVariable(r,"numeric",d).addVariable(s,"numeric",p)}function cu(e,t){const n=e[t];return n?.kind==="position"?n:null}class lu extends Ce{constructor(t){super(),this.geomRegistry=t}dependencies(t){return[t.scales.x,t.scales.y,t.scales.ySecondary]}compileLayer(t,n){const r=this.geomRegistry.get(t.geom),s=tu({channels:r.positionChannels,data:t.data,mapping:t.mapping,yScaleType:t.yScaleType,getPositionScale:o=>cu(n.scales,o)});return{...t,data:s}}}class uu extends le{constructor(t){super(),this.registry=t}dependencies(t){return[t.layers,t.scales]}run(t){this.validateScaleTypeCompatibility(t);const n=new Map;for(const o of t.scales)n.set(o.scaledAesthetic,o);const r=this.collectValues(t.layers,n),s={};for(const[o,a]of n){const i=r.get(o)??[],c=this.registry.get(a.scaleType);s[o]=c.compile(a,i)}return s}validateScaleTypeCompatibility(t){const n=[];for(const r of t.scales){const{compatibleDataTypes:s}=this.registry.get(r.scaleType),o=J(r.scaledAesthetic),a=t.layers.find(l=>h(l.mapping[o]));if(!a)continue;const i=v(a.mapping[o]);if(!h(i)||!a.data.hasVariable(i))continue;const c=a.data.getType(i);if(s.includes(c)||n.push({code:"INCOMPATIBLE_TYPE",message:`Scale '${r.scaledAesthetic}' (${r.scaleType}) is incompatible with variable '${i}' (${c})`,aesthetic:o}),r.scaledAesthetic==="lineType"&&c!=="categorical"){const l=c==="temporal"?"Bucket the variable into categorical periods (e.g. quarter, year) first.":"Bin the variable into categorical buckets first.";n.push({code:"INCOMPATIBLE_TYPE",message:`Scale 'lineType' is discrete-only and cannot be mapped to ${c} variable '${i}'. ${l}`,aesthetic:o})}}if(n.length>0)throw new Lo(n)}collectValues(t,n){const r=new Map;for(const s of t)for(const[o,a]of Object.entries(s.mapping)){const i=o,c=i==="y"?tt(s.yScaleType):i;if(!mc(c)||!n.has(c))continue;const l=this.resolveVariables(i,a,s.data);this.collectFromVariables(s.data,l,c,r)}return r}resolveVariables(t,n,r){if(t==="y"&&this.hasPositionAdjustedY(r))return[g.yMin,g.yMax];const s=v(n);return!s||!r.hasVariable(s)?[]:[s]}hasPositionAdjustedY(t){return t.hasVariable(g.yMin)&&t.hasVariable(g.yMax)}collectFromVariables(t,n,r,s){if(n.length===0)return;let o=[];for(const i of n)o=o.concat(t.getValues(i));const a=s.get(r);s.set(r,a?a.concat(o):o)}}class rt{createPositionScale(t,n){return{kind:"position",aesthetic:J(t.scaledAesthetic),spec:t,...n}}createVisualScale(t,n){return{kind:"visual",aesthetic:J(t.scaledAesthetic),spec:t,...n}}}class du extends rt{constructor(){super(...arguments),this.compatibleDataTypes=["numeric"]}compile(t,n){if(t.scaleType!=="continuous")throw new Error("ContinuousScale.compile received non-continuous spec");const r=Ft(t.scaledAesthetic),s=this.computeDataDomain(n,t);return r?this.buildPositionScale(s,t):this.buildVisualScale(s,t)}computeDataDomain(t,n){let r=1/0,s=-1/0;for(const o of t)typeof o=="number"&&(o<r&&(r=o),o>s&&(s=o));return r===1/0?[0,0]:(n.zero&&(r>0&&(r=0),s<0&&(s=0)),[r,s])}createD3Scale(t,n,r){let s=[r.domainMin??t[0],r.domainMax??t[1]];const o=r.transform==="log"&&pu(s),a=o?ie.scaleLog():r.transform==="sqrt"?ie.scaleSqrt():ie.scaleLinear();return r.nice&&!o&&(s=a.copy().domain(s).nice().domain()),a.domain([r.domainMin??s[0],r.domainMax??s[1]]).range(n).clamp(r.clamp)}buildPositionScale(t,n){const r=n.reverse?[1,0]:[0,1],s=this.createD3Scale(t,r,n);return this.createPositionScale(n,{map:s,domain:s.domain(),bandwidth:null,generateTicks:o=>o&&"count"in o?s.ticks(o.count):s.ticks()})}buildVisualScale(t,n){const r=n.range??[0,1],s=n.reverse?[r[1],r[0]]:r,o=this.createD3Scale(t,s,n);return this.createVisualScale(n,{map:o,domain:o.domain(),generateTicks:a=>a&&"count"in a?o.ticks(a.count):o.ticks()})}}const pu=e=>{const[t,n]=e;return t>0&&n>0||t<0&&n<0};class mu extends rt{constructor(){super(...arguments),this.compatibleDataTypes=["temporal"]}compile(t,n){if(t.scaleType!=="datetime")throw new Error("DatetimeScale.compile received non-datetime spec");const r=Ft(t.scaledAesthetic),s=this.computeDataDomain(n);if(!r)throw new Error("Datetime scale is not supported for non-position aesthetics");return this.buildScale(s,t,this.collectInputDates(n))}collectInputDates(t){const n=new Set,r=[];for(const s of t){if(!(s instanceof Date))continue;const o=s.getTime();n.has(o)||(n.add(o),r.push(s))}return r.sort((s,o)=>s.getTime()-o.getTime()),r}computeDataDomain(t){let n=1/0,r=-1/0;for(const s of t){if(!(s instanceof Date))continue;const o=s.getTime();o<n&&(n=o),o>r&&(r=o)}return n===1/0?[]:[new Date(n),new Date(r)]}createD3Scale(t,n,r){const s=fu(t)?t:[],o=ie.scaleUtc().domain(s).range(n).clamp(r.clamp);if(r.nice&&o.nice(),h(r.domainMin)||h(r.domainMax)){const[a,i]=o.domain();a!==void 0&&i!==void 0&&o.domain([r.domainMin??a,r.domainMax??i])}return o}buildScale(t,n,r){const s=n.reverse?[1,0]:[0,1],o=this.createD3Scale(t,s,n),[a,i]=o.domain(),c=a&&i?r.filter(l=>l>=a&&l<=i):[];return this.createPositionScale(n,{map:o,domain:o.domain(),bandwidth:null,generateTicks:l=>l&&"atInputs"in l?c:l&&"interval"in l?a&&i?Sc(a,i,l.interval):[]:o.ticks(l?.count)})}}const fu=e=>e.length===2&&G(e[0])&&G(e[1]),Me={transform:"linear",reverse:!1,nice:!0,zero:!1,domainMin:null,domainMax:null},Qr={size:[4,20],alpha:[.1,1],strokeWidth:[1,4]},ct={domainMin:null,domainMax:null,nice:!1,reverse:!1},Ue={range:null,domain:null,padding:.1,reverse:!1},hu={palette:{type:"default"}};class yu extends rt{constructor(){super(...arguments),this.compatibleDataTypes=["categorical","numeric","temporal"]}compile(t,n){if(t.scaleType!=="discrete")throw new Error("DiscreteScale.compile received non-discrete spec");const r=Ft(t.scaledAesthetic),s=this.computeDataDomain(n,t);return r?this.buildPositionScale(s,t):this.buildVisualScale(s,t)}computeDataDomain(t,n){if(n.domain!==null&&n.domain.length>0)return[...n.domain];const r=new Set,s=[];for(const o of t)r.has(o)||(r.add(o),s.push(o));return s}buildPositionScale(t,n){const r=t.map(String),s=n.padding??Ue.padding,o=n.reverse?[1,0]:[0,1],a=ie.scaleBand().domain(r).range(o).paddingInner(s).paddingOuter(s/2),i=a.bandwidth()/2;return this.createPositionScale(n,{map:c=>(a(String(c))??0)+i,domain:t,bandwidth:a.bandwidth(),generateTicks:()=>[...t]})}buildVisualScale(t,n){const r=t.map(String),s=n.range&&n.range.length>0?ie.scaleOrdinal().domain(r).range(n.range).unknown(n.range[0]):null;return this.createVisualScale(n,{map:o=>{const a=String(o);return s?s(a):a},domain:t,generateTicks:()=>t})}}class gu extends rt{constructor(){super(...arguments),this.compatibleDataTypes=["numeric","categorical","temporal"]}compile(t){if(t.scaleType!=="identity")throw new Error("IdentityScale.compile received non-identity spec");return{kind:"identity",aesthetic:J(t.scaledAesthetic),spec:t,map:n=>n,domain:[],generateTicks:()=>[]}}}const ko=["grey","red","orange","yellow","green","cyan","blue","purple","pink"],Eo=["cyan","pink","purple","red","orange","yellow","green","blue"],On=["#B399FE","#FC7E91","#33B6E0","#FFC849","#25CDA5","#FA9B65","#D93C95","#845FD8","#3F8EEB","#58C8D8","#F35074","#6EA0DA"],q={red:"#E83562",orange:"#F38650",yellow:"#FBBC30",green:"#31FCB4",cyan:"#40F8FF",blue:"#279EFF",purple:"#B399FD",dark_purple:"#6D48D2",plum:"#C82184",pink:"#FC8497"},bu=[q.purple,q.pink,q.yellow,q.blue,q.red,q.cyan,q.orange,q.plum,q.green,q.dark_purple],W={green:"#B2DDC9",cyan:"#A2D5E2",blue:"#AAC4FF",purple:"#B2A4FF",plum:"#DCA8C7",pink:"#FFCCD3",red:"#FFADAD",orange:"#FFDEB4",yellow:"#FDF7C3"},vu=[W.green,W.purple,W.red,W.cyan,W.pink,W.blue,W.orange,W.plum,W.yellow],vn={grey900:"#1c1917",grey800:"#292524",grey700:"#44403c",grey600:"#57534e",grey500:"#78716c",grey400:"#a8a29e",grey300:"#d6d3d1",grey200:"#e7e5e4",grey100:"#f5f5f4",grey50:"#fafaf9",red900:"#7f1d1d",red800:"#991b1b",red700:"#b91c1c",red600:"#dc2626",red500:"#ef4444",red400:"#f87171",red300:"#fca5a5",red200:"#fecaca",red100:"#fee2e2",red50:"#fef2f2",orange900:"#7c2d12",orange800:"#9a3412",orange700:"#c2410c",orange600:"#ea580c",orange500:"#f97316",orange400:"#fb923c",orange300:"#fdba74",orange200:"#fed7aa",orange100:"#ffedd5",orange50:"#fff7ed",yellow900:"#553B0C",yellow800:"#6F4B08",yellow700:"#8D6300",yellow600:"#BD8A00",yellow500:"#E5B400",yellow400:"#FFC800",yellow300:"#FBDA2B",yellow200:"#FEED72",yellow100:"#FEF8B4",yellow50:"#FEFCE2",green900:"#064e3b",green800:"#065f46",green700:"#047857",green600:"#059669",green500:"#10b981",green400:"#34d399",green300:"#6ee7b7",green200:"#a7f3d0",green100:"#d1fae5",green50:"#ecfdf5",cyan900:"#164e63",cyan800:"#155e75",cyan700:"#0e7490",cyan600:"#0891B2",cyan500:"#06b6d4",cyan400:"#22d3ee",cyan300:"#67e8f9",cyan200:"#a5f3fc",cyan100:"#cffafe",cyan50:"#ecfeff",blue900:"#1e3a8a",blue800:"#1e40af",blue700:"#1d4ed8",blue600:"#2563eb",blue500:"#3b82f6",blue400:"#60a5fa",blue300:"#93c5fd",blue200:"#bfdbfe",blue100:"#dbeafe",blue50:"#eff6ff",purple900:"#4c1d95",purple800:"#5b21b6",purple700:"#6d28d9",purple600:"#7c3aed",purple500:"#8b5cf6",purple400:"#a78bfa",purple300:"#c4b5fd",purple200:"#ddd6fe",purple100:"#ede9fe",purple50:"#f5f3ff",pink900:"#751A5E",pink800:"#8F1972",pink700:"#AF1C8A",pink600:"#D326A8",pink500:"#E845BF",pink400:"#F979D9",pink300:"#FCABE8",pink200:"#FED0F3",pink100:"#FFE8F9",pink50:"#FFF4FC"},Su=[vn.grey200,W.green,W.red,vn.grey200],Zr={dark:{1:[500],2:[600,400],3:[600,400,200],4:[600,500,300,100],5:[700,600,400,200,50],6:[600,500,400,300,200,100],7:[600,500,400,300,200,100,50],default:[700,600,500,400,300,200,100,50]},light:{1:[600],2:[700,500],3:[800,600,400],4:[800,600,400,300],5:[800,700,600,500,400],6:[800,700,600,500,400,300],7:[900,800,700,600,500,400,300],default:[900,800,700,600,500,400,300,200]}},z={cyan:"#22D3EE",pink:"#F377EF",purple:"#6528F7",red:"#FB2576",orange:"#FF9300",yellow:"#FBFF00",green:"#06FF00",blue:"#0079FF"},lt=[z.cyan,z.pink,z.purple,z.red,z.orange,z.yellow,z.green,z.blue],xu=[z.cyan,z.green,z.red,z.cyan],ut={start:"#84D1FC",positive:"#84FC89",negative:"#FC8497",total:"#84D1FC"},wu=[ut.start,ut.positive,ut.negative,ut.total];function Au(e,t="light",n){return((n!==void 0?Zr[t][n]:void 0)??Zr[t].default).map(s=>vn[`${e}${s}`])}function Tu(e){const t=lt.indexOf(z[e]);return t<=0?lt:[...lt.slice(t),...lt.slice(0,t)]}function Mu(e,t){switch(e.type){case"default":return On;case"graphy":return e.variant==="waterfall"?wu:bu;case"pastel":return e.variant==="waterfall"?Su:vu;case"neon":return e.variant==="waterfall"?xu:Tu(e.base);case"mono":return Au(e.base,e.variant??"light",t);case"custom":return e.colors}}function Lu(e,t){if(!e)return hu.palette;if(e.type==="custom"){const n=t[e.id];if(!n)throw new Error(`Custom palette with id "${e.id}" not found`);return{type:"custom",id:e.id,colors:n}}return e}class Vu extends rt{constructor(){super(...arguments),this.compatibleDataTypes=["categorical","temporal"]}compile(t,n){if(t.scaleType!=="palette")throw new Error("PaletteScale.compile received non-palette spec");const r=this.computeDomain(n),s=Mu(t.palette,r.length),o=s.length>0?s:[...On],a=ie.scaleOrdinal().domain(r.map(String)).range(o).unknown(o[0]);return this.createVisualScale(t,{map:i=>a(String(i)),domain:r,generateTicks:()=>r})}computeDomain(t){const n=new Set,r=[];for(const s of t)n.has(s)||(n.add(s),r.push(s));return r}}class ku extends Fe{constructor(){super("scale"),this.register("continuous",new du),this.register("discrete",new yu),this.register("datetime",new mu),this.register("identity",new gu),this.register("palette",new Vu)}}const Io=e=>!("layers"in e),C={point:Eu,line:Iu,area:Cu,bar:Fu,rule:Du};function Eu(e={}){return{type:"layer",geom:"point",mapping:e.aes,stat:e.stat,params:e.params,position:e.position,yScaleType:e.yScaleType,transforms:e.transforms,interactive:e.interactive,dataLabels:e.dataLabels}}function Iu(e={}){return{type:"layer",geom:"line",mapping:e.aes,stat:e.stat,params:e.params,position:e.position,yScaleType:e.yScaleType,transforms:e.transforms,interactive:e.interactive,dataLabels:e.dataLabels}}function Cu(e={}){return{type:"layer",geom:"area",mapping:e.aes,stat:e.stat,params:e.params,position:e.position,yScaleType:e.yScaleType,transforms:e.transforms,interactive:e.interactive,dataLabels:e.dataLabels}}function Fu(e={}){return{type:"layer",geom:"bar",mapping:e.aes,stat:e.stat,params:e.params,position:e.position,yScaleType:e.yScaleType,transforms:e.transforms,interactive:e.interactive,dataLabels:e.dataLabels}}function Du(e={}){return{type:"layer",geom:"rule",mapping:e.aes,stat:e.stat,params:e.params,position:e.position,yScaleType:e.yScaleType,transforms:e.transforms,interactive:e.interactive,dataLabels:e.dataLabels}}const $n={identity:Ru,count:Pu,smooth:_u,mean:Nu};function _u(e){return{type:"smooth",method:e.method,order:e.order,bandwidth:e.bandwidth}}function Ru(){return{type:"identity"}}function Pu(){return{type:"count"}}function Nu(){return{type:"mean"}}const ge={reshape:Ou,filter:$u,sort:Bu,aggregate:Gu,constant:zu};function Ou(e={}){return{type:"transform",transformType:"reshape",options:e}}function $u(e){return{type:"transform",transformType:"filter",options:e}}function Bu(e){return{type:"transform",transformType:"sort",options:e}}function Gu(e){return{type:"transform",transformType:"aggregate",options:e}}function zu(e){return{type:"transform",transformType:"constant",options:e}}const Jr="#%_ENCODED_%#",Co=e=>{if(!e.startsWith(Jr))return e;try{const{value:t}=JSON.parse(e.slice(Jr.length));return typeof t=="string"?t:e}catch{return e}},Uu=({annotations:e,dataset:t,mapping:n})=>{const r=[],s=[],o=[],a=[],i=[],c=[],l=[],u=v(n.x);for(const d of e??[])switch(d.type){case"difference-arrow":{const p=Yu(d,u,t);p!==null&&r.push(p);break}case"shape":{s.push(Wu(d));break}case"arrow":{o.push(qu(d));break}case"highlight":break;case"text":{a.push(Hu(d));break}case"sticker":{const p=Ku(d,u,t);p!==null&&i.push(p);break}case"tooltip":{const p=Xu(d,u,t);if(p===null)break;p.kind==="pinnedNumber"?c.push(p.value):l.push(p.value);break}default:{const p=d;throw new Error(`Unsupported annotation type: ${p.type}`)}}return{differenceArrows:r,shapes:s,freeformArrows:o,textAnnotations:a,stickers:i,pinnedNumbers:c,comments:l}},Yu=(e,t,n)=>{const r=At({dataset:n,input:e.start,anchorVariable:t}),s=At({dataset:n,input:e.end,anchorVariable:t});return r===null||s===null?null:{id:e.id,start:r,end:s,label:e.show,color:e.color??null,size:e.size,labelCrossPosition:e.labelPosition}},Wu=e=>({id:e.id,kind:e.shape,zOrder:e.layer==="abovePlot"?"foreground":"background",x:e.x,y:e.y,width:e.width,height:e.height,fillColor:e.fillColor,fillOpacity:e.fillOpacity,strokeWidth:e.strokeWidth,strokeColor:e.fillColor}),Hu=e=>({id:e.id,content:e.content,x:e.x,y:e.y,width:e.width,backgroundColor:e.backgroundColor??null,backgroundColorStyle:e.backgroundColorStyle}),Ku=(e,t,n)=>{const r=At({dataset:n,input:e,anchorVariable:t});return r===null?null:{id:e.id,anchor:r,sticker:e.sticker}},Xu=(e,t,n)=>{const r=At({dataset:n,input:e,anchorVariable:t});return r===null?null:e.caption===null||e.caption===void 0?{kind:"pinnedNumber",value:{id:e.id,anchor:r}}:{kind:"comment",value:{id:e.id,anchor:r,content:e.caption}}},qu=e=>({id:e.id,start:{x:e.startX,y:e.startY},end:{x:e.endX,y:e.endY},color:e.color??null,thickness:e.thickness,startArrowheadStyle:e.startArrowheadStyle,endArrowheadStyle:e.endArrowheadStyle,lineStyle:e.lineStyle,hasStickerStyle:e.hasStickerStyle}),At=({dataset:e,input:t,anchorVariable:n})=>{if(!h(t)||!h(t.columnKey))return null;const r=ju(t,n,e);return r===null?null:{anchorValue:r,groupValue:Co(t.columnKey)}},ju=(e,t,n)=>e.rowValue!==void 0?e.rowValue:t===null||!h(e.rowIndex)||!n.hasVariable(t)?null:n.getValues(t)[e.rowIndex]??null,Fo=["lilac","neon_pink","blackberry","sun","iceland","sunset","ultraviolet","purple","ice_cream","mint","cool","fresh"];function Do(e){return{type:"config",config:e}}const Qu="#E5E5E5",Zu={x:"top",y:"left"},Ju=new Set(["pie","donut"]);function ed(e){return Do({legend:od(e.legend),axes:id(e.axes),headline:cd(e),numberFormat:ld(e.appearance),content:ud(e.content),appearance:td(e.appearance,e.themeOverrides)}).config}function td(e,t){const n=sd(e?.border),r=e?.hasRoundedCorners===!1?0:void 0,s=nd(e,t),o={};return e?.textScale!==void 0&&(o.textScale=e.textScale),n!==void 0&&(o.border=n),r!==void 0&&(o.cornerRadius=r),s!==void 0&&(o.background=s),e?.highlightStyle!==void 0&&(o.highlightStyle=e.highlightStyle==="grey"?"desaturate":"dim"),Object.keys(o).length>0?o:void 0}function nd(e,t){if(e?.backgroundModifier==="tint")return{type:"tinted"};const n=t?.graphBackground;if(typeof n=="string")return{type:"solid",color:n}}const rd=e=>Fo.includes(e);function sd(e){if(!e?.style)return;if(e.style==="none")return{type:"none"};const t=e.width??0;if(e.style==="grey")return{type:"solid",color:Qu,width:t};if(e.style==="preset")return e.color===void 0||!rd(e.color)?void 0:{type:"preset",preset:e.color,width:t};if(e.color!==void 0)return e.style==="custom"?{type:"solid",color:e.color,width:t}:{type:e.style,color:e.color,width:t}}function od(e){if(e)return{position:e.position}}function es(e,t,n){return!t&&n===void 0?{}:{...t?.isHidden!==void 0?{isVisible:!t.isHidden}:void 0,...t?.label!==void 0?{label:t.label}:void 0,...t?.isReversed?{position:Zu[e]}:void 0,...t?.tickDisplayMode?{labels:{mode:t.tickDisplayMode}}:void 0,...n!==void 0?{grid:{isVisible:n}}:void 0}}function ad(e){return{...e.label!==void 0?{label:e.label}:void 0}}function id(e){if(e)return{x:es("x",e.x,e.showGridLines),y:es("y",e.y,e.showGridLines),...e.y2?{ySecondary:ad(e.y2)}:void 0}}function cd(e){const{headlineNumbers:t,options:n,type:r}=e,s=r!==void 0&&Ju.has(r)?n?.pieTotalPosition:void 0;if(t===void 0&&s===void 0)return;const o={};return t?.show!==void 0&&(o.show=t.show),t?.compareWith!==void 0&&(o.compareWith=t.compareWith),t?.size!==void 0&&(o.size=t.size),s!==void 0&&(o.show="total",o.position=s==="center"?"center":"above"),o}function ld(e){if(e?.numberFormat)return{decimals:e.numberFormat.decimalPlaces,abbreviation:e.numberFormat.abbreviation}}function ud(e){if(!e)return;const t={};e.title!==void 0&&(t.title=e.title),e.isTitleHidden!==void 0&&(t.isTitleVisible=!e.isTitleHidden),e.subtitle!==void 0&&(t.subtitle=e.subtitle),e.isSubtitleHidden!==void 0&&(t.isSubtitleVisible=!e.isSubtitleHidden),e.caption!==void 0&&(t.caption=e.caption),e.isCaptionHidden!==void 0&&(t.isCaptionVisible=!e.isCaptionHidden);const n=dd(e.source);return n!==void 0&&(t.source=n),e.isSourceHidden!==void 0&&(t.isSourceVisible=!e.isSourceHidden),t}function dd(e){if(!e)return;const t={};return e.label!==void 0&&(t.label=e.label),e.url!==void 0&&(t.url=e.url),Object.keys(t).length===0?void 0:t}const B={cartesian:(e={})=>({type:"coord",coordType:"cartesian",params:e}),flip:(e={})=>({type:"coord",coordType:"flip",params:e}),polar:(e={})=>({type:"coord",coordType:"polar",params:e})},pd={showDataLabels:!1,format:"absolute",showStackTotals:!1,showCategoryLabels:!1,labelSource:{variable:g.yRaw}},bt={stat:{type:"identity"},position:"identity",params:{size:8}},en={stat:{type:"identity"},position:"identity",params:{lineWidth:"auto",interpolate:"linear",missingValues:"gap"}},tn={stat:{type:"identity"},position:"stack",params:{lineWidth:"auto",interpolate:"linear",missingValues:"zero"}},nn={stat:{type:"identity"},position:"dodge",params:{}},Be={stat:{type:"identity"},position:"identity",interactive:!1,params:{strokeWidth:1,lineType:"dashed",labelPosition:"start"}},Re="primary";function md(e,t){const n={...pd};return e==="bar"&&t==="polar"&&(n.format="percentage"),n}function R(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"continuous",transform:t.transform,reverse:t.reverse,nice:t.nice,zero:t.zero,clamp:t.clamp,domainMin:t.domainMin??null,domainMax:t.domainMax??null,range:t.range}}function vt(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"datetime",domainMin:t.domainMin??null,domainMax:t.domainMax??null,nice:t.nice,reverse:t.reverse,clamp:t.clamp}}function j(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"discrete",range:t.range,domain:t.domain??null,padding:t.padding,reverse:t.reverse}}function Ye(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"identity"}}function St(e,t){return{type:"scale",scaledAesthetic:e,scaleType:"inferred",options:t}}function _o(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"palette",palette:t.palette}}const be={x:Object.assign(e=>St("x",e),{continuous:e=>R("x",e),discrete:e=>j("x",e),datetime:e=>vt("x",e),log:e=>R("x",{...e,transform:"log"}),sqrt:e=>R("x",{...e,transform:"sqrt"})}),y:Object.assign(e=>St("y",e),{continuous:e=>R("y",e),discrete:e=>j("y",e),datetime:e=>vt("y",e),log:e=>R("y",{...e,transform:"log"}),sqrt:e=>R("y",{...e,transform:"sqrt"})}),ySecondary:Object.assign(e=>St("ySecondary",e),{continuous:e=>R("ySecondary",e),discrete:e=>j("ySecondary",e),datetime:e=>vt("ySecondary",e),log:e=>R("ySecondary",{...e,transform:"log"}),sqrt:e=>R("ySecondary",{...e,transform:"sqrt"})}),color:{continuous:e=>R("color",e),discrete:e=>j("color",e),palette:e=>_o("color",e)},size:{continuous:e=>R("size",e),discrete:e=>j("size",e),identity:e=>Ye("size",e)},alpha:{continuous:e=>R("alpha",e),discrete:e=>j("alpha",e),identity:e=>Ye("alpha",e)},strokeWidth:{continuous:e=>R("strokeWidth",e),discrete:e=>j("strokeWidth",e),identity:e=>Ye("strokeWidth",e)},lineType:{discrete:e=>j("lineType",e),identity:e=>Ye("lineType",e)}},Y="key",ne="value",ts=A("lineSeriesLabel"),ns=A("barSeriesLabel"),Tt=A("constantY"),fd=(e,t,n,r)=>xd[t](e,n,r),Bn=e=>{const{numeric:t,categorical:n,temporal:r}=e.groupVariableNamesByType();return h(r[0])?r[0]:h(n[0])?n[0]:h(t[0])?t[0]:""},Gn=e=>{const t=Bn(e),{numeric:n}=e.groupVariableNamesByType(),r=n.filter(o=>o!==t);return r.length<=1?{dataset:e,mapping:{x:t,y:r[0]??""},seriesVariables:r}:{dataset:e.reshapeFromWideToLong({keep:[t],keyName:Y,valueName:ne}),mapping:{x:t,y:ne,color:Y},seriesVariables:r}},zn=e=>{const t=e.appearance?.seriesStyles;if(!t||e.seriesVariables.length===0)return{mapping:{},scales:[]};if(!e.seriesVariables.some(s=>h(t[s]?.lineStyle)))return{mapping:{},scales:[]};if(e.seriesVariables.length===1){const s=e.seriesVariables[0];if(!s)return{mapping:{},scales:[]};const o=t[s]?.lineStyle;return o?{mapping:{lineType:{value:o}},scales:[]}:{mapping:{},scales:[]}}const r=e.seriesVariables.map(s=>t[s]?.lineStyle??"solid");return{mapping:{lineType:Y},scales:[be.lineType.discrete({domain:e.seriesVariables,range:r})]}},hd=e=>{const{categorical:t,temporal:n,numeric:r}=e.groupVariableNamesByType(),s=r[0];if(!h(s))throw new Error("No first numeric variable found");const o=r.slice(1);return o.length===0?{dataset:e.addConstantVariable(Tt,"categorical",""),mapping:{x:s,y:Tt,label:t[0]}}:o.length===1?{dataset:e,mapping:{x:s,y:o[0]??"",label:t[0]}}:{dataset:e.reshapeFromWideToLong({keep:[s,...t,...n],keyName:Y,valueName:ne}),mapping:{x:s,y:ne,label:t[0],color:Y}}},yd=e=>{const{categorical:t,temporal:n,numeric:r}=e.groupVariableNamesByType();let s,o;if(h(t[0])&&h(r[0]))s=t[0],o=r[0];else if(h(n[0])&&h(r[0]))s=n[0],o=r[0];else if(h(r[0])&&h(r[1]))s=r[0],o=r[1];else throw new Error("No label or value variable found");return{x:"",y:o,color:s}},Ro=(e,t,n)=>{const{dataset:r,mapping:s,seriesVariables:o}=Gn(e.dataset),a=zn({appearance:n,seriesVariables:o}),i=[C.line({params:{lineWidth:t?.lineThickness,interpolate:t?.isSmoothLine?"catmull-rom":"linear",missingValues:t?.missingValues}})];return t?.showPoints&&i.push(C.point({params:{size:Po(t.pointSize)},interactive:!1})),{dataset:r,layers:i,coords:B.cartesian(),mapping:{...s,...a.mapping},scales:a.scales,seriesVariables:o}},gd=(e,t,n)=>{const{dataset:r,mapping:s,seriesVariables:o}=Gn(e.dataset),a=zn({appearance:n,seriesVariables:o}),i=[C.area({position:"stack",params:{lineWidth:t?.lineThickness,interpolate:t?.isSmoothLine?"catmull-rom":"linear",missingValues:t?.missingValues}})];return t?.showPoints&&i.push(C.point({params:{size:Po(t.pointSize)},position:"stack",interactive:!1})),{dataset:r,layers:i,coords:B.cartesian(),mapping:{...s,...a.mapping},scales:a.scales,seriesVariables:o}},fe=(e,t,n,r,s)=>{const{dataset:o,mapping:a,seriesVariables:i}=Gn(e.dataset),c=[];if(r?.sortBars){const l=v(a.y);l!==null&&l!==""&&c.push(ge.sort({variableName:l,direction:"desc"}))}if(!s?.useSingleColorForBars){const l=Bn(e.dataset),{numeric:u}=e.dataset.groupVariableNamesByType();u.filter(p=>p!==l).length===1&&e.dataset.getType(l)==="categorical"&&(a.color=l)}return{dataset:o,layers:[C.bar({position:t})],coords:n,mapping:a,scales:[],transforms:c,seriesVariables:i}},rs=(e,t)=>({dataset:e.dataset,layers:[C.bar({position:"fill"})],coords:B.polar({theta:"y",innerRadius:t==="donut"?.55:0}),mapping:yd(e.dataset),scales:[],seriesVariables:[]}),bd=e=>{const{dataset:t,mapping:n}=hd(e.dataset);return{dataset:t,layers:[C.point()],coords:B.cartesian(),mapping:n,scales:[],seriesVariables:[]}},vd=e=>{const{numeric:t,categorical:n}=e.dataset.groupVariableNamesByType(),r=t[0];if(!h(r))throw new Error("No first numeric variable found");const o=h(t[1])?e.dataset:e.dataset.addConstantVariable(Tt,"categorical",""),a={x:r,y:t[1]??Tt,size:t[2],label:n[0]},i=[];return h(a.size)&&i.push(be.size.continuous()),{dataset:o,layers:[C.point()],coords:B.cartesian(),mapping:a,scales:i,seriesVariables:[]}},rn=(e,t,n)=>{const r=n?.seriesStyles?.[e]?.lineStyle;return C.line({transforms:[ge.constant({variableName:ts,type:"categorical",value:e})],aes:{y:e,color:ts,...r?{lineType:{value:r}}:{}},...t?{yScaleType:"secondary"}:void 0})},Sd=(e,t,n)=>{const{numeric:r,categorical:s,temporal:o}=e.dataset.groupVariableNamesByType(),a=Bn(e.dataset),i=[...s,...o],c=r.filter(b=>b!==a),l=t?.comboType??"grouped-bars",u=l==="lines";if(c.length===1)return u?Ro(e,t,n):fe(e,"dodge",B.cartesian(),t,n);const d=e.axes?.hasDualYAxis===!0,p=u?[]:c.slice(0,-1),m=u?c:c.slice(-1),f=[],y=[];if(p.length>0){const b=l==="stacked-bars"?"stack":"dodge",x=p.length===1?p[0]:null;h(x)?f.push(C.bar({transforms:[ge.constant({variableName:ns,type:"categorical",value:x})],aes:{y:x,color:ns},position:b})):f.push(C.bar({transforms:[ge.reshape({keep:i,reshape:p,keyName:Y,valueName:ne})],aes:{y:ne,color:Y},position:b}))}if(u&&m.length>=2){const b=d?m.slice(0,-1):m,x=b.length===1?b[0]:null;if(h(x))f.push(rn(x,!1,n));else{const S=zn({appearance:n,seriesVariables:b});f.push(C.line({transforms:[ge.reshape({keep:i,reshape:b,keyName:Y,valueName:ne})],aes:{y:ne,color:Y,...S.mapping}})),y.push(...S.scales)}if(d){const S=m[m.length-1];h(S)&&f.push(rn(S,!0,n))}}else for(const b of m)f.push(rn(b,d,n));return{dataset:e.dataset,layers:f,coords:B.cartesian(),mapping:{x:a},scales:y,seriesVariables:c}},Po=(e="auto")=>e==="auto"?bt.params.size:e,Ge=e=>()=>{throw new Error(`Unsupported graph type: ${e}`)},xd={line:(e,t,n)=>Ro(e,t,n),areaStacked:(e,t,n)=>gd(e,t,n),bar:(e,t,n)=>fe(e,"dodge",B.flip(),t,n),barStacked:(e,t,n)=>fe(e,"stack",B.flip(),t,n),barStackedFill:(e,t,n)=>fe(e,"fill",B.flip(),t,n),column:(e,t,n)=>fe(e,"dodge",B.cartesian(),t,n),columnStacked:(e,t,n)=>fe(e,"stack",B.cartesian(),t,n),columnStackedFill:(e,t,n)=>fe(e,"fill",B.cartesian(),t,n),pie:e=>rs(e,"pie"),donut:e=>rs(e,"donut"),scatter:e=>bd(e),bubble:e=>vd(e),combo:(e,t,n)=>Sd(e,t,n),funnel:Ge("funnel"),heatmap:Ge("heatmap"),waterfall:Ge("waterfall"),mekko:Ge("mekko"),table:Ge("table")},No=["key",A("lineSeriesLabel"),A("barSeriesLabel")];function wd(e){const t=e.annotations??[],n=Ad(e.mapping),r=Ld(e.convertedDataset,e.layers),s=[];for(const o of t){if(o.type!=="highlight")continue;const a=Td({annotation:o,rowIdentityVariable:n,dataset:e.dataset,compiledVariableNames:r});a!==null&&s.push({type:"highlight",id:o.id,predicate:a,scope:o.highlight})}return s}function Ad(e){const t=v(e.x);return t!==null&&t!==""?t:v(e.color)}function Td({annotation:e,rowIdentityVariable:t,dataset:n,compiledVariableNames:r}){switch(e.highlight){case"x-value":return ss(e,t,n);case"series":return os(e,r);case"data-point":{const s=ss(e,t,n),o=os(e,r);return s===null&&o===null?null:s===null?o:o===null?s:{and:[s,o]}}}}function ss(e,t,n){if(t===null)return null;const r=Vd(e,t,n);return r===null?null:{variable:t,eq:r}}function os(e,t){if(!Md(t))return null;const n=e.columnKey;return h(n)?{or:No.map(r=>({variable:r,eq:n}))}:null}function Md(e){return No.some(t=>e.includes(t))}function Ld(e,t){const n=[...e.getVariableNames()];for(const r of t)for(const s of r.transforms??[])s.transformType==="reshape"?n.push(s.options.keyName??Y):s.transformType==="constant"&&n.push(s.options.variableName);return n}function Vd(e,t,n){return e.rowValue!==void 0?e.rowValue:!h(e.rowIndex)||!n.getVariableNames().includes(t)?null:n.getValues(t)[e.rowIndex]??null}function kd(e,t,n){const{theme:r,customPalettes:s}=n;if(s&&e&&s[e])return{type:"custom",id:e};if(e?.startsWith("preset:pastel"))return{type:"pastel",variant:sn(t)};if(e?.startsWith("preset:graphy"))return{type:"graphy",variant:sn(t)};const i="preset:mono:";if(e?.startsWith(i)){const l=e.slice(i.length);if(Ed(l))return{type:"mono",base:l,variant:r}}const c="preset:neon:";if(e?.startsWith(c)){const l=e.slice(c.length);if(Id(l))return{type:"neon",base:l,variant:sn(t)}}return{type:"default"}}function sn(e){if(e==="waterfall")return"waterfall"}function Ed(e){return ko.includes(e)}function Id(e){return Eo.includes(e)}function Cd(e,t,n,r={}){const s=[];s.push(as("x",t?.x)),s.push(as("y",t?.y));const o=kd(n?.paletteId,e,r);return s.push(be.color.palette({palette:o})),s}function as(e,t){return t?.scaleType==="logarithmic"||t?.min!==void 0||t?.max!==void 0?t.scaleType==="logarithmic"?be[e].log({domainMin:t.min??void 0,domainMax:t.max??void 0}):be[e]({domainMin:t.min??void 0,domainMax:t.max??void 0}):be[e]()}const Fd=new Set(["column","columnStacked","columnStackedFill","bar","barStacked","barStackedFill","line","areaStacked","scatter","bubble","funnel","combo"]),Dd=new Set(["column","columnStacked","columnStackedFill","bar","barStacked","barStackedFill","line","areaStacked","combo"]);function _d(e,t,n){const r=t.type??"column",s={dataset:e,axes:t.axes},o=fd(s,r,t.options??void 0,t.appearance??void 0);return{data:o.dataset,mapping:o.mapping,layers:Rd(r,t,o.layers,o.coords,o.mapping,o.seriesVariables),scales:[...Cd(r,t.axes,t.appearance,n),...o.scales],transforms:o.transforms??[],highlights:wd({annotations:t.annotations,dataset:e,mapping:o.mapping,convertedDataset:o.dataset,layers:o.layers}),annotations:Uu({annotations:t.annotations,dataset:e,mapping:o.mapping}),coords:o.coords,config:ed(t)}}function Rd(e,t,n,r,s,o){const a=Bd(t.dataLabels),i=a===void 0?n:n.filter(l=>l.interactive!==!1).map(l=>({...l,dataLabels:{...a,...l.dataLabels}})),c=t.axes?.hasDualYAxis??!1;return[...i,...Pd({type:e,trendline:t.referenceLines?.trendline,coords:r}),...Nd({type:e,hasDualYAxis:c,goalLine:t.referenceLines?.goalLine,coords:r}),...$d({type:e,hasDualYAxis:c,averageLine:t.referenceLines?.averageLine,coords:r,mapping:s,seriesVariables:o})]}function Pd({type:e,trendline:t,coords:n}){return t===void 0?[]:Fd.has(e)?n.coordType==="polar"?[]:[C.line({aes:{lineType:{value:"dashed"}},stat:$n.smooth({method:t}),interactive:!1})]:[]}function Nd({type:e,hasDualYAxis:t,goalLine:n,coords:r}){if(!Od(n))return[];if(r.coordType==="polar")return[];const s=r.coordType==="flip"?"end":"start";return[C.rule({aes:{y:{value:n.target}},params:{labelPosition:s,label:n.label??"Goal"},yScaleType:e==="combo"&&t?"secondary":"primary",interactive:!1})]}function Od(e){return e!==void 0&&Number.isFinite(e.target)}function $d({type:e,hasDualYAxis:t,averageLine:n,coords:r,mapping:s,seriesVariables:o}){if(n===void 0)return[];if(!Dd.has(e))return[];if(r.coordType==="polar")return[];const a=Co(n.columnKey);if(!o.includes(a))return[];const i=s.color===Y,c=i?ne:a,l=i?[ge.filter({variableName:Y,operator:"eq",value:a})]:[];return[C.rule({aes:{y:c,color:void 0,group:void 0,lineType:void 0},stat:$n.mean(),transforms:l,params:{label:"Average",labelPosition:r.coordType==="flip"?"end":"start"},yScaleType:e==="combo"&&t?"secondary":"primary",interactive:!1})]}function Bd(e){if(!e)return;const t={};return e.showDataLabels!==void 0&&(t.showDataLabels=e.showDataLabels),e.dataLabelFormat!==void 0&&(t.format=e.dataLabelFormat),e.showStackTotals!==void 0&&(t.showStackTotals=e.showStackTotals),e.showCategoryLabels!==void 0&&(t.showCategoryLabels=e.showCategoryLabels),Object.keys(t).length===0?void 0:t}const on={color:null,size:"small",labelCrossPosition:.5},Le={kind:"rectangle",zOrder:"foreground",fillColor:"transparent",fillOpacity:1,strokeWidth:1,strokeColor:null},is={backgroundColor:null,backgroundColorStyle:"opaque"},Ve={color:null,thickness:"medium",startArrowheadStyle:"none",endArrowheadStyle:"line-arrow",lineStyle:"solid",hasStickerStyle:!1},Gd=(e,t)=>({differenceArrows:(e?.differenceArrows??[]).map(n=>Wd(n,t)),shapes:(e?.shapes??[]).map(qd),freeformArrows:(e?.freeformArrows??[]).map(jd),textAnnotations:(e?.textAnnotations??[]).map(Yd),stickers:(e?.stickers??[]).map(n=>Hd(n,t)),pinnedNumbers:(e?.pinnedNumbers??[]).map(n=>Kd(n,t)),comments:(e?.comments??[]).map(n=>Xd(n,t)),custom:(e?.custom??[]).map(n=>zd(n,t))}),zd=(e,t)=>({id:e.id??crypto.randomUUID(),type:e.type,coordinates:e.coordinates.map(n=>Ud(n,t)),params:e.params??{},zOrder:e.zOrder??null}),Ud=(e,t)=>"observation"in e?{observation:Ee(e.observation,t)}:e,Yd=e=>({id:e.id??crypto.randomUUID(),content:e.content,x:e.x,y:e.y,width:e.width,backgroundColor:e.backgroundColor??is.backgroundColor,backgroundColorStyle:e.backgroundColorStyle??is.backgroundColorStyle}),Wd=(e,t)=>({id:e.id??crypto.randomUUID(),start:Ee(e.start,t),end:Ee(e.end,t),label:e.label,color:e.color??on.color,size:e.size??on.size,labelCrossPosition:e.labelCrossPosition??on.labelCrossPosition}),Ee=(e,t)=>{if(e.layerIndex===void 0)return{anchorValue:e.anchorValue,groupValue:e.groupValue};const n=t[e.layerIndex]?.id;if(n===void 0)throw new Error(`Annotation references layerIndex ${e.layerIndex} but only ${t.length} layer(s) are defined.`);return{layerId:n,anchorValue:e.anchorValue,groupValue:e.groupValue}},Hd=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:Ee(e.anchor,t),sticker:e.sticker}),Kd=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:Ee(e.anchor,t)}),Xd=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:Ee(e.anchor,t),content:e.content}),qd=e=>({id:e.id??crypto.randomUUID(),kind:e.kind??Le.kind,zOrder:e.zOrder??Le.zOrder,x:e.x,y:e.y,width:e.width,height:e.height,fillColor:e.fillColor??Le.fillColor,fillOpacity:e.fillOpacity??Le.fillOpacity,strokeWidth:e.strokeWidth??Le.strokeWidth,strokeColor:e.strokeColor??Le.strokeColor}),jd=e=>({id:e.id??crypto.randomUUID(),start:e.start,end:e.end,color:e.color??Ve.color,thickness:e.thickness??Ve.thickness,startArrowheadStyle:e.startArrowheadStyle??Ve.startArrowheadStyle,endArrowheadStyle:e.endArrowheadStyle??Ve.endArrowheadStyle,lineStyle:e.lineStyle??Ve.lineStyle,hasStickerStyle:e.hasStickerStyle??Ve.hasStickerStyle}),Qd={parsingLocale:"en-US",legend:{position:"auto",display:"auto"},axes:{x:{isVisible:!0,label:null,position:"bottom",grid:{isVisible:null},ticks:{isVisible:!0,mode:"auto"}},y:{isVisible:!0,label:null,position:"right",grid:{isVisible:null},ticks:{isVisible:!1,mode:"auto"}}},panel:{border:{isVisible:!0}},headline:{show:"none",compareWith:"none",size:"auto",position:"above"},numberFormat:{decimals:"auto",abbreviation:"auto"},content:{title:null,isTitleVisible:!0,subtitle:null,isSubtitleVisible:!0,caption:null,isCaptionVisible:!1,source:null,isSourceVisible:!1},appearance:{textScale:1,background:{type:"theme"},border:{type:"none"},cornerRadius:8,highlightStyle:"dim"}};function Zd(e){return ce.merge({},Qd,e)}const Jd={xLimits:null,yLimits:null},an={theta:"x",startAngle:0,innerRadius:0};function ep(e){const t=e??{type:"coord",coordType:"cartesian"},n=Is({},Jd,t.params??{});switch(t.coordType){case"cartesian":case"flip":return{...t,params:n};case"polar":return{...t,params:{...n,theta:t.params?.theta??an.theta,startAngle:t.params?.startAngle??an.startAngle,innerRadius:t.params?.innerRadius??an.innerRadius}}}}function tp(e,t){return e.map(n=>{const r=n.layerIndex!==void 0?t[n.layerIndex]?.id:void 0;if(n.layerIndex!==void 0&&r===void 0)throw new Error(`Highlight references layerIndex ${n.layerIndex} but only ${t.length} layer(s) are defined.`);return{type:"highlight",id:n.id??crypto.randomUUID(),predicate:n.predicate,scope:n.scope??"data-point",...r!==void 0?{layerId:r}:{}}})}const np="linear",rp=3,sp=.3;function Pe(e,t){const n=e??t,r=typeof n=="string"?n:n.type;if(r==="smooth"){const s=typeof n=="string"?void 0:n;return{type:"smooth",method:s?.method??np,order:s?.order??rp,bandwidth:s?.bandwidth??sp}}return{type:r}}function Oo(e,t,n){if(!ip(n))return cp(e,t,n);switch(n.geom){case"point":return lp(e,t,n);case"line":return up(e,t,n);case"area":return dp(e,t,n);case"bar":return pp(e,t,n);case"rule":return mp(e,t,n)}}function op(e,t,n){const r=n.map(s=>Oo(e,t,s));return fp(r)}const ap=(e,t,n)=>n.label!==void 0?n.label:hp(e,t,n),ip=e=>vo(e.geom);function cp(e,t,n){const r=n.position??"identity";return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Pe(n.stat,"identity"),position:r,yScaleType:n.yScaleType??Re,params:n.params??{},transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Ne(e,n,r,t)}}const Ne=(e,t,n,r)=>{const s={...e,...t.mapping},o=ap(t.geom,n,s);return{...md(t.geom,r),...t.dataLabels,labelSource:o}};function lp(e,t,n){const r=n.position??bt.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Pe(n.stat,bt.stat.type),position:r,yScaleType:n.yScaleType??Re,params:ce.merge({},bt.params,n.params),transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Ne(e,n,r,t)}}function up(e,t,n){const r=n.position??en.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Pe(n.stat,en.stat.type),position:r,yScaleType:n.yScaleType??Re,params:ce.merge({},en.params,n.params),transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Ne(e,n,r,t)}}function dp(e,t,n){const r=ce.merge({},tn.params,n.params);r.missingValues==="gap"&&(r.missingValues="zero");const s=n.position??tn.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Pe(n.stat,tn.stat.type),position:s,yScaleType:n.yScaleType??Re,params:r,transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Ne(e,n,s,t)}}function pp(e,t,n){const r=n.position??nn.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Pe(n.stat,nn.stat.type),position:r,yScaleType:n.yScaleType??Re,params:{...nn.params,...n.params},transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Ne(e,n,r,t)}}function mp(e,t,n){const r=n.position??Be.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Pe(n.stat,Be.stat.type),position:n.position??Be.position,yScaleType:n.yScaleType??Re,params:ce.merge({},Be.params,n.params),transforms:n.transforms??[],interactive:n.interactive??Be.interactive,dataLabels:Ne(e,n,r,t)}}const fp=e=>{const t=new Set;for(const n of e)n.position==="fill"&&t.add(n.yScaleType);return t.size===0?e:e.map(n=>{if(n.geom!=="rule"||!t.has(n.yScaleType))return n;const r=re(n.mapping.y);if(!F(r))return n;const s=Math.min(1,Math.max(0,r));return{...n,mapping:{...n.mapping,y:{value:s}}}})},hp=(e,t,n)=>{if(e==="point"){const r=v(n.size);if(r!==null)return{variable:r}}return nt(t,n)};function Rt(e,...t){return e?t.includes(e.geom):!1}function Pt(e,t){return e.find(n=>n.id===t)}function st(e,...t){return e.find(n=>t.includes(n.geom))}function Un(e,t,n){const r=e.layers.findIndex(o=>o.id===t);if(r===-1)return e;const s=e.layers.map((o,a)=>a===r?n:o);return{...e,layers:s}}function yp(e,t){const n=e.layers.findIndex(s=>s.id===t);if(n===-1||e.layers.length<=1)return e;const r=e.layers.filter((s,o)=>o!==n);return Mn(r)?{...e,layers:r}:e}const $o={x:"position",y:"position",ySecondary:"position",color:"color-range",size:"continuous-range",alpha:"continuous-range",strokeWidth:"continuous-range",lineType:"discrete-only"},gp={numeric:{position:"continuous","color-range":"continuous","continuous-range":"continuous","discrete-only":"discrete"},categorical:{position:"discrete","color-range":"discrete","continuous-range":"discrete","discrete-only":"discrete"},temporal:{position:"datetime","color-range":"continuous","continuous-range":"continuous","discrete-only":"discrete"}};function Bo(e,t,n,r,s){switch(e.scaleType){case"inferred":{const o=Sp(e,t,n,r);return Bo(o,t,n,r,s)}case"continuous":{const o=$o[e.scaledAesthetic],a=o==="continuous-range"&&e.scaledAesthetic in Qr?Qr[e.scaledAesthetic]:null,i=e.scaledAesthetic==="size"&&o==="continuous-range"?"sqrt":Me.transform;return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,transform:e.transform??i,reverse:e.reverse??Me.reverse,nice:e.nice??Me.nice,zero:e.zero??Me.zero,clamp:e.clamp??o!=="position",domainMin:e.domainMin??Me.domainMin,domainMax:e.domainMax??Me.domainMax,range:e.range??a??null}}case"datetime":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,domainMin:e.domainMin??ct.domainMin,domainMax:e.domainMax??ct.domainMax,nice:e.nice??ct.nice,reverse:e.reverse??ct.reverse,clamp:e.clamp??!1};case"discrete":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,range:e.range??Ue.range,domain:e.domain??Ue.domain,padding:e.padding??Ue.padding,reverse:e.reverse??Ue.reverse};case"palette":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,palette:Lu(e.palette,s)};case"identity":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType};default:{const o=e;throw new Error(`Unknown scale type: ${o.scaleType}`)}}}function bp(e,t,n,r,s,o){const a=wp(t,n),i=Ap(a),c=new Map;for(const u of i)c.set(u.scaledAesthetic,u);const l=[...c.values()].map(u=>Bo(u,e,n,r,o));return s.coordType==="polar"?vp(l):l}const vp=e=>e.map(t=>t.scaleType==="discrete"?{...t,padding:0}:t);function Sp(e,t,n,r){const s=J(e.scaledAesthetic),o=e.scaledAesthetic==="ySecondary"?xp(n,r):r[s],a=st(n,"bar");if(e.scaledAesthetic==="x"&&a)return j(e.scaledAesthetic,e.options);if(a&&e.scaledAesthetic===(a.yScaleType==="secondary"?"ySecondary":"y")){const d=e.options,p=a.position==="fill";return R(e.scaledAesthetic,{...d,zero:!0,...p&&{nice:!1}})}const i=v(o);if(!h(i)||!t.hasVariable(i))return R(e.scaledAesthetic,e.options);const c=t.getType(i),l=$o[e.scaledAesthetic];switch(gp[c][l]){case"discrete":return j(e.scaledAesthetic,e.options);case"datetime":return vt(e.scaledAesthetic,e.options);case"continuous":return R(e.scaledAesthetic,e.options);case"identity":default:return Ye(e.scaledAesthetic)}}function xp(e,t){const n=e.find(r=>r.yScaleType==="secondary");return n?n.mapping.y??t.y:t.y}function wp(e,t){return!t.some(s=>s.yScaleType==="secondary")||e.some(s=>s.scaledAesthetic==="ySecondary")?e:[...e,St("ySecondary")]}function Ap(e){return e.some(n=>n.scaledAesthetic==="color")?e:[...e,_o("color")]}function cs(e,t){const n=ep(e.coords),r=op(e.mapping,n.coordType,e.layers),s=bp(e.data,e.scales,r,e.mapping,n,t),o=Zd(e.config),a=tp(e.highlights,r),i=Gd(e.annotations,r);return{data:e.data,mapping:e.mapping,layers:r,scales:s,transforms:e.transforms,highlights:a,annotations:i,coords:n,config:o}}class Go{compile({input:t,dataset:n,ctx:r}){const s=r.customPalettes??{};return Io(t)?cs(_d(n,t,r),s):cs({...t,data:n},s)}}class Tp{constructor(t){this.registry=t}compute(t,n){return this.registry.get(t.type).compute({data:n.data,mapping:n.mapping,spec:t,xScaleIsDiscrete:n.xScaleIsDiscrete})}}class Nt{compute(t){return t.data.size()===0?{data:t.data,mapping:{}}:this.computeStat(t)}}class Mp extends Nt{constructor(){super(...arguments),this.type="count",this.computedVariables=new Set(["y"])}computeStat({data:t,mapping:n}){const r=v(n.x);if(!h(r))throw new Error("'x' variable is required for 'count' stat");if(v(n.y)!==null)throw new Error("Cannot map 'y' variable together with 'count' stat");const o=[...new Set([r,...Cn(t,n)])];return{data:t.groupBy(...o).rollup({[Ke.count]:{variableName:r,aggregation:"count"}}),mapping:{y:Ke.count}}}}class Lp extends Nt{constructor(){super(...arguments),this.type="identity",this.computedVariables=new Set}computeStat({data:t}){return{data:t,mapping:{}}}}class Vp extends Nt{constructor(){super(...arguments),this.type="mean",this.computedVariables=new Set(["y"])}computeStat({data:t,mapping:n}){const r=v(n.y);if(!h(r))throw new Error("'y' variable is required for 'mean' stat");return{data:t.rollup({[Ke.mean]:{variableName:r,aggregation:"mean"}}),mapping:{y:Ke.mean}}}}const kp=2,zo=1440*60*1e3;class Ep extends Nt{constructor(){super(...arguments),this.type="smooth",this.computedVariables=new Set}computeStat({data:t,mapping:n,spec:r,xScaleIsDiscrete:s}){if(r.type!=="smooth")throw new Error(`SmoothStat received a spec of type '${r.type}'`);const o=v(n.x),a=v(n.y);if(!h(o))throw new Error("'x' variable is required for 'smooth' stat");if(!h(a))throw new Error("'y' variable is required for 'smooth' stat");const i=t.getType(o),c=t.getType(a);if(c!=="numeric")throw new Error(`'smooth' stat requires a numeric 'y' (got '${c}' for variable '${a}')`);const l=Cn(t,n),u=Pp(o,i,a,l,t);return l.length===0?ls({data:t,xVariable:o,xType:i,yVariable:a,spec:r,output:u,groupObservation:{},xScaleIsDiscrete:s}):t.groupBy(...l).forEach(d=>{const p=Np(d,l);ls({data:d,xVariable:o,xType:i,yVariable:a,spec:r,output:u,groupObservation:p,xScaleIsDiscrete:s})}),{data:u.build(),mapping:{}}}}const ls=({data:e,xVariable:t,xType:n,yVariable:r,spec:s,output:o,groupObservation:a,xScaleIsDiscrete:i})=>{const{observations:c,temporalOrigin:l}=Ip({data:e,xVariable:t,yVariable:r,xType:n});c.length<kp||(i?Rp({observations:c,spec:s,output:o,groupObservation:a}):Dp({observations:c,xType:n,temporalOrigin:l,spec:s,output:o,groupObservation:a}))},Ip=({data:e,xVariable:t,yVariable:n,xType:r})=>{const s=e.getValues(t),o=e.getValues(n,{type:"numeric"}),a=r==="temporal"?Cp(s):null,i=[],c=new Map;for(let l=0;l<s.length;l++){const u=s[l],d=o[l];if(!h(u)||!h(d)||!Number.isFinite(d))continue;const p=Fp({xValue:u,xType:r,categoryRank:c,temporalOrigin:a});p!==null&&i.push({x:p,y:d,originalX:u})}return{observations:i,temporalOrigin:a}},Cp=e=>{let t=null;for(const n of e){if(!G(n))continue;const r=n.getTime();(t===null||r<t)&&(t=r)}return t},Fp=({xValue:e,xType:t,categoryRank:n,temporalOrigin:r})=>{switch(t){case"numeric":return!F(e)||!Number.isFinite(e)?null:e;case"temporal":{if(!G(e))return null;const s=e.getTime();return r===null?s:(s-r)/zo+1}case"categorical":{if(!Ze(e))return null;const s=n.get(e);if(s!==void 0)return s;const o=n.size+1;return n.set(e,o),o}default:{const s=t;throw new Error(`Unexpected xType: ${s}`)}}},Dp=({observations:e,xType:t,temporalOrigin:n,spec:r,output:s,groupObservation:o})=>{const a=Uo(r,e);for(const[i,c]of a){if(!Number.isFinite(i)||!Number.isFinite(c))continue;const l=t==="temporal"?_p(i,n):i;s.push({x:l,y:c,groupObservation:o})}},_p=(e,t)=>t===null?new Date(e):new Date((e-1)*zo+t),Rp=({observations:e,spec:t,output:n,groupObservation:r})=>{const s=new Map;for(const i of e)s.has(i.x)||s.set(i.x,i.originalX);const o=[...s.keys()].sort((i,c)=>i-c);if(t.method==="loess"){const i=Uo(t,e),c=new Map;for(const[l,u]of i)Number.isFinite(u)&&(c.has(l)||c.set(l,u));for(const l of o){const u=c.get(l),d=s.get(l);u===void 0||d===void 0||n.push({x:d,y:u,groupObservation:r})}return}const a=Yo(t,e);for(const i of o){const c=s.get(i),l=a.predict(i);c===void 0||!Number.isFinite(l)||n.push({x:c,y:l,groupObservation:r})}},Uo=(e,t)=>e.method==="loess"?me.regressionLoess().x(r=>r.x).y(r=>r.y).bandwidth(e.bandwidth)(t):Yo(e,t),Yo=(e,t)=>{const n=s=>s.x,r=s=>s.y;switch(e.method){case"linear":return me.regressionLinear().x(n).y(r)(t);case"exponential":return me.regressionExp().x(n).y(r)(t);case"logarithmic":return me.regressionLog().x(n).y(r)(t);case"quadratic":return me.regressionQuad().x(n).y(r)(t);case"power":return me.regressionPow().x(n).y(r)(t);case"polynomial":return me.regressionPoly().x(n).y(r).order(e.order)(t);case"loess":throw new Error("'loess' does not expose a 'predict' function")}},Pp=(e,t,n,r,s)=>{const o=[],a=[],i=Object.fromEntries(r.map(c=>[c,[]]));return{push:({x:c,y:l,groupObservation:u})=>{o.push(c),a.push(l);for(const d of r)i[d]?.push(u[d]??null)},build:()=>{const c={[e]:{type:t,values:o,valueFormat:s.getValueFormat(e)},[n]:{type:"numeric",values:a,valueFormat:s.getValueFormat(n)}};for(const l of r)c[l]={type:s.getType(l),values:i[l]??[],valueFormat:s.getValueFormat(l)};return new V(c)}}},Np=(e,t)=>{const n={};for(const r of t){const s=e.getValues(r);n[r]=s[0]??null}return n};class Op extends Fe{constructor(){super("stat"),this.register("identity",new Lp),this.register("count",new Mp),this.register("smooth",new Ep),this.register("mean",new Vp)}}const $p=({layer:e})=>{if(e.position==="stack")return;const t=v(e.mapping.y);if(t===null)return;let n=0,r=0;for(const s of e.data){const o=s[t];F(o)&&(n+=o,r+=Math.abs(o))}return{grandTotal:n,absoluteGrandTotal:r}},Bp=({layer:e})=>{if(e.position!=="stack")return;const t=v(e.mapping.x);if(t===null||!e.data.hasVariable(g.yMin)||!e.data.hasVariable(g.yMax))return;const n=new Map;for(const s of e.data){const o=s[t],a=Se(s),i=Z(s),c=qe(s),l=ke(s),u=co(s);if(!h(o)||!h(a)||!h(i)||!h(c)||!h(l)||!h(u))continue;const d=u>=0;if(Math.abs(u)===0)continue;const m=_n(s,t),f={yMin:a,yMax:i},y=n.get(m);if(y===void 0){n.set(m,{total:u,topPositive:d?f:null,bottomNegative:d?null:f,anchorXMin:c,anchorXMax:l});continue}y.total+=u,d?(y.topPositive===null||i>y.topPositive.yMax)&&(y.topPositive=f):(y.bottomNegative===null||a<y.bottomNegative.yMin)&&(y.bottomNegative=f)}const r=[];for(const[s,o]of n){const a=o.topPositive??o.bottomNegative;a!==null&&r.push({xKey:s,total:o.total,anchor:{xMin:o.anchorXMin,xMax:o.anchorXMax,yMin:a.yMin,yMax:a.yMax,direction:o.topPositive!==null?"positive":"negative"}})}return r};class Gp extends Ce{constructor(t){super(),this.geomCompiler=t}dependencies(){return[]}compileLayer(t){const n={};if(this.geomCompiler.emitsStackTotals(t.geom)){const r=Bp({layer:t});r!==void 0&&(n.stackTotals=r)}if(this.geomCompiler.emitsGrandTotal(t.geom)){const r=$p({layer:t});r!==void 0&&(n.grandTotal=r.grandTotal,n.absoluteGrandTotal=r.absoluteGrandTotal)}return{...t,summary:n}}}class zp extends le{constructor(t){super(),this.registry=t}key(t){return t.data}dependencies(t){return[t.transforms]}run(t){return t.transforms.reduce((n,r)=>this.registry.get(r.transformType).apply(n,r),t.data)}}class Up{constructor(){this.transformType="aggregate"}apply(t,n){const{options:r}=n,s={};for(const o of r.operations)s[o.as]={variableName:o.variableName,aggregation:o.op};return t.groupBy(...r.groupby).rollup(s)}}class Yp{constructor(){this.transformType="constant"}apply(t,n){const{options:r}=n;return t.addConstantVariable(r.variableName,r.type,r.value)}}class Wp{constructor(){this.transformType="filter"}apply(t,n){const{options:r}=n;return t.filter(r.variableName,r.operator,r.value)}}class Hp{constructor(){this.transformType="reshape"}apply(t,n){const{options:r}=n;return t.reshapeFromWideToLong({keep:r.keep,reshape:r.reshape,keyName:r.keyName,valueName:r.valueName})}}class Kp{constructor(){this.transformType="sort"}apply(t,n){const{options:r}=n;return t.orderBy(r.variableName,r.direction??"asc")}}class Xp extends Fe{constructor(){super("transform"),this.register("aggregate",new Up),this.register("constant",new Yp),this.register("filter",new Wp),this.register("reshape",new Hp),this.register("sort",new Kp)}}const us={color:"categorical",size:"numeric",alpha:"numeric",strokeWidth:"numeric",lineType:"categorical"};class qp extends Ce{constructor(t){super(),this.geomCompiler=t}dependencies(t){return[...Ct].map(n=>t.scales[n])}compileLayer(t,n){const r=this.geomCompiler.getVisualAesthetics(t.geom),s=jp(t.data,t.mapping,r,n.scales);return{...t,data:s}}}function jp(e,t,n,r){let s=e;for(const o of n){const a=ue[o],i=re(t[o]);if(i!==void 0){s=s.deriveVariable(a,us[o],()=>i);continue}const c=v(t[o]),l=r[o];if(!l||l.kind!=="visual")continue;const u=Qp(o,c,l);u&&(s=s.deriveVariable(a,us[o],u))}return s}const Qp=(e,t,n)=>{if(!t){if(e!=="color"||n.spec.scaleType!=="palette")return null;const r=n.map(null);return()=>r}return r=>h(r[t])?n.map(r[t]):null},Zp=["data","transform","constantMapping","layer","coordSetup","scale","positionMapper","visualMapper","coordTransform","summarise","guide","highlights","config","annotations"];class Wo{constructor(t,n,r,s,o,a,i,c,l,u,d,p,m,f,y){this.dataCompiler=t,this.specCompiler=n,this.transformCompiler=r,this.constantMappingCompiler=s,this.layerValidationCheck=o,this.layerCompiler=a,this.scaleCompiler=i,this.coordCompiler=c,this.positionMapperCompiler=l,this.visualMapperCompiler=u,this.guideCompiler=d,this.summariseCompiler=p,this.highlightsCompiler=m,this.configCompiler=f,this.annotationsCompiler=y,this.lastCompile=null,this.lastData=void 0,this.stages=[{name:"data",getStats:()=>this.dataCompiler.stats},{name:"transform",getStats:()=>this.transformCompiler.stats},{name:"constantMapping",getStats:()=>this.constantMappingCompiler.stats},{name:"layer",getStats:()=>this.layerCompiler.stats},{name:"coordSetup",getStats:()=>this.coordCompiler.setupStats},{name:"scale",getStats:()=>this.scaleCompiler.stats},{name:"positionMapper",getStats:()=>this.positionMapperCompiler.stats},{name:"visualMapper",getStats:()=>this.visualMapperCompiler.stats},{name:"coordTransform",getStats:()=>this.coordCompiler.transformStats},{name:"summarise",getStats:()=>this.summariseCompiler.stats},{name:"guide",getStats:()=>this.guideCompiler.stats},{name:"highlights",getStats:()=>this.highlightsCompiler.stats},{name:"config",getStats:()=>this.configCompiler.stats},{name:"annotations",getStats:()=>this.annotationsCompiler.stats}]}compile({input:t,data:n,ctx:r={}}){return this.trackCompile(()=>(this.lastData=n,this.runPipeline({spec:this.specCompiler.compile({input:t,ctx:r,dataset:this.dataCompiler.compile(n)})})))}recompile({spec:t,data:n}){return this.trackCompile(()=>n===void 0?this.runPipeline({spec:t}):(this.lastData=n,this.runPipeline({spec:jt(t,{data:this.dataCompiler.compile(n)})})))}getCacheStats(){const t={};for(const{name:n,getStats:r}of this.stages)t[n]={...r()};return t}getLastCompile(){return this.lastCompile}trackCompile(t){if(!ye)return t();const n=this.getCacheStats(),r=performance.now(),s=t(),o=performance.now()-r,a={};for(const{name:i,getStats:c}of this.stages){const l=c();a[i]={hits:l.hits-n[i].hits,misses:l.misses-n[i].misses}}return this.lastCompile={stages:a,durationMs:o},s}runPipeline({spec:t}){return Vt({spec:t}).pipe(({spec:r})=>({spec:jt(r,{data:this.transformCompiler.compile({data:r.data,transforms:r.transforms})})})).pipe(({spec:r})=>{const s=this.constantMappingCompiler.compile({data:r.data,mapping:r.mapping});return{spec:jt(r,{data:s.data,mapping:s.mapping})}}).pipe(({spec:r})=>{const s={data:r.data,layers:r.layers,mapping:r.mapping,coords:r.coords,scales:r.scales};return this.layerValidationCheck.check({...s,coords:r.coords}),{layers:this.layerCompiler.compile(s)}}).pipe(({spec:r,layers:s})=>this.coordCompiler.setup({coordSpec:r.coords,scales:r.scales,layers:s})).pipe(({layers:r,scales:s})=>({scales:this.scaleCompiler.compile({layers:r,scales:s})})).pipe(({spec:r,scales:s})=>({config:this.configCompiler.compile({config:r.config,scales:s})})).pipe(({layers:r,scales:s})=>({layers:this.positionMapperCompiler.compile({layers:r,scales:s})})).pipe(({layers:r,scales:s})=>({layers:this.visualMapperCompiler.compile({layers:r,scales:s})})).pipe(({spec:r,layers:s})=>({layers:this.coordCompiler.transform({coordSpec:r.coords,layers:s})})).pipe(({layers:r})=>({layers:this.summariseCompiler.compile({layers:r})})).pipe(({spec:r,scales:s,layers:o,coordSystem:a})=>({guides:this.guideCompiler.compile({scales:s,config:r.config,layers:o,coordSystem:a,originalData:this.lastData})})).pipe(({spec:r,layers:s})=>({layers:this.highlightsCompiler.compile({layers:s,highlights:r.highlights,config:r.config})})).pipe(({spec:r,layers:s,coordSystem:o,scales:a})=>({annotations:this.annotationsCompiler.compile({annotations:r.annotations,layers:s,coordSystem:o,scales:a})})).result()}}const Jp=e=>{const t=new uc({geoms:e?.geoms}),n=new rc(t),r=new Op,s=new ku,o=new zp(new Xp);return new Wo(new Zi,new Go,o,new ei,new Hl(o,new Kl(t,r)),new Wl(o,new Tp(r),new dc,n,new ql(new eu)),new uu(s),new si(new gi(t)),new lu(t),new qp(n),new xl(n),new Gp(n),new Fl,new Ja,new Ya(n))};function em(e,t){return e.geom===t}const Yn="–",Ho="n/a",$={timeZone:"UTC"},O=e=>t=>{if(!G(t))return Yn;try{return e(t)}catch{return Ho}},de=e=>t=>F(t)?e(t):Yn,Wn=e=>t=>Ze(t)?t:Yn,tm=2,nm=3,rm=2,sm=0,om=1,am=2,im=Va.humanizer({language:"en",spacer:"",delimiter:" ",languages:{en:{y:()=>"y",mo:()=>"mo",w:()=>"w",d:()=>"d",h:()=>"h",m:()=>"m",s:()=>"s",ms:()=>"ms"}}}),Ko=({valueFormat:e,locale:t,numberFormat:n,intlOptions:r})=>de(s=>{const o=typeof n.decimals=="number"?n.decimals:tm,a=qn(s,o),{base:i,suffix:c}=Xn(s,n.abbreviation),l={...a,...Ys(e)?{style:"currency",currencyDisplay:"narrowSymbol",currency:e.iso}:{},...r};return`${Intl.NumberFormat(t,l).format(i)}${c}`}),Hn=({locale:e,numberFormat:t,intlOptions:n})=>de(r=>{const{base:s,suffix:o}=Xn(r,t.abbreviation),i={...qn(s,t.decimals),...n};return`${Intl.NumberFormat(e,i).format(s)}${o}`}),Kn=e=>de(t=>im(t)),Xo=({locale:e,intlOptions:t})=>de(n=>Intl.NumberFormat(e,{maximumFractionDigits:0,...t}).format(n)),qo=({locale:e,numberFormat:t,intlOptions:n})=>de(r=>{const s=qn(r,t.decimals);return Intl.NumberFormat(e,{...s,...n,style:"percent"}).format(r)}),Xn=(e,t="none")=>{switch(t){case"none":return{base:e,suffix:""};case"auto":{const n=cm(e);return Xn(e,n)}default:return{base:e/He[t],suffix:t}}},qn=(e,t)=>{if(typeof t=="number")return{minimumFractionDigits:t,maximumFractionDigits:t};const n=Math.ceil(Math.log10(Math.abs(e))),r=n>=nm?sm:n===rm?om:am;return{minimumFractionDigits:t==="auto"?0:r,maximumFractionDigits:r}},cm=e=>{const t=Math.abs(e);return t>=He.b?"b":t>=He.m?"m":t>=He.k?"k":"none"},lm=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{dateStyle:"medium",...$,...t}).format(n)),um=({locale:e,intlOptions:t})=>O(n=>{const r=Intl.DateTimeFormat(e,{dateStyle:"medium",timeStyle:"medium",...$,...t}).formatToParts(n);return dm(r.map(pm))}),jo=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"long",...$,...t}).format(n)),Qo=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{month:"long",...$,...t}).format(n)),jn=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{month:"short",year:"numeric",...$,...t}).format(n)),Qn=e=>O(t=>`Q${Math.floor(t.getUTCMonth()/3)+1} ${t.getUTCFullYear()}`),Zo=({locale:e,intlOptions:t})=>O(n=>{const r=k.addDays(n,6);return Intl.DateTimeFormat(e,{day:"numeric",month:"long",...$,...t,year:void 0}).formatRange(n,r)}),Jo=({locale:e,intlOptions:t})=>O(n=>{const r=k.addDays(n,6);return Intl.DateTimeFormat(e,{dateStyle:"medium",...$,...t}).formatRange(n,r)}),Zn=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{year:"numeric",...$,...t}).format(n)),ea=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{timeStyle:"short",...$,...t}).format(n)),dm=e=>e.map(t=>t.value).join(""),pm=e=>e.type!=="literal"||e.value!==", "?e:{type:"literal",value:" • "},mm=1,fm=4,hm=1,ds=1e3,ym=({valueFormat:e,locale:t,tickValues:n,intlOptions:r})=>de(s=>{const a={...er(s,n),notation:"compact",...Ys(e)?{style:"currency",currencyDisplay:"narrowSymbol",currency:e.iso}:{},...r};return Jn(s,t,a)}),gm=({locale:e,tickValues:t,intlOptions:n})=>de(r=>{const o={...er(r,t),notation:"compact",...n};return Jn(r,e,o)}),bm=({locale:e,tickValues:t,intlOptions:n})=>de(r=>{const o={...er(r,t),notation:"compact",...n,style:"percent"};return Jn(r,e,o)}),Jn=(e,t,n)=>Intl.NumberFormat(t,n).formatToParts(e).map(s=>s.type==="compact"?s.value.toLowerCase():s.value).join(""),ta=e=>Math.abs(e)>ds?ta(e/ds):Number.isInteger(e),vm=e=>{if(e.length<2)return!1;const[t,n]=e;return typeof t!="number"||typeof n!="number"?!1:Math.abs(n-t)<mm},er=(e,t)=>ta(e)?{minimumFractionDigits:0,maximumFractionDigits:0}:vm(t)?{minimumFractionDigits:0,maximumFractionDigits:fm}:{minimumFractionDigits:0,maximumFractionDigits:hm},Sm=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"short",...$,...t}).format(n)),xm=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{month:"short",...$,...t}).format(n)),wm=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"short",...$,...t}).format(n)),Am=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{timeStyle:"short",...$,...t}).format(n)),tr=e=>{const{valueFormat:t}=e;switch(t.type){case"currency":return ym(e);case"date":case"datetime":return Sm(e);case"day_month":case"weekly_date_range":case"weekly_date_range_with_year":return wm(e);case"decimal":case"integer":return gm(e);case"duration":return Kn();case"month":return xm(e);case"month_year":return jn(e);case"percentage":return bm(e);case"quarter":return Qn();case"text":return Wn();case"time":return Am(e);case"year":return Zn(e);case"lookup":return tr({...e,valueFormat:t.fallback});default:{const n=t;throw new Error(`Unhandled value format: ${n.type}`)}}},Tm=40,Mm=60,ps=8,Lm=50,Vm=1/3,km=1/4,cn="…",Em=(e,t,n)=>{if(t<=0||e.length===0)return"";if(n(e)<=t)return e;if(n(cn)>t)return"";let r=0,s=e.length-1,o=0;for(;r<=s;){const a=r+s>>>1,i=e.slice(0,a)+cn;n(i)<=t?(o=a,r=a+1):s=a-1}return e.slice(0,o)+cn},Im=e=>e.formattedAxis.position==="top"||e.formattedAxis.position==="bottom"?Cm(e):Fm(e),Cm=({formattedAxis:e,bandwidthPx:t,panelRect:n,measureLabel:r})=>{const{widths:s,maxWidth:o,maxHeight:a}=na(e.ticks,r),i=t-ps;if(o<=i)return{...e,labelRotation:0,labelMaxWidthPx:null};if(t>=Lm){const l=xn(i);return{...e,ticks:Sn(e.ticks,s,l,r),labelRotation:0,labelMaxWidthPx:l}}if(a+ps>t)return{...e,ticks:[],labelRotation:0,labelMaxWidthPx:null};const c=xn(n.height*Vm);return{...e,ticks:Sn(e.ticks,s,c,r),labelRotation:-90,labelMaxWidthPx:c}},Fm=({formattedAxis:e,bandwidthPx:t,panelRect:n,measureLabel:r})=>{const{widths:s,maxWidth:o,maxHeight:a}=na(e.ticks,r);if(a>t)return{...e,ticks:[],labelRotation:0,labelMaxWidthPx:null};const i=xn(n.width*km);return o<=i?{...e,labelRotation:0,labelMaxWidthPx:null}:{...e,ticks:Sn(e.ticks,s,i,r),labelRotation:0,labelMaxWidthPx:i}},na=(e,t)=>{const n=[];let r=0,s=0;for(const o of e){const{width:a,height:i}=t(o.formattedLabel);n.push(a),a>r&&(r=a),i>s&&(s=i)}return{widths:n,maxWidth:r,maxHeight:s}},Sn=(e,t,n,r)=>{const s=o=>r(o).width;return e.map((o,a)=>(t[a]??0)<=n?o:{...o,formattedLabel:Em(o.formattedLabel,n,s)})},xn=e=>Math.max(0,Math.floor(e)),Dm=(e,t,n,r)=>{if(e.length===0)return!0;const s=t==="top"||t==="bottom",o=s?Mm:Tm;let a=n-(e.length-1)*o;for(const i of e){const{width:c,height:l}=r(i);if(a-=s?c:l,a<0)return!1}return!0},_m=({axis:e,availableSpacePx:t,measureLabel:n,resolveFormatter:r})=>{const{tickCandidates:s,position:o}=e;if(s.length===0)return[];const a=new Map,i=d=>{const p=a.get(d);if(p)return p;const m=s[d],f=m?Rm(m.ticks,r(m)):[];return a.set(d,f),f};let c=0,l=s.length-1,u=-1;for(;c<=l;){const d=c+l>>>1,m=i(d).map(f=>f.formattedLabel);Dm(m,o,t,n)?(u=d,c=d+1):l=d-1}return u>=0?i(u):i(0)},Rm=(e,t)=>e.map(n=>({...n,formattedLabel:t(n.value)})),ln=6,un=6,dn=15,pn=5,mn=15,nr=(e,t)=>{switch(e){case"small":return{arrowStartGap:ln,arrowEndGap:un,offsetFromHigherObservation:dn,arrowheadSize:pn,curveRadius:mn,strokeWidth:2,labelLineHeight:12*t,labelPaddingX:6,labelPaddingY:3,labelStrokeWidth:1,labelFontWeight:500};case"medium":return{arrowStartGap:ln*1.5,arrowEndGap:un*1.5,offsetFromHigherObservation:dn*1.25,arrowheadSize:pn*1.5,curveRadius:mn*1.25,strokeWidth:3,labelLineHeight:16*t,labelPaddingX:8,labelPaddingY:4,labelStrokeWidth:1.5,labelFontWeight:500};case"large":return{arrowStartGap:ln*2,arrowEndGap:un*2,offsetFromHigherObservation:dn*1.75,arrowheadSize:pn*2.5,curveRadius:mn*1.5,strokeWidth:5,labelLineHeight:20*t,labelPaddingX:10,labelPaddingY:5,labelStrokeWidth:2,labelFontWeight:600}}},Pm=e=>{const t=D({...e,valueFormat:e.valueFormat.fallback}),n={};for(const[s,o]of Object.entries(e.valueFormat.cases))n[s]=D({...e,valueFormat:o});const r=e.valueFormat.byVariable;return(s,o)=>{if(o===void 0||o[r]===void 0)return t(s);const a=E(o[r]),i=n[a];return i!==void 0?i(s,o):t(s)}},D=e=>{switch(e.valueFormat.type){case"currency":return Ko(e);case"date":return lm(e);case"datetime":return um(e);case"day_month":return jo(e);case"decimal":return Hn(e);case"duration":return Kn();case"integer":return Xo(e);case"month":return Qo(e);case"month_year":return jn(e);case"percentage":return qo(e);case"quarter":return Qn();case"text":return Wn();case"weekly_date_range":return Zo(e);case"weekly_date_range_with_year":return Jo(e);case"year":return Zn(e);case"time":return ea(e);case"lookup":return Pm({...e,valueFormat:e.valueFormat});default:{const t=e.valueFormat;throw new Error(`Unhandled value format: ${t.type}`)}}},fn={abbreviation:"none",decimals:"auto"},ra=({locale:e,kind:t,startValue:n,endValue:r})=>{if(n===null||r===null)return Ho;switch(t){case"absolute-difference":return Hn({locale:e,numberFormat:fn,intlOptions:{signDisplay:"always"}})(r-n);case"relative-difference":{const s=r-n;if(s===0)return"0%";const o=s/n;return o===Number.POSITIVE_INFINITY?"∞":o===Number.NEGATIVE_INFINITY?"-∞":D({valueFormat:{type:"percentage"},locale:e,numberFormat:fn,intlOptions:{signDisplay:"always"}})(o)}case"proportion":{if(r-n===0)return"=";const s=r/n;return s===Number.POSITIVE_INFINITY?"∞":s===Number.NEGATIVE_INFINITY?"-∞":`${D({valueFormat:{type:"decimal"},locale:e,numberFormat:fn,intlOptions:{maximumFractionDigits:1}})(s)}x`}}},Nm=e=>{const t=e.padding??0,n=ms(e.rows,t),r=ms(e.cols,t);return{rows:n.tracks,cols:r.tracks,placements:Gm(e.placements,n.nameToIndex,r.nameToIndex),width:e.containerSize.width,height:e.containerSize.height}},Om=e=>{const t=fs(e.rows,e.height),n=fs(e.cols,e.width),r=hs(t),s=hs(n),o=new Map;for(const a of e.placements){const i=a.rowSpan??1,c=a.colSpan??1,l=s[a.col]??0,u=r[a.row]??0,d=ys(n,a.col,c),p=ys(t,a.row,i);o.set(a.name,{x:l,y:u,width:Math.max(0,d),height:Math.max(0,p)})}return o},ms=(e,t)=>{const n=[],r=new Map;t>0&&n.push({type:"fixed",pixels:t});for(let s=0;s<e.length;s++){const o=e[s];if(!o)continue;r.set(o.name,n.length),n.push($m(o));const a=Bm(e,s);if(sa(o)&&a){const i=o.gaps?.after??0,c=a.gaps?.before??0,l=Math.max(i,c);l>0&&n.push({type:"fixed",pixels:l})}}return t>0&&n.push({type:"fixed",pixels:t}),{tracks:n,nameToIndex:r}},$m=e=>typeof e.size=="number"?{type:"fixed",pixels:e.size}:{type:"flex",weight:e.size.flex},sa=e=>typeof e.size=="number"?e.size>0:e.size.flex>0,Bm=(e,t)=>{for(let n=t+1;n<e.length;n++){const r=e[n];if(r&&sa(r))return r}},Gm=(e,t,n)=>{const r=[];for(const s of e){const o=t.get(s.row),a=n.get(s.col);if(o===void 0||a===void 0)continue;const i=s.rowEnd!==void 0?t.get(s.rowEnd):o,c=s.colEnd!==void 0?n.get(s.colEnd):a;i===void 0||c===void 0||r.push({name:s.name,row:o,col:a,rowSpan:Math.max(1,i-o+1),colSpan:Math.max(1,c-a+1)})}return r},fs=(e,t)=>{let n=0,r=0;for(const o of e)o.type==="fixed"?n+=o.pixels:r+=o.weight;const s=Math.max(0,t-n);return e.map(o=>o.type==="fixed"?o.pixels:r===0?0:o.weight/r*s)},hs=e=>{const t=new Array(e.length);let n=0;for(let r=0;r<e.length;r++)t[r]=n,n+=e[r]??0;return t},ys=(e,t,n)=>{let r=0;const s=Math.min(t+n,e.length);for(let o=t;o<s;o++)r+=e[o]??0;return r},oa=24,te={header:{after:10,before:0},headline:{after:4,before:0},topLegend:{after:16,before:0},topAxisLabel:{after:4,before:0},topAxis:{after:0,before:0},panel:{after:0,before:0},bottomAxis:{after:4,before:0},bottomAxisLabel:{after:16,before:0},bottomLegend:{after:10,before:16}},dt={leftLegend:{after:10,before:0},leftAxis:{after:4,before:0},panel:{after:4,before:0},rightAxis:{after:10,before:0}},rr={top:0,right:0,bottom:0,left:0},zm=(e,t,n,r=rr)=>{const o=n.axes.top>0||n.axesLabels.top>0?n.axesLabels.top:Math.max(n.axesLabels.top,n.axesLabels.left,n.axesLabels.right);return Nm({rows:[{name:"header",size:t.headerSize.height,gaps:te.header},{name:"topLegend",size:n.legends.top,gaps:te.topLegend},{name:"headline",size:n.headline,gaps:te.headline},{name:"topAxisLabel",size:o,gaps:te.topAxisLabel},{name:"topAxis",size:n.axes.top,gaps:te.topAxis},{name:"topAnnotation",size:r.top},{name:"panel",size:{flex:1},gaps:te.panel},{name:"bottomAxis",size:n.axes.bottom,gaps:te.bottomAxis},{name:"bottomAxisLabel",size:n.axesLabels.bottom,gaps:te.bottomAxisLabel},{name:"bottomLegend",size:n.legends.bottom,gaps:te.bottomLegend},{name:"footer",size:t.footerSize.height}],cols:[{name:"leftLegend",size:n.legends.left,gaps:dt.leftLegend},{name:"leftAxis",size:n.axes.left,gaps:dt.leftAxis},{name:"panel",size:{flex:1},gaps:dt.panel},{name:"rightAnnotation",size:r.right},{name:"rightAxis",size:n.axes.right,gaps:dt.rightAxis},{name:"rightLegend",size:n.legends.right}],placements:[{name:"header",row:"header",col:"leftLegend",colEnd:"rightLegend"},{name:"headline",row:"headline",col:"leftLegend",colEnd:"rightLegend"},{name:"footer",row:"footer",col:"leftLegend",colEnd:"rightLegend"},{name:"plot",row:"topAxisLabel",rowEnd:"bottomAxisLabel",col:"leftAxis",colEnd:"rightAxis"},{name:"panel",row:"panel",col:"panel"},...Um(n.axes),...Ym(n.axesLabels,n.axes),...Wm(n.legends)],containerSize:e,padding:oa})},Um=e=>{const t=[];return e.top>0&&t.push({name:"topAxis",row:"topAxis",col:"panel"}),e.bottom>0&&t.push({name:"bottomAxis",row:"bottomAxis",col:"panel"}),e.left>0&&t.push({name:"leftAxis",row:"panel",col:"leftAxis"}),e.right>0&&t.push({name:"rightAxis",row:"panel",col:"rightAxis"}),t},Ym=(e,t)=>{const n=[];return e.top>0||t.top>0?(e.top>0&&n.push({name:"topAxisLabel",row:"topAxisLabel",col:"panel"}),e.left>0&&n.push({name:"leftAxisLabel",row:"topAxis",col:"leftAxis"}),e.right>0&&n.push({name:"rightAxisLabel",row:"topAxis",col:"rightAxis"})):(e.left>0&&n.push({name:"leftAxisLabel",row:"topAxisLabel",col:"leftAxis"}),e.right>0&&n.push({name:"rightAxisLabel",row:"topAxisLabel",col:"rightAxis"})),e.bottom>0&&n.push({name:"bottomAxisLabel",row:"bottomAxisLabel",col:"panel"}),n},Wm=e=>{const t=[];return e.top>0&&t.push({name:"topLegend",row:"topLegend",col:"leftAxis",colEnd:"rightAxis"}),e.bottom>0&&t.push({name:"bottomLegend",row:"bottomLegend",col:"leftAxis",colEnd:"rightAxis"}),e.left>0&&t.push({name:"leftLegend",row:"panel",col:"leftLegend"}),e.right>0&&t.push({name:"rightLegend",row:"panel",col:"rightLegend"}),t},Hm=({annotations:e,mainAxis:t,panelRect:n,textScale:r,locale:s,measureLabel:o,currentOverflow:a})=>{if(e.differenceArrows.length===0)return rr;const i=t==="y",c=n.height+a.top,l=n.width+a.right;let u=0,d=0;for(const p of e.differenceArrows){const{start:m,end:f,size:y,label:b}=p;if(!gs(m.x,m.y)||!gs(f.x,f.y))continue;const x=nr(y,r),S=x.offsetFromHigherObservation+x.arrowheadSize+x.arrowEndGap,w=ra({locale:s,kind:b,startValue:m.measurementValue,endValue:f.measurementValue}),I=o(w,y);if(i){const _=Math.max(m.x,f.x),X=S+I.width/2+x.labelPaddingX;d=Math.max(d,bs(X,_,l))}else{const _=Math.max(m.y,f.y),X=S+x.labelLineHeight/2+x.labelPaddingY;u=Math.max(u,bs(X,_,c))}}return{top:Math.ceil(u),right:Math.ceil(d),bottom:0,left:0}},gs=(e,t)=>e>=0&&e<=1&&t>=0&&t<=1,bs=(e,t,n)=>{if(t<=0)return 0;const r=(e-(1-t)*n)/t;return Math.max(0,r)},Km=["top","right","bottom","left"],hn=(e,t)=>{const n={};for(const r of Km){const s=e.get(`${r}${t}`);s&&(n[r]=s)}return n},wn=["large","medium","small"],Xm=({size:e,availableWidth:t,measureStripWidth:n})=>{if(e!=="auto")return e;for(const r of wn)if(n(r)<=t)return r;return"small"},qm=({size:e,availableWidth:t,measureStripWidth:n})=>{const r=e==="auto"?0:wn.indexOf(e);for(const s of wn.slice(r))if(n(s)<=t)return s;return null},jm=({itemWidths:e,gap:t,availableWidth:n})=>{let r=0,s=0;for(const o of e){const a=s===0?o:r+t+o;if(a>n)break;r=a,s+=1}return s},Qm=({headline:e,containerSize:t,measurer:n})=>{if(aa(e))return 0;const r=ia(e,t.width,n);return n.measureHeadline(e.formatted,r).height},Zm=({headline:e,layout:t,containerSize:n,measurer:r,itemGap:s})=>{if(aa(e)){const i=Jm(t.panel,e.innerRadius),c=qm({size:e.size,availableWidth:i.width,measureStripWidth:ca(e,r)});return c===null?null:{rect:i,resolvedSize:c,visibleItemCount:1}}const o=ia(e,n.width,r);if(e.formatted.kind!=="perGroup")return{rect:t.headline,resolvedSize:o,visibleItemCount:1};const a=jm({itemWidths:r.measureHeadlineItemWidths(e.formatted,o),gap:s,availableWidth:t.headline.width});return a===0?null:{rect:t.headline,resolvedSize:o,visibleItemCount:a}},aa=e=>e.formatted.kind==="grandTotal"&&e.position==="center"&&e.innerRadius>0,Jm=(e,t)=>{const n=Math.min(e.width,e.height)/2,r=t*n*Math.SQRT2,s=e.x+e.width/2,o=e.y+e.height/2;return{x:s-r/2,y:o-r/2,width:r,height:r}},ia=(e,t,n)=>Xm({size:e.size,availableWidth:t,measureStripWidth:ca(e,n)}),ca=(e,t)=>n=>t.measureHeadline(e.formatted,n).width,ze={x:0,y:0,width:0,height:0},ef="0000";class tf{constructor(t){this.measurer=t}compile(t){const n=Vt({axes:t.axes,numberFormat:t.numberFormat,formattedLegends:t.formattedLegends,containerSize:t.containerSize,externalMeasurements:t.externalMeasurements,annotationOverflow:rr,headline:t.headline,locale:t.formattingLocale??t.parsingLocale}).pipe(({axes:r,numberFormat:s,locale:o})=>{const a=r.filter(i=>i.geometry!=="linear").map(i=>rf(i,xs(i,o,s)));return{cartesianAxes:r.filter(i=>i.geometry==="linear"),formattedPolarAxes:a,polarMargin:sf(a,this.measurer.measureTickLabel)}}).pipe(({cartesianAxes:r,numberFormat:s,locale:o})=>({axisBundles:r.map(a=>({axis:a,resolveFormatter:xs(a,o,s),formatted:this.seedAxis(a)}))})).pipe(({axisBundles:r,formattedLegends:s,containerSize:o,externalMeasurements:a,annotationOverflow:i,headline:c,polarMargin:l})=>({layout:this.resolveLayout({axes:r.map(u=>u.formatted),formattedLegends:s,containerSize:o,externalMeasurements:a,annotationOverflow:i,headline:c,polarMargin:l})})).pipe(({axisBundles:r,layout:s})=>({axisBundles:r.map(o=>Ss(o.axis.position)?{...o,formatted:this.finalizeAxis(o.axis,o.resolveFormatter,s.panel)}:o)})).pipe(({axisBundles:r,formattedLegends:s,containerSize:o,externalMeasurements:a,annotationOverflow:i,headline:c,polarMargin:l})=>({layout:this.resolveLayout({axes:r.map(u=>u.formatted),formattedLegends:s,containerSize:o,externalMeasurements:a,annotationOverflow:i,headline:c,polarMargin:l})})).pipe(({axisBundles:r,layout:s})=>({formattedAxes:r.map(o=>Ss(o.axis.position)?o.formatted:this.finalizeAxis(o.axis,o.resolveFormatter,s.panel))})).pipe(({formattedAxes:r,formattedLegends:s,containerSize:o,externalMeasurements:a,annotationOverflow:i,headline:c,polarMargin:l})=>({layout:this.resolveLayout({axes:r,formattedLegends:s,containerSize:o,externalMeasurements:a,annotationOverflow:i,headline:c,polarMargin:l})})).pipe(({formattedAxes:r,formattedLegends:s,containerSize:o,externalMeasurements:a,layout:i,annotationOverflow:c,headline:l,polarMargin:u,locale:d})=>{const p=this.measureAnnotationOverflow(t,i.panel,d,c);return p===c?{formattedAxes:r,layout:i}:{formattedAxes:r,layout:this.resolveLayout({axes:r,formattedLegends:s,containerSize:o,externalMeasurements:a,annotationOverflow:p,headline:l,polarMargin:u})}}).result();return{formattedAxes:n.formattedAxes,layout:n.layout,formattedPolarAxes:n.formattedPolarAxes}}measureAnnotationOverflow(t,n,r,s){if(!t.annotations||t.annotations.differenceArrows.length===0||t.coordSystem?.type!=="cartesian")return s;const o=Hm({annotations:t.annotations,mainAxis:t.coordSystem.mainAxis,panelRect:n,textScale:t.textScale??1,locale:r,measureLabel:this.measurer.measureDifferenceArrowLabel,currentOverflow:s});return o.top===s.top&&o.right===s.right?s:o}seedAxis(t){const{tickCandidates:n,...r}=t;return{...r,ticks:[{value:0,position:0,formattedLabel:ef}],labelRotation:0,labelMaxWidthPx:null}}finalizeAxis(t,n,r){const o=t.position==="top"||t.position==="bottom"?r.width:r.height,a=_m({axis:t,availableSpacePx:o,measureLabel:this.measurer.measureTickLabel,resolveFormatter:n}),{tickCandidates:i,...c}=t,l={...c,ticks:a,labelRotation:0,labelMaxWidthPx:null};if(t.scaleType==="discrete"&&t.bandwidth!==void 0){const u=t.bandwidth*o;return Im({formattedAxis:l,bandwidthPx:u,panelRect:r,measureLabel:this.measurer.measureTickLabel})}return l}resolveLayout({axes:t,formattedLegends:n,containerSize:r,externalMeasurements:s,annotationOverflow:o,headline:a,polarMargin:i}){const c=this.measureGuides(t,n,a,r,i),l=zm(r,s,c,o),u=Om(l);return{header:u.get("header")??ze,headline:u.get("headline")??ze,footer:u.get("footer")??ze,plot:u.get("plot")??ze,panel:u.get("panel")??ze,axes:hn(u,"Axis"),axisLabels:hn(u,"AxisLabel"),legends:hn(u,"Legend")}}measureGuides(t,n,r,s,o){const a={...o},i={top:0,right:0,bottom:0,left:0};for(const l of t)l.isVisible&&(a[l.position]=this.measurer.measureAxis(l),l.label!==null&&(i[l.position]=this.measurer.measureAxisLabel(l)));const c={top:0,right:0,bottom:0,left:0};for(const l of n)c[l.position]=this.measurer.measureLegend(l);return{axes:a,axesLabels:i,legends:c,headline:this.measureHeadlineBand(r,s)}}measureHeadlineBand(t,n){return t===void 0?0:Qm({headline:t,containerSize:n,measurer:this.measurer})}}const vs=5,pt=8,Ss=e=>e==="left"||e==="right",nf=e=>{const[t,...n]=e.tickCandidates;if(t)return e.geometry==="circular"?t:n.reduce((r,s)=>Math.abs(s.ticks.length-vs)<Math.abs(r.ticks.length-vs)?s:r,t)},rf=(e,t)=>{const{tickCandidates:n,...r}=e,s=nf(e);if(!s)return{...r,ticks:[],labelRotation:0,labelMaxWidthPx:null};const o=t(s),a=s.ticks.map(i=>({...i,formattedLabel:o(i.value)}));return{...r,ticks:a,labelRotation:0,labelMaxWidthPx:null}},sf=(e,t)=>{const n=e.find(o=>o.geometry==="circular");if(!n||n.ticks.length===0)return{top:0,right:0,bottom:0,left:0};let r=0,s=0;for(const o of n.ticks){const a=t(o.formattedLabel);r=Math.max(r,a.width),s=Math.max(s,a.height)}return{top:s+pt,bottom:s+pt,left:r+pt,right:r+pt}},xs=(e,t,n)=>{const r=e.tickCandidates.flatMap(o=>o.ticks.map(a=>a.value)),s=new WeakMap;return o=>{const a=s.get(o);if(a)return a;const i=tr({valueFormat:o.valueFormat??e.valueFormat,locale:t,numberFormat:n,tickValues:r});return s.set(o,i),i}};function of(e,t,n,r){const s=new Map;if(!n||n.kind!=="visual"||n.domain.length<=1)return s;const o=new Map(t.map(a=>[a.id,a.swatchShape]));for(const a of e){if(a.geom!=="rule"||a.stat.type!=="mean")continue;const i=a.transforms.find(y=>y.transformType==="filter"&&y.options.operator==="eq"),c=v(a.mapping.y);let l,u,d;if(i?.transformType==="filter"&&typeof i.options.value=="string")l="color",u=i.options.variableName,d=i.options.value;else if(c!==null)l="y",u=c,d=c;else continue;const p=af(e,l,u);if(p===null)continue;const m=o.get(p.id);if(m===void 0)continue;const f=n.map(d);Ze(f)&&s.set(a.id,{shape:je(m,r),color:f})}return s}function af(e,t,n){let r=null;for(const s of e)if(s.geom!=="rule"&&(r===null&&(r=s),v(s.mapping[t])===n))return s;return r}function Qe(e,t){return e==="x"?t.x:t.y}function Ot(e,t){return e==="x"?t.y:t.x}function cf(e,t){return{main:Qe(e,t),cross:Ot(e,t)}}function lf(e){return e.type==="cartesian"}const sr=12,uf=4,df=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=_e(n),s=Z(n)??se(n);if(r===null||s===null||r<0||r>1||s<0||s>1)continue;const o=e.formatLabel(n);if(o==="")continue;const{width:a,height:i}=e.measureDataLabel("dataLabel",o),c=r*e.panelRect.width,l=(1-s)*e.panelRect.height-sr-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:c,y:l,text:o,width:a,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},pf={place:df,getPercentageValueStrategy:e=>e.position==="fill"?"fill":H(e.position)?"stack":"none"},yn=4,mt=6,mf=e=>{const t=[],n=H(e.layer.position),r=e.coordSystem.mainAxis==="y";if(e.layer.dataLabels.showDataLabels){const{entries:s,shouldRotate:o}=hf({layer:e.layer,mainAxis:e.coordSystem.mainAxis,panelRect:e.panelRect,measureDataLabel:e.measureDataLabel,formatLabel:e.formatLabel,isFlipped:r,getObservationKey:e.getObservationKey});for(const a of s){const i=vf({mainAxis:e.coordSystem.mainAxis,isStacked:n,isNegativeBar:a.isNegative,shouldRotate:o,bounds:a.bounds,labelWidth:a.labelWidth,labelHeight:a.labelHeight,panelWidth:e.panelRect.width,panelHeight:e.panelRect.height});i!==null&&t.push({layerId:e.layer.id,key:a.key,x:i.x,y:i.y,text:a.text,width:a.labelWidth,height:a.labelHeight,isRotated:i.isRotated,target:"observation",position:i.position})}}if(e.layer.dataLabels.showStackTotals){const s=Af({layer:e.layer,mainAxis:e.coordSystem.mainAxis,panelRect:e.panelRect,measureDataLabel:e.measureDataLabel,formatAbsolute:e.formatAbsolute});for(const o of s)t.push(o)}return t},ff={place:mf,getPercentageValueStrategy:e=>e.position==="fill"?"fill":H(e.position)?"stack":"absoluteGrandTotal"},hf=({layer:e,mainAxis:t,panelRect:n,measureDataLabel:r,formatLabel:s,isFlipped:o,getObservationKey:a})=>{const i=[];let c=!1;const l=v(e.mapping.y);for(const u of e.data){const d=yf(t,u);if(d===null)continue;const p=s(u);if(p==="")continue;const{width:m,height:f}=r("dataLabel",p),y=la(d,n);m>y.width&&(c=!0);const b=l===null?null:u[l],x=F(b)&&b<0;i.push({key:a(u),isNegative:x,text:p,labelWidth:m,labelHeight:f,bounds:y})}return{entries:i,shouldRotate:!o&&c}},la=(e,t)=>({x:e.x*t.width,y:e.y*t.height,width:e.width*t.width,height:e.height*t.height}),ua=(e,t,n,r,s)=>{if(e==="x"){let i=1-s,c=s-r;return c<0&&(i+=c,c=-c),{x:t,y:i,width:n-t,height:c}}let o=t,a=n-t;return a<0&&(o+=a,a=-a),{x:o,y:1-s,width:a,height:s-r}},yf=(e,t)=>{const n=qe(t),r=ke(t),s=Se(t),o=Z(t)??se(t);return n===null||r===null||s===null||o===null?null:ua(e,n,r,s,o)},gf=(e,t)=>{const{xMin:n,xMax:r,yMin:s,yMax:o}=t.anchor;return ua(e,n,r,s,o)},bf=(e,t)=>e==="x"?t?"bottom":"top":t?"left":"right",da=(e,t,n)=>n?{width:t,height:e}:{width:e,height:t},vf=e=>e.isStacked?Sf({bounds:e.bounds,labelWidth:e.labelWidth,labelHeight:e.labelHeight,isRotated:e.shouldRotate}):wf({edge:bf(e.mainAxis,e.isNegativeBar),bounds:e.bounds,labelWidth:e.labelWidth,labelHeight:e.labelHeight,isRotated:e.shouldRotate,panelWidth:e.panelWidth,panelHeight:e.panelHeight}),Sf=({bounds:e,labelWidth:t,labelHeight:n,isRotated:r})=>{const s=da(t,n,r);return s.width>e.width||s.height>e.height?null:{x:e.x+e.width/2,y:e.y+e.height/2,isRotated:r,position:"inside"}},xf=(e,t,n,r)=>{switch(e){case"top":return{edgeCoord:t.y,outwardSign:-1,panelExtent:r};case"bottom":return{edgeCoord:t.y+t.height,outwardSign:1,panelExtent:r};case"left":return{edgeCoord:t.x,outwardSign:-1,panelExtent:n};case"right":return{edgeCoord:t.x+t.width,outwardSign:1,panelExtent:n}}},wf=({edge:e,bounds:t,labelWidth:n,labelHeight:r,isRotated:s,panelWidth:o,panelHeight:a})=>{const i=e==="top"||e==="bottom",c=t.x+t.width/2,l=t.y+t.height/2,u=da(n,r,s),d=i?u.height:u.width,p=i?u.width:u.height,m=i?t.height:t.width,f=i?t.width:t.height,y=d/2,{edgeCoord:b,outwardSign:x,panelExtent:S}=xf(e,t,o,a);if(d+yn<m){if(p>f)return null;if(s)return{x:c,y:l,isRotated:!0,position:"inside"};const I=b-x*(y+yn);return{...i?{x:c,y:I}:{x:I,y:l},isRotated:!1,position:"inside"}}const w=b+x*(y+yn);return w-y<0||w+y>S?null:{...i?{x:c,y:w}:{x:w,y:l},isRotated:s,position:"outside"}},Af=({layer:e,mainAxis:t,panelRect:n,measureDataLabel:r,formatAbsolute:s})=>{const o=[],a=e.summary.stackTotals;if(a===void 0||a.length===0)return o;const i=t==="y";for(const c of a){const l=la(gf(t,c),n),u=s(c.total),{width:d,height:p}=r("stackTotal",u),m=c.anchor.direction==="positive";let f,y;i?(f=m?l.x+l.width+mt+d/2:l.x-mt-d/2,y=l.y+l.height/2):(f=l.x+l.width/2,y=m?l.y-mt-p/2:l.y+l.height+mt+p/2),o.push({layerId:e.id,key:`${e.id}:stack:${c.xKey}`,x:f,y,text:u,width:d,height:p,isRotated:!1,target:"aggregate",position:"outside"})}return o},Tf=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=_e(n),s=se(n);if(r===null||s===null||r<0||r>1||s<0||s>1)continue;const o=e.formatLabel(n);if(o==="")continue;const{width:a,height:i}=e.measureDataLabel("dataLabel",o),c=r*e.panelRect.width,l=(1-s)*e.panelRect.height-sr-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:c,y:l,text:o,width:a,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},Mf={place:Tf,getPercentageValueStrategy:()=>"none"},Lf=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=_e(n),s=se(n);if(r===null||s===null||r<0||r>1||s<0||s>1)continue;const o=e.formatLabel(n);if(o==="")continue;const{width:a,height:i}=e.measureDataLabel("dataLabel",o),c=(Ps(n)??e.layer.params.size)/2,l=r*e.panelRect.width,u=(1-s)*e.panelRect.height-c-sr-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:l,y:u,text:o,width:a,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},Vf={place:Lf,getPercentageValueStrategy:()=>"none"};function pa(e){return{startAngle:e[g.xMin],endAngle:e[g.xMax]}}function ma(e){return{innerRadius:e[g.yMin],outerRadius:e[g.yMax]??e[g.y]}}const kf=" · ",Ef=e=>typeof e=="string"?e:e instanceof Date?e.toISOString():String(e),If=(e,t)=>{const n=v(t.x);return n!==null&&n!==gn.x?Rn(e,t):s=>Ie(s)},Cf=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;const n=e.layer.dataLabels.showCategoryLabels?If(e.layer.data,e.layer.mapping):null,r=e.panelRect.width/2,s=e.panelRect.height/2,o=Math.min(e.panelRect.width,e.panelRect.height)/2;for(const a of e.layer.data){const{startAngle:i,endAngle:c}=pa(a),{outerRadius:l}=ma(a);if(i===null||c===null||l===null)continue;const u=e.formatLabel(a);if(u==="")continue;const d=n===null?null:n(a),p=d===null?u:`${Ef(d)}${kf}${u}`,{width:m,height:f}=e.measureDataLabel("dataLabel",p),y=(i+c)/2,b=Math.abs(Math.sin(y))*(m/2)+Math.abs(Math.cos(y))*(f/2),x=l*o+uf+b,S=r+Math.sin(y)*x,w=s-Math.cos(y)*x,I=m/2,_=f/2;S-I<0||S+I>e.panelRect.width||w-_<0||w+_>e.panelRect.height||t.push({layerId:e.layer.id,key:e.getObservationKey(a),x:S,y:w,text:p,width:m,height:f,isRotated:!1,target:"observation",position:"outside"})}return t},Ff={place:Cf,getPercentageValueStrategy:()=>"absoluteGrandTotal"},Df={type:"decimal"};function fa({layer:e,numberFormat:t,locale:n}){const r=v(e.mapping.y),s=r!==null&&e.data.hasVariable(r)?e.data.getValueFormat(r):Df;return D({valueFormat:s,locale:n,numberFormat:t})}const _f=({layer:e,coordSystem:t,axes:n,numberFormat:r,panelRect:s,measureDataLabel:o,formattingLocale:a,percentageValueStrategy:i})=>{const c=fa({layer:e,numberFormat:r,locale:a});return{layer:e,coordSystem:t,panelRect:s,measureDataLabel:o,formatLabel:$f({layer:e,numberFormat:r,axes:n,locale:a,absoluteFormatter:c,percentageValueStrategy:i}),formatAbsolute:c,getObservationKey:Rf(e)}},Rf=e=>t=>`${e.id}:${Dt(t)}`,Pf=(e,t)=>{switch(t){case"stack":return Nf(e);case"fill":return Of(e);case"absoluteGrandTotal":return()=>e.summary.absoluteGrandTotal??null;case"none":return()=>null}},Nf=e=>{const t=v(e.mapping.x);let n=null,r=!1;return s=>{const o=e.summary.stackTotals;if(o===void 0||o.length===0||t===null)return null;if(!r){n=new Map;for(const c of o)n.set(c.xKey,c);r=!0}const a=s[t];if(a==null)return null;const i=n?.get(_n(s,t));return i===void 0?null:i.total}},Of=e=>{const t=Pn(e);return n=>{const r=Se(n),s=Z(n);if(!F(r)||!F(s))return null;const o=Math.abs(s-r);if(o===0)return null;const a=t(n);return F(a)?a/o:null}},$f=({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:s,percentageValueStrategy:o})=>{const a=K(e.data,e.dataLabels.labelSource),i=Pf(e,o),c=Bf({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:s}),l=D({valueFormat:{type:"percentage"},locale:r,numberFormat:t}),u=e.dataLabels.format==="percentage"&&ha(e);return d=>{const p=a(d);if(p===null)return"";if(!u||!F(p))return c(p,d);const m=i(d);return m===null||m===0?c(p,d):l(p/m)}},Bf=({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:s})=>{const o=e.dataLabels.labelSource,a=v(o);if(a!==null){if(ha(e))return s;const i=Gf(e,n,t,r,a);if(i!==null)return i}return D({valueFormat:zf(e.data,o),locale:r,numberFormat:t})},ha=e=>{const t=v(e.dataLabels.labelSource);return t===null?!1:t===v(nt(e.position,e.mapping))},Gf=(e,t,n,r,s)=>{const o=v(e.mapping.x);if(o===null||o!==s)return null;const a=t.find(i=>i.scaleAestheticKey==="x");return a===void 0?null:D({valueFormat:a.valueFormat,locale:r,numberFormat:n})},zf=(e,t)=>{const n=re(t);if(n!==void 0)return typeof n=="number"?{type:"decimal"}:Ga(n)?{type:"date"}:{type:"text"};const r=v(t);return r===null||!e.hasVariable(r)?{type:"text"}:e.getValueFormat(r)},Uf={bar:{cartesian:ff,polar:Ff},line:{cartesian:Mf},point:{cartesian:Vf},area:{cartesian:pf}},Yf=({layers:e,coordSystem:t,axes:n,numberFormat:r,parsingLocale:s,panelRect:o,measureDataLabel:a,formattingLocale:i})=>{const c=[],l=i??s,u=t.type;for(const d of e){if(!d.dataLabels.showDataLabels&&!d.dataLabels.showStackTotals)continue;const p=Uf[d.geom]?.[u];if(p===void 0)continue;const m=_f({layer:d,coordSystem:t,axes:n,numberFormat:r,panelRect:o,measureDataLabel:a,formattingLocale:l,percentageValueStrategy:p.getPercentageValueStrategy(d)}),f=p.place(m);for(const y of f)c.push(y)}return{labels:c}},Wf=(e,t,n,r)=>{const s=r.offsetFromHigherObservation+r.arrowheadSize+r.arrowEndGap;return e?Math.max(t.x,n.x)+s:Math.min(t.y,n.y)-s},Hf=(e,t,n,{arrowStartGap:r,arrowEndGap:s,curveRadius:o})=>{const a={x:e.x,y:e.y-r},i={x:e.x,y:n},c={x:t.x,y:n},l={x:t.x,y:t.y-s},u=t.x>e.x?1:-1;return`
|
|
5
|
+
M ${a.x} ${a.y}
|
|
6
|
+
L ${i.x} ${i.y+o}
|
|
7
|
+
Q ${i.x} ${i.y} ${i.x+u*o} ${i.y}
|
|
8
|
+
L ${c.x-u*o} ${c.y}
|
|
9
|
+
Q ${c.x} ${c.y} ${c.x} ${c.y+o}
|
|
10
10
|
L ${l.x} ${l.y}
|
|
11
|
-
`},
|
|
12
|
-
M ${
|
|
13
|
-
L ${i.x-
|
|
14
|
-
Q ${i.x} ${i.y} ${i.x} ${i.y+u*
|
|
15
|
-
L ${c.x} ${c.y-u*
|
|
16
|
-
Q ${c.x} ${c.y} ${c.x-
|
|
11
|
+
`},Kf=(e,t,n,{arrowStartGap:r,arrowEndGap:s,curveRadius:o})=>{const a={x:e.x+r,y:e.y},i={x:n,y:e.y},c={x:n,y:t.y},l={x:t.x+s,y:t.y},u=t.y>e.y?1:-1;return`
|
|
12
|
+
M ${a.x} ${a.y}
|
|
13
|
+
L ${i.x-o} ${i.y}
|
|
14
|
+
Q ${i.x} ${i.y} ${i.x} ${i.y+u*o}
|
|
15
|
+
L ${c.x} ${c.y-u*o}
|
|
16
|
+
Q ${c.x} ${c.y} ${c.x-o} ${c.y}
|
|
17
17
|
L ${l.x} ${l.y}
|
|
18
|
-
`},
|
|
18
|
+
`},Xf=(e,t,{arrowEndGap:n,arrowheadSize:r})=>e?`
|
|
19
19
|
M ${t.x+n+r} ${t.y-r}
|
|
20
20
|
L ${t.x+n} ${t.y}
|
|
21
21
|
L ${t.x+n+r} ${t.y+r}
|
|
@@ -23,4 +23,4 @@ ${n}`)}}class vl{constructor(t,n){this.transformCompiler=t,this.validator=n}chec
|
|
|
23
23
|
M ${t.x-r} ${t.y-n-r}
|
|
24
24
|
L ${t.x} ${t.y-n}
|
|
25
25
|
L ${t.x+r} ${t.y-n-r}
|
|
26
|
-
`,Mf=(e,t,n,r,o,a=.5)=>{if(e){const i=Math.min(t.y,n.y);return{x:r,y:i+a*o}}return{x:Math.min(t.x,n.x)+a*o,y:r}},Lf=(e,t,n)=>Math.abs(e?t.y-n.y:t.x-n.x),Vf=({arrow:e,mainAxis:t,panelWidth:n,panelHeight:r,textScale:o,locale:a})=>{const s=t==="y",i={x:e.start.x*n,y:(1-e.start.y)*r},c={x:e.end.x*n,y:(1-e.end.y)*r},l=Bn(e.size,o),u=xf(s,i,c,l),d=(s?Af:wf)(i,c,u,l),m=Tf(s,c,l),p=Lf(s,i,c),f=Mf(s,i,c,u,p,e.labelCrossPosition),y=_a({locale:a,kind:e.label,startValue:e.start.measurementValue,endValue:e.end.measurementValue});return{id:e.id,linePath:d,arrowheadPath:m,labelPosition:f,labelText:y,color:e.color,strokeWidth:l.strokeWidth,labelLineHeight:l.labelLineHeight,labelPaddingX:l.labelPaddingX,labelPaddingY:l.labelPaddingY,labelStrokeWidth:l.labelStrokeWidth,labelFontWeight:l.labelFontWeight}},kf=100,Ef=({items:e,containerHeight:t,labelHeight:n})=>{const r=e.map(l=>{const u=(1-l.normalizedY)*t;return{anchorY:u,y:u,payload:l.payload}}).sort((l,u)=>l.y-u.y),o=n/2;let a=!1,s=!0,i=0;for(;s;){s=!1,i++;for(let l=0;l<r.length-1;l++){const u=r[l],d=r[l+1];if(!u||!d)continue;const m=u.y+o,p=d.y-o;if(m>p){s=!0,a=!0;const y=(m-p)/2+1;u.y-=y,d.y+=y,u.y<0&&(u.y=0),d.y>t&&(d.y=t)}}if(i>kf)break}return{placements:r.filter(l=>l.y>=0&&l.y<=t).map(l=>({y:l.y,anchorY:l.anchorY,payload:l.payload})),hasOverlap:a}},If=({headline:e,show:t,numberFormat:n,parsingLocale:r,formattingLocale:o})=>{if(e===null)return null;const a=o??r;return e.kind==="grandTotal"?Cf(e,a,n):_f(e,t,a,n)},Cf=(e,t,n)=>({kind:"grandTotal",value:C({valueFormat:e.valueFormat,locale:t,numberFormat:n})(e.value)}),_f=(e,t,n,r)=>{const o=C({valueFormat:{type:"percentage"},locale:n,numberFormat:r}),a=Nf(t,e.items.length>1);return{kind:"perGroup",items:e.items.map(i=>{const c=C({valueFormat:i.valueFormat,locale:n,numberFormat:r}),l=C({valueFormat:i.groupLabelFormat,locale:n,numberFormat:r}),u=On({valueFormat:i.mainValueFormat,locale:n,numberFormat:r,tickValues:[]}),d=i.label??l(i.value);return{swatch:i.swatch,label:`${a}${d}`,value:i.aggregate===null?null:c(i.aggregate),observationLabel:Rf(i.observationLabel,u),comparison:Ff(i.comparison,u,o)}})}},Ff=(e,t,n)=>e===null?null:{direction:Df(e.variation),percentage:n(Math.abs(e.variation)),reference:`from ${t(e.against)}`},Df=e=>e>0?"up":e<0?"down":"flat",Rf=(e,t)=>e===null?null:e.kind==="point"?t(e.value):`${t(e.from)} – ${t(e.to)}`,Nf=(e,t)=>{switch(e){case"total":return"Total ";case"average":return t?"Avg. ":"Average ";default:return""}},Pf=({legends:e,numberFormat:t,parsingLocale:n,formattingLocale:r})=>{const o=r??n;return e.map(a=>Of(a,o,t))},Of=(e,t,n)=>({...e,items:e.items.map(r=>{const o=C({valueFormat:r.valueFormat,locale:t,numberFormat:n});return{...r,formattedLabel:r.label??o(r.value)}})});function Dt(e,t){return e.axes.find(n=>n.scaleAestheticKey===t)??null}function Bf(e,t){return e.legends.find(n=>n.aesthetics.includes(t))??null}const $f=({guides:e,numberFormat:t,layer:n,locale:r})=>{const o=n.data.getFirst();if(!o)return null;const a=n.mapping.y!==void 0,i=(a?qo:vn)(n.data,n.mapping)(o);if(i===null)return null;const c=a?et(n.yScaleType):"x",l=Dt(e,c)?.valueFormat??{type:"decimal"};return C({valueFormat:l,locale:r,numberFormat:t})(i)},Gf=800,qr=400,Uf={thin:{strokeWidth:{minValue:1.5,targetValue:2},arrowheadLength:{minValue:7,targetValue:8}},medium:{strokeWidth:{minValue:3,targetValue:4},arrowheadLength:{minValue:14,targetValue:16}},thick:{strokeWidth:{minValue:6,targetValue:8},arrowheadLength:{minValue:28,targetValue:32}}},Yf=e=>Math.max(1,(e-qr)/(Gf-qr)+1),Wf=(e,t)=>{const n=Yf(t),r=Uf[e];return{strokeWidth:Math.min(r.strokeWidth.targetValue,r.strokeWidth.minValue*n),arrowheadLength:Math.min(r.arrowheadLength.targetValue,r.arrowheadLength.minValue*n)}},mt=Math.PI/4,cn=1.5,Hf=({startX:e,startY:t,endX:n,endY:r})=>`M ${e} ${t} L ${n} ${r}`,Qr=(e,t,n)=>{if(n<=0)return"";const{startX:r,startY:o,endX:a,endY:s}=t,i=e==="start"?r:a,c=e==="start"?o:s,l=e==="start"?Math.atan2(o-s,r-a):Math.atan2(s-o,a-r),u=i-n*Math.cos(l-mt),d=c-n*Math.sin(l-mt),m=i-n*Math.cos(l+mt),p=c-n*Math.sin(l+mt);return`M ${i} ${c} L ${u} ${d} M ${i} ${c} L ${m} ${p}`},Kf=(e,t)=>e==="solid"?null:`${t*cn} ${t*cn*2}`,zf=(e,t)=>t?e*cn:0,Xf=64,jf=({arrow:e,panelWidth:t,panelHeight:n})=>{const r={startX:e.start.x*t,startY:e.start.y*n,endX:e.end.x*t,endY:e.end.y*n};if(r.startX===r.endX&&r.startY===r.endY)return null;const{strokeWidth:o,arrowheadLength:a}=Wf(e.thickness,t),s=Math.hypot(r.endX-r.startX,r.endY-r.startY),i=qf(a,s),c=e.startArrowheadStyle==="line-arrow",l=e.endArrowheadStyle==="line-arrow",d=c||l?i*Math.sin(Math.PI/4):0;return{id:e.id,linePath:Hf(r),startArrowheadPath:c?Qr("start",r,i):"",endArrowheadPath:l?Qr("end",r,i):"",color:e.color,strokeWidth:o,dashArray:Kf(e.lineStyle,o),hasStickerStyle:e.hasStickerStyle,startX:r.startX,startY:r.startY,endX:r.endX,endY:r.endY,dashOffset:zf(o,c),arrowheadExtent:d}},qf=(e,t)=>Math.min(e,t*e/Xf);function Ha(e,t){return Un(e.buckets,t,n=>n.main)}function Qf(e,t){return Un(e.bands,t,n=>n.bandCenter)}function Zf(e,t){return Un(e.columns,t,n=>n.mainMid)}function Un(e,t,n){if(e.length===0)return null;let r=0,o=e.length;for(;r<o;){const i=r+o>>>1,c=e[i];c&&n(c)<t?r=i+1:o=i}const a=e[r-1],s=e[r];return a?s&&Math.abs(n(s)-t)<Math.abs(n(a)-t)?s:a:s??null}function Yn(e,t,n){return Math.hypot(e*n,t)}function Jf(e,t,n,r){if(e.points.length===0)return null;const o=e.delaunay;if(!o)return null;const a=o.find(t.x*n,t.y,r??void 0),s=e.points[a];return s?{hit:{layerId:e.layerId,pointIndex:s.pointIndex,x:s.x,y:s.y,observation:s.observation},index:e,distance:Yn(s.x-t.x,s.y-t.y,n)}:null}function eh(e,t){if(e.points.length===0||!e.delaunay||e.delaunayAspectRatio===null)return null;const n=e.delaunay.find(t.x*e.delaunayAspectRatio,t.y);return e.points[n]??null}function Zr(e,t){return{group:th(e),related:ah(e,t)}}function th(e){switch(e.kind){case"buckets":{const t=e.match.index;return Y(t.position)?nh(t,e.match):[]}case"rects":{const t=e.match.index;return Y(t.position)?rh(t,e.match):oh(t,e.match)}case"points":case"arcs":case"polar-points":case"render-hit-test":return[]}}function nh(e,t){const n=[];for(const r of t.bucket.entries)r.pointIndex!==t.hit.pointIndex&&n.push({layerId:e.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation});return n}function rh(e,t){const n=[];for(const r of t.column.rects)r.pointIndex!==t.hit.pointIndex&&n.push(Wn(e,r));return n}function oh(e,t){const n=e.bands.find(o=>o.columns.includes(t.column));if(!n)return[];const r=[];for(const o of n.columns)for(const a of o.rects)a.pointIndex!==t.hit.pointIndex&&r.push(Wn(e,a));return r}function ah(e,t){const n=new Map;if(e.kind==="arcs"||e.kind==="polar-points")return n;for(const r of t){if(r.layerId!==e.match.index.layerId){ih(n,r,e.match.hit);continue}e.kind==="buckets"&&(Y(r.position)||r.kind==="buckets"&&sh(n,r,e.match))}return n}function sh(e,t,n){for(const r of n.bucket.entries){if(r.pointIndex===n.hit.pointIndex)continue;vt(e,t.layerId).push({layerId:t.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation})}}function ih(e,t,n){switch(t.kind){case"buckets":{const r=Ha(t,je(t.mainAxis,n));if(!r)return;const o=vt(e,t.layerId);for(const a of r.entries)o.push({layerId:t.layerId,pointIndex:a.pointIndex,x:a.x,y:a.y,observation:a.observation});return}case"rects":{const r=Qf(t,je(t.mainAxis,n));if(!r)return;const o=vt(e,t.layerId);for(const a of r.columns)for(const s of a.rects)o.push(Wn(t,s));return}case"points":{const r=eh(t,n);if(!r)return;vt(e,t.layerId).push({layerId:t.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation});return}case"arcs":case"polar-points":return;case"noop":return;case"render-hit-test":return}}function vt(e,t){let n=e.get(t);return n||(n=[],e.set(t,n)),n}function Wn(e,t){return{layerId:e.layerId,pointIndex:t.pointIndex,x:(t.xMin+t.xMax)/2,y:(t.yMin+t.yMax)/2,observation:t.observation}}function ch(e){const t=lh(e);return{kind:"arcs",layerId:e.id,position:e.position,arcs:t}}function lh(e){const t=e.data;if(t.size()===0)return[];const n=[g.xMin,g.xMax,g.yMin,g.yMax];for(const l of n)if(!t.hasVariable(l))return[];const r=t.getValues(g.xMin,{type:"numeric"}),o=t.getValues(g.xMax,{type:"numeric"}),a=t.getValues(g.yMin,{type:"numeric"}),s=t.getValues(g.yMax,{type:"numeric"}),i=[];let c=0;for(const l of t){const u=r[c],d=o[c],m=a[c],p=s[c];if(!h(u)||!h(d)||!h(m)||!h(p)){c++;continue}i.push({pointIndex:c,startAngle:u,endAngle:d,innerRadius:m,outerRadius:p,observation:l}),c++}return i}const uh=1e-9;function dh(e,t){const n=mh(e,t);n.sort((o,a)=>o.main-a.main);const r=[];for(const o of n){const a=r[r.length-1];a&&Math.abs(a.main-o.main)<=uh?a.entries.push(o.entry):r.push({main:o.main,entries:[o.entry]})}return{kind:"buckets",layerId:e.id,position:e.position,mainAxis:t,buckets:r}}function mh(e,t){const n=e.data;if(n.size()===0)return[];const o=n.hasVariable(g.x),a=n.hasVariable(g.y);if(!o||!a)return[];const s=n.getValues(g.x,{type:"numeric"}),i=n.getValues(g.y,{type:"numeric"}),c=t==="y",l=c?g.xMin:g.yMin,u=c?g.xMax:g.yMax,d=Y(e.position),m=d?n.getValues(l,{type:"numeric"}):null,p=d?n.getValues(u,{type:"numeric"}):null,f=n.hasVariable(D.group)?n.getValues(D.group,{type:"categorical"}):null,y=[];let b=0;for(const x of n){const S=s[b],w=i[b];if(!h(S)||!h(w)){b+=1;continue}const k=f?.[b]??null,_=c?w:S;if(d){const H=m?.[b],Ne=p?.[b];if(!h(H)||!h(Ne)){b+=1;continue}const T=c?Ne:S,Q=c?w:Ne;y.push({main:_,entry:{isStacked:d,pointIndex:b,x:T,y:Q,stackMin:H,stackMax:Ne,groupKey:k,observation:x}})}else y.push({main:_,entry:{isStacked:d,pointIndex:b,x:S,y:w,groupKey:k,observation:x}});b+=1}return y}function ph(e){return{kind:"noop",layerId:e.id,position:e.position}}function fh(e,t){const n={kind:"points",layerId:e.id,position:e.position,points:hh(e),delaunay:null,delaunayAspectRatio:null};return Ka(n,t),n}function Ka(e,t){e.delaunay&&e.delaunayAspectRatio===t||(e.delaunay=ns.Delaunay.from(e.points,n=>n.x*t,n=>n.y),e.delaunayAspectRatio=t)}function hh(e){const t=e.data;if(t.size()===0)return[];if(!t.hasVariable(g.x)||!t.hasVariable(g.y))return[];const n=t.getValues(g.x,{type:"numeric"}),r=t.getValues(g.y,{type:"numeric"}),o=[];let a=0;for(const s of t){const i=n[a],c=r[a];a+=1,!(!h(i)||!h(c))&&o.push({pointIndex:o.length,x:i,y:c,observation:s})}return o}function yh(e){return{kind:"polar-points",layerId:e.id,position:e.position,points:gh(e)}}function gh(e){const t=e.data;if(t.size()===0)return[];if(!t.hasVariable(g.x)||!t.hasVariable(g.y))return[];const n=t.getValues(g.x,{type:"numeric"}),r=t.getValues(g.y,{type:"numeric"}),o=[];let a=0;for(const s of t){const i=n[a],c=r[a];a+=1,!(!h(i)||!h(c))&&o.push({pointIndex:o.length,angle:i,radius:c,observation:s})}return o}const bh=1e6;function vh(e,t){const n=Sh(e,t);n.sort((i,c)=>i.mainMid-c.mainMid);const r=new Map,o=new Map;for(const i of n){const c=Jr(i.mainMid);let l=r.get(c);if(!l){l={mainMid:i.mainMid,columnKey:c,rects:[]},r.set(c,l);const u=Jr(i.bandCenter);let d=o.get(u);d||(d={bandCenter:i.bandCenter,bandKey:u,columns:[]},o.set(u,d)),d.columns.push(l)}l.rects.push(i.entry)}const a=[...r.values()].sort((i,c)=>i.mainMid-c.mainMid),s=[...o.values()].sort((i,c)=>i.bandCenter-c.bandCenter);for(const i of s)i.columns.sort((c,l)=>c.mainMid-l.mainMid);return{kind:"rects",layerId:e.id,position:e.position,mainAxis:t,columns:a,bands:s}}function Jr(e){return String(Math.round(e*bh))}function Sh(e,t){const n=e.data;if(n.size()===0)return[];if(!(n.hasVariable(g.xMin)&&n.hasVariable(g.xMax)&&n.hasVariable(g.yMin)&&n.hasVariable(g.yMax)))return[];const o=n.getValues(g.xMin,{type:"numeric"}),a=n.getValues(g.xMax,{type:"numeric"}),s=n.getValues(g.yMin,{type:"numeric"}),i=n.getValues(g.yMax,{type:"numeric"}),c=t==="y",l=c?g.y:g.x,u=n.hasVariable(l)?n.getValues(l,{type:"numeric"}):null,d=n.hasVariable(D.group)?n.getValues(D.group,{type:"categorical"}):null,m=[];let p=0;for(const f of n){const y=o[p],b=a[p],x=s[p],S=i[p];if(!h(y)||!h(b)||!h(x)||!h(S)){p++;continue}const w=c?(x+S)/2:(y+b)/2,k=u?.[p]??w;m.push({mainMid:w,bandCenter:k,entry:{pointIndex:p,xMin:y,xMax:b,yMin:x,yMax:S,segmentKey:d?.[p]??null,observation:f}}),p++}return m}function xh(e){const t=new Map;let n=0;for(const r of e.data)t.set(It(r),{pointIndex:n,observation:r}),n++;return{kind:"render-hit-test",layerId:e.id,position:e.position,byKey:t}}function eo(e,t,n){switch(e.spatialMap.kind){case"points":return fh(e,n);case"buckets":return dh(e,to(t));case"rects":return vh(e,to(t));case"arcs":return ch(e);case"polar-points":return yh(e);case"noop":return ph(e);case"render-hit-test":return xh(e);default:{const r=e.spatialMap.kind;throw new Error(`buildLayerIndex: unhandled spatial-map kind ${String(r)}`)}}}function to(e){if(e.type!=="cartesian")throw new Error("buildLayerIndex: a bucket or rect hit-test requires a cartesian coord system");return e.mainAxis}const X=Math.PI*2,wh=1e-9;function Ah(e,t,n){if(e.arcs.length===0)return null;const{angle:r,radius:o}=Th(t,n);for(const a of e.arcs)if(!(o<a.innerRadius||o>a.outerRadius)&&Mh(r,a))return{hit:{layerId:e.layerId,pointIndex:a.pointIndex,x:(a.startAngle+a.endAngle)/2,y:(a.innerRadius+a.outerRadius)/2,observation:a.observation},index:e};return null}function Th(e,t){const n=e.x-.5,r=e.y-.5,o=t>=1?n*2*t:n*2,a=t>=1?r*2:r*2/t,s=Math.hypot(o,a);return{angle:(Math.atan2(o,a)%X+X)%X,radius:s}}function Mh(e,t){const n=t.endAngle-t.startAngle;if(Math.abs(n)>=X-wh)return!0;const r=(n%X+X)%X;return((e-t.startAngle)%X+X)%X<=r}function Lh(e,t,n){if(e.points.length===0)return null;const r=t.x-.5,o=t.y-.5,a=n>=1?r*2*n:r*2,s=n>=1?o*2:o*2/n;let i=e.points[0];if(!i)return null;let c=Number.POSITIVE_INFINITY;for(const l of e.points){const u=l.radius*Math.sin(l.angle),d=l.radius*Math.cos(l.angle),m=Math.hypot(u-a,d-s);m<c&&(c=m,i=l)}return{hit:{layerId:e.layerId,pointIndex:i.pointIndex,x:i.angle,y:i.radius,observation:i.observation},index:e,distance:c}}function Vh(e,t,n){const r=n.get(e.layerId);if(!r)return null;const o=r({x:t.x,y:1-t.y});if(!o)return null;const a=e.byKey.get(o.key);return a?{hit:{layerId:e.layerId,pointIndex:a.pointIndex,x:t.x,y:t.y,observation:a.observation},index:e}:null}function kh(e,t,n){if(e.buckets.length===0)return null;const{main:r,cross:o}=Pp(e.mainAxis,t),a=Ha(e,r),s=a?.entries??[];if(!a||!ao(s))return null;const i=_h(s,o,e.mainAxis);return{hit:{layerId:e.layerId,pointIndex:i.pointIndex,x:i.x,y:i.y,observation:i.observation},index:e,bucket:a,distance:Yn(i.x-t.x,i.y-t.y,n)}}function Eh(e,t,n){if(e.columns.length===0)return null;const r=je(e.mainAxis,t),o=Zf(e,r),a=o?.rects??[];if(!o||!ao(a))return null;const s=Y(e.position)?Ih(a,t,e.mainAxis):Ch(a,t,n);return{hit:{layerId:e.layerId,pointIndex:s.pointIndex,x:(s.xMin+s.xMax)/2,y:(s.yMin+s.yMax)/2,observation:s.observation},index:e,column:o,distance:za(s,t,n)}}function Ih(e,t,n){const r=Ft(n,t);return Hn(e,a=>Fh(a,n,r),{shortCircuitOnZero:!0})}function Ch(e,t,n){return Hn(e,o=>za(o,t,n))}function _h(e,t,n){return Hn(e,o=>Math.abs(Ft(n,o)-t))}function Hn(e,t,{shortCircuitOnZero:n=!1}={}){let r=e[0],o=t(r);if(n&&o===0)return r;for(let a=1;a<e.length;a+=1){const s=e[a];if(s===void 0)continue;const i=t(s);if(n&&i===0)return s;i<o&&(r=s,o=i)}return r}function za(e,t,n){const r=ln(t.x,e.xMin,e.xMax),o=ln(t.y,e.yMin,e.yMax);return Yn(r,o,n)}function Fh(e,t,n){const r=t==="x"?e.yMin:e.xMin,o=t==="x"?e.yMax:e.xMax;return ln(n,r,o)}function ln(e,t,n){return e<t?t-e:e>n?e-n:0}const Dh=new Map,Rh=.05;function Nh({layers:e,cursor:t,aspectRatio:n,warmStarts:r,hitTesters:o=Dh}){const a={match:null,distance:Number.POSITIVE_INFINITY},s={match:null,distance:Number.POSITIVE_INFINITY};let i=null;for(const c of e){if(c.kind==="arcs"){const u=Ah(c,t,n);return u?{kind:"arcs",match:u}:null}if(c.kind==="polar-points"){const u=Lh(c,t,n);return u?{kind:"polar-points",match:u}:null}if(c.kind==="render-hit-test"){const u=Vh(c,t,o);u&&(i={kind:"render-hit-test",match:u});continue}const l=Oh({layer:c,cursor:t,aspectRatio:n,warmStarts:r});if(l){if(l.kind==="rects"){l.match.distance<a.distance&&(a.match=l,a.distance=l.match.distance);continue}l.match.distance<s.distance&&(s.match=l,s.distance=l.match.distance)}}return i||Ph({rect:a,continuous:s})}function Ph({rect:e,continuous:t}){return e.match&&t.match?t.distance<=e.distance+Rh?t.match:e.match:e.match??t.match}function Oh({layer:e,cursor:t,aspectRatio:n,warmStarts:r}){switch(e.kind){case"buckets":{const o=kh(e,t,n);return o?{kind:"buckets",match:o}:null}case"rects":{const o=Eh(e,t,n);return o?{kind:"rects",match:o}:null}case"points":{const o=r.get(e.layerId)??null,a=Jf(e,t,n,o);return a?{kind:"points",match:a}:null}case"noop":return null}}const me={primary:null,group:[],related:new Map},Bh=1;class $h{constructor({layers:t,coordSystem:n}){this.layerIndexes=[],this.layerRefs=[],this.aspectRatio=Bh,this.warmStarts=new Map,this.cachedState=me,this.cachedKey=null,this.nonInteractiveLayerIds=new Set,this.hitTesters=new Map,this.layerIndexes=t.map(r=>eo(r,n,this.aspectRatio)),this.layerRefs=t.map(r=>no(r,n)),this.nonInteractiveLayerIds=ro(t)}update({layers:t,coordSystem:n}){const r=new Map;for(let s=0;s<this.layerIndexes.length;s+=1){const i=this.layerIndexes[s],c=this.layerRefs[s];!i||!c||r.set(i.layerId,{index:i,ref:c})}const o=[],a=[];for(const s of t){const i=r.get(s.id),c=no(s,n);if(i!==void 0&&Gh(i.ref,c)){o.push(i.index),a.push(i.ref);continue}this.warmStarts.delete(s.id),o.push(eo(s,n,this.aspectRatio)),a.push(c)}for(const s of this.warmStarts.keys())t.some(i=>i.id===s)||this.warmStarts.delete(s);this.layerIndexes=o,this.layerRefs=a,this.nonInteractiveLayerIds=ro(t),this.invalidateCache()}setViewport(t){this.aspectRatio=t.width/t.height;for(const n of this.layerIndexes)n.kind==="points"&&Ka(n,this.aspectRatio)}setHitTesters(t){this.hitTesters=t}hoverByKey(t,n){const r=this.layerIndexes.find(l=>l.layerId===t);if(!r||r.kind!=="render-hit-test")return me;const o=r.byKey.get(n);if(!o)return me;const a={layerId:t,pointIndex:o.pointIndex,x:0,y:0,observation:o.observation},s={kind:"render-hit-test",match:{hit:a,index:r}},{group:i,related:c}=Zr(s,this.layerIndexes);return{primary:a,group:i,related:c}}query(t){if(this.layerIndexes.length===0)return me;const n=this.nonInteractiveLayerIds.size===0?this.layerIndexes:this.layerIndexes.filter(c=>!this.nonInteractiveLayerIds.has(c.layerId)),r=Nh({layers:n,aspectRatio:this.aspectRatio,warmStarts:this.warmStarts,hitTesters:this.hitTesters,cursor:t});if(!r)return this.invalidateCache(),me;const o=r.match.hit;this.warmStarts.set(o.layerId,o.pointIndex);const a=`${o.layerId}:${o.pointIndex}`;if(this.cachedKey===a)return this.cachedState;const{group:s,related:i}=Zr(r,n);return this.cachedKey=a,this.cachedState={primary:o,group:s,related:i},this.cachedState}invalidateCache(){this.cachedKey=null,this.cachedState=me}}function no(e,t){return{data:e.data,geom:e.geom,position:e.position,coord:t}}function ro(e){const t=new Set;for(const n of e)n.interactive||t.add(n.id);return t}function Gh(e,t){return e.data===t.data&&e.geom===t.geom&&e.position===t.position&&e.coord===t.coord}const Uh=({locale:e,intlOptions:t})=>R(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"long",year:"numeric",weekday:"long",...N,...t}).format(n)),Yh=({locale:e,intlOptions:t})=>R(n=>{const r=n.getUTCSeconds()!==0;return Intl.DateTimeFormat(e,{day:"2-digit",month:"short",year:"numeric",weekday:"short",hour:"2-digit",minute:"2-digit",second:r?"2-digit":void 0,...N,...t}).format(n)}),At=e=>{const{valueFormat:t}=e;switch(t.type){case"currency":return wa(e);case"date":return Uh(e);case"datetime":return Yh(e);case"day_month":return Ma(e);case"decimal":return En(e);case"duration":return In();case"integer":return Aa(e);case"month":return La(e);case"month_year":return Fn(e);case"percentage":return Ta(e);case"quarter":return Dn();case"text":return kn();case"time":return Ea(e);case"weekly_date_range":return Va(e);case"weekly_date_range_with_year":return ka(e);case"year":return Rn(e);case"lookup":return At({...e,valueFormat:t.fallback});default:{const n=t;throw new Error(`Unhandled value format: ${n.type}`)}}},Wh={type:"decimal"},Hh=({layers:e,coordSystem:t,scales:n,guides:r,numberFormat:o,parsingLocale:a,hover:s,formattingLocale:i})=>{const{primary:c}=s;if(c===null)return null;const l=i??a;return{header:Kh({layers:e,coordSystem:t,guides:r,primary:c,locale:l,numberFormat:o}),rows:zh({layers:e,coordSystem:t,scales:n,guides:r,hover:s,locale:l,numberFormat:o})}};function Kh(e){if(e.coordSystem.type!=="cartesian")return null;const t=Dt(e.guides,"x");if(!t)return null;const n=e.layers.find(s=>s.id===e.primary.layerId);if(!n)return null;const r=n.semanticMap.encodings.find(s=>s.aesthetic==="x");if(!r)return null;const o=e.primary.observation[r.variable];return h(o)?At({valueFormat:t.valueFormat,locale:e.locale,numberFormat:e.numberFormat})(o):null}function zh(e){const t=[],n=e.scales.color??null,r=Qh({guides:e.guides,locale:e.locale,numberFormat:e.numberFormat});for(const o of e.layers){const a=jh(o,e.hover);if(a.length===0)continue;if(o.semanticMap.detailRows.length>0){const{primary:p}=e.hover;p!==null&&p.layerId===o.id&&t.push(...Xh({layer:o,observation:p.observation,coordSystem:e.coordSystem,locale:e.locale,numberFormat:e.numberFormat}));continue}const s=Qo(o.data,o.mapping),i=qh(a,o,n,s),c=ll(o.semanticMap),l=C({valueFormat:Jh(o),locale:e.locale,numberFormat:e.numberFormat}),u=Zh(e.guides,o),d=o.mapping.color!==void 0,m=Xe(o.swatchShape,e.coordSystem);for(const p of i){const f=d?s(p.observation):null,y=dn(p.observation)??null,b=po(p.observation),x=d&&f!==null?r(f):u,S=ey(c,p),w=S===null?"":l(S,p.observation);t.push({swatchColor:y,swatchShape:m,swatchLineType:b,label:x,value:w,isPrimary:p===e.hover.primary,key:`${p.layerId}:${p.pointIndex}`})}}return t}function Xh(e){const t=Xe(e.layer.swatchShape,e.coordSystem);return e.layer.semanticMap.detailRows.map((n,r)=>{const o=C({valueFormat:n.valueFormat,locale:e.locale,numberFormat:e.numberFormat}),a=e.observation[n.variable]??null;return{swatchColor:null,swatchShape:t,swatchLineType:"solid",label:n.label,value:a===null?"":o(a,e.observation),isPrimary:!1,key:`${e.layer.id}:detail:${r}`}})}function jh(e,t){const n=[];return t.primary!==null&&t.primary.layerId===e.id&&n.push(t.primary,...t.group),n.push(...t.related.get(e.id)??[]),n}function qh(e,t,n,r){if(n===null||t.mapping.color===void 0)return e;const o=new Map;return n.domain.forEach((a,s)=>{o.set(V(a),s)}),e.map((a,s)=>{const i=r(a.observation),c=i===null?null:V(i),l=c===null?Number.POSITIVE_INFINITY:o.get(c)??Number.POSITIVE_INFINITY;return{hit:a,originalIndex:s,rank:l}}).sort((a,s)=>a.rank===s.rank?a.originalIndex-s.originalIndex:a.rank-s.rank).map(a=>a.hit)}function Qh({guides:e,locale:t,numberFormat:n}){const r=new Map(e.colorGroups.map(a=>[V(a.value),{label:a.label,format:At({valueFormat:a.valueFormat,locale:t,numberFormat:n})}])),o=At({valueFormat:{type:"text"},locale:t,numberFormat:n});return a=>{const s=r.get(V(a));return s===void 0?o(a):s.label??s.format(a)}}function Zh(e,t){const n=et(t.yScaleType);return Dt(e,n)?.label??""}function Jh(e){return e.semanticMap.encodings.find(n=>n.aesthetic==="y")?.valueFormat??Wh}function ey(e,t){return e(t.observation).encodings.find(r=>r.aesthetic==="y")?.value??null}const Xa={differenceArrow(e){return{type:"annotation",kind:"differenceArrow",annotation:e}},shape(e){return{type:"annotation",kind:"shape",annotation:e}},freeformArrow(e){return{type:"annotation",kind:"freeformArrow",annotation:e}},text(e){return{type:"annotation",kind:"text",annotation:e}},sticker(e){return{type:"annotation",kind:"sticker",annotation:e}},pinnedNumber(e){return{type:"annotation",kind:"pinnedNumber",annotation:e}},comment(e){return{type:"annotation",kind:"comment",annotation:e}}},ty={lilac:"linear-gradient(94deg, #C9C0F7 -2.94%, #F6E6FD 92.51%)",neon_pink:"linear-gradient(93deg, #E04A95 2.61%, #FD7F92 97.51%)",blackberry:"linear-gradient(132deg, #9F9FED 2.98%, #B9E6FF 97.65%)",sun:"linear-gradient(139deg, #FCDB61 5.51%, #FB9C65 97.21%)",iceland:"linear-gradient(94deg, #29CDA8 -2.94%, #52C9D2 92.51%)",sunset:"linear-gradient(138deg, #FCDB62 5.77%, #FD8091 99.91%)",ultraviolet:"linear-gradient(132deg, #D167D8 2.98%, #6584E6 97.65%)",purple:"linear-gradient(203.63deg, #BBADFD 15.22%, #BE9AF0 81.52%)",ice_cream:"linear-gradient(119.34deg, #FC7E91 3.68%, #FCD1B1 116.76%)",mint:"linear-gradient(93.55deg, #25CDA5 -6.07%, #58C8D8 113.6%)",cool:"linear-gradient(93.55deg, #3F8EEB -6.07%, #58C8D8 113.6%)",fresh:"linear-gradient(114.37deg, #A4A4EE 4.32%, #58C8D8 87.71%)"};function ja(...e){let t={},n;const[r,...o]=e;h(r)&&!ry(r)?(t=r,n=o):n=e;const a={mapping:t,layers:[],scales:[],transforms:[],highlights:[],config:{}};return n.reduce((s,i)=>qa(s,i),a)}function ny(e,...t){return t.reduce((n,r)=>qa(n,r),e)}function ry(e){return typeof e=="object"&&e!==null&&"type"in e}function qa(e,t){switch(t.type){case"scale":return{...e,scales:[...e.scales,t]};case"coord":return{...e,coords:t};case"config":return{...e,config:oo({},e.config,t.config)};case"layer":return{...e,layers:[...e.layers,t]};case"transform":return{...e,transforms:[...e.transforms,t]};case"mapping":return{...e,mapping:{...e.mapping,...t.mapping}};case"highlight":return{...e,highlights:[...e.highlights,t]};case"annotation":return oy(e,t);default:{const n=t;throw new Error(`Unknown spec item type: ${n.type}`)}}}function oy(e,t){const n={...e.annotations};switch(t.kind){case"differenceArrow":n.differenceArrows=[...n.differenceArrows??[],t.annotation];break;case"shape":n.shapes=[...n.shapes??[],t.annotation];break;case"freeformArrow":n.freeformArrows=[...n.freeformArrows??[],t.annotation];break;case"text":n.textAnnotations=[...n.textAnnotations??[],t.annotation];break;case"sticker":n.stickers=[...n.stickers??[],t.annotation];break;case"pinnedNumber":n.pinnedNumbers=[...n.pinnedNumbers??[],t.annotation];break;case"comment":n.comments=[...n.comments??[],t.annotation];break;case"custom":n.custom=[...n.custom??[],t.annotation];break;default:{const r=t;throw new Error(`Unknown annotation kind: ${r.kind}`)}}return{...e,annotations:n}}function ay(e){const t={};for(const r of e.geoms??[]){const o=r;t[o.type]=(a={})=>({type:"layer",geom:o.type,mapping:a.aes,stat:a.stat,params:{...o.defaultParams,...a.params},position:a.position,yScaleType:a.yScaleType,transforms:a.transforms,interactive:a.interactive,dataLabels:a.dataLabels})}const n={};for(const r of e.annotations??[]){const o=r;n[o.type]=a=>(sy(o,a.coordinates),{type:"annotation",kind:"custom",annotation:{id:a.id,type:o.type,coordinates:a.coordinates,params:{...o.defaultParams,...a.params},zOrder:a.zOrder}})}return{geom:{...I,...t},annotation:{...Xa,...n},createSpec:ja}}function sy(e,t){const n=e.coordinates;if(n!==void 0){if(n.min!==void 0&&t.length<n.min)throw new Error(`Annotation '${e.type}' requires at least ${n.min} coordinate(s), got ${t.length}.`);if(n.max!==void 0&&t.length>n.max)throw new Error(`Annotation '${e.type}' accepts at most ${n.max} coordinate(s), got ${t.length}.`)}}function iy(e,t={}){return{type:"highlight",id:t.id,predicate:e,scope:t.scope,layerIndex:t.layerIndex}}function cy(e){return{mapping:e.mapping,layers:e.layers,scales:e.scales.map(uy),transforms:e.transforms,highlights:e.highlights.map(t=>ly(t,e.layers)),coords:e.coords,config:e.config}}function ly(e,t){const n=e.layerId?t.findIndex(r=>r.id===e.layerId):-1;return{type:"highlight",id:e.id,predicate:e.predicate,scope:e.scope,layerIndex:n>=0?n:void 0}}function uy(e){return e.scaleType==="palette"?dy(e):e}function dy(e){return{...e,palette:my(e.palette)}}function my(e){return e.type==="custom"?{type:"custom",id:e.id}:e}class py{constructor(t={}){this.undoStack=[],this.redoStack=[],this.listeners=new Set,this.isEmitting=!1,this.cachedSnapshot=null,this.maxHistorySize=t.maxHistorySize??100}apply(t,n){return this.withReentrancyGuard(()=>{const r=t.apply(n);return r?(this.undoStack.push({command:t,revert:r.revert}),this.redoStack=[],this.undoStack.length>this.maxHistorySize&&this.undoStack.shift(),this.emit({type:"apply",command:t,spec:r.spec}),r.spec):n})}undo(t){return this.withReentrancyGuard(()=>{const n=this.undoStack.pop();if(!n)return null;const r=n.revert.apply(t);return r?(this.redoStack.push({command:n.command,revert:r.revert}),this.emit({type:"undo",command:n.command,spec:r.spec}),{spec:r.spec,command:n.command}):(this.undoStack.push(n),null)})}redo(t){return this.withReentrancyGuard(()=>{const n=this.redoStack.pop();if(!n)return null;const r=n.revert.apply(t);return r?(this.undoStack.push({command:n.command,revert:r.revert}),this.emit({type:"redo",command:n.command,spec:r.spec}),{spec:r.spec,command:n.command}):(this.redoStack.push(n),null)})}clear(){this.withReentrancyGuard(()=>{this.undoStack=[],this.redoStack=[],this.emit({type:"clear"})})}getSnapshot(){return this.cachedSnapshot||(this.cachedSnapshot={canUndo:this.undoStack.length>0,canRedo:this.redoStack.length>0,undoDescription:this.undoStack[this.undoStack.length-1]?.command.metadata.description??null,redoDescription:this.redoStack[this.redoStack.length-1]?.command.metadata.description??null}),this.cachedSnapshot}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}withReentrancyGuard(t){if(this.isEmitting)throw new Error("CommandStack: cannot call apply/undo/redo/clear from within a listener");this.isEmitting=!0;try{return t()}finally{this.isEmitting=!1}}emit(t){this.cachedSnapshot=null;for(const n of this.listeners)try{n(t)}catch(r){console.error("CommandStack listener error:",r)}}}function Se(e){return{id:e.id??crypto.randomUUID(),timestamp:e.timestamp??Date.now(),description:e.description,author:e.author??"unknown"}}class Kn{constructor(t,n={}){this.type="set-axis-position",this.params=t,this.metadata=Se({...n,description:`Set ${t.axis} axis position to ${t.position}`})}apply(t){const{axis:n,position:r}=this.params,o=qe(t,{config:{axes:{[n]:{position:r}}}}),a=n==="x"?{axis:"x",position:t.config.axes.x.position}:{axis:"y",position:t.config.axes.y.position},s=new Kn(a,this.metadata);return{spec:o,revert:s}}}class zn{constructor(t,n={}){this.type="set-content-caption",this.params=t,this.metadata=Se({...n,description:"Set chart caption"})}apply(t){const n=t.config.content.caption;if(n===this.params.caption)return null;const r=qe(t,{config:{content:{caption:this.params.caption}}}),o=new zn({caption:n},this.metadata);return{spec:r,revert:o}}}class Xn{constructor(t,n={}){this.type="set-content-subtitle",this.params=t,this.metadata=Se({...n,description:"Set chart subtitle"})}apply(t){const n=t.config.content.subtitle;if(n===this.params.subtitle)return null;const r=qe(t,{config:{content:{subtitle:this.params.subtitle}}}),o=new Xn({subtitle:n},this.metadata);return{spec:r,revert:o}}}class jn{constructor(t,n={}){this.type="set-content-title",this.params=t,this.metadata=Se({...n,description:"Set chart title"})}apply(t){const n=t.config.content.title;if(n===this.params.title)return null;const r=qe(t,{config:{content:{title:this.params.title}}}),o=new jn({title:n},this.metadata);return{spec:r,revert:o}}}class qn{constructor(t,n={}){this.type="set-headline-show",this.params=t,this.metadata=Se({...n,description:`Set headline show to ${t.show}`})}apply(t){const n=t.config.headline.show,r=qe(t,{config:{headline:{show:this.params.show}}}),o=new qn({show:n},this.metadata);return{spec:r,revert:o}}}class Qn{constructor(t,n={}){this.type="set-line-width",this.params=t,this.metadata=Se({...n,description:`Set line width to ${t.lineWidth}`})}apply(t){const n=this.params.layerId?Hd(t.layers,this.params.layerId):pa(t.layers,"line","area");if(!Wd(n,"line","area"))return null;const r=n.params.lineWidth,o=Kd(t,n.id,{...n,params:{...n.params,lineWidth:this.params.lineWidth}}),a=new Qn({layerId:n.id,lineWidth:r},this.metadata);return{spec:o,revert:a}}}function fy(e,t){return e.scales.find(n=>n.scaledAesthetic===t)}function hy(e,t,n){const r=e.scales.map(o=>o.scaledAesthetic===t?n:o);return{...e,scales:r}}function yy(e){const t=e.replace(/([A-Z])/g," $1").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}class Zn{constructor(t,n={}){this.type="set-scale-domain",this.params=t,this.metadata=Se({...n,description:`Set ${yy(t.scaledAesthetic)} scale domain`})}apply(t){const n=fy(t,this.params.scaledAesthetic);if(!n||n.scaleType!=="continuous"&&n.scaleType!=="datetime")return null;const r={min:n.domainMin??null,max:n.domainMax??null},o={...n,...this.params.domainMin!==void 0&&{domainMin:this.params.domainMin},...this.params.domainMax!==void 0&&{domainMax:this.params.domainMax}},a=hy(t,this.params.scaledAesthetic,o),s={scaledAesthetic:this.params.scaledAesthetic};this.params.domainMin!==void 0&&(s.domainMin=r.min),this.params.domainMax!==void 0&&(s.domainMax=r.max);const i=new Zn(s,this.metadata);return{spec:a,revert:i}}}const Jn=500,er="normal",Qa={thin:100,hairline:100,extraLight:200,ultraLight:200,light:300,normal:400,regular:400,medium:500,semiBold:600,demiBold:600,bold:700,extraBold:800,ultraBold:800,black:900,heavy:900,extraBlack:950,ultraBlack:950},gy=e=>{const t=e.style??er,n=e.weight??Jn,r=e.family.includes(",")?e.family:`'${e.family}'`;return`${t} ${n} ${e.size}px ${r}`},by=e=>typeof e=="string"?e:Za(e),Za=e=>e.text!==void 0?e.text:e.content?e.content.map(Za).join(""):"",Ja=e=>typeof e!="string"?e??Jn:Qa[e],vy="\0";class Sy{constructor(t){this.inner=t,this.cache=new Map}measureText(t,n){const r=this.getCacheKey(t,n),o=this.cache.get(r);if(o)return o;const a=this.inner.measureText(t,n);return this.cache.set(r,a),a}getCacheKey(t,n){return[n.family,n.size,Ja(n.weight),n.style??er,t].join(vy)}}const xy={" ":.25,"!":.27,'"':.36,"#":.6,$:.56,"%":.78,"&":.66,"'":.21,"(":.31,")":.31,"*":.44,"+":.56,",":.22,"-":.36,".":.22,"/":.35,0:.56,1:.56,2:.56,3:.56,4:.56,5:.56,6:.56,7:.56,8:.56,9:.56,":":.22,";":.22,"<":.56,"=":.56,">":.56,"?":.46,"@":.88,A:.63,B:.63,C:.65,D:.69,E:.56,F:.53,G:.7,H:.7,I:.26,J:.44,K:.62,L:.53,M:.84,N:.7,O:.73,P:.6,Q:.73,R:.62,S:.56,T:.56,U:.69,V:.6,W:.88,X:.58,Y:.56,Z:.58,"[":.29,"\\":.35,"]":.29,"^":.56,_:.44,"`":.33,a:.53,b:.58,c:.48,d:.58,e:.54,f:.31,g:.56,h:.57,i:.23,j:.23,k:.52,l:.23,m:.87,n:.57,o:.57,p:.58,q:.58,r:.35,s:.45,t:.34,u:.57,v:.49,w:.74,x:.49,y:.49,z:.46,"{":.33,"|":.26,"}":.33,"~":.56},wy=.55,Ay=1.05,Ty=.84,My=.21;class Ly{measureText(t,n){let r=0;for(const i of t)r+=(xy[i]??wy)*n.size;Ja(n.weight)>=Qa.semiBold&&(r*=Ay);const a=Ty*n.size,s=My*n.size;return{width:r,height:a+s,ascent:a,descent:s}}}function Vy(e,t,n){const r=e[t];return typeof r=="number"?r:n??null}function ky(e,t,n){const r=e[t];return typeof r=="string"?r:n??null}class Ey{constructor(){this.columnTypes=new Map,this.kindColumns=new Map,this.rows=[]}kind(t,n){if(this.kindColumns.has(t))throw new Error(`createMarkTable: kind "${t}" is already declared.`);for(const[r,o]of Object.entries(n)){const a=this.columnTypes.get(r);if(a!==void 0&&a!==o)throw new Error(`createMarkTable: column "${r}" is declared as both "${a}" and "${o}".`);this.columnTypes.set(r,o)}return this.kindColumns.set(t,Object.keys(n)),this}push(t,n){const r=this.kindColumns.get(t);if(!r)throw new Error(`createMarkTable: cannot push to undeclared kind "${t}".`);for(const o of r)if(!(o in n))throw new Error(`createMarkTable: row for kind "${t}" is missing column "${o}".`);for(const o of Object.keys(n))if(!r.includes(o))throw new Error(`createMarkTable: column "${o}" is not declared for kind "${t}".`);return this.rows.push({kind:t,values:n}),this}toDataset(t){const{kindColumn:n}=t;if(this.columnTypes.has(n))throw new Error(`createMarkTable: kindColumn "${n}" collides with a declared column.`);const r={[n]:{type:"categorical",values:this.rows.map(o=>o.kind)}};for(const[o,a]of this.columnTypes)r[o]={type:a,values:this.rows.map(s=>{const i=s.values[o];return i===void 0?null:i})};return new M(r)}}function Iy(){return new Ey}function Cy(e){return{type:e.type,defaultParams:e.defaultParams??{},coordinates:e.coordinates}}function _y(e,t,n,r,o){const a=n-t;return a===0?r:r+(e-t)/a*(o-r)}exports.BORDER_PRESETS=ia;exports.BORDER_PRESET_GRADIENTS=ty;exports.BUILTIN_GEOM_NAMES=zo;exports.COMPILER_STAGE_KEYS=km;exports.CachedTextMeasurer=Sy;exports.CommandStackManager=py;exports.Compiler=Sa;exports.DEFAULT_COLOR_PALETTE=wn;exports.DEFAULT_FONT_STYLE=er;exports.DEFAULT_FONT_WEIGHT=Jn;exports.DEFAULT_LOCALE=Lt;exports.Dataset=M;exports.GEOM_NAMES=Ko;exports.GROUP_VARIABLES=D;exports.Geom=Ce;exports.HeuristicTextMeasurer=Ly;exports.HoverEngine=$h;exports.LAYOUT_PADDING=Da;exports.LayoutCompiler=Cp;exports.MONO_BASES=ra;exports.NEON_BASES=oa;exports.POSITION_VARIABLES=g;exports.RESTING_HOVER_STATE=me;exports.SetAxisPositionCommand=Kn;exports.SetContentCaptionCommand=zn;exports.SetContentSubtitleCommand=Xn;exports.SetContentTitleCommand=jn;exports.SetHeadlineShowCommand=qn;exports.SetLineWidthCommand=Qn;exports.SetScaleDomainCommand=Zn;exports.SpecResolver=ya;exports.VISUAL_VARIABLES=ie;exports.annotation=Xa;exports.buildAverageLineSymbols=Rp;exports.buildDataLabelsContent=Sf;exports.buildFontString=gy;exports.buildLayerYValueFormatter=Ya;exports.buildTooltipContent=Hh;exports.computeDifferenceArrow=Vf;exports.computeDirectLabelsLayout=Ef;exports.computeFreeformArrow=jf;exports.config=ca;exports.convertSpecToInput=cy;exports.coord=P;exports.createAlphaValueReader=Jc;exports.createColorValueReader=Qo;exports.createCompiler=Em;exports.createEmptyHighlight=Zo;exports.createGraphyBuilder=ay;exports.createGroupValueReader=el;exports.createLabelValueReader=Qc;exports.createMarkTable=Iy;exports.createRawValueReader=W;exports.createSegmentYReader=Sn;exports.createSizeValueReader=Zc;exports.createSpec=ja;exports.createStrokeWidthValueReader=tl;exports.createValueFormatter=C;exports.createXValueReader=vn;exports.createYValueReader=qo;exports.defineAnnotation=Cy;exports.extractConstantValue=ee;exports.extractPlainText=by;exports.extractVariableName=v;exports.findAxisGuide=Dt;exports.findLegendForAesthetic=Bf;exports.formatHeadline=If;exports.formatLegends=Pf;exports.formatRuleValue=$f;exports.geom=I;exports.getAlpha=hs;exports.getAngleExtent=Ga;exports.getColor=dn;exports.getCrossAxisCoordinate=Ft;exports.getDifferenceArrowDimensions=Bn;exports.getGroup=ke;exports.getIdentityKey=It;exports.getLineType=po;exports.getMainAxisCoordinate=je;exports.getRadiusExtent=Ua;exports.getSize=mo;exports.getStrokeWidth=ys;exports.getX=_e;exports.getXMax=Le;exports.getXMin=ze;exports.getY=te;exports.getYMax=j;exports.getYMin=ge;exports.getYRaw=Oo;exports.highlight=iy;exports.interpolateInScaledInterval=_y;exports.isBuiltinGeomName=Xo;exports.isCartesian=Op;exports.isCompilerCachingEnabled=os;exports.isDefined=h;exports.isGraphConfig=aa;exports.isLayerOf=Im;exports.isStackedPosition=Y;exports.mapping=is;exports.pipe=ny;exports.prefixInternalVariable=A;exports.readAesthetic=un;exports.readNumber=Vy;exports.readString=ky;exports.resolveHeadlinePlacement=kp;exports.resolveSegmentYSource=tt;exports.resolveYScaleAesthetic=et;exports.scale=he;exports.setCompilerCachingEnabled=rs;exports.sortByXIfContinuous=Vt;exports.stat=An;exports.transform=fe;exports.variableFor=$;
|
|
26
|
+
`,qf=(e,t,n,r,s,o=.5)=>{if(e){const i=Math.min(t.y,n.y);return{x:r,y:i+o*s}}return{x:Math.min(t.x,n.x)+o*s,y:r}},jf=(e,t,n)=>Math.abs(e?t.y-n.y:t.x-n.x),Qf=({arrow:e,mainAxis:t,panelWidth:n,panelHeight:r,textScale:s,locale:o})=>{const a=t==="y",i={x:e.start.x*n,y:(1-e.start.y)*r},c={x:e.end.x*n,y:(1-e.end.y)*r},l=nr(e.size,s),u=Wf(a,i,c,l),d=(a?Kf:Hf)(i,c,u,l),p=Xf(a,c,l),m=jf(a,i,c),f=qf(a,i,c,u,m,e.labelCrossPosition),y=ra({locale:o,kind:e.label,startValue:e.start.measurementValue,endValue:e.end.measurementValue});return{id:e.id,linePath:d,arrowheadPath:p,labelPosition:f,labelText:y,color:e.color,strokeWidth:l.strokeWidth,labelLineHeight:l.labelLineHeight,labelPaddingX:l.labelPaddingX,labelPaddingY:l.labelPaddingY,labelStrokeWidth:l.labelStrokeWidth,labelFontWeight:l.labelFontWeight}},Zf=100,Jf=({items:e,containerHeight:t,labelHeight:n})=>{const r=e.map(l=>{const u=(1-l.normalizedY)*t;return{anchorY:u,y:u,payload:l.payload}}).sort((l,u)=>l.y-u.y),s=n/2;let o=!1,a=!0,i=0;for(;a;){a=!1,i++;for(let l=0;l<r.length-1;l++){const u=r[l],d=r[l+1];if(!u||!d)continue;const p=u.y+s,m=d.y-s;if(p>m){a=!0,o=!0;const y=(p-m)/2+1;u.y-=y,d.y+=y,u.y<0&&(u.y=0),d.y>t&&(d.y=t)}}if(i>Zf)break}return{placements:r.filter(l=>l.y>=0&&l.y<=t).map(l=>({y:l.y,anchorY:l.anchorY,payload:l.payload})),hasOverlap:o}},eh=({headline:e,show:t,numberFormat:n,parsingLocale:r,formattingLocale:s})=>{if(e===null)return null;const o=s??r;return e.kind==="grandTotal"?th(e,o,n):nh(e,t,o,n)},th=(e,t,n)=>({kind:"grandTotal",value:D({valueFormat:e.valueFormat,locale:t,numberFormat:n})(e.value)}),nh=(e,t,n,r)=>{const s=D({valueFormat:{type:"percentage"},locale:n,numberFormat:r}),o=ah(t,e.items.length>1);return{kind:"perGroup",items:e.items.map(i=>{const c=D({valueFormat:i.valueFormat,locale:n,numberFormat:r}),l=D({valueFormat:i.groupLabelFormat,locale:n,numberFormat:r}),u=tr({valueFormat:i.mainValueFormat,locale:n,numberFormat:r,tickValues:[]}),d=i.label??l(i.value);return{swatch:i.swatch,label:`${o}${d}`,value:i.aggregate===null?null:c(i.aggregate),observationLabel:oh(i.observationLabel,u),comparison:rh(i.comparison,u,s)}})}},rh=(e,t,n)=>e===null?null:{direction:sh(e.variation),percentage:n(Math.abs(e.variation)),reference:`from ${t(e.against)}`},sh=e=>e>0?"up":e<0?"down":"flat",oh=(e,t)=>e===null?null:e.kind==="point"?t(e.value):`${t(e.from)} – ${t(e.to)}`,ah=(e,t)=>{switch(e){case"total":return"Total ";case"average":return t?"Avg. ":"Average ";default:return""}},ih=({legends:e,numberFormat:t,parsingLocale:n,formattingLocale:r})=>{const s=r??n;return e.map(o=>ch(o,s,t))},ch=(e,t,n)=>({...e,items:e.items.map(r=>{const s=D({valueFormat:r.valueFormat,locale:t,numberFormat:n});return{...r,formattedLabel:r.label??s(r.value)}})});function $t(e,t){return e.axes.find(n=>n.scaleAestheticKey===t)??null}function lh(e,t){return e.legends.find(n=>n.aesthetics.includes(t))??null}const uh=({guides:e,numberFormat:t,layer:n,locale:r})=>{const s=n.data.getFirst();if(!s)return null;const o=n.mapping.y!==void 0,i=(o?xo:Rn)(n.data,n.mapping)(s);if(i===null)return null;const c=o?tt(n.yScaleType):"x",l=$t(e,c)?.valueFormat??{type:"decimal"};return D({valueFormat:l,locale:r,numberFormat:t})(i)},dh=800,ws=400,ph={thin:{strokeWidth:{minValue:1.5,targetValue:2},arrowheadLength:{minValue:7,targetValue:8}},medium:{strokeWidth:{minValue:3,targetValue:4},arrowheadLength:{minValue:14,targetValue:16}},thick:{strokeWidth:{minValue:6,targetValue:8},arrowheadLength:{minValue:28,targetValue:32}}},mh=e=>Math.max(1,(e-ws)/(dh-ws)+1),fh=(e,t)=>{const n=mh(t),r=ph[e];return{strokeWidth:Math.min(r.strokeWidth.targetValue,r.strokeWidth.minValue*n),arrowheadLength:Math.min(r.arrowheadLength.targetValue,r.arrowheadLength.minValue*n)}},ft=Math.PI/4,An=1.5,hh=({startX:e,startY:t,endX:n,endY:r})=>`M ${e} ${t} L ${n} ${r}`,As=(e,t,n)=>{if(n<=0)return"";const{startX:r,startY:s,endX:o,endY:a}=t,i=e==="start"?r:o,c=e==="start"?s:a,l=e==="start"?Math.atan2(s-a,r-o):Math.atan2(a-s,o-r),u=i-n*Math.cos(l-ft),d=c-n*Math.sin(l-ft),p=i-n*Math.cos(l+ft),m=c-n*Math.sin(l+ft);return`M ${i} ${c} L ${u} ${d} M ${i} ${c} L ${p} ${m}`},yh=(e,t)=>e==="solid"?null:`${t*An} ${t*An*2}`,gh=(e,t)=>t?e*An:0,bh=64,vh=({arrow:e,panelWidth:t,panelHeight:n})=>{const r={startX:e.start.x*t,startY:e.start.y*n,endX:e.end.x*t,endY:e.end.y*n};if(r.startX===r.endX&&r.startY===r.endY)return null;const{strokeWidth:s,arrowheadLength:o}=fh(e.thickness,t),a=Math.hypot(r.endX-r.startX,r.endY-r.startY),i=Sh(o,a),c=e.startArrowheadStyle==="line-arrow",l=e.endArrowheadStyle==="line-arrow",d=c||l?i*Math.sin(Math.PI/4):0;return{id:e.id,linePath:hh(r),startArrowheadPath:c?As("start",r,i):"",endArrowheadPath:l?As("end",r,i):"",color:e.color,strokeWidth:s,dashArray:yh(e.lineStyle,s),hasStickerStyle:e.hasStickerStyle,startX:r.startX,startY:r.startY,endX:r.endX,endY:r.endY,dashOffset:gh(s,c),arrowheadExtent:d}},Sh=(e,t)=>Math.min(e,t*e/bh);function ya(e,t){return or(e.buckets,t,n=>n.main)}function xh(e,t){return or(e.bands,t,n=>n.bandCenter)}function wh(e,t){return or(e.columns,t,n=>n.mainMid)}function or(e,t,n){if(e.length===0)return null;let r=0,s=e.length;for(;r<s;){const i=r+s>>>1,c=e[i];c&&n(c)<t?r=i+1:s=i}const o=e[r-1],a=e[r];return o?a&&Math.abs(n(a)-t)<Math.abs(n(o)-t)?a:o:a??null}function ar(e,t,n){return Math.hypot(e*n,t)}function Ah(e,t,n,r){if(e.points.length===0)return null;const s=e.delaunay;if(!s)return null;const o=s.find(t.x*n,t.y,r??void 0),a=e.points[o];return a?{hit:{layerId:e.layerId,pointIndex:a.pointIndex,x:a.x,y:a.y,observation:a.observation},index:e,distance:ar(a.x-t.x,a.y-t.y,n)}:null}function Th(e,t){if(e.points.length===0||!e.delaunay||e.delaunayAspectRatio===null)return null;const n=e.delaunay.find(t.x*e.delaunayAspectRatio,t.y);return e.points[n]??null}function Ts(e,t){return{group:Mh(e),related:Eh(e,t)}}function Mh(e){switch(e.kind){case"buckets":{const t=e.match.index;return H(t.position)?Lh(t,e.match):[]}case"rects":{const t=e.match.index;return H(t.position)?Vh(t,e.match):kh(t,e.match)}case"points":case"arcs":case"polar-points":case"render-hit-test":return[]}}function Lh(e,t){const n=[];for(const r of t.bucket.entries)r.pointIndex!==t.hit.pointIndex&&n.push({layerId:e.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation});return n}function Vh(e,t){const n=[];for(const r of t.column.rects)r.pointIndex!==t.hit.pointIndex&&n.push(ir(e,r));return n}function kh(e,t){const n=e.bands.find(s=>s.columns.includes(t.column));if(!n)return[];const r=[];for(const s of n.columns)for(const o of s.rects)o.pointIndex!==t.hit.pointIndex&&r.push(ir(e,o));return r}function Eh(e,t){const n=new Map;if(e.kind==="arcs"||e.kind==="polar-points")return n;for(const r of t){if(r.layerId!==e.match.index.layerId){Ch(n,r,e.match.hit);continue}e.kind==="buckets"&&(H(r.position)||r.kind==="buckets"&&Ih(n,r,e.match))}return n}function Ih(e,t,n){for(const r of n.bucket.entries){if(r.pointIndex===n.hit.pointIndex)continue;xt(e,t.layerId).push({layerId:t.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation})}}function Ch(e,t,n){switch(t.kind){case"buckets":{const r=ya(t,Qe(t.mainAxis,n));if(!r)return;const s=xt(e,t.layerId);for(const o of r.entries)s.push({layerId:t.layerId,pointIndex:o.pointIndex,x:o.x,y:o.y,observation:o.observation});return}case"rects":{const r=xh(t,Qe(t.mainAxis,n));if(!r)return;const s=xt(e,t.layerId);for(const o of r.columns)for(const a of o.rects)s.push(ir(t,a));return}case"points":{const r=Th(t,n);if(!r)return;xt(e,t.layerId).push({layerId:t.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation});return}case"arcs":case"polar-points":return;case"noop":return;case"render-hit-test":return}}function xt(e,t){let n=e.get(t);return n||(n=[],e.set(t,n)),n}function ir(e,t){return{layerId:e.layerId,pointIndex:t.pointIndex,x:(t.xMin+t.xMax)/2,y:(t.yMin+t.yMax)/2,observation:t.observation}}function Fh(e){const t=Dh(e);return{kind:"arcs",layerId:e.id,position:e.position,arcs:t}}function Dh(e){const t=e.data;if(t.size()===0)return[];const n=[g.xMin,g.xMax,g.yMin,g.yMax];for(const l of n)if(!t.hasVariable(l))return[];const r=t.getValues(g.xMin,{type:"numeric"}),s=t.getValues(g.xMax,{type:"numeric"}),o=t.getValues(g.yMin,{type:"numeric"}),a=t.getValues(g.yMax,{type:"numeric"}),i=[];let c=0;for(const l of t){const u=r[c],d=s[c],p=o[c],m=a[c];if(!h(u)||!h(d)||!h(p)||!h(m)){c++;continue}i.push({pointIndex:c,startAngle:u,endAngle:d,innerRadius:p,outerRadius:m,observation:l}),c++}return i}const _h=1e-9;function Rh(e,t){const n=Ph(e,t);n.sort((s,o)=>s.main-o.main);const r=[];for(const s of n){const o=r[r.length-1];o&&Math.abs(o.main-s.main)<=_h?o.entries.push(s.entry):r.push({main:s.main,entries:[s.entry]})}return{kind:"buckets",layerId:e.id,position:e.position,mainAxis:t,buckets:r}}function Ph(e,t){const n=e.data;if(n.size()===0)return[];const s=n.hasVariable(g.x),o=n.hasVariable(g.y);if(!s||!o)return[];const a=n.getValues(g.x,{type:"numeric"}),i=n.getValues(g.y,{type:"numeric"}),c=t==="y",l=c?g.xMin:g.yMin,u=c?g.xMax:g.yMax,d=H(e.position),p=d?n.getValues(l,{type:"numeric"}):null,m=d?n.getValues(u,{type:"numeric"}):null,f=n.hasVariable(P.group)?n.getValues(P.group,{type:"categorical"}):null,y=[];let b=0;for(const x of n){const S=a[b],w=i[b];if(!h(S)||!h(w)){b+=1;continue}const I=f?.[b]??null,_=c?w:S;if(d){const X=p?.[b],Oe=m?.[b];if(!h(X)||!h(Oe)){b+=1;continue}const T=c?Oe:S,ee=c?w:Oe;y.push({main:_,entry:{isStacked:d,pointIndex:b,x:T,y:ee,stackMin:X,stackMax:Oe,groupKey:I,observation:x}})}else y.push({main:_,entry:{isStacked:d,pointIndex:b,x:S,y:w,groupKey:I,observation:x}});b+=1}return y}function Nh(e){return{kind:"noop",layerId:e.id,position:e.position}}function Oh(e,t){const n={kind:"points",layerId:e.id,position:e.position,points:$h(e),delaunay:null,delaunayAspectRatio:null};return ga(n,t),n}function ga(e,t){e.delaunay&&e.delaunayAspectRatio===t||(e.delaunay=ka.Delaunay.from(e.points,n=>n.x*t,n=>n.y),e.delaunayAspectRatio=t)}function $h(e){const t=e.data;if(t.size()===0)return[];if(!t.hasVariable(g.x)||!t.hasVariable(g.y))return[];const n=t.getValues(g.x,{type:"numeric"}),r=t.getValues(g.y,{type:"numeric"}),s=[];let o=0;for(const a of t){const i=n[o],c=r[o];o+=1,!(!h(i)||!h(c))&&s.push({pointIndex:s.length,x:i,y:c,observation:a})}return s}function Bh(e){return{kind:"polar-points",layerId:e.id,position:e.position,points:Gh(e)}}function Gh(e){const t=e.data;if(t.size()===0)return[];if(!t.hasVariable(g.x)||!t.hasVariable(g.y))return[];const n=t.getValues(g.x,{type:"numeric"}),r=t.getValues(g.y,{type:"numeric"}),s=[];let o=0;for(const a of t){const i=n[o],c=r[o];o+=1,!(!h(i)||!h(c))&&s.push({pointIndex:s.length,angle:i,radius:c,observation:a})}return s}const zh=1e6;function Uh(e,t){const n=Yh(e,t);n.sort((i,c)=>i.mainMid-c.mainMid);const r=new Map,s=new Map;for(const i of n){const c=Ms(i.mainMid);let l=r.get(c);if(!l){l={mainMid:i.mainMid,columnKey:c,rects:[]},r.set(c,l);const u=Ms(i.bandCenter);let d=s.get(u);d||(d={bandCenter:i.bandCenter,bandKey:u,columns:[]},s.set(u,d)),d.columns.push(l)}l.rects.push(i.entry)}const o=[...r.values()].sort((i,c)=>i.mainMid-c.mainMid),a=[...s.values()].sort((i,c)=>i.bandCenter-c.bandCenter);for(const i of a)i.columns.sort((c,l)=>c.mainMid-l.mainMid);return{kind:"rects",layerId:e.id,position:e.position,mainAxis:t,columns:o,bands:a}}function Ms(e){return String(Math.round(e*zh))}function Yh(e,t){const n=e.data;if(n.size()===0)return[];if(!(n.hasVariable(g.xMin)&&n.hasVariable(g.xMax)&&n.hasVariable(g.yMin)&&n.hasVariable(g.yMax)))return[];const s=n.getValues(g.xMin,{type:"numeric"}),o=n.getValues(g.xMax,{type:"numeric"}),a=n.getValues(g.yMin,{type:"numeric"}),i=n.getValues(g.yMax,{type:"numeric"}),c=t==="y",l=c?g.y:g.x,u=n.hasVariable(l)?n.getValues(l,{type:"numeric"}):null,d=n.hasVariable(P.group)?n.getValues(P.group,{type:"categorical"}):null,p=[];let m=0;for(const f of n){const y=s[m],b=o[m],x=a[m],S=i[m];if(!h(y)||!h(b)||!h(x)||!h(S)){m++;continue}const w=c?(x+S)/2:(y+b)/2,I=u?.[m]??w;p.push({mainMid:w,bandCenter:I,entry:{pointIndex:m,xMin:y,xMax:b,yMin:x,yMax:S,segmentKey:d?.[m]??null,observation:f}}),m++}return p}function Wh(e){const t=new Map;let n=0;for(const r of e.data)t.set(Dt(r),{pointIndex:n,observation:r}),n++;return{kind:"render-hit-test",layerId:e.id,position:e.position,byKey:t}}function Ls(e,t,n){switch(e.spatialMap.kind){case"points":return Oh(e,n);case"buckets":return Rh(e,Vs(t));case"rects":return Uh(e,Vs(t));case"arcs":return Fh(e);case"polar-points":return Bh(e);case"noop":return Nh(e);case"render-hit-test":return Wh(e);default:{const r=e.spatialMap.kind;throw new Error(`buildLayerIndex: unhandled spatial-map kind ${String(r)}`)}}}function Vs(e){if(e.type!=="cartesian")throw new Error("buildLayerIndex: a bucket or rect hit-test requires a cartesian coord system");return e.mainAxis}const Q=Math.PI*2,Hh=1e-9;function Kh(e,t,n){if(e.arcs.length===0)return null;const{angle:r,radius:s}=Xh(t,n);for(const o of e.arcs)if(!(s<o.innerRadius||s>o.outerRadius)&&qh(r,o))return{hit:{layerId:e.layerId,pointIndex:o.pointIndex,x:(o.startAngle+o.endAngle)/2,y:(o.innerRadius+o.outerRadius)/2,observation:o.observation},index:e};return null}function Xh(e,t){const n=e.x-.5,r=e.y-.5,s=t>=1?n*2*t:n*2,o=t>=1?r*2:r*2/t,a=Math.hypot(s,o);return{angle:(Math.atan2(s,o)%Q+Q)%Q,radius:a}}function qh(e,t){const n=t.endAngle-t.startAngle;if(Math.abs(n)>=Q-Hh)return!0;const r=(n%Q+Q)%Q;return((e-t.startAngle)%Q+Q)%Q<=r}function jh(e,t,n){if(e.points.length===0)return null;const r=t.x-.5,s=t.y-.5,o=n>=1?r*2*n:r*2,a=n>=1?s*2:s*2/n;let i=e.points[0];if(!i)return null;let c=Number.POSITIVE_INFINITY;for(const l of e.points){const u=l.radius*Math.sin(l.angle),d=l.radius*Math.cos(l.angle),p=Math.hypot(u-o,d-a);p<c&&(c=p,i=l)}return{hit:{layerId:e.layerId,pointIndex:i.pointIndex,x:i.angle,y:i.radius,observation:i.observation},index:e,distance:c}}function Qh(e,t,n){const r=n.get(e.layerId);if(!r)return null;const s=r({x:t.x,y:1-t.y});if(!s)return null;const o=e.byKey.get(s.key);return o?{hit:{layerId:e.layerId,pointIndex:o.pointIndex,x:t.x,y:t.y,observation:o.observation},index:e}:null}function Zh(e,t,n){if(e.buckets.length===0)return null;const{main:r,cross:s}=cf(e.mainAxis,t),o=ya(e,r),a=o?.entries??[];if(!o||!Mn(a))return null;const i=ny(a,s,e.mainAxis);return{hit:{layerId:e.layerId,pointIndex:i.pointIndex,x:i.x,y:i.y,observation:i.observation},index:e,bucket:o,distance:ar(i.x-t.x,i.y-t.y,n)}}function Jh(e,t,n){if(e.columns.length===0)return null;const r=Qe(e.mainAxis,t),s=wh(e,r),o=s?.rects??[];if(!s||!Mn(o))return null;const a=H(e.position)?ey(o,t,e.mainAxis):ty(o,t,n);return{hit:{layerId:e.layerId,pointIndex:a.pointIndex,x:(a.xMin+a.xMax)/2,y:(a.yMin+a.yMax)/2,observation:a.observation},index:e,column:s,distance:ba(a,t,n)}}function ey(e,t,n){const r=Ot(n,t);return cr(e,o=>ry(o,n,r),{shortCircuitOnZero:!0})}function ty(e,t,n){return cr(e,s=>ba(s,t,n))}function ny(e,t,n){return cr(e,s=>Math.abs(Ot(n,s)-t))}function cr(e,t,{shortCircuitOnZero:n=!1}={}){let r=e[0],s=t(r);if(n&&s===0)return r;for(let o=1;o<e.length;o+=1){const a=e[o];if(a===void 0)continue;const i=t(a);if(n&&i===0)return a;i<s&&(r=a,s=i)}return r}function ba(e,t,n){const r=Tn(t.x,e.xMin,e.xMax),s=Tn(t.y,e.yMin,e.yMax);return ar(r,s,n)}function ry(e,t,n){const r=t==="x"?e.yMin:e.xMin,s=t==="x"?e.yMax:e.xMax;return Tn(n,r,s)}function Tn(e,t,n){return e<t?t-e:e>n?e-n:0}const sy=new Map,oy=.05;function ay({layers:e,cursor:t,aspectRatio:n,warmStarts:r,hitTesters:s=sy}){const o={match:null,distance:Number.POSITIVE_INFINITY},a={match:null,distance:Number.POSITIVE_INFINITY};let i=null;for(const c of e){if(c.kind==="arcs"){const u=Kh(c,t,n);return u?{kind:"arcs",match:u}:null}if(c.kind==="polar-points"){const u=jh(c,t,n);return u?{kind:"polar-points",match:u}:null}if(c.kind==="render-hit-test"){const u=Qh(c,t,s);u&&(i={kind:"render-hit-test",match:u});continue}const l=cy({layer:c,cursor:t,aspectRatio:n,warmStarts:r});if(l){if(l.kind==="rects"){l.match.distance<o.distance&&(o.match=l,o.distance=l.match.distance);continue}l.match.distance<a.distance&&(a.match=l,a.distance=l.match.distance)}}return i||iy({rect:o,continuous:a})}function iy({rect:e,continuous:t}){return e.match&&t.match?t.distance<=e.distance+oy?t.match:e.match:e.match??t.match}function cy({layer:e,cursor:t,aspectRatio:n,warmStarts:r}){switch(e.kind){case"buckets":{const s=Zh(e,t,n);return s?{kind:"buckets",match:s}:null}case"rects":{const s=Jh(e,t,n);return s?{kind:"rects",match:s}:null}case"points":{const s=r.get(e.layerId)??null,o=Ah(e,t,n,s);return o?{kind:"points",match:o}:null}case"noop":return null}}const he={primary:null,group:[],related:new Map},ly=1;class uy{constructor({layers:t,coordSystem:n}){this.layerIndexes=[],this.layerRefs=[],this.aspectRatio=ly,this.warmStarts=new Map,this.cachedState=he,this.cachedKey=null,this.nonInteractiveLayerIds=new Set,this.hitTesters=new Map,this.layerIndexes=t.map(r=>Ls(r,n,this.aspectRatio)),this.layerRefs=t.map(r=>ks(r,n)),this.nonInteractiveLayerIds=Es(t)}update({layers:t,coordSystem:n}){const r=new Map;for(let a=0;a<this.layerIndexes.length;a+=1){const i=this.layerIndexes[a],c=this.layerRefs[a];!i||!c||r.set(i.layerId,{index:i,ref:c})}const s=[],o=[];for(const a of t){const i=r.get(a.id),c=ks(a,n);if(i!==void 0&&dy(i.ref,c)){s.push(i.index),o.push(i.ref);continue}this.warmStarts.delete(a.id),s.push(Ls(a,n,this.aspectRatio)),o.push(c)}for(const a of this.warmStarts.keys())t.some(i=>i.id===a)||this.warmStarts.delete(a);this.layerIndexes=s,this.layerRefs=o,this.nonInteractiveLayerIds=Es(t),this.invalidateCache()}setViewport(t){this.aspectRatio=t.width/t.height;for(const n of this.layerIndexes)n.kind==="points"&&ga(n,this.aspectRatio)}setHitTesters(t){this.hitTesters=t}hoverByKey(t,n){const r=this.layerIndexes.find(l=>l.layerId===t);if(!r||r.kind!=="render-hit-test")return he;const s=r.byKey.get(n);if(!s)return he;const o={layerId:t,pointIndex:s.pointIndex,x:0,y:0,observation:s.observation},a={kind:"render-hit-test",match:{hit:o,index:r}},{group:i,related:c}=Ts(a,this.layerIndexes);return{primary:o,group:i,related:c}}query(t){if(this.layerIndexes.length===0)return he;const n=this.nonInteractiveLayerIds.size===0?this.layerIndexes:this.layerIndexes.filter(c=>!this.nonInteractiveLayerIds.has(c.layerId)),r=ay({layers:n,aspectRatio:this.aspectRatio,warmStarts:this.warmStarts,hitTesters:this.hitTesters,cursor:t});if(!r)return this.invalidateCache(),he;const s=r.match.hit;this.warmStarts.set(s.layerId,s.pointIndex);const o=`${s.layerId}:${s.pointIndex}`;if(this.cachedKey===o)return this.cachedState;const{group:a,related:i}=Ts(r,n);return this.cachedKey=o,this.cachedState={primary:s,group:a,related:i},this.cachedState}invalidateCache(){this.cachedKey=null,this.cachedState=he}}function ks(e,t){return{data:e.data,geom:e.geom,position:e.position,coord:t}}function Es(e){const t=new Set;for(const n of e)n.interactive||t.add(n.id);return t}function dy(e,t){return e.data===t.data&&e.geom===t.geom&&e.position===t.position&&e.coord===t.coord}const py=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"long",year:"numeric",weekday:"long",...$,...t}).format(n)),my=({locale:e,intlOptions:t})=>O(n=>{const r=n.getUTCSeconds()!==0;return Intl.DateTimeFormat(e,{day:"2-digit",month:"short",year:"numeric",weekday:"short",hour:"2-digit",minute:"2-digit",second:r?"2-digit":void 0,...$,...t}).format(n)}),Mt=e=>{const{valueFormat:t}=e;switch(t.type){case"currency":return Ko(e);case"date":return py(e);case"datetime":return my(e);case"day_month":return jo(e);case"decimal":return Hn(e);case"duration":return Kn();case"integer":return Xo(e);case"month":return Qo(e);case"month_year":return jn(e);case"percentage":return qo(e);case"quarter":return Qn();case"text":return Wn();case"time":return ea(e);case"weekly_date_range":return Zo(e);case"weekly_date_range_with_year":return Jo(e);case"year":return Zn(e);case"lookup":return Mt({...e,valueFormat:t.fallback});default:{const n=t;throw new Error(`Unhandled value format: ${n.type}`)}}},fy={type:"decimal"},hy=({layers:e,coordSystem:t,scales:n,guides:r,numberFormat:s,parsingLocale:o,hover:a,formattingLocale:i})=>{const{primary:c}=a;if(c===null)return null;const l=i??o;return{header:yy({layers:e,coordSystem:t,guides:r,primary:c,locale:l,numberFormat:s}),rows:gy({layers:e,coordSystem:t,scales:n,guides:r,hover:a,locale:l,numberFormat:s})}};function yy(e){if(e.coordSystem.type!=="cartesian")return null;const t=$t(e.guides,"x");if(!t)return null;const n=e.layers.find(a=>a.id===e.primary.layerId);if(!n)return null;const r=n.semanticMap.encodings.find(a=>a.aesthetic==="x");if(!r)return null;const s=e.primary.observation[r.variable];return h(s)?Mt({valueFormat:t.valueFormat,locale:e.locale,numberFormat:e.numberFormat})(s):null}function gy(e){const t=[],n=e.scales.color??null,r=xy({guides:e.guides,locale:e.locale,numberFormat:e.numberFormat});for(const s of e.layers){const o=vy(s,e.hover);if(o.length===0)continue;if(s.semanticMap.detailRows.length>0){const{primary:m}=e.hover;m!==null&&m.layerId===s.id&&t.push(...by({layer:s,observation:m.observation,coordSystem:e.coordSystem,locale:e.locale,numberFormat:e.numberFormat}));continue}const a=wo(s.data,s.mapping),i=Sy(o,s,n,a),c=Pl(s.semanticMap),l=D({valueFormat:Ay(s),locale:e.locale,numberFormat:e.numberFormat}),u=wy(e.guides,s),d=s.mapping.color!==void 0,p=je(s.swatchShape,e.coordSystem);for(const m of i){const f=d?a(m.observation):null,y=Vn(m.observation)??null,b=Ns(m.observation),x=d&&f!==null?r(f):u,S=Ty(c,m),w=S===null?"":l(S,m.observation);t.push({swatchColor:y,swatchShape:p,swatchLineType:b,label:x,value:w,isPrimary:m===e.hover.primary,key:`${m.layerId}:${m.pointIndex}`})}}return t}function by(e){const t=je(e.layer.swatchShape,e.coordSystem);return e.layer.semanticMap.detailRows.map((n,r)=>{const s=D({valueFormat:n.valueFormat,locale:e.locale,numberFormat:e.numberFormat}),o=e.observation[n.variable]??null;return{swatchColor:null,swatchShape:t,swatchLineType:"solid",label:n.label,value:o===null?"":s(o,e.observation),isPrimary:!1,key:`${e.layer.id}:detail:${r}`}})}function vy(e,t){const n=[];return t.primary!==null&&t.primary.layerId===e.id&&n.push(t.primary,...t.group),n.push(...t.related.get(e.id)??[]),n}function Sy(e,t,n,r){if(n===null||t.mapping.color===void 0)return e;const s=new Map;return n.domain.forEach((o,a)=>{s.set(E(o),a)}),e.map((o,a)=>{const i=r(o.observation),c=i===null?null:E(i),l=c===null?Number.POSITIVE_INFINITY:s.get(c)??Number.POSITIVE_INFINITY;return{hit:o,originalIndex:a,rank:l}}).sort((o,a)=>o.rank===a.rank?o.originalIndex-a.originalIndex:o.rank-a.rank).map(o=>o.hit)}function xy({guides:e,locale:t,numberFormat:n}){const r=new Map(e.colorGroups.map(o=>[E(o.value),{label:o.label,format:Mt({valueFormat:o.valueFormat,locale:t,numberFormat:n})}])),s=Mt({valueFormat:{type:"text"},locale:t,numberFormat:n});return o=>{const a=r.get(E(o));return a===void 0?s(o):a.label??a.format(o)}}function wy(e,t){const n=tt(t.yScaleType);return $t(e,n)?.label??""}function Ay(e){return e.semanticMap.encodings.find(n=>n.aesthetic==="y")?.valueFormat??fy}function Ty(e,t){return e(t.observation).encodings.find(r=>r.aesthetic==="y")?.value??null}const va={differenceArrow(e){return{type:"annotation",kind:"differenceArrow",annotation:e}},shape(e){return{type:"annotation",kind:"shape",annotation:e}},freeformArrow(e){return{type:"annotation",kind:"freeformArrow",annotation:e}},text(e){return{type:"annotation",kind:"text",annotation:e}},sticker(e){return{type:"annotation",kind:"sticker",annotation:e}},pinnedNumber(e){return{type:"annotation",kind:"pinnedNumber",annotation:e}},comment(e){return{type:"annotation",kind:"comment",annotation:e}}},My={lilac:"linear-gradient(94deg, #C9C0F7 -2.94%, #F6E6FD 92.51%)",neon_pink:"linear-gradient(93deg, #E04A95 2.61%, #FD7F92 97.51%)",blackberry:"linear-gradient(132deg, #9F9FED 2.98%, #B9E6FF 97.65%)",sun:"linear-gradient(139deg, #FCDB61 5.51%, #FB9C65 97.21%)",iceland:"linear-gradient(94deg, #29CDA8 -2.94%, #52C9D2 92.51%)",sunset:"linear-gradient(138deg, #FCDB62 5.77%, #FD8091 99.91%)",ultraviolet:"linear-gradient(132deg, #D167D8 2.98%, #6584E6 97.65%)",purple:"linear-gradient(203.63deg, #BBADFD 15.22%, #BE9AF0 81.52%)",ice_cream:"linear-gradient(119.34deg, #FC7E91 3.68%, #FCD1B1 116.76%)",mint:"linear-gradient(93.55deg, #25CDA5 -6.07%, #58C8D8 113.6%)",cool:"linear-gradient(93.55deg, #3F8EEB -6.07%, #58C8D8 113.6%)",fresh:"linear-gradient(114.37deg, #A4A4EE 4.32%, #58C8D8 87.71%)"};function Sa(...e){let t={},n;const[r,...s]=e;h(r)&&!Vy(r)?(t=r,n=s):n=e;const o={mapping:t,layers:[],scales:[],transforms:[],highlights:[],config:{}};return n.reduce((a,i)=>xa(a,i),o)}function Ly(e,...t){return t.reduce((n,r)=>xa(n,r),e)}function Vy(e){return typeof e=="object"&&e!==null&&"type"in e}function xa(e,t){switch(t.type){case"scale":return{...e,scales:[...e.scales,t]};case"coord":return{...e,coords:t};case"config":return{...e,config:Is({},e.config,t.config)};case"layer":return{...e,layers:[...e.layers,t]};case"transform":return{...e,transforms:[...e.transforms,t]};case"mapping":return{...e,mapping:{...e.mapping,...t.mapping}};case"highlight":return{...e,highlights:[...e.highlights,t]};case"annotation":return ky(e,t);default:{const n=t;throw new Error(`Unknown spec item type: ${n.type}`)}}}function ky(e,t){const n={...e.annotations};switch(t.kind){case"differenceArrow":n.differenceArrows=[...n.differenceArrows??[],t.annotation];break;case"shape":n.shapes=[...n.shapes??[],t.annotation];break;case"freeformArrow":n.freeformArrows=[...n.freeformArrows??[],t.annotation];break;case"text":n.textAnnotations=[...n.textAnnotations??[],t.annotation];break;case"sticker":n.stickers=[...n.stickers??[],t.annotation];break;case"pinnedNumber":n.pinnedNumbers=[...n.pinnedNumbers??[],t.annotation];break;case"comment":n.comments=[...n.comments??[],t.annotation];break;case"custom":n.custom=[...n.custom??[],t.annotation];break;default:{const r=t;throw new Error(`Unknown annotation kind: ${r.kind}`)}}return{...e,annotations:n}}function Ey(e){const t={};for(const r of e.geoms??[]){const s=r;t[s.type]=(o={})=>({type:"layer",geom:s.type,mapping:o.aes,stat:o.stat,params:{...s.defaultParams,...o.params},position:o.position,yScaleType:o.yScaleType,transforms:o.transforms,interactive:o.interactive,dataLabels:o.dataLabels})}const n={};for(const r of e.annotations??[]){const s=r;n[s.type]=o=>(Iy(s,o.coordinates),{type:"annotation",kind:"custom",annotation:{id:o.id,type:s.type,coordinates:o.coordinates,params:{...s.defaultParams,...o.params},zOrder:o.zOrder}})}return{geom:{...C,...t},annotation:{...va,...n},createSpec:Sa}}function Iy(e,t){const n=e.coordinates;if(n!==void 0){if(n.min!==void 0&&t.length<n.min)throw new Error(`Annotation '${e.type}' requires at least ${n.min} coordinate(s), got ${t.length}.`);if(n.max!==void 0&&t.length>n.max)throw new Error(`Annotation '${e.type}' accepts at most ${n.max} coordinate(s), got ${t.length}.`)}}function Cy(e,t={}){return{type:"highlight",id:t.id,predicate:e,scope:t.scope,layerIndex:t.layerIndex}}function Fy(e){return{mapping:e.mapping,layers:e.layers,scales:e.scales.map(_y),transforms:e.transforms,highlights:e.highlights.map(t=>Dy(t,e.layers)),coords:e.coords,config:e.config}}function Dy(e,t){const n=e.layerId?t.findIndex(r=>r.id===e.layerId):-1;return{type:"highlight",id:e.id,predicate:e.predicate,scope:e.scope,layerIndex:n>=0?n:void 0}}function _y(e){return e.scaleType==="palette"?Ry(e):e}function Ry(e){return{...e,palette:Py(e.palette)}}function Py(e){return e.type==="custom"?{type:"custom",id:e.id}:e}function M(e){return{id:e.id??crypto.randomUUID(),timestamp:e.timestamp??Date.now(),description:e.description,author:e.author??"unknown"}}class lr{constructor(t,n={}){this.type="set-axis-label",this.params=t,this.metadata=M({...n,description:`Set ${t.axis} axis label to ${t.label??"(none)"}`})}apply(t){const{axis:n,label:r}=this.params,s=t.config.axes[n].label??null,o=N(t,{config:{axes:{[n]:{label:r}}}}),a=new lr({axis:n,label:s},this.metadata);return{spec:o,revert:a}}}const Ny={type:"set-axis-label",deserialize:(e,t)=>new lr(e,t)};class ur{constructor(t,n={}){this.type="set-axis-label-mode",this.params=t,this.metadata=M({...n,description:`Set ${t.axis} axis label mode to ${t.labelMode}`})}apply(t){const{axis:n,labelMode:r}=this.params,s=t.config.axes[n].ticks.mode,o=N(t,{config:{axes:{[n]:{ticks:{mode:r}}}}}),a=new ur({axis:n,labelMode:s},this.metadata);return{spec:o,revert:a}}}const Oy={type:"set-axis-label-mode",deserialize:(e,t)=>new ur(e,t)};class Bt{constructor(t,n={}){this.type="set-axis-position",this.params=t,this.metadata=M({...n,description:`Set ${t.axis} axis position to ${t.position}`})}apply(t){const{axis:n,position:r}=this.params,s=N(t,{config:{axes:{[n]:{position:r}}}}),o=n==="x"?{axis:"x",position:t.config.axes.x.position}:{axis:"y",position:t.config.axes.y.position},a=new Bt(o,this.metadata);return{spec:s,revert:a}}}const $y={type:"set-axis-position",deserialize:(e,t)=>new Bt(e,t)};class dr{constructor(t,n={}){this.type="set-axis-ticks-visibility",this.params=t,this.metadata=M({...n,description:`Set ${t.axis} axis ticks visibility to ${t.isVisible}`})}apply(t){const{axis:n,isVisible:r}=this.params,s=t.config.axes[n].ticks.isVisible,o=N(t,{config:{axes:{[n]:{ticks:{isVisible:r}}}}}),a=new dr({axis:n,isVisible:s},this.metadata);return{spec:o,revert:a}}}const By={type:"set-axis-ticks-visibility",deserialize:(e,t)=>new dr(e,t)};class pr{constructor(t,n={}){this.type="set-axis-visibility",this.params=t,this.metadata=M({...n,description:`Set ${t.axis} axis visibility to ${t.isVisible}`})}apply(t){const{axis:n,isVisible:r}=this.params,s=t.config.axes[n].isVisible,o=N(t,{config:{axes:{[n]:{isVisible:r}}}}),a=new pr({axis:n,isVisible:s},this.metadata);return{spec:o,revert:a}}}const Gy={type:"set-axis-visibility",deserialize:(e,t)=>new pr(e,t)};class Gt{constructor(t,n={}){this.type="set-content-caption",this.params=t,this.metadata=M({...n,description:"Set chart caption"})}apply(t){const n=t.config.content.caption;if(n===this.params.caption)return null;const r=N(t,{config:{content:{caption:this.params.caption}}}),s=new Gt({caption:n},this.metadata);return{spec:r,revert:s}}}const zy={type:"set-content-caption",deserialize:(e,t)=>new Gt(e,t)};class zt{constructor(t,n={}){this.type="set-content-subtitle",this.params=t,this.metadata=M({...n,description:"Set chart subtitle"})}apply(t){const n=t.config.content.subtitle;if(n===this.params.subtitle)return null;const r=N(t,{config:{content:{subtitle:this.params.subtitle}}}),s=new zt({subtitle:n},this.metadata);return{spec:r,revert:s}}}const Uy={type:"set-content-subtitle",deserialize:(e,t)=>new zt(e,t)};class Ut{constructor(t,n={}){this.type="set-content-title",this.params=t,this.metadata=M({...n,description:"Set chart title"})}apply(t){const n=t.config.content.title;if(n===this.params.title)return null;const r=N(t,{config:{content:{title:this.params.title}}}),s=new Ut({title:n},this.metadata);return{spec:r,revert:s}}}const Yy={type:"set-content-title",deserialize:(e,t)=>new Ut(e,t)};class mr{constructor(t,n={}){this.type="set-grid-visibility",this.params=t,this.metadata=M({...n,description:`Set grid visibility to x=${t.xIsVisible}, y=${t.yIsVisible}`})}apply(t){const n=t.config.axes.x.grid.isVisible,r=t.config.axes.y.grid.isVisible,s=N(t,{config:{axes:{x:{grid:{isVisible:this.params.xIsVisible}},y:{grid:{isVisible:this.params.yIsVisible}}}}}),o=new mr({xIsVisible:n,yIsVisible:r},this.metadata);return{spec:s,revert:o}}}const Wy={type:"set-grid-visibility",deserialize:(e,t)=>new mr(e,t)};class fr{constructor(t,n={}){this.type="set-headline-compare-with",this.params=t,this.metadata=M({...n,description:`Set headline compare with to ${t.compareWith}`})}apply(t){const n=t.config.headline.compareWith,r=N(t,{config:{headline:{compareWith:this.params.compareWith}}}),s=new fr({compareWith:n},this.metadata);return{spec:r,revert:s}}}const Hy={type:"set-headline-compare-with",deserialize:(e,t)=>new fr(e,t)};class hr{constructor(t,n={}){this.type="set-headline-position",this.params=t,this.metadata=M({...n,description:`Set headline position to ${t.position}`})}apply(t){const n=t.config.headline.position,r=N(t,{config:{headline:{position:this.params.position}}}),s=new hr({position:n},this.metadata);return{spec:r,revert:s}}}const Ky={type:"set-headline-position",deserialize:(e,t)=>new hr(e,t)};class Yt{constructor(t,n={}){this.type="set-headline-show",this.params=t,this.metadata=M({...n,description:`Set headline show to ${t.show}`})}apply(t){const n=t.config.headline.show,r=N(t,{config:{headline:{show:this.params.show}}}),s=new Yt({show:n},this.metadata);return{spec:r,revert:s}}}const Xy={type:"set-headline-show",deserialize:(e,t)=>new Yt(e,t)};class yr{constructor(t,n={}){this.type="set-headline-size",this.params=t,this.metadata=M({...n,description:`Set headline size to ${t.size}`})}apply(t){const n=t.config.headline.size,r=N(t,{config:{headline:{size:this.params.size}}}),s=new yr({size:n},this.metadata);return{spec:r,revert:s}}}const qy={type:"set-headline-size",deserialize:(e,t)=>new yr(e,t)};class gr{constructor(t,n={}){this.type="set-legend-position",this.params=t,this.metadata=M({...n,description:`Set legend position to ${t.position}`})}apply(t){const n=t.config.legend.position,r=N(t,{config:{legend:{position:this.params.position}}}),s=new gr({position:n},this.metadata);return{spec:r,revert:s}}}const jy={type:"set-legend-position",deserialize:(e,t)=>new gr(e,t)};class br{constructor(t,n={}){this.type="set-number-format-abbreviation",this.params=t,this.metadata=M({...n,description:`Set number format abbreviation to ${t.abbreviation}`})}apply(t){const n=t.config.numberFormat.abbreviation,r=N(t,{config:{numberFormat:{abbreviation:this.params.abbreviation}}}),s=new br({abbreviation:n},this.metadata);return{spec:r,revert:s}}}const Qy={type:"set-number-format-abbreviation",deserialize:(e,t)=>new br(e,t)};class vr{constructor(t,n={}){this.type="set-number-format-decimals",this.params=t,this.metadata=M({...n,description:`Set number format decimals to ${t.decimals}`})}apply(t){const n=t.config.numberFormat.decimals,r=N(t,{config:{numberFormat:{decimals:this.params.decimals}}}),s=new vr({decimals:n},this.metadata);return{spec:r,revert:s}}}const Zy={type:"set-number-format-decimals",deserialize:(e,t)=>new vr(e,t)};class Sr{constructor(t,n={}){this.type="set-line-interpolation",this.params=t,this.metadata=M({...n,description:`Set line interpolation to ${t.interpolate}`})}apply(t){const n=this.params.layerId?Pt(t.layers,this.params.layerId):st(t.layers,"line","area");if(!Rt(n,"line","area"))return null;const r=n.params.interpolate,s=Un(t,n.id,{...n,params:{...n.params,interpolate:this.params.interpolate}}),o=new Sr({layerId:n.id,interpolate:r},this.metadata);return{spec:s,revert:o}}}const Jy={type:"set-line-interpolation",deserialize:(e,t)=>new Sr(e,t)};class Wt{constructor(t,n={}){this.type="set-line-width",this.params=t,this.metadata=M({...n,description:`Set line width to ${t.lineWidth}`})}apply(t){const n=this.params.layerId?Pt(t.layers,this.params.layerId):st(t.layers,"line","area");if(!Rt(n,"line","area"))return null;const r=n.params.lineWidth,s=Un(t,n.id,{...n,params:{...n.params,lineWidth:this.params.lineWidth}}),o=new Wt({layerId:n.id,lineWidth:r},this.metadata);return{spec:s,revert:o}}}const eg={type:"set-line-width",deserialize:(e,t)=>new Wt(e,t)};class xr{constructor(t,n={}){this.type="set-point-size",this.params=t,this.metadata=M({...n,description:`Set point size to ${t.size}`})}apply(t){const n=this.params.layerId?Pt(t.layers,this.params.layerId):st(t.layers,"point");if(!Rt(n,"point"))return null;const r=n.params.size,s=Un(t,n.id,{...n,params:{...n.params,size:this.params.size}}),o=new xr({layerId:n.id,size:r},this.metadata);return{spec:s,revert:o}}}const tg={type:"set-point-size",deserialize:(e,t)=>new xr(e,t)};class Lt{constructor(t,n={}){this.type="toggle-line-points",this.params=t,this.metadata=M({...n,description:`${t.showPoints?"Show":"Hide"} line points`})}apply(t){const n=this.params.layerId?Pt(t.layers,this.params.layerId):st(t.layers,"line");return Rt(n,"line")?this.params.showPoints?this.addPointLayer(t,n):this.removePointLayer(t,n):null}addPointLayer(t,n){if(this.findAssociatedPointLayer(t,n))return null;const r=this.params.removedLayer??Oo(t.mapping,t.coords.coordType,C.point({aes:{...n.mapping},interactive:!1})),s={...t,layers:[...t.layers,r]},o=new Lt({layerId:n.id,showPoints:!1},this.metadata);return{spec:s,revert:o}}removePointLayer(t,n){const r=this.findAssociatedPointLayer(t,n);if(!r)return null;const s=yp(t,r.id),o=new Lt({layerId:n.id,showPoints:!0,removedLayer:r},this.metadata);return{spec:s,revert:o}}findAssociatedPointLayer(t,n){return t.layers.find(r=>r.geom==="point"&&Ea(r.mapping,n.mapping))}}const ng={type:"toggle-line-points",deserialize:(e,t)=>new Lt(e,t)};function Ht(e,t){return e.scales.find(n=>n.scaledAesthetic===t)}function Kt(e,t,n){const r=e.scales.map(s=>s.scaledAesthetic===t?n:s);return{...e,scales:r}}function Xt(e){const t=e.replace(/([A-Z])/g," $1").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}class qt{constructor(t,n={}){this.type="set-scale-domain",this.params=t,this.metadata=M({...n,description:`Set ${Xt(t.scaledAesthetic)} scale domain`})}apply(t){const n=Ht(t,this.params.scaledAesthetic);if(!n||n.scaleType!=="continuous"&&n.scaleType!=="datetime")return null;const r={min:n.domainMin??null,max:n.domainMax??null},s={...n,...this.params.domainMin!==void 0&&{domainMin:this.params.domainMin},...this.params.domainMax!==void 0&&{domainMax:this.params.domainMax}},o=Kt(t,this.params.scaledAesthetic,s),a={scaledAesthetic:this.params.scaledAesthetic};this.params.domainMin!==void 0&&(a.domainMin=r.min),this.params.domainMax!==void 0&&(a.domainMax=r.max);const i=new qt(a,this.metadata);return{spec:o,revert:i}}}const rg={type:"set-scale-domain",deserialize:(e,t)=>new qt(e,t)};class wr{constructor(t,n={}){this.type="set-scale-palette",this.params=t,this.metadata=M({...n,description:`Set ${Xt(t.scaledAesthetic)} palette`})}apply(t){const n=Ht(t,this.params.scaledAesthetic);if(n?.scaleType!=="palette")return null;const r=Kt(t,this.params.scaledAesthetic,{...n,scaledAesthetic:this.params.scaledAesthetic,palette:this.params.palette}),s=new wr({scaledAesthetic:this.params.scaledAesthetic,palette:n.palette},this.metadata);return{spec:r,revert:s}}}const sg={type:"set-scale-palette",deserialize:(e,t)=>new wr(e,t)};class Ar{constructor(t,n={}){this.type="set-scale-reverse",this.params=t,this.metadata=M({...n,description:`Set ${Xt(t.scaledAesthetic)} scale reverse to ${t.reverse}`})}apply(t){const n=Ht(t,this.params.scaledAesthetic);if(!n||n.scaleType!=="continuous")return null;const r=n.reverse,s=Kt(t,this.params.scaledAesthetic,{...n,reverse:this.params.reverse}),o=new Ar({scaledAesthetic:this.params.scaledAesthetic,reverse:r},this.metadata);return{spec:s,revert:o}}}const og={type:"set-scale-reverse",deserialize:(e,t)=>new Ar(e,t)};class Tr{constructor(t,n={}){this.type="set-scale-transform",this.params=t,this.metadata=M({...n,description:`Set ${Xt(t.scaledAesthetic)} scale transform to ${t.transform}`})}apply(t){const n=Ht(t,this.params.scaledAesthetic);if(!n||n.scaleType!=="continuous")return null;const r=n.transform,s=Kt(t,this.params.scaledAesthetic,{...n,transform:this.params.transform}),o=new Tr({scaledAesthetic:this.params.scaledAesthetic,transform:r},this.metadata);return{spec:s,revert:o}}}const ag={type:"set-scale-transform",deserialize:(e,t)=>new Tr(e,t)};class wa{constructor(){this.descriptors=new Map}register(t){if(this.descriptors.has(t.type))throw new Error(`CommandRegistry: descriptor for type '${t.type}' is already registered`);this.descriptors.set(t.type,t)}serialize(t){return{type:t.type,params:t.params,metadata:t.metadata}}deserialize(t){return this.getDescriptor(t.type).deserialize(t.params,t.metadata)}getRegisteredTypes(){return[...this.descriptors.keys()]}getDescriptor(t){const n=this.descriptors.get(t);if(!n)throw new Error(`CommandRegistry: no descriptor registered for type '${t}'`);return n}}const L=new wa;L.register(Jy);L.register(eg);L.register(tg);L.register(ng);L.register(rg);L.register(sg);L.register(og);L.register(ag);L.register(Ny);L.register(Oy);L.register($y);L.register(By);L.register(Gy);L.register(zy);L.register(Uy);L.register(Yy);L.register(Wy);L.register(Hy);L.register(Ky);L.register(Xy);L.register(qy);L.register(jy);L.register(Qy);L.register(Zy);class ig{constructor(t={}){this.undoStack=[],this.redoStack=[],this.listeners=new Set,this.isEmitting=!1,this.cachedSnapshot=null,this.maxHistorySize=t.maxHistorySize??100}apply(t,n){return this.withReentrancyGuard(()=>{const r=t.apply(n);return r?(this.undoStack.push({command:t,revert:r.revert}),this.redoStack=[],this.undoStack.length>this.maxHistorySize&&this.undoStack.shift(),this.emit({type:"apply",command:t,spec:r.spec}),r.spec):n})}undo(t){return this.withReentrancyGuard(()=>{const n=this.undoStack.pop();if(!n)return null;const r=n.revert.apply(t);return r?(this.redoStack.push({command:n.command,revert:r.revert}),this.emit({type:"undo",command:n.command,spec:r.spec}),{spec:r.spec,command:n.command}):(this.undoStack.push(n),null)})}redo(t){return this.withReentrancyGuard(()=>{const n=this.redoStack.pop();if(!n)return null;const r=n.revert.apply(t);return r?(this.undoStack.push({command:n.command,revert:r.revert}),this.emit({type:"redo",command:n.command,spec:r.spec}),{spec:r.spec,command:n.command}):(this.redoStack.push(n),null)})}clear(){this.withReentrancyGuard(()=>{this.undoStack=[],this.redoStack=[],this.emit({type:"clear"})})}getSnapshot(){return this.cachedSnapshot||(this.cachedSnapshot={canUndo:this.undoStack.length>0,canRedo:this.redoStack.length>0,undoDescription:this.undoStack[this.undoStack.length-1]?.command.metadata.description??null,redoDescription:this.redoStack[this.redoStack.length-1]?.command.metadata.description??null}),this.cachedSnapshot}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}withReentrancyGuard(t){if(this.isEmitting)throw new Error("CommandStack: cannot call apply/undo/redo/clear from within a listener");this.isEmitting=!0;try{return t()}finally{this.isEmitting=!1}}emit(t){this.cachedSnapshot=null;for(const n of this.listeners)try{n(t)}catch(r){console.error("CommandStack listener error:",r)}}}const Mr=500,Lr="normal",Aa={thin:100,hairline:100,extraLight:200,ultraLight:200,light:300,normal:400,regular:400,medium:500,semiBold:600,demiBold:600,bold:700,extraBold:800,ultraBold:800,black:900,heavy:900,extraBlack:950,ultraBlack:950},cg=e=>{const t=e.style??Lr,n=e.weight??Mr,r=e.family.includes(",")?e.family:`'${e.family}'`;return`${t} ${n} ${e.size}px ${r}`},lg=e=>typeof e=="string"?e:Ta(e),Ta=e=>e.text!==void 0?e.text:e.content?e.content.map(Ta).join(""):"",Ma=e=>typeof e!="string"?e??Mr:Aa[e],ug="\0";class dg{constructor(t){this.inner=t,this.cache=new Map}measureText(t,n){const r=this.getCacheKey(t,n),s=this.cache.get(r);if(s)return s;const o=this.inner.measureText(t,n);return this.cache.set(r,o),o}getCacheKey(t,n){return[n.family,n.size,Ma(n.weight),n.style??Lr,t].join(ug)}}const pg={" ":.25,"!":.27,'"':.36,"#":.6,$:.56,"%":.78,"&":.66,"'":.21,"(":.31,")":.31,"*":.44,"+":.56,",":.22,"-":.36,".":.22,"/":.35,0:.56,1:.56,2:.56,3:.56,4:.56,5:.56,6:.56,7:.56,8:.56,9:.56,":":.22,";":.22,"<":.56,"=":.56,">":.56,"?":.46,"@":.88,A:.63,B:.63,C:.65,D:.69,E:.56,F:.53,G:.7,H:.7,I:.26,J:.44,K:.62,L:.53,M:.84,N:.7,O:.73,P:.6,Q:.73,R:.62,S:.56,T:.56,U:.69,V:.6,W:.88,X:.58,Y:.56,Z:.58,"[":.29,"\\":.35,"]":.29,"^":.56,_:.44,"`":.33,a:.53,b:.58,c:.48,d:.58,e:.54,f:.31,g:.56,h:.57,i:.23,j:.23,k:.52,l:.23,m:.87,n:.57,o:.57,p:.58,q:.58,r:.35,s:.45,t:.34,u:.57,v:.49,w:.74,x:.49,y:.49,z:.46,"{":.33,"|":.26,"}":.33,"~":.56},mg=.55,fg=1.05,hg=.84,yg=.21;class gg{measureText(t,n){let r=0;for(const i of t)r+=(pg[i]??mg)*n.size;Ma(n.weight)>=Aa.semiBold&&(r*=fg);const o=hg*n.size,a=yg*n.size;return{width:r,height:o+a,ascent:o,descent:a}}}function bg(e,t,n){const r=e[t];return typeof r=="number"?r:n??null}function vg(e,t,n){const r=e[t];return typeof r=="string"?r:n??null}class Sg{constructor(){this.columnTypes=new Map,this.kindColumns=new Map,this.rows=[]}kind(t,n){if(this.kindColumns.has(t))throw new Error(`createMarkTable: kind "${t}" is already declared.`);for(const[r,s]of Object.entries(n)){const o=this.columnTypes.get(r);if(o!==void 0&&o!==s)throw new Error(`createMarkTable: column "${r}" is declared as both "${o}" and "${s}".`);this.columnTypes.set(r,s)}return this.kindColumns.set(t,Object.keys(n)),this}push(t,n){const r=this.kindColumns.get(t);if(!r)throw new Error(`createMarkTable: cannot push to undeclared kind "${t}".`);for(const s of r)if(!(s in n))throw new Error(`createMarkTable: row for kind "${t}" is missing column "${s}".`);for(const s of Object.keys(n))if(!r.includes(s))throw new Error(`createMarkTable: column "${s}" is not declared for kind "${t}".`);return this.rows.push({kind:t,values:n}),this}toDataset(t){const{kindColumn:n}=t;if(this.columnTypes.has(n))throw new Error(`createMarkTable: kindColumn "${n}" collides with a declared column.`);const r={[n]:{type:"categorical",values:this.rows.map(s=>s.kind)}};for(const[s,o]of this.columnTypes)r[s]={type:o,values:this.rows.map(a=>{const i=a.values[s];return i===void 0?null:i})};return new V(r)}}function xg(){return new Sg}function wg(e){return{type:e.type,defaultParams:e.defaultParams??{},coordinates:e.coordinates}}function Ag(e,t,n,r,s){const o=n-t;return o===0?r:r+(e-t)/o*(s-r)}exports.BORDER_PRESETS=Fo;exports.BORDER_PRESET_GRADIENTS=My;exports.BUILTIN_GEOM_NAMES=bo;exports.COMPILER_STAGE_KEYS=Zp;exports.CachedTextMeasurer=dg;exports.CommandRegistry=wa;exports.CommandStackManager=ig;exports.Compiler=Wo;exports.DEFAULT_COLOR_PALETTE=On;exports.DEFAULT_FONT_STYLE=Lr;exports.DEFAULT_FONT_WEIGHT=Mr;exports.DEFAULT_LOCALE=Et;exports.Dataset=V;exports.GEOM_NAMES=go;exports.GROUP_VARIABLES=P;exports.Geom=De;exports.HeuristicTextMeasurer=gg;exports.HoverEngine=uy;exports.LAYOUT_PADDING=oa;exports.LayoutCompiler=tf;exports.MONO_BASES=ko;exports.NEON_BASES=Eo;exports.POSITION_VARIABLES=g;exports.RESTING_HOVER_STATE=he;exports.SetAxisPositionCommand=Bt;exports.SetContentCaptionCommand=Gt;exports.SetContentSubtitleCommand=zt;exports.SetContentTitleCommand=Ut;exports.SetHeadlineShowCommand=Yt;exports.SetLineWidthCommand=Wt;exports.SetScaleDomainCommand=qt;exports.SpecResolver=Go;exports.VISUAL_VARIABLES=ue;exports.annotation=va;exports.buildAverageLineSymbols=of;exports.buildDataLabelsContent=Yf;exports.buildFontString=cg;exports.buildLayerYValueFormatter=fa;exports.buildTooltipContent=hy;exports.commandRegistry=L;exports.computeDifferenceArrow=Qf;exports.computeDirectLabelsLayout=Jf;exports.computeFreeformArrow=vh;exports.config=Do;exports.convertSpecToInput=Fy;exports.coord=B;exports.createAlphaValueReader=Ll;exports.createColorValueReader=wo;exports.createCommandMetadata=M;exports.createCompiler=Jp;exports.createEmptyHighlight=Ao;exports.createGraphyBuilder=Ey;exports.createGroupValueReader=Vl;exports.createLabelValueReader=Tl;exports.createMarkTable=xg;exports.createRawValueReader=K;exports.createSegmentYReader=Pn;exports.createSizeValueReader=Ml;exports.createSpec=Sa;exports.createStrokeWidthValueReader=kl;exports.createValueFormatter=D;exports.createXValueReader=Rn;exports.createYValueReader=xo;exports.defineAnnotation=wg;exports.extractConstantValue=re;exports.extractPlainText=lg;exports.extractVariableName=v;exports.findAxisGuide=$t;exports.findLegendForAesthetic=lh;exports.formatHeadline=eh;exports.formatLegends=ih;exports.formatRuleValue=uh;exports.geom=C;exports.getAlpha=za;exports.getAngleExtent=pa;exports.getColor=Vn;exports.getCrossAxisCoordinate=Ot;exports.getDifferenceArrowDimensions=nr;exports.getGroup=Ie;exports.getIdentityKey=Dt;exports.getLineType=Ns;exports.getMainAxisCoordinate=Qe;exports.getRadiusExtent=ma;exports.getSize=Ps;exports.getStrokeWidth=Ua;exports.getX=_e;exports.getXMax=ke;exports.getXMin=qe;exports.getY=se;exports.getYMax=Z;exports.getYMin=Se;exports.getYRaw=co;exports.highlight=Cy;exports.interpolateInScaledInterval=Ag;exports.isBuiltinGeomName=vo;exports.isCartesian=lf;exports.isCompilerCachingEnabled=Ca;exports.isDefined=h;exports.isGraphConfig=Io;exports.isLayerOf=em;exports.isStackedPosition=H;exports.mapping=_a;exports.pipe=Ly;exports.prefixInternalVariable=A;exports.readAesthetic=Ln;exports.readNumber=bg;exports.readString=vg;exports.resolveHeadlinePlacement=Zm;exports.resolveSegmentYSource=nt;exports.resolveYScaleAesthetic=tt;exports.scale=be;exports.setCompilerCachingEnabled=Ia;exports.sortByXIfContinuous=It;exports.stat=$n;exports.transform=ge;exports.variableFor=U;
|