@graphysdk/viz-engine 0.0.1-experimental.2 → 0.0.1-experimental.3
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 +3 -3
- package/dist/index.d.ts +12 -4
- package/dist/index.mjs +783 -748
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("date-fns"),ie=require("arquero"),ue=require("lodash-es"),$e=require("d3-time"),Ao=require("date-fns/differenceInDays"),ce=require("d3-scale"),Es=require("lodash-es/merge"),ye=require("d3-regression"),To=require("humanize-duration");require("@graphysdk/i18n");const _e=require("d3-shape"),Mo=require("d3-delaunay"),Lo=require("lodash-es/isEqual");typeof window<"u"&&(window.__GRAPHY_SDK__??={},window.__GRAPHY_SDK__.vizEngine="0.0.1-experimental.2");const In=e=>e.length>0;function h(e){return e!=null}function Nr(e){if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function R(e,t){return Is(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 Is(e,t){let n=!1;const r={...e};for(const[s,a]of Object.entries(t)){const o=e[s];if(Nr(a)&&Nr(o)){const i=Is(o,a);i!==o&&(r[s]=i,n=!0)}else a!==void 0&&a!==o&&(r[s]=a,n=!0)}return n?r:e}const ve=process.env.NODE_ENV!=="production";function It(e){return{pipe:t=>{const n=t(e);return It({...e,...n})},result:()=>e}}let kt=!0;const Vo=e=>{kt=e},Eo=()=>kt,Io=()=>{let e=null;const t={hits:0,misses:0};return Object.assign((r,s)=>{if(!kt)return ve&&(t.misses+=1),s();if(e&&Cs(e.args,r))return ve&&(t.hits+=1),e.out;ve&&(t.misses+=1);const a=s();return e={args:r,out:a},a},{stats:t,reset:()=>{e=null}})},ks=()=>{const e=new WeakMap,t={hits:0,misses:0};return Object.assign((r,s,a)=>{if(!kt)return ve&&(t.misses+=1),a();const o=e.get(r);if(o){for(const c of o)if(Cs(c.args,s))return ve&&(t.hits+=1),c.out}ve&&(t.misses+=1);const i=a();return o?o.push({args:s,out:i}):e.set(r,[{args:s,out:i}]),i},{stats:t})},ko=(...e)=>e.reduce((t,n)=>({hits:t.hits+n.hits,misses:t.misses+n.misses}),{hits:0,misses:0}),Cs=(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 de{constructor(){this.memo=ks(),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}}const G=e=>e instanceof Date&&V.isValid(e),Co=e=>G(e)||e===null,Ze=e=>typeof e=="string",D=e=>typeof e=="number"&&!Number.isNaN(e)&&Number.isFinite(e);function Do(e){return{type:"mapping",mapping:e}}function v(e){return h(e)?typeof e=="string"?e:"variable"in e?e.variable:null:null}function le(e){if(!(!h(e)||typeof e=="string")&&"value"in e)return e.value}const Ds="\0graphy\0_",A=e=>`${Ds}${e}`,Sn={x:A("constantX")},je={count:A("count"),mean:A("mean")},z={group:A("group")},f={x:A("x"),y:A("y"),xMin:A("xMin"),xMax:A("xMax"),yMin:A("yMin"),yMax:A("yMax"),yRaw:A("yRaw")},pe={color:A("color"),size:A("size"),alpha:A("alpha"),strokeWidth:A("strokeWidth"),lineType:A("lineType")},ct={y:A("ruleY"),x:A("ruleX")};({...z,...f,...pe});const _o=new Set(Object.values(je)),Fo=e=>e.startsWith(Ds),Ro=e=>_o.has(e),Le=e=>e[z.group];function $(e){return e[f.x]}function C(e){return e[f.y]}function me(e){return e[f.xMin]}function ae(e){return e[f.xMax]}function te(e){return e[f.yMin]}function H(e){return e[f.yMax]}function _s(e){return e[f.yRaw]}function Ct(e){return e[pe.color]}function No(e){return e[pe.alpha]}function Fs(e){return e[pe.size]}function Rs(e){return e[pe.strokeWidth]}function Ns(e){return e[pe.lineType]??"solid"}const wn=(e,t,n)=>{for(const r of t){if(r.geom!=="bar"&&r.geom!=="line"||e.layerId!==void 0&&r.id!==e.layerId)continue;const s=v(r.mapping.x);if(s===null)continue;const a=v(r.mapping.y);for(const o of r.data){if(o[s]!==e.anchorValue||Le(o)!==e.groupValue)continue;const i=Po(o,r.geom,n);if(i===null)continue;const c=a!==null?o[a]??null:null;if(D(c))return{...i,measurementValue:c,color:Ct(o)}}}return null},Po=(e,t,n)=>{if(n.type==="polar")return t!=="bar"?null:Bo(e);const r=Oo(e,t,n.mainAxis);return r===null?null:{...r,geom:t}},Oo=(e,t,n)=>{if(t==="line"){const o=$(e),i=C(e);return o===null||i===null?null:{x:o,y:i}}if(n==="x"){const o=me(e),i=ae(e),c=H(e)??C(e);return o===null||i===null||c===null?null:{x:(o+i)/2,y:c}}const r=te(e),s=H(e),a=ae(e)??$(e);return r===null||s===null||a===null?null:{x:a,y:(r+s)/2}},Bo=e=>{const t=me(e),n=ae(e),r=te(e),s=H(e);if(t===null||n===null||r===null||s===null)return null;const a=(t+n)/2,o=(r+s)/2,i=.5+.5*o*Math.sin(a),c=.5-.5*o*Math.cos(a);return{x:i,y:c,geom:"polar-bar"}};class $o extends de{dependencies(t){return[t.annotations,t.layers,t.coordSystem]}run(t){return{differenceArrows:Go(t),shapes:t.annotations.shapes,freeformArrows:t.annotations.freeformArrows,textAnnotations:t.annotations.textAnnotations,stickers:en(t.annotations.stickers,t.layers,t.coordSystem),pinnedNumbers:en(t.annotations.pinnedNumbers,t.layers,t.coordSystem),comments:en(t.annotations.comments,t.layers,t.coordSystem)}}}const en=(e,t,n)=>{const r=[];for(const s of e){const a=wn(s.anchor,t,n);a!==null&&r.push({...s,anchor:a})}return r},Go=({annotations:e,layers:t,coordSystem:n})=>{if(n.type!=="cartesian")return[];const r=[];for(const s of e.differenceArrows){if(zo(s.start,s.end))continue;const a=wn(s.start,t,n),o=wn(s.end,t,n);a===null||o===null||r.push({id:s.id,start:a,end:o,color:Wo(s,a,o),size:s.size,label:s.label,labelCrossPosition:s.labelCrossPosition})}return r},zo=(e,t)=>e.layerId===t.layerId&&e.anchorValue===t.anchorValue&&e.groupValue===t.groupValue,Wo=(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 Yo(e,t){const n=Ko(t);return{...e,background:Ho(e.background,n),border:Uo(e.border,n)}}function Ho(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 Uo(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 Ko(e){const t=e.color,n=t?.domain[0];if(!n)return;const r=t.map(n);if(typeof r=="string")return r}class Xo extends de{dependencies(t){return[t.scales,t.config]}run(t){const{scales:n,config:r}=t;return{...r,appearance:Yo(r.appearance,n)}}}class jo extends de{dependencies(t){return[t.data,t.mapping]}run(t){let n=t.data,r=t.mapping;r.x===""&&(n=n.addConstantVariable(Sn.x,"categorical",""),r={...r,x:Sn.x});for(const s of Object.keys(r)){const a=le(r[s]);if(a===void 0)continue;const o=A(`const_${s}`);n=n.addConstantVariable(o,qo(a),a),r={...r,[s]:o}}return{data:n,mapping:r}}}const qo=e=>typeof e=="number"?"numeric":e instanceof Date?"temporal":"categorical";class Re{constructor(){this.perLayerMemo=ks(),this.listMemo=Io()}get stats(){return ko(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 Qo extends de{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 Zo extends Re{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 Jo{constructor(t){this.setupStage=new Qo(t),this.transformStage=new Zo(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 Ne{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 ei{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}}class ti{constructor(){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:ri(t.scales,t.layers)}}transform(t){return t.layers.map(n=>ai(n))}}const ni=[[f.x,f.y],[f.xMin,f.yMin],[f.xMax,f.yMax]],Pr=A("flipSwap"),ri=(e,t)=>si(t)?e.map(n=>n.scaledAesthetic!=="x"||n.scaleType!=="continuous"&&n.scaleType!=="datetime"&&n.scaleType!=="discrete"?n:{...n,reverse:!n.reverse}):e,si=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},ai=e=>{let t=e.data;for(const[n,r]of ni){const s=t.hasVariable(n),a=t.hasVariable(r);s&&a?t=t.renameVariable(n,Pr).renameVariable(r,n).renameVariable(Pr,r):s?t=t.renameVariable(n,r):a&&(t=t.renameVariable(r,n))}return{...e,data:t}};class oi{constructor(){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},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=ci(n),s=li(n);return t.layers.map(a=>{const o=n.theta==="y"?di(a):a;return ui(o,r,s)})}}const ii=[[f.x,f.y],[f.xMin,f.yMin],[f.xMax,f.yMax]];function ci(e){const t=e.startAngle*(Math.PI/180);return n=>n*2*Math.PI+t}function li(e){const{innerRadius:t}=e;return n=>t+n*(1-t)}function ui(e,t,n){let r=e.data;return r=Ve(r,f.x,t),r=Ve(r,f.xMin,t),r=Ve(r,f.xMax,t),r=Ve(r,f.y,n),r=Ve(r,f.yMin,n),r=Ve(r,f.yMax,n),{...e,data:r}}function Ve(e,t,n){if(!e.hasVariable(t))return e;const s=e.getValues(t,{type:"numeric"}).map(a=>a===null?null:n(a));return e.addVariable(t,"numeric",s)}function di(e){let t=e.data;for(const[n,r]of ii){const s=t.hasVariable(n),a=t.hasVariable(r);if(!s&&!a)continue;const o=s?t.getValues(n):null,i=a?t.getValues(r):null;o&&(t=t.addVariable(r,"numeric",o)),i&&(t=t.addVariable(n,"numeric",i))}return{...e,data:t}}class pi extends Ne{constructor(){super("coord"),this.register("cartesian",new ei),this.register("flip",new ti),this.register("polar",new oi)}}const mi=new Set(["count","sum","mean","median"]);function Ps(e,t){return mi.has(e)?"numeric":t}const E=e=>(Array.isArray(e)?e:[e]).map(n=>n instanceof Date?n.toISOString():String(n??"<null>")).join("\0"),fi="key",hi="value",Or="\0__rowMaskIndex",Ke={numeric:{type:"decimal"},categorical:{type:"text"},temporal:{type:"datetime"}},yi={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},Os=(e,t)=>e==="count"?{type:"integer"}:t;class I{constructor(t={}){const{table:n,variableMetadata:r}=this.parseVariableMap(t);this.table=n,this.variableMetadata=r}static fromTrusted(t,n){const r=Object.create(I.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 a={...this.variableMetadata,[t]:{type:n,valueFormat:this.resolveAddedVariableFormat(t,n,s)}},o=this.normalizeRawValues(n,r),i=this.table.assign(ie.table({[t]:o}));return I.fromTrusted(i,a)}addConstantVariable(t,n,r,s){const a={...this.variableMetadata,[t]:{type:n,valueFormat:this.resolveAddedVariableFormat(t,n,s)}},[o]=this.normalizeRawValues(n,[r]),i=this.table.assign(ie.table({[t]:Array(this.size()).fill(o)}));return I.fromTrusted(i,a)}deriveVariable(t,n,r,s){const a=Array.from({length:this.size()},(o,i)=>r(this.table.object(i)));return this.addVariable(t,n,a,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]:a,...o}=this.variableMetadata,i={...o,[n]:r};return I.fromTrusted(s,i)}selectVariables(...t){const n=this.table.select(...t),r=Object.fromEntries(Object.entries(this.variableMetadata).filter(([s])=>t.includes(s)));return I.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=yi[n],a=this.table.params({__variableName:t,__value:r}).filter(s);return I.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},(s,a)=>a),r=this.table.assign(ie.table({[Or]:n})).params({__indexColumnName:Or,__mask:t}).filter((s,a)=>a.__mask[s[a.__indexColumnName]]===1).select(...this.table.columnNames());return I.fromTrusted(r,this.variableMetadata)}orderBy(t,n="asc"){const r=this.table.orderby(n==="asc"?t:ie.desc(t));return I.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 gi(t,n,this.variableMetadata)}rollup(t){const n=this.table.rollup(Object.fromEntries(Object.entries(t).map(([s,a])=>[s,ie.op[a.aggregation](a.variableName)]))),r={};for(const[s,{variableName:a,aggregation:o}]of Object.entries(t)){const i=this.variableMetadata[a],c=i?.type??"numeric",l=i?.valueFormat??Ke[c],u=Ps(o,c);r[s]={type:u,valueFormat:Os(o,l)}}return I.fromTrusted(n,r)}reshapeFromWideToLong({keep:t,reshape:n,keyName:r=fi,valueName:s=hi}={}){const{numeric:a,categorical:o,temporal:i}=this.groupVariableNamesByType(),c=t??[...o,...i],l=n??a.filter(y=>!c.includes(y));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 y={};for(const g of c){const b=this.variableMetadata[g];b&&(y[g]={type:b.type,values:[],valueFormat:b.valueFormat})}return y[r]={type:"categorical",values:[],valueFormat:{type:"text"}},y[s]={type:"numeric",values:[],valueFormat:{type:"decimal"}},new I(y)}if(l.filter(y=>this.variableMetadata[y]?.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 y of c){const g=this.variableMetadata[y];g&&(m[y]=g)}return m[r]={type:"categorical",valueFormat:{type:"text"}},m[s]={type:"numeric",valueFormat:bi(this.variableMetadata,l,r)},I.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:Ke[n]}parseVariableMap(t){const n={},r={};for(const[a,{type:o,values:i,valueFormat:c}]of Object.entries(t))n[a]=i,r[a]={type:o,valueFormat:c??Ke[o]};return{table:ie.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)||!V.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,a=[];for(const o of n){const i=r&&o instanceof Date?o.getTime():o;s.has(i)||(s.add(i),a.push(o))}return a}}class gi{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(o=>this.grouped.column(o)).filter(o=>o!==void 0);let a=0;for(const o of n){const i=o[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,o.map(m=>p?.get(m))]})),u=ie.table(l);t(I.fromTrusted(u,this.variableMetadata),c,a++)}}rollup(t){const n=this.grouped.rollup(Object.fromEntries(Object.entries(t).map(([s,a])=>[s,ie.op[a.aggregation](a.variableName)]))),r=Object.fromEntries(this.groupedBy.map(s=>{const a=this.variableMetadata[s],o=a?.type??"categorical",i=a?.valueFormat??Ke[o];return[s,{type:o,valueFormat:i}]}));for(const[s,{variableName:a,aggregation:o}]of Object.entries(t)){const i=this.variableMetadata[a],c=i?.type??"numeric",l=i?.valueFormat??Ke[c],u=Ps(o,c);r[s]={type:u,valueFormat:Os(o,l)}}return I.fromTrusted(n,r)}getStableKey(t,n){return E(t.map(r=>r.get(n)))}}function bi(e,t,n){const r=t.map(c=>e[c]?.valueFormat??{type:"decimal"}),[s,...a]=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(a.every(c=>ue.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 Bs{constructor(){this.currentYear=new Date().getUTCFullYear(),this.previousDate=null,this.previousYear=null}incrementYearIfNeeded(t){this.previousYear===null?this.previousYear=t.getUTCFullYear():this.previousDate!==null&&V.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 $s=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==="-",Dt="en-GB",Gs=e=>e.type==="lookup",zs=e=>e.type==="text",Pe=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",kn=e=>e.type==="decimal"||e.type==="integer"||e.type==="percentage"||e.type==="duration"||e.type==="currency",Cn=e=>e.type==="currency",Dn=e=>e.type==="month"||e.type==="day_month"||e.type==="weekly_date_range",Ws=e=>{if(Gs(e))return Ws(e.fallback);if(Pe(e))return"temporal";if(kn(e))return"numeric";if(zs(e))return"categorical";const t=e;throw new Error(`No data type found for value format: ${t.type}`)},Xe={k:1e3,m:1e6,b:1e9,t:1e12},_n=["k","m","b","t"],vi=new RegExp(`^-?(\\d{1,3}(,\\d{3})*|\\d+)\\.?\\d*(${_n.join("|")})?$`,"i"),xi=/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?%?$/,Ae=e=>e===null||e instanceof Date||Array.isArray(e)||typeof e=="boolean"?!1:typeof e=="string"?vi.test(e)&&!Number.isNaN(Number(e.replace(new RegExp(`[,${_n.join("")}]`,"gi"),""))):!Number.isNaN(Number(e)),Ys=e=>Ae(e)?!0:typeof e=="string"?xi.test(e):!1,Si=/^\d{4}-\d{2}-\d{2}(T|\s)\d{1,2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|\+00:00)?$/,wi=/^\s*(19\d{2}|2[01]\d{2})\s*$/,Ai=[[/\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"]],Ti={"en-US":"MDY","en-GB":"DMY","pt-PT":"DMY",ar:"DMY"},Hs=["/","-","."," "],Br=[["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"]],$r=[["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"]],Gr=[["yyyy","M","d"],["yyyy","M","dd"],["yyyy","MM","d"],["yyyy","MM","dd"],["yyyy","MMMM","d"],["yyyy","MMMM","dd"],["yyyy","MMMM","do"]],Us=[["d","MMMM"],["dd","MMMM"],["do","MMMM"],["MMMM","d"],["MMMM","dd"],["MMMM","do"]],Mi=[{dateFormat:"MMMM d, yyyy",type:"date"},{dateFormat:"MMMM dd, yyyy",type:"date"},{dateFormat:"MMMM do, yyyy",type:"date"},{dateFormat:"yyyy-MM",type:"month_year"}],Ks=1900,Xs=2199,Li=3,Vi=6,Ei=5,Ii=1,ki=28,Ci=/\s*[–—]\s*|\s-\s/,Di=e=>typeof e=="number"?Number.isNaN(e)?!1:e>=Ks&&e<=Xs:typeof e=="string"?wi.test(e):!1,js=(e,t)=>{const n=qe(e);return Ae(n)?Ri(n):typeof n=="string"?!!qs(n)||Fn(n)&&V.isValid(new Date(n)):V.isValid(n)},qe=e=>{if(typeof e!="string")return e;let t=e;for(const[n,r]of Ai)t=t.replace(n,r);return t},qs=(e,t=Dt)=>{const n=qe(e);return Fn(n)?{type:"datetime"}:Qs(t).find(r=>!Pe(r)||r.type==="month"&&n.length<Li?!1:r.dateFormat&&V.isValid(V.parse(n,r.dateFormat,new Date)))},Fn=e=>Si.test(e.trim()),_i=(e,t=Dt)=>{const[n,r]=e.split(Ci);if(!n||!r)return;const s=qe(n).trim(),a=qe(r).trim();return Fi(t).find(o=>{if(!Pe(o)||!o.dateFormat)return!1;const i=V.parse(s,o.dateFormat,new Date),c=V.parse(a,o.dateFormat,new Date);if(!V.isValid(i)||!V.isValid(c))return!1;const l=new Bs,u=l.incrementYearIfNeeded(i),d=l.incrementYearIfNeeded(c),p=V.differenceInDays(d,u);return V.isWithinInterval(new Date(u.getFullYear(),Ii,ki),{start:u,end:d})&&p===Ei?!0:p===Vi})},Qs=e=>{const t={date:Zs(e),year:[["yyyy"]],day_month:Us,month_year:[["MMMM","yyyy"],["yyyy","MMMM"]],month:[["MMMM"]],quarter:[["QQQ","yyyy"],["yyyy","QQQ"]]};return[...Mi,...Object.entries(t).flatMap(([n,r])=>r.flatMap(s=>Hs.map(a=>({dateFormat:s.join(a),type:n}))))]},Zs=e=>Ti[e]==="MDY"?[...$r,...Br,...Gr]:[...Br,...$r,...Gr],Fi=e=>{const t={weekly_date_range:Us,weekly_date_range_with_year:Zs(e)};return Object.entries(t).flatMap(([n,r])=>r.flatMap(s=>Hs.map(a=>({dateFormat:s.join(a),type:n}))))},Ri=e=>{const t=Number(e);if(!ue.isInteger(t))return!1;const n=new Date(t),r=new Date(t*1e3),s=a=>V.isValid(a)&&a.getFullYear()>=Ks&&a.getFullYear()<=Xs;return s(n)||s(r)},Js={$:"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"},ea=e=>{if(typeof e=="string"){const t=ta(e);return t.length?Ae(t):!1}return Ae(e)},Ni=e=>{const t=na(e),n=t?Js[t]:void 0;if(!n)throw new Error("Could not get currency ISO");return n},ta=e=>{const t=na(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 Ae(n)?n.split(",").join(""):""},na=e=>Object.keys(Js).sort((n,r)=>r.length-n.length).find(n=>e.includes(n)),Pi=(e,t)=>{const n=typeof e=="string"?e.trim():e;if(Ae(n))return{type:"decimal"};const r=typeof n=="string"&&qs(n,t);if(r)return r;const s=typeof n=="string"&&_i(n,t);return s||(js(e)?{type:"date"}:Ys(e)?{type:"percentage"}:ea(e)&&typeof e=="string"?{type:"currency",iso:Ni(e)}:{type:"text"})},Oi=/\s*[–—]\s*|\s-\s/,Bi=(e,t,n)=>{if(Je(e))return null;switch(t.type){case"decimal":case"integer":case"duration":return ra(e);case"percentage":return $i(e);case"currency":return Gi(e);case"datetime":case"date":case"year":case"month_year":case"month":case"day_month":case"quarter":case"time":return Rn(e,t.dateFormat,n);case"weekly_date_range":case"weekly_date_range_with_year":return zi(e,t.dateFormat,n);case"text":return Wi(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}`)}}},Rn=(e,t,n)=>{if(e instanceof Date)return V.isValid(e)?e:null;const r=qe(String(e).trim());if(r.length===0)return null;const s=new Date;if(t){const o=V.parse(r,t,s);return V.isValid(o)?tn(o):null}for(const o of Qs(n)){if(!Pe(o)||!o.dateFormat)continue;const i=V.parse(r,o.dateFormat,s);if(V.isValid(i))return tn(i)}const a=new Date(r);return js(a)?Fn(r)?a:tn(a):null},ra=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;let t=e.trim();if(!Ae(t))return null;let n=1;for(const r of _n)if(new RegExp(`${r}$`,"i").test(t)){n=Xe[r],t=t.slice(0,-1);break}return Number(t.split(",").join(""))*n},$i=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;const t=e.trim();if(!Ys(t))return null;const n=Number(t.replace(/%/g,"").replace(/,/g,""))/100;return Number.isNaN(n)?null:n},Gi=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;const t=e.trim();return ea(t)?ra(ta(t)):null},zi=(e,t,n)=>{const r=String(e).trim().split(Oi),[s,a]=[r[0]?.trim(),r[1]?.trim()];return!s||!a?null:Rn(s,t,n)},Wi=e=>String(e).trim(),tn=e=>new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())),Yi={type:"year",dateFormat:"yyyy"};class Hi extends de{dependencies(t){return[t]}run(t){const n=t._metadata?.parsingLocale??Dt,r={},s=Xi(t),a=Ui(t);for(const[o,i]of t.columns.entries()){if(i._metadata?.isHidden)continue;const c=s.get(i.key);if(Je(c))continue;const l=o===a?Yi:Pi(c,n),u=Ws(l);r[i.key]=Ki(i.key,t.rows,l,u,n)}return new I(r)}}const Ui=e=>{const t=ji(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(Di)})},Ki=(e,t,n,r,s)=>{const a=new Bs,o=t.reduce((i,c)=>{if($s(c))return i;const l=Bi(c[e],n,s);return Dn(n)&&G(l)?i.push(a.incrementYearIfNeeded(l)):i.push(l),i},[]);return{type:r,values:o,valueFormat:n}},Xi=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 a=r[s];Je(a)||(t.set(s,a),n.delete(s))}if(n.size===0)break}return t},ji=(e,t)=>{const n=[];for(const r of e)if($s(r)||n.push(r),n.length===t)return n;return n};class qi{constructor(t){this.registry=t}compile(t,n){return this.registry.get(t).compile(n)}}class et{constructor(){this.requiredAesthetics=[]}}const Nn=(e,t)=>{const n=v(t.x);return!n||!["numeric","temporal"].includes(e.getType(n))?e:e.orderBy(n,"asc")};class Qi extends et{constructor(){super(...arguments),this.type="area",this.requiredAesthetics=["x","y"]}compile({data:t,mapping:n}){if(t=Nn(t,n),t.hasVariable(f.yMin)||(t=t.addConstantVariable(f.yMin,"numeric",0)),!t.hasVariable(f.yMax)){const r=v(n.y);h(r)&&t.hasVariable(r)&&(t=t.addVariable(f.yMax,"numeric",t.getValues(r,{type:"numeric"})))}return{data:t,mapping:{}}}}const sa=.7,Zi=.1;class Ji extends et{constructor(){super(...arguments),this.type="bar"}compile({data:t,mapping:n}){if(t=Nn(t,n),t.hasVariable(f.yMin)||(t=t.addConstantVariable(f.yMin,"numeric",0)),!t.hasVariable(f.yMax)){const s=v(n.y);h(s)&&t.hasVariable(s)&&(t=t.addVariable(f.yMax,"numeric",t.getValues(s,{type:"numeric"})))}const r=sa/2;return t=t.addConstantVariable(f.xMin,"numeric",-r).addConstantVariable(f.xMax,"numeric",r),{data:t,mapping:{}}}}class ec extends et{constructor(){super(...arguments),this.type="line",this.requiredAesthetics=["x","y"]}compile(t){return{data:Nn(t.data,t.mapping),mapping:{}}}}class tc extends et{constructor(){super(...arguments),this.type="point",this.requiredAesthetics=["x","y"]}compile({data:t}){return{data:t,mapping:{}}}}class nc extends et{constructor(){super(...arguments),this.type="rule"}compile({data:t,mapping:n}){const r=zr(n.y,t);if(r!==null)return{data:new I({[ct.y]:{type:"numeric",values:[r.value],valueFormat:r.sourceFormat}}),mapping:{y:ct.y,x:void 0}};const s=zr(n.x,t);return s!==null?{data:new I({[ct.x]:{type:"numeric",values:[s.value],valueFormat:s.sourceFormat}}),mapping:{x:ct.x,y:void 0}}:{data:new I,mapping:{x:void 0,y:void 0}}}}const zr=(e,t)=>{const n=le(e);if(D(n))return{value:n,sourceFormat:void 0};const r=v(e);if(r===null||!Ro(r)||!t.hasVariable(r))return null;const[s]=t.getValues(r);return D(s)?{value:s,sourceFormat:t.getValueFormat(r)}:null};class rc extends Ne{constructor(){super("geom"),this.register("bar",new Ji),this.register("point",new tc),this.register("line",new ec),this.register("area",new Qi),this.register("rule",new nc)}}const Pn=(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 a=v(t[s]);h(a)&&(n.has(a)||e.getType(a)==="categorical"&&r.add(a))}return[...r]};class sc{compute({data:t,mapping:n}){const r=Pn(t,n);if(r.length===0)return{data:t.addConstantVariable(z.group,"categorical",null)};const s=t.size(),a=r.map(i=>t.getValues(i)),o=new Array(s);for(let i=0;i<s;i++)o[i]=E(a.map(c=>c[i]));return{data:t.addVariable(z.group,"categorical",o)}}}const aa=new Set(["x","y","ySecondary"]),On=new Set(["color","size","alpha","strokeWidth","lineType"]),_t=e=>aa.has(e),ac=e=>On.has(e),oc=e=>_t(e)||ac(e);function Oe(e){return e==="secondary"?"ySecondary":"y"}function ee(e){return e==="ySecondary"?"y":e}const ic=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},cc=(e,t,n)=>{const r=Te(t,"color");return r===null?{}:(e?.columns??[]).some(o=>o.key===r)?{}:n};function Te(e,t){const n=ee(t);for(const r of oa(t,e)){const s=v(r.mapping[n]);if(h(s))return s}return null}const Bn=(e,t)=>e===null?null:t[e]??e,lc=(e,t)=>e===null?null:t[String(e)]??null,Me=({layers:e,scaleType:t,variableName:n})=>{if(n===null)return nn(t);for(const r of e){if(!r.data.hasVariable(n))continue;const s=r.data.getValueFormat(n),a=s.type==="lookup"?s.fallback:s;return dc(a,t)?a:nn(t)}return nn(t)},uc=(e,t)=>t!=="y"&&t!=="ySecondary"?!1:oa(t,e).some(n=>n.position==="fill");function oa(e,t){return e==="ySecondary"?t.filter(n=>n.yScaleType==="secondary"):e==="y"?t.filter(n=>n.yScaleType==="primary"):t}const nn=e=>{switch(e){case"continuous":return{type:"decimal"};case"datetime":return{type:"date"};case"discrete":case"palette":case"identity":return{type:"text"}}},dc=(e,t)=>{switch(t){case"continuous":return kn(e);case"datetime":return Pe(e);case"discrete":case"palette":case"identity":return!0}},pc=[{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}],Wr={year:0,quarter:1,month:2,week:3,day:4,hour:5},Ee=40,mc=(e,t,n)=>{const r=n.unit==="quarter"?n.step*3:n.step;return gc(n.unit).range(e,new Date(t.valueOf()+1),r)},fc=({unit:e,step:t,start:n,stop:r})=>{const s=Ao.differenceInDays(r,n);switch(e){case"hour":return 24*s/t>Ee;case"day":return s/t>Ee;case"week":return s/(7*t)>Ee;case"month":return s/(30*t)>Ee;case"quarter":return s/(90*t)>Ee;case"year":return s/(365*t)>Ee}},hc=(e,t)=>{const n=!Dn(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"}}},yc=(e,t)=>{const n=bc(t);return n===null?!1:Wr[e]>Wr[n]},gc=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}},bc=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}},ia={left:"right",right:"left",top:"bottom",bottom:"top"},vc={x:!0,y:!0,ySecondary:!1},xc={bar:{cartesian:{hideGridX:!0},flip:{hideGridX:!0},polar:{hideGridX:!0,hideGridY:!0}}},Sc=20,Yr=new Set(["top","bottom"]),wc={type:"percentage"};function Ac(e,t){const{scales:n,config:r,layers:s,coordSystem:a,variableLabels:o}=e;if(a.type==="polar")return[];const i=Mc(s,a.type,r),c=new Set(t.map(d=>d.position)),l=Vc(ca(r.axes.y.position,a.axisMapping.y.position),c),u=[];for(const d of aa){const p=n[d];if(!h(p)||p.kind!=="position")continue;const m=Tc({scaleAestheticKey:d,scale:p,config:r,layers:s,axisMapping:a.axisMapping,resolvedYPosition:l,gridOverrides:i,variableLabels:o});u.push(m)}return u}function Tc(e){const{scaleAestheticKey:t,scale:n,config:r,layers:s,axisMapping:a,resolvedYPosition:o,gridOverrides:i,variableLabels:c}=e,l=ee(t),{axisConfig:u,position:d}=Lc(t,r,a,o),p=Te(s,t),m=uc(s,t)?wc:Me({layers:s,scaleType:n.spec.scaleType,variableName:p}),y=Bn(p,c);return{scaleAestheticKey:t,aesthetic:l,position:d,label:u.label??y,isVisible:u.isVisible,tickCandidates:Ic(n,m),valueFormat:m,tickMode:u.ticks.mode,ticksVisible:u.ticks.isVisible,gridVisible:Ec(u,i,t),scaleType:n.spec.scaleType,bandwidth:n.bandwidth??void 0}}function Mc(e,t,n){const r=e.flatMap(i=>{const c=xc[i.geom]?.[t];return c?[c]:[]}),s=r.some(i=>i.hideGridX),a=r.some(i=>i.hideGridY),o=r.some(i=>i.hideBorder);return{x:{gridVisible:Hr(s,n.axes.x.grid.isVisible)},y:{gridVisible:Hr(a,n.axes.y.grid.isVisible)},borderVisible:o?!1:void 0}}function Hr(e,t){if(e&&t===null)return!1}function Lc(e,t,n,r){switch(e){case"x":return{axisConfig:t.axes[e],position:ca(t.axes[e].position,n[e].position)};case"y":return{axisConfig:t.axes[e],position:r};case"ySecondary":{const s=ia[r],a=ue.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:a,position:a.position}}}}function ca(e,t){return Yr.has(e)===Yr.has(t)?e:t}function Vc(e,t){return t.has(e)?ia[e]:e}function Ec(e,t,n){const{gridVisible:r}=n==="x"?t.x:t.y;return r??e.grid.isVisible??vc[n]}const Ic=(e,t)=>{if(e.spec.scaleType==="continuous"){const r=new Set,s=[];for(let a=1;a<=Sc;a++){const o=e.generateTicks({count:a}),i=E(o);r.has(i)||(r.add(i),s.push({ticks:o.map(c=>At(e,c))}))}return s}return e.spec.scaleType==="datetime"?kc(e,t):[{ticks:e.generateTicks().map(r=>At(e,r))}]},kc=(e,t)=>{const[n,r]=e.domain;if(!G(n)||!G(r))return[{ticks:e.generateTicks().map(c=>At(e,c))}];const s=new Set,a=[],o=(i,c)=>{if(i.length===0)return;const l=E(i);s.has(l)||(s.add(l),a.push({ticks:i.map(u=>At(e,u)),valueFormat:c}))};for(const i of pc)fc({...i,start:n,stop:r})||yc(i.unit,t)||o(e.generateTicks({interval:i}),hc(i,t));return o(e.generateTicks({atInputs:!0})),a.sort((i,c)=>i.ticks.length-c.ticks.length),a},At=(e,t)=>({value:t,position:e.map(t)});function Tt(e,t){switch(e){case"bar":return t.type==="polar"?"slice":"square";case"line":return"line";case"area":return"area";case"point":return"circle";default:return"square"}}function la({scale:e,aesthetics:t,layers:n,coordSystem:r}){const s=Cc({layers:n,coordSystem:r,aesthetics:t}),a=ua({layers:n,aesthetics:t});return e.domain.map(o=>({value:o,swatchShape:s(o),owner:a(o)}))}function Cc({layers:e,coordSystem:t,aesthetics:n}){const r=ua({layers:e,aesthetics:n}),s=e.find(o=>n.some(i=>h(o.mapping[i]))),a=s?Tt(s.geom,t):"square";return o=>{const i=r(o);return i?Tt(i.layer.geom,t):a}}function ua({layers:e,aesthetics:t,layerFilter:n}){const r=new Map;for(const[s,a]of e.entries()){if(n&&!n(a))continue;const o=t.find(c=>h(a.mapping[c]));if(o===void 0)continue;const i=v(a.mapping[o]);if(!(i===null||!a.data.hasVariable(i)))for(const c of a.data.getValues(i,{distinct:!0})){const l=E(c);r.has(l)||r.set(l,{layer:a,layerIndex:s})}}return s=>r.get(E(s))}const $n=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 s=e.color;if(s===void 0||!$n(s))return[];if(!t.some(u=>h(u.mapping.color)))return[];const a=Te(t,"color");if(da({colorVariableName:a,xVariableName:Te(t,"x"),mapsColorAcrossMultipleLayers:Fc(t)>1,isMergedWithAnotherAesthetic:_c(e,t,a)}))return[];const i=s.spec.scaleType,c=t.findIndex(u=>h(u.mapping.color));return la({scale:s,aesthetics:["color"],layers:t,coordSystem:n}).map(({value:u,swatchShape:d,owner:p})=>{const m=p?.layerIndex??c,y=t[m],g=y?v(y.mapping.color):null;return{value:u,color:String(s.map(u)),shape:d,layerIndex:m,valueFormat:Me({layers:y?[y]:t,scaleType:i,variableName:g}),label:lc(u,r)}})}const da=({colorVariableName:e,xVariableName:t,mapsColorAcrossMultipleLayers:n,isMergedWithAnotherAesthetic:r})=>r?!1:e===null||Fo(e)?!n:t!==null&&e===t;function _c(e,t,n){if(n===null)return!1;for(const r of On){if(r==="color")continue;const s=e[r];if(!(s===void 0||!$n(s))&&Te(t,r)===n)return!0}return!1}const Fc=e=>e.filter(t=>h(t.mapping.color)).length,pa=["bar","line","area","point"];function Rc(e,t,n){const r=t.findIndex(s=>pa.includes(s.geom));if(r===-1)return[];if(e.length<2){const s=v(t[r]?.mapping.y);return[{value:null,swatch:null,layerIndex:r,groupLabelFormat:{type:"text"},label:Bn(s,n)}]}return e.map(s=>({value:s.value,swatch:{color:s.color,shape:s.shape},layerIndex:s.layerIndex,groupLabelFormat:s.valueFormat,label:s.label}))}function Ur(e,t,n){if(n===null||t===null)return[...e];const r=E(n);return e.filter((s,a)=>E(t[a]??null)===r)}const Nc=(e,t)=>{switch(t){case"total":{const{sum:n,count:r}=Kr(e);return r===0?null:n}case"average":{const{sum:n,count:r}=Kr(e);return r===0?null:n/r}case"current":return e.at(-1)??null}},Pc=(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}},Kr=e=>e.reduce((t,n)=>n===null?t:{sum:t.sum+n,count:t.count+1},{sum:0,count:0});function Oc(e){const{config:t,coordSystem:n}=e,r=t.headline.show;return r==="none"||r==="conversion"?null:n.type==="polar"?Bc(e,r):$c(e,r)}function Bc(e,t){if(t!=="total")return null;const{scales:n,layers:r}=e,s=r.find(c=>c.geom==="bar");if(s===void 0)return null;const a=s.summary.grandTotal;if(a===void 0)return null;const o=v(s.mapping.y);if(o===null)return null;const i=Me({layers:[s],scaleType:n.y?.spec.scaleType??"continuous",variableName:o});return{kind:"grandTotal",value:a,valueFormat:i}}function $c(e,t){const{config:n,scales:r,layers:s,variableLabels:a,colorGroups:o}=e;if(!s.some(l=>pa.includes(l.geom)))return null;const i=Rc(o,s,a);if(i.length===0)return null;const c=i.map(l=>Gc({group:l,show:t,compareWith:n.headline.compareWith,layers:s,scales:r})).filter(l=>l!==null);return c.length===0?null:{kind:"perGroup",items:c}}function Gc({group:e,show:t,compareWith:n,layers:r,scales:s}){const a=r[e.layerIndex];if(a===void 0)return null;const o=v(a.mapping.y);if(o===null||t==="total"&&a.position==="fill")return null;const i=v(a.mapping.x),c=v(a.mapping.color),l=a.yScaleType==="secondary"?s.ySecondary:s.y,u=Me({layers:[a],scaleType:l?.spec.scaleType??"continuous",variableName:o}),d=Yc(a.data,i),p=Me({layers:[a],scaleType:d?"datetime":s.x?.spec.scaleType??"discrete",variableName:i}),m=Hc(a.data,i),y=m.getValues(o,{type:"numeric"}),g=i!==null?m.getValues(i):[],b=c!==null?m.getValues(c):null,x=Ur(y,b,e.value),S=Ur(g,b,e.value);return{value:e.value,swatch:e.swatch,aggregate:Nc(x,t),valueFormat:u,groupLabelFormat:e.groupLabelFormat,mainValueFormat:p,label:e.label,observationLabel:zc(t,d,S),comparison:Wc(t,n,d,S,x)}}function zc(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),s=n.at(-1);return r===void 0||s===void 0?null:{kind:"range",from:r,to:s}}function Wc(e,t,n,r,s){if(e!=="current"||!n)return null;const a=t==="none"?"first":t,o=r.map((i,c)=>({main:i,cross:s[c]??null}));return Pc(o,a)}function Yc(e,t){return t!==null&&e.hasVariable(t)&&e.getType(t)==="temporal"}function Hc(e,t){return t===null||!["numeric","temporal"].includes(e.getType(t))?e:e.orderBy(t)}function X(e){return e==="stack"||e==="fill"}const Uc=3,Kc={line:{stack:!0,dodge:!0,identity:!0,fill:!0},area:{stack:!0,dodge:!0,identity:!0,fill:!0},bar:{stack:!0,fill:!0}};function Xc({scales:e,config:t,layers:n,coordSystem:r,variableLabels:s,colorGroups:a}){if(t.legend.position==="none")return[];const o=new Map(a.map(g=>[E(g.value),g])),i=Qc({scales:e,layers:n}),c=tl(i),l=Te(n,"x"),u=c.map(g=>{if(Jc(g,l,n))return null;const b=rl({group:g,variableLabels:s,layers:n,coordSystem:r,colorGroupsByValue:o});return b.items.length===0?null:{group:g,built:b}}).filter(h);if(u.length===0)return[];const d=jc(u);if(t.legend.position==="auto"&&cl(d,n,r))return[];const p=ll(t.legend.position,d,n,r),m=dl(t.legend.display,p,n,r),y=m==="direct"?fl(n):null;return u.map(({built:g})=>qc(g,p,m,y))}function jc(e){return e.reduce((t,{group:n,built:r})=>{const s=n.some(a=>a.guideType!=="discrete");return t+(s?1:r.items.length)},0)}function qc(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 Qc(e){const{scales:t,layers:n}=e,r=[];for(const s of On){const a=t[s];if(a===void 0||a.kind==="identity"||!Zc(s,n))continue;const o=Te(n,s),i=ml(s,a);r.push({scaleAestheticKey:s,scale:a,variableName:o,guideType:i})}return r}function Zc(e,t){const n=ee(e);return t.some(r=>h(r.mapping[n]))}function Jc(e,t,n){const[r]=e;return r.scaleAestheticKey!=="color"?!1:da({colorVariableName:r.variableName,xVariableName:t,mapsColorAcrossMultipleLayers:el(r.scaleAestheticKey,n),isMergedWithAnotherAesthetic:e.length>1})}function el(e,t){const n=ee(e);return t.filter(r=>h(r.mapping[n])).length>1}function tl(e){const t=new Map;for(const n of e){const r=pl(n),s=t.get(r);s?s.push(n):t.set(r,[n])}return[...t.values()]}function nl(e,t,n){if(t==="lineType"){e.lineType=n;return}if(t==="color"){e.color=String(n);return}e[t]=n}function rl({group:e,variableLabels:t,layers:n,coordSystem:r,colorGroupsByValue:s}){const a=e[0],o=e.map(u=>ee(u.scaleAestheticKey)),i=la({scale:a.scale,aesthetics:o,layers:n,coordSystem:r}),c=Bn(a.variableName,t),l=Me({layers:n,scaleType:a.scale.spec.scaleType,variableName:a.variableName});return{aesthetics:e.map(u=>u.scaleAestheticKey),title:c,items:i.map(u=>sl(u,e,o,l,s))}}function sl(e,t,n,r,s){const a={};for(const i of t)nl(a,i.scaleAestheticKey,i.scale.map(e.value));const o=ol(e,t,n,r,s);return{value:e.value,label:al(t,e,s),visual:a,normalizedY:null,swatchShape:e.swatchShape,valueFormat:o}}function al(e,t,n){return e[0].scaleAestheticKey!=="color"?null:n.get(E(t.value))?.label??null}function ol(e,t,n,r,s){if(t[0].scaleAestheticKey==="color")return s.get(E(e.value))?.valueFormat??r;const a=e.owner?.layer,o=il(a,n);return a===void 0||o===null?r:Me({layers:[a],scaleType:t[0].scale.spec.scaleType,variableName:o})}function il(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 cl(e,t,n){if(e>1)return!1;const r=n.type==="polar";return yt(t,["line","area","bar"])||r}function ll(e,t,n,r){if(e!=="auto")return e;if(r.type==="polar")return"top";const s=yt(n,["line","area"]),a=yt(n,["bar"]),o=yt(n,["bar"],c=>X(c.position)),i=t>=Uc;return s&&a?"top":s?i?"right":"top":o?ma(r)?"top":i?"right":"top":"top"}function ul(e){if(e.length!==1)return!1;const t=e[0];return t?Kc[t.geom]?.[t.position]===!0:!1}function dl(e,t,n,r){if(!(t==="right"&&!ma(r)))return"pill";switch(e){case"pill":return"pill";case"direct":return"direct";case"auto":return ul(n)?"direct":"pill"}}function ma(e){return e.type==="cartesian"&&e.mainAxis==="y"}function yt(e,t,n){return e.some(r=>t.includes(r.geom)&&(n?.(r)??!0))}function pl(e){const t=e.scale.domain.map(E);return JSON.stringify([e.variableName,e.guideType,...t])}function ml(e,t){return $n(t)?"discrete":`continuous:${e}`}function fl(e){const t=e[0];if(!t)return new Map;const n=new Map;return t.data.groupBy(z.group).forEach(r=>{const s=r.findLast(l=>h(H(l))||h(C(l)));if(!s)return;const a=Le(s);if(!h(a))return;const o=te(s),i=H(s)??C(s);if(!h(i))return;const c=h(o)?(o+i)/2:i;n.set(String(a),c)}),n}class hl extends de{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=ic(t.originalData),r=Dc({scales:t.scales,layers:t.layers,coordSystem:t.coordSystem,valueLabels:cc(t.originalData,t.layers,n)}),s={scales:t.scales,config:t.config,layers:t.layers,coordSystem:t.coordSystem,variableLabels:n,colorGroups:r},a=Oc(s),o=yl(a,Xc(s));return{axes:Ac(s,o),legends:o,headline:a,panel:{border:{isVisible:t.config.panel.border.isVisible}},colorGroups:r}}}const yl=(e,t)=>e?.kind!=="perGroup"||t.some(r=>r.display==="direct")?t:[],gl=e=>E([Le(e)]),Gn=(e,t)=>{const n=t!==null?e[t]??null:null;return E([n])},j=(e,t)=>{const n=le(t);if(n!==void 0)return()=>n;const r=v(t);return h(r)?s=>{const a=s[r];if(a===void 0)return null;switch(e.getType(r)){case"numeric":return D(a)?a:null;case"categorical":return Ze(a)?a:null;case"temporal":return G(a)?a:null;default:return null}}:()=>null},Ft=(e,t)=>j(e,t.x),fa=(e,t)=>j(e,t.y),bl=(e,t)=>j(e,t.label),ha=(e,t)=>j(e,t.color),vl=(e,t)=>j(e,t.size),xl=(e,t)=>j(e,t.alpha),Sl=(e,t)=>j(e,t.group),wl=(e,t)=>j(e,t.strokeWidth),Xr={variable:f.yRaw};function Rt(e,t){return X(e)?Xr:t.y??Xr}function Nt(e){return j(e.data,Rt(e.position,e.mapping))}const Al=["lt","lte","gt","gte","range"];function gt(e,t){if("and"in e){const n=e.and.map(r=>gt(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=>gt(r,t));return r=>{for(const s of n)if(s(r))return!0;return!1}}if("not"in e){const n=gt(e.not,t);return r=>!n(r)}return Tl(e,t)}function bt(e,t){if("and"in e){for(const r of e.and)bt(r,t);return}if("or"in e){for(const r of e.or)bt(r,t);return}if("not"in e){bt(e.not,t);return}const n=Ml(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 jr=()=>!1;function Tl(e,t){if(!t.hasVariable(e.variable))return jr;const n=t.getType(e.variable);if("eq"in e){const r=oe(e.eq,n,t.parsingLocale);return s=>qr(t.readValue(s,e.variable),r)}if("oneOf"in e){const r=e.oneOf.map(s=>oe(s,n,t.parsingLocale));return s=>{const a=t.readValue(s,e.variable);for(const o of r)if(qr(a,o))return!0;return!1}}if("lt"in e){const r=oe(e.lt,n,t.parsingLocale);return s=>Ie(t.readValue(s,e.variable),r)==="less"}if("lte"in e){const r=oe(e.lte,n,t.parsingLocale);return s=>{const a=Ie(t.readValue(s,e.variable),r);return a==="less"||a==="equal"}}if("gt"in e){const r=oe(e.gt,n,t.parsingLocale);return s=>Ie(t.readValue(s,e.variable),r)==="greater"}if("gte"in e){const r=oe(e.gte,n,t.parsingLocale);return s=>{const a=Ie(t.readValue(s,e.variable),r);return a==="greater"||a==="equal"}}if("range"in e){const[r,s]=e.range,a=oe(r,n,t.parsingLocale),o=oe(s,n,t.parsingLocale);return i=>{const c=t.readValue(i,e.variable),l=Ie(c,a),u=Ie(c,o);return l==="incomparable"||u==="incomparable"?!1:(l==="greater"||l==="equal")&&(u==="less"||u==="equal")}}return jr}function Ml(e){for(const t of Al)if(t in e)return t;return null}function Ie(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 D(e)&&D(t)?e<t?"less":e>t?"greater":"equal":"incomparable"}function qr(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:Rn(e,void 0,n)}const Ll={bar:"observation-rerender",rule:null,line:"overlay-anchor",area:"overlay-anchor",point:"overlay-anchor"};function ya(e){const t=Ll[e];return t===null?null:{strategy:t,composition:ga()}}function ga(){return{isDimmed:!1,matchedLayer:null,overlayCandidates:[]}}class Vl extends Re{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:o})=>o===void 0||o===t.id);if(s.length===0)return t;const a=El({layer:t,highlights:s,parsingLocale:n.config.parsingLocale,strategy:r.strategy});return{...t,highlight:{...r,composition:a}}}}function El({layer:e,highlights:t,parsingLocale:n,strategy:r}){for(const T of t)bt(T.predicate,e.data);const s=v(e.mapping.x),a=Il(e,n),o=t.map(T=>({predicate:gt(T.predicate,a),scope:T.scope})),i=o.some(({scope:T})=>T==="series"),c=o.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,y=new Uint8Array(u),g=new Set,b=new Set;let x=!1,S=0;for(const T of e.data){let ne,he;d!==null&&(ne=gl(T),d[S]=ne),p!==null&&(he=Gn(T,s),p[S]=he),m!==null&&(m[S]=T);for(const{predicate:ot,scope:it}of o)if(ot(T))switch(it){case"series":ne!==void 0&&g.add(ne);break;case"x-value":he!==void 0&&b.add(he);break;case"data-point":y[S]=1,x=!0;break}S++}if(g.size===0&&b.size===0&&!x)return ga();const w=new Uint8Array(u),k=[];let W=0;for(let T=0;T<u;T++){const ne=d?.[T],he=p?.[T],ot=ne!==void 0&&g.has(ne),it=he!==void 0&&b.has(he),Fr=y[T]===1;if(r==="observation-rerender")(ot||Fr||it)&&(w[T]=1,W++);else if(ot)w[T]=1,W++;else if(Fr||it){const Rr=m?.[T];Rr!==void 0&&k.push({observation:Rr,observationIndex:T})}}const q=W>0?{...e,data:e.data.filterByMask(w)}:null;return{isDimmed:(r==="observation-rerender"||g.size>0)&&q!==null,matchedLayer:q,overlayCandidates:k}}function Il(e,t){const n=v(e.mapping.y),r=Nt(e);return{hasVariable:s=>e.data.hasVariable(s),getType:s=>e.data.getType(s),readValue:(s,a)=>n!==null&&a===n?r(s):s[a]??null,parsingLocale:t}}class kl extends Re{constructor(t,n,r,s,a){super(),this.transformCompiler=t,this.statCompiler=n,this.groupCompiler=r,this.geomCompiler=s,this.positionAdjusterCompiler=a}dependencies(t){return[t.data,t.mapping,Qr(t)]}compileLayer(t,n){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){return{...It({data:n,mapping:r}).pipe(({data:o,mapping:i})=>{const c=this.statCompiler.compute(t.stat,{data:o,mapping:i,xScaleIsDiscrete:s});return{data:c.data,mapping:{...i,...c.mapping}}}).pipe(({data:o,mapping:i})=>({data:this.groupCompiler.compute({data:o,mapping:i}).data,mapping:i})).pipe(({data:o,mapping:i})=>{const c=this.geomCompiler.compile(t.geom,{data:o,mapping:i,params:t.params});return{data:c.data,mapping:{...i,...c.mapping}}}).pipe(({data:o,mapping:i})=>{const c=this.positionAdjusterCompiler.adjust(t.position,{data:o,mapping:i});return{data:c.data,mapping:{...i,...c.mapping}}}).result(),id:t.id,geom:t.geom,position:t.position,yScaleType:t.yScaleType,params:t.params,interactive:t.interactive,dataLabels:t.dataLabels,summary:{},highlight:ya(t.geom)}}}function Qr(e){return e.scales.some(t=>t.scaledAesthetic==="x"&&t.scaleType==="discrete")}class ba extends Error{constructor(t){const n=t.map(r=>`- ${r.message}`).join(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("date-fns"),ie=require("arquero"),ue=require("lodash-es"),$e=require("d3-time"),Ao=require("date-fns/differenceInDays"),ce=require("d3-scale"),Is=require("lodash-es/merge"),ye=require("d3-regression"),To=require("humanize-duration");require("@graphysdk/i18n");const _e=require("d3-shape"),Mo=require("d3-delaunay"),Lo=require("lodash-es/isEqual");typeof window<"u"&&(window.__GRAPHY_SDK__??={},window.__GRAPHY_SDK__.vizEngine="0.0.1-experimental.3");const In=e=>e.length>0;function h(e){return e!=null}function Pr(e){if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function R(e,t){return ks(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 ks(e,t){let n=!1;const r={...e};for(const[s,a]of Object.entries(t)){const o=e[s];if(Pr(a)&&Pr(o)){const i=ks(o,a);i!==o&&(r[s]=i,n=!0)}else a!==void 0&&a!==o&&(r[s]=a,n=!0)}return n?r:e}const ve=process.env.NODE_ENV!=="production";function It(e){return{pipe:t=>{const n=t(e);return It({...e,...n})},result:()=>e}}let kt=!0;const Vo=e=>{kt=e},Eo=()=>kt,Io=()=>{let e=null;const t={hits:0,misses:0};return Object.assign((r,s)=>{if(!kt)return ve&&(t.misses+=1),s();if(e&&Ds(e.args,r))return ve&&(t.hits+=1),e.out;ve&&(t.misses+=1);const a=s();return e={args:r,out:a},a},{stats:t,reset:()=>{e=null}})},Cs=()=>{const e=new WeakMap,t={hits:0,misses:0};return Object.assign((r,s,a)=>{if(!kt)return ve&&(t.misses+=1),a();const o=e.get(r);if(o){for(const c of o)if(Ds(c.args,s))return ve&&(t.hits+=1),c.out}ve&&(t.misses+=1);const i=a();return o?o.push({args:s,out:i}):e.set(r,[{args:s,out:i}]),i},{stats:t})},ko=(...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 de{constructor(){this.memo=Cs(),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}}const G=e=>e instanceof Date&&V.isValid(e),Co=e=>G(e)||e===null,Ze=e=>typeof e=="string",D=e=>typeof e=="number"&&!Number.isNaN(e)&&Number.isFinite(e);function Do(e){return{type:"mapping",mapping:e}}function v(e){return h(e)?typeof e=="string"?e:"variable"in e?e.variable:null:null}function le(e){if(!(!h(e)||typeof e=="string")&&"value"in e)return e.value}const _s="\0graphy\0_",A=e=>`${_s}${e}`,Sn={x:A("constantX")},je={count:A("count"),mean:A("mean")},z={group:A("group")},f={x:A("x"),y:A("y"),xMin:A("xMin"),xMax:A("xMax"),yMin:A("yMin"),yMax:A("yMax"),yRaw:A("yRaw")},pe={color:A("color"),size:A("size"),alpha:A("alpha"),strokeWidth:A("strokeWidth"),lineType:A("lineType")},ct={y:A("ruleY"),x:A("ruleX")};({...z,...f,...pe});const _o=new Set(Object.values(je)),Fo=e=>e.startsWith(_s),Ro=e=>_o.has(e),Le=e=>e[z.group];function $(e){return e[f.x]}function C(e){return e[f.y]}function me(e){return e[f.xMin]}function ae(e){return e[f.xMax]}function te(e){return e[f.yMin]}function H(e){return e[f.yMax]}function Fs(e){return e[f.yRaw]}function Ct(e){return e[pe.color]}function No(e){return e[pe.alpha]}function Rs(e){return e[pe.size]}function Ns(e){return e[pe.strokeWidth]}function Ps(e){return e[pe.lineType]??"solid"}const wn=(e,t,n)=>{for(const r of t){if(r.geom!=="bar"&&r.geom!=="line"||e.layerId!==void 0&&r.id!==e.layerId)continue;const s=v(r.mapping.x);if(s===null)continue;const a=v(r.mapping.y);for(const o of r.data){if(o[s]!==e.anchorValue||Le(o)!==e.groupValue)continue;const i=Po(o,r.geom,n);if(i===null)continue;const c=a!==null?o[a]??null:null;if(D(c))return{...i,measurementValue:c,color:Ct(o)}}}return null},Po=(e,t,n)=>{if(n.type==="polar")return t!=="bar"?null:Bo(e);const r=Oo(e,t,n.mainAxis);return r===null?null:{...r,geom:t}},Oo=(e,t,n)=>{if(t==="line"){const o=$(e),i=C(e);return o===null||i===null?null:{x:o,y:i}}if(n==="x"){const o=me(e),i=ae(e),c=H(e)??C(e);return o===null||i===null||c===null?null:{x:(o+i)/2,y:c}}const r=te(e),s=H(e),a=ae(e)??$(e);return r===null||s===null||a===null?null:{x:a,y:(r+s)/2}},Bo=e=>{const t=me(e),n=ae(e),r=te(e),s=H(e);if(t===null||n===null||r===null||s===null)return null;const a=(t+n)/2,o=(r+s)/2,i=.5+.5*o*Math.sin(a),c=.5-.5*o*Math.cos(a);return{x:i,y:c,geom:"polar-bar"}};class $o extends de{dependencies(t){return[t.annotations,t.layers,t.coordSystem]}run(t){return{differenceArrows:Go(t),shapes:t.annotations.shapes,freeformArrows:t.annotations.freeformArrows,textAnnotations:t.annotations.textAnnotations,stickers:en(t.annotations.stickers,t.layers,t.coordSystem),pinnedNumbers:en(t.annotations.pinnedNumbers,t.layers,t.coordSystem),comments:en(t.annotations.comments,t.layers,t.coordSystem)}}}const en=(e,t,n)=>{const r=[];for(const s of e){const a=wn(s.anchor,t,n);a!==null&&r.push({...s,anchor:a})}return r},Go=({annotations:e,layers:t,coordSystem:n})=>{if(n.type!=="cartesian")return[];const r=[];for(const s of e.differenceArrows){if(zo(s.start,s.end))continue;const a=wn(s.start,t,n),o=wn(s.end,t,n);a===null||o===null||r.push({id:s.id,start:a,end:o,color:Wo(s,a,o),size:s.size,label:s.label,labelCrossPosition:s.labelCrossPosition})}return r},zo=(e,t)=>e.layerId===t.layerId&&e.anchorValue===t.anchorValue&&e.groupValue===t.groupValue,Wo=(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 Yo(e,t){const n=Ko(t);return{...e,background:Ho(e.background,n),border:Uo(e.border,n)}}function Ho(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 Uo(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 Ko(e){const t=e.color,n=t?.domain[0];if(!n)return;const r=t.map(n);if(typeof r=="string")return r}class Xo extends de{dependencies(t){return[t.scales,t.config]}run(t){const{scales:n,config:r}=t;return{...r,appearance:Yo(r.appearance,n)}}}class jo extends de{dependencies(t){return[t.data,t.mapping]}run(t){let n=t.data,r=t.mapping;r.x===""&&(n=n.addConstantVariable(Sn.x,"categorical",""),r={...r,x:Sn.x});for(const s of Object.keys(r)){const a=le(r[s]);if(a===void 0)continue;const o=A(`const_${s}`);n=n.addConstantVariable(o,qo(a),a),r={...r,[s]:o}}return{data:n,mapping:r}}}const qo=e=>typeof e=="number"?"numeric":e instanceof Date?"temporal":"categorical";class Re{constructor(){this.perLayerMemo=Cs(),this.listMemo=Io()}get stats(){return ko(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 Qo extends de{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 Zo extends Re{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 Jo{constructor(t){this.setupStage=new Qo(t),this.transformStage=new Zo(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 Ne{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 ei{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}}class ti{constructor(){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:ri(t.scales,t.layers)}}transform(t){return t.layers.map(n=>ai(n))}}const ni=[[f.x,f.y],[f.xMin,f.yMin],[f.xMax,f.yMax]],Or=A("flipSwap"),ri=(e,t)=>si(t)?e.map(n=>n.scaledAesthetic!=="x"||n.scaleType!=="continuous"&&n.scaleType!=="datetime"&&n.scaleType!=="discrete"?n:{...n,reverse:!n.reverse}):e,si=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},ai=e=>{let t=e.data;for(const[n,r]of ni){const s=t.hasVariable(n),a=t.hasVariable(r);s&&a?t=t.renameVariable(n,Or).renameVariable(r,n).renameVariable(Or,r):s?t=t.renameVariable(n,r):a&&(t=t.renameVariable(r,n))}return{...e,data:t}};class oi{constructor(){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},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=ci(n),s=li(n);return t.layers.map(a=>{const o=n.theta==="y"?di(a):a;return ui(o,r,s)})}}const ii=[[f.x,f.y],[f.xMin,f.yMin],[f.xMax,f.yMax]];function ci(e){const t=e.startAngle*(Math.PI/180);return n=>n*2*Math.PI+t}function li(e){const{innerRadius:t}=e;return n=>t+n*(1-t)}function ui(e,t,n){let r=e.data;return r=Ve(r,f.x,t),r=Ve(r,f.xMin,t),r=Ve(r,f.xMax,t),r=Ve(r,f.y,n),r=Ve(r,f.yMin,n),r=Ve(r,f.yMax,n),{...e,data:r}}function Ve(e,t,n){if(!e.hasVariable(t))return e;const s=e.getValues(t,{type:"numeric"}).map(a=>a===null?null:n(a));return e.addVariable(t,"numeric",s)}function di(e){let t=e.data;for(const[n,r]of ii){const s=t.hasVariable(n),a=t.hasVariable(r);if(!s&&!a)continue;const o=s?t.getValues(n):null,i=a?t.getValues(r):null;o&&(t=t.addVariable(r,"numeric",o)),i&&(t=t.addVariable(n,"numeric",i))}return{...e,data:t}}class pi extends Ne{constructor(){super("coord"),this.register("cartesian",new ei),this.register("flip",new ti),this.register("polar",new oi)}}const mi=new Set(["count","sum","mean","median"]);function Os(e,t){return mi.has(e)?"numeric":t}const E=e=>(Array.isArray(e)?e:[e]).map(n=>n instanceof Date?n.toISOString():String(n??"<null>")).join("\0"),fi="key",hi="value",Br="\0__rowMaskIndex",Ke={numeric:{type:"decimal"},categorical:{type:"text"},temporal:{type:"datetime"}},yi={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 I{constructor(t={}){const{table:n,variableMetadata:r}=this.parseVariableMap(t);this.table=n,this.variableMetadata=r}static fromTrusted(t,n){const r=Object.create(I.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 a={...this.variableMetadata,[t]:{type:n,valueFormat:this.resolveAddedVariableFormat(t,n,s)}},o=this.normalizeRawValues(n,r),i=this.table.assign(ie.table({[t]:o}));return I.fromTrusted(i,a)}addConstantVariable(t,n,r,s){const a={...this.variableMetadata,[t]:{type:n,valueFormat:this.resolveAddedVariableFormat(t,n,s)}},[o]=this.normalizeRawValues(n,[r]),i=this.table.assign(ie.table({[t]:Array(this.size()).fill(o)}));return I.fromTrusted(i,a)}deriveVariable(t,n,r,s){const a=Array.from({length:this.size()},(o,i)=>r(this.table.object(i)));return this.addVariable(t,n,a,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]:a,...o}=this.variableMetadata,i={...o,[n]:r};return I.fromTrusted(s,i)}selectVariables(...t){const n=this.table.select(...t),r=Object.fromEntries(Object.entries(this.variableMetadata).filter(([s])=>t.includes(s)));return I.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=yi[n],a=this.table.params({__variableName:t,__value:r}).filter(s);return I.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},(s,a)=>a),r=this.table.assign(ie.table({[Br]:n})).params({__indexColumnName:Br,__mask:t}).filter((s,a)=>a.__mask[s[a.__indexColumnName]]===1).select(...this.table.columnNames());return I.fromTrusted(r,this.variableMetadata)}orderBy(t,n="asc"){const r=this.table.orderby(n==="asc"?t:ie.desc(t));return I.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 gi(t,n,this.variableMetadata)}rollup(t){const n=this.table.rollup(Object.fromEntries(Object.entries(t).map(([s,a])=>[s,ie.op[a.aggregation](a.variableName)]))),r={};for(const[s,{variableName:a,aggregation:o}]of Object.entries(t)){const i=this.variableMetadata[a],c=i?.type??"numeric",l=i?.valueFormat??Ke[c],u=Os(o,c);r[s]={type:u,valueFormat:Bs(o,l)}}return I.fromTrusted(n,r)}reshapeFromWideToLong({keep:t,reshape:n,keyName:r=fi,valueName:s=hi}={}){const{numeric:a,categorical:o,temporal:i}=this.groupVariableNamesByType(),c=t??[...o,...i],l=n??a.filter(y=>!c.includes(y));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 y={};for(const g of c){const b=this.variableMetadata[g];b&&(y[g]={type:b.type,values:[],valueFormat:b.valueFormat})}return y[r]={type:"categorical",values:[],valueFormat:{type:"text"}},y[s]={type:"numeric",values:[],valueFormat:{type:"decimal"}},new I(y)}if(l.filter(y=>this.variableMetadata[y]?.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 y of c){const g=this.variableMetadata[y];g&&(m[y]=g)}return m[r]={type:"categorical",valueFormat:{type:"text"}},m[s]={type:"numeric",valueFormat:bi(this.variableMetadata,l,r)},I.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:Ke[n]}parseVariableMap(t){const n={},r={};for(const[a,{type:o,values:i,valueFormat:c}]of Object.entries(t))n[a]=i,r[a]={type:o,valueFormat:c??Ke[o]};return{table:ie.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)||!V.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,a=[];for(const o of n){const i=r&&o instanceof Date?o.getTime():o;s.has(i)||(s.add(i),a.push(o))}return a}}class gi{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(o=>this.grouped.column(o)).filter(o=>o!==void 0);let a=0;for(const o of n){const i=o[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,o.map(m=>p?.get(m))]})),u=ie.table(l);t(I.fromTrusted(u,this.variableMetadata),c,a++)}}rollup(t){const n=this.grouped.rollup(Object.fromEntries(Object.entries(t).map(([s,a])=>[s,ie.op[a.aggregation](a.variableName)]))),r=Object.fromEntries(this.groupedBy.map(s=>{const a=this.variableMetadata[s],o=a?.type??"categorical",i=a?.valueFormat??Ke[o];return[s,{type:o,valueFormat:i}]}));for(const[s,{variableName:a,aggregation:o}]of Object.entries(t)){const i=this.variableMetadata[a],c=i?.type??"numeric",l=i?.valueFormat??Ke[c],u=Os(o,c);r[s]={type:u,valueFormat:Bs(o,l)}}return I.fromTrusted(n,r)}getStableKey(t,n){return E(t.map(r=>r.get(n)))}}function bi(e,t,n){const r=t.map(c=>e[c]?.valueFormat??{type:"decimal"}),[s,...a]=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(a.every(c=>ue.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 $s{constructor(){this.currentYear=new Date().getUTCFullYear(),this.previousDate=null,this.previousYear=null}incrementYearIfNeeded(t){this.previousYear===null?this.previousYear=t.getUTCFullYear():this.previousDate!==null&&V.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 Gs=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==="-",Dt="en-GB",zs=e=>e.type==="lookup",Ws=e=>e.type==="text",Pe=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",kn=e=>e.type==="decimal"||e.type==="integer"||e.type==="percentage"||e.type==="duration"||e.type==="currency",Cn=e=>e.type==="currency",Dn=e=>e.type==="month"||e.type==="day_month"||e.type==="weekly_date_range",Ys=e=>{if(zs(e))return Ys(e.fallback);if(Pe(e))return"temporal";if(kn(e))return"numeric";if(Ws(e))return"categorical";const t=e;throw new Error(`No data type found for value format: ${t.type}`)},Xe={k:1e3,m:1e6,b:1e9,t:1e12},_n=["k","m","b","t"],vi=new RegExp(`^-?(\\d{1,3}(,\\d{3})*|\\d+)\\.?\\d*(${_n.join("|")})?$`,"i"),xi=/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?%?$/,Ae=e=>e===null||e instanceof Date||Array.isArray(e)||typeof e=="boolean"?!1:typeof e=="string"?vi.test(e)&&!Number.isNaN(Number(e.replace(new RegExp(`[,${_n.join("")}]`,"gi"),""))):!Number.isNaN(Number(e)),Hs=e=>Ae(e)?!0:typeof e=="string"?xi.test(e):!1,Si=/^\d{4}-\d{2}-\d{2}(T|\s)\d{1,2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|\+00:00)?$/,wi=/^\s*(19\d{2}|2[01]\d{2})\s*$/,Ai=[[/\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"]],Ti={"en-US":"MDY","en-GB":"DMY","pt-PT":"DMY",ar:"DMY"},Us=["/","-","."," "],$r=[["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"]],Gr=[["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"]],zr=[["yyyy","M","d"],["yyyy","M","dd"],["yyyy","MM","d"],["yyyy","MM","dd"],["yyyy","MMMM","d"],["yyyy","MMMM","dd"],["yyyy","MMMM","do"]],Ks=[["d","MMMM"],["dd","MMMM"],["do","MMMM"],["MMMM","d"],["MMMM","dd"],["MMMM","do"]],Mi=[{dateFormat:"MMMM d, yyyy",type:"date"},{dateFormat:"MMMM dd, yyyy",type:"date"},{dateFormat:"MMMM do, yyyy",type:"date"},{dateFormat:"yyyy-MM",type:"month_year"}],Xs=1900,js=2199,Li=3,Vi=6,Ei=5,Ii=1,ki=28,Ci=/\s*[–—]\s*|\s-\s/,Di=e=>typeof e=="number"?Number.isNaN(e)?!1:e>=Xs&&e<=js:typeof e=="string"?wi.test(e):!1,qs=(e,t)=>{const n=qe(e);return Ae(n)?Ri(n):typeof n=="string"?!!Qs(n)||Fn(n)&&V.isValid(new Date(n)):V.isValid(n)},qe=e=>{if(typeof e!="string")return e;let t=e;for(const[n,r]of Ai)t=t.replace(n,r);return t},Qs=(e,t=Dt)=>{const n=qe(e);return Fn(n)?{type:"datetime"}:Zs(t).find(r=>!Pe(r)||r.type==="month"&&n.length<Li?!1:r.dateFormat&&V.isValid(V.parse(n,r.dateFormat,new Date)))},Fn=e=>Si.test(e.trim()),_i=(e,t=Dt)=>{const[n,r]=e.split(Ci);if(!n||!r)return;const s=qe(n).trim(),a=qe(r).trim();return Fi(t).find(o=>{if(!Pe(o)||!o.dateFormat)return!1;const i=V.parse(s,o.dateFormat,new Date),c=V.parse(a,o.dateFormat,new Date);if(!V.isValid(i)||!V.isValid(c))return!1;const l=new $s,u=l.incrementYearIfNeeded(i),d=l.incrementYearIfNeeded(c),p=V.differenceInDays(d,u);return V.isWithinInterval(new Date(u.getFullYear(),Ii,ki),{start:u,end:d})&&p===Ei?!0:p===Vi})},Zs=e=>{const t={date:Js(e),year:[["yyyy"]],day_month:Ks,month_year:[["MMMM","yyyy"],["yyyy","MMMM"]],month:[["MMMM"]],quarter:[["QQQ","yyyy"],["yyyy","QQQ"]]};return[...Mi,...Object.entries(t).flatMap(([n,r])=>r.flatMap(s=>Us.map(a=>({dateFormat:s.join(a),type:n}))))]},Js=e=>Ti[e]==="MDY"?[...Gr,...$r,...zr]:[...$r,...Gr,...zr],Fi=e=>{const t={weekly_date_range:Ks,weekly_date_range_with_year:Js(e)};return Object.entries(t).flatMap(([n,r])=>r.flatMap(s=>Us.map(a=>({dateFormat:s.join(a),type:n}))))},Ri=e=>{const t=Number(e);if(!ue.isInteger(t))return!1;const n=new Date(t),r=new Date(t*1e3),s=a=>V.isValid(a)&&a.getFullYear()>=Xs&&a.getFullYear()<=js;return s(n)||s(r)},ea={$:"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"},ta=e=>{if(typeof e=="string"){const t=na(e);return t.length?Ae(t):!1}return Ae(e)},Ni=e=>{const t=ra(e),n=t?ea[t]:void 0;if(!n)throw new Error("Could not get currency ISO");return n},na=e=>{const t=ra(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 Ae(n)?n.split(",").join(""):""},ra=e=>Object.keys(ea).sort((n,r)=>r.length-n.length).find(n=>e.includes(n)),Pi=(e,t)=>{const n=typeof e=="string"?e.trim():e;if(Ae(n))return{type:"decimal"};const r=typeof n=="string"&&Qs(n,t);if(r)return r;const s=typeof n=="string"&&_i(n,t);return s||(qs(e)?{type:"date"}:Hs(e)?{type:"percentage"}:ta(e)&&typeof e=="string"?{type:"currency",iso:Ni(e)}:{type:"text"})},Oi=/\s*[–—]\s*|\s-\s/,Bi=(e,t,n)=>{if(Je(e))return null;switch(t.type){case"decimal":case"integer":case"duration":return sa(e);case"percentage":return $i(e);case"currency":return Gi(e);case"datetime":case"date":case"year":case"month_year":case"month":case"day_month":case"quarter":case"time":return Rn(e,t.dateFormat,n);case"weekly_date_range":case"weekly_date_range_with_year":return zi(e,t.dateFormat,n);case"text":return Wi(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}`)}}},Rn=(e,t,n)=>{if(e instanceof Date)return V.isValid(e)?e:null;const r=qe(String(e).trim());if(r.length===0)return null;const s=new Date;if(t){const o=V.parse(r,t,s);return V.isValid(o)?tn(o):null}for(const o of Zs(n)){if(!Pe(o)||!o.dateFormat)continue;const i=V.parse(r,o.dateFormat,s);if(V.isValid(i))return tn(i)}const a=new Date(r);return qs(a)?Fn(r)?a:tn(a):null},sa=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;let t=e.trim();if(!Ae(t))return null;let n=1;for(const r of _n)if(new RegExp(`${r}$`,"i").test(t)){n=Xe[r],t=t.slice(0,-1);break}return Number(t.split(",").join(""))*n},$i=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;const t=e.trim();if(!Hs(t))return null;const n=Number(t.replace(/%/g,"").replace(/,/g,""))/100;return Number.isNaN(n)?null:n},Gi=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;const t=e.trim();return ta(t)?sa(na(t)):null},zi=(e,t,n)=>{const r=String(e).trim().split(Oi),[s,a]=[r[0]?.trim(),r[1]?.trim()];return!s||!a?null:Rn(s,t,n)},Wi=e=>String(e).trim(),tn=e=>new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())),Yi={type:"year",dateFormat:"yyyy"};class Hi extends de{dependencies(t){return[t]}run(t){const n=t._metadata?.parsingLocale??Dt,r={},s=Xi(t),a=Ui(t);for(const[o,i]of t.columns.entries()){if(i._metadata?.isHidden)continue;const c=s.get(i.key);if(Je(c))continue;const l=o===a?Yi:Pi(c,n),u=Ys(l);r[i.key]=Ki(i.key,t.rows,l,u,n)}return new I(r)}}const Ui=e=>{const t=ji(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(Di)})},Ki=(e,t,n,r,s)=>{const a=new $s,o=t.reduce((i,c)=>{if(Gs(c))return i;const l=Bi(c[e],n,s);return Dn(n)&&G(l)?i.push(a.incrementYearIfNeeded(l)):i.push(l),i},[]);return{type:r,values:o,valueFormat:n}},Xi=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 a=r[s];Je(a)||(t.set(s,a),n.delete(s))}if(n.size===0)break}return t},ji=(e,t)=>{const n=[];for(const r of e)if(Gs(r)||n.push(r),n.length===t)return n;return n};class qi{constructor(t){this.registry=t}compile(t,n){return this.registry.get(t).compile(n)}}class et{constructor(){this.requiredAesthetics=[]}}const Nn=(e,t)=>{const n=v(t.x);return!n||!["numeric","temporal"].includes(e.getType(n))?e:e.orderBy(n,"asc")};class Qi extends et{constructor(){super(...arguments),this.type="area",this.requiredAesthetics=["x","y"]}compile({data:t,mapping:n}){if(t=Nn(t,n),t.hasVariable(f.yMin)||(t=t.addConstantVariable(f.yMin,"numeric",0)),!t.hasVariable(f.yMax)){const r=v(n.y);h(r)&&t.hasVariable(r)&&(t=t.addVariable(f.yMax,"numeric",t.getValues(r,{type:"numeric"})))}return{data:t,mapping:{}}}}const aa=.7,Zi=.1;class Ji extends et{constructor(){super(...arguments),this.type="bar"}compile({data:t,mapping:n}){if(t=Nn(t,n),t.hasVariable(f.yMin)||(t=t.addConstantVariable(f.yMin,"numeric",0)),!t.hasVariable(f.yMax)){const s=v(n.y);h(s)&&t.hasVariable(s)&&(t=t.addVariable(f.yMax,"numeric",t.getValues(s,{type:"numeric"})))}const r=aa/2;return t=t.addConstantVariable(f.xMin,"numeric",-r).addConstantVariable(f.xMax,"numeric",r),{data:t,mapping:{}}}}class ec extends et{constructor(){super(...arguments),this.type="line",this.requiredAesthetics=["x","y"]}compile(t){return{data:Nn(t.data,t.mapping),mapping:{}}}}class tc extends et{constructor(){super(...arguments),this.type="point",this.requiredAesthetics=["x","y"]}compile({data:t}){return{data:t,mapping:{}}}}class nc extends et{constructor(){super(...arguments),this.type="rule"}compile({data:t,mapping:n}){const r=Wr(n.y,t);if(r!==null)return{data:new I({[ct.y]:{type:"numeric",values:[r.value],valueFormat:r.sourceFormat}}),mapping:{y:ct.y,x:void 0}};const s=Wr(n.x,t);return s!==null?{data:new I({[ct.x]:{type:"numeric",values:[s.value],valueFormat:s.sourceFormat}}),mapping:{x:ct.x,y:void 0}}:{data:new I,mapping:{x:void 0,y:void 0}}}}const Wr=(e,t)=>{const n=le(e);if(D(n))return{value:n,sourceFormat:void 0};const r=v(e);if(r===null||!Ro(r)||!t.hasVariable(r))return null;const[s]=t.getValues(r);return D(s)?{value:s,sourceFormat:t.getValueFormat(r)}:null};class rc extends Ne{constructor(){super("geom"),this.register("bar",new Ji),this.register("point",new tc),this.register("line",new ec),this.register("area",new Qi),this.register("rule",new nc)}}const Pn=(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 a=v(t[s]);h(a)&&(n.has(a)||e.getType(a)==="categorical"&&r.add(a))}return[...r]};class sc{compute({data:t,mapping:n}){const r=Pn(t,n);if(r.length===0)return{data:t.addConstantVariable(z.group,"categorical",null)};const s=t.size(),a=r.map(i=>t.getValues(i)),o=new Array(s);for(let i=0;i<s;i++)o[i]=E(a.map(c=>c[i]));return{data:t.addVariable(z.group,"categorical",o)}}}const oa=new Set(["x","y","ySecondary"]),On=new Set(["color","size","alpha","strokeWidth","lineType"]),_t=e=>oa.has(e),ac=e=>On.has(e),oc=e=>_t(e)||ac(e);function Oe(e){return e==="secondary"?"ySecondary":"y"}function ee(e){return e==="ySecondary"?"y":e}const ic=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},cc=(e,t,n)=>{const r=Te(t,"color");return r===null?{}:(e?.columns??[]).some(o=>o.key===r)?{}:n};function Te(e,t){const n=ee(t);for(const r of ia(t,e)){const s=v(r.mapping[n]);if(h(s))return s}return null}const Bn=(e,t)=>e===null?null:t[e]??e,lc=(e,t)=>e===null?null:t[String(e)]??null,Me=({layers:e,scaleType:t,variableName:n})=>{if(n===null)return nn(t);for(const r of e){if(!r.data.hasVariable(n))continue;const s=r.data.getValueFormat(n),a=s.type==="lookup"?s.fallback:s;return dc(a,t)?a:nn(t)}return nn(t)},uc=(e,t)=>t!=="y"&&t!=="ySecondary"?!1:ia(t,e).some(n=>n.position==="fill");function ia(e,t){return e==="ySecondary"?t.filter(n=>n.yScaleType==="secondary"):e==="y"?t.filter(n=>n.yScaleType==="primary"):t}const nn=e=>{switch(e){case"continuous":return{type:"decimal"};case"datetime":return{type:"date"};case"discrete":case"palette":case"identity":return{type:"text"}}},dc=(e,t)=>{switch(t){case"continuous":return kn(e);case"datetime":return Pe(e);case"discrete":case"palette":case"identity":return!0}},pc=[{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}],Yr={year:0,quarter:1,month:2,week:3,day:4,hour:5},Ee=40,mc=(e,t,n)=>{const r=n.unit==="quarter"?n.step*3:n.step;return gc(n.unit).range(e,new Date(t.valueOf()+1),r)},fc=({unit:e,step:t,start:n,stop:r})=>{const s=Ao.differenceInDays(r,n);switch(e){case"hour":return 24*s/t>Ee;case"day":return s/t>Ee;case"week":return s/(7*t)>Ee;case"month":return s/(30*t)>Ee;case"quarter":return s/(90*t)>Ee;case"year":return s/(365*t)>Ee}},hc=(e,t)=>{const n=!Dn(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"}}},yc=(e,t)=>{const n=bc(t);return n===null?!1:Yr[e]>Yr[n]},gc=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}},bc=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}},ca={left:"right",right:"left",top:"bottom",bottom:"top"},vc={x:!0,y:!0,ySecondary:!1},xc={bar:{cartesian:{hideGridX:!0},flip:{hideGridX:!0},polar:{hideGridX:!0,hideGridY:!0}}},Sc=20,Hr=new Set(["top","bottom"]),wc={type:"percentage"};function Ac(e,t){const{scales:n,config:r,layers:s,coordSystem:a,variableLabels:o}=e;if(a.type==="polar")return[];const i=Mc(s,a.type,r),c=new Set(t.map(d=>d.position)),l=Vc(la(r.axes.y.position,a.axisMapping.y.position),c),u=[];for(const d of oa){const p=n[d];if(!h(p)||p.kind!=="position")continue;const m=Tc({scaleAestheticKey:d,scale:p,config:r,layers:s,axisMapping:a.axisMapping,resolvedYPosition:l,gridOverrides:i,variableLabels:o});u.push(m)}return u}function Tc(e){const{scaleAestheticKey:t,scale:n,config:r,layers:s,axisMapping:a,resolvedYPosition:o,gridOverrides:i,variableLabels:c}=e,l=ee(t),{axisConfig:u,position:d}=Lc(t,r,a,o),p=Te(s,t),m=uc(s,t)?wc:Me({layers:s,scaleType:n.spec.scaleType,variableName:p}),y=Bn(p,c);return{scaleAestheticKey:t,aesthetic:l,position:d,label:u.label??y,isVisible:u.isVisible,tickCandidates:Ic(n,m),valueFormat:m,tickMode:u.ticks.mode,ticksVisible:u.ticks.isVisible,gridVisible:Ec(u,i,t),scaleType:n.spec.scaleType,bandwidth:n.bandwidth??void 0}}function Mc(e,t,n){const r=e.flatMap(i=>{const c=xc[i.geom]?.[t];return c?[c]:[]}),s=r.some(i=>i.hideGridX),a=r.some(i=>i.hideGridY),o=r.some(i=>i.hideBorder);return{x:{gridVisible:Ur(s,n.axes.x.grid.isVisible)},y:{gridVisible:Ur(a,n.axes.y.grid.isVisible)},borderVisible:o?!1:void 0}}function Ur(e,t){if(e&&t===null)return!1}function Lc(e,t,n,r){switch(e){case"x":return{axisConfig:t.axes[e],position:la(t.axes[e].position,n[e].position)};case"y":return{axisConfig:t.axes[e],position:r};case"ySecondary":{const s=ca[r],a=ue.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:a,position:a.position}}}}function la(e,t){return Hr.has(e)===Hr.has(t)?e:t}function Vc(e,t){return t.has(e)?ca[e]:e}function Ec(e,t,n){const{gridVisible:r}=n==="x"?t.x:t.y;return r??e.grid.isVisible??vc[n]}const Ic=(e,t)=>{if(e.spec.scaleType==="continuous"){const r=new Set,s=[];for(let a=1;a<=Sc;a++){const o=e.generateTicks({count:a}),i=E(o);r.has(i)||(r.add(i),s.push({ticks:o.map(c=>At(e,c))}))}return s}return e.spec.scaleType==="datetime"?kc(e,t):[{ticks:e.generateTicks().map(r=>At(e,r))}]},kc=(e,t)=>{const[n,r]=e.domain;if(!G(n)||!G(r))return[{ticks:e.generateTicks().map(c=>At(e,c))}];const s=new Set,a=[],o=(i,c)=>{if(i.length===0)return;const l=E(i);s.has(l)||(s.add(l),a.push({ticks:i.map(u=>At(e,u)),valueFormat:c}))};for(const i of pc)fc({...i,start:n,stop:r})||yc(i.unit,t)||o(e.generateTicks({interval:i}),hc(i,t));return o(e.generateTicks({atInputs:!0})),a.sort((i,c)=>i.ticks.length-c.ticks.length),a},At=(e,t)=>({value:t,position:e.map(t)});function Tt(e,t){switch(e){case"bar":return t.type==="polar"?"slice":"square";case"line":return"line";case"area":return"area";case"point":return"circle";default:return"square"}}function ua({scale:e,aesthetics:t,layers:n,coordSystem:r}){const s=Cc({layers:n,coordSystem:r,aesthetics:t}),a=da({layers:n,aesthetics:t});return e.domain.map(o=>({value:o,swatchShape:s(o),owner:a(o)}))}function Cc({layers:e,coordSystem:t,aesthetics:n}){const r=da({layers:e,aesthetics:n}),s=e.find(o=>n.some(i=>h(o.mapping[i]))),a=s?Tt(s.geom,t):"square";return o=>{const i=r(o);return i?Tt(i.layer.geom,t):a}}function da({layers:e,aesthetics:t,layerFilter:n}){const r=new Map;for(const[s,a]of e.entries()){if(n&&!n(a))continue;const o=t.find(c=>h(a.mapping[c]));if(o===void 0)continue;const i=v(a.mapping[o]);if(!(i===null||!a.data.hasVariable(i)))for(const c of a.data.getValues(i,{distinct:!0})){const l=E(c);r.has(l)||r.set(l,{layer:a,layerIndex:s})}}return s=>r.get(E(s))}const $n=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 s=e.color;if(s===void 0||!$n(s))return[];if(!t.some(u=>h(u.mapping.color)))return[];const a=Te(t,"color");if(pa({colorVariableName:a,xVariableName:Te(t,"x"),mapsColorAcrossMultipleLayers:Fc(t)>1,isMergedWithAnotherAesthetic:_c(e,t,a)}))return[];const i=s.spec.scaleType,c=t.findIndex(u=>h(u.mapping.color));return ua({scale:s,aesthetics:["color"],layers:t,coordSystem:n}).map(({value:u,swatchShape:d,owner:p})=>{const m=p?.layerIndex??c,y=t[m],g=y?v(y.mapping.color):null;return{value:u,color:String(s.map(u)),shape:d,layerIndex:m,valueFormat:Me({layers:y?[y]:t,scaleType:i,variableName:g}),label:lc(u,r)}})}const pa=({colorVariableName:e,xVariableName:t,mapsColorAcrossMultipleLayers:n,isMergedWithAnotherAesthetic:r})=>r?!1:e===null||Fo(e)?!n:t!==null&&e===t;function _c(e,t,n){if(n===null)return!1;for(const r of On){if(r==="color")continue;const s=e[r];if(!(s===void 0||!$n(s))&&Te(t,r)===n)return!0}return!1}const Fc=e=>e.filter(t=>h(t.mapping.color)).length,ma=["bar","line","area","point"];function Rc(e,t,n){const r=t.findIndex(s=>ma.includes(s.geom));if(r===-1)return[];if(e.length<2){const s=v(t[r]?.mapping.y);return[{value:null,swatch:null,layerIndex:r,groupLabelFormat:{type:"text"},label:Bn(s,n)}]}return e.map(s=>({value:s.value,swatch:{color:s.color,shape:s.shape},layerIndex:s.layerIndex,groupLabelFormat:s.valueFormat,label:s.label}))}function Kr(e,t,n){if(n===null||t===null)return[...e];const r=E(n);return e.filter((s,a)=>E(t[a]??null)===r)}const Nc=(e,t)=>{switch(t){case"total":{const{sum:n,count:r}=Xr(e);return r===0?null:n}case"average":{const{sum:n,count:r}=Xr(e);return r===0?null:n/r}case"current":return e.at(-1)??null}},Pc=(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}},Xr=e=>e.reduce((t,n)=>n===null?t:{sum:t.sum+n,count:t.count+1},{sum:0,count:0});function Oc(e){const{config:t,coordSystem:n}=e,r=t.headline.show;return r==="none"||r==="conversion"?null:n.type==="polar"?Bc(e,r):$c(e,r)}function Bc(e,t){if(t!=="total")return null;const{scales:n,layers:r}=e,s=r.find(c=>c.geom==="bar");if(s===void 0)return null;const a=s.summary.grandTotal;if(a===void 0)return null;const o=v(s.mapping.y);if(o===null)return null;const i=Me({layers:[s],scaleType:n.y?.spec.scaleType??"continuous",variableName:o});return{kind:"grandTotal",value:a,valueFormat:i}}function $c(e,t){const{config:n,scales:r,layers:s,variableLabels:a,colorGroups:o}=e;if(!s.some(l=>ma.includes(l.geom)))return null;const i=Rc(o,s,a);if(i.length===0)return null;const c=i.map(l=>Gc({group:l,show:t,compareWith:n.headline.compareWith,layers:s,scales:r})).filter(l=>l!==null);return c.length===0?null:{kind:"perGroup",items:c}}function Gc({group:e,show:t,compareWith:n,layers:r,scales:s}){const a=r[e.layerIndex];if(a===void 0)return null;const o=v(a.mapping.y);if(o===null||t==="total"&&a.position==="fill")return null;const i=v(a.mapping.x),c=v(a.mapping.color),l=a.yScaleType==="secondary"?s.ySecondary:s.y,u=Me({layers:[a],scaleType:l?.spec.scaleType??"continuous",variableName:o}),d=Yc(a.data,i),p=Me({layers:[a],scaleType:d?"datetime":s.x?.spec.scaleType??"discrete",variableName:i}),m=Hc(a.data,i),y=m.getValues(o,{type:"numeric"}),g=i!==null?m.getValues(i):[],b=c!==null?m.getValues(c):null,x=Kr(y,b,e.value),S=Kr(g,b,e.value);return{value:e.value,swatch:e.swatch,aggregate:Nc(x,t),valueFormat:u,groupLabelFormat:e.groupLabelFormat,mainValueFormat:p,label:e.label,observationLabel:zc(t,d,S),comparison:Wc(t,n,d,S,x)}}function zc(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),s=n.at(-1);return r===void 0||s===void 0?null:{kind:"range",from:r,to:s}}function Wc(e,t,n,r,s){if(e!=="current"||!n)return null;const a=t==="none"?"first":t,o=r.map((i,c)=>({main:i,cross:s[c]??null}));return Pc(o,a)}function Yc(e,t){return t!==null&&e.hasVariable(t)&&e.getType(t)==="temporal"}function Hc(e,t){return t===null||!["numeric","temporal"].includes(e.getType(t))?e:e.orderBy(t)}function X(e){return e==="stack"||e==="fill"}const Uc=3,Kc={line:{stack:!0,dodge:!0,identity:!0,fill:!0},area:{stack:!0,dodge:!0,identity:!0,fill:!0},bar:{stack:!0,fill:!0}};function Xc({scales:e,config:t,layers:n,coordSystem:r,variableLabels:s,colorGroups:a}){if(t.legend.position==="none")return[];const o=new Map(a.map(g=>[E(g.value),g])),i=Qc({scales:e,layers:n}),c=tl(i),l=Te(n,"x"),u=c.map(g=>{if(Jc(g,l,n))return null;const b=rl({group:g,variableLabels:s,layers:n,coordSystem:r,colorGroupsByValue:o});return b.items.length===0?null:{group:g,built:b}}).filter(h);if(u.length===0)return[];const d=jc(u);if(t.legend.position==="auto"&&cl(d,n,r))return[];const p=ll(t.legend.position,d,n,r),m=dl(t.legend.display,p,n,r),y=m==="direct"?fl(n):null;return u.map(({built:g})=>qc(g,p,m,y))}function jc(e){return e.reduce((t,{group:n,built:r})=>{const s=n.some(a=>a.guideType!=="discrete");return t+(s?1:r.items.length)},0)}function qc(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 Qc(e){const{scales:t,layers:n}=e,r=[];for(const s of On){const a=t[s];if(a===void 0||a.kind==="identity"||!Zc(s,n))continue;const o=Te(n,s),i=ml(s,a);r.push({scaleAestheticKey:s,scale:a,variableName:o,guideType:i})}return r}function Zc(e,t){const n=ee(e);return t.some(r=>h(r.mapping[n]))}function Jc(e,t,n){const[r]=e;return r.scaleAestheticKey!=="color"?!1:pa({colorVariableName:r.variableName,xVariableName:t,mapsColorAcrossMultipleLayers:el(r.scaleAestheticKey,n),isMergedWithAnotherAesthetic:e.length>1})}function el(e,t){const n=ee(e);return t.filter(r=>h(r.mapping[n])).length>1}function tl(e){const t=new Map;for(const n of e){const r=pl(n),s=t.get(r);s?s.push(n):t.set(r,[n])}return[...t.values()]}function nl(e,t,n){if(t==="lineType"){e.lineType=n;return}if(t==="color"){e.color=String(n);return}e[t]=n}function rl({group:e,variableLabels:t,layers:n,coordSystem:r,colorGroupsByValue:s}){const a=e[0],o=e.map(u=>ee(u.scaleAestheticKey)),i=ua({scale:a.scale,aesthetics:o,layers:n,coordSystem:r}),c=Bn(a.variableName,t),l=Me({layers:n,scaleType:a.scale.spec.scaleType,variableName:a.variableName});return{aesthetics:e.map(u=>u.scaleAestheticKey),title:c,items:i.map(u=>sl(u,e,o,l,s))}}function sl(e,t,n,r,s){const a={};for(const i of t)nl(a,i.scaleAestheticKey,i.scale.map(e.value));const o=ol(e,t,n,r,s);return{value:e.value,label:al(t,e,s),visual:a,normalizedY:null,swatchShape:e.swatchShape,valueFormat:o}}function al(e,t,n){return e[0].scaleAestheticKey!=="color"?null:n.get(E(t.value))?.label??null}function ol(e,t,n,r,s){if(t[0].scaleAestheticKey==="color")return s.get(E(e.value))?.valueFormat??r;const a=e.owner?.layer,o=il(a,n);return a===void 0||o===null?r:Me({layers:[a],scaleType:t[0].scale.spec.scaleType,variableName:o})}function il(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 cl(e,t,n){if(e>1)return!1;const r=n.type==="polar";return yt(t,["line","area","bar"])||r}function ll(e,t,n,r){if(e!=="auto")return e;if(r.type==="polar")return"top";const s=yt(n,["line","area"]),a=yt(n,["bar"]),o=yt(n,["bar"],c=>X(c.position)),i=t>=Uc;return s&&a?"top":s?i?"right":"top":o?fa(r)?"top":i?"right":"top":"top"}function ul(e){if(e.length!==1)return!1;const t=e[0];return t?Kc[t.geom]?.[t.position]===!0:!1}function dl(e,t,n,r){if(!(t==="right"&&!fa(r)))return"pill";switch(e){case"pill":return"pill";case"direct":return"direct";case"auto":return ul(n)?"direct":"pill"}}function fa(e){return e.type==="cartesian"&&e.mainAxis==="y"}function yt(e,t,n){return e.some(r=>t.includes(r.geom)&&(n?.(r)??!0))}function pl(e){const t=e.scale.domain.map(E);return JSON.stringify([e.variableName,e.guideType,...t])}function ml(e,t){return $n(t)?"discrete":`continuous:${e}`}function fl(e){const t=e[0];if(!t)return new Map;const n=new Map;return t.data.groupBy(z.group).forEach(r=>{const s=r.findLast(l=>h(H(l))||h(C(l)));if(!s)return;const a=Le(s);if(!h(a))return;const o=te(s),i=H(s)??C(s);if(!h(i))return;const c=h(o)?(o+i)/2:i;n.set(String(a),c)}),n}class hl extends de{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=ic(t.originalData),r=Dc({scales:t.scales,layers:t.layers,coordSystem:t.coordSystem,valueLabels:cc(t.originalData,t.layers,n)}),s={scales:t.scales,config:t.config,layers:t.layers,coordSystem:t.coordSystem,variableLabels:n,colorGroups:r},a=Oc(s),o=yl(a,Xc(s));return{axes:Ac(s,o),legends:o,headline:a,panel:{border:{isVisible:t.config.panel.border.isVisible}},colorGroups:r}}}const yl=(e,t)=>e?.kind!=="perGroup"||t.some(r=>r.display==="direct")?t:[],gl=e=>E([Le(e)]),Gn=(e,t)=>{const n=t!==null?e[t]??null:null;return E([n])},j=(e,t)=>{const n=le(t);if(n!==void 0)return()=>n;const r=v(t);return h(r)?s=>{const a=s[r];if(a===void 0)return null;switch(e.getType(r)){case"numeric":return D(a)?a:null;case"categorical":return Ze(a)?a:null;case"temporal":return G(a)?a:null;default:return null}}:()=>null},Ft=(e,t)=>j(e,t.x),ha=(e,t)=>j(e,t.y),bl=(e,t)=>j(e,t.label),ya=(e,t)=>j(e,t.color),vl=(e,t)=>j(e,t.size),xl=(e,t)=>j(e,t.alpha),Sl=(e,t)=>j(e,t.group),wl=(e,t)=>j(e,t.strokeWidth),jr={variable:f.yRaw};function Rt(e,t){return X(e)?jr:t.y??jr}function Nt(e){return j(e.data,Rt(e.position,e.mapping))}const Al=["lt","lte","gt","gte","range"];function gt(e,t){if("and"in e){const n=e.and.map(r=>gt(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=>gt(r,t));return r=>{for(const s of n)if(s(r))return!0;return!1}}if("not"in e){const n=gt(e.not,t);return r=>!n(r)}return Tl(e,t)}function bt(e,t){if("and"in e){for(const r of e.and)bt(r,t);return}if("or"in e){for(const r of e.or)bt(r,t);return}if("not"in e){bt(e.not,t);return}const n=Ml(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 qr=()=>!1;function Tl(e,t){if(!t.hasVariable(e.variable))return qr;const n=t.getType(e.variable);if("eq"in e){const r=oe(e.eq,n,t.parsingLocale);return s=>Qr(t.readValue(s,e.variable),r)}if("oneOf"in e){const r=e.oneOf.map(s=>oe(s,n,t.parsingLocale));return s=>{const a=t.readValue(s,e.variable);for(const o of r)if(Qr(a,o))return!0;return!1}}if("lt"in e){const r=oe(e.lt,n,t.parsingLocale);return s=>Ie(t.readValue(s,e.variable),r)==="less"}if("lte"in e){const r=oe(e.lte,n,t.parsingLocale);return s=>{const a=Ie(t.readValue(s,e.variable),r);return a==="less"||a==="equal"}}if("gt"in e){const r=oe(e.gt,n,t.parsingLocale);return s=>Ie(t.readValue(s,e.variable),r)==="greater"}if("gte"in e){const r=oe(e.gte,n,t.parsingLocale);return s=>{const a=Ie(t.readValue(s,e.variable),r);return a==="greater"||a==="equal"}}if("range"in e){const[r,s]=e.range,a=oe(r,n,t.parsingLocale),o=oe(s,n,t.parsingLocale);return i=>{const c=t.readValue(i,e.variable),l=Ie(c,a),u=Ie(c,o);return l==="incomparable"||u==="incomparable"?!1:(l==="greater"||l==="equal")&&(u==="less"||u==="equal")}}return qr}function Ml(e){for(const t of Al)if(t in e)return t;return null}function Ie(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 D(e)&&D(t)?e<t?"less":e>t?"greater":"equal":"incomparable"}function Qr(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:Rn(e,void 0,n)}const Ll={bar:"observation-rerender",rule:null,line:"overlay-anchor",area:"overlay-anchor",point:"overlay-anchor"};function ga(e){const t=Ll[e];return t===null?null:{strategy:t,composition:ba()}}function ba(){return{isDimmed:!1,matchedLayer:null,overlayCandidates:[]}}class Vl extends Re{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:o})=>o===void 0||o===t.id);if(s.length===0)return t;const a=El({layer:t,highlights:s,parsingLocale:n.config.parsingLocale,strategy:r.strategy});return{...t,highlight:{...r,composition:a}}}}function El({layer:e,highlights:t,parsingLocale:n,strategy:r}){for(const T of t)bt(T.predicate,e.data);const s=v(e.mapping.x),a=Il(e,n),o=t.map(T=>({predicate:gt(T.predicate,a),scope:T.scope})),i=o.some(({scope:T})=>T==="series"),c=o.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,y=new Uint8Array(u),g=new Set,b=new Set;let x=!1,S=0;for(const T of e.data){let ne,he;d!==null&&(ne=gl(T),d[S]=ne),p!==null&&(he=Gn(T,s),p[S]=he),m!==null&&(m[S]=T);for(const{predicate:ot,scope:it}of o)if(ot(T))switch(it){case"series":ne!==void 0&&g.add(ne);break;case"x-value":he!==void 0&&b.add(he);break;case"data-point":y[S]=1,x=!0;break}S++}if(g.size===0&&b.size===0&&!x)return ba();const w=new Uint8Array(u),k=[];let W=0;for(let T=0;T<u;T++){const ne=d?.[T],he=p?.[T],ot=ne!==void 0&&g.has(ne),it=he!==void 0&&b.has(he),Rr=y[T]===1;if(r==="observation-rerender")(ot||Rr||it)&&(w[T]=1,W++);else if(ot)w[T]=1,W++;else if(Rr||it){const Nr=m?.[T];Nr!==void 0&&k.push({observation:Nr,observationIndex:T})}}const q=W>0?{...e,data:e.data.filterByMask(w)}:null;return{isDimmed:(r==="observation-rerender"||g.size>0)&&q!==null,matchedLayer:q,overlayCandidates:k}}function Il(e,t){const n=v(e.mapping.y),r=Nt(e);return{hasVariable:s=>e.data.hasVariable(s),getType:s=>e.data.getType(s),readValue:(s,a)=>n!==null&&a===n?r(s):s[a]??null,parsingLocale:t}}class kl extends Re{constructor(t,n,r,s,a){super(),this.transformCompiler=t,this.statCompiler=n,this.groupCompiler=r,this.geomCompiler=s,this.positionAdjusterCompiler=a}dependencies(t){return[t.data,t.mapping,Zr(t)]}compileLayer(t,n){const r=this.transformCompiler.compile({data:n.data,transforms:t.transforms}),s={...n.mapping,...t.mapping};return this.runLayerPipeline(t,r,s,Zr(n))}runLayerPipeline(t,n,r,s){return{...It({data:n,mapping:r}).pipe(({data:o,mapping:i})=>{const c=this.statCompiler.compute(t.stat,{data:o,mapping:i,xScaleIsDiscrete:s});return{data:c.data,mapping:{...i,...c.mapping}}}).pipe(({data:o,mapping:i})=>({data:this.groupCompiler.compute({data:o,mapping:i}).data,mapping:i})).pipe(({data:o,mapping:i})=>{const c=this.geomCompiler.compile(t.geom,{data:o,mapping:i,params:t.params});return{data:c.data,mapping:{...i,...c.mapping}}}).pipe(({data:o,mapping:i})=>{const c=this.positionAdjusterCompiler.adjust(t.position,{data:o,mapping:i});return{data:c.data,mapping:{...i,...c.mapping}}}).result(),id:t.id,geom:t.geom,position:t.position,yScaleType:t.yScaleType,params:t.params,interactive:t.interactive,dataLabels:t.dataLabels,summary:{},highlight:ga(t.geom)}}}function Zr(e){return e.scales.some(t=>t.scaledAesthetic==="x"&&t.scaleType==="discrete")}class va extends Error{constructor(t){const n=t.map(r=>`- ${r.message}`).join(`
|
|
2
2
|
`);super(`Spec validation failed:
|
|
3
|
-
${n}`),this.issues=t,this.name="SpecValidationError"}}class Cl{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}),a={...t.mapping,...r.mapping};n.push(...this.validator.validate({layerId:r.id,geom:r.geom,stat:r.stat,effectiveMapping:a,data:s,coordType:t.coords.coordType}))}if(n.length>0)throw new ba(n)}}class Dl{constructor(t,n){this.geomRegistry=t,this.statRegistry=n}validate(t){return[...this.validateRequiredAesthetics(t),...this.validateVariableExistence(t),...this.validateRuleMapping(t),...this.validateRuleCoord(t)]}validateRequiredAesthetics({layerId:t,geom:n,stat:r,effectiveMapping:s}){const a=[],{requiredAesthetics:o}=this.geomRegistry.get(n),{computedVariables:i}=this.statRegistry.get(r.type);for(const c of o)i.has(c)||h(s[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:s}){const a=[],{computedVariables:o}=this.statRegistry.get(n.type);for(const[i,c]of Object.entries(r)){if(o.has(i))continue;const l=v(c);l!==null&&(s.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}validateRuleMapping({layerId:t,geom:n,stat:r,effectiveMapping:s}){if(n!=="rule")return[];const{computedVariables:a}=this.statRegistry.get(r.type),o=a.has("x"),i=a.has("y"),c=le(s.x),l=le(s.y),u=o||D(c),d=i||D(l);return u&&d?[{code:"INVALID_RULE_MAPPING",message:`Layer '${t}': rule geom requires exactly one of 'x' or 'y', both were provided`,layerId:t}]:!u&&!d?[{code:"INVALID_RULE_MAPPING",message:`Layer '${t}': rule geom requires a numeric value on 'x' or 'y'`,layerId:t}]:[]}validateRuleCoord({layerId:t,geom:n,coordType:r}){return n==="rule"&&r==="polar"?[{code:"INVALID_RULE_COORD",message:`Layer '${t}': rule geom is not supported under polar coords`,layerId:t}]:[]}}class _l{constructor(t){this.registry=t}adjust(t,n){return this.registry.get(t).adjust(n)}}class Pt{}class Fl extends Pt{constructor(){super(...arguments),this.type="dodge"}adjust({data:t,mapping:n}){if(!v(n.x))return{data:t,mapping:{}};const s=t.getValues(z.group,{type:"categorical",distinct:!0,skipNulls:!0});if(s.length===0)return{data:t,mapping:{}};const a=t.size(),o=t.getValues(z.group,{type:"categorical"}),i=sa/2,c=s.length>1?Zi:0,l=ce.scaleBand().domain(s.map(String)).range([-i,i]).paddingInner(c).paddingOuter(0),u=l.bandwidth(),d=new Array(a).fill(null),p=new Array(a).fill(null);for(let y=0;y<a;y++){const g=o[y];if(!h(g))continue;const b=l(String(g));h(b)&&(d[y]=b,p[y]=b+u)}return{data:t.addVariable(f.xMin,"numeric",d).addVariable(f.xMax,"numeric",p),mapping:{}}}}const Zr=A("__ungrouped__"),va=(e,t)=>{const n=v(t.x),r=v(t.y);if(!n||!r)return null;const s=e.getValues(z.group,{type:"categorical",distinct:!0,skipNulls:!0}),a=s.length===0,o=a?[Zr]:s,i=e.getValues(n),c=e.getValues(r,{type:"numeric"}),l=e.getValues(z.group,{type:"categorical"}),u=e.size(),d=new Map;for(let p=0;p<u;p++){const m=i[p]??null,y=l[p],g=a?Zr:y;if(!h(g))continue;let b=d.get(m);b||(b=new Map,d.set(m,b)),b.set(g,p)}return{yValues:c,observationIndexByXAndGroup:d,uniqueGroupKeys:o,observationCount:u}};class Rl extends Pt{constructor(){super(...arguments),this.type="fill"}adjust({data:t,mapping:n}){const r=va(t,n);if(r===null)return{data:t,mapping:{}};const{yValues:s,observationIndexByXAndGroup:a,uniqueGroupKeys:o,observationCount:i}=r,c=[...s],l=new Array(i).fill(0);for(const[,d]of a){let p=0,m=0;for(const b of o){const x=d.get(b);if(x===void 0)continue;const S=s[x];S!=null&&(S>=0?p+=S:m-=S)}let y=0,g=0;for(const b of o){const x=d.get(b);if(x===void 0)continue;const S=s[x];if(S===void 0)continue;if(S===null){l[x]=null,c[x]=null;continue}const w=S>=0?p:m;if(w===0){l[x]=0,c[x]=0;continue}const k=S/w;S>=0?(l[x]=y,c[x]=y+=k):(c[x]=g,l[x]=g+=k)}}return{data:t.addVariable(f.yMin,"numeric",l).addVariable(f.yMax,"numeric",c).addVariable(f.yRaw,"numeric",s),mapping:{}}}}class Nl extends Pt{constructor(){super(...arguments),this.type="identity"}adjust({data:t}){return{data:t,mapping:{}}}}class Pl extends Pt{constructor(){super(...arguments),this.type="stack"}adjust({data:t,mapping:n}){const r=va(t,n);if(r===null)return{data:t,mapping:{}};const{yValues:s,observationIndexByXAndGroup:a,uniqueGroupKeys:o,observationCount:i}=r,c=[...s],l=new Array(i).fill(0);for(const[,p]of a){let m=0,y=0;for(const g of o){const b=p.get(g);if(b===void 0)continue;const x=s[b];if(x!==void 0){if(x===null){l[b]=null,c[b]=null;continue}x>=0?(l[b]=m,c[b]=m+=x):(c[b]=y,l[b]=y+=x)}}}let u=t.addVariable(f.yMin,"numeric",l).addVariable(f.yMax,"numeric",c).addVariable(f.yRaw,"numeric",s);const d=v(n.y);return d!==null&&(u=u.addVariable(d,"numeric",c)),{data:u,mapping:{}}}}class Ol extends Ne{constructor(){super("position"),this.register("identity",new Nl),this.register("stack",new Pl),this.register("fill",new Rl),this.register("dodge",new Fl)}}class Bl{map({data:t,layer:n,getPositionScale:r}){const s=v(n.mapping.x),a=r("x");if(!s||!a)return t;const i=t.getValues(s).map(c=>h(c)?a.map(c):null);return t.addVariable(f.x,"numeric",i)}}class $l{map({data:t,getPositionScale:n}){const r=n("x");if(!r?.bandwidth||!t.hasVariable(f.x)||!t.hasVariable(f.xMin)||!t.hasVariable(f.xMax))return t;const s=t.getValues(f.x,{type:"numeric"}),a=t.getValues(f.xMin,{type:"numeric"}),o=t.getValues(f.xMax,{type:"numeric"}),i=t.size(),c=new Array(i),l=new Array(i);for(let u=0;u<i;u++){const d=s[u],p=a[u],m=o[u];h(d)&&h(p)&&h(m)?(c[u]=d+p*r.bandwidth,l[u]=d+m*r.bandwidth):(c[u]=null,l[u]=null)}return t.addVariable(f.xMin,"numeric",c).addVariable(f.xMax,"numeric",l)}}class Gl{map({data:t,layer:n,getPositionScale:r}){const s=v(n.mapping.y),a=Oe(n.yScaleType),o=r(a);if(!s||!o)return t;const c=t.getValues(s).map(l=>h(l)?o.map(l):null);return t.addVariable(f.y,"numeric",c)}}class zl{map({data:t,layer:n,getPositionScale:r}){const s=Oe(n.yScaleType),a=r(s);if(!a||!t.hasVariable(f.yMin)||!t.hasVariable(f.yMax))return t;const o=t.getValues(f.yMin,{type:"numeric"}),i=t.getValues(f.yMax,{type:"numeric"}),c=t.size(),l=new Array(c),u=new Array(c);for(let d=0;d<c;d++){const p=o[d],m=i[d];h(p)&&h(m)?(l[d]=a.map(p),u[d]=a.map(m)):(l[d]=null,u[d]=null)}return t.addVariable(f.yMin,"numeric",l).addVariable(f.yMax,"numeric",u)}}const Wl=[new Bl,new Gl,new $l,new zl];function Yl(e,t){const n=e[t];return n?.kind==="position"?n:null}class Hl extends Re{constructor(t=Wl){super(),this.mappers=t}dependencies(t){return[t.scales.x,t.scales.y,t.scales.ySecondary]}compileLayer(t,n){const r=a=>Yl(n.scales,a);let s=t.data;for(const a of this.mappers)s=a.map({data:s,layer:t,getPositionScale:r});return{...t,data:s}}}class Ul extends de{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),s={};for(const[a,o]of n){const i=r.get(a)??[],c=this.registry.get(o.scaleType);s[a]=c.compile(o,i)}return s}validateScaleTypeCompatibility(t){const n=[];for(const r of t.scales){const{compatibleDataTypes:s}=this.registry.get(r.scaleType),a=ee(r.scaledAesthetic),o=t.layers.find(l=>h(l.mapping[a]));if(!o)continue;const i=v(o.mapping[a]);if(!h(i)||!o.data.hasVariable(i))continue;const c=o.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: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 ba(n)}collectValues(t,n){const r=new Map;for(const s of t)for(const[a,o]of Object.entries(s.mapping)){const i=a,c=i==="y"?Oe(s.yScaleType):i;if(!oc(c)||!n.has(c))continue;const l=this.resolveVariables(i,o,s.data);this.collectFromVariables(s.data,l,c,r)}return r}resolveVariables(t,n,r){if(t==="y"&&this.hasPositionAdjustedY(r))return[f.yMin,f.yMax];const s=v(n);return!s||!r.hasVariable(s)?[]:[s]}hasPositionAdjustedY(t){return t.hasVariable(f.yMin)&&t.hasVariable(f.yMax)}collectFromVariables(t,n,r,s){if(n.length===0)return;let a=[];for(const i of n)a=a.concat(t.getValues(i));const o=s.get(r);s.set(r,o?o.concat(a):a)}}class tt{createPositionScale(t,n){return{kind:"position",aesthetic:ee(t.scaledAesthetic),spec:t,...n}}createVisualScale(t,n){return{kind:"visual",aesthetic:ee(t.scaledAesthetic),spec:t,...n}}}class Kl extends tt{constructor(){super(...arguments),this.compatibleDataTypes=["numeric"]}compile(t,n){if(t.scaleType!=="continuous")throw new Error("ContinuousScale.compile received non-continuous spec");const r=_t(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 a of t)typeof a=="number"&&(a<r&&(r=a),a>s&&(s=a));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 a=r.transform==="log"&&Xl(s),o=a?ce.scaleLog():r.transform==="sqrt"?ce.scaleSqrt():ce.scaleLinear();return r.nice&&!a&&(s=o.copy().domain(s).nice().domain()),o.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:a=>a&&"count"in a?s.ticks(a.count):s.ticks()})}buildVisualScale(t,n){const r=n.range??[0,1],s=n.reverse?[r[1],r[0]]:r,a=this.createD3Scale(t,s,n);return this.createVisualScale(n,{map:a,domain:a.domain(),generateTicks:o=>o&&"count"in o?a.ticks(o.count):a.ticks()})}}const Xl=e=>{const[t,n]=e;return t>0&&n>0||t<0&&n<0};class jl extends tt{constructor(){super(...arguments),this.compatibleDataTypes=["temporal"]}compile(t,n){if(t.scaleType!=="datetime")throw new Error("DatetimeScale.compile received non-datetime spec");const r=_t(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 a=s.getTime();n.has(a)||(n.add(a),r.push(s))}return r.sort((s,a)=>s.getTime()-a.getTime()),r}computeDataDomain(t){let n=1/0,r=-1/0;for(const s of t){if(!(s instanceof Date))continue;const a=s.getTime();a<n&&(n=a),a>r&&(r=a)}return n===1/0?[]:[new Date(n),new Date(r)]}createD3Scale(t,n,r){const s=ql(t)?t:[],a=ce.scaleUtc().domain(s).range(n).clamp(r.clamp);if(r.nice&&a.nice(),h(r.domainMin)||h(r.domainMax)){const[o,i]=a.domain();o!==void 0&&i!==void 0&&a.domain([r.domainMin??o,r.domainMax??i])}return a}buildScale(t,n,r){const s=n.reverse?[1,0]:[0,1],a=this.createD3Scale(t,s,n),[o,i]=a.domain(),c=o&&i?r.filter(l=>l>=o&&l<=i):[];return this.createPositionScale(n,{map:a,domain:a.domain(),bandwidth:null,generateTicks:l=>l&&"atInputs"in l?c:l&&"interval"in l?o&&i?mc(o,i,l.interval):[]:a.ticks(l?.count)})}}const ql=e=>e.length===2&&G(e[0])&&G(e[1]),ke={transform:"linear",reverse:!1,nice:!0,zero:!1,domainMin:null,domainMax:null},Jr={size:[4,20],alpha:[.1,1],strokeWidth:[1,4]},lt={domainMin:null,domainMax:null,nice:!1,reverse:!1},Ye={range:null,domain:null,padding:.1,reverse:!1},Ql={palette:{type:"default"}};class Zl extends tt{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=_t(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 a of t)r.has(a)||(r.add(a),s.push(a));return s}buildPositionScale(t,n){const r=t.map(String),s=n.padding??Ye.padding,a=n.reverse?[1,0]:[0,1],o=ce.scaleBand().domain(r).range(a).paddingInner(s).paddingOuter(s/2),i=o.bandwidth()/2;return this.createPositionScale(n,{map:c=>(o(String(c))??0)+i,domain:t,bandwidth:o.bandwidth(),generateTicks:()=>[...t]})}buildVisualScale(t,n){const r=t.map(String),s=n.range&&n.range.length>0?ce.scaleOrdinal().domain(r).range(n.range).unknown(n.range[0]):null;return this.createVisualScale(n,{map:a=>{const o=String(a);return s?s(o):o},domain:t,generateTicks:()=>t})}}class Jl extends tt{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:ee(t.scaledAesthetic),spec:t,map:n=>n,domain:[],generateTicks:()=>[]}}}const xa=["grey","red","orange","yellow","green","cyan","blue","purple","pink"],Sa=["cyan","pink","purple","red","orange","yellow","green","blue"],wa=["#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"},eu=[Q.purple,Q.pink,Q.yellow,Q.blue,Q.red,Q.cyan,Q.orange,Q.plum,Q.green,Q.dark_purple],K={green:"#B2DDC9",cyan:"#A2D5E2",blue:"#AAC4FF",purple:"#B2A4FF",plum:"#DCA8C7",pink:"#FFCCD3",red:"#FFADAD",orange:"#FFDEB4",yellow:"#FDF7C3"},tu=[K.green,K.purple,K.red,K.cyan,K.pink,K.blue,K.orange,K.plum,K.yellow],An={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"},nu=[An.grey200,K.green,K.red,An.grey200],es={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]}},Y={cyan:"#22D3EE",pink:"#F377EF",purple:"#6528F7",red:"#FB2576",orange:"#FF9300",yellow:"#FBFF00",green:"#06FF00",blue:"#0079FF"},ut=[Y.cyan,Y.pink,Y.purple,Y.red,Y.orange,Y.yellow,Y.green,Y.blue],ru=[Y.cyan,Y.green,Y.red,Y.cyan],dt={start:"#84D1FC",positive:"#84FC89",negative:"#FC8497",total:"#84D1FC"},su=[dt.start,dt.positive,dt.negative,dt.total];function au(e,t="light",n){return((n!==void 0?es[t][n]:void 0)??es[t].default).map(s=>An[`${e}${s}`])}function ou(e){const t=ut.indexOf(Y[e]);return t<=0?ut:[...ut.slice(t),...ut.slice(0,t)]}function iu(e,t){switch(e.type){case"default":return wa;case"graphy":return e.variant==="waterfall"?su:eu;case"pastel":return e.variant==="waterfall"?nu:tu;case"neon":return e.variant==="waterfall"?ru:ou(e.base);case"mono":return au(e.base,e.variant??"light",t);case"custom":return e.colors}}function cu(e,t){if(!t)return e;const n=[...e];for(const[r,s]of Object.entries(t)){const a=Number(r);if(!Number.isInteger(a)||a<1)continue;const o=a-1;o<n.length&&(n[o]=s)}return n}function lu(e,t,n){if(!e)return;const r=t?.type==="custom"?n[t.id]:void 0,s={};for(const[a,o]of Object.entries(e)){const i=Number(a);if(!(!Number.isInteger(i)||i<1)){if(o.hex!==void 0){s[i]=o.hex;continue}if(o.id!==void 0){const c=r?.find(l=>l.id===o.id)?.hex;c!==void 0?s[i]=c:console.warn(`[viz-engine] palette override at slot ${i} with id '${o.id}' did not resolve against the active palette — falling back to palette color.`)}}}return Object.keys(s).length>0?s:void 0}function uu(e,t){if(!e)return Ql.palette;if(e.type==="custom"){const n=t[e.id];if(!n)throw new Error(`Custom palette with id "${e.id}" not found`);const r=n.map(s=>s.hex);return{type:"custom",id:e.id,colors:r}}return e}class du extends tt{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=iu(t.palette,r.length),a=s.length>0?s:[...wa],o=cu(a,t.overrides),i=ce.scaleOrdinal().domain(r.map(String)).range(o).unknown(o[0]);return this.createVisualScale(t,{map:c=>i(String(c)),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 pu extends Ne{constructor(){super("scale"),this.register("continuous",new Kl),this.register("discrete",new Zl),this.register("datetime",new jl),this.register("identity",new Jl),this.register("palette",new du)}}const Aa=e=>!("layers"in e),_={point:mu,line:fu,area:hu,bar:yu,rule:gu};function mu(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 fu(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 hu(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 yu(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 gu(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 zn={identity:vu,count:xu,smooth:bu,mean:Su};function bu(e){return{type:"smooth",method:e.method,order:e.order,bandwidth:e.bandwidth}}function vu(){return{type:"identity"}}function xu(){return{type:"count"}}function Su(){return{type:"mean"}}const xe={reshape:wu,filter:Au,sort:Tu,aggregate:Mu,constant:Lu};function wu(e={}){return{type:"transform",transformType:"reshape",options:e}}function Au(e){return{type:"transform",transformType:"filter",options:e}}function Tu(e){return{type:"transform",transformType:"sort",options:e}}function Mu(e){return{type:"transform",transformType:"aggregate",options:e}}function Lu(e){return{type:"transform",transformType:"constant",options:e}}const ts="#%_ENCODED_%#",Ta=e=>{if(!e.startsWith(ts))return e;try{const{value:t}=JSON.parse(e.slice(ts.length));return typeof t=="string"?t:e}catch{return e}},Vu=({annotations:e,dataset:t,mapping:n})=>{const r=[],s=[],a=[],o=[],i=[],c=[],l=[],u=v(n.x);for(const d of e??[])switch(d.type){case"difference-arrow":{const p=Eu(d,u,t);p!==null&&r.push(p);break}case"shape":{s.push(Iu(d));break}case"arrow":{a.push(_u(d));break}case"highlight":break;case"text":{o.push(ku(d));break}case"sticker":{const p=Cu(d,u,t);p!==null&&i.push(p);break}case"tooltip":{const p=Du(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:a,textAnnotations:o,stickers:i,pinnedNumbers:c,comments:l}},Eu=(e,t,n)=>{const r=Mt({dataset:n,input:e.start,anchorVariable:t}),s=Mt({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}},Iu=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}),ku=e=>({id:e.id,content:e.content,x:e.x,y:e.y,width:e.width,backgroundColor:e.backgroundColor??null,backgroundColorStyle:e.backgroundColorStyle}),Cu=(e,t,n)=>{const r=Mt({dataset:n,input:e,anchorVariable:t});return r===null?null:{id:e.id,anchor:r,sticker:e.sticker}},Du=(e,t,n)=>{const r=Mt({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}}},_u=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}),Mt=({dataset:e,input:t,anchorVariable:n})=>{if(!h(t)||!h(t.columnKey))return null;const r=Fu(t,n,e);return r===null?null:{anchorValue:r,groupValue:Ta(t.columnKey)}},Fu=(e,t,n)=>e.rowValue!==void 0?e.rowValue:t===null||!h(e.rowIndex)||!n.hasVariable(t)?null:n.getValues(t)[e.rowIndex]??null,Ma=["lilac","neon_pink","blackberry","sun","iceland","sunset","ultraviolet","purple","ice_cream","mint","cool","fresh"];function La(e){return{type:"config",config:e}}const Ru="#E5E5E5",Nu={x:"top",y:"left"},Pu=new Set(["pie","donut"]);function Ou(e){return La({legend:Wu(e.legend),axes:Hu(e.axes),headline:Uu(e),numberFormat:Ku(e.appearance),content:Xu(e.content),appearance:Bu(e.appearance,e.themeOverrides)}).config}function Bu(e,t){const n=zu(e?.border),r=e?.hasRoundedCorners===!1?0:void 0,s=$u(e,t),a={};return e?.textScale!==void 0&&(a.textScale=e.textScale),n!==void 0&&(a.border=n),r!==void 0&&(a.cornerRadius=r),s!==void 0&&(a.background=s),e?.highlightStyle!==void 0&&(a.highlightStyle=e.highlightStyle==="grey"?"desaturate":"dim"),Object.keys(a).length>0?a:void 0}function $u(e,t){if(e?.backgroundModifier==="tint")return{type:"tinted"};const n=t?.graphBackground;if(typeof n=="string")return{type:"solid",color:n}}const Gu=e=>Ma.includes(e);function zu(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:Ru,width:t};if(e.style==="preset")return e.color===void 0||!Gu(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 Wu(e){if(e)return{position:e.position}}function ns(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:Nu[e]}:void 0,...t?.tickDisplayMode?{labels:{mode:t.tickDisplayMode}}:void 0,...n!==void 0?{grid:{isVisible:n}}:void 0}}function Yu(e){return{...e.label!==void 0?{label:e.label}:void 0}}function Hu(e){if(e)return{x:ns("x",e.x,e.showGridLines),y:ns("y",e.y,e.showGridLines),...e.y2?{ySecondary:Yu(e.y2)}:void 0}}function Uu(e){const{headlineNumbers:t,options:n,type:r}=e,s=r!==void 0&&Pu.has(r)?n?.pieTotalPosition:void 0;if(t===void 0&&s===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),s!==void 0&&(a.show="total",a.position=s==="center"?"center":"above"),a}function Ku(e){if(e?.numberFormat)return{decimals:e.numberFormat.decimalPlaces,abbreviation:e.numberFormat.abbreviation}}function Xu(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=ju(e.source);return n!==void 0&&(t.source=n),e.isSourceHidden!==void 0&&(t.isSourceVisible=!e.isSourceHidden),t}function ju(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})},qu={showDataLabels:!1,format:"absolute",showStackTotals:!1,showCategoryLabels:!1,labelSource:{variable:f.yRaw}},vt={stat:{type:"identity"},position:"identity",params:{size:8}},rn={stat:{type:"identity"},position:"identity",params:{lineWidth:"auto",interpolate:"linear",missingValues:"gap"}},sn={stat:{type:"identity"},position:"stack",params:{lineWidth:"auto",interpolate:"linear",missingValues:"zero"}},an={stat:{type:"identity"},position:"dodge",params:{}},Ge={stat:{type:"identity"},position:"identity",interactive:!1,params:{strokeWidth:1,lineType:"dashed",labelPosition:"start"}},nt="primary";function Qu(e,t){const n={...qu};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 xt(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 He(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"identity"}}function St(e,t){return{type:"scale",scaledAesthetic:e,scaleType:"inferred",options:t}}function Va(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"palette",palette:t.palette,overrides:t.overrides}}const Se={x:Object.assign(e=>St("x",e),{continuous:e=>F("x",e),discrete:e=>Z("x",e),datetime:e=>xt("x",e),log:e=>F("x",{...e,transform:"log"}),sqrt:e=>F("x",{...e,transform:"sqrt"})}),y:Object.assign(e=>St("y",e),{continuous:e=>F("y",e),discrete:e=>Z("y",e),datetime:e=>xt("y",e),log:e=>F("y",{...e,transform:"log"}),sqrt:e=>F("y",{...e,transform:"sqrt"})}),ySecondary:Object.assign(e=>St("ySecondary",e),{continuous:e=>F("ySecondary",e),discrete:e=>Z("ySecondary",e),datetime:e=>xt("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=>Va("color",e)},size:{continuous:e=>F("size",e),discrete:e=>Z("size",e),identity:e=>He("size",e)},alpha:{continuous:e=>F("alpha",e),discrete:e=>Z("alpha",e),identity:e=>He("alpha",e)},strokeWidth:{continuous:e=>F("strokeWidth",e),discrete:e=>Z("strokeWidth",e),identity:e=>He("strokeWidth",e)},lineType:{discrete:e=>Z("lineType",e),identity:e=>He("lineType",e)}},U="key",se="value",rs=A("lineSeriesLabel"),ss=A("barSeriesLabel"),Lt=A("constantY"),Zu=(e,t,n,r)=>ad[t](e,n,r),Wn=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]:""},Yn=e=>{const t=Wn(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:U,valueName:se}),mapping:{x:t,y:se,color:U},seriesVariables:r}},Hn=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 a=t[s]?.lineStyle;return a?{mapping:{lineType:{value:a}},scales:[]}:{mapping:{},scales:[]}}const r=e.seriesVariables.map(s=>t[s]?.lineStyle??"solid");return{mapping:{lineType:U},scales:[Se.lineType.discrete({domain:e.seriesVariables,range:r})]}},Ju=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 a=r.slice(1);return a.length===0?{dataset:e.addConstantVariable(Lt,"categorical",""),mapping:{x:s,y:Lt,label:t[0]}}:a.length===1?{dataset:e,mapping:{x:s,y:a[0]??"",label:t[0]}}:{dataset:e.reshapeFromWideToLong({keep:[s,...t,...n],keyName:U,valueName:se}),mapping:{x:s,y:se,label:t[0],color:U}}},ed=e=>{const{categorical:t,temporal:n,numeric:r}=e.groupVariableNamesByType();let s,a;if(h(t[0])&&h(r[0]))s=t[0],a=r[0];else if(h(n[0])&&h(r[0]))s=n[0],a=r[0];else if(h(r[0])&&h(r[1]))s=r[0],a=r[1];else throw new Error("No label or value variable found");return{x:"",y:a,color:s}},Ea=(e,t,n)=>{const{dataset:r,mapping:s,seriesVariables:a}=Yn(e.dataset),o=Hn({appearance:n,seriesVariables:a}),i=[_.line({params:{lineWidth:t?.lineThickness,interpolate:t?.isSmoothLine?"catmull-rom":"linear",missingValues:t?.missingValues}})];return t?.showPoints&&i.push(_.point({params:{size:Ia(t.pointSize)},interactive:!1})),{dataset:r,layers:i,coords:B.cartesian(),mapping:{...s,...o.mapping},scales:o.scales,seriesVariables:a}},td=(e,t,n)=>{const{dataset:r,mapping:s,seriesVariables:a}=Yn(e.dataset),o=Hn({appearance:n,seriesVariables:a}),i=[_.area({position:"stack",params:{lineWidth:t?.lineThickness,interpolate:t?.isSmoothLine?"catmull-rom":"linear",missingValues:t?.missingValues}})];return t?.showPoints&&i.push(_.point({params:{size:Ia(t.pointSize)},position:"stack",interactive:!1})),{dataset:r,layers:i,coords:B.cartesian(),mapping:{...s,...o.mapping},scales:o.scales,seriesVariables:a}},ge=(e,t,n,r,s)=>{const{dataset:a,mapping:o,seriesVariables:i}=Yn(e.dataset),c=[];if(r?.sortBars){const l=v(o.y);l!==null&&l!==""&&c.push(xe.sort({variableName:l,direction:"desc"}))}if(!s?.useSingleColorForBars){const l=Wn(e.dataset),{numeric:u}=e.dataset.groupVariableNamesByType();u.filter(p=>p!==l).length===1&&e.dataset.getType(l)==="categorical"&&(o.color=l)}return{dataset:a,layers:[_.bar({position:t})],coords:n,mapping:o,scales:[],transforms:c,seriesVariables:i}},as=(e,t)=>({dataset:e.dataset,layers:[_.bar({position:"fill"})],coords:B.polar({theta:"y",innerRadius:t==="donut"?.55:0}),mapping:ed(e.dataset),scales:[],seriesVariables:[]}),nd=e=>{const{dataset:t,mapping:n}=Ju(e.dataset);return{dataset:t,layers:[_.point()],coords:B.cartesian(),mapping:n,scales:[],seriesVariables:[]}},rd=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(Lt,"categorical",""),o={x:r,y:t[1]??Lt,size:t[2],label:n[0]},i=[];return h(o.size)&&i.push(Se.size.continuous()),{dataset:a,layers:[_.point()],coords:B.cartesian(),mapping:o,scales:i,seriesVariables:[]}},on=(e,t,n)=>{const r=n?.seriesStyles?.[e]?.lineStyle;return _.line({transforms:[xe.constant({variableName:rs,type:"categorical",value:e})],aes:{y:e,color:rs,...r?{lineType:{value:r}}:{}},...t?{yScaleType:"secondary"}:void 0})},sd=(e,t,n)=>{const{numeric:r,categorical:s,temporal:a}=e.dataset.groupVariableNamesByType(),o=Wn(e.dataset),i=[...s,...a],c=r.filter(b=>b!==o),l=t?.comboType??"grouped-bars",u=l==="lines";if(c.length===1)return u?Ea(e,t,n):ge(e,"dodge",B.cartesian(),t,n);const d=e.axes?.hasDualYAxis===!0,p=u?[]:c.slice(0,-1),m=u?c:c.slice(-1),y=[],g=[];if(p.length>0){const b=l==="stacked-bars"?"stack":"dodge",x=p.length===1?p[0]:null;h(x)?y.push(_.bar({transforms:[xe.constant({variableName:ss,type:"categorical",value:x})],aes:{y:x,color:ss},position:b})):y.push(_.bar({transforms:[xe.reshape({keep:i,reshape:p,keyName:U,valueName:se})],aes:{y:se,color:U},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))y.push(on(x,!1,n));else{const S=Hn({appearance:n,seriesVariables:b});y.push(_.line({transforms:[xe.reshape({keep:i,reshape:b,keyName:U,valueName:se})],aes:{y:se,color:U,...S.mapping}})),g.push(...S.scales)}if(d){const S=m[m.length-1];h(S)&&y.push(on(S,!0,n))}}else for(const b of m)y.push(on(b,d,n));return{dataset:e.dataset,layers:y,coords:B.cartesian(),mapping:{x:o},scales:g,seriesVariables:c}},Ia=(e="auto")=>e==="auto"?vt.params.size:e,ze=e=>()=>{throw new Error(`Unsupported graph type: ${e}`)},ad={line:(e,t,n)=>Ea(e,t,n),areaStacked:(e,t,n)=>td(e,t,n),bar:(e,t,n)=>ge(e,"dodge",B.flip(),t,n),barStacked:(e,t,n)=>ge(e,"stack",B.flip(),t,n),barStackedFill:(e,t,n)=>ge(e,"fill",B.flip(),t,n),column:(e,t,n)=>ge(e,"dodge",B.cartesian(),t,n),columnStacked:(e,t,n)=>ge(e,"stack",B.cartesian(),t,n),columnStackedFill:(e,t,n)=>ge(e,"fill",B.cartesian(),t,n),pie:e=>as(e,"pie"),donut:e=>as(e,"donut"),scatter:e=>nd(e),bubble:e=>rd(e),combo:(e,t,n)=>sd(e,t,n),funnel:ze("funnel"),heatmap:ze("heatmap"),waterfall:ze("waterfall"),mekko:ze("mekko"),table:ze("table")},ka=["key",A("lineSeriesLabel"),A("barSeriesLabel")];function od(e){const t=e.annotations??[],n=id(e.mapping),r=ud(e.convertedDataset,e.layers),s=[];for(const a of t){if(a.type!=="highlight")continue;const o=cd({annotation:a,rowIdentityVariable:n,dataset:e.dataset,compiledVariableNames:r});o!==null&&s.push({type:"highlight",id:a.id,predicate:o,scope:a.highlight})}return s}function id(e){const t=v(e.x);return t!==null&&t!==""?t:v(e.color)}function cd({annotation:e,rowIdentityVariable:t,dataset:n,compiledVariableNames:r}){switch(e.highlight){case"x-value":return os(e,t,n);case"series":return is(e,r);case"data-point":{const s=os(e,t,n),a=is(e,r);return s===null&&a===null?null:s===null?a:a===null?s:{and:[s,a]}}}}function os(e,t,n){if(t===null)return null;const r=dd(e,t,n);return r===null?null:{variable:t,eq:r}}function is(e,t){if(!ld(t))return null;const n=e.columnKey;return h(n)?{or:ka.map(r=>({variable:r,eq:n}))}:null}function ld(e){return ka.some(t=>e.includes(t))}function ud(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??U):s.transformType==="constant"&&n.push(s.options.variableName);return n}function dd(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 pd(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:cn(t)};if(e?.startsWith("preset:graphy"))return{type:"graphy",variant:cn(t)};const i="preset:mono:";if(e?.startsWith(i)){const l=e.slice(i.length);if(md(l))return{type:"mono",base:l,variant:r}}const c="preset:neon:";if(e?.startsWith(c)){const l=e.slice(c.length);if(fd(l))return{type:"neon",base:l,variant:cn(t)}}return{type:"default"}}function cn(e){if(e==="waterfall")return"waterfall"}function md(e){return xa.includes(e)}function fd(e){return Sa.includes(e)}function hd(e){if(!e)return;const t={};for(const[n,r]of Object.entries(e)){if(!n.startsWith("series"))continue;const s=Number.parseInt(n.slice(6));if(Number.isNaN(s))continue;const a={hex:r.customColor,id:r.paletteColorId};(a.hex!==void 0||a.id!==void 0)&&(t[s]=a)}return Object.keys(t).length>0?t:void 0}function yd(e,t,n,r={}){const s=[];s.push(cs("x",t?.x)),s.push(cs("y",t?.y));const a=pd(n?.paletteId,e,r),o=hd(n?.seriesStyles);return s.push(Se.color.palette({palette:a,overrides:o})),s}function cs(e,t){return t?.scaleType==="logarithmic"||t?.min!==void 0||t?.max!==void 0?t.scaleType==="logarithmic"?Se[e].log({domainMin:t.min??void 0,domainMax:t.max??void 0}):Se[e]({domainMin:t.min??void 0,domainMax:t.max??void 0}):Se[e]()}const gd=new Set(["column","columnStacked","columnStackedFill","bar","barStacked","barStackedFill","line","areaStacked","scatter","bubble","funnel","combo"]),bd=new Set(["column","columnStacked","columnStackedFill","bar","barStacked","barStackedFill","line","areaStacked","combo"]);function vd(e,t,n){const r=t.type??"column",s={dataset:e,axes:t.axes},a=Zu(s,r,t.options??void 0,t.appearance??void 0);return{data:a.dataset,mapping:a.mapping,layers:xd(r,t,a.layers,a.coords,a.mapping,a.seriesVariables),scales:[...yd(r,t.axes,t.appearance,n),...a.scales],transforms:a.transforms??[],highlights:od({annotations:t.annotations,dataset:e,mapping:a.mapping,convertedDataset:a.dataset,layers:a.layers}),annotations:Vu({annotations:t.annotations,dataset:e,mapping:a.mapping}),coords:a.coords,config:Ou(t)}}function xd(e,t,n,r,s,a){const o=Md(t.dataLabels),i=o===void 0?n:n.filter(l=>l.interactive!==!1).map(l=>({...l,dataLabels:{...o,...l.dataLabels}})),c=t.axes?.hasDualYAxis??!1;return[...i,...Sd({type:e,trendline:t.referenceLines?.trendline,coords:r}),...wd({type:e,hasDualYAxis:c,goalLine:t.referenceLines?.goalLine,coords:r}),...Td({type:e,hasDualYAxis:c,averageLine:t.referenceLines?.averageLine,coords:r,mapping:s,seriesVariables:a})]}function Sd({type:e,trendline:t,coords:n}){return t===void 0?[]:gd.has(e)?n.coordType==="polar"?[]:[_.line({aes:{lineType:{value:"dashed"}},stat:zn.smooth({method:t}),interactive:!1})]:[]}function wd({type:e,hasDualYAxis:t,goalLine:n,coords:r}){if(!Ad(n))return[];if(r.coordType==="polar")return[];const s=r.coordType==="flip"?"end":"start";return[_.rule({aes:{y:{value:n.target}},params:{labelPosition:s,label:n.label??"Goal"},yScaleType:e==="combo"&&t?"secondary":"primary",interactive:!1})]}function Ad(e){return e!==void 0&&Number.isFinite(e.target)}function Td({type:e,hasDualYAxis:t,averageLine:n,coords:r,mapping:s,seriesVariables:a}){if(n===void 0)return[];if(!bd.has(e))return[];if(r.coordType==="polar")return[];const o=Ta(n.columnKey);if(!a.includes(o))return[];const i=s.color===U,c=i?se:o,l=i?[xe.filter({variableName:U,operator:"eq",value:o})]:[];return[_.rule({aes:{y:c,color:void 0,group:void 0,lineType:void 0},stat:zn.mean(),transforms:l,params:{label:"Average",labelPosition:r.coordType==="flip"?"end":"start"},yScaleType:e==="combo"&&t?"secondary":"primary",interactive:!1})]}function Md(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 ln={color:null,size:"small",labelCrossPosition:.5},Ce={kind:"rectangle",zOrder:"foreground",fillColor:"transparent",fillOpacity:1,strokeWidth:1,strokeColor:null},ls={backgroundColor:null,backgroundColorStyle:"opaque"},De={color:null,thickness:"medium",startArrowheadStyle:"none",endArrowheadStyle:"line-arrow",lineStyle:"solid",hasStickerStyle:!1},Ld=(e,t)=>({differenceArrows:(e?.differenceArrows??[]).map(n=>Ed(n,t)),shapes:(e?.shapes??[]).map(Dd),freeformArrows:(e?.freeformArrows??[]).map(_d),textAnnotations:(e?.textAnnotations??[]).map(Vd),stickers:(e?.stickers??[]).map(n=>Id(n,t)),pinnedNumbers:(e?.pinnedNumbers??[]).map(n=>kd(n,t)),comments:(e?.comments??[]).map(n=>Cd(n,t))}),Vd=e=>({id:e.id??crypto.randomUUID(),content:e.content,x:e.x,y:e.y,width:e.width,backgroundColor:e.backgroundColor??ls.backgroundColor,backgroundColorStyle:e.backgroundColorStyle??ls.backgroundColorStyle}),Ed=(e,t)=>({id:e.id??crypto.randomUUID(),start:Qe(e.start,t),end:Qe(e.end,t),label:e.label,color:e.color??ln.color,size:e.size??ln.size,labelCrossPosition:e.labelCrossPosition??ln.labelCrossPosition}),Qe=(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}},Id=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:Qe(e.anchor,t),sticker:e.sticker}),kd=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:Qe(e.anchor,t)}),Cd=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:Qe(e.anchor,t),content:e.content}),Dd=e=>({id:e.id??crypto.randomUUID(),kind:e.kind??Ce.kind,zOrder:e.zOrder??Ce.zOrder,x:e.x,y:e.y,width:e.width,height:e.height,fillColor:e.fillColor??Ce.fillColor,fillOpacity:e.fillOpacity??Ce.fillOpacity,strokeWidth:e.strokeWidth??Ce.strokeWidth,strokeColor:e.strokeColor??Ce.strokeColor}),_d=e=>({id:e.id??crypto.randomUUID(),start:e.start,end:e.end,color:e.color??De.color,thickness:e.thickness??De.thickness,startArrowheadStyle:e.startArrowheadStyle??De.startArrowheadStyle,endArrowheadStyle:e.endArrowheadStyle??De.endArrowheadStyle,lineStyle:e.lineStyle??De.lineStyle,hasStickerStyle:e.hasStickerStyle??De.hasStickerStyle}),Fd={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 Rd(e){return ue.merge({},Fd,e)}const Nd={xLimits:null,yLimits:null},un={theta:"x",startAngle:0,innerRadius:0};function Pd(e){const t=e??{type:"coord",coordType:"cartesian"},n=Es({},Nd,t.params??{});switch(t.coordType){case"cartesian":case"flip":return{...t,params:n};case"polar":return{...t,params:{...n,theta:t.params?.theta??un.theta,startAngle:t.params?.startAngle??un.startAngle,innerRadius:t.params?.innerRadius??un.innerRadius}}}}function Od(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 Bd="linear",$d=3,Gd=.3;function rt(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??Bd,order:s?.order??$d,bandwidth:s?.bandwidth??Gd}}return{type:r}}function Ca(e,t,n){switch(n.geom){case"point":return Yd(e,t,n);case"line":return Hd(e,t,n);case"area":return Ud(e,t,n);case"bar":return Kd(e,t,n);case"rule":return Xd(e,t,n)}}function zd(e,t,n){const r=n.map(s=>Ca(e,t,s));return jd(r)}const Wd=(e,t,n)=>n.label!==void 0?n.label:qd(e,t,n),st=(e,t,n,r)=>{const s={...e,...t.mapping},a=Wd(t.geom,n,s);return{...Qu(t.geom,r),...t.dataLabels,labelSource:a}};function Yd(e,t,n){const r=n.position??vt.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:rt(n.stat,vt.stat.type),position:r,yScaleType:n.yScaleType??nt,params:ue.merge({},vt.params,n.params),transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:st(e,n,r,t)}}function Hd(e,t,n){const r=n.position??rn.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:rt(n.stat,rn.stat.type),position:r,yScaleType:n.yScaleType??nt,params:ue.merge({},rn.params,n.params),transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:st(e,n,r,t)}}function Ud(e,t,n){const r=ue.merge({},sn.params,n.params);r.missingValues==="gap"&&(r.missingValues="zero");const s=n.position??sn.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:rt(n.stat,sn.stat.type),position:s,yScaleType:n.yScaleType??nt,params:r,transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:st(e,n,s,t)}}function Kd(e,t,n){const r=n.position??an.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:rt(n.stat,an.stat.type),position:r,yScaleType:n.yScaleType??nt,params:{...an.params,...n.params},transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:st(e,n,r,t)}}function Xd(e,t,n){const r=n.position??Ge.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:rt(n.stat,Ge.stat.type),position:n.position??Ge.position,yScaleType:n.yScaleType??nt,params:ue.merge({},Ge.params,n.params),transforms:n.transforms??[],interactive:n.interactive??Ge.interactive,dataLabels:st(e,n,r,t)}}const jd=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=le(n.mapping.y);if(!D(r))return n;const s=Math.min(1,Math.max(0,r));return{...n,mapping:{...n.mapping,y:{value:s}}}})},qd=(e,t,n)=>{if(e==="point"){const r=v(n.size);if(r!==null)return{variable:r}}return Rt(t,n)};function Ot(e,...t){return e?t.includes(e.geom):!1}function Bt(e,t){return e.find(n=>n.id===t)}function at(e,...t){return e.find(n=>t.includes(n.geom))}function Un(e,t,n){const r=e.layers.findIndex(a=>a.id===t);if(r===-1)return e;const s=e.layers.map((a,o)=>o===r?n:a);return{...e,layers:s}}function Qd(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,a)=>a!==n);return In(r)?{...e,layers:r}:e}const Da={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 _a(e,t,n,r,s){switch(e.scaleType){case"inferred":{const a=tp(e,t,n,r);return _a(a,t,n,r,s)}case"continuous":{const a=Da[e.scaledAesthetic],o=a==="continuous-range"&&e.scaledAesthetic in Jr?Jr[e.scaledAesthetic]:null,i=e.scaledAesthetic==="size"&&a==="continuous-range"?"sqrt":ke.transform;return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,transform:e.transform??i,reverse:e.reverse??ke.reverse,nice:e.nice??ke.nice,zero:e.zero??ke.zero,clamp:e.clamp??a!=="position",domainMin:e.domainMin??ke.domainMin,domainMax:e.domainMax??ke.domainMax,range:e.range??o??null}}case"datetime":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,domainMin:e.domainMin??lt.domainMin,domainMax:e.domainMax??lt.domainMax,nice:e.nice??lt.nice,reverse:e.reverse??lt.reverse,clamp:e.clamp??!1};case"discrete":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,range:e.range??Ye.range,domain:e.domain??Ye.domain,padding:e.padding??Ye.padding,reverse:e.reverse??Ye.reverse};case"palette":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,palette:uu(e.palette,s),overrides:lu(e.overrides,e.palette,s)};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 Jd(e,t,n,r,s,a){const o=rp(t,n),i=sp(o),c=new Map;for(const u of i)c.set(u.scaledAesthetic,u);const l=[...c.values()].map(u=>_a(u,e,n,r,a));return s.coordType==="polar"?ep(l):l}const ep=e=>e.map(t=>t.scaleType==="discrete"?{...t,padding:0}:t);function tp(e,t,n,r){const s=ee(e.scaledAesthetic),a=e.scaledAesthetic==="ySecondary"?np(n,r):r[s],o=at(n,"bar");if(e.scaledAesthetic==="x"&&o)return Z(e.scaledAesthetic,e.options);if(o&&e.scaledAesthetic===(o.yScaleType==="secondary"?"ySecondary":"y")){const d=e.options,p=o.position==="fill";return F(e.scaledAesthetic,{...d,zero:!0,...p&&{nice:!1}})}const i=v(a);if(!h(i)||!t.hasVariable(i))return F(e.scaledAesthetic,e.options);const c=t.getType(i),l=Da[e.scaledAesthetic];switch(Zd[c][l]){case"discrete":return Z(e.scaledAesthetic,e.options);case"datetime":return xt(e.scaledAesthetic,e.options);case"continuous":return F(e.scaledAesthetic,e.options);case"identity":default:return He(e.scaledAesthetic)}}function np(e,t){const n=e.find(r=>r.yScaleType==="secondary");return n?n.mapping.y??t.y:t.y}function rp(e,t){return!t.some(s=>s.yScaleType==="secondary")||e.some(s=>s.scaledAesthetic==="ySecondary")?e:[...e,St("ySecondary")]}function sp(e){return e.some(n=>n.scaledAesthetic==="color")?e:[...e,Va("color")]}function us(e,t){const n=Pd(e.coords),r=zd(e.mapping,n.coordType,e.layers),s=Jd(e.data,e.scales,r,e.mapping,n,t),a=Rd(e.config),o=Od(e.highlights,r),i=Ld(e.annotations,r);return{data:e.data,mapping:e.mapping,layers:r,scales:s,transforms:e.transforms,highlights:o,annotations:i,coords:n,config:a}}class Fa{compile({input:t,dataset:n,ctx:r}){const s=r.customPalettes??{};return Aa(t)?us(vd(n,t,r),s):us({...t,data:n},s)}}class ap{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 op 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,...Pn(t,n)])];return{data:t.groupBy(...a).rollup({[je.count]:{variableName:r,aggregation:"count"}}),mapping:{y:je.count}}}}class ip extends $t{constructor(){super(...arguments),this.type="identity",this.computedVariables=new Set}computeStat({data:t}){return{data:t,mapping:{}}}}class cp 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({[je.mean]:{variableName:r,aggregation:"mean"}}),mapping:{y:je.mean}}}}const lp=2,Ra=1440*60*1e3;class up extends $t{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 a=v(n.x),o=v(n.y);if(!h(a))throw new Error("'x' variable is required for 'smooth' stat");if(!h(o))throw new Error("'y' variable is required for 'smooth' stat");const i=t.getType(a),c=t.getType(o);if(c!=="numeric")throw new Error(`'smooth' stat requires a numeric 'y' (got '${c}' for variable '${o}')`);const l=Pn(t,n),u=gp(a,i,o,l,t);return l.length===0?ds({data:t,xVariable:a,xType:i,yVariable:o,spec:r,output:u,groupObservation:{},xScaleIsDiscrete:s}):t.groupBy(...l).forEach(d=>{const p=bp(d,l);ds({data:d,xVariable:a,xType:i,yVariable:o,spec:r,output:u,groupObservation:p,xScaleIsDiscrete:s})}),{data:u.build(),mapping:{}}}}const ds=({data:e,xVariable:t,xType:n,yVariable:r,spec:s,output:a,groupObservation:o,xScaleIsDiscrete:i})=>{const{observations:c,temporalOrigin:l}=dp({data:e,xVariable:t,yVariable:r,xType:n});c.length<lp||(i?yp({observations:c,spec:s,output:a,groupObservation:o}):fp({observations:c,xType:n,temporalOrigin:l,spec:s,output:a,groupObservation:o}))},dp=({data:e,xVariable:t,yVariable:n,xType:r})=>{const s=e.getValues(t),a=e.getValues(n,{type:"numeric"}),o=r==="temporal"?pp(s):null,i=[],c=new Map;for(let l=0;l<s.length;l++){const u=s[l],d=a[l];if(!h(u)||!h(d)||!Number.isFinite(d))continue;const p=mp({xValue:u,xType:r,categoryRank:c,temporalOrigin:o});p!==null&&i.push({x:p,y:d,originalX:u})}return{observations:i,temporalOrigin:o}},pp=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},mp=({xValue:e,xType:t,categoryRank:n,temporalOrigin:r})=>{switch(t){case"numeric":return!D(e)||!Number.isFinite(e)?null:e;case"temporal":{if(!G(e))return null;const s=e.getTime();return r===null?s:(s-r)/Ra+1}case"categorical":{if(!Ze(e))return null;const s=n.get(e);if(s!==void 0)return s;const a=n.size+1;return n.set(e,a),a}default:{const s=t;throw new Error(`Unexpected xType: ${s}`)}}},fp=({observations:e,xType:t,temporalOrigin:n,spec:r,output:s,groupObservation:a})=>{const o=Na(r,e);for(const[i,c]of o){if(!Number.isFinite(i)||!Number.isFinite(c))continue;const l=t==="temporal"?hp(i,n):i;s.push({x:l,y:c,groupObservation:a})}},hp=(e,t)=>t===null?new Date(e):new Date((e-1)*Ra+t),yp=({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 a=[...s.keys()].sort((i,c)=>i-c);if(t.method==="loess"){const i=Na(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=s.get(l);u===void 0||d===void 0||n.push({x:d,y:u,groupObservation:r})}return}const o=Pa(t,e);for(const i of a){const c=s.get(i),l=o.predict(i);c===void 0||!Number.isFinite(l)||n.push({x:c,y:l,groupObservation:r})}},Na=(e,t)=>e.method==="loess"?ye.regressionLoess().x(r=>r.x).y(r=>r.y).bandwidth(e.bandwidth)(t):Pa(e,t),Pa=(e,t)=>{const n=s=>s.x,r=s=>s.y;switch(e.method){case"linear":return ye.regressionLinear().x(n).y(r)(t);case"exponential":return ye.regressionExp().x(n).y(r)(t);case"logarithmic":return ye.regressionLog().x(n).y(r)(t);case"quadratic":return ye.regressionQuad().x(n).y(r)(t);case"power":return ye.regressionPow().x(n).y(r)(t);case"polynomial":return ye.regressionPoly().x(n).y(r).order(e.order)(t);case"loess":throw new Error("'loess' does not expose a 'predict' function")}},gp=(e,t,n,r,s)=>{const a=[],o=[],i=Object.fromEntries(r.map(c=>[c,[]]));return{push:({x:c,y:l,groupObservation:u})=>{a.push(c),o.push(l);for(const d of r)i[d]?.push(u[d]??null)},build:()=>{const c={[e]:{type:t,values:a,valueFormat:s.getValueFormat(e)},[n]:{type:"numeric",values:o,valueFormat:s.getValueFormat(n)}};for(const l of r)c[l]={type:s.getType(l),values:i[l]??[],valueFormat:s.getValueFormat(l)};return new I(c)}}},bp=(e,t)=>{const n={};for(const r of t){const s=e.getValues(r);n[r]=s[0]??null}return n};class vp extends Ne{constructor(){super("stat"),this.register("identity",new ip),this.register("count",new op),this.register("smooth",new up),this.register("mean",new cp)}}const xp=({layer:e})=>{if(e.geom!=="bar"||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 a=s[t];D(a)&&(n+=a,r+=Math.abs(a))}return{grandTotal:n,absoluteGrandTotal:r}},Sp=({layer:e})=>{if(e.geom!=="bar"||e.position!=="stack")return;const t=v(e.mapping.x);if(t===null||!e.data.hasVariable(f.yMin)||!e.data.hasVariable(f.yMax))return;const n=new Map;for(const s of e.data){const a=s[t],o=te(s),i=H(s),c=me(s),l=ae(s),u=_s(s);if(!h(a)||!h(o)||!h(i)||!h(c)||!h(l)||!h(u))continue;const d=u>=0;if(Math.abs(u)===0)continue;const m=Gn(s,t),y={yMin:o,yMax:i},g=n.get(m);if(g===void 0){n.set(m,{total:u,topPositive:d?y:null,bottomNegative:d?null:y,anchorXMin:c,anchorXMax:l});continue}g.total+=u,d?(g.topPositive===null||i>g.topPositive.yMax)&&(g.topPositive=y):(g.bottomNegative===null||o<g.bottomNegative.yMin)&&(g.bottomNegative=y)}const r=[];for(const[s,a]of n){const o=a.topPositive??a.bottomNegative;o!==null&&r.push({xKey:s,total:a.total,anchor:{xMin:a.anchorXMin,xMax:a.anchorXMax,yMin:o.yMin,yMax:o.yMax,direction:a.topPositive!==null?"positive":"negative"}})}return r};class wp extends Re{dependencies(){return[]}compileLayer(t){const n={},r=Sp({layer:t});r!==void 0&&(n.stackTotals=r);const s=xp({layer:t});return s!==void 0&&(n.grandTotal=s.grandTotal,n.absoluteGrandTotal=s.absoluteGrandTotal),{...t,summary:n}}}class Ap extends de{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 Tp{constructor(){this.transformType="aggregate"}apply(t,n){const{options:r}=n,s={};for(const a of r.operations)s[a.as]={variableName:a.variableName,aggregation:a.op};return t.groupBy(...r.groupby).rollup(s)}}class Mp{constructor(){this.transformType="constant"}apply(t,n){const{options:r}=n;return t.addConstantVariable(r.variableName,r.type,r.value)}}class Lp{constructor(){this.transformType="filter"}apply(t,n){const{options:r}=n;return t.filter(r.variableName,r.operator,r.value)}}class Vp{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 Ep{constructor(){this.transformType="sort"}apply(t,n){const{options:r}=n;return t.orderBy(r.variableName,r.direction??"asc")}}class Ip extends Ne{constructor(){super("transform"),this.register("aggregate",new Tp),this.register("constant",new Mp),this.register("filter",new Lp),this.register("reshape",new Vp),this.register("sort",new Ep)}}const ps={color:"categorical",size:"numeric",alpha:"numeric",strokeWidth:"numeric",lineType:"categorical"},kp=["color","size","alpha","strokeWidth","lineType"];class Cp extends Re{dependencies(t){return kp.map(n=>t.scales[n])}compileLayer(t,n){let r=t.data;const s=Object.entries(pe);for(const[a,o]of s){const i=le(t.mapping[a]);if(i!==void 0){r=r.deriveVariable(o,ps[a],()=>i);continue}const c=v(t.mapping[a]),l=n.scales[a];if(!l||l.kind!=="visual")continue;const u=Dp(a,c,l);u&&(r=r.deriveVariable(o,ps[a],u))}return{...t,data:r}}}const Dp=(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},_p=["data","transform","constantMapping","layer","coordSetup","scale","positionMapper","visualMapper","coordTransform","summarise","guide","highlights","config","annotations"];class Oa{constructor(t,n,r,s,a,o,i,c,l,u,d,p,m,y,g){this.dataCompiler=t,this.specCompiler=n,this.transformCompiler=r,this.constantMappingCompiler=s,this.layerValidationCheck=a,this.layerCompiler=o,this.scaleCompiler=i,this.coordCompiler=c,this.positionMapperCompiler=l,this.visualMapperCompiler=u,this.guideCompiler=d,this.summariseCompiler=p,this.highlightsCompiler=m,this.configCompiler=y,this.annotationsCompiler=g,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(!ve)return t();const n=this.getCacheStats(),r=performance.now(),s=t(),a=performance.now()-r,o={};for(const{name:i,getStats:c}of this.stages){const l=c();o[i]={hits:l.hits-n[i].hits,misses:l.misses-n[i].misses}}return this.lastCompile={stages:o,durationMs:a},s}runPipeline({spec:t}){return It({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:a,coordSystem:o})=>({guides:this.guideCompiler.compile({scales:s,config:r.config,layers:a,coordSystem:o,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:a})=>({annotations:this.annotationsCompiler.compile({annotations:r.annotations,layers:s,coordSystem:a})})).result()}}const Fp=()=>{const e=new vp,t=new pu,n=new rc,r=new Ap(new Ip);return new Oa(new Hi,new Fa,r,new jo,new Cl(r,new Dl(n,e)),new kl(r,new ap(e),new sc,new qi(n),new _l(new Ol)),new Ul(t),new Jo(new pi),new Hl,new Cp,new hl,new wp,new Vl,new Xo,new $o)};function Rp(e,t){return e.geom===t}const Kn="–",Ba="n/a",O={timeZone:"UTC"},N=e=>t=>{if(!G(t))return Kn;try{return e(t)}catch{return Ba}},fe=e=>t=>D(t)?e(t):Kn,Xn=e=>t=>Ze(t)?t:Kn,Np=2,Pp=3,Op=2,Bp=0,$p=1,Gp=2,zp=To.humanizer({language:"en",spacer:"",delimiter:" ",languages:{en:{y:()=>"y",mo:()=>"mo",w:()=>"w",d:()=>"d",h:()=>"h",m:()=>"m",s:()=>"s",ms:()=>"ms"}}}),$a=({valueFormat:e,locale:t,numberFormat:n,intlOptions:r})=>fe(s=>{const a=typeof n.decimals=="number"?n.decimals:Np,o=Zn(s,a),{base:i,suffix:c}=Qn(s,n.abbreviation),l={...o,...Cn(e)?{style:"currency",currencyDisplay:"narrowSymbol",currency:e.iso}:{},...r};return`${Intl.NumberFormat(t,l).format(i)}${c}`}),jn=({locale:e,numberFormat:t,intlOptions:n})=>fe(r=>{const{base:s,suffix:a}=Qn(r,t.abbreviation),i={...Zn(s,t.decimals),...n};return`${Intl.NumberFormat(e,i).format(s)}${a}`}),qn=e=>fe(t=>zp(t)),Ga=({locale:e,intlOptions:t})=>fe(n=>Intl.NumberFormat(e,{maximumFractionDigits:0,...t}).format(n)),za=({locale:e,numberFormat:t,intlOptions:n})=>fe(r=>{const s=Zn(r,t.decimals);return Intl.NumberFormat(e,{...s,...n,style:"percent"}).format(r)}),Qn=(e,t="none")=>{switch(t){case"none":return{base:e,suffix:""};case"auto":{const n=Wp(e);return Qn(e,n)}default:return{base:e/Xe[t],suffix:t}}},Zn=(e,t)=>{if(typeof t=="number")return{minimumFractionDigits:t,maximumFractionDigits:t};const n=Math.ceil(Math.log10(Math.abs(e))),r=n>=Pp?Bp:n===Op?$p:Gp;return{minimumFractionDigits:t==="auto"?0:r,maximumFractionDigits:r}},Wp=e=>{const t=Math.abs(e);return t>=Xe.b?"b":t>=Xe.m?"m":t>=Xe.k?"k":"none"},Yp=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{dateStyle:"medium",...O,...t}).format(n)),Hp=({locale:e,intlOptions:t})=>N(n=>{const r=Intl.DateTimeFormat(e,{dateStyle:"medium",timeStyle:"medium",...O,...t}).formatToParts(n);return Up(r.map(Kp))}),Wa=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"long",...O,...t}).format(n)),Ya=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{month:"long",...O,...t}).format(n)),Jn=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{month:"short",year:"numeric",...O,...t}).format(n)),er=e=>N(t=>`Q${Math.floor(t.getUTCMonth()/3)+1} ${t.getUTCFullYear()}`),Ha=({locale:e,intlOptions:t})=>N(n=>{const r=V.addDays(n,6);return Intl.DateTimeFormat(e,{day:"numeric",month:"long",...O,...t,year:void 0}).formatRange(n,r)}),Ua=({locale:e,intlOptions:t})=>N(n=>{const r=V.addDays(n,6);return Intl.DateTimeFormat(e,{dateStyle:"medium",...O,...t}).formatRange(n,r)}),tr=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{year:"numeric",...O,...t}).format(n)),Ka=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{timeStyle:"short",...O,...t}).format(n)),Up=e=>e.map(t=>t.value).join(""),Kp=e=>e.type!=="literal"||e.value!==", "?e:{type:"literal",value:" • "},Xp=1,jp=4,qp=1,ms=1e3,Qp=({valueFormat:e,locale:t,tickValues:n,intlOptions:r})=>fe(s=>{const o={...rr(s,n),notation:"compact",...Cn(e)?{style:"currency",currencyDisplay:"narrowSymbol",currency:e.iso}:{},...r};return nr(s,t,o)}),Zp=({locale:e,tickValues:t,intlOptions:n})=>fe(r=>{const a={...rr(r,t),notation:"compact",...n};return nr(r,e,a)}),Jp=({locale:e,tickValues:t,intlOptions:n})=>fe(r=>{const a={...rr(r,t),notation:"compact",...n,style:"percent"};return nr(r,e,a)}),nr=(e,t,n)=>Intl.NumberFormat(t,n).formatToParts(e).map(s=>s.type==="compact"?s.value.toLowerCase():s.value).join(""),Xa=e=>Math.abs(e)>ms?Xa(e/ms):Number.isInteger(e),em=e=>{if(e.length<2)return!1;const[t,n]=e;return typeof t!="number"||typeof n!="number"?!1:Math.abs(n-t)<Xp},rr=(e,t)=>Xa(e)?{minimumFractionDigits:0,maximumFractionDigits:0}:em(t)?{minimumFractionDigits:0,maximumFractionDigits:jp}:{minimumFractionDigits:0,maximumFractionDigits:qp},tm=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"short",...O,...t}).format(n)),nm=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{month:"short",...O,...t}).format(n)),rm=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"short",...O,...t}).format(n)),sm=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{timeStyle:"short",...O,...t}).format(n)),sr=e=>{const{valueFormat:t}=e;switch(t.type){case"currency":return Qp(e);case"date":case"datetime":return tm(e);case"day_month":case"weekly_date_range":case"weekly_date_range_with_year":return rm(e);case"decimal":case"integer":return Zp(e);case"duration":return qn();case"month":return nm(e);case"month_year":return Jn(e);case"percentage":return Jp(e);case"quarter":return er();case"text":return Xn();case"time":return sm(e);case"year":return tr(e);case"lookup":return sr({...e,valueFormat:t.fallback});default:{const n=t;throw new Error(`Unhandled value format: ${n.type}`)}}},am=40,om=60,fs=8,im=50,cm=1/3,lm=1/4,dn="…",um=(e,t,n)=>{if(t<=0||e.length===0)return"";if(n(e)<=t)return e;if(n(dn)>t)return"";let r=0,s=e.length-1,a=0;for(;r<=s;){const o=r+s>>>1,i=e.slice(0,o)+dn;n(i)<=t?(a=o,r=o+1):s=o-1}return e.slice(0,a)+dn},dm=e=>e.formattedAxis.position==="top"||e.formattedAxis.position==="bottom"?pm(e):mm(e),pm=({formattedAxis:e,bandwidthPx:t,panelRect:n,measureLabel:r})=>{const{widths:s,maxWidth:a,maxHeight:o}=ja(e.ticks,r),i=t-fs;if(a<=i)return{...e,labelRotation:0,labelMaxWidthPx:null};if(t>=im){const l=Mn(i);return{...e,ticks:Tn(e.ticks,s,l,r),labelRotation:0,labelMaxWidthPx:l}}if(o+fs>t)return{...e,ticks:[],labelRotation:0,labelMaxWidthPx:null};const c=Mn(n.height*cm);return{...e,ticks:Tn(e.ticks,s,c,r),labelRotation:-90,labelMaxWidthPx:c}},mm=({formattedAxis:e,bandwidthPx:t,panelRect:n,measureLabel:r})=>{const{widths:s,maxWidth:a,maxHeight:o}=ja(e.ticks,r);if(o>t)return{...e,ticks:[],labelRotation:0,labelMaxWidthPx:null};const i=Mn(n.width*lm);return a<=i?{...e,labelRotation:0,labelMaxWidthPx:null}:{...e,ticks:Tn(e.ticks,s,i,r),labelRotation:0,labelMaxWidthPx:i}},ja=(e,t)=>{const n=[];let r=0,s=0;for(const a of e){const{width:o,height:i}=t(a.formattedLabel);n.push(o),o>r&&(r=o),i>s&&(s=i)}return{widths:n,maxWidth:r,maxHeight:s}},Tn=(e,t,n,r)=>{const s=a=>r(a).width;return e.map((a,o)=>(t[o]??0)<=n?a:{...a,formattedLabel:um(a.formattedLabel,n,s)})},Mn=e=>Math.max(0,Math.floor(e)),fm=(e,t,n,r)=>{if(e.length===0)return!0;const s=t==="top"||t==="bottom",a=s?om:am;let o=n-(e.length-1)*a;for(const i of e){const{width:c,height:l}=r(i);if(o-=s?c:l,o<0)return!1}return!0},hm=({axis:e,availableSpacePx:t,measureLabel:n,resolveFormatter:r})=>{const{tickCandidates:s,position:a}=e;if(s.length===0)return[];const o=new Map,i=d=>{const p=o.get(d);if(p)return p;const m=s[d],y=m?ym(m.ticks,r(m)):[];return o.set(d,y),y};let c=0,l=s.length-1,u=-1;for(;c<=l;){const d=c+l>>>1,m=i(d).map(y=>y.formattedLabel);fm(m,a,t,n)?(u=d,c=d+1):l=d-1}return u>=0?i(u):i(0)},ym=(e,t)=>e.map(n=>({...n,formattedLabel:t(n.value)})),pn=6,mn=6,fn=15,hn=5,yn=15,ar=(e,t)=>{switch(e){case"small":return{arrowStartGap:pn,arrowEndGap:mn,offsetFromHigherObservation:fn,arrowheadSize:hn,curveRadius:yn,strokeWidth:2,labelLineHeight:12*t,labelPaddingX:6,labelPaddingY:3,labelStrokeWidth:1,labelFontWeight:500};case"medium":return{arrowStartGap:pn*1.5,arrowEndGap:mn*1.5,offsetFromHigherObservation:fn*1.25,arrowheadSize:hn*1.5,curveRadius:yn*1.25,strokeWidth:3,labelLineHeight:16*t,labelPaddingX:8,labelPaddingY:4,labelStrokeWidth:1.5,labelFontWeight:500};case"large":return{arrowStartGap:pn*2,arrowEndGap:mn*2,offsetFromHigherObservation:fn*1.75,arrowheadSize:hn*2.5,curveRadius:yn*1.5,strokeWidth:5,labelLineHeight:20*t,labelPaddingX:10,labelPaddingY:5,labelStrokeWidth:2,labelFontWeight:600}}},gm=e=>{const t=P({...e,valueFormat:e.valueFormat.fallback}),n={};for(const[s,a]of Object.entries(e.valueFormat.cases))n[s]=P({...e,valueFormat:a});const r=e.valueFormat.byVariable;return(s,a)=>{if(a===void 0||a[r]===void 0)return t(s);const o=E(a[r]),i=n[o];return i!==void 0?i(s,a):t(s)}},P=e=>{switch(e.valueFormat.type){case"currency":return $a(e);case"date":return Yp(e);case"datetime":return Hp(e);case"day_month":return Wa(e);case"decimal":return jn(e);case"duration":return qn();case"integer":return Ga(e);case"month":return Ya(e);case"month_year":return Jn(e);case"percentage":return za(e);case"quarter":return er();case"text":return Xn();case"weekly_date_range":return Ha(e);case"weekly_date_range_with_year":return Ua(e);case"year":return tr(e);case"time":return Ka(e);case"lookup":return gm({...e,valueFormat:e.valueFormat});default:{const t=e.valueFormat;throw new Error(`Unhandled value format: ${t.type}`)}}},gn={abbreviation:"none",decimals:"auto"},qa=({locale:e,kind:t,startValue:n,endValue:r})=>{if(n===null||r===null)return Ba;switch(t){case"absolute-difference":return jn({locale:e,numberFormat:gn,intlOptions:{signDisplay:"always"}})(r-n);case"relative-difference":{const s=r-n;if(s===0)return"0%";const a=s/n;return a===Number.POSITIVE_INFINITY?"∞":a===Number.NEGATIVE_INFINITY?"-∞":P({valueFormat:{type:"percentage"},locale:e,numberFormat:gn,intlOptions:{signDisplay:"always"}})(a)}case"proportion":{if(r-n===0)return"=";const s=r/n;return s===Number.POSITIVE_INFINITY?"∞":s===Number.NEGATIVE_INFINITY?"-∞":`${P({valueFormat:{type:"decimal"},locale:e,numberFormat:gn,intlOptions:{maximumFractionDigits:1}})(s)}x`}}},bm=e=>{const t=e.padding??0,n=hs(e.rows,t),r=hs(e.cols,t);return{rows:n.tracks,cols:r.tracks,placements:wm(e.placements,n.nameToIndex,r.nameToIndex),width:e.containerSize.width,height:e.containerSize.height}},vm=e=>{const t=ys(e.rows,e.height),n=ys(e.cols,e.width),r=gs(t),s=gs(n),a=new Map;for(const o of e.placements){const i=o.rowSpan??1,c=o.colSpan??1,l=s[o.col]??0,u=r[o.row]??0,d=bs(n,o.col,c),p=bs(t,o.row,i);a.set(o.name,{x:l,y:u,width:Math.max(0,d),height:Math.max(0,p)})}return a},hs=(e,t)=>{const n=[],r=new Map;t>0&&n.push({type:"fixed",pixels:t});for(let s=0;s<e.length;s++){const a=e[s];if(!a)continue;r.set(a.name,n.length),n.push(xm(a));const o=Sm(e,s);if(Qa(a)&&o){const i=a.gaps?.after??0,c=o.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}},xm=e=>typeof e.size=="number"?{type:"fixed",pixels:e.size}:{type:"flex",weight:e.size.flex},Qa=e=>typeof e.size=="number"?e.size>0:e.size.flex>0,Sm=(e,t)=>{for(let n=t+1;n<e.length;n++){const r=e[n];if(r&&Qa(r))return r}},wm=(e,t,n)=>{const r=[];for(const s of e){const a=t.get(s.row),o=n.get(s.col);if(a===void 0||o===void 0)continue;const i=s.rowEnd!==void 0?t.get(s.rowEnd):a,c=s.colEnd!==void 0?n.get(s.colEnd):o;i===void 0||c===void 0||r.push({name:s.name,row:a,col:o,rowSpan:Math.max(1,i-a+1),colSpan:Math.max(1,c-o+1)})}return r},ys=(e,t)=>{let n=0,r=0;for(const a of e)a.type==="fixed"?n+=a.pixels:r+=a.weight;const s=Math.max(0,t-n);return e.map(a=>a.type==="fixed"?a.pixels:r===0?0:a.weight/r*s)},gs=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},bs=(e,t,n)=>{let r=0;const s=Math.min(t+n,e.length);for(let a=t;a<s;a++)r+=e[a]??0;return r},Za=24,re={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}},pt={leftLegend:{after:10,before:0},leftAxis:{after:4,before:0},panel:{after:4,before:0},rightAxis:{after:10,before:0}},or={top:0,right:0,bottom:0,left:0},Am=(e,t,n,r=or)=>{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 bm({rows:[{name:"header",size:t.headerSize.height,gaps:re.header},{name:"topLegend",size:n.legends.top,gaps:re.topLegend},{name:"headline",size:n.headline,gaps:re.headline},{name:"topAxisLabel",size:a,gaps:re.topAxisLabel},{name:"topAxis",size:n.axes.top,gaps:re.topAxis},{name:"topAnnotation",size:r.top},{name:"panel",size:{flex:1},gaps:re.panel},{name:"bottomAxis",size:n.axes.bottom,gaps:re.bottomAxis},{name:"bottomAxisLabel",size:n.axesLabels.bottom,gaps:re.bottomAxisLabel},{name:"bottomLegend",size:n.legends.bottom,gaps:re.bottomLegend},{name:"footer",size:t.footerSize.height}],cols:[{name:"leftLegend",size:n.legends.left,gaps:pt.leftLegend},{name:"leftAxis",size:n.axes.left,gaps:pt.leftAxis},{name:"panel",size:{flex:1},gaps:pt.panel},{name:"rightAnnotation",size:r.right},{name:"rightAxis",size:n.axes.right,gaps:pt.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"},...Tm(n.axes),...Mm(n.axesLabels,n.axes),...Lm(n.legends)],containerSize:e,padding:Za})},Tm=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},Mm=(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},Lm=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},Vm=({annotations:e,mainAxis:t,panelRect:n,textScale:r,locale:s,measureLabel:a,currentOverflow:o})=>{if(e.differenceArrows.length===0)return or;const i=t==="y",c=n.height+o.top,l=n.width+o.right;let u=0,d=0;for(const p of e.differenceArrows){const{start:m,end:y,size:g,label:b}=p;if(!vs(m.x,m.y)||!vs(y.x,y.y))continue;const x=ar(g,r),S=x.offsetFromHigherObservation+x.arrowheadSize+x.arrowEndGap,w=qa({locale:s,kind:b,startValue:m.measurementValue,endValue:y.measurementValue}),k=a(w,g);if(i){const W=Math.max(m.x,y.x),q=S+k.width/2+x.labelPaddingX;d=Math.max(d,xs(q,W,l))}else{const W=Math.max(m.y,y.y),q=S+x.labelLineHeight/2+x.labelPaddingY;u=Math.max(u,xs(q,W,c))}}return{top:Math.ceil(u),right:Math.ceil(d),bottom:0,left:0}},vs=(e,t)=>e>=0&&e<=1&&t>=0&&t<=1,xs=(e,t,n)=>{if(t<=0)return 0;const r=(e-(1-t)*n)/t;return Math.max(0,r)},Em=["top","right","bottom","left"],bn=(e,t)=>{const n={};for(const r of Em){const s=e.get(`${r}${t}`);s&&(n[r]=s)}return n},Ln=["large","medium","small"],Im=({size:e,availableWidth:t,measureStripWidth:n})=>{if(e!=="auto")return e;for(const r of Ln)if(n(r)<=t)return r;return"small"},km=({size:e,availableWidth:t,measureStripWidth:n})=>{const r=e==="auto"?0:Ln.indexOf(e);for(const s of Ln.slice(r))if(n(s)<=t)return s;return null},Cm=({itemWidths:e,gap:t,availableWidth:n})=>{let r=0,s=0;for(const a of e){const o=s===0?a:r+t+a;if(o>n)break;r=o,s+=1}return s},Dm=({headline:e,containerSize:t,measurer:n})=>{if(Ja(e))return 0;const r=eo(e,t.width,n);return n.measureHeadline(e.formatted,r).height},_m=({headline:e,layout:t,containerSize:n,measurer:r,itemGap:s})=>{if(Ja(e)){const i=Fm(t.panel,e.innerRadius),c=km({size:e.size,availableWidth:i.width,measureStripWidth:to(e,r)});return c===null?null:{rect:i,resolvedSize:c,visibleItemCount:1}}const a=eo(e,n.width,r);if(e.formatted.kind!=="perGroup")return{rect:t.headline,resolvedSize:a,visibleItemCount:1};const o=Cm({itemWidths:r.measureHeadlineItemWidths(e.formatted,a),gap:s,availableWidth:t.headline.width});return o===0?null:{rect:t.headline,resolvedSize:a,visibleItemCount:o}},Ja=e=>e.formatted.kind==="grandTotal"&&e.position==="center"&&e.innerRadius>0,Fm=(e,t)=>{const n=Math.min(e.width,e.height)/2,r=t*n*Math.SQRT2,s=e.x+e.width/2,a=e.y+e.height/2;return{x:s-r/2,y:a-r/2,width:r,height:r}},eo=(e,t,n)=>Im({size:e.size,availableWidth:t,measureStripWidth:to(e,n)}),to=(e,t)=>n=>t.measureHeadline(e.formatted,n).width,We={x:0,y:0,width:0,height:0},Rm="0000";class Nm{constructor(t){this.measurer=t}compile(t){return It({axes:t.axes,numberFormat:t.numberFormat,formattedLegends:t.formattedLegends,containerSize:t.containerSize,externalMeasurements:t.externalMeasurements,annotationOverflow:or,headline:t.headline,locale:t.formattingLocale??t.parsingLocale}).pipe(({axes:n,numberFormat:r,locale:s})=>({axisBundles:n.map(a=>({axis:a,resolveFormatter:Pm(a,s,r),formatted:this.seedAxis(a)}))})).pipe(({axisBundles:n,formattedLegends:r,containerSize:s,externalMeasurements:a,annotationOverflow:o,headline:i})=>({layout:this.resolveLayout({axes:n.map(c=>c.formatted),formattedLegends:r,containerSize:s,externalMeasurements:a,annotationOverflow:o,headline:i})})).pipe(({axisBundles:n,layout:r})=>({axisBundles:n.map(s=>Ss(s.axis.position)?{...s,formatted:this.finalizeAxis(s.axis,s.resolveFormatter,r.panel)}:s)})).pipe(({axisBundles:n,formattedLegends:r,containerSize:s,externalMeasurements:a,annotationOverflow:o,headline:i})=>({layout:this.resolveLayout({axes:n.map(c=>c.formatted),formattedLegends:r,containerSize:s,externalMeasurements:a,annotationOverflow:o,headline:i})})).pipe(({axisBundles:n,layout:r})=>({formattedAxes:n.map(s=>Ss(s.axis.position)?s.formatted:this.finalizeAxis(s.axis,s.resolveFormatter,r.panel))})).pipe(({formattedAxes:n,formattedLegends:r,containerSize:s,externalMeasurements:a,annotationOverflow:o,headline:i})=>({layout:this.resolveLayout({axes:n,formattedLegends:r,containerSize:s,externalMeasurements:a,annotationOverflow:o,headline:i})})).pipe(({formattedAxes:n,formattedLegends:r,containerSize:s,externalMeasurements:a,layout:o,annotationOverflow:i,headline:c,locale:l})=>{const u=this.measureAnnotationOverflow(t,o.panel,l,i);return u===i?{formattedAxes:n,layout:o}:{formattedAxes:n,layout:this.resolveLayout({axes:n,formattedLegends:r,containerSize:s,externalMeasurements:a,annotationOverflow:u,headline:c})}}).result()}measureAnnotationOverflow(t,n,r,s){if(!t.annotations||t.annotations.differenceArrows.length===0||t.coordSystem?.type!=="cartesian")return s;const a=Vm({annotations:t.annotations,mainAxis:t.coordSystem.mainAxis,panelRect:n,textScale:t.textScale??1,locale:r,measureLabel:this.measurer.measureDifferenceArrowLabel,currentOverflow:s});return a.top===s.top&&a.right===s.right?s:a}seedAxis(t){const{tickCandidates:n,...r}=t;return{...r,ticks:[{value:0,position:0,formattedLabel:Rm}],labelRotation:0,labelMaxWidthPx:null}}finalizeAxis(t,n,r){const a=t.position==="top"||t.position==="bottom"?r.width:r.height,o=hm({axis:t,availableSpacePx:a,measureLabel:this.measurer.measureTickLabel,resolveFormatter:n}),{tickCandidates:i,...c}=t,l={...c,ticks:o,labelRotation:0,labelMaxWidthPx:null};if(t.scaleType==="discrete"&&t.bandwidth!==void 0){const u=t.bandwidth*a;return dm({formattedAxis:l,bandwidthPx:u,panelRect:r,measureLabel:this.measurer.measureTickLabel})}return l}resolveLayout({axes:t,formattedLegends:n,containerSize:r,externalMeasurements:s,annotationOverflow:a,headline:o}){const i=this.measureGuides(t,n,o,r),c=Am(r,s,i,a),l=vm(c);return{header:l.get("header")??We,headline:l.get("headline")??We,footer:l.get("footer")??We,plot:l.get("plot")??We,panel:l.get("panel")??We,axes:bn(l,"Axis"),axisLabels:bn(l,"AxisLabel"),legends:bn(l,"Legend")}}measureGuides(t,n,r,s){const a={top:0,right:0,bottom:0,left:0},o={top:0,right:0,bottom:0,left:0};for(const c of t)c.isVisible&&(a[c.position]=this.measurer.measureAxis(c),c.label!==null&&(o[c.position]=this.measurer.measureAxisLabel(c)));const i={top:0,right:0,bottom:0,left:0};for(const c of n)i[c.position]=this.measurer.measureLegend(c);return{axes:a,axesLabels:o,legends:i,headline:this.measureHeadlineBand(r,s)}}measureHeadlineBand(t,n){return t===void 0?0:Dm({headline:t,containerSize:n,measurer:this.measurer})}}const Ss=e=>e==="left"||e==="right",Pm=(e,t,n)=>{const r=e.tickCandidates.flatMap(a=>a.ticks.map(o=>o.value)),s=new WeakMap;return a=>{const o=s.get(a);if(o)return o;const i=sr({valueFormat:a.valueFormat??e.valueFormat,locale:t,numberFormat:n,tickValues:r});return s.set(a,i),i}};function Om(e,t,n){const r=new Map;if(!t||t.kind!=="visual"||t.domain.length<=1)return r;for(const s of e){if(s.geom!=="rule"||s.stat.type!=="mean")continue;const a=s.transforms.find(p=>p.transformType==="filter"&&p.options.operator==="eq"),o=v(s.mapping.y);let i,c,l;if(a?.transformType==="filter"&&typeof a.options.value=="string")i="color",c=a.options.variableName,l=a.options.value;else if(o!==null)i="y",c=o,l=o;else continue;const u=Bm(e,i,c);if(u===null)continue;const d=t.map(l);Ze(d)&&r.set(s.id,{shape:Tt(u.geom,n),color:d})}return r}function Bm(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 Fe(e,t){return e==="x"?t.x:t.y}function Gt(e,t){return e==="x"?t.y:t.x}function $m(e,t){return{main:Fe(e,t),cross:Gt(e,t)}}function Gm(e){return e.type==="cartesian"}function zm(e){return e}function we(e){return 1-e}const be=e=>`${Number.parseFloat((e*100).toFixed(4))}%`,ir=12,Wm=4,Ym=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=$(n),s=H(n)??C(n);if(r===null||s===null||r<0||r>1||s<0||s>1)continue;const a=e.formatLabel(n);if(a==="")continue;const{width:o,height:i}=e.measureDataLabel("dataLabel",a),c=r*e.panelRect.width,l=(1-s)*e.panelRect.height-ir-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:c,y:l,text:a,width:o,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},Hm={place:Ym,getPercentageValueStrategy:e=>e.position==="fill"?"fill":X(e.position)?"stack":"none"},vn=4,mt=6,Um=e=>{const t=[],n=X(e.layer.position),r=e.coordSystem.mainAxis==="y";if(e.layer.dataLabels.showDataLabels){const{entries:s,shouldRotate:a}=Xm({layer:e.layer,mainAxis:e.coordSystem.mainAxis,panelRect:e.panelRect,measureDataLabel:e.measureDataLabel,formatLabel:e.formatLabel,isFlipped:r,getObservationKey:e.getObservationKey});for(const o of s){const i=Zm({mainAxis:e.coordSystem.mainAxis,isStacked:n,isNegativeBar:o.isNegative,shouldRotate:a,bounds:o.bounds,labelWidth:o.labelWidth,labelHeight:o.labelHeight,panelWidth:e.panelRect.width,panelHeight:e.panelRect.height});i!==null&&t.push({layerId:e.layer.id,key:o.key,x:i.x,y:i.y,text:o.text,width:o.labelWidth,height:o.labelHeight,isRotated:i.isRotated,target:"observation",position:i.position})}}if(e.layer.dataLabels.showStackTotals){const s=nf({layer:e.layer,mainAxis:e.coordSystem.mainAxis,panelRect:e.panelRect,measureDataLabel:e.measureDataLabel,formatAbsolute:e.formatAbsolute});for(const a of s)t.push(a)}return t},Km={place:Um,getPercentageValueStrategy:e=>e.position==="fill"?"fill":X(e.position)?"stack":"absoluteGrandTotal"},Xm=({layer:e,mainAxis:t,panelRect:n,measureDataLabel:r,formatLabel:s,isFlipped:a,getObservationKey:o})=>{const i=[];let c=!1;const l=v(e.mapping.y);for(const u of e.data){const d=jm(t,u);if(d===null)continue;const p=s(u);if(p==="")continue;const{width:m,height:y}=r("dataLabel",p),g=no(d,n);m>g.width&&(c=!0);const b=l===null?null:u[l],x=D(b)&&b<0;i.push({key:o(u),isNegative:x,text:p,labelWidth:m,labelHeight:y,bounds:g})}return{entries:i,shouldRotate:!a&&c}},no=(e,t)=>({x:e.x*t.width,y:e.y*t.height,width:e.width*t.width,height:e.height*t.height}),ro=(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 a=t,o=n-t;return o<0&&(a+=o,o=-o),{x:a,y:1-s,width:o,height:s-r}},jm=(e,t)=>{const n=me(t),r=ae(t),s=te(t),a=H(t)??C(t);return n===null||r===null||s===null||a===null?null:ro(e,n,r,s,a)},qm=(e,t)=>{const{xMin:n,xMax:r,yMin:s,yMax:a}=t.anchor;return ro(e,n,r,s,a)},Qm=(e,t)=>e==="x"?t?"bottom":"top":t?"left":"right",so=(e,t,n)=>n?{width:t,height:e}:{width:e,height:t},Zm=e=>e.isStacked?Jm({bounds:e.bounds,labelWidth:e.labelWidth,labelHeight:e.labelHeight,isRotated:e.shouldRotate}):tf({edge:Qm(e.mainAxis,e.isNegativeBar),bounds:e.bounds,labelWidth:e.labelWidth,labelHeight:e.labelHeight,isRotated:e.shouldRotate,panelWidth:e.panelWidth,panelHeight:e.panelHeight}),Jm=({bounds:e,labelWidth:t,labelHeight:n,isRotated:r})=>{const s=so(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"}},ef=(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}}},tf=({edge:e,bounds:t,labelWidth:n,labelHeight:r,isRotated:s,panelWidth:a,panelHeight:o})=>{const i=e==="top"||e==="bottom",c=t.x+t.width/2,l=t.y+t.height/2,u=so(n,r,s),d=i?u.height:u.width,p=i?u.width:u.height,m=i?t.height:t.width,y=i?t.width:t.height,g=d/2,{edgeCoord:b,outwardSign:x,panelExtent:S}=ef(e,t,a,o);if(d+vn<m){if(p>y)return null;if(s)return{x:c,y:l,isRotated:!0,position:"inside"};const k=b-x*(g+vn);return{...i?{x:c,y:k}:{x:k,y:l},isRotated:!1,position:"inside"}}const w=b+x*(g+vn);return w-g<0||w+g>S?null:{...i?{x:c,y:w}:{x:w,y:l},isRotated:s,position:"outside"}},nf=({layer:e,mainAxis:t,panelRect:n,measureDataLabel:r,formatAbsolute:s})=>{const a=[],o=e.summary.stackTotals;if(o===void 0||o.length===0)return a;const i=t==="y";for(const c of o){const l=no(qm(t,c),n),u=s(c.total),{width:d,height:p}=r("stackTotal",u),m=c.anchor.direction==="positive";let y,g;i?(y=m?l.x+l.width+mt+d/2:l.x-mt-d/2,g=l.y+l.height/2):(y=l.x+l.width/2,g=m?l.y-mt-p/2:l.y+l.height+mt+p/2),a.push({layerId:e.id,key:`${e.id}:stack:${c.xKey}`,x:y,y:g,text:u,width:d,height:p,isRotated:!1,target:"aggregate",position:"outside"})}return a},rf=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=$(n),s=C(n);if(r===null||s===null||r<0||r>1||s<0||s>1)continue;const a=e.formatLabel(n);if(a==="")continue;const{width:o,height:i}=e.measureDataLabel("dataLabel",a),c=r*e.panelRect.width,l=(1-s)*e.panelRect.height-ir-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:c,y:l,text:a,width:o,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},sf={place:rf,getPercentageValueStrategy:()=>"none"},af=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=$(n),s=C(n);if(r===null||s===null||r<0||r>1||s<0||s>1)continue;const a=e.formatLabel(n);if(a==="")continue;const{width:o,height:i}=e.measureDataLabel("dataLabel",a),c=(Fs(n)??e.layer.params.size)/2,l=r*e.panelRect.width,u=(1-s)*e.panelRect.height-c-ir-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:l,y:u,text:a,width:o,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},of={place:af,getPercentageValueStrategy:()=>"none"};function ao(e){return{startAngle:e[f.xMin],endAngle:e[f.xMax]}}function oo(e){return{innerRadius:e[f.yMin],outerRadius:e[f.yMax]??e[f.y]}}const cf=" · ",lf=e=>typeof e=="string"?e:e instanceof Date?e.toISOString():String(e),uf=(e,t)=>{const n=v(t.x);return n!==null&&n!==Sn.x?Ft(e,t):s=>Le(s)},df=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;const n=e.layer.dataLabels.showCategoryLabels?uf(e.layer.data,e.layer.mapping):null,r=e.panelRect.width/2,s=e.panelRect.height/2,a=Math.min(e.panelRect.width,e.panelRect.height)/2;for(const o of e.layer.data){const{startAngle:i,endAngle:c}=ao(o),{outerRadius:l}=oo(o);if(i===null||c===null||l===null)continue;const u=e.formatLabel(o);if(u==="")continue;const d=n===null?null:n(o),p=d===null?u:`${lf(d)}${cf}${u}`,{width:m,height:y}=e.measureDataLabel("dataLabel",p),g=(i+c)/2,b=Math.abs(Math.sin(g))*(m/2)+Math.abs(Math.cos(g))*(y/2),x=l*a+Wm+b,S=r+Math.sin(g)*x,w=s-Math.cos(g)*x,k=m/2,W=y/2;S-k<0||S+k>e.panelRect.width||w-W<0||w+W>e.panelRect.height||t.push({layerId:e.layer.id,key:e.getObservationKey(o),x:S,y:w,text:p,width:m,height:y,isRotated:!1,target:"observation",position:"outside"})}return t},pf={place:df,getPercentageValueStrategy:()=>"absoluteGrandTotal"},mf={type:"decimal"};function cr({layer:e,numberFormat:t,locale:n}){const r=v(e.mapping.y),s=r!==null&&e.data.hasVariable(r)?e.data.getValueFormat(r):mf;return P({valueFormat:s,locale:n,numberFormat:t})}const ff=({layer:e,coordSystem:t,axes:n,numberFormat:r,panelRect:s,measureDataLabel:a,formattingLocale:o,percentageValueStrategy:i})=>{const c=cr({layer:e,numberFormat:r,locale:o});return{layer:e,coordSystem:t,panelRect:s,measureDataLabel:a,formatLabel:vf({layer:e,numberFormat:r,axes:n,locale:o,absoluteFormatter:c,percentageValueStrategy:i}),formatAbsolute:c,getObservationKey:hf(e)}},hf=e=>{const t=v(e.mapping.x);return n=>{const r=t===null?null:n[t]??null,s=Le(n);return`${e.id}:${E([r,s])}`}},yf=(e,t)=>{switch(t){case"stack":return gf(e);case"fill":return bf(e);case"absoluteGrandTotal":return()=>e.summary.absoluteGrandTotal??null;case"none":return()=>null}},gf=e=>{const t=v(e.mapping.x);let n=null,r=!1;return s=>{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 o=s[t];if(o==null)return null;const i=n?.get(Gn(s,t));return i===void 0?null:i.total}},bf=e=>{const t=Nt(e);return n=>{const r=te(n),s=H(n);if(!D(r)||!D(s))return null;const a=Math.abs(s-r);if(a===0)return null;const o=t(n);return D(o)?o/a:null}},vf=({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:s,percentageValueStrategy:a})=>{const o=j(e.data,e.dataLabels.labelSource),i=yf(e,a),c=xf({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:s}),l=P({valueFormat:{type:"percentage"},locale:r,numberFormat:t}),u=e.dataLabels.format==="percentage"&&io(e);return d=>{const p=o(d);if(p===null)return"";if(!u||!D(p))return c(p,d);const m=i(d);return m===null||m===0?c(p,d):l(p/m)}},xf=({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:s})=>{const a=e.dataLabels.labelSource,o=v(a);if(o!==null){if(io(e))return s;const i=Sf(e,n,t,r,o);if(i!==null)return i}return P({valueFormat:wf(e.data,a),locale:r,numberFormat:t})},io=e=>{const t=v(e.dataLabels.labelSource);return t===null?!1:t===v(Rt(e.position,e.mapping))},Sf=(e,t,n,r,s)=>{const a=v(e.mapping.x);if(a===null||a!==s)return null;const o=t.find(i=>i.scaleAestheticKey==="x");return o===void 0?null:P({valueFormat:o.valueFormat,locale:r,numberFormat:n})},wf=(e,t)=>{const n=le(t);if(n!==void 0)return typeof n=="number"?{type:"decimal"}:Co(n)?{type:"date"}:{type:"text"};const r=v(t);return r===null||!e.hasVariable(r)?{type:"text"}:e.getValueFormat(r)},Af={bar:{cartesian:Km,polar:pf},line:{cartesian:sf},point:{cartesian:of},area:{cartesian:Hm}},Tf=({layers:e,coordSystem:t,axes:n,numberFormat:r,parsingLocale:s,panelRect:a,measureDataLabel:o,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=Af[d.geom]?.[u];if(p===void 0)continue;const m=ff({layer:d,coordSystem:t,axes:n,numberFormat:r,panelRect:a,measureDataLabel:o,formattingLocale:l,percentageValueStrategy:p.getPercentageValueStrategy(d)}),y=p.place(m);for(const g of y)c.push(g)}return{labels:c}},Mf=(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},Lf=(e,t,n,{arrowStartGap:r,arrowEndGap:s,curveRadius:a})=>{const o={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`
|
|
3
|
+
${n}`),this.issues=t,this.name="SpecValidationError"}}class Cl{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}),a={...t.mapping,...r.mapping};n.push(...this.validator.validate({layerId:r.id,geom:r.geom,stat:r.stat,effectiveMapping:a,data:s,coordType:t.coords.coordType}))}if(n.length>0)throw new va(n)}}class Dl{constructor(t,n){this.geomRegistry=t,this.statRegistry=n}validate(t){return[...this.validateRequiredAesthetics(t),...this.validateVariableExistence(t),...this.validateRuleMapping(t),...this.validateRuleCoord(t)]}validateRequiredAesthetics({layerId:t,geom:n,stat:r,effectiveMapping:s}){const a=[],{requiredAesthetics:o}=this.geomRegistry.get(n),{computedVariables:i}=this.statRegistry.get(r.type);for(const c of o)i.has(c)||h(s[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:s}){const a=[],{computedVariables:o}=this.statRegistry.get(n.type);for(const[i,c]of Object.entries(r)){if(o.has(i))continue;const l=v(c);l!==null&&(s.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}validateRuleMapping({layerId:t,geom:n,stat:r,effectiveMapping:s}){if(n!=="rule")return[];const{computedVariables:a}=this.statRegistry.get(r.type),o=a.has("x"),i=a.has("y"),c=le(s.x),l=le(s.y),u=o||D(c),d=i||D(l);return u&&d?[{code:"INVALID_RULE_MAPPING",message:`Layer '${t}': rule geom requires exactly one of 'x' or 'y', both were provided`,layerId:t}]:!u&&!d?[{code:"INVALID_RULE_MAPPING",message:`Layer '${t}': rule geom requires a numeric value on 'x' or 'y'`,layerId:t}]:[]}validateRuleCoord({layerId:t,geom:n,coordType:r}){return n==="rule"&&r==="polar"?[{code:"INVALID_RULE_COORD",message:`Layer '${t}': rule geom is not supported under polar coords`,layerId:t}]:[]}}class _l{constructor(t){this.registry=t}adjust(t,n){return this.registry.get(t).adjust(n)}}class Pt{}class Fl extends Pt{constructor(){super(...arguments),this.type="dodge"}adjust({data:t,mapping:n}){if(!v(n.x))return{data:t,mapping:{}};const s=t.getValues(z.group,{type:"categorical",distinct:!0,skipNulls:!0});if(s.length===0)return{data:t,mapping:{}};const a=t.size(),o=t.getValues(z.group,{type:"categorical"}),i=aa/2,c=s.length>1?Zi:0,l=ce.scaleBand().domain(s.map(String)).range([-i,i]).paddingInner(c).paddingOuter(0),u=l.bandwidth(),d=new Array(a).fill(null),p=new Array(a).fill(null);for(let y=0;y<a;y++){const g=o[y];if(!h(g))continue;const b=l(String(g));h(b)&&(d[y]=b,p[y]=b+u)}return{data:t.addVariable(f.xMin,"numeric",d).addVariable(f.xMax,"numeric",p),mapping:{}}}}const Jr=A("__ungrouped__"),xa=(e,t)=>{const n=v(t.x),r=v(t.y);if(!n||!r)return null;const s=e.getValues(z.group,{type:"categorical",distinct:!0,skipNulls:!0}),a=s.length===0,o=a?[Jr]:s,i=e.getValues(n),c=e.getValues(r,{type:"numeric"}),l=e.getValues(z.group,{type:"categorical"}),u=e.size(),d=new Map;for(let p=0;p<u;p++){const m=i[p]??null,y=l[p],g=a?Jr:y;if(!h(g))continue;let b=d.get(m);b||(b=new Map,d.set(m,b)),b.set(g,p)}return{yValues:c,observationIndexByXAndGroup:d,uniqueGroupKeys:o,observationCount:u}};class Rl extends Pt{constructor(){super(...arguments),this.type="fill"}adjust({data:t,mapping:n}){const r=xa(t,n);if(r===null)return{data:t,mapping:{}};const{yValues:s,observationIndexByXAndGroup:a,uniqueGroupKeys:o,observationCount:i}=r,c=[...s],l=new Array(i).fill(0);for(const[,d]of a){let p=0,m=0;for(const b of o){const x=d.get(b);if(x===void 0)continue;const S=s[x];S!=null&&(S>=0?p+=S:m-=S)}let y=0,g=0;for(const b of o){const x=d.get(b);if(x===void 0)continue;const S=s[x];if(S===void 0)continue;if(S===null){l[x]=null,c[x]=null;continue}const w=S>=0?p:m;if(w===0){l[x]=0,c[x]=0;continue}const k=S/w;S>=0?(l[x]=y,c[x]=y+=k):(c[x]=g,l[x]=g+=k)}}return{data:t.addVariable(f.yMin,"numeric",l).addVariable(f.yMax,"numeric",c).addVariable(f.yRaw,"numeric",s),mapping:{}}}}class Nl extends Pt{constructor(){super(...arguments),this.type="identity"}adjust({data:t}){return{data:t,mapping:{}}}}class Pl extends Pt{constructor(){super(...arguments),this.type="stack"}adjust({data:t,mapping:n}){const r=xa(t,n);if(r===null)return{data:t,mapping:{}};const{yValues:s,observationIndexByXAndGroup:a,uniqueGroupKeys:o,observationCount:i}=r,c=[...s],l=new Array(i).fill(0);for(const[,p]of a){let m=0,y=0;for(const g of o){const b=p.get(g);if(b===void 0)continue;const x=s[b];if(x!==void 0){if(x===null){l[b]=null,c[b]=null;continue}x>=0?(l[b]=m,c[b]=m+=x):(c[b]=y,l[b]=y+=x)}}}let u=t.addVariable(f.yMin,"numeric",l).addVariable(f.yMax,"numeric",c).addVariable(f.yRaw,"numeric",s);const d=v(n.y);return d!==null&&(u=u.addVariable(d,"numeric",c)),{data:u,mapping:{}}}}class Ol extends Ne{constructor(){super("position"),this.register("identity",new Nl),this.register("stack",new Pl),this.register("fill",new Rl),this.register("dodge",new Fl)}}class Bl{map({data:t,layer:n,getPositionScale:r}){const s=v(n.mapping.x),a=r("x");if(!s||!a)return t;const i=t.getValues(s).map(c=>h(c)?a.map(c):null);return t.addVariable(f.x,"numeric",i)}}class $l{map({data:t,getPositionScale:n}){const r=n("x");if(!r?.bandwidth||!t.hasVariable(f.x)||!t.hasVariable(f.xMin)||!t.hasVariable(f.xMax))return t;const s=t.getValues(f.x,{type:"numeric"}),a=t.getValues(f.xMin,{type:"numeric"}),o=t.getValues(f.xMax,{type:"numeric"}),i=t.size(),c=new Array(i),l=new Array(i);for(let u=0;u<i;u++){const d=s[u],p=a[u],m=o[u];h(d)&&h(p)&&h(m)?(c[u]=d+p*r.bandwidth,l[u]=d+m*r.bandwidth):(c[u]=null,l[u]=null)}return t.addVariable(f.xMin,"numeric",c).addVariable(f.xMax,"numeric",l)}}class Gl{map({data:t,layer:n,getPositionScale:r}){const s=v(n.mapping.y),a=Oe(n.yScaleType),o=r(a);if(!s||!o)return t;const c=t.getValues(s).map(l=>h(l)?o.map(l):null);return t.addVariable(f.y,"numeric",c)}}class zl{map({data:t,layer:n,getPositionScale:r}){const s=Oe(n.yScaleType),a=r(s);if(!a||!t.hasVariable(f.yMin)||!t.hasVariable(f.yMax))return t;const o=t.getValues(f.yMin,{type:"numeric"}),i=t.getValues(f.yMax,{type:"numeric"}),c=t.size(),l=new Array(c),u=new Array(c);for(let d=0;d<c;d++){const p=o[d],m=i[d];h(p)&&h(m)?(l[d]=a.map(p),u[d]=a.map(m)):(l[d]=null,u[d]=null)}return t.addVariable(f.yMin,"numeric",l).addVariable(f.yMax,"numeric",u)}}const Wl=[new Bl,new Gl,new $l,new zl];function Yl(e,t){const n=e[t];return n?.kind==="position"?n:null}class Hl extends Re{constructor(t=Wl){super(),this.mappers=t}dependencies(t){return[t.scales.x,t.scales.y,t.scales.ySecondary]}compileLayer(t,n){const r=a=>Yl(n.scales,a);let s=t.data;for(const a of this.mappers)s=a.map({data:s,layer:t,getPositionScale:r});return{...t,data:s}}}class Ul extends de{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),s={};for(const[a,o]of n){const i=r.get(a)??[],c=this.registry.get(o.scaleType);s[a]=c.compile(o,i)}return s}validateScaleTypeCompatibility(t){const n=[];for(const r of t.scales){const{compatibleDataTypes:s}=this.registry.get(r.scaleType),a=ee(r.scaledAesthetic),o=t.layers.find(l=>h(l.mapping[a]));if(!o)continue;const i=v(o.mapping[a]);if(!h(i)||!o.data.hasVariable(i))continue;const c=o.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: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 va(n)}collectValues(t,n){const r=new Map;for(const s of t)for(const[a,o]of Object.entries(s.mapping)){const i=a,c=i==="y"?Oe(s.yScaleType):i;if(!oc(c)||!n.has(c))continue;const l=this.resolveVariables(i,o,s.data);this.collectFromVariables(s.data,l,c,r)}return r}resolveVariables(t,n,r){if(t==="y"&&this.hasPositionAdjustedY(r))return[f.yMin,f.yMax];const s=v(n);return!s||!r.hasVariable(s)?[]:[s]}hasPositionAdjustedY(t){return t.hasVariable(f.yMin)&&t.hasVariable(f.yMax)}collectFromVariables(t,n,r,s){if(n.length===0)return;let a=[];for(const i of n)a=a.concat(t.getValues(i));const o=s.get(r);s.set(r,o?o.concat(a):a)}}class tt{createPositionScale(t,n){return{kind:"position",aesthetic:ee(t.scaledAesthetic),spec:t,...n}}createVisualScale(t,n){return{kind:"visual",aesthetic:ee(t.scaledAesthetic),spec:t,...n}}}class Kl extends tt{constructor(){super(...arguments),this.compatibleDataTypes=["numeric"]}compile(t,n){if(t.scaleType!=="continuous")throw new Error("ContinuousScale.compile received non-continuous spec");const r=_t(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 a of t)typeof a=="number"&&(a<r&&(r=a),a>s&&(s=a));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 a=r.transform==="log"&&Xl(s),o=a?ce.scaleLog():r.transform==="sqrt"?ce.scaleSqrt():ce.scaleLinear();return r.nice&&!a&&(s=o.copy().domain(s).nice().domain()),o.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:a=>a&&"count"in a?s.ticks(a.count):s.ticks()})}buildVisualScale(t,n){const r=n.range??[0,1],s=n.reverse?[r[1],r[0]]:r,a=this.createD3Scale(t,s,n);return this.createVisualScale(n,{map:a,domain:a.domain(),generateTicks:o=>o&&"count"in o?a.ticks(o.count):a.ticks()})}}const Xl=e=>{const[t,n]=e;return t>0&&n>0||t<0&&n<0};class jl extends tt{constructor(){super(...arguments),this.compatibleDataTypes=["temporal"]}compile(t,n){if(t.scaleType!=="datetime")throw new Error("DatetimeScale.compile received non-datetime spec");const r=_t(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 a=s.getTime();n.has(a)||(n.add(a),r.push(s))}return r.sort((s,a)=>s.getTime()-a.getTime()),r}computeDataDomain(t){let n=1/0,r=-1/0;for(const s of t){if(!(s instanceof Date))continue;const a=s.getTime();a<n&&(n=a),a>r&&(r=a)}return n===1/0?[]:[new Date(n),new Date(r)]}createD3Scale(t,n,r){const s=ql(t)?t:[],a=ce.scaleUtc().domain(s).range(n).clamp(r.clamp);if(r.nice&&a.nice(),h(r.domainMin)||h(r.domainMax)){const[o,i]=a.domain();o!==void 0&&i!==void 0&&a.domain([r.domainMin??o,r.domainMax??i])}return a}buildScale(t,n,r){const s=n.reverse?[1,0]:[0,1],a=this.createD3Scale(t,s,n),[o,i]=a.domain(),c=o&&i?r.filter(l=>l>=o&&l<=i):[];return this.createPositionScale(n,{map:a,domain:a.domain(),bandwidth:null,generateTicks:l=>l&&"atInputs"in l?c:l&&"interval"in l?o&&i?mc(o,i,l.interval):[]:a.ticks(l?.count)})}}const ql=e=>e.length===2&&G(e[0])&&G(e[1]),ke={transform:"linear",reverse:!1,nice:!0,zero:!1,domainMin:null,domainMax:null},es={size:[4,20],alpha:[.1,1],strokeWidth:[1,4]},lt={domainMin:null,domainMax:null,nice:!1,reverse:!1},Ye={range:null,domain:null,padding:.1,reverse:!1},Ql={palette:{type:"default"}};class Zl extends tt{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=_t(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 a of t)r.has(a)||(r.add(a),s.push(a));return s}buildPositionScale(t,n){const r=t.map(String),s=n.padding??Ye.padding,a=n.reverse?[1,0]:[0,1],o=ce.scaleBand().domain(r).range(a).paddingInner(s).paddingOuter(s/2),i=o.bandwidth()/2;return this.createPositionScale(n,{map:c=>(o(String(c))??0)+i,domain:t,bandwidth:o.bandwidth(),generateTicks:()=>[...t]})}buildVisualScale(t,n){const r=t.map(String),s=n.range&&n.range.length>0?ce.scaleOrdinal().domain(r).range(n.range).unknown(n.range[0]):null;return this.createVisualScale(n,{map:a=>{const o=String(a);return s?s(o):o},domain:t,generateTicks:()=>t})}}class Jl extends tt{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:ee(t.scaledAesthetic),spec:t,map:n=>n,domain:[],generateTicks:()=>[]}}}const Sa=["grey","red","orange","yellow","green","cyan","blue","purple","pink"],wa=["cyan","pink","purple","red","orange","yellow","green","blue"],Aa=["#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"},eu=[Q.purple,Q.pink,Q.yellow,Q.blue,Q.red,Q.cyan,Q.orange,Q.plum,Q.green,Q.dark_purple],K={green:"#B2DDC9",cyan:"#A2D5E2",blue:"#AAC4FF",purple:"#B2A4FF",plum:"#DCA8C7",pink:"#FFCCD3",red:"#FFADAD",orange:"#FFDEB4",yellow:"#FDF7C3"},tu=[K.green,K.purple,K.red,K.cyan,K.pink,K.blue,K.orange,K.plum,K.yellow],An={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"},nu=[An.grey200,K.green,K.red,An.grey200],ts={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]}},Y={cyan:"#22D3EE",pink:"#F377EF",purple:"#6528F7",red:"#FB2576",orange:"#FF9300",yellow:"#FBFF00",green:"#06FF00",blue:"#0079FF"},ut=[Y.cyan,Y.pink,Y.purple,Y.red,Y.orange,Y.yellow,Y.green,Y.blue],ru=[Y.cyan,Y.green,Y.red,Y.cyan],dt={start:"#84D1FC",positive:"#84FC89",negative:"#FC8497",total:"#84D1FC"},su=[dt.start,dt.positive,dt.negative,dt.total];function au(e,t="light",n){return((n!==void 0?ts[t][n]:void 0)??ts[t].default).map(s=>An[`${e}${s}`])}function ou(e){const t=ut.indexOf(Y[e]);return t<=0?ut:[...ut.slice(t),...ut.slice(0,t)]}function iu(e,t){switch(e.type){case"default":return Aa;case"graphy":return e.variant==="waterfall"?su:eu;case"pastel":return e.variant==="waterfall"?nu:tu;case"neon":return e.variant==="waterfall"?ru:ou(e.base);case"mono":return au(e.base,e.variant??"light",t);case"custom":return e.colors}}function cu(e,t){if(!t)return e;const n=[...e];for(const[r,s]of Object.entries(t)){const a=Number(r);if(!Number.isInteger(a)||a<1)continue;const o=a-1;o<n.length&&(n[o]=s)}return n}function lu(e,t,n){if(!e)return;const r=t?.type==="custom"?n[t.id]:void 0,s={};for(const[a,o]of Object.entries(e)){const i=Number(a);if(!(!Number.isInteger(i)||i<1)){if(o.hex!==void 0){s[i]=o.hex;continue}if(o.id!==void 0){const c=r?.find(l=>l.id===o.id)?.hex;c!==void 0?s[i]=c:console.warn(`[viz-engine] palette override at slot ${i} with id '${o.id}' did not resolve against the active palette — falling back to palette color.`)}}}return Object.keys(s).length>0?s:void 0}function uu(e,t){if(!e)return Ql.palette;if(e.type==="custom"){const n=t[e.id];if(!n)throw new Error(`Custom palette with id "${e.id}" not found`);const r=n.map(s=>s.hex);return{type:"custom",id:e.id,colors:r}}return e}class du extends tt{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=iu(t.palette,r.length),a=s.length>0?s:[...Aa],o=cu(a,t.overrides),i=ce.scaleOrdinal().domain(r.map(String)).range(o).unknown(o[0]);return this.createVisualScale(t,{map:c=>i(String(c)),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 pu extends Ne{constructor(){super("scale"),this.register("continuous",new Kl),this.register("discrete",new Zl),this.register("datetime",new jl),this.register("identity",new Jl),this.register("palette",new du)}}const Ta=e=>!("layers"in e),_={point:mu,line:fu,area:hu,bar:yu,rule:gu};function mu(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 fu(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 hu(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 yu(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 gu(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 zn={identity:vu,count:xu,smooth:bu,mean:Su};function bu(e){return{type:"smooth",method:e.method,order:e.order,bandwidth:e.bandwidth}}function vu(){return{type:"identity"}}function xu(){return{type:"count"}}function Su(){return{type:"mean"}}const xe={reshape:wu,filter:Au,sort:Tu,aggregate:Mu,constant:Lu};function wu(e={}){return{type:"transform",transformType:"reshape",options:e}}function Au(e){return{type:"transform",transformType:"filter",options:e}}function Tu(e){return{type:"transform",transformType:"sort",options:e}}function Mu(e){return{type:"transform",transformType:"aggregate",options:e}}function Lu(e){return{type:"transform",transformType:"constant",options:e}}const ns="#%_ENCODED_%#",Ma=e=>{if(!e.startsWith(ns))return e;try{const{value:t}=JSON.parse(e.slice(ns.length));return typeof t=="string"?t:e}catch{return e}},Vu=({annotations:e,dataset:t,mapping:n})=>{const r=[],s=[],a=[],o=[],i=[],c=[],l=[],u=v(n.x);for(const d of e??[])switch(d.type){case"difference-arrow":{const p=Eu(d,u,t);p!==null&&r.push(p);break}case"shape":{s.push(Iu(d));break}case"arrow":{a.push(_u(d));break}case"highlight":break;case"text":{o.push(ku(d));break}case"sticker":{const p=Cu(d,u,t);p!==null&&i.push(p);break}case"tooltip":{const p=Du(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:a,textAnnotations:o,stickers:i,pinnedNumbers:c,comments:l}},Eu=(e,t,n)=>{const r=Mt({dataset:n,input:e.start,anchorVariable:t}),s=Mt({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}},Iu=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}),ku=e=>({id:e.id,content:e.content,x:e.x,y:e.y,width:e.width,backgroundColor:e.backgroundColor??null,backgroundColorStyle:e.backgroundColorStyle}),Cu=(e,t,n)=>{const r=Mt({dataset:n,input:e,anchorVariable:t});return r===null?null:{id:e.id,anchor:r,sticker:e.sticker}},Du=(e,t,n)=>{const r=Mt({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}}},_u=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}),Mt=({dataset:e,input:t,anchorVariable:n})=>{if(!h(t)||!h(t.columnKey))return null;const r=Fu(t,n,e);return r===null?null:{anchorValue:r,groupValue:Ma(t.columnKey)}},Fu=(e,t,n)=>e.rowValue!==void 0?e.rowValue:t===null||!h(e.rowIndex)||!n.hasVariable(t)?null:n.getValues(t)[e.rowIndex]??null,La=["lilac","neon_pink","blackberry","sun","iceland","sunset","ultraviolet","purple","ice_cream","mint","cool","fresh"];function Va(e){return{type:"config",config:e}}const Ru="#E5E5E5",Nu={x:"top",y:"left"},Pu=new Set(["pie","donut"]);function Ou(e){return Va({legend:Wu(e.legend),axes:Hu(e.axes),headline:Uu(e),numberFormat:Ku(e.appearance),content:Xu(e.content),appearance:Bu(e.appearance,e.themeOverrides)}).config}function Bu(e,t){const n=zu(e?.border),r=e?.hasRoundedCorners===!1?0:void 0,s=$u(e,t),a={};return e?.textScale!==void 0&&(a.textScale=e.textScale),n!==void 0&&(a.border=n),r!==void 0&&(a.cornerRadius=r),s!==void 0&&(a.background=s),e?.highlightStyle!==void 0&&(a.highlightStyle=e.highlightStyle==="grey"?"desaturate":"dim"),Object.keys(a).length>0?a:void 0}function $u(e,t){if(e?.backgroundModifier==="tint")return{type:"tinted"};const n=t?.graphBackground;if(typeof n=="string")return{type:"solid",color:n}}const Gu=e=>La.includes(e);function zu(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:Ru,width:t};if(e.style==="preset")return e.color===void 0||!Gu(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 Wu(e){if(e)return{position:e.position}}function rs(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:Nu[e]}:void 0,...t?.tickDisplayMode?{labels:{mode:t.tickDisplayMode}}:void 0,...n!==void 0?{grid:{isVisible:n}}:void 0}}function Yu(e){return{...e.label!==void 0?{label:e.label}:void 0}}function Hu(e){if(e)return{x:rs("x",e.x,e.showGridLines),y:rs("y",e.y,e.showGridLines),...e.y2?{ySecondary:Yu(e.y2)}:void 0}}function Uu(e){const{headlineNumbers:t,options:n,type:r}=e,s=r!==void 0&&Pu.has(r)?n?.pieTotalPosition:void 0;if(t===void 0&&s===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),s!==void 0&&(a.show="total",a.position=s==="center"?"center":"above"),a}function Ku(e){if(e?.numberFormat)return{decimals:e.numberFormat.decimalPlaces,abbreviation:e.numberFormat.abbreviation}}function Xu(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=ju(e.source);return n!==void 0&&(t.source=n),e.isSourceHidden!==void 0&&(t.isSourceVisible=!e.isSourceHidden),t}function ju(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})},qu={showDataLabels:!1,format:"absolute",showStackTotals:!1,showCategoryLabels:!1,labelSource:{variable:f.yRaw}},vt={stat:{type:"identity"},position:"identity",params:{size:8}},rn={stat:{type:"identity"},position:"identity",params:{lineWidth:"auto",interpolate:"linear",missingValues:"gap"}},sn={stat:{type:"identity"},position:"stack",params:{lineWidth:"auto",interpolate:"linear",missingValues:"zero"}},an={stat:{type:"identity"},position:"dodge",params:{}},Ge={stat:{type:"identity"},position:"identity",interactive:!1,params:{strokeWidth:1,lineType:"dashed",labelPosition:"start"}},nt="primary";function Qu(e,t){const n={...qu};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 xt(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 He(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"identity"}}function St(e,t){return{type:"scale",scaledAesthetic:e,scaleType:"inferred",options:t}}function Ea(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"palette",palette:t.palette,overrides:t.overrides}}const Se={x:Object.assign(e=>St("x",e),{continuous:e=>F("x",e),discrete:e=>Z("x",e),datetime:e=>xt("x",e),log:e=>F("x",{...e,transform:"log"}),sqrt:e=>F("x",{...e,transform:"sqrt"})}),y:Object.assign(e=>St("y",e),{continuous:e=>F("y",e),discrete:e=>Z("y",e),datetime:e=>xt("y",e),log:e=>F("y",{...e,transform:"log"}),sqrt:e=>F("y",{...e,transform:"sqrt"})}),ySecondary:Object.assign(e=>St("ySecondary",e),{continuous:e=>F("ySecondary",e),discrete:e=>Z("ySecondary",e),datetime:e=>xt("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=>Ea("color",e)},size:{continuous:e=>F("size",e),discrete:e=>Z("size",e),identity:e=>He("size",e)},alpha:{continuous:e=>F("alpha",e),discrete:e=>Z("alpha",e),identity:e=>He("alpha",e)},strokeWidth:{continuous:e=>F("strokeWidth",e),discrete:e=>Z("strokeWidth",e),identity:e=>He("strokeWidth",e)},lineType:{discrete:e=>Z("lineType",e),identity:e=>He("lineType",e)}},U="key",se="value",ss=A("lineSeriesLabel"),as=A("barSeriesLabel"),Lt=A("constantY"),Zu=(e,t,n,r)=>ad[t](e,n,r),Wn=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]:""},Yn=e=>{const t=Wn(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:U,valueName:se}),mapping:{x:t,y:se,color:U},seriesVariables:r}},Hn=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 a=t[s]?.lineStyle;return a?{mapping:{lineType:{value:a}},scales:[]}:{mapping:{},scales:[]}}const r=e.seriesVariables.map(s=>t[s]?.lineStyle??"solid");return{mapping:{lineType:U},scales:[Se.lineType.discrete({domain:e.seriesVariables,range:r})]}},Ju=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 a=r.slice(1);return a.length===0?{dataset:e.addConstantVariable(Lt,"categorical",""),mapping:{x:s,y:Lt,label:t[0]}}:a.length===1?{dataset:e,mapping:{x:s,y:a[0]??"",label:t[0]}}:{dataset:e.reshapeFromWideToLong({keep:[s,...t,...n],keyName:U,valueName:se}),mapping:{x:s,y:se,label:t[0],color:U}}},ed=e=>{const{categorical:t,temporal:n,numeric:r}=e.groupVariableNamesByType();let s,a;if(h(t[0])&&h(r[0]))s=t[0],a=r[0];else if(h(n[0])&&h(r[0]))s=n[0],a=r[0];else if(h(r[0])&&h(r[1]))s=r[0],a=r[1];else throw new Error("No label or value variable found");return{x:"",y:a,color:s}},Ia=(e,t,n)=>{const{dataset:r,mapping:s,seriesVariables:a}=Yn(e.dataset),o=Hn({appearance:n,seriesVariables:a}),i=[_.line({params:{lineWidth:t?.lineThickness,interpolate:t?.isSmoothLine?"catmull-rom":"linear",missingValues:t?.missingValues}})];return t?.showPoints&&i.push(_.point({params:{size:ka(t.pointSize)},interactive:!1})),{dataset:r,layers:i,coords:B.cartesian(),mapping:{...s,...o.mapping},scales:o.scales,seriesVariables:a}},td=(e,t,n)=>{const{dataset:r,mapping:s,seriesVariables:a}=Yn(e.dataset),o=Hn({appearance:n,seriesVariables:a}),i=[_.area({position:"stack",params:{lineWidth:t?.lineThickness,interpolate:t?.isSmoothLine?"catmull-rom":"linear",missingValues:t?.missingValues}})];return t?.showPoints&&i.push(_.point({params:{size:ka(t.pointSize)},position:"stack",interactive:!1})),{dataset:r,layers:i,coords:B.cartesian(),mapping:{...s,...o.mapping},scales:o.scales,seriesVariables:a}},ge=(e,t,n,r,s)=>{const{dataset:a,mapping:o,seriesVariables:i}=Yn(e.dataset),c=[];if(r?.sortBars){const l=v(o.y);l!==null&&l!==""&&c.push(xe.sort({variableName:l,direction:"desc"}))}if(!s?.useSingleColorForBars){const l=Wn(e.dataset),{numeric:u}=e.dataset.groupVariableNamesByType();u.filter(p=>p!==l).length===1&&e.dataset.getType(l)==="categorical"&&(o.color=l)}return{dataset:a,layers:[_.bar({position:t})],coords:n,mapping:o,scales:[],transforms:c,seriesVariables:i}},os=(e,t)=>({dataset:e.dataset,layers:[_.bar({position:"fill"})],coords:B.polar({theta:"y",innerRadius:t==="donut"?.55:0}),mapping:ed(e.dataset),scales:[],seriesVariables:[]}),nd=e=>{const{dataset:t,mapping:n}=Ju(e.dataset);return{dataset:t,layers:[_.point()],coords:B.cartesian(),mapping:n,scales:[],seriesVariables:[]}},rd=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(Lt,"categorical",""),o={x:r,y:t[1]??Lt,size:t[2],label:n[0]},i=[];return h(o.size)&&i.push(Se.size.continuous()),{dataset:a,layers:[_.point()],coords:B.cartesian(),mapping:o,scales:i,seriesVariables:[]}},on=(e,t,n)=>{const r=n?.seriesStyles?.[e]?.lineStyle;return _.line({transforms:[xe.constant({variableName:ss,type:"categorical",value:e})],aes:{y:e,color:ss,...r?{lineType:{value:r}}:{}},...t?{yScaleType:"secondary"}:void 0})},sd=(e,t,n)=>{const{numeric:r,categorical:s,temporal:a}=e.dataset.groupVariableNamesByType(),o=Wn(e.dataset),i=[...s,...a],c=r.filter(b=>b!==o),l=t?.comboType??"grouped-bars",u=l==="lines";if(c.length===1)return u?Ia(e,t,n):ge(e,"dodge",B.cartesian(),t,n);const d=e.axes?.hasDualYAxis===!0,p=u?[]:c.slice(0,-1),m=u?c:c.slice(-1),y=[],g=[];if(p.length>0){const b=l==="stacked-bars"?"stack":"dodge",x=p.length===1?p[0]:null;h(x)?y.push(_.bar({transforms:[xe.constant({variableName:as,type:"categorical",value:x})],aes:{y:x,color:as},position:b})):y.push(_.bar({transforms:[xe.reshape({keep:i,reshape:p,keyName:U,valueName:se})],aes:{y:se,color:U},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))y.push(on(x,!1,n));else{const S=Hn({appearance:n,seriesVariables:b});y.push(_.line({transforms:[xe.reshape({keep:i,reshape:b,keyName:U,valueName:se})],aes:{y:se,color:U,...S.mapping}})),g.push(...S.scales)}if(d){const S=m[m.length-1];h(S)&&y.push(on(S,!0,n))}}else for(const b of m)y.push(on(b,d,n));return{dataset:e.dataset,layers:y,coords:B.cartesian(),mapping:{x:o},scales:g,seriesVariables:c}},ka=(e="auto")=>e==="auto"?vt.params.size:e,ze=e=>()=>{throw new Error(`Unsupported graph type: ${e}`)},ad={line:(e,t,n)=>Ia(e,t,n),areaStacked:(e,t,n)=>td(e,t,n),bar:(e,t,n)=>ge(e,"dodge",B.flip(),t,n),barStacked:(e,t,n)=>ge(e,"stack",B.flip(),t,n),barStackedFill:(e,t,n)=>ge(e,"fill",B.flip(),t,n),column:(e,t,n)=>ge(e,"dodge",B.cartesian(),t,n),columnStacked:(e,t,n)=>ge(e,"stack",B.cartesian(),t,n),columnStackedFill:(e,t,n)=>ge(e,"fill",B.cartesian(),t,n),pie:e=>os(e,"pie"),donut:e=>os(e,"donut"),scatter:e=>nd(e),bubble:e=>rd(e),combo:(e,t,n)=>sd(e,t,n),funnel:ze("funnel"),heatmap:ze("heatmap"),waterfall:ze("waterfall"),mekko:ze("mekko"),table:ze("table")},Ca=["key",A("lineSeriesLabel"),A("barSeriesLabel")];function od(e){const t=e.annotations??[],n=id(e.mapping),r=ud(e.convertedDataset,e.layers),s=[];for(const a of t){if(a.type!=="highlight")continue;const o=cd({annotation:a,rowIdentityVariable:n,dataset:e.dataset,compiledVariableNames:r});o!==null&&s.push({type:"highlight",id:a.id,predicate:o,scope:a.highlight})}return s}function id(e){const t=v(e.x);return t!==null&&t!==""?t:v(e.color)}function cd({annotation:e,rowIdentityVariable:t,dataset:n,compiledVariableNames:r}){switch(e.highlight){case"x-value":return is(e,t,n);case"series":return cs(e,r);case"data-point":{const s=is(e,t,n),a=cs(e,r);return s===null&&a===null?null:s===null?a:a===null?s:{and:[s,a]}}}}function is(e,t,n){if(t===null)return null;const r=dd(e,t,n);return r===null?null:{variable:t,eq:r}}function cs(e,t){if(!ld(t))return null;const n=e.columnKey;return h(n)?{or:Ca.map(r=>({variable:r,eq:n}))}:null}function ld(e){return Ca.some(t=>e.includes(t))}function ud(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??U):s.transformType==="constant"&&n.push(s.options.variableName);return n}function dd(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 pd(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:cn(t)};if(e?.startsWith("preset:graphy"))return{type:"graphy",variant:cn(t)};const i="preset:mono:";if(e?.startsWith(i)){const l=e.slice(i.length);if(md(l))return{type:"mono",base:l,variant:r}}const c="preset:neon:";if(e?.startsWith(c)){const l=e.slice(c.length);if(fd(l))return{type:"neon",base:l,variant:cn(t)}}return{type:"default"}}function cn(e){if(e==="waterfall")return"waterfall"}function md(e){return Sa.includes(e)}function fd(e){return wa.includes(e)}function hd(e){if(!e)return;const t={};for(const[n,r]of Object.entries(e)){if(!n.startsWith("series"))continue;const s=Number.parseInt(n.slice(6));if(Number.isNaN(s))continue;const a={hex:r.customColor,id:r.paletteColorId};(a.hex!==void 0||a.id!==void 0)&&(t[s]=a)}return Object.keys(t).length>0?t:void 0}function yd(e,t,n,r={}){const s=[];s.push(ls("x",t?.x)),s.push(ls("y",t?.y));const a=pd(n?.paletteId,e,r),o=hd(n?.seriesStyles);return s.push(Se.color.palette({palette:a,overrides:o})),s}function ls(e,t){return t?.scaleType==="logarithmic"||t?.min!==void 0||t?.max!==void 0?t.scaleType==="logarithmic"?Se[e].log({domainMin:t.min??void 0,domainMax:t.max??void 0}):Se[e]({domainMin:t.min??void 0,domainMax:t.max??void 0}):Se[e]()}const gd=new Set(["column","columnStacked","columnStackedFill","bar","barStacked","barStackedFill","line","areaStacked","scatter","bubble","funnel","combo"]),bd=new Set(["column","columnStacked","columnStackedFill","bar","barStacked","barStackedFill","line","areaStacked","combo"]);function vd(e,t,n){const r=t.type??"column",s={dataset:e,axes:t.axes},a=Zu(s,r,t.options??void 0,t.appearance??void 0);return{data:a.dataset,mapping:a.mapping,layers:xd(r,t,a.layers,a.coords,a.mapping,a.seriesVariables),scales:[...yd(r,t.axes,t.appearance,n),...a.scales],transforms:a.transforms??[],highlights:od({annotations:t.annotations,dataset:e,mapping:a.mapping,convertedDataset:a.dataset,layers:a.layers}),annotations:Vu({annotations:t.annotations,dataset:e,mapping:a.mapping}),coords:a.coords,config:Ou(t)}}function xd(e,t,n,r,s,a){const o=Md(t.dataLabels),i=o===void 0?n:n.filter(l=>l.interactive!==!1).map(l=>({...l,dataLabels:{...o,...l.dataLabels}})),c=t.axes?.hasDualYAxis??!1;return[...i,...Sd({type:e,trendline:t.referenceLines?.trendline,coords:r}),...wd({type:e,hasDualYAxis:c,goalLine:t.referenceLines?.goalLine,coords:r}),...Td({type:e,hasDualYAxis:c,averageLine:t.referenceLines?.averageLine,coords:r,mapping:s,seriesVariables:a})]}function Sd({type:e,trendline:t,coords:n}){return t===void 0?[]:gd.has(e)?n.coordType==="polar"?[]:[_.line({aes:{lineType:{value:"dashed"}},stat:zn.smooth({method:t}),interactive:!1})]:[]}function wd({type:e,hasDualYAxis:t,goalLine:n,coords:r}){if(!Ad(n))return[];if(r.coordType==="polar")return[];const s=r.coordType==="flip"?"end":"start";return[_.rule({aes:{y:{value:n.target}},params:{labelPosition:s,label:n.label??"Goal"},yScaleType:e==="combo"&&t?"secondary":"primary",interactive:!1})]}function Ad(e){return e!==void 0&&Number.isFinite(e.target)}function Td({type:e,hasDualYAxis:t,averageLine:n,coords:r,mapping:s,seriesVariables:a}){if(n===void 0)return[];if(!bd.has(e))return[];if(r.coordType==="polar")return[];const o=Ma(n.columnKey);if(!a.includes(o))return[];const i=s.color===U,c=i?se:o,l=i?[xe.filter({variableName:U,operator:"eq",value:o})]:[];return[_.rule({aes:{y:c,color:void 0,group:void 0,lineType:void 0},stat:zn.mean(),transforms:l,params:{label:"Average",labelPosition:r.coordType==="flip"?"end":"start"},yScaleType:e==="combo"&&t?"secondary":"primary",interactive:!1})]}function Md(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 ln={color:null,size:"small",labelCrossPosition:.5},Ce={kind:"rectangle",zOrder:"foreground",fillColor:"transparent",fillOpacity:1,strokeWidth:1,strokeColor:null},us={backgroundColor:null,backgroundColorStyle:"opaque"},De={color:null,thickness:"medium",startArrowheadStyle:"none",endArrowheadStyle:"line-arrow",lineStyle:"solid",hasStickerStyle:!1},Ld=(e,t)=>({differenceArrows:(e?.differenceArrows??[]).map(n=>Ed(n,t)),shapes:(e?.shapes??[]).map(Dd),freeformArrows:(e?.freeformArrows??[]).map(_d),textAnnotations:(e?.textAnnotations??[]).map(Vd),stickers:(e?.stickers??[]).map(n=>Id(n,t)),pinnedNumbers:(e?.pinnedNumbers??[]).map(n=>kd(n,t)),comments:(e?.comments??[]).map(n=>Cd(n,t))}),Vd=e=>({id:e.id??crypto.randomUUID(),content:e.content,x:e.x,y:e.y,width:e.width,backgroundColor:e.backgroundColor??us.backgroundColor,backgroundColorStyle:e.backgroundColorStyle??us.backgroundColorStyle}),Ed=(e,t)=>({id:e.id??crypto.randomUUID(),start:Qe(e.start,t),end:Qe(e.end,t),label:e.label,color:e.color??ln.color,size:e.size??ln.size,labelCrossPosition:e.labelCrossPosition??ln.labelCrossPosition}),Qe=(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}},Id=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:Qe(e.anchor,t),sticker:e.sticker}),kd=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:Qe(e.anchor,t)}),Cd=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:Qe(e.anchor,t),content:e.content}),Dd=e=>({id:e.id??crypto.randomUUID(),kind:e.kind??Ce.kind,zOrder:e.zOrder??Ce.zOrder,x:e.x,y:e.y,width:e.width,height:e.height,fillColor:e.fillColor??Ce.fillColor,fillOpacity:e.fillOpacity??Ce.fillOpacity,strokeWidth:e.strokeWidth??Ce.strokeWidth,strokeColor:e.strokeColor??Ce.strokeColor}),_d=e=>({id:e.id??crypto.randomUUID(),start:e.start,end:e.end,color:e.color??De.color,thickness:e.thickness??De.thickness,startArrowheadStyle:e.startArrowheadStyle??De.startArrowheadStyle,endArrowheadStyle:e.endArrowheadStyle??De.endArrowheadStyle,lineStyle:e.lineStyle??De.lineStyle,hasStickerStyle:e.hasStickerStyle??De.hasStickerStyle}),Fd={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 Rd(e){return ue.merge({},Fd,e)}const Nd={xLimits:null,yLimits:null},un={theta:"x",startAngle:0,innerRadius:0};function Pd(e){const t=e??{type:"coord",coordType:"cartesian"},n=Is({},Nd,t.params??{});switch(t.coordType){case"cartesian":case"flip":return{...t,params:n};case"polar":return{...t,params:{...n,theta:t.params?.theta??un.theta,startAngle:t.params?.startAngle??un.startAngle,innerRadius:t.params?.innerRadius??un.innerRadius}}}}function Od(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 Bd="linear",$d=3,Gd=.3;function rt(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??Bd,order:s?.order??$d,bandwidth:s?.bandwidth??Gd}}return{type:r}}function Da(e,t,n){switch(n.geom){case"point":return Yd(e,t,n);case"line":return Hd(e,t,n);case"area":return Ud(e,t,n);case"bar":return Kd(e,t,n);case"rule":return Xd(e,t,n)}}function zd(e,t,n){const r=n.map(s=>Da(e,t,s));return jd(r)}const Wd=(e,t,n)=>n.label!==void 0?n.label:qd(e,t,n),st=(e,t,n,r)=>{const s={...e,...t.mapping},a=Wd(t.geom,n,s);return{...Qu(t.geom,r),...t.dataLabels,labelSource:a}};function Yd(e,t,n){const r=n.position??vt.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:rt(n.stat,vt.stat.type),position:r,yScaleType:n.yScaleType??nt,params:ue.merge({},vt.params,n.params),transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:st(e,n,r,t)}}function Hd(e,t,n){const r=n.position??rn.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:rt(n.stat,rn.stat.type),position:r,yScaleType:n.yScaleType??nt,params:ue.merge({},rn.params,n.params),transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:st(e,n,r,t)}}function Ud(e,t,n){const r=ue.merge({},sn.params,n.params);r.missingValues==="gap"&&(r.missingValues="zero");const s=n.position??sn.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:rt(n.stat,sn.stat.type),position:s,yScaleType:n.yScaleType??nt,params:r,transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:st(e,n,s,t)}}function Kd(e,t,n){const r=n.position??an.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:rt(n.stat,an.stat.type),position:r,yScaleType:n.yScaleType??nt,params:{...an.params,...n.params},transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:st(e,n,r,t)}}function Xd(e,t,n){const r=n.position??Ge.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:rt(n.stat,Ge.stat.type),position:n.position??Ge.position,yScaleType:n.yScaleType??nt,params:ue.merge({},Ge.params,n.params),transforms:n.transforms??[],interactive:n.interactive??Ge.interactive,dataLabels:st(e,n,r,t)}}const jd=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=le(n.mapping.y);if(!D(r))return n;const s=Math.min(1,Math.max(0,r));return{...n,mapping:{...n.mapping,y:{value:s}}}})},qd=(e,t,n)=>{if(e==="point"){const r=v(n.size);if(r!==null)return{variable:r}}return Rt(t,n)};function Ot(e,...t){return e?t.includes(e.geom):!1}function Bt(e,t){return e.find(n=>n.id===t)}function at(e,...t){return e.find(n=>t.includes(n.geom))}function Un(e,t,n){const r=e.layers.findIndex(a=>a.id===t);if(r===-1)return e;const s=e.layers.map((a,o)=>o===r?n:a);return{...e,layers:s}}function Qd(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,a)=>a!==n);return In(r)?{...e,layers:r}:e}const _a={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 Fa(e,t,n,r,s){switch(e.scaleType){case"inferred":{const a=tp(e,t,n,r);return Fa(a,t,n,r,s)}case"continuous":{const a=_a[e.scaledAesthetic],o=a==="continuous-range"&&e.scaledAesthetic in es?es[e.scaledAesthetic]:null,i=e.scaledAesthetic==="size"&&a==="continuous-range"?"sqrt":ke.transform;return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,transform:e.transform??i,reverse:e.reverse??ke.reverse,nice:e.nice??ke.nice,zero:e.zero??ke.zero,clamp:e.clamp??a!=="position",domainMin:e.domainMin??ke.domainMin,domainMax:e.domainMax??ke.domainMax,range:e.range??o??null}}case"datetime":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,domainMin:e.domainMin??lt.domainMin,domainMax:e.domainMax??lt.domainMax,nice:e.nice??lt.nice,reverse:e.reverse??lt.reverse,clamp:e.clamp??!1};case"discrete":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,range:e.range??Ye.range,domain:e.domain??Ye.domain,padding:e.padding??Ye.padding,reverse:e.reverse??Ye.reverse};case"palette":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,palette:uu(e.palette,s),overrides:lu(e.overrides,e.palette,s)};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 Jd(e,t,n,r,s,a){const o=rp(t,n),i=sp(o),c=new Map;for(const u of i)c.set(u.scaledAesthetic,u);const l=[...c.values()].map(u=>Fa(u,e,n,r,a));return s.coordType==="polar"?ep(l):l}const ep=e=>e.map(t=>t.scaleType==="discrete"?{...t,padding:0}:t);function tp(e,t,n,r){const s=ee(e.scaledAesthetic),a=e.scaledAesthetic==="ySecondary"?np(n,r):r[s],o=at(n,"bar");if(e.scaledAesthetic==="x"&&o)return Z(e.scaledAesthetic,e.options);if(o&&e.scaledAesthetic===(o.yScaleType==="secondary"?"ySecondary":"y")){const d=e.options,p=o.position==="fill";return F(e.scaledAesthetic,{...d,zero:!0,...p&&{nice:!1}})}const i=v(a);if(!h(i)||!t.hasVariable(i))return F(e.scaledAesthetic,e.options);const c=t.getType(i),l=_a[e.scaledAesthetic];switch(Zd[c][l]){case"discrete":return Z(e.scaledAesthetic,e.options);case"datetime":return xt(e.scaledAesthetic,e.options);case"continuous":return F(e.scaledAesthetic,e.options);case"identity":default:return He(e.scaledAesthetic)}}function np(e,t){const n=e.find(r=>r.yScaleType==="secondary");return n?n.mapping.y??t.y:t.y}function rp(e,t){return!t.some(s=>s.yScaleType==="secondary")||e.some(s=>s.scaledAesthetic==="ySecondary")?e:[...e,St("ySecondary")]}function sp(e){return e.some(n=>n.scaledAesthetic==="color")?e:[...e,Ea("color")]}function ds(e,t){const n=Pd(e.coords),r=zd(e.mapping,n.coordType,e.layers),s=Jd(e.data,e.scales,r,e.mapping,n,t),a=Rd(e.config),o=Od(e.highlights,r),i=Ld(e.annotations,r);return{data:e.data,mapping:e.mapping,layers:r,scales:s,transforms:e.transforms,highlights:o,annotations:i,coords:n,config:a}}class Ra{compile({input:t,dataset:n,ctx:r}){const s=r.customPalettes??{};return Ta(t)?ds(vd(n,t,r),s):ds({...t,data:n},s)}}class ap{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 op 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,...Pn(t,n)])];return{data:t.groupBy(...a).rollup({[je.count]:{variableName:r,aggregation:"count"}}),mapping:{y:je.count}}}}class ip extends $t{constructor(){super(...arguments),this.type="identity",this.computedVariables=new Set}computeStat({data:t}){return{data:t,mapping:{}}}}class cp 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({[je.mean]:{variableName:r,aggregation:"mean"}}),mapping:{y:je.mean}}}}const lp=2,Na=1440*60*1e3;class up extends $t{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 a=v(n.x),o=v(n.y);if(!h(a))throw new Error("'x' variable is required for 'smooth' stat");if(!h(o))throw new Error("'y' variable is required for 'smooth' stat");const i=t.getType(a),c=t.getType(o);if(c!=="numeric")throw new Error(`'smooth' stat requires a numeric 'y' (got '${c}' for variable '${o}')`);const l=Pn(t,n),u=gp(a,i,o,l,t);return l.length===0?ps({data:t,xVariable:a,xType:i,yVariable:o,spec:r,output:u,groupObservation:{},xScaleIsDiscrete:s}):t.groupBy(...l).forEach(d=>{const p=bp(d,l);ps({data:d,xVariable:a,xType:i,yVariable:o,spec:r,output:u,groupObservation:p,xScaleIsDiscrete:s})}),{data:u.build(),mapping:{}}}}const ps=({data:e,xVariable:t,xType:n,yVariable:r,spec:s,output:a,groupObservation:o,xScaleIsDiscrete:i})=>{const{observations:c,temporalOrigin:l}=dp({data:e,xVariable:t,yVariable:r,xType:n});c.length<lp||(i?yp({observations:c,spec:s,output:a,groupObservation:o}):fp({observations:c,xType:n,temporalOrigin:l,spec:s,output:a,groupObservation:o}))},dp=({data:e,xVariable:t,yVariable:n,xType:r})=>{const s=e.getValues(t),a=e.getValues(n,{type:"numeric"}),o=r==="temporal"?pp(s):null,i=[],c=new Map;for(let l=0;l<s.length;l++){const u=s[l],d=a[l];if(!h(u)||!h(d)||!Number.isFinite(d))continue;const p=mp({xValue:u,xType:r,categoryRank:c,temporalOrigin:o});p!==null&&i.push({x:p,y:d,originalX:u})}return{observations:i,temporalOrigin:o}},pp=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},mp=({xValue:e,xType:t,categoryRank:n,temporalOrigin:r})=>{switch(t){case"numeric":return!D(e)||!Number.isFinite(e)?null:e;case"temporal":{if(!G(e))return null;const s=e.getTime();return r===null?s:(s-r)/Na+1}case"categorical":{if(!Ze(e))return null;const s=n.get(e);if(s!==void 0)return s;const a=n.size+1;return n.set(e,a),a}default:{const s=t;throw new Error(`Unexpected xType: ${s}`)}}},fp=({observations:e,xType:t,temporalOrigin:n,spec:r,output:s,groupObservation:a})=>{const o=Pa(r,e);for(const[i,c]of o){if(!Number.isFinite(i)||!Number.isFinite(c))continue;const l=t==="temporal"?hp(i,n):i;s.push({x:l,y:c,groupObservation:a})}},hp=(e,t)=>t===null?new Date(e):new Date((e-1)*Na+t),yp=({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 a=[...s.keys()].sort((i,c)=>i-c);if(t.method==="loess"){const i=Pa(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=s.get(l);u===void 0||d===void 0||n.push({x:d,y:u,groupObservation:r})}return}const o=Oa(t,e);for(const i of a){const c=s.get(i),l=o.predict(i);c===void 0||!Number.isFinite(l)||n.push({x:c,y:l,groupObservation:r})}},Pa=(e,t)=>e.method==="loess"?ye.regressionLoess().x(r=>r.x).y(r=>r.y).bandwidth(e.bandwidth)(t):Oa(e,t),Oa=(e,t)=>{const n=s=>s.x,r=s=>s.y;switch(e.method){case"linear":return ye.regressionLinear().x(n).y(r)(t);case"exponential":return ye.regressionExp().x(n).y(r)(t);case"logarithmic":return ye.regressionLog().x(n).y(r)(t);case"quadratic":return ye.regressionQuad().x(n).y(r)(t);case"power":return ye.regressionPow().x(n).y(r)(t);case"polynomial":return ye.regressionPoly().x(n).y(r).order(e.order)(t);case"loess":throw new Error("'loess' does not expose a 'predict' function")}},gp=(e,t,n,r,s)=>{const a=[],o=[],i=Object.fromEntries(r.map(c=>[c,[]]));return{push:({x:c,y:l,groupObservation:u})=>{a.push(c),o.push(l);for(const d of r)i[d]?.push(u[d]??null)},build:()=>{const c={[e]:{type:t,values:a,valueFormat:s.getValueFormat(e)},[n]:{type:"numeric",values:o,valueFormat:s.getValueFormat(n)}};for(const l of r)c[l]={type:s.getType(l),values:i[l]??[],valueFormat:s.getValueFormat(l)};return new I(c)}}},bp=(e,t)=>{const n={};for(const r of t){const s=e.getValues(r);n[r]=s[0]??null}return n};class vp extends Ne{constructor(){super("stat"),this.register("identity",new ip),this.register("count",new op),this.register("smooth",new up),this.register("mean",new cp)}}const xp=({layer:e})=>{if(e.geom!=="bar"||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 a=s[t];D(a)&&(n+=a,r+=Math.abs(a))}return{grandTotal:n,absoluteGrandTotal:r}},Sp=({layer:e})=>{if(e.geom!=="bar"||e.position!=="stack")return;const t=v(e.mapping.x);if(t===null||!e.data.hasVariable(f.yMin)||!e.data.hasVariable(f.yMax))return;const n=new Map;for(const s of e.data){const a=s[t],o=te(s),i=H(s),c=me(s),l=ae(s),u=Fs(s);if(!h(a)||!h(o)||!h(i)||!h(c)||!h(l)||!h(u))continue;const d=u>=0;if(Math.abs(u)===0)continue;const m=Gn(s,t),y={yMin:o,yMax:i},g=n.get(m);if(g===void 0){n.set(m,{total:u,topPositive:d?y:null,bottomNegative:d?null:y,anchorXMin:c,anchorXMax:l});continue}g.total+=u,d?(g.topPositive===null||i>g.topPositive.yMax)&&(g.topPositive=y):(g.bottomNegative===null||o<g.bottomNegative.yMin)&&(g.bottomNegative=y)}const r=[];for(const[s,a]of n){const o=a.topPositive??a.bottomNegative;o!==null&&r.push({xKey:s,total:a.total,anchor:{xMin:a.anchorXMin,xMax:a.anchorXMax,yMin:o.yMin,yMax:o.yMax,direction:a.topPositive!==null?"positive":"negative"}})}return r};class wp extends Re{dependencies(){return[]}compileLayer(t){const n={},r=Sp({layer:t});r!==void 0&&(n.stackTotals=r);const s=xp({layer:t});return s!==void 0&&(n.grandTotal=s.grandTotal,n.absoluteGrandTotal=s.absoluteGrandTotal),{...t,summary:n}}}class Ap extends de{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 Tp{constructor(){this.transformType="aggregate"}apply(t,n){const{options:r}=n,s={};for(const a of r.operations)s[a.as]={variableName:a.variableName,aggregation:a.op};return t.groupBy(...r.groupby).rollup(s)}}class Mp{constructor(){this.transformType="constant"}apply(t,n){const{options:r}=n;return t.addConstantVariable(r.variableName,r.type,r.value)}}class Lp{constructor(){this.transformType="filter"}apply(t,n){const{options:r}=n;return t.filter(r.variableName,r.operator,r.value)}}class Vp{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 Ep{constructor(){this.transformType="sort"}apply(t,n){const{options:r}=n;return t.orderBy(r.variableName,r.direction??"asc")}}class Ip extends Ne{constructor(){super("transform"),this.register("aggregate",new Tp),this.register("constant",new Mp),this.register("filter",new Lp),this.register("reshape",new Vp),this.register("sort",new Ep)}}const ms={color:"categorical",size:"numeric",alpha:"numeric",strokeWidth:"numeric",lineType:"categorical"},kp=["color","size","alpha","strokeWidth","lineType"];class Cp extends Re{dependencies(t){return kp.map(n=>t.scales[n])}compileLayer(t,n){let r=t.data;const s=Object.entries(pe);for(const[a,o]of s){const i=le(t.mapping[a]);if(i!==void 0){r=r.deriveVariable(o,ms[a],()=>i);continue}const c=v(t.mapping[a]),l=n.scales[a];if(!l||l.kind!=="visual")continue;const u=Dp(a,c,l);u&&(r=r.deriveVariable(o,ms[a],u))}return{...t,data:r}}}const Dp=(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},_p=["data","transform","constantMapping","layer","coordSetup","scale","positionMapper","visualMapper","coordTransform","summarise","guide","highlights","config","annotations"];class Ba{constructor(t,n,r,s,a,o,i,c,l,u,d,p,m,y,g){this.dataCompiler=t,this.specCompiler=n,this.transformCompiler=r,this.constantMappingCompiler=s,this.layerValidationCheck=a,this.layerCompiler=o,this.scaleCompiler=i,this.coordCompiler=c,this.positionMapperCompiler=l,this.visualMapperCompiler=u,this.guideCompiler=d,this.summariseCompiler=p,this.highlightsCompiler=m,this.configCompiler=y,this.annotationsCompiler=g,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(!ve)return t();const n=this.getCacheStats(),r=performance.now(),s=t(),a=performance.now()-r,o={};for(const{name:i,getStats:c}of this.stages){const l=c();o[i]={hits:l.hits-n[i].hits,misses:l.misses-n[i].misses}}return this.lastCompile={stages:o,durationMs:a},s}runPipeline({spec:t}){return It({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:a,coordSystem:o})=>({guides:this.guideCompiler.compile({scales:s,config:r.config,layers:a,coordSystem:o,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:a})=>({annotations:this.annotationsCompiler.compile({annotations:r.annotations,layers:s,coordSystem:a})})).result()}}const Fp=()=>{const e=new vp,t=new pu,n=new rc,r=new Ap(new Ip);return new Ba(new Hi,new Ra,r,new jo,new Cl(r,new Dl(n,e)),new kl(r,new ap(e),new sc,new qi(n),new _l(new Ol)),new Ul(t),new Jo(new pi),new Hl,new Cp,new hl,new wp,new Vl,new Xo,new $o)};function Rp(e,t){return e.geom===t}const Kn="–",$a="n/a",O={timeZone:"UTC"},N=e=>t=>{if(!G(t))return Kn;try{return e(t)}catch{return $a}},fe=e=>t=>D(t)?e(t):Kn,Xn=e=>t=>Ze(t)?t:Kn,Np=2,Pp=3,Op=2,Bp=0,$p=1,Gp=2,zp=To.humanizer({language:"en",spacer:"",delimiter:" ",languages:{en:{y:()=>"y",mo:()=>"mo",w:()=>"w",d:()=>"d",h:()=>"h",m:()=>"m",s:()=>"s",ms:()=>"ms"}}}),Ga=({valueFormat:e,locale:t,numberFormat:n,intlOptions:r})=>fe(s=>{const a=typeof n.decimals=="number"?n.decimals:Np,o=Zn(s,a),{base:i,suffix:c}=Qn(s,n.abbreviation),l={...o,...Cn(e)?{style:"currency",currencyDisplay:"narrowSymbol",currency:e.iso}:{},...r};return`${Intl.NumberFormat(t,l).format(i)}${c}`}),jn=({locale:e,numberFormat:t,intlOptions:n})=>fe(r=>{const{base:s,suffix:a}=Qn(r,t.abbreviation),i={...Zn(s,t.decimals),...n};return`${Intl.NumberFormat(e,i).format(s)}${a}`}),qn=e=>fe(t=>zp(t)),za=({locale:e,intlOptions:t})=>fe(n=>Intl.NumberFormat(e,{maximumFractionDigits:0,...t}).format(n)),Wa=({locale:e,numberFormat:t,intlOptions:n})=>fe(r=>{const s=Zn(r,t.decimals);return Intl.NumberFormat(e,{...s,...n,style:"percent"}).format(r)}),Qn=(e,t="none")=>{switch(t){case"none":return{base:e,suffix:""};case"auto":{const n=Wp(e);return Qn(e,n)}default:return{base:e/Xe[t],suffix:t}}},Zn=(e,t)=>{if(typeof t=="number")return{minimumFractionDigits:t,maximumFractionDigits:t};const n=Math.ceil(Math.log10(Math.abs(e))),r=n>=Pp?Bp:n===Op?$p:Gp;return{minimumFractionDigits:t==="auto"?0:r,maximumFractionDigits:r}},Wp=e=>{const t=Math.abs(e);return t>=Xe.b?"b":t>=Xe.m?"m":t>=Xe.k?"k":"none"},Yp=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{dateStyle:"medium",...O,...t}).format(n)),Hp=({locale:e,intlOptions:t})=>N(n=>{const r=Intl.DateTimeFormat(e,{dateStyle:"medium",timeStyle:"medium",...O,...t}).formatToParts(n);return Up(r.map(Kp))}),Ya=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"long",...O,...t}).format(n)),Ha=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{month:"long",...O,...t}).format(n)),Jn=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{month:"short",year:"numeric",...O,...t}).format(n)),er=e=>N(t=>`Q${Math.floor(t.getUTCMonth()/3)+1} ${t.getUTCFullYear()}`),Ua=({locale:e,intlOptions:t})=>N(n=>{const r=V.addDays(n,6);return Intl.DateTimeFormat(e,{day:"numeric",month:"long",...O,...t,year:void 0}).formatRange(n,r)}),Ka=({locale:e,intlOptions:t})=>N(n=>{const r=V.addDays(n,6);return Intl.DateTimeFormat(e,{dateStyle:"medium",...O,...t}).formatRange(n,r)}),tr=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{year:"numeric",...O,...t}).format(n)),Xa=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{timeStyle:"short",...O,...t}).format(n)),Up=e=>e.map(t=>t.value).join(""),Kp=e=>e.type!=="literal"||e.value!==", "?e:{type:"literal",value:" • "},Xp=1,jp=4,qp=1,fs=1e3,Qp=({valueFormat:e,locale:t,tickValues:n,intlOptions:r})=>fe(s=>{const o={...rr(s,n),notation:"compact",...Cn(e)?{style:"currency",currencyDisplay:"narrowSymbol",currency:e.iso}:{},...r};return nr(s,t,o)}),Zp=({locale:e,tickValues:t,intlOptions:n})=>fe(r=>{const a={...rr(r,t),notation:"compact",...n};return nr(r,e,a)}),Jp=({locale:e,tickValues:t,intlOptions:n})=>fe(r=>{const a={...rr(r,t),notation:"compact",...n,style:"percent"};return nr(r,e,a)}),nr=(e,t,n)=>Intl.NumberFormat(t,n).formatToParts(e).map(s=>s.type==="compact"?s.value.toLowerCase():s.value).join(""),ja=e=>Math.abs(e)>fs?ja(e/fs):Number.isInteger(e),em=e=>{if(e.length<2)return!1;const[t,n]=e;return typeof t!="number"||typeof n!="number"?!1:Math.abs(n-t)<Xp},rr=(e,t)=>ja(e)?{minimumFractionDigits:0,maximumFractionDigits:0}:em(t)?{minimumFractionDigits:0,maximumFractionDigits:jp}:{minimumFractionDigits:0,maximumFractionDigits:qp},tm=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"short",...O,...t}).format(n)),nm=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{month:"short",...O,...t}).format(n)),rm=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"short",...O,...t}).format(n)),sm=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{timeStyle:"short",...O,...t}).format(n)),sr=e=>{const{valueFormat:t}=e;switch(t.type){case"currency":return Qp(e);case"date":case"datetime":return tm(e);case"day_month":case"weekly_date_range":case"weekly_date_range_with_year":return rm(e);case"decimal":case"integer":return Zp(e);case"duration":return qn();case"month":return nm(e);case"month_year":return Jn(e);case"percentage":return Jp(e);case"quarter":return er();case"text":return Xn();case"time":return sm(e);case"year":return tr(e);case"lookup":return sr({...e,valueFormat:t.fallback});default:{const n=t;throw new Error(`Unhandled value format: ${n.type}`)}}},am=40,om=60,hs=8,im=50,cm=1/3,lm=1/4,dn="…",um=(e,t,n)=>{if(t<=0||e.length===0)return"";if(n(e)<=t)return e;if(n(dn)>t)return"";let r=0,s=e.length-1,a=0;for(;r<=s;){const o=r+s>>>1,i=e.slice(0,o)+dn;n(i)<=t?(a=o,r=o+1):s=o-1}return e.slice(0,a)+dn},dm=e=>e.formattedAxis.position==="top"||e.formattedAxis.position==="bottom"?pm(e):mm(e),pm=({formattedAxis:e,bandwidthPx:t,panelRect:n,measureLabel:r})=>{const{widths:s,maxWidth:a,maxHeight:o}=qa(e.ticks,r),i=t-hs;if(a<=i)return{...e,labelRotation:0,labelMaxWidthPx:null};if(t>=im){const l=Mn(i);return{...e,ticks:Tn(e.ticks,s,l,r),labelRotation:0,labelMaxWidthPx:l}}if(o+hs>t)return{...e,ticks:[],labelRotation:0,labelMaxWidthPx:null};const c=Mn(n.height*cm);return{...e,ticks:Tn(e.ticks,s,c,r),labelRotation:-90,labelMaxWidthPx:c}},mm=({formattedAxis:e,bandwidthPx:t,panelRect:n,measureLabel:r})=>{const{widths:s,maxWidth:a,maxHeight:o}=qa(e.ticks,r);if(o>t)return{...e,ticks:[],labelRotation:0,labelMaxWidthPx:null};const i=Mn(n.width*lm);return a<=i?{...e,labelRotation:0,labelMaxWidthPx:null}:{...e,ticks:Tn(e.ticks,s,i,r),labelRotation:0,labelMaxWidthPx:i}},qa=(e,t)=>{const n=[];let r=0,s=0;for(const a of e){const{width:o,height:i}=t(a.formattedLabel);n.push(o),o>r&&(r=o),i>s&&(s=i)}return{widths:n,maxWidth:r,maxHeight:s}},Tn=(e,t,n,r)=>{const s=a=>r(a).width;return e.map((a,o)=>(t[o]??0)<=n?a:{...a,formattedLabel:um(a.formattedLabel,n,s)})},Mn=e=>Math.max(0,Math.floor(e)),fm=(e,t,n,r)=>{if(e.length===0)return!0;const s=t==="top"||t==="bottom",a=s?om:am;let o=n-(e.length-1)*a;for(const i of e){const{width:c,height:l}=r(i);if(o-=s?c:l,o<0)return!1}return!0},hm=({axis:e,availableSpacePx:t,measureLabel:n,resolveFormatter:r})=>{const{tickCandidates:s,position:a}=e;if(s.length===0)return[];const o=new Map,i=d=>{const p=o.get(d);if(p)return p;const m=s[d],y=m?ym(m.ticks,r(m)):[];return o.set(d,y),y};let c=0,l=s.length-1,u=-1;for(;c<=l;){const d=c+l>>>1,m=i(d).map(y=>y.formattedLabel);fm(m,a,t,n)?(u=d,c=d+1):l=d-1}return u>=0?i(u):i(0)},ym=(e,t)=>e.map(n=>({...n,formattedLabel:t(n.value)})),pn=6,mn=6,fn=15,hn=5,yn=15,ar=(e,t)=>{switch(e){case"small":return{arrowStartGap:pn,arrowEndGap:mn,offsetFromHigherObservation:fn,arrowheadSize:hn,curveRadius:yn,strokeWidth:2,labelLineHeight:12*t,labelPaddingX:6,labelPaddingY:3,labelStrokeWidth:1,labelFontWeight:500};case"medium":return{arrowStartGap:pn*1.5,arrowEndGap:mn*1.5,offsetFromHigherObservation:fn*1.25,arrowheadSize:hn*1.5,curveRadius:yn*1.25,strokeWidth:3,labelLineHeight:16*t,labelPaddingX:8,labelPaddingY:4,labelStrokeWidth:1.5,labelFontWeight:500};case"large":return{arrowStartGap:pn*2,arrowEndGap:mn*2,offsetFromHigherObservation:fn*1.75,arrowheadSize:hn*2.5,curveRadius:yn*1.5,strokeWidth:5,labelLineHeight:20*t,labelPaddingX:10,labelPaddingY:5,labelStrokeWidth:2,labelFontWeight:600}}},gm=e=>{const t=P({...e,valueFormat:e.valueFormat.fallback}),n={};for(const[s,a]of Object.entries(e.valueFormat.cases))n[s]=P({...e,valueFormat:a});const r=e.valueFormat.byVariable;return(s,a)=>{if(a===void 0||a[r]===void 0)return t(s);const o=E(a[r]),i=n[o];return i!==void 0?i(s,a):t(s)}},P=e=>{switch(e.valueFormat.type){case"currency":return Ga(e);case"date":return Yp(e);case"datetime":return Hp(e);case"day_month":return Ya(e);case"decimal":return jn(e);case"duration":return qn();case"integer":return za(e);case"month":return Ha(e);case"month_year":return Jn(e);case"percentage":return Wa(e);case"quarter":return er();case"text":return Xn();case"weekly_date_range":return Ua(e);case"weekly_date_range_with_year":return Ka(e);case"year":return tr(e);case"time":return Xa(e);case"lookup":return gm({...e,valueFormat:e.valueFormat});default:{const t=e.valueFormat;throw new Error(`Unhandled value format: ${t.type}`)}}},gn={abbreviation:"none",decimals:"auto"},Qa=({locale:e,kind:t,startValue:n,endValue:r})=>{if(n===null||r===null)return $a;switch(t){case"absolute-difference":return jn({locale:e,numberFormat:gn,intlOptions:{signDisplay:"always"}})(r-n);case"relative-difference":{const s=r-n;if(s===0)return"0%";const a=s/n;return a===Number.POSITIVE_INFINITY?"∞":a===Number.NEGATIVE_INFINITY?"-∞":P({valueFormat:{type:"percentage"},locale:e,numberFormat:gn,intlOptions:{signDisplay:"always"}})(a)}case"proportion":{if(r-n===0)return"=";const s=r/n;return s===Number.POSITIVE_INFINITY?"∞":s===Number.NEGATIVE_INFINITY?"-∞":`${P({valueFormat:{type:"decimal"},locale:e,numberFormat:gn,intlOptions:{maximumFractionDigits:1}})(s)}x`}}},bm=e=>{const t=e.padding??0,n=ys(e.rows,t),r=ys(e.cols,t);return{rows:n.tracks,cols:r.tracks,placements:wm(e.placements,n.nameToIndex,r.nameToIndex),width:e.containerSize.width,height:e.containerSize.height}},vm=e=>{const t=gs(e.rows,e.height),n=gs(e.cols,e.width),r=bs(t),s=bs(n),a=new Map;for(const o of e.placements){const i=o.rowSpan??1,c=o.colSpan??1,l=s[o.col]??0,u=r[o.row]??0,d=vs(n,o.col,c),p=vs(t,o.row,i);a.set(o.name,{x:l,y:u,width:Math.max(0,d),height:Math.max(0,p)})}return a},ys=(e,t)=>{const n=[],r=new Map;t>0&&n.push({type:"fixed",pixels:t});for(let s=0;s<e.length;s++){const a=e[s];if(!a)continue;r.set(a.name,n.length),n.push(xm(a));const o=Sm(e,s);if(Za(a)&&o){const i=a.gaps?.after??0,c=o.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}},xm=e=>typeof e.size=="number"?{type:"fixed",pixels:e.size}:{type:"flex",weight:e.size.flex},Za=e=>typeof e.size=="number"?e.size>0:e.size.flex>0,Sm=(e,t)=>{for(let n=t+1;n<e.length;n++){const r=e[n];if(r&&Za(r))return r}},wm=(e,t,n)=>{const r=[];for(const s of e){const a=t.get(s.row),o=n.get(s.col);if(a===void 0||o===void 0)continue;const i=s.rowEnd!==void 0?t.get(s.rowEnd):a,c=s.colEnd!==void 0?n.get(s.colEnd):o;i===void 0||c===void 0||r.push({name:s.name,row:a,col:o,rowSpan:Math.max(1,i-a+1),colSpan:Math.max(1,c-o+1)})}return r},gs=(e,t)=>{let n=0,r=0;for(const a of e)a.type==="fixed"?n+=a.pixels:r+=a.weight;const s=Math.max(0,t-n);return e.map(a=>a.type==="fixed"?a.pixels:r===0?0:a.weight/r*s)},bs=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},vs=(e,t,n)=>{let r=0;const s=Math.min(t+n,e.length);for(let a=t;a<s;a++)r+=e[a]??0;return r},or=24,re={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}},pt={leftLegend:{after:10,before:0},leftAxis:{after:4,before:0},panel:{after:4,before:0},rightAxis:{after:10,before:0}},ir={top:0,right:0,bottom:0,left:0},Am=(e,t,n,r=ir,s=or)=>{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 bm({rows:[{name:"header",size:t.headerSize.height,gaps:re.header},{name:"topLegend",size:n.legends.top,gaps:re.topLegend},{name:"headline",size:n.headline,gaps:re.headline},{name:"topAxisLabel",size:o,gaps:re.topAxisLabel},{name:"topAxis",size:n.axes.top,gaps:re.topAxis},{name:"topAnnotation",size:r.top},{name:"panel",size:{flex:1},gaps:re.panel},{name:"bottomAxis",size:n.axes.bottom,gaps:re.bottomAxis},{name:"bottomAxisLabel",size:n.axesLabels.bottom,gaps:re.bottomAxisLabel},{name:"bottomLegend",size:n.legends.bottom,gaps:re.bottomLegend},{name:"footer",size:t.footerSize.height}],cols:[{name:"leftLegend",size:n.legends.left,gaps:pt.leftLegend},{name:"leftAxis",size:n.axes.left,gaps:pt.leftAxis},{name:"panel",size:{flex:1},gaps:pt.panel},{name:"rightAnnotation",size:r.right},{name:"rightAxis",size:n.axes.right,gaps:pt.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"},...Tm(n.axes),...Mm(n.axesLabels,n.axes),...Lm(n.legends)],containerSize:e,padding:s})},Tm=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},Mm=(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},Lm=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},Vm=({annotations:e,mainAxis:t,panelRect:n,textScale:r,locale:s,measureLabel:a,currentOverflow:o})=>{if(e.differenceArrows.length===0)return ir;const i=t==="y",c=n.height+o.top,l=n.width+o.right;let u=0,d=0;for(const p of e.differenceArrows){const{start:m,end:y,size:g,label:b}=p;if(!xs(m.x,m.y)||!xs(y.x,y.y))continue;const x=ar(g,r),S=x.offsetFromHigherObservation+x.arrowheadSize+x.arrowEndGap,w=Qa({locale:s,kind:b,startValue:m.measurementValue,endValue:y.measurementValue}),k=a(w,g);if(i){const W=Math.max(m.x,y.x),q=S+k.width/2+x.labelPaddingX;d=Math.max(d,Ss(q,W,l))}else{const W=Math.max(m.y,y.y),q=S+x.labelLineHeight/2+x.labelPaddingY;u=Math.max(u,Ss(q,W,c))}}return{top:Math.ceil(u),right:Math.ceil(d),bottom:0,left:0}},xs=(e,t)=>e>=0&&e<=1&&t>=0&&t<=1,Ss=(e,t,n)=>{if(t<=0)return 0;const r=(e-(1-t)*n)/t;return Math.max(0,r)},Em=["top","right","bottom","left"],bn=(e,t)=>{const n={};for(const r of Em){const s=e.get(`${r}${t}`);s&&(n[r]=s)}return n},Ln=["large","medium","small"],Im=({size:e,availableWidth:t,measureStripWidth:n})=>{if(e!=="auto")return e;for(const r of Ln)if(n(r)<=t)return r;return"small"},km=({size:e,availableWidth:t,measureStripWidth:n})=>{const r=e==="auto"?0:Ln.indexOf(e);for(const s of Ln.slice(r))if(n(s)<=t)return s;return null},Cm=({itemWidths:e,gap:t,availableWidth:n})=>{let r=0,s=0;for(const a of e){const o=s===0?a:r+t+a;if(o>n)break;r=o,s+=1}return s},Dm=({headline:e,containerSize:t,measurer:n})=>{if(Ja(e))return 0;const r=eo(e,t.width,n);return n.measureHeadline(e.formatted,r).height},_m=({headline:e,layout:t,containerSize:n,measurer:r,itemGap:s})=>{if(Ja(e)){const i=Fm(t.panel,e.innerRadius),c=km({size:e.size,availableWidth:i.width,measureStripWidth:to(e,r)});return c===null?null:{rect:i,resolvedSize:c,visibleItemCount:1}}const a=eo(e,n.width,r);if(e.formatted.kind!=="perGroup")return{rect:t.headline,resolvedSize:a,visibleItemCount:1};const o=Cm({itemWidths:r.measureHeadlineItemWidths(e.formatted,a),gap:s,availableWidth:t.headline.width});return o===0?null:{rect:t.headline,resolvedSize:a,visibleItemCount:o}},Ja=e=>e.formatted.kind==="grandTotal"&&e.position==="center"&&e.innerRadius>0,Fm=(e,t)=>{const n=Math.min(e.width,e.height)/2,r=t*n*Math.SQRT2,s=e.x+e.width/2,a=e.y+e.height/2;return{x:s-r/2,y:a-r/2,width:r,height:r}},eo=(e,t,n)=>Im({size:e.size,availableWidth:t,measureStripWidth:to(e,n)}),to=(e,t)=>n=>t.measureHeadline(e.formatted,n).width,We={x:0,y:0,width:0,height:0},Rm="0000";class Nm{constructor(t){this.measurer=t}compile(t){return It({axes:t.axes,numberFormat:t.numberFormat,formattedLegends:t.formattedLegends,containerSize:t.containerSize,externalMeasurements:t.externalMeasurements,annotationOverflow:ir,headline:t.headline,locale:t.formattingLocale??t.parsingLocale,padding:t.padding??or}).pipe(({axes:n,numberFormat:r,locale:s})=>({axisBundles:n.map(a=>({axis:a,resolveFormatter:Pm(a,s,r),formatted:this.seedAxis(a)}))})).pipe(({axisBundles:n,formattedLegends:r,containerSize:s,externalMeasurements:a,annotationOverflow:o,headline:i,padding:c})=>({layout:this.resolveLayout({axes:n.map(l=>l.formatted),formattedLegends:r,containerSize:s,externalMeasurements:a,annotationOverflow:o,headline:i,padding:c})})).pipe(({axisBundles:n,layout:r})=>({axisBundles:n.map(s=>ws(s.axis.position)?{...s,formatted:this.finalizeAxis(s.axis,s.resolveFormatter,r.panel)}:s)})).pipe(({axisBundles:n,formattedLegends:r,containerSize:s,externalMeasurements:a,annotationOverflow:o,headline:i,padding:c})=>({layout:this.resolveLayout({axes:n.map(l=>l.formatted),formattedLegends:r,containerSize:s,externalMeasurements:a,annotationOverflow:o,headline:i,padding:c})})).pipe(({axisBundles:n,layout:r})=>({formattedAxes:n.map(s=>ws(s.axis.position)?s.formatted:this.finalizeAxis(s.axis,s.resolveFormatter,r.panel))})).pipe(({formattedAxes:n,formattedLegends:r,containerSize:s,externalMeasurements:a,annotationOverflow:o,headline:i,padding:c})=>({layout:this.resolveLayout({axes:n,formattedLegends:r,containerSize:s,externalMeasurements:a,annotationOverflow:o,headline:i,padding:c})})).pipe(({formattedAxes:n,formattedLegends:r,containerSize:s,externalMeasurements:a,layout:o,annotationOverflow:i,headline:c,locale:l,padding:u})=>{const d=this.measureAnnotationOverflow(t,o.panel,l,i);return d===i?{formattedAxes:n,layout:o}:{formattedAxes:n,layout:this.resolveLayout({axes:n,formattedLegends:r,containerSize:s,externalMeasurements:a,annotationOverflow:d,headline:c,padding:u})}}).result()}measureAnnotationOverflow(t,n,r,s){if(!t.annotations||t.annotations.differenceArrows.length===0||t.coordSystem?.type!=="cartesian")return s;const a=Vm({annotations:t.annotations,mainAxis:t.coordSystem.mainAxis,panelRect:n,textScale:t.textScale??1,locale:r,measureLabel:this.measurer.measureDifferenceArrowLabel,currentOverflow:s});return a.top===s.top&&a.right===s.right?s:a}seedAxis(t){const{tickCandidates:n,...r}=t;return{...r,ticks:[{value:0,position:0,formattedLabel:Rm}],labelRotation:0,labelMaxWidthPx:null}}finalizeAxis(t,n,r){const a=t.position==="top"||t.position==="bottom"?r.width:r.height,o=hm({axis:t,availableSpacePx:a,measureLabel:this.measurer.measureTickLabel,resolveFormatter:n}),{tickCandidates:i,...c}=t,l={...c,ticks:o,labelRotation:0,labelMaxWidthPx:null};if(t.scaleType==="discrete"&&t.bandwidth!==void 0){const u=t.bandwidth*a;return dm({formattedAxis:l,bandwidthPx:u,panelRect:r,measureLabel:this.measurer.measureTickLabel})}return l}resolveLayout({axes:t,formattedLegends:n,containerSize:r,externalMeasurements:s,annotationOverflow:a,headline:o,padding:i}){const c=this.measureGuides(t,n,o,r),l=Am(r,s,c,a,i),u=vm(l);return{header:u.get("header")??We,headline:u.get("headline")??We,footer:u.get("footer")??We,plot:u.get("plot")??We,panel:u.get("panel")??We,axes:bn(u,"Axis"),axisLabels:bn(u,"AxisLabel"),legends:bn(u,"Legend")}}measureGuides(t,n,r,s){const a={top:0,right:0,bottom:0,left:0},o={top:0,right:0,bottom:0,left:0};for(const c of t)c.isVisible&&(a[c.position]=this.measurer.measureAxis(c),c.label!==null&&(o[c.position]=this.measurer.measureAxisLabel(c)));const i={top:0,right:0,bottom:0,left:0};for(const c of n)i[c.position]=this.measurer.measureLegend(c);return{axes:a,axesLabels:o,legends:i,headline:this.measureHeadlineBand(r,s)}}measureHeadlineBand(t,n){return t===void 0?0:Dm({headline:t,containerSize:n,measurer:this.measurer})}}const ws=e=>e==="left"||e==="right",Pm=(e,t,n)=>{const r=e.tickCandidates.flatMap(a=>a.ticks.map(o=>o.value)),s=new WeakMap;return a=>{const o=s.get(a);if(o)return o;const i=sr({valueFormat:a.valueFormat??e.valueFormat,locale:t,numberFormat:n,tickValues:r});return s.set(a,i),i}};function Om(e,t,n){const r=new Map;if(!t||t.kind!=="visual"||t.domain.length<=1)return r;for(const s of e){if(s.geom!=="rule"||s.stat.type!=="mean")continue;const a=s.transforms.find(p=>p.transformType==="filter"&&p.options.operator==="eq"),o=v(s.mapping.y);let i,c,l;if(a?.transformType==="filter"&&typeof a.options.value=="string")i="color",c=a.options.variableName,l=a.options.value;else if(o!==null)i="y",c=o,l=o;else continue;const u=Bm(e,i,c);if(u===null)continue;const d=t.map(l);Ze(d)&&r.set(s.id,{shape:Tt(u.geom,n),color:d})}return r}function Bm(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 Fe(e,t){return e==="x"?t.x:t.y}function Gt(e,t){return e==="x"?t.y:t.x}function $m(e,t){return{main:Fe(e,t),cross:Gt(e,t)}}function Gm(e){return e.type==="cartesian"}function zm(e){return e}function we(e){return 1-e}const be=e=>`${Number.parseFloat((e*100).toFixed(4))}%`,cr=12,Wm=4,Ym=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=$(n),s=H(n)??C(n);if(r===null||s===null||r<0||r>1||s<0||s>1)continue;const a=e.formatLabel(n);if(a==="")continue;const{width:o,height:i}=e.measureDataLabel("dataLabel",a),c=r*e.panelRect.width,l=(1-s)*e.panelRect.height-cr-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:c,y:l,text:a,width:o,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},Hm={place:Ym,getPercentageValueStrategy:e=>e.position==="fill"?"fill":X(e.position)?"stack":"none"},vn=4,mt=6,Um=e=>{const t=[],n=X(e.layer.position),r=e.coordSystem.mainAxis==="y";if(e.layer.dataLabels.showDataLabels){const{entries:s,shouldRotate:a}=Xm({layer:e.layer,mainAxis:e.coordSystem.mainAxis,panelRect:e.panelRect,measureDataLabel:e.measureDataLabel,formatLabel:e.formatLabel,isFlipped:r,getObservationKey:e.getObservationKey});for(const o of s){const i=Zm({mainAxis:e.coordSystem.mainAxis,isStacked:n,isNegativeBar:o.isNegative,shouldRotate:a,bounds:o.bounds,labelWidth:o.labelWidth,labelHeight:o.labelHeight,panelWidth:e.panelRect.width,panelHeight:e.panelRect.height});i!==null&&t.push({layerId:e.layer.id,key:o.key,x:i.x,y:i.y,text:o.text,width:o.labelWidth,height:o.labelHeight,isRotated:i.isRotated,target:"observation",position:i.position})}}if(e.layer.dataLabels.showStackTotals){const s=nf({layer:e.layer,mainAxis:e.coordSystem.mainAxis,panelRect:e.panelRect,measureDataLabel:e.measureDataLabel,formatAbsolute:e.formatAbsolute});for(const a of s)t.push(a)}return t},Km={place:Um,getPercentageValueStrategy:e=>e.position==="fill"?"fill":X(e.position)?"stack":"absoluteGrandTotal"},Xm=({layer:e,mainAxis:t,panelRect:n,measureDataLabel:r,formatLabel:s,isFlipped:a,getObservationKey:o})=>{const i=[];let c=!1;const l=v(e.mapping.y);for(const u of e.data){const d=jm(t,u);if(d===null)continue;const p=s(u);if(p==="")continue;const{width:m,height:y}=r("dataLabel",p),g=no(d,n);m>g.width&&(c=!0);const b=l===null?null:u[l],x=D(b)&&b<0;i.push({key:o(u),isNegative:x,text:p,labelWidth:m,labelHeight:y,bounds:g})}return{entries:i,shouldRotate:!a&&c}},no=(e,t)=>({x:e.x*t.width,y:e.y*t.height,width:e.width*t.width,height:e.height*t.height}),ro=(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 a=t,o=n-t;return o<0&&(a+=o,o=-o),{x:a,y:1-s,width:o,height:s-r}},jm=(e,t)=>{const n=me(t),r=ae(t),s=te(t),a=H(t)??C(t);return n===null||r===null||s===null||a===null?null:ro(e,n,r,s,a)},qm=(e,t)=>{const{xMin:n,xMax:r,yMin:s,yMax:a}=t.anchor;return ro(e,n,r,s,a)},Qm=(e,t)=>e==="x"?t?"bottom":"top":t?"left":"right",so=(e,t,n)=>n?{width:t,height:e}:{width:e,height:t},Zm=e=>e.isStacked?Jm({bounds:e.bounds,labelWidth:e.labelWidth,labelHeight:e.labelHeight,isRotated:e.shouldRotate}):tf({edge:Qm(e.mainAxis,e.isNegativeBar),bounds:e.bounds,labelWidth:e.labelWidth,labelHeight:e.labelHeight,isRotated:e.shouldRotate,panelWidth:e.panelWidth,panelHeight:e.panelHeight}),Jm=({bounds:e,labelWidth:t,labelHeight:n,isRotated:r})=>{const s=so(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"}},ef=(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}}},tf=({edge:e,bounds:t,labelWidth:n,labelHeight:r,isRotated:s,panelWidth:a,panelHeight:o})=>{const i=e==="top"||e==="bottom",c=t.x+t.width/2,l=t.y+t.height/2,u=so(n,r,s),d=i?u.height:u.width,p=i?u.width:u.height,m=i?t.height:t.width,y=i?t.width:t.height,g=d/2,{edgeCoord:b,outwardSign:x,panelExtent:S}=ef(e,t,a,o);if(d+vn<m){if(p>y)return null;if(s)return{x:c,y:l,isRotated:!0,position:"inside"};const k=b-x*(g+vn);return{...i?{x:c,y:k}:{x:k,y:l},isRotated:!1,position:"inside"}}const w=b+x*(g+vn);return w-g<0||w+g>S?null:{...i?{x:c,y:w}:{x:w,y:l},isRotated:s,position:"outside"}},nf=({layer:e,mainAxis:t,panelRect:n,measureDataLabel:r,formatAbsolute:s})=>{const a=[],o=e.summary.stackTotals;if(o===void 0||o.length===0)return a;const i=t==="y";for(const c of o){const l=no(qm(t,c),n),u=s(c.total),{width:d,height:p}=r("stackTotal",u),m=c.anchor.direction==="positive";let y,g;i?(y=m?l.x+l.width+mt+d/2:l.x-mt-d/2,g=l.y+l.height/2):(y=l.x+l.width/2,g=m?l.y-mt-p/2:l.y+l.height+mt+p/2),a.push({layerId:e.id,key:`${e.id}:stack:${c.xKey}`,x:y,y:g,text:u,width:d,height:p,isRotated:!1,target:"aggregate",position:"outside"})}return a},rf=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=$(n),s=C(n);if(r===null||s===null||r<0||r>1||s<0||s>1)continue;const a=e.formatLabel(n);if(a==="")continue;const{width:o,height:i}=e.measureDataLabel("dataLabel",a),c=r*e.panelRect.width,l=(1-s)*e.panelRect.height-cr-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:c,y:l,text:a,width:o,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},sf={place:rf,getPercentageValueStrategy:()=>"none"},af=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=$(n),s=C(n);if(r===null||s===null||r<0||r>1||s<0||s>1)continue;const a=e.formatLabel(n);if(a==="")continue;const{width:o,height:i}=e.measureDataLabel("dataLabel",a),c=(Rs(n)??e.layer.params.size)/2,l=r*e.panelRect.width,u=(1-s)*e.panelRect.height-c-cr-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:l,y:u,text:a,width:o,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},of={place:af,getPercentageValueStrategy:()=>"none"};function ao(e){return{startAngle:e[f.xMin],endAngle:e[f.xMax]}}function oo(e){return{innerRadius:e[f.yMin],outerRadius:e[f.yMax]??e[f.y]}}const cf=" · ",lf=e=>typeof e=="string"?e:e instanceof Date?e.toISOString():String(e),uf=(e,t)=>{const n=v(t.x);return n!==null&&n!==Sn.x?Ft(e,t):s=>Le(s)},df=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;const n=e.layer.dataLabels.showCategoryLabels?uf(e.layer.data,e.layer.mapping):null,r=e.panelRect.width/2,s=e.panelRect.height/2,a=Math.min(e.panelRect.width,e.panelRect.height)/2;for(const o of e.layer.data){const{startAngle:i,endAngle:c}=ao(o),{outerRadius:l}=oo(o);if(i===null||c===null||l===null)continue;const u=e.formatLabel(o);if(u==="")continue;const d=n===null?null:n(o),p=d===null?u:`${lf(d)}${cf}${u}`,{width:m,height:y}=e.measureDataLabel("dataLabel",p),g=(i+c)/2,b=Math.abs(Math.sin(g))*(m/2)+Math.abs(Math.cos(g))*(y/2),x=l*a+Wm+b,S=r+Math.sin(g)*x,w=s-Math.cos(g)*x,k=m/2,W=y/2;S-k<0||S+k>e.panelRect.width||w-W<0||w+W>e.panelRect.height||t.push({layerId:e.layer.id,key:e.getObservationKey(o),x:S,y:w,text:p,width:m,height:y,isRotated:!1,target:"observation",position:"outside"})}return t},pf={place:df,getPercentageValueStrategy:()=>"absoluteGrandTotal"},mf={type:"decimal"};function lr({layer:e,numberFormat:t,locale:n}){const r=v(e.mapping.y),s=r!==null&&e.data.hasVariable(r)?e.data.getValueFormat(r):mf;return P({valueFormat:s,locale:n,numberFormat:t})}const ff=({layer:e,coordSystem:t,axes:n,numberFormat:r,panelRect:s,measureDataLabel:a,formattingLocale:o,percentageValueStrategy:i})=>{const c=lr({layer:e,numberFormat:r,locale:o});return{layer:e,coordSystem:t,panelRect:s,measureDataLabel:a,formatLabel:vf({layer:e,numberFormat:r,axes:n,locale:o,absoluteFormatter:c,percentageValueStrategy:i}),formatAbsolute:c,getObservationKey:hf(e)}},hf=e=>{const t=v(e.mapping.x);return n=>{const r=t===null?null:n[t]??null,s=Le(n);return`${e.id}:${E([r,s])}`}},yf=(e,t)=>{switch(t){case"stack":return gf(e);case"fill":return bf(e);case"absoluteGrandTotal":return()=>e.summary.absoluteGrandTotal??null;case"none":return()=>null}},gf=e=>{const t=v(e.mapping.x);let n=null,r=!1;return s=>{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 o=s[t];if(o==null)return null;const i=n?.get(Gn(s,t));return i===void 0?null:i.total}},bf=e=>{const t=Nt(e);return n=>{const r=te(n),s=H(n);if(!D(r)||!D(s))return null;const a=Math.abs(s-r);if(a===0)return null;const o=t(n);return D(o)?o/a:null}},vf=({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:s,percentageValueStrategy:a})=>{const o=j(e.data,e.dataLabels.labelSource),i=yf(e,a),c=xf({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:s}),l=P({valueFormat:{type:"percentage"},locale:r,numberFormat:t}),u=e.dataLabels.format==="percentage"&&io(e);return d=>{const p=o(d);if(p===null)return"";if(!u||!D(p))return c(p,d);const m=i(d);return m===null||m===0?c(p,d):l(p/m)}},xf=({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:s})=>{const a=e.dataLabels.labelSource,o=v(a);if(o!==null){if(io(e))return s;const i=Sf(e,n,t,r,o);if(i!==null)return i}return P({valueFormat:wf(e.data,a),locale:r,numberFormat:t})},io=e=>{const t=v(e.dataLabels.labelSource);return t===null?!1:t===v(Rt(e.position,e.mapping))},Sf=(e,t,n,r,s)=>{const a=v(e.mapping.x);if(a===null||a!==s)return null;const o=t.find(i=>i.scaleAestheticKey==="x");return o===void 0?null:P({valueFormat:o.valueFormat,locale:r,numberFormat:n})},wf=(e,t)=>{const n=le(t);if(n!==void 0)return typeof n=="number"?{type:"decimal"}:Co(n)?{type:"date"}:{type:"text"};const r=v(t);return r===null||!e.hasVariable(r)?{type:"text"}:e.getValueFormat(r)},Af={bar:{cartesian:Km,polar:pf},line:{cartesian:sf},point:{cartesian:of},area:{cartesian:Hm}},Tf=({layers:e,coordSystem:t,axes:n,numberFormat:r,parsingLocale:s,panelRect:a,measureDataLabel:o,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=Af[d.geom]?.[u];if(p===void 0)continue;const m=ff({layer:d,coordSystem:t,axes:n,numberFormat:r,panelRect:a,measureDataLabel:o,formattingLocale:l,percentageValueStrategy:p.getPercentageValueStrategy(d)}),y=p.place(m);for(const g of y)c.push(g)}return{labels:c}},Mf=(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},Lf=(e,t,n,{arrowStartGap:r,arrowEndGap:s,curveRadius:a})=>{const o={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`
|
|
4
4
|
M ${o.x} ${o.y}
|
|
5
5
|
L ${i.x} ${i.y+a}
|
|
6
6
|
Q ${i.x} ${i.y} ${i.x+u*a} ${i.y}
|
|
@@ -22,4 +22,4 @@ ${n}`),this.issues=t,this.name="SpecValidationError"}}class Cl{constructor(t,n){
|
|
|
22
22
|
M ${t.x-r} ${t.y-n-r}
|
|
23
23
|
L ${t.x} ${t.y-n}
|
|
24
24
|
L ${t.x+r} ${t.y-n-r}
|
|
25
|
-
`,If=(e,t,n,r,s,a=.5)=>{if(e){const i=Math.min(t.y,n.y);return{x:r,y:i+a*s}}return{x:Math.min(t.x,n.x)+a*s,y:r}},kf=(e,t,n)=>Math.abs(e?t.y-n.y:t.x-n.x),Cf=({arrow:e,mainAxis:t,panelWidth:n,panelHeight:r,textScale:s,locale:a})=>{const o=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=ar(e.size,s),u=Mf(o,i,c,l),d=(o?Vf:Lf)(i,c,u,l),p=Ef(o,c,l),m=kf(o,i,c),y=If(o,i,c,u,m,e.labelCrossPosition),g=qa({locale:a,kind:e.label,startValue:e.start.measurementValue,endValue:e.end.measurementValue});return{id:e.id,linePath:d,arrowheadPath:p,labelPosition:y,labelText:g,color:e.color,strokeWidth:l.strokeWidth,labelLineHeight:l.labelLineHeight,labelPaddingX:l.labelPaddingX,labelPaddingY:l.labelPaddingY,labelStrokeWidth:l.labelStrokeWidth,labelFontWeight:l.labelFontWeight}},Df=100,_f=({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 a=!1,o=!0,i=0;for(;o;){o=!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){o=!0,a=!0;const g=(p-m)/2+1;u.y-=g,d.y+=g,u.y<0&&(u.y=0),d.y>t&&(d.y=t)}}if(i>Df)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}},Ff=({headline:e,show:t,numberFormat:n,parsingLocale:r,formattingLocale:s,t:a})=>{if(e===null)return null;const o=s??r;return e.kind==="grandTotal"?Rf(e,o,n):Nf(e,t,o,n,a)},Rf=(e,t,n)=>({kind:"grandTotal",value:P({valueFormat:e.valueFormat,locale:t,numberFormat:n})(e.value)}),Nf=(e,t,n,r,s)=>{const a=P({valueFormat:{type:"percentage"},locale:n,numberFormat:r}),o=e.items.length>1;return{kind:"perGroup",items:e.items.map(c=>{const l=P({valueFormat:c.valueFormat,locale:n,numberFormat:r}),u=P({valueFormat:c.groupLabelFormat,locale:n,numberFormat:r}),d=sr({valueFormat:c.mainValueFormat,locale:n,numberFormat:r,tickValues:[]}),p=c.label??u(c.value);return{swatch:c.swatch,label:$f(t,o,p,s),value:c.aggregate===null?null:l(c.aggregate),observationLabel:Bf(c.observationLabel,d),comparison:Pf(c.comparison,d,a,s)}})}},Pf=(e,t,n,r)=>e===null?null:{direction:Of(e.variation),percentage:n(Math.abs(e.variation)),reference:r("graph.headlineMetrics.comparisonReference",{value:t(e.against)})},Of=e=>e>0?"up":e<0?"down":"flat",Bf=(e,t)=>e===null?null:e.kind==="point"?t(e.value):`${t(e.from)} – ${t(e.to)}`,$f=(e,t,n,r)=>{switch(e){case"total":return r("graph.headlineMetrics.total",{value:n});case"average":return t?r("graph.headlineMetrics.averageShort",{value:n}):r("graph.headlineMetrics.averageLong",{value:n});case"current":case"conversion":case"none":return n}},Gf=({legends:e,numberFormat:t,parsingLocale:n,formattingLocale:r})=>{const s=r??n;return e.map(a=>zf(a,s,t))},zf=(e,t,n)=>({...e,items:e.items.map(r=>{const s=P({valueFormat:r.valueFormat,locale:t,numberFormat:n});return{...r,formattedLabel:r.label??s(r.value)}})});function zt(e,t){return e.axes.find(n=>n.scaleAestheticKey===t)??null}function Wf(e,t){return e.legends.find(n=>n.aesthetics.includes(t))??null}const Yf=({guides:e,numberFormat:t,layer:n,locale:r})=>{const s=n.data.getFirst();if(!s)return null;const a=n.mapping.y!==void 0,i=(a?fa:Ft)(n.data,n.mapping)(s);if(i===null)return null;const c=a?Oe(n.yScaleType):"x",l=zt(e,c)?.valueFormat??{type:"decimal"};return P({valueFormat:l,locale:r,numberFormat:t})(i)},co=12,lo=4,uo=4,po=12,mo=4,Hf=e=>{const{value:t,observationLabel:n,comparison:r,swatch:s,label:a}=e;return[{role:"valueRow",gap:uo,segments:xn([ft("value","value",t??"–"),ft("observation","label",n)])},{role:"trendRow",gap:mo,ariaLabel:r===null?void 0:jf(r),segments:xn([Kf(r),Xf(r),ft("trendReference","label",r?.reference??null)])},{role:"groupRow",gap:lo,segments:xn([Uf(s),ft("label","label",a)])}].filter(i=>i.segments.length>0)},ft=(e,t,n)=>n===null?null:{kind:"text",textRole:e,fontRole:t,text:n},Uf=e=>e===null?null:{kind:"swatch",swatch:e,size:co},Kf=e=>e===null?null:{kind:"trendArrow",direction:e.direction,size:po},Xf=e=>e===null?null:{kind:"text",textRole:"trendPercentage",fontRole:"label",text:e.percentage,trendDirection:e.direction},jf=e=>{switch(e.direction){case"up":return`Increased ${e.percentage} ${e.reference}`;case"down":return`Decreased ${e.percentage} ${e.reference}`;case"flat":return`No change ${e.reference}`}},xn=e=>e.filter(t=>t!==null),qf=800,ws=400,Qf={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}}},Zf=e=>Math.max(1,(e-ws)/(qf-ws)+1),Jf=(e,t)=>{const n=Zf(t),r=Qf[e];return{strokeWidth:Math.min(r.strokeWidth.targetValue,r.strokeWidth.minValue*n),arrowheadLength:Math.min(r.arrowheadLength.targetValue,r.arrowheadLength.minValue*n)}},ht=Math.PI/4,Vn=1.5,eh=({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:a,endY:o}=t,i=e==="start"?r:a,c=e==="start"?s:o,l=e==="start"?Math.atan2(s-o,r-a):Math.atan2(o-s,a-r),u=i-n*Math.cos(l-ht),d=c-n*Math.sin(l-ht),p=i-n*Math.cos(l+ht),m=c-n*Math.sin(l+ht);return`M ${i} ${c} L ${u} ${d} M ${i} ${c} L ${p} ${m}`},th=(e,t)=>e==="solid"?null:`${t*Vn} ${t*Vn*2}`,nh=(e,t)=>t?e*Vn:0,rh=64,sh=({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:a}=Jf(e.thickness,t),o=Math.hypot(r.endX-r.startX,r.endY-r.startY),i=ah(a,o),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:eh(r),startArrowheadPath:c?As("start",r,i):"",endArrowheadPath:l?As("end",r,i):"",color:e.color,strokeWidth:s,dashArray:th(e.lineStyle,s),hasStickerStyle:e.hasStickerStyle,startX:r.startX,startY:r.startY,endX:r.endX,endY:r.endY,dashOffset:nh(s,c),arrowheadExtent:d}},ah=(e,t)=>Math.min(e,t*e/rh),fo=2,lr=e=>e==="catmull-rom"?_e.curveCatmullRom:_e.curveLinear,oh=e=>{switch(e){case"dashed":return"8 4";case"dotted":return"2 2";case"solid":return}},ih=(e,t)=>t.lineWidth!=="auto"?t.lineWidth:Rs(e)??fo,ch=(e,t)=>{const n=lr(t.interpolate),r=_e.area().curve(n),s=_e.line().curve(n);if(e.mainAxis==="y"){const a=c=>we(C(c)??0),o=c=>me(c)??0,i=c=>ae(c)??$(c)??0;r.y(a).x0(o).x1(i),s.y(a).x(i)}else{const a=c=>$(c)??0,o=c=>we(te(c)??0),i=c=>we(H(c)??C(c)??0);r.x(a).y0(o).y1(i),s.x(a).y(i)}if(t.missingValues==="gap"){const a=o=>$(o)!==null&&C(o)!==null;r.defined(a),s.defined(a)}return{lineGenerator:s,areaGenerator:r}},lh=(e,t)=>t!=="connect"?e:e.filter(n=>$(n)!==null&&C(n)!==null),uh=(e,t)=>{const n=me(t),r=ae(t),s=te(t),a=H(t)??C(t);if(n===null||r===null||s===null||a===null)return null;if(e==="x"){let c=1-a,l=a-s;return l<0&&(c+=l,l=-l),{x:n,y:c,width:r-n,height:l}}let o=n,i=r-n;return i<0&&(o+=i,i=-i),{x:o,y:1-a,width:i,height:a-s}},dh=e=>{const t=_e.line().x(n=>$(n)??0).y(n=>we(C(n)??0)).curve(lr(e.interpolate));return e.missingValues==="gap"&&t.defined(n=>$(n)!==null&&C(n)!==null),t},ph=(e,t)=>t!=="connect"?e:e.filter(n=>$(n)!==null&&C(n)!==null),mh=_e.arc(),fh=e=>mh(e),hh=(e,t,n)=>{const r=Ft(e,t);return s=>{const a=Le(s)??"default",o=r(s);return`${n}-${a}${o!==null&&o!==""?`-${o}`:""}`}},yh=()=>(e,t)=>Ct(e)??`default-${t}`;function ho(e,t){return ur(e.buckets,t,n=>n.main)}function gh(e,t){return ur(e.bands,t,n=>n.bandCenter)}function bh(e,t){return ur(e.columns,t,n=>n.mainMid)}function ur(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 a=e[r-1],o=e[r];return a?o&&Math.abs(n(o)-t)<Math.abs(n(a)-t)?o:a:o??null}function dr(e,t,n){return Math.hypot(e*n,t)}function vh(e,t,n,r){if(e.points.length===0)return null;const s=e.delaunay;if(!s)return null;const a=s.find(t.x*n,t.y,r??void 0),o=e.points[a];return o?{hit:{layerId:e.layerId,pointIndex:o.pointIndex,x:o.x,y:o.y,observation:o.observation},index:e,distance:dr(o.x-t.x,o.y-t.y,n)}:null}function xh(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 Sh(e,t){return{group:wh(e),related:Lh(e,t)}}function wh(e){switch(e.kind){case"buckets":{const t=e.match.index;return X(t.position)?Ah(t,e.match):[]}case"rects":{const t=e.match.index;return X(t.position)?Th(t,e.match):Mh(t,e.match)}case"points":case"arcs":return[]}}function Ah(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 Th(e,t){const n=[];for(const r of t.column.rects)r.pointIndex!==t.hit.pointIndex&&n.push(pr(e,r));return n}function Mh(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 a of s.rects)a.pointIndex!==t.hit.pointIndex&&r.push(pr(e,a));return r}function Lh(e,t){const n=new Map;if(e.kind==="arcs")return n;for(const r of t){if(r.layerId!==e.match.index.layerId){Eh(n,r,e.match.hit);continue}e.kind==="buckets"&&(X(r.position)||r.kind==="buckets"&&Vh(n,r,e.match))}return n}function Vh(e,t,n){for(const r of n.bucket.entries){if(r.pointIndex===n.hit.pointIndex)continue;wt(e,t.layerId).push({layerId:t.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation})}}function Eh(e,t,n){switch(t.kind){case"buckets":{const r=ho(t,Fe(t.mainAxis,n));if(!r)return;const s=wt(e,t.layerId);for(const a of r.entries)s.push({layerId:t.layerId,pointIndex:a.pointIndex,x:a.x,y:a.y,observation:a.observation});return}case"rects":{const r=gh(t,Fe(t.mainAxis,n));if(!r)return;const s=wt(e,t.layerId);for(const a of r.columns)for(const o of a.rects)s.push(pr(t,o));return}case"points":{const r=xh(t,n);if(!r)return;wt(e,t.layerId).push({layerId:t.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation});return}case"arcs":return;case"noop":return}}function wt(e,t){let n=e.get(t);return n||(n=[],e.set(t,n)),n}function pr(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 Ih(e){const t=kh(e);return{kind:"arcs",layerId:e.id,geom:e.geom,position:e.position,arcs:t}}function kh(e){const t=e.data;if(t.size()===0)return[];const n=[f.xMin,f.xMax,f.yMin,f.yMax];for(const l of n)if(!t.hasVariable(l))return[];const r=t.getValues(f.xMin,{type:"numeric"}),s=t.getValues(f.xMax,{type:"numeric"}),a=t.getValues(f.yMin,{type:"numeric"}),o=t.getValues(f.yMax,{type:"numeric"}),i=[];let c=0;for(const l of t){const u=r[c],d=s[c],p=a[c],m=o[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 Ch=1e-9;function Dh(e,t){const n=_h(e,t);n.sort((s,a)=>s.main-a.main);const r=[];for(const s of n){const a=r[r.length-1];a&&Math.abs(a.main-s.main)<=Ch?a.entries.push(s.entry):r.push({main:s.main,entries:[s.entry]})}return{kind:"buckets",layerId:e.id,geom:e.geom,position:e.position,mainAxis:t,buckets:r}}function _h(e,t){const n=e.data;if(n.size()===0)return[];const s=n.hasVariable(f.x),a=n.hasVariable(f.y);if(!s||!a)return[];const o=n.getValues(f.x,{type:"numeric"}),i=n.getValues(f.y,{type:"numeric"}),c=t==="y",l=c?f.xMin:f.yMin,u=c?f.xMax:f.yMax,d=X(e.position),p=d?n.getValues(l,{type:"numeric"}):null,m=d?n.getValues(u,{type:"numeric"}):null,y=n.hasVariable(z.group)?n.getValues(z.group,{type:"categorical"}):null,g=[];let b=0;for(const x of n){const S=o[b],w=i[b];if(!h(S)||!h(w)){b+=1;continue}const k=y?.[b]??null,W=c?w:S;if(d){const q=p?.[b],Be=m?.[b];if(!h(q)||!h(Be)){b+=1;continue}const T=c?Be:S,ne=c?w:Be;g.push({main:W,entry:{isStacked:d,pointIndex:b,x:T,y:ne,stackMin:q,stackMax:Be,groupKey:k,observation:x}})}else g.push({main:W,entry:{isStacked:d,pointIndex:b,x:S,y:w,groupKey:k,observation:x}});b+=1}return g}function Fh(e){return{kind:"noop",layerId:e.id,geom:e.geom,position:e.position}}function Rh(e,t){const n={kind:"points",layerId:e.id,geom:e.geom,position:e.position,points:Nh(e),delaunay:null,delaunayAspectRatio:null};return yo(n,t),n}function yo(e,t){e.delaunay&&e.delaunayAspectRatio===t||(e.delaunay=Mo.Delaunay.from(e.points,n=>n.x*t,n=>n.y),e.delaunayAspectRatio=t)}function Nh(e){const t=e.data;if(t.size()===0)return[];if(!t.hasVariable(f.x)||!t.hasVariable(f.y))return[];const n=t.getValues(f.x,{type:"numeric"}),r=t.getValues(f.y,{type:"numeric"}),s=[];let a=0;for(const o of t){const i=n[a],c=r[a];a+=1,!(!h(i)||!h(c))&&s.push({pointIndex:s.length,x:i,y:c,observation:o})}return s}const Ph=1e6;function Oh(e,t){const n=Bh(e,t);n.sort((i,c)=>i.mainMid-c.mainMid);const r=new Map,s=new Map;for(const i of n){const c=Ts(i.mainMid);let l=r.get(c);if(!l){l={mainMid:i.mainMid,columnKey:c,rects:[]},r.set(c,l);const u=Ts(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 a=[...r.values()].sort((i,c)=>i.mainMid-c.mainMid),o=[...s.values()].sort((i,c)=>i.bandCenter-c.bandCenter);for(const i of o)i.columns.sort((c,l)=>c.mainMid-l.mainMid);return{kind:"rects",layerId:e.id,geom:e.geom,position:e.position,mainAxis:t,columns:a,bands:o}}function Ts(e){return String(Math.round(e*Ph))}function Bh(e,t){const n=e.data;if(n.size()===0)return[];if(!(n.hasVariable(f.xMin)&&n.hasVariable(f.xMax)&&n.hasVariable(f.yMin)&&n.hasVariable(f.yMax)))return[];const s=n.getValues(f.xMin,{type:"numeric"}),a=n.getValues(f.xMax,{type:"numeric"}),o=n.getValues(f.yMin,{type:"numeric"}),i=n.getValues(f.yMax,{type:"numeric"}),c=t==="y",l=c?f.y:f.x,u=n.hasVariable(l)?n.getValues(l,{type:"numeric"}):null,d=n.hasVariable(z.group)?n.getValues(z.group,{type:"categorical"}):null,p=[];let m=0;for(const y of n){const g=s[m],b=a[m],x=o[m],S=i[m];if(!h(g)||!h(b)||!h(x)||!h(S)){m++;continue}const w=c?(x+S)/2:(g+b)/2,k=u?.[m]??w;p.push({mainMid:w,bandCenter:k,entry:{pointIndex:m,xMin:g,xMax:b,yMin:x,yMax:S,segmentKey:d?.[m]??null,observation:y}}),m++}return p}function Ms(e,t,n){if(t.type==="polar")return Ih(e);switch(e.geom){case"point":return Rh(e,n);case"line":case"area":return Dh(e,t.mainAxis);case"bar":return Oh(e,t.mainAxis);case"rule":return Fh(e);default:{const r=e.geom;throw new Error(`buildLayerIndex: unhandled geom ${String(r)}`)}}}const J=Math.PI*2,$h=1e-9;function Gh(e,t,n){if(e.arcs.length===0)return null;const{angle:r,radius:s}=zh(t,n);for(const a of e.arcs)if(!(s<a.innerRadius||s>a.outerRadius)&&Wh(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 zh(e,t){const n=e.x-.5,r=e.y-.5,s=t>=1?n*2*t:n*2,a=t>=1?r*2:r*2/t,o=Math.hypot(s,a);return{angle:(Math.atan2(s,a)%J+J)%J,radius:o}}function Wh(e,t){const n=t.endAngle-t.startAngle;if(Math.abs(n)>=J-$h)return!0;const r=(n%J+J)%J;return((e-t.startAngle)%J+J)%J<=r}function Yh(e,t,n){if(e.buckets.length===0)return null;const{main:r,cross:s}=$m(e.mainAxis,t),a=ho(e,r),o=a?.entries??[];if(!a||!In(o))return null;const i=Xh(o,s,e.mainAxis);return{hit:{layerId:e.layerId,pointIndex:i.pointIndex,x:i.x,y:i.y,observation:i.observation},index:e,bucket:a,distance:dr(i.x-t.x,i.y-t.y,n)}}function Hh(e,t,n){if(e.columns.length===0)return null;const r=Fe(e.mainAxis,t),s=bh(e,r),a=s?.rects??[];if(!s||!In(a))return null;const o=X(e.position)?Uh(a,t,e.mainAxis):Kh(a,t,n);return{hit:{layerId:e.layerId,pointIndex:o.pointIndex,x:(o.xMin+o.xMax)/2,y:(o.yMin+o.yMax)/2,observation:o.observation},index:e,column:s,distance:go(o,t,n)}}function Uh(e,t,n){const r=Gt(n,t);return mr(e,a=>jh(a,n,r),{shortCircuitOnZero:!0})}function Kh(e,t,n){return mr(e,s=>go(s,t,n))}function Xh(e,t,n){return mr(e,s=>Math.abs(Gt(n,s)-t))}function mr(e,t,{shortCircuitOnZero:n=!1}={}){let r=e[0],s=t(r);if(n&&s===0)return r;for(let a=1;a<e.length;a+=1){const o=e[a];if(o===void 0)continue;const i=t(o);if(n&&i===0)return o;i<s&&(r=o,s=i)}return r}function go(e,t,n){const r=En(t.x,e.xMin,e.xMax),s=En(t.y,e.yMin,e.yMax);return dr(r,s,n)}function jh(e,t,n){const r=t==="x"?e.yMin:e.xMin,s=t==="x"?e.yMax:e.xMax;return En(n,r,s)}function En(e,t,n){return e<t?t-e:e>n?e-n:0}const qh=.05;function Qh({layers:e,cursor:t,aspectRatio:n,warmStarts:r}){const s={match:null,distance:Number.POSITIVE_INFINITY},a={match:null,distance:Number.POSITIVE_INFINITY};for(const o of e){if(o.kind==="arcs"){const c=Gh(o,t,n);return c?{kind:"arcs",match:c}:null}const i=Jh({layer:o,cursor:t,aspectRatio:n,warmStarts:r});if(i){if(i.kind==="rects"){i.match.distance<s.distance&&(s.match=i,s.distance=i.match.distance);continue}i.match.distance<a.distance&&(a.match=i,a.distance=i.match.distance)}}return Zh({rect:s,continuous:a})}function Zh({rect:e,continuous:t}){return e.match&&t.match?t.distance<=e.distance+qh?t.match:e.match:e.match??t.match}function Jh({layer:e,cursor:t,aspectRatio:n,warmStarts:r}){switch(e.kind){case"buckets":{const s=Yh(e,t,n);return s?{kind:"buckets",match:s}:null}case"rects":{const s=Hh(e,t,n);return s?{kind:"rects",match:s}:null}case"points":{const s=r.get(e.layerId)??null,a=vh(e,t,n,s);return a?{kind:"points",match:a}:null}case"noop":return null}}const Ue={primary:null,group:[],related:new Map},ey=1;class ty{constructor({layers:t,coordSystem:n}){this.layerIndexes=[],this.layerRefs=[],this.aspectRatio=ey,this.warmStarts=new Map,this.cachedState=Ue,this.cachedKey=null,this.nonInteractiveLayerIds=new Set,this.layerIndexes=t.map(r=>Ms(r,n,this.aspectRatio)),this.layerRefs=t.map(r=>Ls(r,n)),this.nonInteractiveLayerIds=Vs(t)}update({layers:t,coordSystem:n}){const r=new Map;for(let o=0;o<this.layerIndexes.length;o+=1){const i=this.layerIndexes[o],c=this.layerRefs[o];!i||!c||r.set(i.layerId,{index:i,ref:c})}const s=[],a=[];for(const o of t){const i=r.get(o.id),c=Ls(o,n);if(i!==void 0&&ny(i.ref,c)){s.push(i.index),a.push(i.ref);continue}this.warmStarts.delete(o.id),s.push(Ms(o,n,this.aspectRatio)),a.push(c)}for(const o of this.warmStarts.keys())t.some(i=>i.id===o)||this.warmStarts.delete(o);this.layerIndexes=s,this.layerRefs=a,this.nonInteractiveLayerIds=Vs(t),this.invalidateCache()}setViewport(t){this.aspectRatio=t.width/t.height;for(const n of this.layerIndexes)n.kind==="points"&&yo(n,this.aspectRatio)}query(t){if(this.layerIndexes.length===0)return Ue;const n=this.nonInteractiveLayerIds.size===0?this.layerIndexes:this.layerIndexes.filter(c=>!this.nonInteractiveLayerIds.has(c.layerId)),r=Qh({layers:n,aspectRatio:this.aspectRatio,warmStarts:this.warmStarts,cursor:t});if(!r)return this.invalidateCache(),Ue;const s=r.match.hit;this.warmStarts.set(s.layerId,s.pointIndex);const a=`${s.layerId}:${s.pointIndex}`;if(this.cachedKey===a)return this.cachedState;const{group:o,related:i}=Sh(r,n);return this.cachedKey=a,this.cachedState={primary:s,group:o,related:i},this.cachedState}invalidateCache(){this.cachedKey=null,this.cachedState=Ue}}function Ls(e,t){return{data:e.data,geom:e.geom,position:e.position,coord:t}}function Vs(e){const t=new Set;for(const n of e)n.interactive||t.add(n.id);return t}function ny(e,t){return e.data===t.data&&e.geom===t.geom&&e.position===t.position&&e.coord===t.coord}function ry(e,t){const n=Fe(e.mainAxis,t);if(e.mainAxis==="y"){const s=be(we(n));return{x1:0,x2:"100%",y1:s,y2:s}}const r=be(n);return{x1:r,x2:r,y1:0,y2:"100%"}}function sy(e,t,n){const r=e.mainAxis==="y"?C(n.observation):$(n.observation);if(r===null)return null;const s=e.mainAxis==="y"?vo(n):bo(n),o=(t.x?.kind==="position"?t.x:null)?.bandwidth??s;if(o===null||o<=0)return null;const i=o/2;if(e.mainAxis==="y"){const u=be(we(r+i)),d=be(o);return{x:0,y:u,width:"100%",height:d}}const c=be(r-i),l=be(o);return{x:c,y:0,width:l,height:"100%"}}function bo(e){const t=me(e.observation),n=ae(e.observation);return t===null||n===null?null:n-t}function vo(e){const t=te(e.observation),n=H(e.observation);return t===null||n===null?null:n-t}const ay=/^(?:https?:|mailto:)/i,oy=e=>{if(typeof e!="string")return!1;const t=e.replace(/^[\x00-\x20]+/,"");return t.length===0?!1:ay.test(t)},iy=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"long",year:"numeric",weekday:"long",...O,...t}).format(n)),cy=({locale:e,intlOptions:t})=>N(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,...O,...t}).format(n)}),Vt=e=>{const{valueFormat:t}=e;switch(t.type){case"currency":return $a(e);case"date":return iy(e);case"datetime":return cy(e);case"day_month":return Wa(e);case"decimal":return jn(e);case"duration":return qn();case"integer":return Ga(e);case"month":return Ya(e);case"month_year":return Jn(e);case"percentage":return za(e);case"quarter":return er();case"text":return Xn();case"time":return Ka(e);case"weekly_date_range":return Ha(e);case"weekly_date_range_with_year":return Ua(e);case"year":return tr(e);case"lookup":return Vt({...e,valueFormat:t.fallback});default:{const n=t;throw new Error(`Unhandled value format: ${n.type}`)}}},ly=({layers:e,coordSystem:t,scales:n,guides:r,numberFormat:s,parsingLocale:a,hover:o,formattingLocale:i})=>{const{primary:c}=o;if(c===null)return null;const l=i??a;return{header:uy({layers:e,coordSystem:t,guides:r,primary:c,locale:l,numberFormat:s}),rows:dy({layers:e,coordSystem:t,scales:n,guides:r,hover:o,locale:l,numberFormat:s})}};function uy(e){if(e.coordSystem.type!=="cartesian")return null;const t=zt(e.guides,"x");if(!t)return null;const n=e.layers.find(o=>o.id===e.primary.layerId);if(!n)return null;const r=v(n.mapping.x);if(!h(r))return null;const s=e.primary.observation[r];return h(s)?Vt({valueFormat:t.valueFormat,locale:e.locale,numberFormat:e.numberFormat})(s):null}function dy(e){const t=[],n=e.scales.color??null,r=fy({guides:e.guides,locale:e.locale,numberFormat:e.numberFormat});for(const s of e.layers){const a=py(s,e.hover);if(a.length===0)continue;const o=ha(s.data,s.mapping),i=my(a,s,n,o),c=cr({layer:s,numberFormat:e.numberFormat,locale:e.locale}),l=hy(e.guides,s),u=Nt(s),d=s.mapping.color!==void 0,p=Tt(s.geom,e.coordSystem);for(const m of i){const y=d?o(m.observation):null,g=Ct(m.observation)??null,b=Ns(m.observation),x=d&&y!==null?r(y):l,S=u(m.observation),w=S===null?"":c(S,m.observation);t.push({swatchColor:g,swatchShape:p,swatchLineType:b,label:x,value:w,isPrimary:m===e.hover.primary,key:`${m.layerId}:${m.pointIndex}`})}}return t}function py(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 my(e,t,n,r){if(n===null||t.mapping.color===void 0)return e;const s=new Map;return n.domain.forEach((a,o)=>{s.set(E(a),o)}),e.map((a,o)=>{const i=r(a.observation),c=i===null?null:E(i),l=c===null?Number.POSITIVE_INFINITY:s.get(c)??Number.POSITIVE_INFINITY;return{hit:a,originalIndex:o,rank:l}}).sort((a,o)=>a.rank===o.rank?a.originalIndex-o.originalIndex:a.rank-o.rank).map(a=>a.hit)}function fy({guides:e,locale:t,numberFormat:n}){const r=new Map(e.colorGroups.map(a=>[E(a.value),{label:a.label,format:Vt({valueFormat:a.valueFormat,locale:t,numberFormat:n})}])),s=Vt({valueFormat:{type:"text"},locale:t,numberFormat:n});return a=>{const o=r.get(E(a));return o===void 0?s(a):o.label??o.format(a)}}function hy(e,t){const n=Oe(t.yScaleType);return zt(e,n)?.label??""}const yy={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 gy(e,t={}){return{type:"highlight",id:t.id,predicate:e,scope:t.scope,layerIndex:t.layerIndex}}function by(...e){let t={},n;const[r,...s]=e;h(r)&&!xy(r)?(t=r,n=s):n=e;const a={mapping:t,layers:[],scales:[],transforms:[],highlights:[],config:{}};return n.reduce((o,i)=>xo(o,i),a)}function vy(e,...t){return t.reduce((n,r)=>xo(n,r),e)}function xy(e){return typeof e=="object"&&e!==null&&"type"in e}function xo(e,t){switch(t.type){case"scale":return{...e,scales:[...e.scales,t]};case"coord":return{...e,coords:t};case"config":return{...e,config:Es({},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]};default:{const n=t;throw new Error(`Unknown spec item type: ${n.type}`)}}}function Sy(e){return{mapping:e.mapping,layers:e.layers,scales:e.scales.map(Ay),transforms:e.transforms,highlights:e.highlights.map(t=>wy(t,e.layers)),coords:e.coords,config:e.config}}function wy(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 Ay(e){return e.scaleType==="palette"?Ty(e):e}function Ty(e){return{...e,palette:My(e.palette),overrides:Ly(e.overrides)}}function My(e){return e.type==="custom"?{type:"custom",id:e.id}:e}function Ly(e){if(!e)return;const t={};for(const[n,r]of Object.entries(e))t[Number(n)]={hex:r};return t}function L(e){return{id:e.id??crypto.randomUUID(),timestamp:e.timestamp??Date.now(),description:e.description,author:e.author??"unknown"}}class fr{constructor(t,n={}){this.type="set-axis-label",this.params=t,this.metadata=L({...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,a=R(t,{config:{axes:{[n]:{label:r}}}}),o=new fr({axis:n,label:s},this.metadata);return{spec:a,revert:o}}}const Vy={type:"set-axis-label",deserialize:(e,t)=>new fr(e,t)};class hr{constructor(t,n={}){this.type="set-axis-label-mode",this.params=t,this.metadata=L({...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,a=R(t,{config:{axes:{[n]:{ticks:{mode:r}}}}}),o=new hr({axis:n,labelMode:s},this.metadata);return{spec:a,revert:o}}}const Ey={type:"set-axis-label-mode",deserialize:(e,t)=>new hr(e,t)};class Wt{constructor(t,n={}){this.type="set-axis-position",this.params=t,this.metadata=L({...n,description:`Set ${t.axis} axis position to ${t.position}`})}apply(t){const{axis:n,position:r}=this.params,s=R(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},o=new Wt(a,this.metadata);return{spec:s,revert:o}}}const Iy={type:"set-axis-position",deserialize:(e,t)=>new Wt(e,t)};class yr{constructor(t,n={}){this.type="set-axis-ticks-visibility",this.params=t,this.metadata=L({...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,a=R(t,{config:{axes:{[n]:{ticks:{isVisible:r}}}}}),o=new yr({axis:n,isVisible:s},this.metadata);return{spec:a,revert:o}}}const ky={type:"set-axis-ticks-visibility",deserialize:(e,t)=>new yr(e,t)};class gr{constructor(t,n={}){this.type="set-axis-visibility",this.params=t,this.metadata=L({...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,a=R(t,{config:{axes:{[n]:{isVisible:r}}}}),o=new gr({axis:n,isVisible:s},this.metadata);return{spec:a,revert:o}}}const Cy={type:"set-axis-visibility",deserialize:(e,t)=>new gr(e,t)};class Yt{constructor(t,n={}){this.type="set-content-caption",this.params=t,this.metadata=L({...n,description:"Set chart caption"})}apply(t){const n=t.config.content.caption;if(n===this.params.caption)return null;const r=R(t,{config:{content:{caption:this.params.caption}}}),s=new Yt({caption:n},this.metadata);return{spec:r,revert:s}}}const Dy={type:"set-content-caption",deserialize:(e,t)=>new Yt(e,t)};class Ht{constructor(t,n={}){this.type="set-content-subtitle",this.params=t,this.metadata=L({...n,description:"Set chart subtitle"})}apply(t){const n=t.config.content.subtitle;if(n===this.params.subtitle)return null;const r=R(t,{config:{content:{subtitle:this.params.subtitle}}}),s=new Ht({subtitle:n},this.metadata);return{spec:r,revert:s}}}const _y={type:"set-content-subtitle",deserialize:(e,t)=>new Ht(e,t)};class Ut{constructor(t,n={}){this.type="set-content-title",this.params=t,this.metadata=L({...n,description:"Set chart title"})}apply(t){const n=t.config.content.title;if(n===this.params.title)return null;const r=R(t,{config:{content:{title:this.params.title}}}),s=new Ut({title:n},this.metadata);return{spec:r,revert:s}}}const Fy={type:"set-content-title",deserialize:(e,t)=>new Ut(e,t)};class br{constructor(t,n={}){this.type="set-grid-visibility",this.params=t,this.metadata=L({...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=R(t,{config:{axes:{x:{grid:{isVisible:this.params.xIsVisible}},y:{grid:{isVisible:this.params.yIsVisible}}}}}),a=new br({xIsVisible:n,yIsVisible:r},this.metadata);return{spec:s,revert:a}}}const Ry={type:"set-grid-visibility",deserialize:(e,t)=>new br(e,t)};class vr{constructor(t,n={}){this.type="set-headline-compare-with",this.params=t,this.metadata=L({...n,description:`Set headline compare with to ${t.compareWith}`})}apply(t){const n=t.config.headline.compareWith,r=R(t,{config:{headline:{compareWith:this.params.compareWith}}}),s=new vr({compareWith:n},this.metadata);return{spec:r,revert:s}}}const Ny={type:"set-headline-compare-with",deserialize:(e,t)=>new vr(e,t)};class xr{constructor(t,n={}){this.type="set-headline-position",this.params=t,this.metadata=L({...n,description:`Set headline position to ${t.position}`})}apply(t){const n=t.config.headline.position,r=R(t,{config:{headline:{position:this.params.position}}}),s=new xr({position:n},this.metadata);return{spec:r,revert:s}}}const Py={type:"set-headline-position",deserialize:(e,t)=>new xr(e,t)};class Kt{constructor(t,n={}){this.type="set-headline-show",this.params=t,this.metadata=L({...n,description:`Set headline show to ${t.show}`})}apply(t){const n=t.config.headline.show,r=R(t,{config:{headline:{show:this.params.show}}}),s=new Kt({show:n},this.metadata);return{spec:r,revert:s}}}const Oy={type:"set-headline-show",deserialize:(e,t)=>new Kt(e,t)};class Sr{constructor(t,n={}){this.type="set-headline-size",this.params=t,this.metadata=L({...n,description:`Set headline size to ${t.size}`})}apply(t){const n=t.config.headline.size,r=R(t,{config:{headline:{size:this.params.size}}}),s=new Sr({size:n},this.metadata);return{spec:r,revert:s}}}const By={type:"set-headline-size",deserialize:(e,t)=>new Sr(e,t)};class wr{constructor(t,n={}){this.type="set-legend-position",this.params=t,this.metadata=L({...n,description:`Set legend position to ${t.position}`})}apply(t){const n=t.config.legend.position,r=R(t,{config:{legend:{position:this.params.position}}}),s=new wr({position:n},this.metadata);return{spec:r,revert:s}}}const $y={type:"set-legend-position",deserialize:(e,t)=>new wr(e,t)};class Ar{constructor(t,n={}){this.type="set-number-format-abbreviation",this.params=t,this.metadata=L({...n,description:`Set number format abbreviation to ${t.abbreviation}`})}apply(t){const n=t.config.numberFormat.abbreviation,r=R(t,{config:{numberFormat:{abbreviation:this.params.abbreviation}}}),s=new Ar({abbreviation:n},this.metadata);return{spec:r,revert:s}}}const Gy={type:"set-number-format-abbreviation",deserialize:(e,t)=>new Ar(e,t)};class Tr{constructor(t,n={}){this.type="set-number-format-decimals",this.params=t,this.metadata=L({...n,description:`Set number format decimals to ${t.decimals}`})}apply(t){const n=t.config.numberFormat.decimals,r=R(t,{config:{numberFormat:{decimals:this.params.decimals}}}),s=new Tr({decimals:n},this.metadata);return{spec:r,revert:s}}}const zy={type:"set-number-format-decimals",deserialize:(e,t)=>new Tr(e,t)};class Mr{constructor(t,n={}){this.type="set-line-interpolation",this.params=t,this.metadata=L({...n,description:`Set line interpolation to ${t.interpolate}`})}apply(t){const n=this.params.layerId?Bt(t.layers,this.params.layerId):at(t.layers,"line","area");if(!Ot(n,"line","area"))return null;const r=n.params.interpolate,s=Un(t,n.id,{...n,params:{...n.params,interpolate:this.params.interpolate}}),a=new Mr({layerId:n.id,interpolate:r},this.metadata);return{spec:s,revert:a}}}const Wy={type:"set-line-interpolation",deserialize:(e,t)=>new Mr(e,t)};class Xt{constructor(t,n={}){this.type="set-line-width",this.params=t,this.metadata=L({...n,description:`Set line width to ${t.lineWidth}`})}apply(t){const n=this.params.layerId?Bt(t.layers,this.params.layerId):at(t.layers,"line","area");if(!Ot(n,"line","area"))return null;const r=n.params.lineWidth,s=Un(t,n.id,{...n,params:{...n.params,lineWidth:this.params.lineWidth}}),a=new Xt({layerId:n.id,lineWidth:r},this.metadata);return{spec:s,revert:a}}}const Yy={type:"set-line-width",deserialize:(e,t)=>new Xt(e,t)};class Lr{constructor(t,n={}){this.type="set-point-size",this.params=t,this.metadata=L({...n,description:`Set point size to ${t.size}`})}apply(t){const n=this.params.layerId?Bt(t.layers,this.params.layerId):at(t.layers,"point");if(!Ot(n,"point"))return null;const r=n.params.size,s=Un(t,n.id,{...n,params:{...n.params,size:this.params.size}}),a=new Lr({layerId:n.id,size:r},this.metadata);return{spec:s,revert:a}}}const Hy={type:"set-point-size",deserialize:(e,t)=>new Lr(e,t)};class Et{constructor(t,n={}){this.type="toggle-line-points",this.params=t,this.metadata=L({...n,description:`${t.showPoints?"Show":"Hide"} line points`})}apply(t){const n=this.params.layerId?Bt(t.layers,this.params.layerId):at(t.layers,"line");return Ot(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??Ca(t.mapping,t.coords.coordType,_.point({aes:{...n.mapping},interactive:!1})),s={...t,layers:[...t.layers,r]},a=new Et({layerId:n.id,showPoints:!1},this.metadata);return{spec:s,revert:a}}removePointLayer(t,n){const r=this.findAssociatedPointLayer(t,n);if(!r)return null;const s=Qd(t,r.id),a=new Et({layerId:n.id,showPoints:!0,removedLayer:r},this.metadata);return{spec:s,revert:a}}findAssociatedPointLayer(t,n){return t.layers.find(r=>r.geom==="point"&&Lo(r.mapping,n.mapping))}}const Uy={type:"toggle-line-points",deserialize:(e,t)=>new Et(e,t)};function jt(e,t){return e.scales.find(n=>n.scaledAesthetic===t)}function qt(e,t,n){const r=e.scales.map(s=>s.scaledAesthetic===t?n:s);return{...e,scales:r}}function Qt(e){const t=e.replace(/([A-Z])/g," $1").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}class Zt{constructor(t,n={}){this.type="set-scale-domain",this.params=t,this.metadata=L({...n,description:`Set ${Qt(t.scaledAesthetic)} scale domain`})}apply(t){const n=jt(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}},a=qt(t,this.params.scaledAesthetic,s),o={scaledAesthetic:this.params.scaledAesthetic};this.params.domainMin!==void 0&&(o.domainMin=r.min),this.params.domainMax!==void 0&&(o.domainMax=r.max);const i=new Zt(o,this.metadata);return{spec:a,revert:i}}}const Ky={type:"set-scale-domain",deserialize:(e,t)=>new Zt(e,t)};class Vr{constructor(t,n={}){this.type="set-scale-palette",this.params=t,this.metadata=L({...n,description:`Set ${Qt(t.scaledAesthetic)} palette`})}apply(t){const n=jt(t,this.params.scaledAesthetic);if(n?.scaleType!=="palette")return null;const r=qt(t,this.params.scaledAesthetic,{...n,scaledAesthetic:this.params.scaledAesthetic,palette:this.params.palette}),s=new Vr({scaledAesthetic:this.params.scaledAesthetic,palette:n.palette},this.metadata);return{spec:r,revert:s}}}const Xy={type:"set-scale-palette",deserialize:(e,t)=>new Vr(e,t)};class Er{constructor(t,n={}){this.type="set-scale-reverse",this.params=t,this.metadata=L({...n,description:`Set ${Qt(t.scaledAesthetic)} scale reverse to ${t.reverse}`})}apply(t){const n=jt(t,this.params.scaledAesthetic);if(!n||n.scaleType!=="continuous")return null;const r=n.reverse,s=qt(t,this.params.scaledAesthetic,{...n,reverse:this.params.reverse}),a=new Er({scaledAesthetic:this.params.scaledAesthetic,reverse:r},this.metadata);return{spec:s,revert:a}}}const jy={type:"set-scale-reverse",deserialize:(e,t)=>new Er(e,t)};class Ir{constructor(t,n={}){this.type="set-scale-transform",this.params=t,this.metadata=L({...n,description:`Set ${Qt(t.scaledAesthetic)} scale transform to ${t.transform}`})}apply(t){const n=jt(t,this.params.scaledAesthetic);if(!n||n.scaleType!=="continuous")return null;const r=n.transform,s=qt(t,this.params.scaledAesthetic,{...n,transform:this.params.transform}),a=new Ir({scaledAesthetic:this.params.scaledAesthetic,transform:r},this.metadata);return{spec:s,revert:a}}}const qy={type:"set-scale-transform",deserialize:(e,t)=>new Ir(e,t)};class So{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 M=new So;M.register(Wy);M.register(Yy);M.register(Hy);M.register(Uy);M.register(Ky);M.register(Xy);M.register(jy);M.register(qy);M.register(Vy);M.register(Ey);M.register(Iy);M.register(ky);M.register(Cy);M.register(Dy);M.register(_y);M.register(Fy);M.register(Ry);M.register(Ny);M.register(Py);M.register(Oy);M.register(By);M.register($y);M.register(Gy);M.register(zy);class Qy{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 kr=500,Cr="normal",Dr={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},Zy=e=>{const t=e.style??Cr,n=e.weight??kr,r=e.family.includes(",")?e.family:`'${e.family}'`;return`${t} ${n} ${e.size}px ${r}`},Jy=e=>typeof e=="string"?e:wo(e),wo=e=>e.text!==void 0?e.text:e.content?e.content.map(wo).join(""):"",_r=e=>typeof e!="string"?e??kr:Dr[e],eg="\0";class tg{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 a=this.inner.measureText(t,n);return this.cache.set(r,a),a}getCacheKey(t,n){return[n.family,n.size,_r(n.weight),n.style??Cr,t].join(eg)}}const ng={" ":.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},rg=.55,sg=1.05,ag=.84,og=.21;class ig{measureText(t,n){let r=0;for(const i of t)r+=(ng[i]??rg)*n.size;_r(n.weight)>=Dr.semiBold&&(r*=sg);const a=ag*n.size,o=og*n.size;return{width:r,height:a+o,ascent:a,descent:o}}}exports.BORDER_PRESETS=Ma;exports.BORDER_PRESET_GRADIENTS=yy;exports.COMPILER_STAGE_KEYS=_p;exports.CachedTextMeasurer=tg;exports.CommandRegistry=So;exports.CommandStackManager=Qy;exports.Compiler=Oa;exports.DEFAULT_FONT_STYLE=Cr;exports.DEFAULT_FONT_WEIGHT=kr;exports.DEFAULT_LINE_WIDTH=fo;exports.DEFAULT_LOCALE=Dt;exports.Dataset=I;exports.GROUP_VARIABLES=z;exports.HEADLINE_SWATCH_GAP=lo;exports.HEADLINE_SWATCH_SIZE=co;exports.HEADLINE_TREND_GAP=mo;exports.HEADLINE_TREND_ICON_SIZE=po;exports.HEADLINE_VALUE_LABEL_GAP=uo;exports.HeuristicTextMeasurer=ig;exports.HoverEngine=ty;exports.LAYOUT_PADDING=Za;exports.LayoutCompiler=Nm;exports.MONO_BASES=xa;exports.NAMED_WEIGHTS=Dr;exports.NEON_BASES=Sa;exports.POSITION_VARIABLES=f;exports.RESTING_HOVER_STATE=Ue;exports.SetAxisPositionCommand=Wt;exports.SetContentCaptionCommand=Yt;exports.SetContentSubtitleCommand=Ht;exports.SetContentTitleCommand=Ut;exports.SetHeadlineShowCommand=Kt;exports.SetLineWidthCommand=Xt;exports.SetScaleDomainCommand=Zt;exports.SpecResolver=Fa;exports.VISUAL_VARIABLES=pe;exports.buildAverageLineSymbols=Om;exports.buildDataLabelsContent=Tf;exports.buildFontString=Zy;exports.buildLayerYValueFormatter=cr;exports.buildPolarBarArcPath=fh;exports.buildTooltipContent=ly;exports.commandRegistry=M;exports.computeDifferenceArrow=Cf;exports.computeDirectLabelsLayout=_f;exports.computeFreeformArrow=sh;exports.config=La;exports.convertSpecToInput=Sy;exports.coord=B;exports.createAlphaValueReader=xl;exports.createAreaPathGenerators=ch;exports.createColorValueReader=ha;exports.createCompiler=Fp;exports.createEmptyHighlight=ya;exports.createGroupValueReader=Sl;exports.createHeadlineItemRows=Hf;exports.createLabelValueReader=bl;exports.createLinePathGenerator=dh;exports.createRawValueReader=j;exports.createSegmentYReader=Nt;exports.createSizeValueReader=vl;exports.createSpec=by;exports.createStableKeyGenerator=hh;exports.createStrokeWidthValueReader=wl;exports.createValueFormatter=P;exports.createXValueReader=Ft;exports.createYValueReader=fa;exports.extractPlainText=Jy;exports.findAxisGuide=zt;exports.findLegendForAesthetic=Wf;exports.formatHeadline=Ff;exports.formatLegends=Gf;exports.formatRuleValue=Yf;exports.geom=_;exports.getAlpha=No;exports.getAngleExtent=ao;exports.getBarRectBounds=uh;exports.getColor=Ct;exports.getCrossAxisCoordinate=Gt;exports.getCurve=lr;exports.getDashArray=oh;exports.getDifferenceArrowDimensions=ar;exports.getGroup=Le;exports.getHoverGuideLineProps=ry;exports.getHoverGuideRectProps=sy;exports.getLineType=Ns;exports.getMainAxisCoordinate=Fe;exports.getNumericWeight=_r;exports.getRadiusExtent=oo;exports.getSize=Fs;exports.getStablePolarBarKeyGenerator=yh;exports.getStrokeWidth=Rs;exports.getX=$;exports.getXMax=ae;exports.getXMin=me;exports.getY=C;exports.getYMax=H;exports.getYMin=te;exports.getYRaw=_s;exports.highlight=gy;exports.isCartesian=Gm;exports.isCategoricalValueFormat=zs;exports.isCompilerCachingEnabled=Eo;exports.isCurrencyValueFormat=Cn;exports.isDateWithoutYearValueFormat=Dn;exports.isDefined=h;exports.isGraphConfig=Aa;exports.isLayerOf=Rp;exports.isLookupValueFormat=Gs;exports.isNumericValueFormat=kn;exports.isSafeUrl=oy;exports.isStackedPosition=X;exports.isTemporalValueFormat=Pe;exports.mapping=Do;exports.pipe=vy;exports.prefixInternalVariable=A;exports.prepareAreaObservations=lh;exports.prepareLineObservations=ph;exports.readXExtent=bo;exports.readYExtent=vo;exports.resolveHeadlinePlacement=_m;exports.resolveSegmentYSource=Rt;exports.resolveStrokeWidth=ih;exports.resolveYScaleAesthetic=Oe;exports.scale=Se;exports.setCompilerCachingEnabled=Vo;exports.stat=zn;exports.toPercent=be;exports.toViewBoxX=zm;exports.toViewBoxY=we;exports.transform=xe;
|
|
25
|
+
`,If=(e,t,n,r,s,a=.5)=>{if(e){const i=Math.min(t.y,n.y);return{x:r,y:i+a*s}}return{x:Math.min(t.x,n.x)+a*s,y:r}},kf=(e,t,n)=>Math.abs(e?t.y-n.y:t.x-n.x),Cf=({arrow:e,mainAxis:t,panelWidth:n,panelHeight:r,textScale:s,locale:a})=>{const o=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=ar(e.size,s),u=Mf(o,i,c,l),d=(o?Vf:Lf)(i,c,u,l),p=Ef(o,c,l),m=kf(o,i,c),y=If(o,i,c,u,m,e.labelCrossPosition),g=Qa({locale:a,kind:e.label,startValue:e.start.measurementValue,endValue:e.end.measurementValue});return{id:e.id,linePath:d,arrowheadPath:p,labelPosition:y,labelText:g,color:e.color,strokeWidth:l.strokeWidth,labelLineHeight:l.labelLineHeight,labelPaddingX:l.labelPaddingX,labelPaddingY:l.labelPaddingY,labelStrokeWidth:l.labelStrokeWidth,labelFontWeight:l.labelFontWeight}},Df=100,_f=({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 a=!1,o=!0,i=0;for(;o;){o=!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){o=!0,a=!0;const g=(p-m)/2+1;u.y-=g,d.y+=g,u.y<0&&(u.y=0),d.y>t&&(d.y=t)}}if(i>Df)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}},Ff=({headline:e,show:t,numberFormat:n,parsingLocale:r,formattingLocale:s,t:a})=>{if(e===null)return null;const o=s??r;return e.kind==="grandTotal"?Rf(e,o,n):Nf(e,t,o,n,a)},Rf=(e,t,n)=>({kind:"grandTotal",value:P({valueFormat:e.valueFormat,locale:t,numberFormat:n})(e.value)}),Nf=(e,t,n,r,s)=>{const a=P({valueFormat:{type:"percentage"},locale:n,numberFormat:r}),o=e.items.length>1;return{kind:"perGroup",items:e.items.map(c=>{const l=P({valueFormat:c.valueFormat,locale:n,numberFormat:r}),u=P({valueFormat:c.groupLabelFormat,locale:n,numberFormat:r}),d=sr({valueFormat:c.mainValueFormat,locale:n,numberFormat:r,tickValues:[]}),p=c.label??u(c.value);return{swatch:c.swatch,label:$f(t,o,p,s),value:c.aggregate===null?null:l(c.aggregate),observationLabel:Bf(c.observationLabel,d),comparison:Pf(c.comparison,d,a,s)}})}},Pf=(e,t,n,r)=>e===null?null:{direction:Of(e.variation),percentage:n(Math.abs(e.variation)),reference:r("graph.headlineMetrics.comparisonReference",{value:t(e.against)})},Of=e=>e>0?"up":e<0?"down":"flat",Bf=(e,t)=>e===null?null:e.kind==="point"?t(e.value):`${t(e.from)} – ${t(e.to)}`,$f=(e,t,n,r)=>{switch(e){case"total":return r("graph.headlineMetrics.total",{value:n});case"average":return t?r("graph.headlineMetrics.averageShort",{value:n}):r("graph.headlineMetrics.averageLong",{value:n});case"current":case"conversion":case"none":return n}},Gf=({legends:e,numberFormat:t,parsingLocale:n,formattingLocale:r})=>{const s=r??n;return e.map(a=>zf(a,s,t))},zf=(e,t,n)=>({...e,items:e.items.map(r=>{const s=P({valueFormat:r.valueFormat,locale:t,numberFormat:n});return{...r,formattedLabel:r.label??s(r.value)}})});function zt(e,t){return e.axes.find(n=>n.scaleAestheticKey===t)??null}function Wf(e,t){return e.legends.find(n=>n.aesthetics.includes(t))??null}const Yf=({guides:e,numberFormat:t,layer:n,locale:r})=>{const s=n.data.getFirst();if(!s)return null;const a=n.mapping.y!==void 0,i=(a?ha:Ft)(n.data,n.mapping)(s);if(i===null)return null;const c=a?Oe(n.yScaleType):"x",l=zt(e,c)?.valueFormat??{type:"decimal"};return P({valueFormat:l,locale:r,numberFormat:t})(i)},co=12,lo=4,uo=4,po=12,mo=4,Hf=e=>{const{value:t,observationLabel:n,comparison:r,swatch:s,label:a}=e;return[{role:"valueRow",gap:uo,segments:xn([ft("value","value",t??"–"),ft("observation","label",n)])},{role:"trendRow",gap:mo,ariaLabel:r===null?void 0:jf(r),segments:xn([Kf(r),Xf(r),ft("trendReference","label",r?.reference??null)])},{role:"groupRow",gap:lo,segments:xn([Uf(s),ft("label","label",a)])}].filter(i=>i.segments.length>0)},ft=(e,t,n)=>n===null?null:{kind:"text",textRole:e,fontRole:t,text:n},Uf=e=>e===null?null:{kind:"swatch",swatch:e,size:co},Kf=e=>e===null?null:{kind:"trendArrow",direction:e.direction,size:po},Xf=e=>e===null?null:{kind:"text",textRole:"trendPercentage",fontRole:"label",text:e.percentage,trendDirection:e.direction},jf=e=>{switch(e.direction){case"up":return`Increased ${e.percentage} ${e.reference}`;case"down":return`Decreased ${e.percentage} ${e.reference}`;case"flat":return`No change ${e.reference}`}},xn=e=>e.filter(t=>t!==null),qf=800,As=400,Qf={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}}},Zf=e=>Math.max(1,(e-As)/(qf-As)+1),Jf=(e,t)=>{const n=Zf(t),r=Qf[e];return{strokeWidth:Math.min(r.strokeWidth.targetValue,r.strokeWidth.minValue*n),arrowheadLength:Math.min(r.arrowheadLength.targetValue,r.arrowheadLength.minValue*n)}},ht=Math.PI/4,Vn=1.5,eh=({startX:e,startY:t,endX:n,endY:r})=>`M ${e} ${t} L ${n} ${r}`,Ts=(e,t,n)=>{if(n<=0)return"";const{startX:r,startY:s,endX:a,endY:o}=t,i=e==="start"?r:a,c=e==="start"?s:o,l=e==="start"?Math.atan2(s-o,r-a):Math.atan2(o-s,a-r),u=i-n*Math.cos(l-ht),d=c-n*Math.sin(l-ht),p=i-n*Math.cos(l+ht),m=c-n*Math.sin(l+ht);return`M ${i} ${c} L ${u} ${d} M ${i} ${c} L ${p} ${m}`},th=(e,t)=>e==="solid"?null:`${t*Vn} ${t*Vn*2}`,nh=(e,t)=>t?e*Vn:0,rh=64,sh=({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:a}=Jf(e.thickness,t),o=Math.hypot(r.endX-r.startX,r.endY-r.startY),i=ah(a,o),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:eh(r),startArrowheadPath:c?Ts("start",r,i):"",endArrowheadPath:l?Ts("end",r,i):"",color:e.color,strokeWidth:s,dashArray:th(e.lineStyle,s),hasStickerStyle:e.hasStickerStyle,startX:r.startX,startY:r.startY,endX:r.endX,endY:r.endY,dashOffset:nh(s,c),arrowheadExtent:d}},ah=(e,t)=>Math.min(e,t*e/rh),fo=2,ur=e=>e==="catmull-rom"?_e.curveCatmullRom:_e.curveLinear,oh=e=>{switch(e){case"dashed":return"8 4";case"dotted":return"2 2";case"solid":return}},ih=(e,t)=>t.lineWidth!=="auto"?t.lineWidth:Ns(e)??fo,ch=(e,t)=>{const n=ur(t.interpolate),r=_e.area().curve(n),s=_e.line().curve(n);if(e.mainAxis==="y"){const a=c=>we(C(c)??0),o=c=>me(c)??0,i=c=>ae(c)??$(c)??0;r.y(a).x0(o).x1(i),s.y(a).x(i)}else{const a=c=>$(c)??0,o=c=>we(te(c)??0),i=c=>we(H(c)??C(c)??0);r.x(a).y0(o).y1(i),s.x(a).y(i)}if(t.missingValues==="gap"){const a=o=>$(o)!==null&&C(o)!==null;r.defined(a),s.defined(a)}return{lineGenerator:s,areaGenerator:r}},lh=(e,t)=>t!=="connect"?e:e.filter(n=>$(n)!==null&&C(n)!==null),uh=(e,t)=>{const n=me(t),r=ae(t),s=te(t),a=H(t)??C(t);if(n===null||r===null||s===null||a===null)return null;if(e==="x"){let c=1-a,l=a-s;return l<0&&(c+=l,l=-l),{x:n,y:c,width:r-n,height:l}}let o=n,i=r-n;return i<0&&(o+=i,i=-i),{x:o,y:1-a,width:i,height:a-s}},dh=e=>{const t=_e.line().x(n=>$(n)??0).y(n=>we(C(n)??0)).curve(ur(e.interpolate));return e.missingValues==="gap"&&t.defined(n=>$(n)!==null&&C(n)!==null),t},ph=(e,t)=>t!=="connect"?e:e.filter(n=>$(n)!==null&&C(n)!==null),mh=_e.arc(),fh=e=>mh(e),hh=(e,t,n)=>{const r=Ft(e,t);return s=>{const a=Le(s)??"default",o=r(s);return`${n}-${a}${o!==null&&o!==""?`-${o}`:""}`}},yh=()=>(e,t)=>Ct(e)??`default-${t}`;function ho(e,t){return dr(e.buckets,t,n=>n.main)}function gh(e,t){return dr(e.bands,t,n=>n.bandCenter)}function bh(e,t){return dr(e.columns,t,n=>n.mainMid)}function dr(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 a=e[r-1],o=e[r];return a?o&&Math.abs(n(o)-t)<Math.abs(n(a)-t)?o:a:o??null}function pr(e,t,n){return Math.hypot(e*n,t)}function vh(e,t,n,r){if(e.points.length===0)return null;const s=e.delaunay;if(!s)return null;const a=s.find(t.x*n,t.y,r??void 0),o=e.points[a];return o?{hit:{layerId:e.layerId,pointIndex:o.pointIndex,x:o.x,y:o.y,observation:o.observation},index:e,distance:pr(o.x-t.x,o.y-t.y,n)}:null}function xh(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 Sh(e,t){return{group:wh(e),related:Lh(e,t)}}function wh(e){switch(e.kind){case"buckets":{const t=e.match.index;return X(t.position)?Ah(t,e.match):[]}case"rects":{const t=e.match.index;return X(t.position)?Th(t,e.match):Mh(t,e.match)}case"points":case"arcs":return[]}}function Ah(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 Th(e,t){const n=[];for(const r of t.column.rects)r.pointIndex!==t.hit.pointIndex&&n.push(mr(e,r));return n}function Mh(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 a of s.rects)a.pointIndex!==t.hit.pointIndex&&r.push(mr(e,a));return r}function Lh(e,t){const n=new Map;if(e.kind==="arcs")return n;for(const r of t){if(r.layerId!==e.match.index.layerId){Eh(n,r,e.match.hit);continue}e.kind==="buckets"&&(X(r.position)||r.kind==="buckets"&&Vh(n,r,e.match))}return n}function Vh(e,t,n){for(const r of n.bucket.entries){if(r.pointIndex===n.hit.pointIndex)continue;wt(e,t.layerId).push({layerId:t.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation})}}function Eh(e,t,n){switch(t.kind){case"buckets":{const r=ho(t,Fe(t.mainAxis,n));if(!r)return;const s=wt(e,t.layerId);for(const a of r.entries)s.push({layerId:t.layerId,pointIndex:a.pointIndex,x:a.x,y:a.y,observation:a.observation});return}case"rects":{const r=gh(t,Fe(t.mainAxis,n));if(!r)return;const s=wt(e,t.layerId);for(const a of r.columns)for(const o of a.rects)s.push(mr(t,o));return}case"points":{const r=xh(t,n);if(!r)return;wt(e,t.layerId).push({layerId:t.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation});return}case"arcs":return;case"noop":return}}function wt(e,t){let n=e.get(t);return n||(n=[],e.set(t,n)),n}function mr(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 Ih(e){const t=kh(e);return{kind:"arcs",layerId:e.id,geom:e.geom,position:e.position,arcs:t}}function kh(e){const t=e.data;if(t.size()===0)return[];const n=[f.xMin,f.xMax,f.yMin,f.yMax];for(const l of n)if(!t.hasVariable(l))return[];const r=t.getValues(f.xMin,{type:"numeric"}),s=t.getValues(f.xMax,{type:"numeric"}),a=t.getValues(f.yMin,{type:"numeric"}),o=t.getValues(f.yMax,{type:"numeric"}),i=[];let c=0;for(const l of t){const u=r[c],d=s[c],p=a[c],m=o[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 Ch=1e-9;function Dh(e,t){const n=_h(e,t);n.sort((s,a)=>s.main-a.main);const r=[];for(const s of n){const a=r[r.length-1];a&&Math.abs(a.main-s.main)<=Ch?a.entries.push(s.entry):r.push({main:s.main,entries:[s.entry]})}return{kind:"buckets",layerId:e.id,geom:e.geom,position:e.position,mainAxis:t,buckets:r}}function _h(e,t){const n=e.data;if(n.size()===0)return[];const s=n.hasVariable(f.x),a=n.hasVariable(f.y);if(!s||!a)return[];const o=n.getValues(f.x,{type:"numeric"}),i=n.getValues(f.y,{type:"numeric"}),c=t==="y",l=c?f.xMin:f.yMin,u=c?f.xMax:f.yMax,d=X(e.position),p=d?n.getValues(l,{type:"numeric"}):null,m=d?n.getValues(u,{type:"numeric"}):null,y=n.hasVariable(z.group)?n.getValues(z.group,{type:"categorical"}):null,g=[];let b=0;for(const x of n){const S=o[b],w=i[b];if(!h(S)||!h(w)){b+=1;continue}const k=y?.[b]??null,W=c?w:S;if(d){const q=p?.[b],Be=m?.[b];if(!h(q)||!h(Be)){b+=1;continue}const T=c?Be:S,ne=c?w:Be;g.push({main:W,entry:{isStacked:d,pointIndex:b,x:T,y:ne,stackMin:q,stackMax:Be,groupKey:k,observation:x}})}else g.push({main:W,entry:{isStacked:d,pointIndex:b,x:S,y:w,groupKey:k,observation:x}});b+=1}return g}function Fh(e){return{kind:"noop",layerId:e.id,geom:e.geom,position:e.position}}function Rh(e,t){const n={kind:"points",layerId:e.id,geom:e.geom,position:e.position,points:Nh(e),delaunay:null,delaunayAspectRatio:null};return yo(n,t),n}function yo(e,t){e.delaunay&&e.delaunayAspectRatio===t||(e.delaunay=Mo.Delaunay.from(e.points,n=>n.x*t,n=>n.y),e.delaunayAspectRatio=t)}function Nh(e){const t=e.data;if(t.size()===0)return[];if(!t.hasVariable(f.x)||!t.hasVariable(f.y))return[];const n=t.getValues(f.x,{type:"numeric"}),r=t.getValues(f.y,{type:"numeric"}),s=[];let a=0;for(const o of t){const i=n[a],c=r[a];a+=1,!(!h(i)||!h(c))&&s.push({pointIndex:s.length,x:i,y:c,observation:o})}return s}const Ph=1e6;function Oh(e,t){const n=Bh(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 a=[...r.values()].sort((i,c)=>i.mainMid-c.mainMid),o=[...s.values()].sort((i,c)=>i.bandCenter-c.bandCenter);for(const i of o)i.columns.sort((c,l)=>c.mainMid-l.mainMid);return{kind:"rects",layerId:e.id,geom:e.geom,position:e.position,mainAxis:t,columns:a,bands:o}}function Ms(e){return String(Math.round(e*Ph))}function Bh(e,t){const n=e.data;if(n.size()===0)return[];if(!(n.hasVariable(f.xMin)&&n.hasVariable(f.xMax)&&n.hasVariable(f.yMin)&&n.hasVariable(f.yMax)))return[];const s=n.getValues(f.xMin,{type:"numeric"}),a=n.getValues(f.xMax,{type:"numeric"}),o=n.getValues(f.yMin,{type:"numeric"}),i=n.getValues(f.yMax,{type:"numeric"}),c=t==="y",l=c?f.y:f.x,u=n.hasVariable(l)?n.getValues(l,{type:"numeric"}):null,d=n.hasVariable(z.group)?n.getValues(z.group,{type:"categorical"}):null,p=[];let m=0;for(const y of n){const g=s[m],b=a[m],x=o[m],S=i[m];if(!h(g)||!h(b)||!h(x)||!h(S)){m++;continue}const w=c?(x+S)/2:(g+b)/2,k=u?.[m]??w;p.push({mainMid:w,bandCenter:k,entry:{pointIndex:m,xMin:g,xMax:b,yMin:x,yMax:S,segmentKey:d?.[m]??null,observation:y}}),m++}return p}function Ls(e,t,n){if(t.type==="polar")return Ih(e);switch(e.geom){case"point":return Rh(e,n);case"line":case"area":return Dh(e,t.mainAxis);case"bar":return Oh(e,t.mainAxis);case"rule":return Fh(e);default:{const r=e.geom;throw new Error(`buildLayerIndex: unhandled geom ${String(r)}`)}}}const J=Math.PI*2,$h=1e-9;function Gh(e,t,n){if(e.arcs.length===0)return null;const{angle:r,radius:s}=zh(t,n);for(const a of e.arcs)if(!(s<a.innerRadius||s>a.outerRadius)&&Wh(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 zh(e,t){const n=e.x-.5,r=e.y-.5,s=t>=1?n*2*t:n*2,a=t>=1?r*2:r*2/t,o=Math.hypot(s,a);return{angle:(Math.atan2(s,a)%J+J)%J,radius:o}}function Wh(e,t){const n=t.endAngle-t.startAngle;if(Math.abs(n)>=J-$h)return!0;const r=(n%J+J)%J;return((e-t.startAngle)%J+J)%J<=r}function Yh(e,t,n){if(e.buckets.length===0)return null;const{main:r,cross:s}=$m(e.mainAxis,t),a=ho(e,r),o=a?.entries??[];if(!a||!In(o))return null;const i=Xh(o,s,e.mainAxis);return{hit:{layerId:e.layerId,pointIndex:i.pointIndex,x:i.x,y:i.y,observation:i.observation},index:e,bucket:a,distance:pr(i.x-t.x,i.y-t.y,n)}}function Hh(e,t,n){if(e.columns.length===0)return null;const r=Fe(e.mainAxis,t),s=bh(e,r),a=s?.rects??[];if(!s||!In(a))return null;const o=X(e.position)?Uh(a,t,e.mainAxis):Kh(a,t,n);return{hit:{layerId:e.layerId,pointIndex:o.pointIndex,x:(o.xMin+o.xMax)/2,y:(o.yMin+o.yMax)/2,observation:o.observation},index:e,column:s,distance:go(o,t,n)}}function Uh(e,t,n){const r=Gt(n,t);return fr(e,a=>jh(a,n,r),{shortCircuitOnZero:!0})}function Kh(e,t,n){return fr(e,s=>go(s,t,n))}function Xh(e,t,n){return fr(e,s=>Math.abs(Gt(n,s)-t))}function fr(e,t,{shortCircuitOnZero:n=!1}={}){let r=e[0],s=t(r);if(n&&s===0)return r;for(let a=1;a<e.length;a+=1){const o=e[a];if(o===void 0)continue;const i=t(o);if(n&&i===0)return o;i<s&&(r=o,s=i)}return r}function go(e,t,n){const r=En(t.x,e.xMin,e.xMax),s=En(t.y,e.yMin,e.yMax);return pr(r,s,n)}function jh(e,t,n){const r=t==="x"?e.yMin:e.xMin,s=t==="x"?e.yMax:e.xMax;return En(n,r,s)}function En(e,t,n){return e<t?t-e:e>n?e-n:0}const qh=.05;function Qh({layers:e,cursor:t,aspectRatio:n,warmStarts:r}){const s={match:null,distance:Number.POSITIVE_INFINITY},a={match:null,distance:Number.POSITIVE_INFINITY};for(const o of e){if(o.kind==="arcs"){const c=Gh(o,t,n);return c?{kind:"arcs",match:c}:null}const i=Jh({layer:o,cursor:t,aspectRatio:n,warmStarts:r});if(i){if(i.kind==="rects"){i.match.distance<s.distance&&(s.match=i,s.distance=i.match.distance);continue}i.match.distance<a.distance&&(a.match=i,a.distance=i.match.distance)}}return Zh({rect:s,continuous:a})}function Zh({rect:e,continuous:t}){return e.match&&t.match?t.distance<=e.distance+qh?t.match:e.match:e.match??t.match}function Jh({layer:e,cursor:t,aspectRatio:n,warmStarts:r}){switch(e.kind){case"buckets":{const s=Yh(e,t,n);return s?{kind:"buckets",match:s}:null}case"rects":{const s=Hh(e,t,n);return s?{kind:"rects",match:s}:null}case"points":{const s=r.get(e.layerId)??null,a=vh(e,t,n,s);return a?{kind:"points",match:a}:null}case"noop":return null}}const Ue={primary:null,group:[],related:new Map},ey=1;class ty{constructor({layers:t,coordSystem:n}){this.layerIndexes=[],this.layerRefs=[],this.aspectRatio=ey,this.warmStarts=new Map,this.cachedState=Ue,this.cachedKey=null,this.nonInteractiveLayerIds=new Set,this.layerIndexes=t.map(r=>Ls(r,n,this.aspectRatio)),this.layerRefs=t.map(r=>Vs(r,n)),this.nonInteractiveLayerIds=Es(t)}update({layers:t,coordSystem:n}){const r=new Map;for(let o=0;o<this.layerIndexes.length;o+=1){const i=this.layerIndexes[o],c=this.layerRefs[o];!i||!c||r.set(i.layerId,{index:i,ref:c})}const s=[],a=[];for(const o of t){const i=r.get(o.id),c=Vs(o,n);if(i!==void 0&&ny(i.ref,c)){s.push(i.index),a.push(i.ref);continue}this.warmStarts.delete(o.id),s.push(Ls(o,n,this.aspectRatio)),a.push(c)}for(const o of this.warmStarts.keys())t.some(i=>i.id===o)||this.warmStarts.delete(o);this.layerIndexes=s,this.layerRefs=a,this.nonInteractiveLayerIds=Es(t),this.invalidateCache()}setViewport(t){this.aspectRatio=t.width/t.height;for(const n of this.layerIndexes)n.kind==="points"&&yo(n,this.aspectRatio)}query(t){if(this.layerIndexes.length===0)return Ue;const n=this.nonInteractiveLayerIds.size===0?this.layerIndexes:this.layerIndexes.filter(c=>!this.nonInteractiveLayerIds.has(c.layerId)),r=Qh({layers:n,aspectRatio:this.aspectRatio,warmStarts:this.warmStarts,cursor:t});if(!r)return this.invalidateCache(),Ue;const s=r.match.hit;this.warmStarts.set(s.layerId,s.pointIndex);const a=`${s.layerId}:${s.pointIndex}`;if(this.cachedKey===a)return this.cachedState;const{group:o,related:i}=Sh(r,n);return this.cachedKey=a,this.cachedState={primary:s,group:o,related:i},this.cachedState}invalidateCache(){this.cachedKey=null,this.cachedState=Ue}}function Vs(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 ny(e,t){return e.data===t.data&&e.geom===t.geom&&e.position===t.position&&e.coord===t.coord}function ry(e,t){const n=Fe(e.mainAxis,t);if(e.mainAxis==="y"){const s=be(we(n));return{x1:0,x2:"100%",y1:s,y2:s}}const r=be(n);return{x1:r,x2:r,y1:0,y2:"100%"}}function sy(e,t,n){const r=e.mainAxis==="y"?C(n.observation):$(n.observation);if(r===null)return null;const s=e.mainAxis==="y"?vo(n):bo(n),o=(t.x?.kind==="position"?t.x:null)?.bandwidth??s;if(o===null||o<=0)return null;const i=o/2;if(e.mainAxis==="y"){const u=be(we(r+i)),d=be(o);return{x:0,y:u,width:"100%",height:d}}const c=be(r-i),l=be(o);return{x:c,y:0,width:l,height:"100%"}}function bo(e){const t=me(e.observation),n=ae(e.observation);return t===null||n===null?null:n-t}function vo(e){const t=te(e.observation),n=H(e.observation);return t===null||n===null?null:n-t}const ay=/^(?:https?:|mailto:)/i,oy=e=>{if(typeof e!="string")return!1;const t=e.replace(/^[\x00-\x20]+/,"");return t.length===0?!1:ay.test(t)},iy=({locale:e,intlOptions:t})=>N(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"long",year:"numeric",weekday:"long",...O,...t}).format(n)),cy=({locale:e,intlOptions:t})=>N(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,...O,...t}).format(n)}),Vt=e=>{const{valueFormat:t}=e;switch(t.type){case"currency":return Ga(e);case"date":return iy(e);case"datetime":return cy(e);case"day_month":return Ya(e);case"decimal":return jn(e);case"duration":return qn();case"integer":return za(e);case"month":return Ha(e);case"month_year":return Jn(e);case"percentage":return Wa(e);case"quarter":return er();case"text":return Xn();case"time":return Xa(e);case"weekly_date_range":return Ua(e);case"weekly_date_range_with_year":return Ka(e);case"year":return tr(e);case"lookup":return Vt({...e,valueFormat:t.fallback});default:{const n=t;throw new Error(`Unhandled value format: ${n.type}`)}}},ly=({layers:e,coordSystem:t,scales:n,guides:r,numberFormat:s,parsingLocale:a,hover:o,formattingLocale:i})=>{const{primary:c}=o;if(c===null)return null;const l=i??a;return{header:uy({layers:e,coordSystem:t,guides:r,primary:c,locale:l,numberFormat:s}),rows:dy({layers:e,coordSystem:t,scales:n,guides:r,hover:o,locale:l,numberFormat:s})}};function uy(e){if(e.coordSystem.type!=="cartesian")return null;const t=zt(e.guides,"x");if(!t)return null;const n=e.layers.find(o=>o.id===e.primary.layerId);if(!n)return null;const r=v(n.mapping.x);if(!h(r))return null;const s=e.primary.observation[r];return h(s)?Vt({valueFormat:t.valueFormat,locale:e.locale,numberFormat:e.numberFormat})(s):null}function dy(e){const t=[],n=e.scales.color??null,r=fy({guides:e.guides,locale:e.locale,numberFormat:e.numberFormat});for(const s of e.layers){const a=py(s,e.hover);if(a.length===0)continue;const o=ya(s.data,s.mapping),i=my(a,s,n,o),c=lr({layer:s,numberFormat:e.numberFormat,locale:e.locale}),l=hy(e.guides,s),u=Nt(s),d=s.mapping.color!==void 0,p=Tt(s.geom,e.coordSystem);for(const m of i){const y=d?o(m.observation):null,g=Ct(m.observation)??null,b=Ps(m.observation),x=d&&y!==null?r(y):l,S=u(m.observation),w=S===null?"":c(S,m.observation);t.push({swatchColor:g,swatchShape:p,swatchLineType:b,label:x,value:w,isPrimary:m===e.hover.primary,key:`${m.layerId}:${m.pointIndex}`})}}return t}function py(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 my(e,t,n,r){if(n===null||t.mapping.color===void 0)return e;const s=new Map;return n.domain.forEach((a,o)=>{s.set(E(a),o)}),e.map((a,o)=>{const i=r(a.observation),c=i===null?null:E(i),l=c===null?Number.POSITIVE_INFINITY:s.get(c)??Number.POSITIVE_INFINITY;return{hit:a,originalIndex:o,rank:l}}).sort((a,o)=>a.rank===o.rank?a.originalIndex-o.originalIndex:a.rank-o.rank).map(a=>a.hit)}function fy({guides:e,locale:t,numberFormat:n}){const r=new Map(e.colorGroups.map(a=>[E(a.value),{label:a.label,format:Vt({valueFormat:a.valueFormat,locale:t,numberFormat:n})}])),s=Vt({valueFormat:{type:"text"},locale:t,numberFormat:n});return a=>{const o=r.get(E(a));return o===void 0?s(a):o.label??o.format(a)}}function hy(e,t){const n=Oe(t.yScaleType);return zt(e,n)?.label??""}const yy={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 gy(e,t={}){return{type:"highlight",id:t.id,predicate:e,scope:t.scope,layerIndex:t.layerIndex}}function by(...e){let t={},n;const[r,...s]=e;h(r)&&!xy(r)?(t=r,n=s):n=e;const a={mapping:t,layers:[],scales:[],transforms:[],highlights:[],config:{}};return n.reduce((o,i)=>xo(o,i),a)}function vy(e,...t){return t.reduce((n,r)=>xo(n,r),e)}function xy(e){return typeof e=="object"&&e!==null&&"type"in e}function xo(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]};default:{const n=t;throw new Error(`Unknown spec item type: ${n.type}`)}}}function Sy(e){return{mapping:e.mapping,layers:e.layers,scales:e.scales.map(Ay),transforms:e.transforms,highlights:e.highlights.map(t=>wy(t,e.layers)),coords:e.coords,config:e.config}}function wy(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 Ay(e){return e.scaleType==="palette"?Ty(e):e}function Ty(e){return{...e,palette:My(e.palette),overrides:Ly(e.overrides)}}function My(e){return e.type==="custom"?{type:"custom",id:e.id}:e}function Ly(e){if(!e)return;const t={};for(const[n,r]of Object.entries(e))t[Number(n)]={hex:r};return t}function L(e){return{id:e.id??crypto.randomUUID(),timestamp:e.timestamp??Date.now(),description:e.description,author:e.author??"unknown"}}class hr{constructor(t,n={}){this.type="set-axis-label",this.params=t,this.metadata=L({...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,a=R(t,{config:{axes:{[n]:{label:r}}}}),o=new hr({axis:n,label:s},this.metadata);return{spec:a,revert:o}}}const Vy={type:"set-axis-label",deserialize:(e,t)=>new hr(e,t)};class yr{constructor(t,n={}){this.type="set-axis-label-mode",this.params=t,this.metadata=L({...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,a=R(t,{config:{axes:{[n]:{ticks:{mode:r}}}}}),o=new yr({axis:n,labelMode:s},this.metadata);return{spec:a,revert:o}}}const Ey={type:"set-axis-label-mode",deserialize:(e,t)=>new yr(e,t)};class Wt{constructor(t,n={}){this.type="set-axis-position",this.params=t,this.metadata=L({...n,description:`Set ${t.axis} axis position to ${t.position}`})}apply(t){const{axis:n,position:r}=this.params,s=R(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},o=new Wt(a,this.metadata);return{spec:s,revert:o}}}const Iy={type:"set-axis-position",deserialize:(e,t)=>new Wt(e,t)};class gr{constructor(t,n={}){this.type="set-axis-ticks-visibility",this.params=t,this.metadata=L({...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,a=R(t,{config:{axes:{[n]:{ticks:{isVisible:r}}}}}),o=new gr({axis:n,isVisible:s},this.metadata);return{spec:a,revert:o}}}const ky={type:"set-axis-ticks-visibility",deserialize:(e,t)=>new gr(e,t)};class br{constructor(t,n={}){this.type="set-axis-visibility",this.params=t,this.metadata=L({...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,a=R(t,{config:{axes:{[n]:{isVisible:r}}}}),o=new br({axis:n,isVisible:s},this.metadata);return{spec:a,revert:o}}}const Cy={type:"set-axis-visibility",deserialize:(e,t)=>new br(e,t)};class Yt{constructor(t,n={}){this.type="set-content-caption",this.params=t,this.metadata=L({...n,description:"Set chart caption"})}apply(t){const n=t.config.content.caption;if(n===this.params.caption)return null;const r=R(t,{config:{content:{caption:this.params.caption}}}),s=new Yt({caption:n},this.metadata);return{spec:r,revert:s}}}const Dy={type:"set-content-caption",deserialize:(e,t)=>new Yt(e,t)};class Ht{constructor(t,n={}){this.type="set-content-subtitle",this.params=t,this.metadata=L({...n,description:"Set chart subtitle"})}apply(t){const n=t.config.content.subtitle;if(n===this.params.subtitle)return null;const r=R(t,{config:{content:{subtitle:this.params.subtitle}}}),s=new Ht({subtitle:n},this.metadata);return{spec:r,revert:s}}}const _y={type:"set-content-subtitle",deserialize:(e,t)=>new Ht(e,t)};class Ut{constructor(t,n={}){this.type="set-content-title",this.params=t,this.metadata=L({...n,description:"Set chart title"})}apply(t){const n=t.config.content.title;if(n===this.params.title)return null;const r=R(t,{config:{content:{title:this.params.title}}}),s=new Ut({title:n},this.metadata);return{spec:r,revert:s}}}const Fy={type:"set-content-title",deserialize:(e,t)=>new Ut(e,t)};class vr{constructor(t,n={}){this.type="set-grid-visibility",this.params=t,this.metadata=L({...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=R(t,{config:{axes:{x:{grid:{isVisible:this.params.xIsVisible}},y:{grid:{isVisible:this.params.yIsVisible}}}}}),a=new vr({xIsVisible:n,yIsVisible:r},this.metadata);return{spec:s,revert:a}}}const Ry={type:"set-grid-visibility",deserialize:(e,t)=>new vr(e,t)};class xr{constructor(t,n={}){this.type="set-headline-compare-with",this.params=t,this.metadata=L({...n,description:`Set headline compare with to ${t.compareWith}`})}apply(t){const n=t.config.headline.compareWith,r=R(t,{config:{headline:{compareWith:this.params.compareWith}}}),s=new xr({compareWith:n},this.metadata);return{spec:r,revert:s}}}const Ny={type:"set-headline-compare-with",deserialize:(e,t)=>new xr(e,t)};class Sr{constructor(t,n={}){this.type="set-headline-position",this.params=t,this.metadata=L({...n,description:`Set headline position to ${t.position}`})}apply(t){const n=t.config.headline.position,r=R(t,{config:{headline:{position:this.params.position}}}),s=new Sr({position:n},this.metadata);return{spec:r,revert:s}}}const Py={type:"set-headline-position",deserialize:(e,t)=>new Sr(e,t)};class Kt{constructor(t,n={}){this.type="set-headline-show",this.params=t,this.metadata=L({...n,description:`Set headline show to ${t.show}`})}apply(t){const n=t.config.headline.show,r=R(t,{config:{headline:{show:this.params.show}}}),s=new Kt({show:n},this.metadata);return{spec:r,revert:s}}}const Oy={type:"set-headline-show",deserialize:(e,t)=>new Kt(e,t)};class wr{constructor(t,n={}){this.type="set-headline-size",this.params=t,this.metadata=L({...n,description:`Set headline size to ${t.size}`})}apply(t){const n=t.config.headline.size,r=R(t,{config:{headline:{size:this.params.size}}}),s=new wr({size:n},this.metadata);return{spec:r,revert:s}}}const By={type:"set-headline-size",deserialize:(e,t)=>new wr(e,t)};class Ar{constructor(t,n={}){this.type="set-legend-position",this.params=t,this.metadata=L({...n,description:`Set legend position to ${t.position}`})}apply(t){const n=t.config.legend.position,r=R(t,{config:{legend:{position:this.params.position}}}),s=new Ar({position:n},this.metadata);return{spec:r,revert:s}}}const $y={type:"set-legend-position",deserialize:(e,t)=>new Ar(e,t)};class Tr{constructor(t,n={}){this.type="set-number-format-abbreviation",this.params=t,this.metadata=L({...n,description:`Set number format abbreviation to ${t.abbreviation}`})}apply(t){const n=t.config.numberFormat.abbreviation,r=R(t,{config:{numberFormat:{abbreviation:this.params.abbreviation}}}),s=new Tr({abbreviation:n},this.metadata);return{spec:r,revert:s}}}const Gy={type:"set-number-format-abbreviation",deserialize:(e,t)=>new Tr(e,t)};class Mr{constructor(t,n={}){this.type="set-number-format-decimals",this.params=t,this.metadata=L({...n,description:`Set number format decimals to ${t.decimals}`})}apply(t){const n=t.config.numberFormat.decimals,r=R(t,{config:{numberFormat:{decimals:this.params.decimals}}}),s=new Mr({decimals:n},this.metadata);return{spec:r,revert:s}}}const zy={type:"set-number-format-decimals",deserialize:(e,t)=>new Mr(e,t)};class Lr{constructor(t,n={}){this.type="set-line-interpolation",this.params=t,this.metadata=L({...n,description:`Set line interpolation to ${t.interpolate}`})}apply(t){const n=this.params.layerId?Bt(t.layers,this.params.layerId):at(t.layers,"line","area");if(!Ot(n,"line","area"))return null;const r=n.params.interpolate,s=Un(t,n.id,{...n,params:{...n.params,interpolate:this.params.interpolate}}),a=new Lr({layerId:n.id,interpolate:r},this.metadata);return{spec:s,revert:a}}}const Wy={type:"set-line-interpolation",deserialize:(e,t)=>new Lr(e,t)};class Xt{constructor(t,n={}){this.type="set-line-width",this.params=t,this.metadata=L({...n,description:`Set line width to ${t.lineWidth}`})}apply(t){const n=this.params.layerId?Bt(t.layers,this.params.layerId):at(t.layers,"line","area");if(!Ot(n,"line","area"))return null;const r=n.params.lineWidth,s=Un(t,n.id,{...n,params:{...n.params,lineWidth:this.params.lineWidth}}),a=new Xt({layerId:n.id,lineWidth:r},this.metadata);return{spec:s,revert:a}}}const Yy={type:"set-line-width",deserialize:(e,t)=>new Xt(e,t)};class Vr{constructor(t,n={}){this.type="set-point-size",this.params=t,this.metadata=L({...n,description:`Set point size to ${t.size}`})}apply(t){const n=this.params.layerId?Bt(t.layers,this.params.layerId):at(t.layers,"point");if(!Ot(n,"point"))return null;const r=n.params.size,s=Un(t,n.id,{...n,params:{...n.params,size:this.params.size}}),a=new Vr({layerId:n.id,size:r},this.metadata);return{spec:s,revert:a}}}const Hy={type:"set-point-size",deserialize:(e,t)=>new Vr(e,t)};class Et{constructor(t,n={}){this.type="toggle-line-points",this.params=t,this.metadata=L({...n,description:`${t.showPoints?"Show":"Hide"} line points`})}apply(t){const n=this.params.layerId?Bt(t.layers,this.params.layerId):at(t.layers,"line");return Ot(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??Da(t.mapping,t.coords.coordType,_.point({aes:{...n.mapping},interactive:!1})),s={...t,layers:[...t.layers,r]},a=new Et({layerId:n.id,showPoints:!1},this.metadata);return{spec:s,revert:a}}removePointLayer(t,n){const r=this.findAssociatedPointLayer(t,n);if(!r)return null;const s=Qd(t,r.id),a=new Et({layerId:n.id,showPoints:!0,removedLayer:r},this.metadata);return{spec:s,revert:a}}findAssociatedPointLayer(t,n){return t.layers.find(r=>r.geom==="point"&&Lo(r.mapping,n.mapping))}}const Uy={type:"toggle-line-points",deserialize:(e,t)=>new Et(e,t)};function jt(e,t){return e.scales.find(n=>n.scaledAesthetic===t)}function qt(e,t,n){const r=e.scales.map(s=>s.scaledAesthetic===t?n:s);return{...e,scales:r}}function Qt(e){const t=e.replace(/([A-Z])/g," $1").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}class Zt{constructor(t,n={}){this.type="set-scale-domain",this.params=t,this.metadata=L({...n,description:`Set ${Qt(t.scaledAesthetic)} scale domain`})}apply(t){const n=jt(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}},a=qt(t,this.params.scaledAesthetic,s),o={scaledAesthetic:this.params.scaledAesthetic};this.params.domainMin!==void 0&&(o.domainMin=r.min),this.params.domainMax!==void 0&&(o.domainMax=r.max);const i=new Zt(o,this.metadata);return{spec:a,revert:i}}}const Ky={type:"set-scale-domain",deserialize:(e,t)=>new Zt(e,t)};class Er{constructor(t,n={}){this.type="set-scale-palette",this.params=t,this.metadata=L({...n,description:`Set ${Qt(t.scaledAesthetic)} palette`})}apply(t){const n=jt(t,this.params.scaledAesthetic);if(n?.scaleType!=="palette")return null;const r=qt(t,this.params.scaledAesthetic,{...n,scaledAesthetic:this.params.scaledAesthetic,palette:this.params.palette}),s=new Er({scaledAesthetic:this.params.scaledAesthetic,palette:n.palette},this.metadata);return{spec:r,revert:s}}}const Xy={type:"set-scale-palette",deserialize:(e,t)=>new Er(e,t)};class Ir{constructor(t,n={}){this.type="set-scale-reverse",this.params=t,this.metadata=L({...n,description:`Set ${Qt(t.scaledAesthetic)} scale reverse to ${t.reverse}`})}apply(t){const n=jt(t,this.params.scaledAesthetic);if(!n||n.scaleType!=="continuous")return null;const r=n.reverse,s=qt(t,this.params.scaledAesthetic,{...n,reverse:this.params.reverse}),a=new Ir({scaledAesthetic:this.params.scaledAesthetic,reverse:r},this.metadata);return{spec:s,revert:a}}}const jy={type:"set-scale-reverse",deserialize:(e,t)=>new Ir(e,t)};class kr{constructor(t,n={}){this.type="set-scale-transform",this.params=t,this.metadata=L({...n,description:`Set ${Qt(t.scaledAesthetic)} scale transform to ${t.transform}`})}apply(t){const n=jt(t,this.params.scaledAesthetic);if(!n||n.scaleType!=="continuous")return null;const r=n.transform,s=qt(t,this.params.scaledAesthetic,{...n,transform:this.params.transform}),a=new kr({scaledAesthetic:this.params.scaledAesthetic,transform:r},this.metadata);return{spec:s,revert:a}}}const qy={type:"set-scale-transform",deserialize:(e,t)=>new kr(e,t)};class So{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 M=new So;M.register(Wy);M.register(Yy);M.register(Hy);M.register(Uy);M.register(Ky);M.register(Xy);M.register(jy);M.register(qy);M.register(Vy);M.register(Ey);M.register(Iy);M.register(ky);M.register(Cy);M.register(Dy);M.register(_y);M.register(Fy);M.register(Ry);M.register(Ny);M.register(Py);M.register(Oy);M.register(By);M.register($y);M.register(Gy);M.register(zy);class Qy{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 Cr=500,Dr="normal",_r={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},Zy=e=>{const t=e.style??Dr,n=e.weight??Cr,r=e.family.includes(",")?e.family:`'${e.family}'`;return`${t} ${n} ${e.size}px ${r}`},Jy=e=>typeof e=="string"?e:wo(e),wo=e=>e.text!==void 0?e.text:e.content?e.content.map(wo).join(""):"",Fr=e=>typeof e!="string"?e??Cr:_r[e],eg="\0";class tg{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 a=this.inner.measureText(t,n);return this.cache.set(r,a),a}getCacheKey(t,n){return[n.family,n.size,Fr(n.weight),n.style??Dr,t].join(eg)}}const ng={" ":.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},rg=.55,sg=1.05,ag=.84,og=.21;class ig{measureText(t,n){let r=0;for(const i of t)r+=(ng[i]??rg)*n.size;Fr(n.weight)>=_r.semiBold&&(r*=sg);const a=ag*n.size,o=og*n.size;return{width:r,height:a+o,ascent:a,descent:o}}}exports.BORDER_PRESETS=La;exports.BORDER_PRESET_GRADIENTS=yy;exports.COMPILER_STAGE_KEYS=_p;exports.CachedTextMeasurer=tg;exports.CommandRegistry=So;exports.CommandStackManager=Qy;exports.Compiler=Ba;exports.DEFAULT_FONT_STYLE=Dr;exports.DEFAULT_FONT_WEIGHT=Cr;exports.DEFAULT_LINE_WIDTH=fo;exports.DEFAULT_LOCALE=Dt;exports.Dataset=I;exports.GROUP_VARIABLES=z;exports.HEADLINE_SWATCH_GAP=lo;exports.HEADLINE_SWATCH_SIZE=co;exports.HEADLINE_TREND_GAP=mo;exports.HEADLINE_TREND_ICON_SIZE=po;exports.HEADLINE_VALUE_LABEL_GAP=uo;exports.HeuristicTextMeasurer=ig;exports.HoverEngine=ty;exports.LAYOUT_PADDING=or;exports.LayoutCompiler=Nm;exports.MONO_BASES=Sa;exports.NAMED_WEIGHTS=_r;exports.NEON_BASES=wa;exports.POSITION_VARIABLES=f;exports.RESTING_HOVER_STATE=Ue;exports.SetAxisPositionCommand=Wt;exports.SetContentCaptionCommand=Yt;exports.SetContentSubtitleCommand=Ht;exports.SetContentTitleCommand=Ut;exports.SetHeadlineShowCommand=Kt;exports.SetLineWidthCommand=Xt;exports.SetScaleDomainCommand=Zt;exports.SpecResolver=Ra;exports.VISUAL_VARIABLES=pe;exports.buildAverageLineSymbols=Om;exports.buildDataLabelsContent=Tf;exports.buildFontString=Zy;exports.buildLayerYValueFormatter=lr;exports.buildPolarBarArcPath=fh;exports.buildTooltipContent=ly;exports.commandRegistry=M;exports.computeDifferenceArrow=Cf;exports.computeDirectLabelsLayout=_f;exports.computeFreeformArrow=sh;exports.config=Va;exports.convertSpecToInput=Sy;exports.coord=B;exports.createAlphaValueReader=xl;exports.createAreaPathGenerators=ch;exports.createColorValueReader=ya;exports.createCompiler=Fp;exports.createEmptyHighlight=ga;exports.createGroupValueReader=Sl;exports.createHeadlineItemRows=Hf;exports.createLabelValueReader=bl;exports.createLinePathGenerator=dh;exports.createRawValueReader=j;exports.createSegmentYReader=Nt;exports.createSizeValueReader=vl;exports.createSpec=by;exports.createStableKeyGenerator=hh;exports.createStrokeWidthValueReader=wl;exports.createValueFormatter=P;exports.createXValueReader=Ft;exports.createYValueReader=ha;exports.extractPlainText=Jy;exports.findAxisGuide=zt;exports.findLegendForAesthetic=Wf;exports.formatHeadline=Ff;exports.formatLegends=Gf;exports.formatRuleValue=Yf;exports.geom=_;exports.getAlpha=No;exports.getAngleExtent=ao;exports.getBarRectBounds=uh;exports.getColor=Ct;exports.getCrossAxisCoordinate=Gt;exports.getCurve=ur;exports.getDashArray=oh;exports.getDifferenceArrowDimensions=ar;exports.getGroup=Le;exports.getHoverGuideLineProps=ry;exports.getHoverGuideRectProps=sy;exports.getLineType=Ps;exports.getMainAxisCoordinate=Fe;exports.getNumericWeight=Fr;exports.getRadiusExtent=oo;exports.getSize=Rs;exports.getStablePolarBarKeyGenerator=yh;exports.getStrokeWidth=Ns;exports.getX=$;exports.getXMax=ae;exports.getXMin=me;exports.getY=C;exports.getYMax=H;exports.getYMin=te;exports.getYRaw=Fs;exports.highlight=gy;exports.isCartesian=Gm;exports.isCategoricalValueFormat=Ws;exports.isCompilerCachingEnabled=Eo;exports.isCurrencyValueFormat=Cn;exports.isDateWithoutYearValueFormat=Dn;exports.isDefined=h;exports.isGraphConfig=Ta;exports.isLayerOf=Rp;exports.isLookupValueFormat=zs;exports.isNumericValueFormat=kn;exports.isSafeUrl=oy;exports.isStackedPosition=X;exports.isTemporalValueFormat=Pe;exports.mapping=Do;exports.pipe=vy;exports.prefixInternalVariable=A;exports.prepareAreaObservations=lh;exports.prepareLineObservations=ph;exports.readXExtent=bo;exports.readYExtent=vo;exports.resolveHeadlinePlacement=_m;exports.resolveSegmentYSource=Rt;exports.resolveStrokeWidth=ih;exports.resolveYScaleAesthetic=Oe;exports.scale=Se;exports.setCompilerCachingEnabled=Vo;exports.stat=zn;exports.toPercent=be;exports.toViewBoxX=zm;exports.toViewBoxY=we;exports.transform=xe;
|