@graphysdk/viz-engine 0.0.1-plugins.9 → 1.8.1-beta.1786024899180

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 CHANGED
@@ -1,39 +1,23 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("date-fns"),le=require("arquero"),ie=require("lodash-es"),Ye=require("d3-time"),Pa=require("date-fns/differenceInDays"),de=require("d3-scale"),$o=require("lodash-es/merge"),ge=require("d3-regression"),Na=require("humanize-duration"),Oa=require("d3-delaunay"),$a=require("lodash-es/isEqual");typeof window<"u"&&(window.__GRAPHY_SDK__??={},window.__GRAPHY_SDK__.vizEngine="0.0.1-plugins.9");const Fn=e=>e.length>0;function h(e){return e!=null}function Rr(e){if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function N(e,t){return Bo(e,t)}function rn(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 Bo(e,t){let n=!1;const r={...e};for(const[o,s]of Object.entries(t)){const a=e[o];if(Rr(s)&&Rr(a)){const i=Bo(a,s);i!==a&&(r[o]=i,n=!0)}else s!==void 0&&s!==a&&(r[o]=s,n=!0)}return n?r:e}const Se=process.env.NODE_ENV!=="production";function _t(e){return{pipe:t=>{const n=t(e);return _t({...e,...n})},result:()=>e}}let Rt=!0;const Ba=e=>{Rt=e},Ga=()=>Rt,za=()=>{let e=null;const t={hits:0,misses:0};return Object.assign((r,o)=>{if(!Rt)return Se&&(t.misses+=1),o();if(e&&zo(e.args,r))return Se&&(t.hits+=1),e.out;Se&&(t.misses+=1);const s=o();return e={args:r,out:s},s},{stats:t,reset:()=>{e=null}})},Go=()=>{const e=new WeakMap,t={hits:0,misses:0};return Object.assign((r,o,s)=>{if(!Rt)return Se&&(t.misses+=1),s();const a=e.get(r);if(a){for(const c of a)if(zo(c.args,o))return Se&&(t.hits+=1),c.out}Se&&(t.misses+=1);const i=s();return a?a.push({args:o,out:i}):e.set(r,[{args:o,out:i}]),i},{stats:t})},Ua=(...e)=>e.reduce((t,n)=>({hits:t.hits+n.hits,misses:t.misses+n.misses}),{hits:0,misses:0}),zo=(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 me{constructor(){this.memo=Go(),this.singletonKey={}}get stats(){return this.memo.stats}compile(t){return this.memo(this.key(t),this.dependencies(t),()=>this.run(t))}key(t){return this.singletonKey}}function Ya(e){return{type:"mapping",mapping:e}}function Dn(e,t){return e[t]}function v(e){return h(e)?typeof e=="string"?e:"variable"in e?e.variable:null:null}function se(e){if(!(!h(e)||typeof e=="string")&&"value"in e)return e.value}const Uo="\0graphy\0_",A=e=>`${Uo}${e}`,wn={x:A("constantX")},et={count:A("count"),mean:A("mean")},P={group:A("group")},Yo={key:A("key")},g={x:A("x"),y:A("y"),xMin:A("xMin"),xMax:A("xMax"),yMin:A("yMin"),yMax:A("yMax"),yRaw:A("yRaw")},fe={color:A("color"),size:A("size"),alpha:A("alpha"),strokeWidth:A("strokeWidth"),lineType:A("lineType")},ht={y:A("ruleY"),x:A("ruleX")};({...P,...g,...fe});const Wa=new Set(Object.values(et)),Ha=e=>e.startsWith(Uo),Ka=e=>Wa.has(e),_e=e=>e[P.group],Xa=e=>{const{coordinate:t,coordSystem:n}=e;return"observation"in t?ja(e):n.type!=="cartesian"?null:"unit"in t?{x:t.unit.x,y:t.unit.y,mode:"unit"}:qa(t.data,e)},ja=({coordinate:e,layers:t,coordSystem:n,geomCompiler:r})=>{if(!("observation"in e))return null;const o=e.observation;for(const s of t){if(o.layerId!==void 0&&s.id!==o.layerId)continue;const a=v(s.mapping.x);if(a!==null)for(const i of s.data){if(i[a]!==o.anchorValue||_e(i)!==o.groupValue)continue;const c=r.resolveAnchorPosition(s.geom,i,n);if(c!==null)return{x:c.x,y:1-c.y,mode:"observation",observation:i}}}return null},qa=(e,{coordSystem:t,scales:n})=>{const r=Pr(n,"x"),o=Pr(n,"y");if(r===null||o===null)return null;const s=r.map(e.x),a=o.map(e.y);if(!Number.isFinite(s)||!Number.isFinite(a))return null;const i=t.type==="cartesian"&&t.mainAxis==="y";return{x:i?a:s,y:1-(i?s:a),mode:"data"}},Pr=(e,t)=>{const n=e[t];return n!==void 0&&n.kind==="position"?n:null},G=e=>e instanceof Date&&k.isValid(e),Qa=e=>G(e)||e===null,at=e=>typeof e=="string",F=e=>typeof e=="number"&&!Number.isNaN(e)&&Number.isFinite(e);function _n(e){return e[fe.color]}function Za(e){return e[fe.alpha]}function Wo(e){return e[fe.size]}function Ja(e){return e[fe.strokeWidth]}function Ho(e){return e[fe.lineType]??"solid"}const An=(e,t,n,r)=>{for(const o of t){if(e.layerId!==void 0&&o.id!==e.layerId)continue;const s=v(o.mapping.x);if(s===null)continue;const a=v(o.mapping.y);for(const i of o.data){if(i[s]!==e.anchorValue||_e(i)!==e.groupValue)continue;const c=r.resolveAnchorPosition(o.geom,i,n);if(c===null)continue;const l=a!==null?i[a]??null:null;if(F(l))return{...c,measurementValue:l,color:_n(i)}}}return null};class ei extends me{constructor(t){super(),this.geomCompiler=t}dependencies(t){return[t.annotations,t.layers,t.coordSystem,t.scales.x,t.scales.y]}run(t){const{geomCompiler:n}=this;return{differenceArrows:ni(t,n),shapes:t.annotations.shapes,freeformArrows:t.annotations.freeformArrows,textAnnotations:t.annotations.textAnnotations,stickers:on(t.annotations.stickers,t.layers,t.coordSystem,n),pinnedNumbers:on(t.annotations.pinnedNumbers,t.layers,t.coordSystem,n),comments:on(t.annotations.comments,t.layers,t.coordSystem,n),custom:ti(t,n)}}}const ti=({annotations:e,layers:t,coordSystem:n,scales:r},o)=>{const s=[];for(const a of e.custom){const i=[];let c=!1;for(const l of a.coordinates){const u=Xa({coordinate:l,layers:t,coordSystem:n,scales:r,geomCompiler:o});if(u===null){c=!0;break}i.push(u)}c||s.push({id:a.id,type:a.type,params:a.params,zOrder:a.zOrder,targets:i})}return s},on=(e,t,n,r)=>{const o=[];for(const s of e){const a=An(s.anchor,t,n,r);a!==null&&o.push({...s,anchor:a})}return o},ni=({annotations:e,layers:t,coordSystem:n},r)=>{if(n.type!=="cartesian")return[];const o=[];for(const s of e.differenceArrows){if(ri(s.start,s.end))continue;const a=An(s.start,t,n,r),i=An(s.end,t,n,r);a===null||i===null||o.push({id:s.id,start:a,end:i,color:oi(s,a,i),size:s.size,label:s.label,labelCrossPosition:s.labelCrossPosition})}return o},ri=(e,t)=>e.layerId===t.layerId&&e.anchorValue===t.anchorValue&&e.groupValue===t.groupValue,oi=(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 si(e,t){const n=ci(t);return{...e,background:ai(e.background,n),border:ii(e.border,n)}}function ai(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 ii(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 ci(e){const t=e.color,n=t?.domain[0];if(!n)return;const r=t.map(n);if(typeof r=="string")return r}class li extends me{dependencies(t){return[t.scales,t.config]}run(t){const{scales:n,config:r}=t;return{...r,appearance:si(r.appearance,n)}}}class ui extends me{dependencies(t){return[t.data,t.mapping]}run(t){let n=t.data,r=t.mapping;r.x===""&&(n=n.addConstantVariable(wn.x,"categorical",""),r={...r,x:wn.x});for(const o of Object.keys(r)){const s=se(r[o]);if(s===void 0)continue;const a=A(`const_${o}`);n=n.addConstantVariable(a,di(s),s),r={...r,[o]:a}}return{data:n,mapping:r}}}const di=e=>typeof e=="number"?"numeric":e instanceof Date?"temporal":"categorical";class Re{constructor(){this.perLayerMemo=Go(),this.listMemo=za()}get stats(){return Ua(this.perLayerMemo.stats,this.listMemo.stats)}compile(t){const n=this.dependencies(t),r=t.layers.map(o=>this.perLayerMemo(o,n,()=>this.compileLayer(o,t)));return this.listMemo(r,()=>r)}}class pi extends me{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 mi extends Re{constructor(t){super(),this.registry=t}dependencies(t){return[t.coordSpec]}compileLayer(t,n){const r=this.registry.get(n.coordSpec.coordType),[o]=r.transform({coordSpec:n.coordSpec,layers:[t]});if(!o)throw new Error(`CoordCompiler: strategy '${n.coordSpec.coordType}' did not return a transformed layer`);return o}}class fi{constructor(t){this.setupStage=new pi(t),this.transformStage=new mi(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 Pe{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 hi{constructor(){this.coordType="cartesian"}setup(t){if(t.coordSpec.coordType!=="cartesian")throw new Error(`Invalid coordinate type: ${t.coordSpec.coordType}`);return{coordSystem:{type:"cartesian",mainAxis:"x",axisMapping:{x:{position:"bottom",geometry:"linear"},y:{position:"right",geometry:"linear"}}},scales:t.scales}}transform(t){return t.layers}}const yi={x:{point:g.x,lower:g.xMin,upper:g.xMax},y:{point:g.y,lower:g.yMin,upper:g.yMax}},Nr=["point","lower","upper"];function gi(e){return e.name??e.role}function U(e,t){return yi[e][t]??A(`${e}_${t}`)}function Ko(e){const t=[];for(const n of e){const r=gi(n);t.includes(r)||t.push(r)}return t.sort((n,r)=>Or(n)-Or(r)),t.map(n=>[U("x",n),U("y",n)])}function Or(e){const t=Nr.indexOf(e);return t===-1?Nr.length:t}class bi{constructor(t){this.geomRegistry=t,this.coordType="flip"}setup(t){if(t.coordSpec.coordType!=="flip")throw new Error(`Invalid coordinate type: ${t.coordSpec.coordType}`);return{coordSystem:{type:"cartesian",mainAxis:"y",axisMapping:{x:{position:"right",geometry:"linear"},y:{position:"bottom",geometry:"linear"}}},scales:vi(t.scales,t.layers)}}transform(t){return t.layers.map(n=>{const r=this.geomRegistry.get(n.geom),o=Ko(r.positionChannels);return xi(n,o)})}}const $r=A("flipSwap"),vi=(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},xi=(e,t)=>{let n=e.data;for(const[r,o]of t){const s=n.hasVariable(r),a=n.hasVariable(o);s&&a?n=n.renameVariable(r,$r).renameVariable(o,r).renameVariable($r,o):s?n=n.renameVariable(r,o):a&&(n=n.renameVariable(o,r))}return{...e,data:n}};class wi{constructor(t){this.geomRegistry=t,this.coordType="polar"}setup(t){if(t.coordSpec.coordType!=="polar")throw new Error(`Invalid coordinate type: ${t.coordSpec.coordType}`);const{params:n}=t.coordSpec;return{coordSystem:{type:"polar",axisMapping:n.theta==="x"?{x:{position:"bottom",geometry:"circular"},y:{position:"left",geometry:"radial"}}:{x:{position:"left",geometry:"radial"},y:{position:"bottom",geometry:"circular"}},innerRadius:n.innerRadius,startAngle:n.startAngle*(Math.PI/180)},scales:t.scales}}transform(t){if(t.coordSpec.coordType!=="polar")throw new Error(`Invalid coordinate type: ${t.coordSpec.coordType}`);const{params:n}=t.coordSpec,r=Ai(n),o=Ti(n);return t.layers.map(s=>{const a=this.geomRegistry.get(s.geom),i=Ko(a.positionChannels),c=n.theta==="y"?Li(s,i):s,l=Mi(c,i,r,o),u=a.spatialKind==="points"?"polar-points":"arcs";return{...l,spatialMap:{kind:u}}})}}function Ai(e){const t=e.startAngle*(Math.PI/180);return n=>n*2*Math.PI+t}function Ti(e){const{innerRadius:t}=e;return n=>t+n*(1-t)}function Mi(e,t,n,r){let o=e.data;for(const[s,a]of t)o=Br(o,s,n),o=Br(o,a,r);return{...e,data:o}}function Br(e,t,n){if(!e.hasVariable(t))return e;const o=e.getValues(t,{type:"numeric"}).map(s=>s===null?null:n(s));return e.addVariable(t,"numeric",o)}function Li(e,t){let n=e.data;for(const[r,o]of t){const s=n.hasVariable(r),a=n.hasVariable(o);if(!s&&!a)continue;const i=s?n.getValues(r):null,c=a?n.getValues(o):null;i&&(n=n.addVariable(o,"numeric",i)),c&&(n=n.addVariable(r,"numeric",c))}return{...e,data:n}}class Vi extends Pe{constructor(t){super("coord"),this.register("cartesian",new hi),this.register("flip",new bi(t)),this.register("polar",new wi(t))}}const ki=new Set(["count","sum","mean","median"]);function Xo(e,t){return ki.has(e)?"numeric":t}const E=e=>(Array.isArray(e)?e:[e]).map(n=>n instanceof Date?n.toISOString():String(n??"<null>")).join("\0"),Ei="key",Ii="value",Gr="\0__rowMaskIndex",je={numeric:{type:"decimal"},categorical:{type:"text"},temporal:{type:"datetime"}},Ci={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},jo=(e,t)=>e==="count"?{type:"integer"}:t;class V{constructor(t={}){const{table:n,variableMetadata:r}=this.parseVariableMap(t);this.table=n,this.variableMetadata=r}static fromTrusted(t,n){const r=Object.create(V.prototype);return r.table=t,r.variableMetadata=n,r}size(){return this.table.numRows()}getVariableNames(){return this.table.columnNames()}hasVariable(t){return this.table.column(t)!==void 0}addVariable(t,n,r,o){const s={...this.variableMetadata,[t]:{type:n,valueFormat:this.resolveAddedVariableFormat(t,n,o)}},a=this.normalizeRawValues(n,r),i=this.table.assign(le.table({[t]:a}));return V.fromTrusted(i,s)}addConstantVariable(t,n,r,o){const s={...this.variableMetadata,[t]:{type:n,valueFormat:this.resolveAddedVariableFormat(t,n,o)}},[a]=this.normalizeRawValues(n,[r]),i=this.table.assign(le.table({[t]:Array(this.size()).fill(a)}));return V.fromTrusted(i,s)}deriveVariable(t,n,r,o){const s=Array.from({length:this.size()},(a,i)=>r(this.table.object(i),i));return this.addVariable(t,n,s,o)}renameVariable(t,n){const r=this.variableMetadata[t];if(!r)throw new Error(`Variable ${t} not defined`);const o=this.table.rename({[t]:n}),{[t]:s,...a}=this.variableMetadata,i={...a,[n]:r};return V.fromTrusted(o,i)}selectVariables(...t){const n=this.table.select(...t),r=Object.fromEntries(Object.entries(this.variableMetadata).filter(([o])=>t.includes(o)));return V.fromTrusted(n,r)}getType(t){const n=this.variableMetadata[t];if(!n)throw new Error(`Variable ${t} not defined`);return n.type}getValueFormat(t){const n=this.variableMetadata[t];if(!n)throw new Error(`Variable ${t} not defined`);return n.valueFormat}groupVariableNamesByType(){const t={numeric:[],categorical:[],temporal:[]};for(const[n,{type:r}]of Object.entries(this.variableMetadata))t[r].push(n);return t}getValues(t,n){if(!this.hasVariable(t))throw new Error(`Variable '${t}' not defined`);const r=this.getType(t);if(n?.type!==void 0&&r!==n.type)throw new Error(`Variable '${t}' has type '${r}', expected '${n.type}'`);let o=this.table.array(t);return n?.distinct&&(o=this.getDistinctValues(r,o)),n?.skipNulls&&(o=this.skipNulls(o)),o}filter(t,n,r){const o=Ci[n],s=this.table.params({__variableName:t,__value:r}).filter(o);return V.fromTrusted(s,this.variableMetadata)}filterByMask(t){if(t.length!==this.size())throw new Error(`Row mask length ${t.length} does not match dataset size ${this.size()}`);const n=Array.from({length:t.length},(o,s)=>s),r=this.table.assign(le.table({[Gr]:n})).params({__indexColumnName:Gr,__mask:t}).filter((o,s)=>s.__mask[o[s.__indexColumnName]]===1).select(...this.table.columnNames());return V.fromTrusted(r,this.variableMetadata)}orderBy(t,n="asc"){const r=this.table.orderby(n==="asc"?t:le.desc(t));return V.fromTrusted(r,this.variableMetadata)}getFirst(){return this.size()===0?null:this.table.object(0)}getLast(){return this.size()===0?null:this.table.object(this.size()-1)}findLast(t){for(let n=this.size()-1;n>=0;n--){const r=this.table.object(n);if(t(r))return r}return null}groupBy(...t){const n=this.table.groupby(...t);return new Fi(t,n,this.variableMetadata)}rollup(t){const n=this.table.rollup(Object.fromEntries(Object.entries(t).map(([o,s])=>[o,le.op[s.aggregation](s.variableName)]))),r={};for(const[o,{variableName:s,aggregation:a}]of Object.entries(t)){const i=this.variableMetadata[s],c=i?.type??"numeric",l=i?.valueFormat??je[c],u=Xo(a,c);r[o]={type:u,valueFormat:jo(a,l)}}return V.fromTrusted(n,r)}reshapeFromWideToLong({keep:t,reshape:n,keyName:r=Ei,valueName:o=Ii}={}){const{numeric:s,categorical:a,temporal:i}=this.groupVariableNamesByType(),c=t??[...a,...i],l=n??s.filter(f=>!c.includes(f));if(c.includes(r)||c.includes(o))throw new Error(`The variables to keep includes the variables '${r}' or '${o}' to create the key and value variables`);if(l.length===0){const f={};for(const y of c){const b=this.variableMetadata[y];b&&(f[y]={type:b.type,values:[],valueFormat:b.valueFormat})}return f[r]={type:"categorical",values:[],valueFormat:{type:"text"}},f[o]={type:"numeric",values:[],valueFormat:{type:"decimal"}},new V(f)}if(l.filter(f=>this.variableMetadata[f]?.type!=="numeric").length>0)throw new Error("Only numeric variables can be reshaped");const p=this.table.select([...c,...l]).fold(l,{as:[r,o]}),m={};for(const f of c){const y=this.variableMetadata[f];y&&(m[f]=y)}return m[r]={type:"categorical",valueFormat:{type:"text"}},m[o]={type:"numeric",valueFormat:Di(this.variableMetadata,l,r)},V.fromTrusted(p,m)}print(){console.table(this.variableMetadata),this.table.print()}[Symbol.iterator](){return this.table[Symbol.iterator]()}resolveAddedVariableFormat(t,n,r){if(r!==void 0)return r;const o=this.variableMetadata[t];return o?o.valueFormat:je[n]}parseVariableMap(t){const n={},r={};for(const[s,{type:a,values:i,valueFormat:c}]of Object.entries(t))n[s]=i,r[s]={type:a,valueFormat:c??je[a]};return{table:le.table(n),variableMetadata:r}}normalizeRawValues(t,n){switch(t){case"numeric":return n.map(r=>typeof r!="number"||Number.isNaN(r)?null:r);case"categorical":return n.map(r=>typeof r!="string"?null:r);case"temporal":return n.map(r=>!(r instanceof Date)||!k.isValid(r)?null:r);default:{const r=t;throw new Error(`Cannot normalize raw value of unknown type: ${r}`)}}}skipNulls(t){return t.filter(n=>n!==null)}getDistinctValues(t,n){const r=t==="temporal",o=new Set,s=[];for(const a of n){const i=r&&a instanceof Date?a.getTime():a;o.has(i)||(o.add(i),s.push(a))}return s}}class Fi{constructor(t,n,r){this.groupedBy=t,this.grouped=n,this.variableMetadata=r}forEach(t){const n=this.grouped.partitions(),r=this.grouped.columnNames(),o=this.groupedBy.map(a=>this.grouped.column(a)).filter(a=>a!==void 0);let s=0;for(const a of n){const i=a[0];if(i===void 0)continue;const c=this.getStableKey(o,i),l=Object.fromEntries(r.map(d=>{const p=this.grouped.column(d);return[d,a.map(m=>p?.get(m))]})),u=le.table(l);t(V.fromTrusted(u,this.variableMetadata),c,s++)}}rollup(t){const n=this.grouped.rollup(Object.fromEntries(Object.entries(t).map(([o,s])=>[o,le.op[s.aggregation](s.variableName)]))),r=Object.fromEntries(this.groupedBy.map(o=>{const s=this.variableMetadata[o],a=s?.type??"categorical",i=s?.valueFormat??je[a];return[o,{type:a,valueFormat:i}]}));for(const[o,{variableName:s,aggregation:a}]of Object.entries(t)){const i=this.variableMetadata[s],c=i?.type??"numeric",l=i?.valueFormat??je[c],u=Xo(a,c);r[o]={type:u,valueFormat:jo(a,l)}}return V.fromTrusted(n,r)}getStableKey(t,n){return E(t.map(r=>r.get(n)))}}function Di(e,t,n){const r=t.map(c=>e[c]?.valueFormat??{type:"decimal"}),[o,...s]=r;if(!o)return{type:"decimal"};for(const c of r)if(c.type==="lookup")throw new Error("Cannot reshape: a source column has a lookup format and lookups cannot nest");if(s.every(c=>ie.isEqual(c,o))||o.type==="lookup")return o;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:o}}class qo{constructor(){this.currentYear=new Date().getUTCFullYear(),this.previousDate=null,this.previousYear=null}incrementYearIfNeeded(t){this.previousYear===null?this.previousYear=t.getUTCFullYear():this.previousDate!==null&&k.isBefore(new Date(this.currentYear,t.getUTCMonth(),t.getUTCDate()),new Date(this.currentYear,this.previousDate.getUTCMonth(),this.previousDate.getUTCDate()))&&this.previousYear++;const n=new Date(t.getTime());return n.setUTCFullYear(this.previousYear),this.previousDate=n,n}}const Qo=e=>{const t=Object.entries(e);return!t.length||!t.some(([,n])=>!it(n))},it=e=>typeof e=="string"&&e.trim()===""||e===void 0||e===null||e==="-",Pt="en-GB",_i=e=>e.type==="lookup",Ri=e=>e.type==="text",ct=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",Zo=e=>e.type==="decimal"||e.type==="integer"||e.type==="percentage"||e.type==="duration"||e.type==="currency",Jo=e=>e.type==="currency",es=e=>e.type==="month"||e.type==="day_month"||e.type==="weekly_date_range",ts=e=>{if(_i(e))return ts(e.fallback);if(ct(e))return"temporal";if(Zo(e))return"numeric";if(Ri(e))return"categorical";const t=e;throw new Error(`No data type found for value format: ${t.type}`)},qe={k:1e3,m:1e6,b:1e9,t:1e12},Rn=["k","m","b","t"],Pi=new RegExp(`^-?(\\d{1,3}(,\\d{3})*|\\d+)\\.?\\d*(${Rn.join("|")})?$`,"i"),Ni=/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?%?$/,we=e=>e===null||e instanceof Date||Array.isArray(e)||typeof e=="boolean"?!1:typeof e=="string"?Pi.test(e)&&!Number.isNaN(Number(e.replace(new RegExp(`[,${Rn.join("")}]`,"gi"),""))):!Number.isNaN(Number(e)),ns=e=>we(e)?!0:typeof e=="string"?Ni.test(e):!1,Oi=/^\d{4}-\d{2}-\d{2}(T|\s)\d{1,2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|\+00:00)?$/,$i=/^\s*(19\d{2}|2[01]\d{2})\s*$/,Bi=[[/\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"]],Gi={"en-US":"MDY","en-GB":"DMY","pt-PT":"DMY",ar:"DMY"},rs=["/","-","."," "],zr=[["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"]],Ur=[["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"]],Yr=[["yyyy","M","d"],["yyyy","M","dd"],["yyyy","MM","d"],["yyyy","MM","dd"],["yyyy","MMMM","d"],["yyyy","MMMM","dd"],["yyyy","MMMM","do"]],os=[["d","MMMM"],["dd","MMMM"],["do","MMMM"],["MMMM","d"],["MMMM","dd"],["MMMM","do"]],zi=[{dateFormat:"MMMM d, yyyy",type:"date"},{dateFormat:"MMMM dd, yyyy",type:"date"},{dateFormat:"MMMM do, yyyy",type:"date"},{dateFormat:"yyyy-MM",type:"month_year"}],ss=1900,as=2199,Ui=3,Yi=6,Wi=5,Hi=1,Ki=28,Xi=/\s*[–—]\s*|\s-\s/,ji=e=>typeof e=="number"?Number.isNaN(e)?!1:e>=ss&&e<=as:typeof e=="string"?$i.test(e):!1,is=(e,t)=>{const n=tt(e);return we(n)?Zi(n):typeof n=="string"?!!cs(n)||Pn(n)&&k.isValid(new Date(n)):k.isValid(n)},tt=e=>{if(typeof e!="string")return e;let t=e;for(const[n,r]of Bi)t=t.replace(n,r);return t},cs=(e,t=Pt)=>{const n=tt(e);return Pn(n)?{type:"datetime"}:ls(t).find(r=>!ct(r)||r.type==="month"&&n.length<Ui?!1:r.dateFormat&&k.isValid(k.parse(n,r.dateFormat,new Date)))},Pn=e=>Oi.test(e.trim()),qi=(e,t=Pt)=>{const[n,r]=e.split(Xi);if(!n||!r)return;const o=tt(n).trim(),s=tt(r).trim();return Qi(t).find(a=>{if(!ct(a)||!a.dateFormat)return!1;const i=k.parse(o,a.dateFormat,new Date),c=k.parse(s,a.dateFormat,new Date);if(!k.isValid(i)||!k.isValid(c))return!1;const l=new qo,u=l.incrementYearIfNeeded(i),d=l.incrementYearIfNeeded(c),p=k.differenceInDays(d,u);return k.isWithinInterval(new Date(u.getFullYear(),Hi,Ki),{start:u,end:d})&&p===Wi?!0:p===Yi})},ls=e=>{const t={date:us(e),year:[["yyyy"]],day_month:os,month_year:[["MMMM","yyyy"],["yyyy","MMMM"]],month:[["MMMM"]],quarter:[["QQQ","yyyy"],["yyyy","QQQ"]]};return[...zi,...Object.entries(t).flatMap(([n,r])=>r.flatMap(o=>rs.map(s=>({dateFormat:o.join(s),type:n}))))]},us=e=>Gi[e]==="MDY"?[...Ur,...zr,...Yr]:[...zr,...Ur,...Yr],Qi=e=>{const t={weekly_date_range:os,weekly_date_range_with_year:us(e)};return Object.entries(t).flatMap(([n,r])=>r.flatMap(o=>rs.map(s=>({dateFormat:o.join(s),type:n}))))},Zi=e=>{const t=Number(e);if(!ie.isInteger(t))return!1;const n=new Date(t),r=new Date(t*1e3),o=s=>k.isValid(s)&&s.getFullYear()>=ss&&s.getFullYear()<=as;return o(n)||o(r)},ds={$:"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"},ps=e=>{if(typeof e=="string"){const t=ms(e);return t.length?we(t):!1}return we(e)},Ji=e=>{const t=fs(e),n=t?ds[t]:void 0;if(!n)throw new Error("Could not get currency ISO");return n},ms=e=>{const t=fs(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 we(n)?n.split(",").join(""):""},fs=e=>Object.keys(ds).sort((n,r)=>r.length-n.length).find(n=>e.includes(n)),ec=(e,t)=>{const n=typeof e=="string"?e.trim():e;if(we(n))return{type:"decimal"};const r=typeof n=="string"&&cs(n,t);if(r)return r;const o=typeof n=="string"&&qi(n,t);return o||(is(e)?{type:"date"}:ns(e)?{type:"percentage"}:ps(e)&&typeof e=="string"?{type:"currency",iso:Ji(e)}:{type:"text"})},tc=/\s*[–—]\s*|\s-\s/,nc=(e,t,n)=>{if(it(e))return null;switch(t.type){case"decimal":case"integer":case"duration":return hs(e);case"percentage":return rc(e);case"currency":return oc(e);case"datetime":case"date":case"year":case"month_year":case"month":case"day_month":case"quarter":case"time":return Nn(e,t.dateFormat,n);case"weekly_date_range":case"weekly_date_range_with_year":return sc(e,t.dateFormat,n);case"text":return ac(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}`)}}},Nn=(e,t,n)=>{if(e instanceof Date)return k.isValid(e)?e:null;const r=tt(String(e).trim());if(r.length===0)return null;const o=new Date;if(t){const a=k.parse(r,t,o);return k.isValid(a)?sn(a):null}for(const a of ls(n)){if(!ct(a)||!a.dateFormat)continue;const i=k.parse(r,a.dateFormat,o);if(k.isValid(i))return sn(i)}const s=new Date(r);return is(s)?Pn(r)?s:sn(s):null},hs=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;let t=e.trim();if(!we(t))return null;let n=1;for(const r of Rn)if(new RegExp(`${r}$`,"i").test(t)){n=qe[r],t=t.slice(0,-1);break}return Number(t.split(",").join(""))*n},rc=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;const t=e.trim();if(!ns(t))return null;const n=Number(t.replace(/%/g,"").replace(/,/g,""))/100;return Number.isNaN(n)?null:n},oc=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;const t=e.trim();return ps(t)?hs(ms(t)):null},sc=(e,t,n)=>{const r=String(e).trim().split(tc),[o,s]=[r[0]?.trim(),r[1]?.trim()];return!o||!s?null:Nn(o,t,n)},ac=e=>String(e).trim(),sn=e=>new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())),ic={type:"year",dateFormat:"yyyy"};class cc extends me{dependencies(t){return[t]}run(t){const n=t._metadata?.parsingLocale??Pt,r={},o=dc(t),s=lc(t);for(const[a,i]of t.columns.entries()){if(i._metadata?.isHidden)continue;const c=o.get(i.key);if(it(c))continue;const l=a===s?ic:ec(c,n),u=ts(l);r[i.key]=uc(i.key,t.rows,l,u,n)}return new V(r)}}const lc=e=>{const t=pc(e.rows,5);return e.columns.findIndex(n=>{const r=t.map(o=>o[n.key]).filter(o=>!it(o));return r.length>=2&&r.every(ji)})},uc=(e,t,n,r,o)=>{const s=new qo,a=t.reduce((i,c)=>{if(Qo(c))return i;const l=nc(c[e],n,o);return es(n)&&G(l)?i.push(s.incrementYearIfNeeded(l)):i.push(l),i},[]);return{type:r,values:a,valueFormat:n}},dc=e=>{const t=new Map,n=new Set(e.columns.map(r=>r.key));for(const r of e.rows){for(const o of n){const s=r[o];it(s)||(t.set(o,s),n.delete(o))}if(n.size===0)break}return t},pc=(e,t)=>{const n=[];for(const r of e)if(Qo(r)||n.push(r),n.length===t)return n;return n};class mc{constructor(t){this.registry=t}compile(t,n){return this.registry.get(t).compile(n)}getPositionChannels(t){return this.registry.get(t).positionChannels}getSwatchShape(t){return this.registry.get(t).swatchShape}getSpatialKind(t){return this.registry.get(t).spatialKind}getVisualAesthetics(t){return this.registry.get(t).visualAesthetics}getHighlightStrategy(t){return this.registry.get(t).highlightStrategy}getDirectLabelPositions(t){return this.registry.get(t).directLabelPositions}getGridPolicies(t){return this.registry.get(t).gridPolicies}getIdentityKeyStrategy(t){return this.registry.get(t).identityKeyStrategy}emitsGrandTotal(t){return this.registry.get(t).emitsGrandTotal}emitsStackTotals(t){return this.registry.get(t).emitsStackTotals}supportsPerGroupHeadline(t){return this.registry.get(t).supportsPerGroupHeadline}resolveAnchorPosition(t,n,r){return this.registry.get(t).resolveAnchorPosition(n,r)}}class Ne{constructor(){this.requiredAesthetics=[],this.defaultParams={},this.positionChannels=[],this.visualAesthetics=["color","size","alpha","strokeWidth","lineType"],this.swatchShape="square",this.highlightStrategy=null,this.spatialKind="noop",this.directLabelPositions=[],this.gridPolicies={},this.identityKeyStrategy="fields",this.supportedCoordTypes=["cartesian","flip","polar"],this.emitsGrandTotal=!1,this.emitsStackTotals=!1,this.supportsPerGroupHeadline=!1}resolveAnchorPosition(t,n){return null}}const Nt=(e,t)=>{const n=v(t.x);return!n||!["numeric","temporal"].includes(e.getType(n))?e:e.orderBy(n,"asc")};class fc extends Ne{constructor(){super(...arguments),this.type="area",this.requiredAesthetics=["x","y"],this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"},{axis:"y",role:"lower",valueKind:"value"},{axis:"y",role:"upper",valueKind:"value"}],this.swatchShape="area",this.highlightStrategy="overlay-anchor",this.spatialKind="buckets",this.directLabelPositions=["identity","stack","dodge","fill"],this.supportsPerGroupHeadline=!0}compile({data:t,mapping:n}){if(t=Nt(t,n),t.hasVariable(g.yMin)||(t=t.addConstantVariable(g.yMin,"numeric",0)),!t.hasVariable(g.yMax)){const r=v(n.y);h(r)&&t.hasVariable(r)&&(t=t.addVariable(g.yMax,"numeric",t.getValues(r,{type:"numeric"})))}return{data:t,mapping:{}}}}const ys=.7,hc=.1;function Oe(e){return e[g.x]}function ae(e){return e[g.y]}function nt(e){return e[g.xMin]}function Ce(e){return e[g.xMax]}function Ae(e){return e[g.yMin]}function J(e){return e[g.yMax]}function gs(e){return e[g.yRaw]}class yc extends Ne{constructor(){super(...arguments),this.type="bar",this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"},{axis:"x",role:"lower",valueKind:"bandOffset"},{axis:"x",role:"upper",valueKind:"bandOffset"},{axis:"y",role:"lower",valueKind:"value"},{axis:"y",role:"upper",valueKind:"value"}],this.swatchShape="square",this.highlightStrategy="observation-rerender",this.spatialKind="rects",this.directLabelPositions=["stack","fill"],this.gridPolicies={cartesian:{hideGridX:!0},flip:{hideGridX:!0},polar:{hideGridX:!0,hideGridY:!0}},this.emitsGrandTotal=!0,this.emitsStackTotals=!0,this.supportsPerGroupHeadline=!0}compile({data:t,mapping:n}){if(t=Nt(t,n),t.hasVariable(g.yMin)||(t=t.addConstantVariable(g.yMin,"numeric",0)),!t.hasVariable(g.yMax)){const o=v(n.y);h(o)&&t.hasVariable(o)&&(t=t.addVariable(g.yMax,"numeric",t.getValues(o,{type:"numeric"})))}const r=ys/2;return t=t.addConstantVariable(g.xMin,"numeric",-r).addConstantVariable(g.xMax,"numeric",r),{data:t,mapping:{}}}resolveAnchorPosition(t,n){if(n.type==="polar"){const a=nt(t),i=Ce(t),c=Ae(t),l=J(t);if(a===null||i===null||c===null||l===null)return null;const u=(a+i)/2,d=(c+l)/2;return{x:.5+.5*d*Math.sin(u),y:.5-.5*d*Math.cos(u),geom:"polar-bar"}}if(n.mainAxis==="x"){const a=nt(t),i=Ce(t),c=J(t)??ae(t);return a===null||i===null||c===null?null:{x:(a+i)/2,y:c,geom:"bar"}}const r=Ae(t),o=J(t),s=Ce(t)??Oe(t);return r===null||o===null||s===null?null:{x:s,y:(r+o)/2,geom:"bar"}}}class gc extends Ne{constructor(){super(...arguments),this.type="line",this.requiredAesthetics=["x","y"],this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"}],this.swatchShape="line",this.highlightStrategy="overlay-anchor",this.spatialKind="buckets",this.directLabelPositions=["identity","stack","dodge","fill"],this.supportsPerGroupHeadline=!0}compile(t){return{data:Nt(t.data,t.mapping),mapping:{}}}resolveAnchorPosition(t,n){if(n.type==="polar")return null;const r=Oe(t),o=ae(t);return r===null||o===null?null:{x:r,y:o,geom:"line"}}}class bc extends Ne{constructor(){super(...arguments),this.type="point",this.requiredAesthetics=["x","y"],this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"}],this.swatchShape="circle",this.highlightStrategy="overlay-anchor",this.spatialKind="points",this.identityKeyStrategy="index",this.supportsPerGroupHeadline=!0}compile({data:t}){return{data:t,mapping:{}}}}class vc extends Ne{constructor(){super(...arguments),this.type="rule",this.positionChannels=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"}],this.highlightStrategy=null,this.supportedCoordTypes=["cartesian","flip"]}compile({data:t,mapping:n}){const r=Wr(n.y,t);if(r!==null)return{data:new V({[ht.y]:{type:"numeric",values:[r.value],valueFormat:r.sourceFormat}}),mapping:{y:ht.y,x:void 0}};const o=Wr(n.x,t);return o!==null?{data:new V({[ht.x]:{type:"numeric",values:[o.value],valueFormat:o.sourceFormat}}),mapping:{x:ht.x,y:void 0}}:{data:new V,mapping:{x:void 0,y:void 0}}}validateMapping({layerId:t,mapping:n,computedVariables:r}){const o=r.has("x")||F(se(n.x)),s=r.has("y")||F(se(n.y));return o&&s?[{code:"INVALID_RULE_MAPPING",message:`Layer '${t}': rule geom requires exactly one of 'x' or 'y', both were provided`,layerId:t}]:!o&&!s?[{code:"INVALID_RULE_MAPPING",message:`Layer '${t}': rule geom requires a numeric value on 'x' or 'y'`,layerId:t}]:[]}}const Wr=(e,t)=>{const n=se(e);if(F(n))return{value:n,sourceFormat:void 0};const r=v(e);if(r===null||!Ka(r)||!t.hasVariable(r))return null;const[o]=t.getValues(r);return F(o)?{value:o,sourceFormat:t.getValueFormat(r)}:null};class Sc extends Pe{constructor(t){super("geom"),this.register("bar",new yc),this.register("point",new bc),this.register("line",new gc),this.register("area",new fc),this.register("rule",new vc);for(const n of t?.geoms??[])this.register(n.type,n)}}const On=(e,t)=>{if(h(t.group)){const o=v(t.group);if(o!==null)return[o]}const n=new Set([v(t.x),v(t.y)].filter(h)),r=new Set;for(const o in t){if(o==="x"||o==="y")continue;const s=v(t[o]);h(s)&&(n.has(s)||e.getType(s)==="categorical"&&r.add(s))}return[...r]};class xc{compute({data:t,mapping:n}){const r=On(t,n);if(r.length===0)return{data:t.addConstantVariable(P.group,"categorical",null)};const o=t.size(),s=r.map(i=>t.getValues(i)),a=new Array(o);for(let i=0;i<o;i++)a[i]=E(s.map(c=>c[i]));return{data:t.addVariable(P.group,"categorical",a)}}}const bs=new Set(["x","y","ySecondary"]),Ot=new Set(["color","size","alpha","strokeWidth","lineType"]),$t=e=>bs.has(e),wc=e=>Ot.has(e),Ac=e=>$t(e)||wc(e);function lt(e){return e==="secondary"?"ySecondary":"y"}function ee(e){return e==="ySecondary"?"y":e}const Tc=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},Mc=(e,t,n)=>{const r=Te(t,"color");return r===null?{}:(e?.columns??[]).some(a=>a.key===r)?{}:n};function Te(e,t){const n=ee(t);for(const r of vs(t,e)){const o=v(r.mapping[n]);if(h(o))return o}return null}const $n=(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 an(t);for(const r of e){if(!r.data.hasVariable(n))continue;const o=r.data.getValueFormat(n),s=o.type==="lookup"?o.fallback:o;return kc(s,t)?s:an(t)}return an(t)},Vc=(e,t)=>t!=="y"&&t!=="ySecondary"?!1:vs(t,e).some(n=>n.position==="fill");function vs(e,t){return e==="ySecondary"?t.filter(n=>n.yScaleType==="secondary"):e==="y"?t.filter(n=>n.yScaleType==="primary"):t}const an=e=>{switch(e){case"continuous":return{type:"decimal"};case"datetime":return{type:"date"};case"discrete":case"palette":case"identity":return{type:"text"}}},kc=(e,t)=>{switch(t){case"continuous":return Zo(e);case"datetime":return ct(e);case"discrete":case"palette":case"identity":return!0}},Ec=[{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}],Hr={year:0,quarter:1,month:2,week:3,day:4,hour:5},Le=40,Ic=(e,t,n)=>{const r=n.unit==="quarter"?n.step*3:n.step;return _c(n.unit).range(e,new Date(t.valueOf()+1),r)},Cc=({unit:e,step:t,start:n,stop:r})=>{const o=Pa.differenceInDays(r,n);switch(e){case"hour":return 24*o/t>Le;case"day":return o/t>Le;case"week":return o/(7*t)>Le;case"month":return o/(30*t)>Le;case"quarter":return o/(90*t)>Le;case"year":return o/(365*t)>Le}},Fc=(e,t)=>{const n=!es(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"}}},Dc=(e,t)=>{const n=Rc(t);return n===null?!1:Hr[e]>Hr[n]},_c=e=>{switch(e){case"hour":return Ye.utcHour;case"day":return Ye.utcDay;case"week":return Ye.utcMonday;case"month":case"quarter":return Ye.utcMonth;case"year":return Ye.utcYear}},Rc=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}},Ss={left:"right",right:"left",top:"bottom",bottom:"top"},Pc={x:!0,y:!0,ySecondary:!1},Nc=20,Kr=new Set(["top","bottom"]),Oc={type:"percentage"};function $c(e,t){const{scales:n,config:r,layers:o,coordSystem:s,variableLabels:a,geomCompiler:i}=e;if(s.type==="polar"&&s.axisMapping.x.geometry!=="circular")return[];const c=Gc(o,s.type,r,i),l=new Set(t.map(p=>p.position)),u=Uc(xs(r.axes.y.position,s.axisMapping.y.position),l),d=[];for(const p of bs){const m=n[p];if(!h(m)||m.kind!=="position")continue;const f=Bc({scaleAestheticKey:p,scale:m,config:r,layers:o,axisMapping:s.axisMapping,resolvedYPosition:u,gridOverrides:c,variableLabels:a});d.push(f)}return d}function Bc(e){const{scaleAestheticKey:t,scale:n,config:r,layers:o,axisMapping:s,resolvedYPosition:a,gridOverrides:i,variableLabels:c}=e,l=ee(t),{axisConfig:u,position:d}=zc(t,r,s,a),p=Te(o,t),m=Vc(o,t)?Oc:Me({layers:o,scaleType:n.spec.scaleType,variableName:p}),f=$n(p,c);return{scaleAestheticKey:t,aesthetic:l,position:d,geometry:s[t==="x"?"x":"y"].geometry,label:u.label??f,isVisible:u.isVisible,tickCandidates:Wc(n,m),valueFormat:m,tickMode:u.ticks.mode,ticksVisible:u.ticks.isVisible,gridVisible:Yc(u,i,t),scaleType:n.spec.scaleType,bandwidth:n.bandwidth??void 0}}function Gc(e,t,n,r){const o=e.flatMap(c=>{const l=r.getGridPolicies(c.geom)[t];return l?[l]:[]}),s=o.some(c=>c.hideGridX),a=o.some(c=>c.hideGridY),i=o.some(c=>c.hideBorder);return{x:{gridVisible:Xr(s,n.axes.x.grid.isVisible)},y:{gridVisible:Xr(a,n.axes.y.grid.isVisible)},borderVisible:i?!1:void 0}}function Xr(e,t){if(e&&t===null)return!1}function zc(e,t,n,r){switch(e){case"x":return{axisConfig:t.axes[e],position:xs(t.axes[e].position,n[e].position)};case"y":return{axisConfig:t.axes[e],position:r};case"ySecondary":{const o=Ss[r],s=ie.merge({isVisible:t.axes.y.isVisible,label:null,position:o,grid:t.axes.y.grid,ticks:t.axes.y.ticks},t.axes.ySecondary);return{axisConfig:s,position:s.position}}}}function xs(e,t){return Kr.has(e)===Kr.has(t)?e:t}function Uc(e,t){return t.has(e)?Ss[e]:e}function Yc(e,t,n){const{gridVisible:r}=n==="x"?t.x:t.y;return r??e.grid.isVisible??Pc[n]}const Wc=(e,t)=>{if(e.spec.scaleType==="continuous"){const r=new Set,o=[];for(let s=1;s<=Nc;s++){const a=e.generateTicks({count:s}),i=E(a);r.has(i)||(r.add(i),o.push({ticks:a.map(c=>Et(e,c))}))}return o}return e.spec.scaleType==="datetime"?Hc(e,t):[{ticks:e.generateTicks().map(r=>Et(e,r))}]},Hc=(e,t)=>{const[n,r]=e.domain;if(!G(n)||!G(r))return[{ticks:e.generateTicks().map(c=>Et(e,c))}];const o=new Set,s=[],a=(i,c)=>{if(i.length===0)return;const l=E(i);o.has(l)||(o.add(l),s.push({ticks:i.map(u=>Et(e,u)),valueFormat:c}))};for(const i of Ec)Cc({...i,start:n,stop:r})||Dc(i.unit,t)||a(e.generateTicks({interval:i}),Fc(i,t));return a(e.generateTicks({atInputs:!0})),s.sort((i,c)=>i.ticks.length-c.ticks.length),s},Et=(e,t)=>({value:t,position:e.map(t)});function rt(e,t){return t.type==="polar"&&e==="square"?"slice":e}function ws({scale:e,aesthetics:t,layers:n,coordSystem:r}){const o=Kc({layers:n,coordSystem:r,aesthetics:t}),s=As({layers:n,aesthetics:t});return e.domain.map(a=>({value:a,swatchShape:o(a),owner:s(a)}))}function Kc({layers:e,coordSystem:t,aesthetics:n}){const r=As({layers:e,aesthetics:n}),o=e.find(a=>n.some(i=>h(a.mapping[i]))),s=o?rt(o.swatchShape,t):"square";return a=>{const i=r(a);return i?rt(i.layer.swatchShape,t):s}}function As({layers:e,aesthetics:t,layerFilter:n}){const r=new Map;for(const[o,s]of e.entries()){if(n&&!n(s))continue;const a=t.find(c=>h(s.mapping[c]));if(a===void 0)continue;const i=v(s.mapping[a]);if(!(i===null||!s.data.hasVariable(i)))for(const c of s.data.getValues(i,{distinct:!0})){const l=E(c);r.has(l)||r.set(l,{layer:s,layerIndex:o})}}return o=>r.get(E(o))}const Bn=e=>{if(e.kind==="identity")return!1;const t=e.spec.scaleType;return t!=="continuous"&&t!=="datetime"};function Xc({scales:e,layers:t,coordSystem:n,valueLabels:r}){const o=e.color;if(o===void 0||!Bn(o))return[];if(!t.some(u=>h(u.mapping.color)))return[];const s=Te(t,"color");if(Ts({colorVariableName:s,xVariableName:Te(t,"x"),mapsColorAcrossMultipleLayers:qc(t)>1,isMergedWithAnotherAesthetic:jc(e,t,s)}))return[];const i=o.spec.scaleType,c=t.findIndex(u=>h(u.mapping.color));return ws({scale:o,aesthetics:["color"],layers:t,coordSystem:n}).map(({value:u,swatchShape:d,owner:p})=>{const m=p?.layerIndex??c,f=t[m],y=f?v(f.mapping.color):null;return{value:u,color:String(o.map(u)),shape:d,layerIndex:m,valueFormat:Me({layers:f?[f]:t,scaleType:i,variableName:y}),label:Lc(u,r)}})}const Ts=({colorVariableName:e,xVariableName:t,mapsColorAcrossMultipleLayers:n,isMergedWithAnotherAesthetic:r})=>r?!1:e===null||Ha(e)?!n:t!==null&&e===t;function jc(e,t,n){if(n===null)return!1;for(const r of Ot){if(r==="color")continue;const o=e[r];if(!(o===void 0||!Bn(o))&&Te(t,r)===n)return!0}return!1}const qc=e=>e.filter(t=>h(t.mapping.color)).length;function Qc(e,t,n,r){const o=t.findIndex(s=>r.supportsPerGroupHeadline(s.geom));if(o===-1)return[];if(e.length<2){const s=v(t[o]?.mapping.y);return[{value:null,swatch:null,layerIndex:o,groupLabelFormat:{type:"text"},label:$n(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 jr(e,t,n){if(n===null||t===null)return[...e];const r=E(n);return e.filter((o,s)=>E(t[s]??null)===r)}const Zc=(e,t)=>{switch(t){case"total":{const{sum:n,count:r}=qr(e);return r===0?null:n}case"average":{const{sum:n,count:r}=qr(e);return r===0?null:n/r}case"current":return e.at(-1)??null}},Jc=(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}},qr=e=>e.reduce((t,n)=>n===null?t:{sum:t.sum+n,count:t.count+1},{sum:0,count:0});function el(e){const{config:t,coordSystem:n}=e,r=t.headline.show;return r==="none"||r==="conversion"?null:n.type==="polar"?tl(e,r):nl(e,r)}function tl(e,t){if(t!=="total")return null;const{scales:n,layers:r}=e,o=r.find(c=>c.summary.grandTotal!==void 0);if(o===void 0)return null;const s=o.summary.grandTotal;if(s===void 0)return null;const a=v(o.mapping.y);if(a===null)return null;const i=Me({layers:[o],scaleType:n.y?.spec.scaleType??"continuous",variableName:a});return{kind:"grandTotal",value:s,valueFormat:i}}function nl(e,t){const{config:n,scales:r,layers:o,variableLabels:s,colorGroups:a,geomCompiler:i}=e;if(!o.some(u=>i.supportsPerGroupHeadline(u.geom)))return null;const c=Qc(a,o,s,i);if(c.length===0)return null;const l=c.map(u=>rl({group:u,show:t,compareWith:n.headline.compareWith,layers:o,scales:r})).filter(u=>u!==null);return l.length===0?null:{kind:"perGroup",items:l}}function rl({group:e,show:t,compareWith:n,layers:r,scales:o}){const s=r[e.layerIndex];if(s===void 0)return null;const a=v(s.mapping.y);if(a===null||t==="total"&&s.position==="fill")return null;const i=v(s.mapping.x),c=v(s.mapping.color),l=s.yScaleType==="secondary"?o.ySecondary:o.y,u=Me({layers:[s],scaleType:l?.spec.scaleType??"continuous",variableName:a}),d=al(s.data,i),p=Me({layers:[s],scaleType:d?"datetime":o.x?.spec.scaleType??"discrete",variableName:i}),m=il(s.data,i),f=m.getValues(a,{type:"numeric"}),y=i!==null?m.getValues(i):[],b=c!==null?m.getValues(c):null,x=jr(f,b,e.value),S=jr(y,b,e.value);return{value:e.value,swatch:e.swatch,aggregate:Zc(x,t),valueFormat:u,groupLabelFormat:e.groupLabelFormat,mainValueFormat:p,label:e.label,observationLabel:ol(t,d,S),comparison:sl(t,n,d,S,x)}}function ol(e,t,n){if(e==="current"){const s=n.at(-1);return s===void 0?null:{kind:"point",value:s}}if(!t)return null;const r=n.at(0),o=n.at(-1);return r===void 0||o===void 0?null:{kind:"range",from:r,to:o}}function sl(e,t,n,r,o){if(e!=="current"||!n)return null;const s=t==="none"?"first":t,a=r.map((i,c)=>({main:i,cross:o[c]??null}));return Jc(a,s)}function al(e,t){return t!==null&&e.hasVariable(t)&&e.getType(t)==="temporal"}function il(e,t){return t===null||!["numeric","temporal"].includes(e.getType(t))?e:e.orderBy(t)}const Ms=["point","line","area","bar","rule"],Ls=new Set(Ms);function Vs(e){return Ls.has(e)}function K(e){return e==="stack"||e==="fill"}const cl=3;function ll({scales:e,config:t,layers:n,coordSystem:r,variableLabels:o,colorGroups:s,geomCompiler:a}){if(t.legend.position==="none")return[];const i=new Map(s.map(b=>[E(b.value),b])),c=pl({scales:e,layers:n,geomCompiler:a}),l=gl(c),u=Te(n,"x"),d=l.map(b=>{if(hl(b,u,n))return null;const x=vl({group:b,variableLabels:o,layers:n,coordSystem:r,colorGroupsByValue:i});return x.items.length===0?null:{group:b,built:x}}).filter(h);if(d.length===0)return[];const p=ul(d);if(t.legend.position==="auto"&&Tl(p,n,r))return[];const m=Ml(t.legend.position,p,n,r),f=Vl(t.legend.display,m,n,r,a),y=f==="direct"?Il(n):null;return d.map(({built:b})=>dl(b,m,f,y))}function ul(e){return e.reduce((t,{group:n,built:r})=>{const o=n.some(s=>s.guideType!=="discrete");return t+(o?1:r.items.length)},0)}function dl(e,t,n,r){return n!=="direct"||r===null?{...e,position:t,display:n}:{...e,position:t,display:n,items:e.items.map(o=>({...o,normalizedY:r.get(String(o.value))??null}))}}function pl(e){const{scales:t,layers:n,geomCompiler:r}=e,o=ml(n,r),s=[];for(const a of Ot){if(!o.has(a))continue;const i=t[a];if(i===void 0||i.kind==="identity"||!fl(a,n))continue;const c=Te(n,a),l=El(a,i);s.push({scaleAestheticKey:a,scale:i,variableName:c,guideType:l})}return s}function ml(e,t){const n=new Set;for(const r of e)for(const o of t.getVisualAesthetics(r.geom))n.add(o);return n}function fl(e,t){const n=ee(e);return t.some(r=>h(r.mapping[n]))}function hl(e,t,n){const[r]=e;return r.scaleAestheticKey!=="color"?!1:Ts({colorVariableName:r.variableName,xVariableName:t,mapsColorAcrossMultipleLayers:yl(r.scaleAestheticKey,n),isMergedWithAnotherAesthetic:e.length>1})}function yl(e,t){const n=ee(e);return t.filter(r=>h(r.mapping[n])).length>1}function gl(e){const t=new Map;for(const n of e){const r=kl(n),o=t.get(r);o?o.push(n):t.set(r,[n])}return[...t.values()]}function bl(e,t,n){if(t==="lineType"){e.lineType=n;return}if(t==="color"){e.color=String(n);return}e[t]=n}function vl({group:e,variableLabels:t,layers:n,coordSystem:r,colorGroupsByValue:o}){const s=e[0],a=e.map(u=>ee(u.scaleAestheticKey)),i=ws({scale:s.scale,aesthetics:a,layers:n,coordSystem:r}),c=$n(s.variableName,t),l=Me({layers:n,scaleType:s.scale.spec.scaleType,variableName:s.variableName});return{aesthetics:e.map(u=>u.scaleAestheticKey),title:c,items:i.map(u=>Sl(u,e,a,l,o))}}function Sl(e,t,n,r,o){const s={};for(const i of t)bl(s,i.scaleAestheticKey,i.scale.map(e.value));const a=wl(e,t,n,r,o);return{value:e.value,label:xl(t,e,o),visual:s,normalizedY:null,swatchShape:e.swatchShape,valueFormat:a}}function xl(e,t,n){return e[0].scaleAestheticKey!=="color"?null:n.get(E(t.value))?.label??null}function wl(e,t,n,r,o){if(t[0].scaleAestheticKey==="color")return o.get(E(e.value))?.valueFormat??r;const s=e.owner?.layer,a=Al(s,n);return s===void 0||a===null?r:Me({layers:[s],scaleType:t[0].scale.spec.scaleType,variableName:a})}function Al(e,t){if(e===void 0)return null;for(const n of t){const r=e.mapping[n];if(r===void 0)continue;const o=v(r);if(o!==null)return o}return null}function Tl(e,t,n){if(e>1)return!1;const r=n.type==="polar";return At(t,["line","area","bar"])||r}function Ml(e,t,n,r){if(e!=="auto")return e;if(r.type==="polar")return"top";const o=At(n,["line","area"]),s=At(n,["bar"]),a=At(n,["bar"],c=>K(c.position)),i=t>=cl;return o&&s?"top":o?i?"right":"top":a?ks(r)?"top":i?"right":"top":"top"}function Ll(e,t){if(e.length!==1)return!1;const n=e[0];return n?t.getDirectLabelPositions(n.geom).includes(n.position):!1}function Vl(e,t,n,r,o){if(!(t==="right"&&!ks(r)))return"pill";switch(e){case"pill":return"pill";case"direct":return"direct";case"auto":return Ll(n,o)?"direct":"pill"}}function ks(e){return e.type==="cartesian"&&e.mainAxis==="y"}function At(e,t,n){return e.some(r=>t.includes(r.geom)&&(n?.(r)??!0))}function kl(e){const t=e.scale.domain.map(E);return JSON.stringify([e.variableName,e.guideType,...t])}function El(e,t){return Bn(t)?"discrete":`continuous:${e}`}function Il(e){const t=e[0];if(!t)return new Map;const n=new Map;return t.data.groupBy(P.group).forEach(r=>{const o=r.findLast(l=>h(J(l))||h(ae(l)));if(!o)return;const s=_e(o);if(!h(s))return;const a=Ae(o),i=J(o)??ae(o);if(!h(i))return;const c=h(a)?(a+i)/2:i;n.set(String(s),c)}),n}class Cl extends me{constructor(t){super(),this.geomCompiler=t}dependencies(t){return[t.scales,t.config.axes,t.config.legend,t.config.headline,t.config.panel,t.layers,t.coordSystem,t.originalData]}run(t){const n=Tc(t.originalData),r=Xc({scales:t.scales,layers:t.layers,coordSystem:t.coordSystem,valueLabels:Mc(t.originalData,t.layers,n)}),o={scales:t.scales,config:t.config,layers:t.layers,coordSystem:t.coordSystem,variableLabels:n,colorGroups:r,geomCompiler:this.geomCompiler},s=el(o),a=Fl(s,ll(o));return{axes:$c(o,a),legends:a,headline:s,panel:{border:{isVisible:t.config.panel.border.isVisible}},colorGroups:r}}}const Fl=(e,t)=>e?.kind!=="perGroup"||t.some(r=>r.display==="direct")?t:[],Bt=e=>e[Yo.key],Dl=e=>E([_e(e)]),Gn=(e,t)=>{const n=t!==null?e[t]??null:null;return E([n])},X=(e,t)=>{const n=se(t);if(n!==void 0)return()=>n;const r=v(t);return h(r)?o=>{const s=o[r];if(s===void 0)return null;switch(e.getType(r)){case"numeric":return F(s)?s:null;case"categorical":return at(s)?s:null;case"temporal":return G(s)?s:null;default:return null}}:()=>null},zn=(e,t)=>X(e,t.x),Es=(e,t)=>X(e,t.y),_l=(e,t)=>X(e,t.label),Is=(e,t)=>X(e,t.color),Rl=(e,t)=>X(e,t.size),Pl=(e,t)=>X(e,t.alpha),Nl=(e,t)=>X(e,t.group),Ol=(e,t)=>X(e,t.strokeWidth),Qr={variable:g.yRaw};function ut(e,t){return K(e)?Qr:t.y??Qr}function Un(e){return X(e.data,ut(e.position,e.mapping))}const $l=["lt","lte","gt","gte","range"];function Tt(e,t){if("and"in e){const n=e.and.map(r=>Tt(r,t));return r=>{for(const o of n)if(!o(r))return!1;return!0}}if("or"in e){const n=e.or.map(r=>Tt(r,t));return r=>{for(const o of n)if(o(r))return!0;return!1}}if("not"in e){const n=Tt(e.not,t);return r=>!n(r)}return Bl(e,t)}function Mt(e,t){if("and"in e){for(const r of e.and)Mt(r,t);return}if("or"in e){for(const r of e.or)Mt(r,t);return}if("not"in e){Mt(e.not,t);return}const n=Gl(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 Zr=()=>!1;function Bl(e,t){if(!t.hasVariable(e.variable))return Zr;const n=t.getType(e.variable);if("eq"in e){const r=ce(e.eq,n,t.parsingLocale);return o=>Jr(t.readValue(o,e.variable),r)}if("oneOf"in e){const r=e.oneOf.map(o=>ce(o,n,t.parsingLocale));return o=>{const s=t.readValue(o,e.variable);for(const a of r)if(Jr(s,a))return!0;return!1}}if("lt"in e){const r=ce(e.lt,n,t.parsingLocale);return o=>Ve(t.readValue(o,e.variable),r)==="less"}if("lte"in e){const r=ce(e.lte,n,t.parsingLocale);return o=>{const s=Ve(t.readValue(o,e.variable),r);return s==="less"||s==="equal"}}if("gt"in e){const r=ce(e.gt,n,t.parsingLocale);return o=>Ve(t.readValue(o,e.variable),r)==="greater"}if("gte"in e){const r=ce(e.gte,n,t.parsingLocale);return o=>{const s=Ve(t.readValue(o,e.variable),r);return s==="greater"||s==="equal"}}if("range"in e){const[r,o]=e.range,s=ce(r,n,t.parsingLocale),a=ce(o,n,t.parsingLocale);return i=>{const c=t.readValue(i,e.variable),l=Ve(c,s),u=Ve(c,a);return l==="incomparable"||u==="incomparable"?!1:(l==="greater"||l==="equal")&&(u==="less"||u==="equal")}}return Zr}function Gl(e){for(const t of $l)if(t in e)return t;return null}function Ve(e,t){if(e===null||t===null)return"incomparable";if(G(e)&&G(t)){const n=e.getTime(),r=t.getTime();return n<r?"less":n>r?"greater":"equal"}return F(e)&&F(t)?e<t?"less":e>t?"greater":"equal":"incomparable"}function Jr(e,t){return e===t?!0:G(e)&&G(t)?e.getTime()===t.getTime():!1}function ce(e,t,n){return t!=="temporal"||!at(e)?e:Nn(e,void 0,n)}function Cs(e){return e===null?null:{strategy:e,composition:Fs()}}function Fs(){return{isDimmed:!1,matchedLayer:null,overlayCandidates:[]}}class zl extends Re{dependencies(t){return[t.highlights,t.config.parsingLocale]}compileLayer(t,n){const r=t.highlight;if(r===null)return t;const o=n.highlights.filter(({layerId:a})=>a===void 0||a===t.id);if(o.length===0)return t;const s=Ul({layer:t,highlights:o,parsingLocale:n.config.parsingLocale,strategy:r.strategy});return{...t,highlight:{...r,composition:s}}}}function Ul({layer:e,highlights:t,parsingLocale:n,strategy:r}){for(const T of t)Mt(T.predicate,e.data);const o=v(e.mapping.x),s=Yl(e,n),a=t.map(T=>({predicate:Tt(T.predicate,s),scope:T.scope})),i=a.some(({scope:T})=>T==="series"),c=a.some(({scope:T})=>T==="x-value"),l=r==="overlay-anchor",u=e.data.size(),d=i?new Array(u):null,p=c?new Array(u):null,m=l?new Array(u):null,f=new Uint8Array(u),y=new Set,b=new Set;let x=!1,S=0;for(const T of e.data){let te,ye;d!==null&&(te=Dl(T),d[S]=te),p!==null&&(ye=Gn(T,o),p[S]=ye),m!==null&&(m[S]=T);for(const{predicate:mt,scope:ft}of a)if(mt(T))switch(ft){case"series":te!==void 0&&y.add(te);break;case"x-value":ye!==void 0&&b.add(ye);break;case"data-point":f[S]=1,x=!0;break}S++}if(y.size===0&&b.size===0&&!x)return Fs();const w=new Uint8Array(u),I=[];let _=0;for(let T=0;T<u;T++){const te=d?.[T],ye=p?.[T],mt=te!==void 0&&y.has(te),ft=ye!==void 0&&b.has(ye),Dr=f[T]===1;if(r==="observation-rerender")(mt||Dr||ft)&&(w[T]=1,_++);else if(mt)w[T]=1,_++;else if(Dr||ft){const _r=m?.[T];_r!==void 0&&I.push({observation:_r,observationIndex:T})}}const j=_>0?{...e,data:e.data.filterByMask(w)}:null;return{isDimmed:(r==="observation-rerender"||y.size>0)&&j!==null,matchedLayer:j,overlayCandidates:I}}function Yl(e,t){const n=v(e.mapping.y),r=Un(e);return{hasVariable:o=>e.data.hasVariable(o),getType:o=>e.data.getType(o),readValue:(o,s)=>n!==null&&s===n?r(o):o[s]??null,parsingLocale:t}}const Wl=["x","y","color","size","alpha","strokeWidth","lineType","label"],Ds=(e,t,n,r=[])=>{const o=[];for(const s of Wl){const a=Xl(s,t,n);a===null||!e.hasVariable(a.valueVariable)||!e.hasVariable(a.formatVariable)||o.push({aesthetic:s,variable:a.valueVariable,valueFormat:e.getValueFormat(a.formatVariable)})}return{encodings:o,detailRows:Kl(e,r)}},Hl=e=>t=>({key:Bt(t),encodings:e.encodings.map(({aesthetic:n,variable:r,valueFormat:o})=>({aesthetic:n,value:t[r]??null,valueFormat:o}))});function Kl(e,t){const n=[];for(const r of t)e.hasVariable(r.variable)&&n.push({label:r.label,variable:r.variable,valueFormat:e.getValueFormat(r.variable)});return n}function Xl(e,t,n){if(e==="y"){const o=v(ut(n,t));return o===null?null:{valueVariable:o,formatVariable:v(t.y)??o}}const r=v(t[e]);return r===null?null:{valueVariable:r,formatVariable:r}}const jl=Object.values(g);function eo(e){const t=new V({});return{id:e.id,data:t,geom:e.geom,mapping:{},position:e.position,yScaleType:e.yScaleType,params:e.params,interactive:e.interactive,dataLabels:e.dataLabels,summary:{},highlight:null,semanticMap:Ds(t,{},e.position),spatialMap:{kind:"noop"},swatchShape:"square",failed:!0}}function ql(e,t){let n;try{n=t()}catch{return eo(e)}return Ql(n)?n:eo(e)}function Ql(e){for(const t of jl)if(e.data.hasVariable(t)&&e.data.getType(t)==="numeric"){for(const n of e.data.getValues(t,{type:"numeric"}))if(n!==null&&!Number.isFinite(n))return!1}return!0}const Zl=e=>e.kind==="index"?(t,n)=>String(n):t=>E(e.variables.map(n=>t[n])),Jl=(e,t)=>{if(e==="index")return{kind:"index"};const n=v(t.x);return{kind:"fields",variables:n===null?[P.group]:[n,P.group]}},eu=(e,t,n)=>{const r=Zl(Jl(t,n));return e.deriveVariable(Yo.key,"categorical",r)};class tu extends Re{constructor(t,n,r,o,s){super(),this.transformCompiler=t,this.statCompiler=n,this.groupCompiler=r,this.geomCompiler=o,this.positionAdjusterCompiler=s}dependencies(t){return[t.data,t.mapping,to(t)]}compileLayer(t,n){return ql(t,()=>{const r=this.transformCompiler.compile({data:n.data,transforms:t.transforms}),o={...n.mapping,...t.mapping};return this.runLayerPipeline(t,r,o,to(n))})}runLayerPipeline(t,n,r,o){const s=_t({data:n,mapping:r}).pipe(({data:c,mapping:l})=>{const u=this.statCompiler.compute(t.stat,{data:c,mapping:l,xScaleIsDiscrete:o});return{data:u.data,mapping:{...l,...u.mapping}}}).pipe(({data:c,mapping:l})=>({data:this.groupCompiler.compute({data:c,mapping:l}).data,mapping:l})).pipe(({data:c,mapping:l})=>{const u=this.geomCompiler.compile(t.geom,{data:c,mapping:l,params:t.params});return{data:u.data,mapping:{...l,...u.mapping},tooltipRows:u.tooltipRows??[]}}).pipe(({data:c,mapping:l})=>{const u=this.geomCompiler.getPositionChannels(t.geom),d=this.positionAdjusterCompiler.adjust(t.position,u,{data:c,mapping:l});return{data:d.data,mapping:{...l,...d.mapping}}}).pipe(({data:c,mapping:l})=>({data:eu(c,this.geomCompiler.getIdentityKeyStrategy(t.geom),l),mapping:l})).result(),{tooltipRows:a,...i}=s;return{...i,id:t.id,geom:t.geom,position:t.position,yScaleType:t.yScaleType,params:t.params,interactive:t.interactive,dataLabels:t.dataLabels,summary:{},highlight:Cs(this.geomCompiler.getHighlightStrategy(t.geom)),semanticMap:Ds(i.data,i.mapping,t.position,a),spatialMap:{kind:this.geomCompiler.getSpatialKind(t.geom)},swatchShape:this.geomCompiler.getSwatchShape(t.geom),failed:!1}}}function to(e){return e.scales.some(t=>t.scaledAesthetic==="x"&&t.scaleType==="discrete")}class _s extends Error{constructor(t){const n=t.map(r=>`- ${r.message}`).join(`
2
- `);super(`Spec validation failed:
3
- ${n}`),this.issues=t,this.name="SpecValidationError",console.warn(`Spec validation failed:
4
- ${n}`)}}class nu{constructor(t,n){this.transformCompiler=t,this.validator=n}check(t){const n=[];for(const r of t.layers){const o=this.transformCompiler.compile({data:t.data,transforms:r.transforms}),s={...t.mapping,...r.mapping};n.push(...this.validator.validate({layerId:r.id,geom:r.geom,stat:r.stat,effectiveMapping:s,data:o,coordType:t.coords.coordType}))}if(n.length>0)throw new _s(n)}}class ru{constructor(t,n){this.geomRegistry=t,this.statRegistry=n}validate(t){return[...this.validateRequiredAesthetics(t),...this.validateVariableExistence(t),...this.validateGeomMapping(t),...this.validateCoordSupport(t)]}validateRequiredAesthetics({layerId:t,geom:n,stat:r,effectiveMapping:o}){const s=[],{requiredAesthetics:a}=this.geomRegistry.get(n),i=this.collectComputedVariables(r);for(const c of a)i.has(c)||h(Dn(o,c))||s.push({code:"MISSING_AESTHETIC",message:`Layer '${t}': geom '${n}' requires aesthetic '${c}'`,layerId:t,aesthetic:c});return s}validateVariableExistence({layerId:t,stat:n,effectiveMapping:r,data:o}){const s=[],a=this.collectComputedVariables(n);for(const[i,c]of Object.entries(r)){if(a.has(i))continue;const l=v(c);l!==null&&(o.hasVariable(l)||s.push({code:"UNKNOWN_VARIABLE",message:`Layer '${t}': aesthetic '${i}' references variable '${l}' which does not exist in the dataset`,layerId:t,aesthetic:i}))}return s}validateGeomMapping({layerId:t,geom:n,stat:r,effectiveMapping:o}){const s=this.geomRegistry.get(n);if(s.validateMapping===void 0)return[];const a=this.collectComputedVariables(r);return s.validateMapping({layerId:t,mapping:o,computedVariables:a})}collectComputedVariables(t){const n=new Set;for(const r of t)for(const o of this.statRegistry.get(r.type).computedVariables)n.add(o);return n}validateCoordSupport({layerId:t,geom:n,coordType:r}){const{supportedCoordTypes:o}=this.geomRegistry.get(n);return o.includes(r)?[]:[{code:"UNSUPPORTED_COORD",message:`Layer '${t}': geom '${n}' is not supported under '${r}' coords`,layerId:t}]}}const no=A("__ungrouped__"),ou=(e,t)=>t===null?!0:e.some(n=>n.axis===t.axis&&n.role===t.role&&n.valueKind===t.valueKind),Rs=(e,t,n="y")=>{const r=n==="y"?"x":"y",o=v(t[n]),s=v(t[r]);if(!o||!s)return null;const a=e.getValues(P.group,{type:"categorical",distinct:!0,skipNulls:!0}),i=a.length===0,c=i?[no]:a,l=e.getValues(s),u=e.getValues(o,{type:"numeric"}),d=e.getValues(P.group,{type:"categorical"}),p=e.size(),m=new Map;for(let f=0;f<p;f++){const y=l[f]??null,b=d[f],x=i?no:b;if(!h(x))continue;let S=m.get(y);S||(S=new Map,m.set(y,S)),S.set(x,f)}return{values:u,observationIndexByPartitionAndGroup:m,uniqueGroupKeys:c,observationCount:p}};class su{constructor(t){this.registry=t}adjust(t,n,r){const o=this.registry.get(t),s=o.getConsumedChannel(r.axis??"y");return ou(n,s)?o.adjust(r):{data:r.data,mapping:{}}}}class Gt{getConsumedChannel(t){return null}}class au extends Gt{constructor(){super(...arguments),this.type="dodge"}getConsumedChannel(t){return{axis:"x",role:"point",valueKind:"value"}}adjust({data:t,mapping:n}){if(!v(n.x))return{data:t,mapping:{}};const o=t.getValues(P.group,{type:"categorical",distinct:!0,skipNulls:!0});if(o.length===0)return{data:t,mapping:{}};const s=t.size(),a=t.getValues(P.group,{type:"categorical"}),i=ys/2,c=o.length>1?hc:0,l=de.scaleBand().domain(o.map(String)).range([-i,i]).paddingInner(c).paddingOuter(0),u=l.bandwidth(),d=new Array(s).fill(null),p=new Array(s).fill(null);for(let f=0;f<s;f++){const y=a[f];if(!h(y))continue;const b=l(String(y));h(b)&&(d[f]=b,p[f]=b+u)}return{data:t.addVariable(g.xMin,"numeric",d).addVariable(g.xMax,"numeric",p),mapping:{}}}}class iu extends Gt{constructor(){super(...arguments),this.type="fill"}getConsumedChannel(t){return{axis:t,role:"point",valueKind:"value"}}adjust({data:t,mapping:n,axis:r="y"}){const o=Rs(t,n,r);if(o===null)return{data:t,mapping:{}};const{values:s,observationIndexByPartitionAndGroup:a,uniqueGroupKeys:i,observationCount:c}=o,l=[...s],u=new Array(c).fill(0);for(const[,p]of a){let m=0,f=0;for(const x of i){const S=p.get(x);if(S===void 0)continue;const w=s[S];w!=null&&(w>=0?m+=w:f-=w)}let y=0,b=0;for(const x of i){const S=p.get(x);if(S===void 0)continue;const w=s[S];if(w===void 0)continue;if(w===null){u[S]=null,l[S]=null;continue}const I=w>=0?m:f;if(I===0){u[S]=0,l[S]=0;continue}const _=w/I;w>=0?(u[S]=y,l[S]=y+=_):(l[S]=b,u[S]=b+=_)}}let d=t.addVariable(U(r,"lower"),"numeric",u).addVariable(U(r,"upper"),"numeric",l);return r==="y"&&(d=d.addVariable(g.yRaw,"numeric",s)),{data:d,mapping:{}}}}class cu extends Gt{constructor(){super(...arguments),this.type="identity"}adjust({data:t}){return{data:t,mapping:{}}}}class lu extends Gt{constructor(){super(...arguments),this.type="stack"}getConsumedChannel(t){return{axis:t,role:"point",valueKind:"value"}}adjust({data:t,mapping:n,axis:r="y"}){const o=Rs(t,n,r);if(o===null)return{data:t,mapping:{}};const{values:s,observationIndexByPartitionAndGroup:a,uniqueGroupKeys:i,observationCount:c}=o,l=[...s],u=new Array(c).fill(0);for(const[,m]of a){let f=0,y=0;for(const b of i){const x=m.get(b);if(x===void 0)continue;const S=s[x];if(S!==void 0){if(S===null){u[x]=null,l[x]=null;continue}S>=0?(u[x]=f,l[x]=f+=S):(l[x]=y,u[x]=y+=S)}}}let d=t.addVariable(U(r,"lower"),"numeric",u).addVariable(U(r,"upper"),"numeric",l);r==="y"&&(d=d.addVariable(g.yRaw,"numeric",s));const p=v(n[r]);return p!==null&&(d=d.addVariable(p,"numeric",l)),{data:d,mapping:{}}}}class uu extends Pe{constructor(){super("position"),this.register("identity",new cu),this.register("stack",new lu),this.register("fill",new iu),this.register("dodge",new au)}}function du(e){let t=e.data;for(const n of e.channels)n.role==="point"&&(t=pu(n.axis,t,e));for(const n of fu(e.channels))t=hu(n,t,e);for(const n of e.channels)n.role==="scalar"&&(t=mu(n,t,e));return t}function Yn(e,t){return e==="x"?"x":lt(t)}function pu(e,t,n){const r=v(n.mapping[e]),o=n.getPositionScale(Yn(e,n.yScaleType));if(!r||!o)return t;const a=t.getValues(r).map(i=>h(i)?o.map(i):null);return t.addVariable(U(e,"point"),"numeric",a)}function mu(e,t,n){const r=n.getPositionScale(Yn(e.axis,n.yScaleType)),s=(e.aes?v(Dn(n.mapping,e.aes)):null)??U(e.axis,e.name);if(!r||!t.hasVariable(s))return t;const i=t.getValues(s,{type:"numeric"}).map(c=>h(c)?r.map(c):null);return t.addVariable(U(e.axis,e.name),"numeric",i)}function fu(e){const t=new Map;for(const n of e){if(n.role==="point"||n.role==="scalar")continue;const r=`${n.axis}:${n.valueKind}`,o=t.get(r)??{axis:n.axis,valueKind:n.valueKind,hasLower:!1,hasUpper:!1};n.role==="lower"&&(o.hasLower=!0),n.role==="upper"&&(o.hasUpper=!0),t.set(r,o)}return[...t.values()].filter(n=>n.hasLower&&n.hasUpper).map(({axis:n,valueKind:r})=>({axis:n,valueKind:r}))}function hu(e,t,n){const r=n.getPositionScale(Yn(e.axis,n.yScaleType));if(!r)return t;const o=U(e.axis,"lower"),s=U(e.axis,"upper");return!t.hasVariable(o)||!t.hasVariable(s)?t:e.valueKind==="value"?yu(t,r,o,s):gu(e.axis,t,r,o,s)}function yu(e,t,n,r){const o=e.getValues(n,{type:"numeric"}),s=e.getValues(r,{type:"numeric"}),a=e.size(),i=new Array(a),c=new Array(a);for(let l=0;l<a;l++){const u=o[l],d=s[l];h(u)&&h(d)?(i[l]=t.map(u),c[l]=t.map(d)):(i[l]=null,c[l]=null)}return e.addVariable(n,"numeric",i).addVariable(r,"numeric",c)}function gu(e,t,n,r,o){const s=U(e,"point");if(!n.bandwidth||!t.hasVariable(s))return t;const a=n.bandwidth,i=t.getValues(s,{type:"numeric"}),c=t.getValues(r,{type:"numeric"}),l=t.getValues(o,{type:"numeric"}),u=t.size(),d=new Array(u),p=new Array(u);for(let m=0;m<u;m++){const f=i[m],y=c[m],b=l[m];h(f)&&h(y)&&h(b)?(d[m]=f+y*a,p[m]=f+b*a):(d[m]=null,p[m]=null)}return t.addVariable(r,"numeric",d).addVariable(o,"numeric",p)}function bu(e,t){const n=e[t];return n?.kind==="position"?n:null}class vu extends Re{constructor(t){super(),this.geomRegistry=t}dependencies(t){return[t.scales.x,t.scales.y,t.scales.ySecondary]}compileLayer(t,n){const r=this.geomRegistry.get(t.geom),o=du({channels:r.positionChannels,data:t.data,mapping:t.mapping,yScaleType:t.yScaleType,getPositionScale:s=>bu(n.scales,s)});return{...t,data:o}}}class Su extends me{constructor(t){super(),this.registry=t}dependencies(t){return[t.layers,t.scales]}run(t){this.validateScaleTypeCompatibility(t);const n=new Map;for(const s of t.scales)n.set(s.scaledAesthetic,s);const r=this.collectValues(t.layers,n),o={};for(const[s,a]of n){const i=r.get(s)??[],c=this.registry.get(a.scaleType);o[s]=c.compile(a,i)}return o}validateScaleTypeCompatibility(t){const n=[];for(const r of t.scales){const{compatibleDataTypes:o}=this.registry.get(r.scaleType),s=ee(r.scaledAesthetic),a=t.layers.find(l=>h(l.mapping[s]));if(!a)continue;const i=v(a.mapping[s]);if(!h(i)||!a.data.hasVariable(i))continue;const c=a.data.getType(i);if(o.includes(c)||n.push({code:"INCOMPATIBLE_TYPE",message:`Scale '${r.scaledAesthetic}' (${r.scaleType}) is incompatible with variable '${i}' (${c})`,aesthetic:s}),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:s})}}if(n.length>0)throw new _s(n)}collectValues(t,n){const r=new Map;for(const o of t)for(const[s,a]of Object.entries(o.mapping)){const i=s,c=i==="y"?lt(o.yScaleType):i;if(!Ac(c)||!n.has(c))continue;const l=this.resolveVariables(i,a,o.data);this.collectFromVariables(o.data,l,c,r)}return r}resolveVariables(t,n,r){if(t==="y"&&this.hasPositionAdjustedY(r))return[g.yMin,g.yMax];const o=v(n);return!o||!r.hasVariable(o)?[]:[o]}hasPositionAdjustedY(t){return t.hasVariable(g.yMin)&&t.hasVariable(g.yMax)}collectFromVariables(t,n,r,o){if(n.length===0)return;let s=[];for(const i of n)s=s.concat(t.getValues(i));const a=o.get(r);o.set(r,a?a.concat(s):s)}}class dt{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 xu extends dt{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),o=this.computeDataDomain(n,t);return r?this.buildPositionScale(o,t):this.buildVisualScale(o,t)}computeDataDomain(t,n){let r=1/0,o=-1/0;for(const s of t)typeof s=="number"&&(s<r&&(r=s),s>o&&(o=s));return r===1/0?[0,0]:(n.zero&&(r>0&&(r=0),o<0&&(o=0)),[r,o])}createD3Scale(t,n,r){let o=[r.domainMin??t[0],r.domainMax??t[1]];const s=r.transform==="log"&&wu(o),a=s?de.scaleLog():r.transform==="sqrt"?de.scaleSqrt():de.scaleLinear();return r.nice&&!s&&(o=a.copy().domain(o).nice().domain()),a.domain([r.domainMin??o[0],r.domainMax??o[1]]).range(n).clamp(r.clamp)}buildPositionScale(t,n){const r=n.reverse?[1,0]:[0,1],o=this.createD3Scale(t,r,n);return this.createPositionScale(n,{map:o,domain:o.domain(),bandwidth:null,generateTicks:s=>s&&"count"in s?o.ticks(s.count):o.ticks()})}buildVisualScale(t,n){const r=n.range??[0,1],o=n.reverse?[r[1],r[0]]:r,s=this.createD3Scale(t,o,n);return this.createVisualScale(n,{map:s,domain:s.domain(),generateTicks:a=>a&&"count"in a?s.ticks(a.count):s.ticks()})}}const wu=e=>{const[t,n]=e;return t>0&&n>0||t<0&&n<0};class Au extends dt{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),o=this.computeDataDomain(n);if(!r)throw new Error("Datetime scale is not supported for non-position aesthetics");return this.buildScale(o,t,this.collectInputDates(n))}collectInputDates(t){const n=new Set,r=[];for(const o of t){if(!(o instanceof Date))continue;const s=o.getTime();n.has(s)||(n.add(s),r.push(o))}return r.sort((o,s)=>o.getTime()-s.getTime()),r}computeDataDomain(t){let n=1/0,r=-1/0;for(const o of t){if(!(o instanceof Date))continue;const s=o.getTime();s<n&&(n=s),s>r&&(r=s)}return n===1/0?[]:[new Date(n),new Date(r)]}createD3Scale(t,n,r){const o=Tu(t)?t:[],s=de.scaleUtc().domain(o).range(n).clamp(r.clamp);if(r.nice&&s.nice(),h(r.domainMin)||h(r.domainMax)){const[a,i]=s.domain();a!==void 0&&i!==void 0&&s.domain([r.domainMin??a,r.domainMax??i])}return s}buildScale(t,n,r){const o=n.reverse?[1,0]:[0,1],s=this.createD3Scale(t,o,n),[a,i]=s.domain(),c=a&&i?r.filter(l=>l>=a&&l<=i):[];return this.createPositionScale(n,{map:s,domain:s.domain(),bandwidth:null,generateTicks:l=>l&&"atInputs"in l?c:l&&"interval"in l?a&&i?Ic(a,i,l.interval):[]:s.ticks(l?.count)})}}const Tu=e=>e.length===2&&G(e[0])&&G(e[1]),ke={transform:"linear",reverse:!1,nice:!0,zero:!1,domainMin:null,domainMax:null},ro={size:[4,20],alpha:[.1,1],strokeWidth:[1,4]},yt={domainMin:null,domainMax:null,nice:!1,reverse:!1},Ke={range:null,domain:null,padding:.1,reverse:!1},Mu={palette:{type:"default"}};class Lu extends dt{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),o=this.computeDataDomain(n,t);return r?this.buildPositionScale(o,t):this.buildVisualScale(o,t)}computeDataDomain(t,n){if(n.domain!==null&&n.domain.length>0)return[...n.domain];const r=new Set,o=[];for(const s of t)r.has(s)||(r.add(s),o.push(s));return o}buildPositionScale(t,n){const r=t.map(String),o=n.padding??Ke.padding,s=n.reverse?[1,0]:[0,1],a=de.scaleBand().domain(r).range(s).paddingInner(o).paddingOuter(o/2),i=a.bandwidth()/2;return this.createPositionScale(n,{map:c=>(a(String(c))??0)+i,domain:t,bandwidth:a.bandwidth(),generateTicks:()=>[...t]})}buildVisualScale(t,n){const r=t.map(String),o=n.range&&n.range.length>0?de.scaleOrdinal().domain(r).range(n.range).unknown(n.range[0]):null;return this.createVisualScale(n,{map:s=>{const a=String(s);return o?o(a):a},domain:t,generateTicks:()=>t})}}class Vu extends dt{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 Ps=["grey","red","orange","yellow","green","cyan","blue","purple","pink"],Ns=["cyan","pink","purple","red","orange","yellow","green","blue"],Wn=["#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"},ku=[q.purple,q.pink,q.yellow,q.blue,q.red,q.cyan,q.orange,q.plum,q.green,q.dark_purple],H={green:"#B2DDC9",cyan:"#A2D5E2",blue:"#AAC4FF",purple:"#B2A4FF",plum:"#DCA8C7",pink:"#FFCCD3",red:"#FFADAD",orange:"#FFDEB4",yellow:"#FDF7C3"},Eu=[H.green,H.purple,H.red,H.cyan,H.pink,H.blue,H.orange,H.plum,H.yellow],Tn={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"},Iu=[Tn.grey200,H.green,H.red,Tn.grey200],oo={dark:{1:[500],2:[600,400],3:[600,400,200],4:[600,500,300,100],5:[700,600,400,200,50],6:[600,500,400,300,200,100],7:[600,500,400,300,200,100,50],default:[700,600,500,400,300,200,100,50]},light:{1:[600],2:[700,500],3:[800,600,400],4:[800,600,400,300],5:[800,700,600,500,400],6:[800,700,600,500,400,300],7:[900,800,700,600,500,400,300],default:[900,800,700,600,500,400,300,200]}},z={cyan:"#22D3EE",pink:"#F377EF",purple:"#6528F7",red:"#FB2576",orange:"#FF9300",yellow:"#FBFF00",green:"#06FF00",blue:"#0079FF"},gt=[z.cyan,z.pink,z.purple,z.red,z.orange,z.yellow,z.green,z.blue],Cu=[z.cyan,z.green,z.red,z.cyan],bt={start:"#84D1FC",positive:"#84FC89",negative:"#FC8497",total:"#84D1FC"},Fu=[bt.start,bt.positive,bt.negative,bt.total];function Du(e,t="light",n){return((n!==void 0?oo[t][n]:void 0)??oo[t].default).map(o=>Tn[`${e}${o}`])}function _u(e){const t=gt.indexOf(z[e]);return t<=0?gt:[...gt.slice(t),...gt.slice(0,t)]}function Ru(e,t){switch(e.type){case"default":return Wn;case"graphy":return e.variant==="waterfall"?Fu:ku;case"pastel":return e.variant==="waterfall"?Iu:Eu;case"neon":return e.variant==="waterfall"?Cu:_u(e.base);case"mono":return Du(e.base,e.variant??"light",t);case"custom":return e.colors}}function Pu(e,t){if(!e)return Mu.palette;if(e.type==="custom"){const n=t[e.id];if(!n)throw new Error(`Custom palette with id "${e.id}" not found`);return{type:"custom",id:e.id,colors:n}}return e}class Nu extends dt{constructor(){super(...arguments),this.compatibleDataTypes=["categorical","temporal"]}compile(t,n){if(t.scaleType!=="palette")throw new Error("PaletteScale.compile received non-palette spec");const r=this.computeDomain(n),o=Ru(t.palette,r.length),s=o.length>0?o:[...Wn],a=de.scaleOrdinal().domain(r.map(String)).range(s).unknown(s[0]);return this.createVisualScale(t,{map:i=>a(String(i)),domain:r,generateTicks:()=>r})}computeDomain(t){const n=new Set,r=[];for(const o of t)n.has(o)||(n.add(o),r.push(o));return r}}class Ou extends Pe{constructor(){super("scale"),this.register("continuous",new xu),this.register("discrete",new Lu),this.register("datetime",new Au),this.register("identity",new Vu),this.register("palette",new Nu)}}const Os=e=>!("layers"in e),C={point:$u,line:Bu,area:Gu,bar:zu,rule:Uu};function $u(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 Bu(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 Gu(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 zu(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 Uu(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 zt={identity:Wu,count:Hu,smooth:Yu,mean:Ku};function Yu(e){return{type:"smooth",method:e.method,order:e.order,bandwidth:e.bandwidth}}function Wu(){return{type:"identity"}}function Hu(){return{type:"count"}}function Ku(){return{type:"mean"}}const pe={reshape:Xu,filter:ju,sort:qu,aggregate:Qu,constant:Zu};function Xu(e={}){return{type:"transform",transformType:"reshape",options:e}}function ju(e){return{type:"transform",transformType:"filter",options:e}}function qu(e){return{type:"transform",transformType:"sort",options:e}}function Qu(e){return{type:"transform",transformType:"aggregate",options:e}}function Zu(e){return{type:"transform",transformType:"constant",options:e}}const so="#%_ENCODED_%#",$s=e=>{if(!e.startsWith(so))return e;try{const{value:t}=JSON.parse(e.slice(so.length));return typeof t=="string"?t:e}catch{return e}},Ju=({annotations:e,dataset:t,mapping:n})=>{const r=[],o=[],s=[],a=[],i=[],c=[],l=[],u=v(n.x);for(const d of e??[])switch(d.type){case"difference-arrow":{const p=ed(d,u,t);p!==null&&r.push(p);break}case"shape":{o.push(td(d));break}case"arrow":{s.push(sd(d));break}case"highlight":break;case"text":{a.push(nd(d));break}case"sticker":{const p=rd(d,u,t);p!==null&&i.push(p);break}case"tooltip":{const p=od(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:o,freeformArrows:s,textAnnotations:a,stickers:i,pinnedNumbers:c,comments:l}},ed=(e,t,n)=>{const r=It({dataset:n,input:e.start,anchorVariable:t}),o=It({dataset:n,input:e.end,anchorVariable:t});return r===null||o===null?null:{id:e.id,start:r,end:o,label:e.show,color:e.color??null,size:e.size,labelCrossPosition:e.labelPosition}},td=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}),nd=e=>({id:e.id,content:e.content,x:e.x,y:e.y,width:e.width,backgroundColor:e.backgroundColor??null,backgroundColorStyle:e.backgroundColorStyle}),rd=(e,t,n)=>{const r=It({dataset:n,input:e,anchorVariable:t});return r===null?null:{id:e.id,anchor:r,sticker:e.sticker}},od=(e,t,n)=>{const r=It({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}}},sd=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}),It=({dataset:e,input:t,anchorVariable:n})=>{if(!h(t)||!h(t.columnKey))return null;const r=ad(t,n,e);return r===null?null:{anchorValue:r,groupValue:$s(t.columnKey)}},ad=(e,t,n)=>e.rowValue!==void 0?e.rowValue:t===null||!h(e.rowIndex)||!n.hasVariable(t)?null:n.getValues(t)[e.rowIndex]??null,Bs=["lilac","neon_pink","blackberry","sun","iceland","sunset","ultraviolet","purple","ice_cream","mint","cool","fresh"];function Gs(e){return{type:"config",config:e}}const id="#E5E5E5",cd={x:"top",y:"left"},ld=new Set(["pie","donut"]);function ud(e){return Gs({legend:hd(e.legend),axes:gd(e.axes),headline:bd(e),numberFormat:vd(e.appearance),content:Sd(e.content),appearance:dd(e.appearance,e.themeOverrides)}).config}function dd(e,t){const n=fd(e?.border),r=e?.hasRoundedCorners===!1?0:void 0,o=pd(e,t),s={};return e?.textScale!==void 0&&(s.textScale=e.textScale),n!==void 0&&(s.border=n),r!==void 0&&(s.cornerRadius=r),o!==void 0&&(s.background=o),e?.highlightStyle!==void 0&&(s.highlightStyle=e.highlightStyle==="grey"?"desaturate":"dim"),Object.keys(s).length>0?s:void 0}function pd(e,t){if(e?.backgroundModifier==="tint")return{type:"tinted"};const n=t?.graphBackground;if(typeof n=="string")return{type:"solid",color:n}}const md=e=>Bs.includes(e);function fd(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:id,width:t};if(e.style==="preset")return e.color===void 0||!md(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 hd(e){if(e)return{position:e.position}}function ao(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:cd[e]}:void 0,...t?.tickDisplayMode?{labels:{mode:t.tickDisplayMode}}:void 0,...n!==void 0?{grid:{isVisible:n}}:void 0}}function yd(e){return{...e.label!==void 0?{label:e.label}:void 0}}function gd(e){if(e)return{x:ao("x",e.x,e.showGridLines),y:ao("y",e.y,e.showGridLines),...e.y2?{ySecondary:yd(e.y2)}:void 0}}function bd(e){const{headlineNumbers:t,options:n,type:r}=e,o=r!==void 0&&ld.has(r)?n?.pieTotalPosition:void 0;if(t===void 0&&o===void 0)return;const s={};return t?.show!==void 0&&(s.show=t.show),t?.compareWith!==void 0&&(s.compareWith=t.compareWith),t?.size!==void 0&&(s.size=t.size),o!==void 0&&(s.show="total",s.position=o==="center"?"center":"above"),s}function vd(e){if(e?.numberFormat)return{decimals:e.numberFormat.decimalPlaces,abbreviation:e.numberFormat.abbreviation}}function Sd(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=xd(e.source);return n!==void 0&&(t.source=n),e.isSourceHidden!==void 0&&(t.isSourceVisible=!e.isSourceHidden),t}function xd(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})},zs={showDataLabels:!1,format:"absolute",showStackTotals:!1,showCategoryLabels:!1,labelSource:{variable:g.yRaw}},Fe={stat:{type:"identity"},position:"identity",params:{size:8}},Qe={stat:{type:"identity"},position:"identity",params:{lineWidth:"auto",interpolate:"linear",missingValues:"gap"}},Ze={stat:{type:"identity"},position:"stack",params:{lineWidth:"auto",interpolate:"linear",missingValues:"zero"}},Je={stat:{type:"identity"},position:"dodge",params:{}},ue={stat:{type:"identity"},position:"identity",interactive:!1,params:{strokeWidth:1,lineType:"dashed",labelPosition:"start"}},$e="primary";function wd(e,t){const n={...zs};return e==="bar"&&t==="polar"&&(n.format="percentage"),n}function R(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"continuous",transform:t.transform,reverse:t.reverse,nice:t.nice,zero:t.zero,clamp:t.clamp,domainMin:t.domainMin??null,domainMax:t.domainMax??null,range:t.range}}function Lt(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 Q(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"discrete",range:t.range,domain:t.domain??null,padding:t.padding,reverse:t.reverse}}function Xe(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"identity"}}function Vt(e,t){return{type:"scale",scaledAesthetic:e,scaleType:"inferred",options:t}}function Us(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"palette",palette:t.palette}}const xe={x:Object.assign(e=>Vt("x",e),{continuous:e=>R("x",e),discrete:e=>Q("x",e),datetime:e=>Lt("x",e),log:e=>R("x",{...e,transform:"log"}),sqrt:e=>R("x",{...e,transform:"sqrt"})}),y:Object.assign(e=>Vt("y",e),{continuous:e=>R("y",e),discrete:e=>Q("y",e),datetime:e=>Lt("y",e),log:e=>R("y",{...e,transform:"log"}),sqrt:e=>R("y",{...e,transform:"sqrt"})}),ySecondary:Object.assign(e=>Vt("ySecondary",e),{continuous:e=>R("ySecondary",e),discrete:e=>Q("ySecondary",e),datetime:e=>Lt("ySecondary",e),log:e=>R("ySecondary",{...e,transform:"log"}),sqrt:e=>R("ySecondary",{...e,transform:"sqrt"})}),color:{continuous:e=>R("color",e),discrete:e=>Q("color",e),palette:e=>Us("color",e)},size:{continuous:e=>R("size",e),discrete:e=>Q("size",e),identity:e=>Xe("size",e)},alpha:{continuous:e=>R("alpha",e),discrete:e=>Q("alpha",e),identity:e=>Xe("alpha",e)},strokeWidth:{continuous:e=>R("strokeWidth",e),discrete:e=>Q("strokeWidth",e),identity:e=>Xe("strokeWidth",e)},lineType:{discrete:e=>Q("lineType",e),identity:e=>Xe("lineType",e)}},Y="key",re="value",io=A("lineSeriesLabel"),co=A("barSeriesLabel"),Ct=A("constantY"),Ad=(e,t,n,r)=>Id[t](e,n,r),Hn=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]:""},Kn=e=>{const t=Hn(e),{numeric:n}=e.groupVariableNamesByType(),r=n.filter(s=>s!==t);return r.length<=1?{dataset:e,mapping:{x:t,y:r[0]??""},seriesVariables:r}:{dataset:e.reshapeFromWideToLong({keep:[t],keyName:Y,valueName:re}),mapping:{x:t,y:re,color:Y},seriesVariables:r}},Xn=e=>{const t=e.appearance?.seriesStyles;if(!t||e.seriesVariables.length===0)return{mapping:{},scales:[]};if(!e.seriesVariables.some(o=>h(t[o]?.lineStyle)))return{mapping:{},scales:[]};if(e.seriesVariables.length===1){const o=e.seriesVariables[0];if(!o)return{mapping:{},scales:[]};const s=t[o]?.lineStyle;return s?{mapping:{lineType:{value:s}},scales:[]}:{mapping:{},scales:[]}}const r=e.seriesVariables.map(o=>t[o]?.lineStyle??"solid");return{mapping:{lineType:Y},scales:[xe.lineType.discrete({domain:e.seriesVariables,range:r})]}},Td=e=>{const{categorical:t,temporal:n,numeric:r}=e.groupVariableNamesByType(),o=r[0];if(!h(o))throw new Error("No first numeric variable found");const s=r.slice(1);return s.length===0?{dataset:e.addConstantVariable(Ct,"categorical",""),mapping:{x:o,y:Ct,label:t[0]}}:s.length===1?{dataset:e,mapping:{x:o,y:s[0]??"",label:t[0]}}:{dataset:e.reshapeFromWideToLong({keep:[o,...t,...n],keyName:Y,valueName:re}),mapping:{x:o,y:re,label:t[0],color:Y}}},Md=e=>{const{categorical:t,temporal:n,numeric:r}=e.groupVariableNamesByType();let o,s;if(h(t[0])&&h(r[0]))o=t[0],s=r[0];else if(h(n[0])&&h(r[0]))o=n[0],s=r[0];else if(h(r[0])&&h(r[1]))o=r[0],s=r[1];else throw new Error("No label or value variable found");return{x:"",y:s,color:o}},Ys=(e,t,n)=>{const{dataset:r,mapping:o,seriesVariables:s}=Kn(e.dataset),a=Xn({appearance:n,seriesVariables:s}),i=[C.line({params:{lineWidth:t?.lineThickness,interpolate:t?.isSmoothLine?"catmull-rom":"linear",missingValues:t?.missingValues}})];return t?.showPoints&&i.push(C.point({params:{size:Ws(t.pointSize)},interactive:!1})),{dataset:r,layers:i,coords:B.cartesian(),mapping:{...o,...a.mapping},scales:a.scales,seriesVariables:s}},Ld=(e,t,n)=>{const{dataset:r,mapping:o,seriesVariables:s}=Kn(e.dataset),a=Xn({appearance:n,seriesVariables:s}),i=[C.area({position:"stack",params:{lineWidth:t?.lineThickness,interpolate:t?.isSmoothLine?"catmull-rom":"linear",missingValues:t?.missingValues}})];return t?.showPoints&&i.push(C.point({params:{size:Ws(t.pointSize)},position:"stack",interactive:!1})),{dataset:r,layers:i,coords:B.cartesian(),mapping:{...o,...a.mapping},scales:a.scales,seriesVariables:s}},be=(e,t,n,r,o)=>{const{dataset:s,mapping:a,seriesVariables:i}=Kn(e.dataset),c=[];if(r?.sortBars){const l=v(a.y);l!==null&&l!==""&&c.push(pe.sort({variableName:l,direction:"desc"}))}if(!o?.useSingleColorForBars){const l=Hn(e.dataset),{numeric:u}=e.dataset.groupVariableNamesByType();u.filter(p=>p!==l).length===1&&e.dataset.getType(l)==="categorical"&&(a.color=l)}return{dataset:s,layers:[C.bar({position:t})],coords:n,mapping:a,scales:[],transforms:c,seriesVariables:i}},lo=(e,t)=>({dataset:e.dataset,layers:[C.bar({position:"fill"})],coords:B.polar({theta:"y",innerRadius:t==="donut"?.55:0}),mapping:Md(e.dataset),scales:[],seriesVariables:[]}),Vd=e=>{const{dataset:t,mapping:n}=Td(e.dataset);return{dataset:t,layers:[C.point()],coords:B.cartesian(),mapping:n,scales:[],seriesVariables:[]}},kd=e=>{const{numeric:t,categorical:n}=e.dataset.groupVariableNamesByType(),r=t[0];if(!h(r))throw new Error("No first numeric variable found");const s=h(t[1])?e.dataset:e.dataset.addConstantVariable(Ct,"categorical",""),a={x:r,y:t[1]??Ct,size:t[2],label:n[0]},i=[];return h(a.size)&&i.push(xe.size.continuous()),{dataset:s,layers:[C.point()],coords:B.cartesian(),mapping:a,scales:i,seriesVariables:[]}},cn=(e,t,n)=>{const r=n?.seriesStyles?.[e]?.lineStyle;return C.line({transforms:[pe.constant({variableName:io,type:"categorical",value:e})],aes:{y:e,color:io,...r?{lineType:{value:r}}:{}},...t?{yScaleType:"secondary"}:void 0})},Ed=(e,t,n)=>{const{numeric:r,categorical:o,temporal:s}=e.dataset.groupVariableNamesByType(),a=Hn(e.dataset),i=[...o,...s],c=r.filter(b=>b!==a),l=t?.comboType??"grouped-bars",u=l==="lines";if(c.length===1)return u?Ys(e,t,n):be(e,"dodge",B.cartesian(),t,n);const d=e.axes?.hasDualYAxis===!0,p=u?[]:c.slice(0,-1),m=u?c:c.slice(-1),f=[],y=[];if(p.length>0){const b=l==="stacked-bars"?"stack":"dodge",x=p.length===1?p[0]:null;h(x)?f.push(C.bar({transforms:[pe.constant({variableName:co,type:"categorical",value:x})],aes:{y:x,color:co},position:b})):f.push(C.bar({transforms:[pe.reshape({keep:i,reshape:p,keyName:Y,valueName:re})],aes:{y:re,color:Y},position:b}))}if(u&&m.length>=2){const b=d?m.slice(0,-1):m,x=b.length===1?b[0]:null;if(h(x))f.push(cn(x,!1,n));else{const S=Xn({appearance:n,seriesVariables:b});f.push(C.line({transforms:[pe.reshape({keep:i,reshape:b,keyName:Y,valueName:re})],aes:{y:re,color:Y,...S.mapping}})),y.push(...S.scales)}if(d){const S=m[m.length-1];h(S)&&f.push(cn(S,!0,n))}}else for(const b of m)f.push(cn(b,d,n));return{dataset:e.dataset,layers:f,coords:B.cartesian(),mapping:{x:a},scales:y,seriesVariables:c}},Ws=(e="auto")=>e==="auto"?Fe.params.size:e,We=e=>()=>{throw new Error(`Unsupported graph type: ${e}`)},Id={line:(e,t,n)=>Ys(e,t,n),areaStacked:(e,t,n)=>Ld(e,t,n),bar:(e,t,n)=>be(e,"dodge",B.flip(),t,n),barStacked:(e,t,n)=>be(e,"stack",B.flip(),t,n),barStackedFill:(e,t,n)=>be(e,"fill",B.flip(),t,n),column:(e,t,n)=>be(e,"dodge",B.cartesian(),t,n),columnStacked:(e,t,n)=>be(e,"stack",B.cartesian(),t,n),columnStackedFill:(e,t,n)=>be(e,"fill",B.cartesian(),t,n),pie:e=>lo(e,"pie"),donut:e=>lo(e,"donut"),scatter:e=>Vd(e),bubble:e=>kd(e),combo:(e,t,n)=>Ed(e,t,n),funnel:We("funnel"),heatmap:We("heatmap"),waterfall:We("waterfall"),mekko:We("mekko"),table:We("table")},Hs=["key",A("lineSeriesLabel"),A("barSeriesLabel")];function Cd(e){const t=e.annotations??[],n=Fd(e.mapping),r=Rd(e.convertedDataset,e.layers),o=[];for(const s of t){if(s.type!=="highlight")continue;const a=Dd({annotation:s,rowIdentityVariable:n,dataset:e.dataset,compiledVariableNames:r});a!==null&&o.push({type:"highlight",id:s.id,predicate:a,scope:s.highlight})}return o}function Fd(e){const t=v(e.x);return t!==null&&t!==""?t:v(e.color)}function Dd({annotation:e,rowIdentityVariable:t,dataset:n,compiledVariableNames:r}){switch(e.highlight){case"x-value":return uo(e,t,n);case"series":return po(e,r);case"data-point":{const o=uo(e,t,n),s=po(e,r);return o===null&&s===null?null:o===null?s:s===null?o:{and:[o,s]}}}}function uo(e,t,n){if(t===null)return null;const r=Od(e,t,n);return r===null?null:{variable:t,eq:r}}function po(e,t){if(!_d(t))return null;const n=e.columnKey;return h(n)?{or:Hs.map(r=>({variable:r,eq:n}))}:null}function _d(e){return Hs.some(t=>e.includes(t))}function Rd(e,t){const n=[...e.getVariableNames()];for(const r of t)for(const o of r.transforms??[])Pd(o)?n.push(o.options.keyName??Y):Nd(o)&&n.push(o.options.variableName);return n}const Pd=e=>e.transformType==="reshape",Nd=e=>e.transformType==="constant";function Od(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 $d(e,t,n){const{theme:r,customPalettes:o}=n;if(o&&e&&o[e])return{type:"custom",id:e};if(e?.startsWith("preset:pastel"))return{type:"pastel",variant:ln(t)};if(e?.startsWith("preset:graphy"))return{type:"graphy",variant:ln(t)};const i="preset:mono:";if(e?.startsWith(i)){const l=e.slice(i.length);if(Bd(l))return{type:"mono",base:l,variant:r}}const c="preset:neon:";if(e?.startsWith(c)){const l=e.slice(c.length);if(Gd(l))return{type:"neon",base:l,variant:ln(t)}}return{type:"default"}}function ln(e){if(e==="waterfall")return"waterfall"}function Bd(e){return Ps.includes(e)}function Gd(e){return Ns.includes(e)}function zd(e,t,n,r={}){const o=[];o.push(mo("x",t?.x)),o.push(mo("y",t?.y));const s=$d(n?.paletteId,e,r);return o.push(xe.color.palette({palette:s})),o}function mo(e,t){return t?.scaleType==="logarithmic"||t?.min!==void 0||t?.max!==void 0?t.scaleType==="logarithmic"?xe[e].log({domainMin:t.min??void 0,domainMax:t.max??void 0}):xe[e]({domainMin:t.min??void 0,domainMax:t.max??void 0}):xe[e]()}const Ud=new Set(["column","columnStacked","columnStackedFill","bar","barStacked","barStackedFill","line","areaStacked","scatter","bubble","funnel","combo"]),Yd=new Set(["column","columnStacked","columnStackedFill","bar","barStacked","barStackedFill","line","areaStacked","combo"]);function Wd(e,t,n){const r=t.type??"column",o={dataset:e,axes:t.axes},s=Ad(o,r,t.options??void 0,t.appearance??void 0);return{data:s.dataset,mapping:s.mapping,layers:Hd(r,t,s.layers,s.coords,s.mapping,s.seriesVariables),scales:[...zd(r,t.axes,t.appearance,n),...s.scales],transforms:s.transforms??[],highlights:Cd({annotations:t.annotations,dataset:e,mapping:s.mapping,convertedDataset:s.dataset,layers:s.layers}),annotations:Ju({annotations:t.annotations,dataset:e,mapping:s.mapping}),coords:s.coords,config:ud(t)}}function Hd(e,t,n,r,o,s){const a=Qd(t.dataLabels),i=a===void 0?n:n.filter(l=>l.interactive!==!1).map(l=>({...l,dataLabels:{...a,...l.dataLabels}})),c=t.axes?.hasDualYAxis??!1;return[...i,...Kd({type:e,trendline:t.referenceLines?.trendline,coords:r}),...Xd({type:e,hasDualYAxis:c,goalLine:t.referenceLines?.goalLine,coords:r}),...qd({type:e,hasDualYAxis:c,averageLine:t.referenceLines?.averageLine,coords:r,mapping:o,seriesVariables:s})]}function Kd({type:e,trendline:t,coords:n}){return t===void 0?[]:Ud.has(e)?n.coordType==="polar"?[]:[C.line({aes:{lineType:{value:"dashed"}},stat:zt.smooth({method:t}),interactive:!1})]:[]}function Xd({type:e,hasDualYAxis:t,goalLine:n,coords:r}){if(!jd(n))return[];if(r.coordType==="polar")return[];const o=r.coordType==="flip"?"end":"start";return[C.rule({aes:{y:{value:n.target}},params:{labelPosition:o,label:n.label??"Goal"},yScaleType:e==="combo"&&t?"secondary":"primary",interactive:!1})]}function jd(e){return e!==void 0&&Number.isFinite(e.target)}function qd({type:e,hasDualYAxis:t,averageLine:n,coords:r,mapping:o,seriesVariables:s}){if(n===void 0)return[];if(!Yd.has(e))return[];if(r.coordType==="polar")return[];const a=$s(n.columnKey);if(!s.includes(a))return[];const i=o.color===Y,c=i?re:a,l=i?[pe.filter({variableName:Y,operator:"eq",value:a})]:[];return[C.rule({aes:{y:c,color:void 0,group:void 0,lineType:void 0},stat:zt.mean(),transforms:l,params:{label:"Average",labelPosition:r.coordType==="flip"?"end":"start"},yScaleType:e==="combo"&&t?"secondary":"primary",interactive:!1})]}function Qd(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 un={color:null,size:"small",labelCrossPosition:.5},Ee={kind:"rectangle",zOrder:"foreground",fillColor:"transparent",fillOpacity:1,strokeWidth:1,strokeColor:null},fo={backgroundColor:null,backgroundColorStyle:"opaque"},Ie={color:null,thickness:"medium",startArrowheadStyle:"none",endArrowheadStyle:"line-arrow",lineStyle:"solid",hasStickerStyle:!1},Zd=(e,t)=>({differenceArrows:(e?.differenceArrows??[]).map(n=>np(n,t)),shapes:(e?.shapes??[]).map(ap),freeformArrows:(e?.freeformArrows??[]).map(ip),textAnnotations:(e?.textAnnotations??[]).map(tp),stickers:(e?.stickers??[]).map(n=>rp(n,t)),pinnedNumbers:(e?.pinnedNumbers??[]).map(n=>op(n,t)),comments:(e?.comments??[]).map(n=>sp(n,t)),custom:(e?.custom??[]).map(n=>Jd(n,t))}),Jd=(e,t)=>({id:e.id??crypto.randomUUID(),type:e.type,coordinates:e.coordinates.map(n=>ep(n,t)),params:e.params??{},zOrder:e.zOrder??null}),ep=(e,t)=>"observation"in e?{observation:De(e.observation,t)}:e,tp=e=>({id:e.id??crypto.randomUUID(),content:e.content,x:e.x,y:e.y,width:e.width,backgroundColor:e.backgroundColor??fo.backgroundColor,backgroundColorStyle:e.backgroundColorStyle??fo.backgroundColorStyle}),np=(e,t)=>({id:e.id??crypto.randomUUID(),start:De(e.start,t),end:De(e.end,t),label:e.label,color:e.color??un.color,size:e.size??un.size,labelCrossPosition:e.labelCrossPosition??un.labelCrossPosition}),De=(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}},rp=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:De(e.anchor,t),sticker:e.sticker}),op=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:De(e.anchor,t)}),sp=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:De(e.anchor,t),content:e.content}),ap=e=>({id:e.id??crypto.randomUUID(),kind:e.kind??Ee.kind,zOrder:e.zOrder??Ee.zOrder,x:e.x,y:e.y,width:e.width,height:e.height,fillColor:e.fillColor??Ee.fillColor,fillOpacity:e.fillOpacity??Ee.fillOpacity,strokeWidth:e.strokeWidth??Ee.strokeWidth,strokeColor:e.strokeColor??Ee.strokeColor}),ip=e=>({id:e.id??crypto.randomUUID(),start:e.start,end:e.end,color:e.color??Ie.color,thickness:e.thickness??Ie.thickness,startArrowheadStyle:e.startArrowheadStyle??Ie.startArrowheadStyle,endArrowheadStyle:e.endArrowheadStyle??Ie.endArrowheadStyle,lineStyle:e.lineStyle??Ie.lineStyle,hasStickerStyle:e.hasStickerStyle??Ie.hasStickerStyle}),Ks={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 cp(e){return ie.merge({},Ks,e)}const lp={xLimits:null,yLimits:null},dn={theta:"x",startAngle:0,innerRadius:0};function up(e){const t=e??{type:"coord",coordType:"cartesian"},n=$o({},lp,t.params??{});switch(t.coordType){case"cartesian":case"flip":return{...t,params:n};case"polar":return{...t,params:{...n,theta:t.params?.theta??dn.theta,startAngle:t.params?.startAngle??dn.startAngle,innerRadius:t.params?.innerRadius??dn.innerRadius}}}}function dp(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 pp="linear",mp=3,fp=.3;function Be(e,t){return Array.isArray(e)?e.length===0?[pn(void 0,t)]:e.map(n=>pn(n,t)):[pn(e,t)]}function pn(e,t){const n=e??t;return typeof n=="string"?n==="smooth"?ho(void 0):{type:n}:n.type==="smooth"?ho(n):n}function ho(e){return{type:"smooth",method:e?.method??pp,order:e?.order??mp,bandwidth:e?.bandwidth??fp}}function Xs(e,t,n){if(!gp(n))return bp(e,t,n);switch(n.geom){case"point":return vp(e,t,n);case"line":return Sp(e,t,n);case"area":return xp(e,t,n);case"bar":return wp(e,t,n);case"rule":return Ap(e,t,n)}}function hp(e,t,n){const r=n.map(o=>Xs(e,t,o));return Tp(r)}const yp=(e,t,n)=>n.label!==void 0?n.label:Mp(e,t,n),gp=e=>Vs(e.geom);function bp(e,t,n){const r=n.position??"identity";return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Be(n.stat,"identity"),position:r,yScaleType:n.yScaleType??$e,params:n.params??{},transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Ge(e,n,r,t)}}const Ge=(e,t,n,r)=>{const o={...e,...t.mapping},s=yp(t.geom,n,o);return{...wd(t.geom,r),...t.dataLabels,labelSource:s}};function vp(e,t,n){const r=n.position??Fe.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Be(n.stat,Fe.stat.type),position:r,yScaleType:n.yScaleType??$e,params:ie.merge({},Fe.params,n.params),transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Ge(e,n,r,t)}}function Sp(e,t,n){const r=n.position??Qe.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Be(n.stat,Qe.stat.type),position:r,yScaleType:n.yScaleType??$e,params:ie.merge({},Qe.params,n.params),transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Ge(e,n,r,t)}}function xp(e,t,n){const r=ie.merge({},Ze.params,n.params);r.missingValues==="gap"&&(r.missingValues="zero");const o=n.position??Ze.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Be(n.stat,Ze.stat.type),position:o,yScaleType:n.yScaleType??$e,params:r,transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Ge(e,n,o,t)}}function wp(e,t,n){const r=n.position??Je.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Be(n.stat,Je.stat.type),position:r,yScaleType:n.yScaleType??$e,params:{...Je.params,...n.params},transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:Ge(e,n,r,t)}}function Ap(e,t,n){const r=n.position??ue.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Be(n.stat,ue.stat.type),position:n.position??ue.position,yScaleType:n.yScaleType??$e,params:ie.merge({},ue.params,n.params),transforms:n.transforms??[],interactive:n.interactive??ue.interactive,dataLabels:Ge(e,n,r,t)}}const Tp=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=se(n.mapping.y);if(!F(r))return n;const o=Math.min(1,Math.max(0,r));return{...n,mapping:{...n.mapping,y:{value:o}}}})},Mp=(e,t,n)=>{if(e==="point"){const r=v(n.size);if(r!==null)return{variable:r}}return ut(t,n)};function Ut(e,...t){return e?t.includes(e.geom):!1}function Yt(e,t){return e.find(n=>n.id===t)}function pt(e,...t){return e.find(n=>t.includes(n.geom))}function jn(e,t,n){const r=e.layers.findIndex(s=>s.id===t);if(r===-1)return e;const o=e.layers.map((s,a)=>a===r?n:s);return{...e,layers:o}}function Lp(e,t){const n=e.layers.findIndex(o=>o.id===t);if(n===-1||e.layers.length<=1)return e;const r=e.layers.filter((o,s)=>s!==n);return Fn(r)?{...e,layers:r}:e}const js={x:"position",y:"position",ySecondary:"position",color:"color-range",size:"continuous-range",alpha:"continuous-range",strokeWidth:"continuous-range",lineType:"discrete-only"},Vp={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 qs(e,t,n,r,o){switch(e.scaleType){case"inferred":{const s=Ip(e,t,n,r);return qs(s,t,n,r,o)}case"continuous":{const s=js[e.scaledAesthetic],a=s==="continuous-range"&&e.scaledAesthetic in ro?ro[e.scaledAesthetic]:null,i=e.scaledAesthetic==="size"&&s==="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??s!=="position",domainMin:e.domainMin??ke.domainMin,domainMax:e.domainMax??ke.domainMax,range:e.range??a??null}}case"datetime":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,domainMin:e.domainMin??yt.domainMin,domainMax:e.domainMax??yt.domainMax,nice:e.nice??yt.nice,reverse:e.reverse??yt.reverse,clamp:e.clamp??!1};case"discrete":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,range:e.range??Ke.range,domain:e.domain??Ke.domain,padding:e.padding??Ke.padding,reverse:e.reverse??Ke.reverse};case"palette":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,palette:Pu(e.palette,o)};case"identity":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType};default:{const s=e;throw new Error(`Unknown scale type: ${s.scaleType}`)}}}function kp(e,t,n,r,o,s){const a=Fp(t,n),i=Dp(a),c=new Map;for(const u of i)c.set(u.scaledAesthetic,u);const l=[...c.values()].map(u=>qs(u,e,n,r,s));return o.coordType==="polar"?Ep(l):l}const Ep=e=>e.map(t=>t.scaleType==="discrete"?{...t,padding:0}:t);function Ip(e,t,n,r){const o=ee(e.scaledAesthetic),s=e.scaledAesthetic==="ySecondary"?Cp(n,r):r[o],a=pt(n,"bar");if(e.scaledAesthetic==="x"&&a)return Q(e.scaledAesthetic,e.options);if(a&&e.scaledAesthetic===(a.yScaleType==="secondary"?"ySecondary":"y")){const d=e.options,p=a.position==="fill";return R(e.scaledAesthetic,{...d,zero:!0,...p&&{nice:!1}})}const i=v(s);if(!h(i)||!t.hasVariable(i))return R(e.scaledAesthetic,e.options);const c=t.getType(i),l=js[e.scaledAesthetic];switch(Vp[c][l]){case"discrete":return Q(e.scaledAesthetic,e.options);case"datetime":return Lt(e.scaledAesthetic,e.options);case"continuous":return R(e.scaledAesthetic,e.options);case"identity":default:return Xe(e.scaledAesthetic)}}function Cp(e,t){const n=e.find(r=>r.yScaleType==="secondary");return n?n.mapping.y??t.y:t.y}function Fp(e,t){return!t.some(o=>o.yScaleType==="secondary")||e.some(o=>o.scaledAesthetic==="ySecondary")?e:[...e,Vt("ySecondary")]}function Dp(e){return e.some(n=>n.scaledAesthetic==="color")?e:[...e,Us("color")]}function yo(e,t){const n=up(e.coords),r=hp(e.mapping,n.coordType,e.layers),o=kp(e.data,e.scales,r,e.mapping,n,t),s=cp(e.config),a=dp(e.highlights,r),i=Zd(e.annotations,r);return{data:e.data,mapping:e.mapping,layers:r,scales:o,transforms:e.transforms,highlights:a,annotations:i,coords:n,config:s}}class Qs{compile({input:t,dataset:n,ctx:r}){const o=r.customPalettes??{};return Os(t)?yo(Wd(n,t,r),o):yo({...t,data:n},o)}}class _p{constructor(t){this.registry=t}compute(t,n){let r=n.data,o=n.mapping;const s={};for(const a of t){const i=this.registry.get(a.type).compute({data:r,mapping:o,spec:a,xScaleIsDiscrete:n.xScaleIsDiscrete});r=i.data,o={...o,...i.mapping},Object.assign(s,i.mapping)}return{data:r,mapping:s}}}class ze{compute(t){return t.data.size()===0?{data:t.data,mapping:{}}:this.computeStat(t)}}class Rp extends ze{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 s=[...new Set([r,...On(t,n)])];return{data:t.groupBy(...s).rollup({[et.count]:{variableName:r,aggregation:"count"}}),mapping:{y:et.count}}}}class Pp extends ze{constructor(){super(...arguments),this.type="identity",this.computedVariables=new Set}computeStat({data:t}){return{data:t,mapping:{}}}}class Np extends ze{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({[et.mean]:{variableName:r,aggregation:"mean"}}),mapping:{y:et.mean}}}}const Op=2,Zs=1440*60*1e3;class $p extends ze{constructor(){super(...arguments),this.type="smooth",this.computedVariables=new Set}computeStat({data:t,mapping:n,spec:r,xScaleIsDiscrete:o}){if(r.type!=="smooth")throw new Error(`SmoothStat received a spec of type '${r.type}'`);const s=r,a=v(n.x),i=v(n.y);if(!h(a))throw new Error("'x' variable is required for 'smooth' stat");if(!h(i))throw new Error("'y' variable is required for 'smooth' stat");const c=t.getType(a),l=t.getType(i);if(l!=="numeric")throw new Error(`'smooth' stat requires a numeric 'y' (got '${l}' for variable '${i}')`);const u=On(t,n),d=Hp(a,c,i,u,t);return u.length===0?go({data:t,xVariable:a,xType:c,yVariable:i,spec:s,output:d,groupObservation:{},xScaleIsDiscrete:o}):t.groupBy(...u).forEach(p=>{const m=Kp(p,u);go({data:p,xVariable:a,xType:c,yVariable:i,spec:s,output:d,groupObservation:m,xScaleIsDiscrete:o})}),{data:d.build(),mapping:{}}}}const go=({data:e,xVariable:t,xType:n,yVariable:r,spec:o,output:s,groupObservation:a,xScaleIsDiscrete:i})=>{const{observations:c,temporalOrigin:l}=Bp({data:e,xVariable:t,yVariable:r,xType:n});c.length<Op||(i?Wp({observations:c,spec:o,output:s,groupObservation:a}):Up({observations:c,xType:n,temporalOrigin:l,spec:o,output:s,groupObservation:a}))},Bp=({data:e,xVariable:t,yVariable:n,xType:r})=>{const o=e.getValues(t),s=e.getValues(n,{type:"numeric"}),a=r==="temporal"?Gp(o):null,i=[],c=new Map;for(let l=0;l<o.length;l++){const u=o[l],d=s[l];if(!h(u)||!h(d)||!Number.isFinite(d))continue;const p=zp({xValue:u,xType:r,categoryRank:c,temporalOrigin:a});p!==null&&i.push({x:p,y:d,originalX:u})}return{observations:i,temporalOrigin:a}},Gp=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},zp=({xValue:e,xType:t,categoryRank:n,temporalOrigin:r})=>{switch(t){case"numeric":return!F(e)||!Number.isFinite(e)?null:e;case"temporal":{if(!G(e))return null;const o=e.getTime();return r===null?o:(o-r)/Zs+1}case"categorical":{if(!at(e))return null;const o=n.get(e);if(o!==void 0)return o;const s=n.size+1;return n.set(e,s),s}default:{const o=t;throw new Error(`Unexpected xType: ${o}`)}}},Up=({observations:e,xType:t,temporalOrigin:n,spec:r,output:o,groupObservation:s})=>{const a=Js(r,e);for(const[i,c]of a){if(!Number.isFinite(i)||!Number.isFinite(c))continue;const l=t==="temporal"?Yp(i,n):i;o.push({x:l,y:c,groupObservation:s})}},Yp=(e,t)=>t===null?new Date(e):new Date((e-1)*Zs+t),Wp=({observations:e,spec:t,output:n,groupObservation:r})=>{const o=new Map;for(const i of e)o.has(i.x)||o.set(i.x,i.originalX);const s=[...o.keys()].sort((i,c)=>i-c);if(t.method==="loess"){const i=Js(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 s){const u=c.get(l),d=o.get(l);u===void 0||d===void 0||n.push({x:d,y:u,groupObservation:r})}return}const a=ea(t,e);for(const i of s){const c=o.get(i),l=a.predict(i);c===void 0||!Number.isFinite(l)||n.push({x:c,y:l,groupObservation:r})}},Js=(e,t)=>e.method==="loess"?ge.regressionLoess().x(r=>r.x).y(r=>r.y).bandwidth(e.bandwidth)(t):ea(e,t),ea=(e,t)=>{const n=o=>o.x,r=o=>o.y;switch(e.method){case"linear":return ge.regressionLinear().x(n).y(r)(t);case"exponential":return ge.regressionExp().x(n).y(r)(t);case"logarithmic":return ge.regressionLog().x(n).y(r)(t);case"quadratic":return ge.regressionQuad().x(n).y(r)(t);case"power":return ge.regressionPow().x(n).y(r)(t);case"polynomial":return ge.regressionPoly().x(n).y(r).order(e.order)(t);case"loess":throw new Error("'loess' does not expose a 'predict' function")}},Hp=(e,t,n,r,o)=>{const s=[],a=[],i=Object.fromEntries(r.map(c=>[c,[]]));return{push:({x:c,y:l,groupObservation:u})=>{s.push(c),a.push(l);for(const d of r)i[d]?.push(u[d]??null)},build:()=>{const c={[e]:{type:t,values:s,valueFormat:o.getValueFormat(e)},[n]:{type:"numeric",values:a,valueFormat:o.getValueFormat(n)}};for(const l of r)c[l]={type:o.getType(l),values:i[l]??[],valueFormat:o.getValueFormat(l)};return new V(c)}}},Kp=(e,t)=>{const n={};for(const r of t){const o=e.getValues(r);n[r]=o[0]??null}return n};class Xp extends Pe{constructor(t){super("stat"),this.register("identity",new Pp),this.register("count",new Rp),this.register("smooth",new $p),this.register("mean",new Np);for(const n of t?.stats??[])this.register(n.type,n)}}const jp=({layer:e})=>{if(e.position==="stack")return;const t=v(e.mapping.y);if(t===null)return;let n=0,r=0;for(const o of e.data){const s=o[t];F(s)&&(n+=s,r+=Math.abs(s))}return{grandTotal:n,absoluteGrandTotal:r}},qp=({layer:e})=>{if(e.position!=="stack")return;const t=v(e.mapping.x);if(t===null||!e.data.hasVariable(g.yMin)||!e.data.hasVariable(g.yMax))return;const n=new Map;for(const o of e.data){const s=o[t],a=Ae(o),i=J(o),c=nt(o),l=Ce(o),u=gs(o);if(!h(s)||!h(a)||!h(i)||!h(c)||!h(l)||!h(u))continue;const d=u>=0;if(Math.abs(u)===0)continue;const m=Gn(o,t),f={yMin:a,yMax:i},y=n.get(m);if(y===void 0){n.set(m,{total:u,topPositive:d?f:null,bottomNegative:d?null:f,anchorXMin:c,anchorXMax:l});continue}y.total+=u,d?(y.topPositive===null||i>y.topPositive.yMax)&&(y.topPositive=f):(y.bottomNegative===null||a<y.bottomNegative.yMin)&&(y.bottomNegative=f)}const r=[];for(const[o,s]of n){const a=s.topPositive??s.bottomNegative;a!==null&&r.push({xKey:o,total:s.total,anchor:{xMin:s.anchorXMin,xMax:s.anchorXMax,yMin:a.yMin,yMax:a.yMax,direction:s.topPositive!==null?"positive":"negative"}})}return r};class Qp extends Re{constructor(t){super(),this.geomCompiler=t}dependencies(){return[]}compileLayer(t){const n={};if(this.geomCompiler.emitsStackTotals(t.geom)){const r=qp({layer:t});r!==void 0&&(n.stackTotals=r)}if(this.geomCompiler.emitsGrandTotal(t.geom)){const r=jp({layer:t});r!==void 0&&(n.grandTotal=r.grandTotal,n.absoluteGrandTotal=r.absoluteGrandTotal)}return{...t,summary:n}}}class Zp extends me{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 Jp{constructor(){this.transformType="aggregate"}apply(t,n){const{options:r}=n,o={};for(const s of r.operations)o[s.as]={variableName:s.variableName,aggregation:s.op};return t.groupBy(...r.groupby).rollup(o)}}class em{constructor(){this.transformType="constant"}apply(t,n){const{options:r}=n;return t.addConstantVariable(r.variableName,r.type,r.value)}}class tm{constructor(){this.transformType="filter"}apply(t,n){const{options:r}=n;return t.filter(r.variableName,r.operator,r.value)}}class nm{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 rm{constructor(){this.transformType="sort"}apply(t,n){const{options:r}=n;return t.orderBy(r.variableName,r.direction??"asc")}}class om extends Pe{constructor(t){super("transform"),this.register("aggregate",new Jp),this.register("constant",new em),this.register("filter",new tm),this.register("reshape",new nm),this.register("sort",new rm);for(const n of t?.transforms??[])this.register(n.transformType,n)}}const bo={color:"categorical",size:"numeric",alpha:"numeric",strokeWidth:"numeric",lineType:"categorical"};class sm extends Re{constructor(t){super(),this.geomCompiler=t}dependencies(t){return[...Ot].map(n=>t.scales[n])}compileLayer(t,n){const r=this.geomCompiler.getVisualAesthetics(t.geom),o=am(t.data,t.mapping,r,n.scales);return{...t,data:o}}}function am(e,t,n,r){let o=e;for(const s of n){const a=fe[s],i=se(t[s]);if(i!==void 0){o=o.deriveVariable(a,bo[s],()=>i);continue}const c=v(t[s]),l=r[s];if(!l||l.kind!=="visual")continue;const u=im(s,c,l);u&&(o=o.deriveVariable(a,bo[s],u))}return o}const im=(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},cm=["data","transform","constantMapping","layer","coordSetup","scale","positionMapper","visualMapper","coordTransform","summarise","guide","highlights","config","annotations"];class ta{constructor(t,n,r,o,s,a,i,c,l,u,d,p,m,f,y){this.dataCompiler=t,this.specCompiler=n,this.transformCompiler=r,this.constantMappingCompiler=o,this.layerValidationCheck=s,this.layerCompiler=a,this.scaleCompiler=i,this.coordCompiler=c,this.positionMapperCompiler=l,this.visualMapperCompiler=u,this.guideCompiler=d,this.summariseCompiler=p,this.highlightsCompiler=m,this.configCompiler=f,this.annotationsCompiler=y,this.lastCompile=null,this.lastData=void 0,this.stages=[{name:"data",getStats:()=>this.dataCompiler.stats},{name:"transform",getStats:()=>this.transformCompiler.stats},{name:"constantMapping",getStats:()=>this.constantMappingCompiler.stats},{name:"layer",getStats:()=>this.layerCompiler.stats},{name:"coordSetup",getStats:()=>this.coordCompiler.setupStats},{name:"scale",getStats:()=>this.scaleCompiler.stats},{name:"positionMapper",getStats:()=>this.positionMapperCompiler.stats},{name:"visualMapper",getStats:()=>this.visualMapperCompiler.stats},{name:"coordTransform",getStats:()=>this.coordCompiler.transformStats},{name:"summarise",getStats:()=>this.summariseCompiler.stats},{name:"guide",getStats:()=>this.guideCompiler.stats},{name:"highlights",getStats:()=>this.highlightsCompiler.stats},{name:"config",getStats:()=>this.configCompiler.stats},{name:"annotations",getStats:()=>this.annotationsCompiler.stats}]}compile({input:t,data:n,ctx:r={}}){return this.trackCompile(()=>(this.lastData=n,this.runPipeline({spec:this.specCompiler.compile({input:t,ctx:r,dataset:this.dataCompiler.compile(n)})})))}recompile({spec:t,data:n}){return this.trackCompile(()=>n===void 0?this.runPipeline({spec:t}):(this.lastData=n,this.runPipeline({spec:rn(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(!Se)return t();const n=this.getCacheStats(),r=performance.now(),o=t(),s=performance.now()-r,a={};for(const{name:i,getStats:c}of this.stages){const l=c();a[i]={hits:l.hits-n[i].hits,misses:l.misses-n[i].misses}}return this.lastCompile={stages:a,durationMs:s},o}runPipeline({spec:t}){return _t({spec:t}).pipe(({spec:r})=>({spec:rn(r,{data:this.transformCompiler.compile({data:r.data,transforms:r.transforms})})})).pipe(({spec:r})=>{const o=this.constantMappingCompiler.compile({data:r.data,mapping:r.mapping});return{spec:rn(r,{data:o.data,mapping:o.mapping})}}).pipe(({spec:r})=>{const o={data:r.data,layers:r.layers,mapping:r.mapping,coords:r.coords,scales:r.scales};return this.layerValidationCheck.check({...o,coords:r.coords}),{layers:this.layerCompiler.compile(o)}}).pipe(({spec:r,layers:o})=>this.coordCompiler.setup({coordSpec:r.coords,scales:r.scales,layers:o})).pipe(({layers:r,scales:o})=>({scales:this.scaleCompiler.compile({layers:r,scales:o})})).pipe(({spec:r,scales:o})=>({config:this.configCompiler.compile({config:r.config,scales:o})})).pipe(({layers:r,scales:o})=>({layers:this.positionMapperCompiler.compile({layers:r,scales:o})})).pipe(({layers:r,scales:o})=>({layers:this.visualMapperCompiler.compile({layers:r,scales:o})})).pipe(({spec:r,layers:o})=>({layers:this.coordCompiler.transform({coordSpec:r.coords,layers:o})})).pipe(({layers:r})=>({layers:this.summariseCompiler.compile({layers:r})})).pipe(({spec:r,scales:o,layers:s,coordSystem:a})=>({guides:this.guideCompiler.compile({scales:o,config:r.config,layers:s,coordSystem:a,originalData:this.lastData})})).pipe(({spec:r,layers:o})=>({layers:this.highlightsCompiler.compile({layers:o,highlights:r.highlights,config:r.config})})).pipe(({spec:r,layers:o,coordSystem:s,scales:a})=>({annotations:this.annotationsCompiler.compile({annotations:r.annotations,layers:o,coordSystem:s,scales:a})})).result()}}const lm=e=>{const t=new Sc({geoms:e?.geoms}),n=new mc(t),r=new Xp({stats:e?.stats}),o=new Ou,s=new Zp(new om({transforms:e?.transforms}));return new ta(new cc,new Qs,s,new ui,new nu(s,new ru(t,r)),new tu(s,new _p(r),new xc,n,new su(new uu)),new Su(o),new fi(new Vi(t)),new vu(t),new sm(n),new Cl(n),new Qp(n),new zl,new li,new ei(n))};function um(e,t){return e.geom===t}const qn="–",na="n/a",$={timeZone:"UTC"},O=e=>t=>{if(!G(t))return qn;try{return e(t)}catch{return na}},he=e=>t=>F(t)?e(t):qn,Qn=e=>t=>at(t)?t:qn,dm=2,pm=3,mm=2,fm=0,hm=1,ym=2,gm=Na.humanizer({language:"en",spacer:"",delimiter:" ",languages:{en:{y:()=>"y",mo:()=>"mo",w:()=>"w",d:()=>"d",h:()=>"h",m:()=>"m",s:()=>"s",ms:()=>"ms"}}}),ra=({valueFormat:e,locale:t,numberFormat:n,intlOptions:r})=>he(o=>{const s=typeof n.decimals=="number"?n.decimals:dm,a=tr(o,s),{base:i,suffix:c}=er(o,n.abbreviation),l={...a,...Jo(e)?{style:"currency",currencyDisplay:"narrowSymbol",currency:e.iso}:{},...r};return`${Intl.NumberFormat(t,l).format(i)}${c}`}),Zn=({locale:e,numberFormat:t,intlOptions:n})=>he(r=>{const{base:o,suffix:s}=er(r,t.abbreviation),i={...tr(o,t.decimals),...n};return`${Intl.NumberFormat(e,i).format(o)}${s}`}),Jn=e=>he(t=>gm(t)),oa=({locale:e,intlOptions:t})=>he(n=>Intl.NumberFormat(e,{maximumFractionDigits:0,...t}).format(n)),sa=({locale:e,numberFormat:t,intlOptions:n})=>he(r=>{const o=tr(r,t.decimals);return Intl.NumberFormat(e,{...o,...n,style:"percent"}).format(r)}),er=(e,t="none")=>{switch(t){case"none":return{base:e,suffix:""};case"auto":{const n=bm(e);return er(e,n)}default:return{base:e/qe[t],suffix:t}}},tr=(e,t)=>{if(typeof t=="number")return{minimumFractionDigits:t,maximumFractionDigits:t};const n=Math.ceil(Math.log10(Math.abs(e))),r=n>=pm?fm:n===mm?hm:ym;return{minimumFractionDigits:t==="auto"?0:r,maximumFractionDigits:r}},bm=e=>{const t=Math.abs(e);return t>=qe.b?"b":t>=qe.m?"m":t>=qe.k?"k":"none"},vm=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{dateStyle:"medium",...$,...t}).format(n)),Sm=({locale:e,intlOptions:t})=>O(n=>{const r=Intl.DateTimeFormat(e,{dateStyle:"medium",timeStyle:"medium",...$,...t}).formatToParts(n);return xm(r.map(wm))}),aa=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"long",...$,...t}).format(n)),ia=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{month:"long",...$,...t}).format(n)),nr=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{month:"short",year:"numeric",...$,...t}).format(n)),rr=e=>O(t=>`Q${Math.floor(t.getUTCMonth()/3)+1} ${t.getUTCFullYear()}`),ca=({locale:e,intlOptions:t})=>O(n=>{const r=k.addDays(n,6);return Intl.DateTimeFormat(e,{day:"numeric",month:"long",...$,...t,year:void 0}).formatRange(n,r)}),la=({locale:e,intlOptions:t})=>O(n=>{const r=k.addDays(n,6);return Intl.DateTimeFormat(e,{dateStyle:"medium",...$,...t}).formatRange(n,r)}),or=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{year:"numeric",...$,...t}).format(n)),ua=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{timeStyle:"short",...$,...t}).format(n)),xm=e=>e.map(t=>t.value).join(""),wm=e=>e.type!=="literal"||e.value!==", "?e:{type:"literal",value:" • "},Am=1,Tm=4,Mm=1,vo=1e3,Lm=({valueFormat:e,locale:t,tickValues:n,intlOptions:r})=>he(o=>{const a={...ar(o,n),notation:"compact",...Jo(e)?{style:"currency",currencyDisplay:"narrowSymbol",currency:e.iso}:{},...r};return sr(o,t,a)}),Vm=({locale:e,tickValues:t,intlOptions:n})=>he(r=>{const s={...ar(r,t),notation:"compact",...n};return sr(r,e,s)}),km=({locale:e,tickValues:t,intlOptions:n})=>he(r=>{const s={...ar(r,t),notation:"compact",...n,style:"percent"};return sr(r,e,s)}),sr=(e,t,n)=>Intl.NumberFormat(t,n).formatToParts(e).map(o=>o.type==="compact"?o.value.toLowerCase():o.value).join(""),da=e=>Math.abs(e)>vo?da(e/vo):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)<Am},ar=(e,t)=>da(e)?{minimumFractionDigits:0,maximumFractionDigits:0}:Em(t)?{minimumFractionDigits:0,maximumFractionDigits:Tm}:{minimumFractionDigits:0,maximumFractionDigits:Mm},Im=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"short",...$,...t}).format(n)),Cm=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{month:"short",...$,...t}).format(n)),Fm=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"short",...$,...t}).format(n)),Dm=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{timeStyle:"short",...$,...t}).format(n)),ir=e=>{const{valueFormat:t}=e;switch(t.type){case"currency":return Lm(e);case"date":case"datetime":return Im(e);case"day_month":case"weekly_date_range":case"weekly_date_range_with_year":return Fm(e);case"decimal":case"integer":return Vm(e);case"duration":return Jn();case"month":return Cm(e);case"month_year":return nr(e);case"percentage":return km(e);case"quarter":return rr();case"text":return Qn();case"time":return Dm(e);case"year":return or(e);case"lookup":return ir({...e,valueFormat:t.fallback});default:{const n=t;throw new Error(`Unhandled value format: ${n.type}`)}}},_m=40,Rm=60,So=8,Pm=50,Nm=1/3,Om=1/4,mn="…",$m=(e,t,n)=>{if(t<=0||e.length===0)return"";if(n(e)<=t)return e;if(n(mn)>t)return"";let r=0,o=e.length-1,s=0;for(;r<=o;){const a=r+o>>>1,i=e.slice(0,a)+mn;n(i)<=t?(s=a,r=a+1):o=a-1}return e.slice(0,s)+mn},Bm=e=>e.formattedAxis.position==="top"||e.formattedAxis.position==="bottom"?Gm(e):zm(e),Gm=({formattedAxis:e,bandwidthPx:t,panelRect:n,measureLabel:r})=>{const{widths:o,maxWidth:s,maxHeight:a}=pa(e.ticks,r),i=t-So;if(s<=i)return{...e,labelRotation:0,labelMaxWidthPx:null};if(t>=Pm){const l=Ln(i);return{...e,ticks:Mn(e.ticks,o,l,r),labelRotation:0,labelMaxWidthPx:l}}if(a+So>t)return{...e,ticks:[],labelRotation:0,labelMaxWidthPx:null};const c=Ln(n.height*Nm);return{...e,ticks:Mn(e.ticks,o,c,r),labelRotation:-90,labelMaxWidthPx:c}},zm=({formattedAxis:e,bandwidthPx:t,panelRect:n,measureLabel:r})=>{const{widths:o,maxWidth:s,maxHeight:a}=pa(e.ticks,r);if(a>t)return{...e,ticks:[],labelRotation:0,labelMaxWidthPx:null};const i=Ln(n.width*Om);return s<=i?{...e,labelRotation:0,labelMaxWidthPx:null}:{...e,ticks:Mn(e.ticks,o,i,r),labelRotation:0,labelMaxWidthPx:i}},pa=(e,t)=>{const n=[];let r=0,o=0;for(const s of e){const{width:a,height:i}=t(s.formattedLabel);n.push(a),a>r&&(r=a),i>o&&(o=i)}return{widths:n,maxWidth:r,maxHeight:o}},Mn=(e,t,n,r)=>{const o=s=>r(s).width;return e.map((s,a)=>(t[a]??0)<=n?s:{...s,formattedLabel:$m(s.formattedLabel,n,o)})},Ln=e=>Math.max(0,Math.floor(e)),Um=(e,t,n,r)=>{if(e.length===0)return!0;const o=t==="top"||t==="bottom",s=o?Rm:_m;let a=n-(e.length-1)*s;for(const i of e){const{width:c,height:l}=r(i);if(a-=o?c:l,a<0)return!1}return!0},Ym=({axis:e,availableSpacePx:t,measureLabel:n,resolveFormatter:r})=>{const{tickCandidates:o,position:s}=e;if(o.length===0)return[];const a=new Map,i=d=>{const p=a.get(d);if(p)return p;const m=o[d],f=m?Wm(m.ticks,r(m)):[];return a.set(d,f),f};let c=0,l=o.length-1,u=-1;for(;c<=l;){const d=c+l>>>1,m=i(d).map(f=>f.formattedLabel);Um(m,s,t,n)?(u=d,c=d+1):l=d-1}return u>=0?i(u):i(0)},Wm=(e,t)=>e.map(n=>({...n,formattedLabel:t(n.value)})),fn=6,hn=6,yn=15,gn=5,bn=15,cr=(e,t)=>{switch(e){case"small":return{arrowStartGap:fn,arrowEndGap:hn,offsetFromHigherObservation:yn,arrowheadSize:gn,curveRadius:bn,strokeWidth:2,labelLineHeight:12*t,labelPaddingX:6,labelPaddingY:3,labelStrokeWidth:1,labelFontWeight:500};case"medium":return{arrowStartGap:fn*1.5,arrowEndGap:hn*1.5,offsetFromHigherObservation:yn*1.25,arrowheadSize:gn*1.5,curveRadius:bn*1.25,strokeWidth:3,labelLineHeight:16*t,labelPaddingX:8,labelPaddingY:4,labelStrokeWidth:1.5,labelFontWeight:500};case"large":return{arrowStartGap:fn*2,arrowEndGap:hn*2,offsetFromHigherObservation:yn*1.75,arrowheadSize:gn*2.5,curveRadius:bn*1.5,strokeWidth:5,labelLineHeight:20*t,labelPaddingX:10,labelPaddingY:5,labelStrokeWidth:2,labelFontWeight:600}}},Hm=e=>{const t=D({...e,valueFormat:e.valueFormat.fallback}),n={};for(const[o,s]of Object.entries(e.valueFormat.cases))n[o]=D({...e,valueFormat:s});const r=e.valueFormat.byVariable;return(o,s)=>{if(s===void 0||s[r]===void 0)return t(o);const a=E(s[r]),i=n[a];return i!==void 0?i(o,s):t(o)}},D=e=>{switch(e.valueFormat.type){case"currency":return ra(e);case"date":return vm(e);case"datetime":return Sm(e);case"day_month":return aa(e);case"decimal":return Zn(e);case"duration":return Jn();case"integer":return oa(e);case"month":return ia(e);case"month_year":return nr(e);case"percentage":return sa(e);case"quarter":return rr();case"text":return Qn();case"weekly_date_range":return ca(e);case"weekly_date_range_with_year":return la(e);case"year":return or(e);case"time":return ua(e);case"lookup":return Hm({...e,valueFormat:e.valueFormat});default:{const t=e.valueFormat;throw new Error(`Unhandled value format: ${t.type}`)}}},vn={abbreviation:"none",decimals:"auto"},ma=({locale:e,kind:t,startValue:n,endValue:r})=>{if(n===null||r===null)return na;switch(t){case"absolute-difference":return Zn({locale:e,numberFormat:vn,intlOptions:{signDisplay:"always"}})(r-n);case"relative-difference":{const o=r-n;if(o===0)return"0%";const s=o/n;return s===Number.POSITIVE_INFINITY?"∞":s===Number.NEGATIVE_INFINITY?"-∞":D({valueFormat:{type:"percentage"},locale:e,numberFormat:vn,intlOptions:{signDisplay:"always"}})(s)}case"proportion":{if(r-n===0)return"=";const o=r/n;return o===Number.POSITIVE_INFINITY?"∞":o===Number.NEGATIVE_INFINITY?"-∞":`${D({valueFormat:{type:"decimal"},locale:e,numberFormat:vn,intlOptions:{maximumFractionDigits:1}})(o)}x`}}},Km=e=>{const t=e.padding??0,n=xo(e.rows,t),r=xo(e.cols,t);return{rows:n.tracks,cols:r.tracks,placements:Qm(e.placements,n.nameToIndex,r.nameToIndex),width:e.containerSize.width,height:e.containerSize.height}},Xm=e=>{const t=wo(e.rows,e.height),n=wo(e.cols,e.width),r=Ao(t),o=Ao(n),s=new Map;for(const a of e.placements){const i=a.rowSpan??1,c=a.colSpan??1,l=o[a.col]??0,u=r[a.row]??0,d=To(n,a.col,c),p=To(t,a.row,i);s.set(a.name,{x:l,y:u,width:Math.max(0,d),height:Math.max(0,p)})}return s},xo=(e,t)=>{const n=[],r=new Map;t>0&&n.push({type:"fixed",pixels:t});for(let o=0;o<e.length;o++){const s=e[o];if(!s)continue;r.set(s.name,n.length),n.push(jm(s));const a=qm(e,o);if(fa(s)&&a){const i=s.gaps?.after??0,c=a.gaps?.before??0,l=Math.max(i,c);l>0&&n.push({type:"fixed",pixels:l})}}return t>0&&n.push({type:"fixed",pixels:t}),{tracks:n,nameToIndex:r}},jm=e=>typeof e.size=="number"?{type:"fixed",pixels:e.size}:{type:"flex",weight:e.size.flex},fa=e=>typeof e.size=="number"?e.size>0:e.size.flex>0,qm=(e,t)=>{for(let n=t+1;n<e.length;n++){const r=e[n];if(r&&fa(r))return r}},Qm=(e,t,n)=>{const r=[];for(const o of e){const s=t.get(o.row),a=n.get(o.col);if(s===void 0||a===void 0)continue;const i=o.rowEnd!==void 0?t.get(o.rowEnd):s,c=o.colEnd!==void 0?n.get(o.colEnd):a;i===void 0||c===void 0||r.push({name:o.name,row:s,col:a,rowSpan:Math.max(1,i-s+1),colSpan:Math.max(1,c-a+1)})}return r},wo=(e,t)=>{let n=0,r=0;for(const s of e)s.type==="fixed"?n+=s.pixels:r+=s.weight;const o=Math.max(0,t-n);return e.map(s=>s.type==="fixed"?s.pixels:r===0?0:s.weight/r*o)},Ao=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},To=(e,t,n)=>{let r=0;const o=Math.min(t+n,e.length);for(let s=t;s<o;s++)r+=e[s]??0;return r},ha=24,ne={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}},vt={leftLegend:{after:10,before:0},leftAxis:{after:4,before:0},panel:{after:4,before:0},rightAxis:{after:10,before:0}},lr={top:0,right:0,bottom:0,left:0},Zm=(e,t,n,r=lr)=>{const s=n.axes.top>0||n.axesLabels.top>0?n.axesLabels.top:Math.max(n.axesLabels.top,n.axesLabels.left,n.axesLabels.right);return Km({rows:[{name:"header",size:t.headerSize.height,gaps:ne.header},{name:"topLegend",size:n.legends.top,gaps:ne.topLegend},{name:"headline",size:n.headline,gaps:ne.headline},{name:"topAxisLabel",size:s,gaps:ne.topAxisLabel},{name:"topAxis",size:n.axes.top,gaps:ne.topAxis},{name:"topAnnotation",size:r.top},{name:"panel",size:{flex:1},gaps:ne.panel},{name:"bottomAxis",size:n.axes.bottom,gaps:ne.bottomAxis},{name:"bottomAxisLabel",size:n.axesLabels.bottom,gaps:ne.bottomAxisLabel},{name:"bottomLegend",size:n.legends.bottom,gaps:ne.bottomLegend},{name:"footer",size:t.footerSize.height}],cols:[{name:"leftLegend",size:n.legends.left,gaps:vt.leftLegend},{name:"leftAxis",size:n.axes.left,gaps:vt.leftAxis},{name:"panel",size:{flex:1},gaps:vt.panel},{name:"rightAnnotation",size:r.right},{name:"rightAxis",size:n.axes.right,gaps:vt.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"},...Jm(n.axes),...ef(n.axesLabels,n.axes),...tf(n.legends)],containerSize:e,padding:ha})},Jm=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},ef=(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},tf=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},nf=({annotations:e,mainAxis:t,panelRect:n,textScale:r,locale:o,measureLabel:s,currentOverflow:a})=>{if(e.differenceArrows.length===0)return lr;const i=t==="y",c=n.height+a.top,l=n.width+a.right;let u=0,d=0;for(const p of e.differenceArrows){const{start:m,end:f,size:y,label:b}=p;if(!Mo(m.x,m.y)||!Mo(f.x,f.y))continue;const x=cr(y,r),S=x.offsetFromHigherObservation+x.arrowheadSize+x.arrowEndGap,w=ma({locale:o,kind:b,startValue:m.measurementValue,endValue:f.measurementValue}),I=s(w,y);if(i){const _=Math.max(m.x,f.x),j=S+I.width/2+x.labelPaddingX;d=Math.max(d,Lo(j,_,l))}else{const _=Math.max(m.y,f.y),j=S+x.labelLineHeight/2+x.labelPaddingY;u=Math.max(u,Lo(j,_,c))}}return{top:Math.ceil(u),right:Math.ceil(d),bottom:0,left:0}},Mo=(e,t)=>e>=0&&e<=1&&t>=0&&t<=1,Lo=(e,t,n)=>{if(t<=0)return 0;const r=(e-(1-t)*n)/t;return Math.max(0,r)},rf=["top","right","bottom","left"],Sn=(e,t)=>{const n={};for(const r of rf){const o=e.get(`${r}${t}`);o&&(n[r]=o)}return n},Vn=["large","medium","small"],of=({size:e,availableWidth:t,measureStripWidth:n})=>{if(e!=="auto")return e;for(const r of Vn)if(n(r)<=t)return r;return"small"},sf=({size:e,availableWidth:t,measureStripWidth:n})=>{const r=e==="auto"?0:Vn.indexOf(e);for(const o of Vn.slice(r))if(n(o)<=t)return o;return null},af=({itemWidths:e,gap:t,availableWidth:n})=>{let r=0,o=0;for(const s of e){const a=o===0?s:r+t+s;if(a>n)break;r=a,o+=1}return o},cf=({headline:e,containerSize:t,measurer:n})=>{if(ya(e))return 0;const r=ga(e,t.width,n);return n.measureHeadline(e.formatted,r).height},lf=({headline:e,layout:t,containerSize:n,measurer:r,itemGap:o})=>{if(ya(e)){const i=uf(t.panel,e.innerRadius),c=sf({size:e.size,availableWidth:i.width,measureStripWidth:ba(e,r)});return c===null?null:{rect:i,resolvedSize:c,visibleItemCount:1}}const s=ga(e,n.width,r);if(e.formatted.kind!=="perGroup")return{rect:t.headline,resolvedSize:s,visibleItemCount:1};const a=af({itemWidths:r.measureHeadlineItemWidths(e.formatted,s),gap:o,availableWidth:t.headline.width});return a===0?null:{rect:t.headline,resolvedSize:s,visibleItemCount:a}},ya=e=>e.formatted.kind==="grandTotal"&&e.position==="center"&&e.innerRadius>0,uf=(e,t)=>{const n=Math.min(e.width,e.height)/2,r=t*n*Math.SQRT2,o=e.x+e.width/2,s=e.y+e.height/2;return{x:o-r/2,y:s-r/2,width:r,height:r}},ga=(e,t,n)=>of({size:e.size,availableWidth:t,measureStripWidth:ba(e,n)}),ba=(e,t)=>n=>t.measureHeadline(e.formatted,n).width,He={x:0,y:0,width:0,height:0},df="0000";class pf{constructor(t){this.measurer=t}compile(t){const n=_t({axes:t.axes,numberFormat:t.numberFormat,formattedLegends:t.formattedLegends,containerSize:t.containerSize,externalMeasurements:t.externalMeasurements,annotationOverflow:lr,headline:t.headline,locale:t.formattingLocale??t.parsingLocale}).pipe(({axes:r,numberFormat:o,locale:s})=>{const a=r.filter(i=>i.geometry!=="linear").map(i=>ff(i,Eo(i,s,o)));return{cartesianAxes:r.filter(i=>i.geometry==="linear"),formattedPolarAxes:a,polarMargin:hf(a,this.measurer.measureTickLabel)}}).pipe(({cartesianAxes:r,numberFormat:o,locale:s})=>({axisBundles:r.map(a=>({axis:a,resolveFormatter:Eo(a,s,o),formatted:this.seedAxis(a)}))})).pipe(({axisBundles:r,formattedLegends:o,containerSize:s,externalMeasurements:a,annotationOverflow:i,headline:c,polarMargin:l})=>({layout:this.resolveLayout({axes:r.map(u=>u.formatted),formattedLegends:o,containerSize:s,externalMeasurements:a,annotationOverflow:i,headline:c,polarMargin:l})})).pipe(({axisBundles:r,layout:o})=>({axisBundles:r.map(s=>ko(s.axis.position)?{...s,formatted:this.finalizeAxis(s.axis,s.resolveFormatter,o.panel)}:s)})).pipe(({axisBundles:r,formattedLegends:o,containerSize:s,externalMeasurements:a,annotationOverflow:i,headline:c,polarMargin:l})=>({layout:this.resolveLayout({axes:r.map(u=>u.formatted),formattedLegends:o,containerSize:s,externalMeasurements:a,annotationOverflow:i,headline:c,polarMargin:l})})).pipe(({axisBundles:r,layout:o})=>({formattedAxes:r.map(s=>ko(s.axis.position)?s.formatted:this.finalizeAxis(s.axis,s.resolveFormatter,o.panel))})).pipe(({formattedAxes:r,formattedLegends:o,containerSize:s,externalMeasurements:a,annotationOverflow:i,headline:c,polarMargin:l})=>({layout:this.resolveLayout({axes:r,formattedLegends:o,containerSize:s,externalMeasurements:a,annotationOverflow:i,headline:c,polarMargin:l})})).pipe(({formattedAxes:r,formattedLegends:o,containerSize:s,externalMeasurements:a,layout:i,annotationOverflow:c,headline:l,polarMargin:u,locale:d})=>{const p=this.measureAnnotationOverflow(t,i.panel,d,c);return p===c?{formattedAxes:r,layout:i}:{formattedAxes:r,layout:this.resolveLayout({axes:r,formattedLegends:o,containerSize:s,externalMeasurements:a,annotationOverflow:p,headline:l,polarMargin:u})}}).result();return{formattedAxes:n.formattedAxes,layout:n.layout,formattedPolarAxes:n.formattedPolarAxes}}measureAnnotationOverflow(t,n,r,o){if(!t.annotations||t.annotations.differenceArrows.length===0||t.coordSystem?.type!=="cartesian")return o;const s=nf({annotations:t.annotations,mainAxis:t.coordSystem.mainAxis,panelRect:n,textScale:t.textScale??1,locale:r,measureLabel:this.measurer.measureDifferenceArrowLabel,currentOverflow:o});return s.top===o.top&&s.right===o.right?o:s}seedAxis(t){const{tickCandidates:n,...r}=t;return{...r,ticks:[{value:0,position:0,formattedLabel:df}],labelRotation:0,labelMaxWidthPx:null}}finalizeAxis(t,n,r){const s=t.position==="top"||t.position==="bottom"?r.width:r.height,a=Ym({axis:t,availableSpacePx:s,measureLabel:this.measurer.measureTickLabel,resolveFormatter:n}),{tickCandidates:i,...c}=t,l={...c,ticks:a,labelRotation:0,labelMaxWidthPx:null};if(t.scaleType==="discrete"&&t.bandwidth!==void 0){const u=t.bandwidth*s;return Bm({formattedAxis:l,bandwidthPx:u,panelRect:r,measureLabel:this.measurer.measureTickLabel})}return l}resolveLayout({axes:t,formattedLegends:n,containerSize:r,externalMeasurements:o,annotationOverflow:s,headline:a,polarMargin:i}){const c=this.measureGuides(t,n,a,r,i),l=Zm(r,o,c,s),u=Xm(l);return{header:u.get("header")??He,headline:u.get("headline")??He,footer:u.get("footer")??He,plot:u.get("plot")??He,panel:u.get("panel")??He,axes:Sn(u,"Axis"),axisLabels:Sn(u,"AxisLabel"),legends:Sn(u,"Legend")}}measureGuides(t,n,r,o,s){const a={...s},i={top:0,right:0,bottom:0,left:0};for(const l of t)l.isVisible&&(a[l.position]=this.measurer.measureAxis(l),l.label!==null&&(i[l.position]=this.measurer.measureAxisLabel(l)));const c={top:0,right:0,bottom:0,left:0};for(const l of n)c[l.position]=this.measurer.measureLegend(l);return{axes:a,axesLabels:i,legends:c,headline:this.measureHeadlineBand(r,o)}}measureHeadlineBand(t,n){return t===void 0?0:cf({headline:t,containerSize:n,measurer:this.measurer})}}const Vo=5,St=8,ko=e=>e==="left"||e==="right",mf=e=>{const[t,...n]=e.tickCandidates;if(t)return e.geometry==="circular"?t:n.reduce((r,o)=>Math.abs(o.ticks.length-Vo)<Math.abs(r.ticks.length-Vo)?o:r,t)},ff=(e,t)=>{const{tickCandidates:n,...r}=e,o=mf(e);if(!o)return{...r,ticks:[],labelRotation:0,labelMaxWidthPx:null};const s=t(o),a=o.ticks.map(i=>({...i,formattedLabel:s(i.value)}));return{...r,ticks:a,labelRotation:0,labelMaxWidthPx:null}},hf=(e,t)=>{const n=e.find(s=>s.geometry==="circular");if(!n||n.ticks.length===0)return{top:0,right:0,bottom:0,left:0};let r=0,o=0;for(const s of n.ticks){const a=t(s.formattedLabel);r=Math.max(r,a.width),o=Math.max(o,a.height)}return{top:o+St,bottom:o+St,left:r+St,right:r+St}},Eo=(e,t,n)=>{const r=e.tickCandidates.flatMap(s=>s.ticks.map(a=>a.value)),o=new WeakMap;return s=>{const a=o.get(s);if(a)return a;const i=ir({valueFormat:s.valueFormat??e.valueFormat,locale:t,numberFormat:n,tickValues:r});return o.set(s,i),i}};function yf(e,t,n,r){const o=new Map;if(!n||n.kind!=="visual"||n.domain.length<=1)return o;const s=new Map(t.map(a=>[a.id,a.swatchShape]));for(const a of e){if(a.geom!=="rule"||!a.stat.some(y=>y.type==="mean"))continue;const i=a.transforms.find(y=>gf(y)&&y.options.operator==="eq"),c=v(a.mapping.y);let l,u,d;if(i!==void 0&&typeof i.options.value=="string")l="color",u=i.options.variableName,d=i.options.value;else if(c!==null)l="y",u=c,d=c;else continue;const p=bf(e,l,u);if(p===null)continue;const m=s.get(p.id);if(m===void 0)continue;const f=n.map(d);at(f)&&o.set(a.id,{shape:rt(m,r),color:f})}return o}const gf=e=>e.transformType==="filter";function bf(e,t,n){let r=null;for(const o of e)if(o.geom!=="rule"&&(r===null&&(r=o),v(o.mapping[t])===n))return o;return r}function ot(e,t){return e==="x"?t.x:t.y}function Wt(e,t){return e==="x"?t.y:t.x}function vf(e,t){return{main:ot(e,t),cross:Wt(e,t)}}function Sf(e){return e.type==="cartesian"}const ur=12,xf=4,wf=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=Oe(n),o=J(n)??ae(n);if(r===null||o===null||r<0||r>1||o<0||o>1)continue;const s=e.formatLabel(n);if(s==="")continue;const{width:a,height:i}=e.measureDataLabel("dataLabel",s),c=r*e.panelRect.width,l=(1-o)*e.panelRect.height-ur-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:c,y:l,text:s,width:a,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},Af={place:wf,getPercentageValueStrategy:e=>e.position==="fill"?"fill":K(e.position)?"stack":"none"},xn=4,xt=6,Tf=e=>{const t=[],n=K(e.layer.position),r=e.coordSystem.mainAxis==="y";if(e.layer.dataLabels.showDataLabels){const{entries:o,shouldRotate:s}=Lf({layer:e.layer,mainAxis:e.coordSystem.mainAxis,panelRect:e.panelRect,measureDataLabel:e.measureDataLabel,formatLabel:e.formatLabel,isFlipped:r,getObservationKey:e.getObservationKey});for(const a of o){const i=If({mainAxis:e.coordSystem.mainAxis,isStacked:n,isNegativeBar:a.isNegative,shouldRotate:s,bounds:a.bounds,labelWidth:a.labelWidth,labelHeight:a.labelHeight,panelWidth:e.panelRect.width,panelHeight:e.panelRect.height});i!==null&&t.push({layerId:e.layer.id,key:a.key,x:i.x,y:i.y,text:a.text,width:a.labelWidth,height:a.labelHeight,isRotated:i.isRotated,target:"observation",position:i.position})}}if(e.layer.dataLabels.showStackTotals){const o=_f({layer:e.layer,mainAxis:e.coordSystem.mainAxis,panelRect:e.panelRect,measureDataLabel:e.measureDataLabel,formatAbsolute:e.formatAbsolute});for(const s of o)t.push(s)}return t},Mf={place:Tf,getPercentageValueStrategy:e=>e.position==="fill"?"fill":K(e.position)?"stack":"absoluteGrandTotal"},Lf=({layer:e,mainAxis:t,panelRect:n,measureDataLabel:r,formatLabel:o,isFlipped:s,getObservationKey:a})=>{const i=[];let c=!1;const l=v(e.mapping.y);for(const u of e.data){const d=Vf(t,u);if(d===null)continue;const p=o(u);if(p==="")continue;const{width:m,height:f}=r("dataLabel",p),y=va(d,n);m>y.width&&(c=!0);const b=l===null?null:u[l],x=F(b)&&b<0;i.push({key:a(u),isNegative:x,text:p,labelWidth:m,labelHeight:f,bounds:y})}return{entries:i,shouldRotate:!s&&c}},va=(e,t)=>({x:e.x*t.width,y:e.y*t.height,width:e.width*t.width,height:e.height*t.height}),Sa=(e,t,n,r,o)=>{if(e==="x"){let i=1-o,c=o-r;return c<0&&(i+=c,c=-c),{x:t,y:i,width:n-t,height:c}}let s=t,a=n-t;return a<0&&(s+=a,a=-a),{x:s,y:1-o,width:a,height:o-r}},Vf=(e,t)=>{const n=nt(t),r=Ce(t),o=Ae(t),s=J(t)??ae(t);return n===null||r===null||o===null||s===null?null:Sa(e,n,r,o,s)},kf=(e,t)=>{const{xMin:n,xMax:r,yMin:o,yMax:s}=t.anchor;return Sa(e,n,r,o,s)},Ef=(e,t)=>e==="x"?t?"bottom":"top":t?"left":"right",xa=(e,t,n)=>n?{width:t,height:e}:{width:e,height:t},If=e=>e.isStacked?Cf({bounds:e.bounds,labelWidth:e.labelWidth,labelHeight:e.labelHeight,isRotated:e.shouldRotate}):Df({edge:Ef(e.mainAxis,e.isNegativeBar),bounds:e.bounds,labelWidth:e.labelWidth,labelHeight:e.labelHeight,isRotated:e.shouldRotate,panelWidth:e.panelWidth,panelHeight:e.panelHeight}),Cf=({bounds:e,labelWidth:t,labelHeight:n,isRotated:r})=>{const o=xa(t,n,r);return o.width>e.width||o.height>e.height?null:{x:e.x+e.width/2,y:e.y+e.height/2,isRotated:r,position:"inside"}},Ff=(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}}},Df=({edge:e,bounds:t,labelWidth:n,labelHeight:r,isRotated:o,panelWidth:s,panelHeight:a})=>{const i=e==="top"||e==="bottom",c=t.x+t.width/2,l=t.y+t.height/2,u=xa(n,r,o),d=i?u.height:u.width,p=i?u.width:u.height,m=i?t.height:t.width,f=i?t.width:t.height,y=d/2,{edgeCoord:b,outwardSign:x,panelExtent:S}=Ff(e,t,s,a);if(d+xn<m){if(p>f)return null;if(o)return{x:c,y:l,isRotated:!0,position:"inside"};const I=b-x*(y+xn);return{...i?{x:c,y:I}:{x:I,y:l},isRotated:!1,position:"inside"}}const w=b+x*(y+xn);return w-y<0||w+y>S?null:{...i?{x:c,y:w}:{x:w,y:l},isRotated:o,position:"outside"}},_f=({layer:e,mainAxis:t,panelRect:n,measureDataLabel:r,formatAbsolute:o})=>{const s=[],a=e.summary.stackTotals;if(a===void 0||a.length===0)return s;const i=t==="y";for(const c of a){const l=va(kf(t,c),n),u=o(c.total),{width:d,height:p}=r("stackTotal",u),m=c.anchor.direction==="positive";let f,y;i?(f=m?l.x+l.width+xt+d/2:l.x-xt-d/2,y=l.y+l.height/2):(f=l.x+l.width/2,y=m?l.y-xt-p/2:l.y+l.height+xt+p/2),s.push({layerId:e.id,key:`${e.id}:stack:${c.xKey}`,x:f,y,text:u,width:d,height:p,isRotated:!1,target:"aggregate",position:"outside"})}return s},Rf=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=Oe(n),o=ae(n);if(r===null||o===null||r<0||r>1||o<0||o>1)continue;const s=e.formatLabel(n);if(s==="")continue;const{width:a,height:i}=e.measureDataLabel("dataLabel",s),c=r*e.panelRect.width,l=(1-o)*e.panelRect.height-ur-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:c,y:l,text:s,width:a,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},Pf={place:Rf,getPercentageValueStrategy:()=>"none"},Nf=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=Oe(n),o=ae(n);if(r===null||o===null||r<0||r>1||o<0||o>1)continue;const s=e.formatLabel(n);if(s==="")continue;const{width:a,height:i}=e.measureDataLabel("dataLabel",s),c=(Wo(n)??e.layer.params.size)/2,l=r*e.panelRect.width,u=(1-o)*e.panelRect.height-c-ur-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:l,y:u,text:s,width:a,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},Of={place:Nf,getPercentageValueStrategy:()=>"none"};function wa(e){return{startAngle:e[g.xMin],endAngle:e[g.xMax]}}function Aa(e){return{innerRadius:e[g.yMin],outerRadius:e[g.yMax]??e[g.y]}}const $f=" · ",Bf=e=>typeof e=="string"?e:e instanceof Date?e.toISOString():String(e),Gf=(e,t)=>{const n=v(t.x);return n!==null&&n!==wn.x?zn(e,t):o=>_e(o)},zf=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;const n=e.layer.dataLabels.showCategoryLabels?Gf(e.layer.data,e.layer.mapping):null,r=e.panelRect.width/2,o=e.panelRect.height/2,s=Math.min(e.panelRect.width,e.panelRect.height)/2;for(const a of e.layer.data){const{startAngle:i,endAngle:c}=wa(a),{outerRadius:l}=Aa(a);if(i===null||c===null||l===null)continue;const u=e.formatLabel(a);if(u==="")continue;const d=n===null?null:n(a),p=d===null?u:`${Bf(d)}${$f}${u}`,{width:m,height:f}=e.measureDataLabel("dataLabel",p),y=(i+c)/2,b=Math.abs(Math.sin(y))*(m/2)+Math.abs(Math.cos(y))*(f/2),x=l*s+xf+b,S=r+Math.sin(y)*x,w=o-Math.cos(y)*x,I=m/2,_=f/2;S-I<0||S+I>e.panelRect.width||w-_<0||w+_>e.panelRect.height||t.push({layerId:e.layer.id,key:e.getObservationKey(a),x:S,y:w,text:p,width:m,height:f,isRotated:!1,target:"observation",position:"outside"})}return t},Uf={place:zf,getPercentageValueStrategy:()=>"absoluteGrandTotal"},Yf={type:"decimal"};function Ta({layer:e,numberFormat:t,locale:n}){const r=v(e.mapping.y),o=r!==null&&e.data.hasVariable(r)?e.data.getValueFormat(r):Yf;return D({valueFormat:o,locale:n,numberFormat:t})}const Wf=({layer:e,coordSystem:t,axes:n,numberFormat:r,panelRect:o,measureDataLabel:s,formattingLocale:a,percentageValueStrategy:i})=>{const c=Ta({layer:e,numberFormat:r,locale:a});return{layer:e,coordSystem:t,panelRect:o,measureDataLabel:s,formatLabel:qf({layer:e,numberFormat:r,axes:n,locale:a,absoluteFormatter:c,percentageValueStrategy:i}),formatAbsolute:c,getObservationKey:Hf(e)}},Hf=e=>t=>`${e.id}:${Bt(t)}`,Kf=(e,t)=>{switch(t){case"stack":return Xf(e);case"fill":return jf(e);case"absoluteGrandTotal":return()=>e.summary.absoluteGrandTotal??null;case"none":return()=>null}},Xf=e=>{const t=v(e.mapping.x);let n=null,r=!1;return o=>{const s=e.summary.stackTotals;if(s===void 0||s.length===0||t===null)return null;if(!r){n=new Map;for(const c of s)n.set(c.xKey,c);r=!0}const a=o[t];if(a==null)return null;const i=n?.get(Gn(o,t));return i===void 0?null:i.total}},jf=e=>{const t=Un(e);return n=>{const r=Ae(n),o=J(n);if(!F(r)||!F(o))return null;const s=Math.abs(o-r);if(s===0)return null;const a=t(n);return F(a)?a/s:null}},qf=({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:o,percentageValueStrategy:s})=>{const a=X(e.data,e.dataLabels.labelSource),i=Kf(e,s),c=Qf({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:o}),l=D({valueFormat:{type:"percentage"},locale:r,numberFormat:t}),u=e.dataLabels.format==="percentage"&&Ma(e);return d=>{const p=a(d);if(p===null)return"";if(!u||!F(p))return c(p,d);const m=i(d);return m===null||m===0?c(p,d):l(p/m)}},Qf=({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:o})=>{const s=e.dataLabels.labelSource,a=v(s);if(a!==null){if(Ma(e))return o;const i=Zf(e,n,t,r,a);if(i!==null)return i}return D({valueFormat:Jf(e.data,s),locale:r,numberFormat:t})},Ma=e=>{const t=v(e.dataLabels.labelSource);return t===null?!1:t===v(ut(e.position,e.mapping))},Zf=(e,t,n,r,o)=>{const s=v(e.mapping.x);if(s===null||s!==o)return null;const a=t.find(i=>i.scaleAestheticKey==="x");return a===void 0?null:D({valueFormat:a.valueFormat,locale:r,numberFormat:n})},Jf=(e,t)=>{const n=se(t);if(n!==void 0)return typeof n=="number"?{type:"decimal"}:Qa(n)?{type:"date"}:{type:"text"};const r=v(t);return r===null||!e.hasVariable(r)?{type:"text"}:e.getValueFormat(r)},eh={bar:{cartesian:Mf,polar:Uf},line:{cartesian:Pf},point:{cartesian:Of},area:{cartesian:Af}},th=({layers:e,coordSystem:t,axes:n,numberFormat:r,parsingLocale:o,panelRect:s,measureDataLabel:a,formattingLocale:i})=>{const c=[],l=i??o,u=t.type;for(const d of e){if(!d.dataLabels.showDataLabels&&!d.dataLabels.showStackTotals)continue;const p=eh[d.geom]?.[u];if(p===void 0)continue;const m=Wf({layer:d,coordSystem:t,axes:n,numberFormat:r,panelRect:s,measureDataLabel:a,formattingLocale:l,percentageValueStrategy:p.getPercentageValueStrategy(d)}),f=p.place(m);for(const y of f)c.push(y)}return{labels:c}},nh=(e,t,n,r)=>{const o=r.offsetFromHigherObservation+r.arrowheadSize+r.arrowEndGap;return e?Math.max(t.x,n.x)+o:Math.min(t.y,n.y)-o},rh=(e,t,n,{arrowStartGap:r,arrowEndGap:o,curveRadius:s})=>{const a={x:e.x,y:e.y-r},i={x:e.x,y:n},c={x:t.x,y:n},l={x:t.x,y:t.y-o},u=t.x>e.x?1:-1;return`
5
- M ${a.x} ${a.y}
6
- L ${i.x} ${i.y+s}
7
- Q ${i.x} ${i.y} ${i.x+u*s} ${i.y}
8
- L ${c.x-u*s} ${c.y}
9
- Q ${c.x} ${c.y} ${c.x} ${c.y+s}
10
- L ${l.x} ${l.y}
11
- `},oh=(e,t,n,{arrowStartGap:r,arrowEndGap:o,curveRadius:s})=>{const a={x:e.x+r,y:e.y},i={x:n,y:e.y},c={x:n,y:t.y},l={x:t.x+o,y:t.y},u=t.y>e.y?1:-1;return`
12
- M ${a.x} ${a.y}
13
- L ${i.x-s} ${i.y}
14
- Q ${i.x} ${i.y} ${i.x} ${i.y+u*s}
15
- L ${c.x} ${c.y-u*s}
16
- Q ${c.x} ${c.y} ${c.x-s} ${c.y}
17
- L ${l.x} ${l.y}
18
- `},sh=(e,t,{arrowEndGap:n,arrowheadSize:r})=>e?`
19
- M ${t.x+n+r} ${t.y-r}
20
- L ${t.x+n} ${t.y}
21
- L ${t.x+n+r} ${t.y+r}
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var wl=Object.create,ya=Object.defineProperty,El=Object.getOwnPropertyDescriptor,Vl=Object.getOwnPropertyNames,Rl=Object.getPrototypeOf,Cl=Object.prototype.hasOwnProperty,kl=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var a=Vl(t),i=0,s=a.length,o;i<s;i++)o=a[i],!Cl.call(e,o)&&o!==r&&ya(e,o,{get:(c=>t[c]).bind(null,o),enumerable:!(n=El(t,o))||n.enumerable});return e},yr=(e,t,r)=>(r=e!=null?wl(Rl(e)):{},kl(t||!e||!e.__esModule?ya(r,"default",{value:e,enumerable:!0}):r,e));const l=require("./config.types-CQX-tSXl.cjs");let va=require("date-fns"),yt=require("lodash-es"),Me=require("d3-time"),Dl=require("date-fns/differenceInDays"),se=require("d3-regression"),j=require("d3-scale"),Le=require("d3-interpolate"),k=require("d3-scale-chromatic"),lt=require("lodash-es/merge");lt=yr(lt,1);let tr=require("humanize-duration");tr=yr(tr,1);let de=require("d3-shape"),yn=require("color2k"),Pl=require("d3-delaunay"),rr=require("lodash-es/isEqual");rr=yr(rr,1);typeof window<"u"&&(window.__GRAPHY_SDK__??={},window.__GRAPHY_SDK__.vizEngine="1.8.1-beta.1786024899180");var Ol=1e6;function H(e){return String(Math.round(e*Ol))}var vn=0;function C(){return vn+=1,`${Math.random().toString(36).slice(2,6)}${vn.toString(36)}`}function V(e){return e[l.POSITION_VARIABLES.x]}function w(e){return e[l.POSITION_VARIABLES.y]}function K(e){return e[l.POSITION_VARIABLES.xMin]}function z(e){return e[l.POSITION_VARIABLES.xMax]}function N(e){return e[l.POSITION_VARIABLES.yMin]}function P(e){return e[l.POSITION_VARIABLES.yMax]}function vr(e){return e[l.POSITION_VARIABLES.yRaw]}function Ml(e,t){return e[l.resolveScaledAestheticVariable(t)]}var _l={xMin:0,xMax:1,yMin:0,yMax:1},nr=(e,t)=>{if(t.type==="polar")return null;const r=K(e)??V(e),n=z(e)??V(e),a=N(e)??w(e),i=P(e)??w(e);return r===null||n===null||a===null||i===null?null:{xMin:r,xMax:n,yMin:a,yMax:i}},Ge=(e,t)=>{const r=(e.xMin+e.xMax)/2,n=(e.yMin+e.yMax)/2;switch(t){case"top":return{x:r,y:e.yMax};case"bottom":return{x:r,y:e.yMin};case"left":return{x:e.xMin,y:n};case"right":return{x:e.xMax,y:n};case"top-left":return{x:e.xMin,y:e.yMax};case"top-right":return{x:e.xMax,y:e.yMax};case"bottom-left":return{x:e.xMin,y:e.yMin};case"bottom-right":return{x:e.xMax,y:e.yMin};default:return{x:r,y:n}}},ba=e=>Ge(_l,e),pe=e=>{const t=l.extractVariableName(e.mapping.x);return t!==null&&t!==l.CONSTANT_VARIABLES.x?t:l.GROUP_VARIABLES.group},Sa=(e,t)=>e.yScaleType===t.yScaleType&&ir(e.valueFormat)===ir(t.valueFormat),ar=e=>`${e.yScaleType} y axis, ${ir(e.valueFormat)}`,ir=e=>e.type==="currency"?`${e.type}:${e.iso}`:e.type,Nl=(e,t)=>{if(!l.isLookupValueFormat(e))return e;const r=t[e.byVariable];return r===void 0?e.fallback:e.cases[l.getStableKey(r)]??e.fallback};function we(e,t){return e==="x"?t.x:t.y}function vt(e,t){return e==="x"?t.y:t.x}function Bl(e,t){return{main:we(e,t),cross:vt(e,t)}}function bn(e,t){return e==="x"?{x:t.main,y:t.cross}:{x:t.cross,y:t.main}}function Fl(e){return e.type==="cartesian"}var G=e=>e[l.GROUP_VARIABLES.group],bt=(e,t)=>{const r=pe(e),n=t[r]??null;if(n===null)return null;const a=r===l.GROUP_VARIABLES.group?null:G(t);return{layerId:e.id,anchorValue:n,...a!==null&&{groupValue:a}}},Ee=(e,t)=>e>=0&&e<=1&&t>=0&&t<=1,$l={type:"decimal"};function xa(e){return e.length>0&&e.every(t=>t.data.size()===0)}function Aa(e,t){return t!==null&&e.data.hasVariable(t)?e.data.getValueFormat(t):$l}function Ia(e){return Aa(e,l.extractVariableName(e.mapping.y))}var br=["solid","dashed","dotted"],Ta=e=>br.includes(e);function O(e){return e==="stack"||e==="fill"}var U=(e,t)=>{const r=l.extractConstantValue(t);if(r!==void 0)return()=>r;const n=l.extractVariableName(t);return l.isDefined(n)?a=>{const i=a[n];if(i===void 0)return null;switch(e.getType(n)){case"numeric":return l.isStrictNumericDataValue(i)?i:null;case"categorical":return l.isStrictCategoricalDataValue(i)?i:null;case"temporal":return l.isStrictTemporalDataValue(i)?i:null;default:return null}}:()=>null},St=(e,t)=>U(e,t.x),La=(e,t)=>U(e,t.y),Gl=(e,t)=>U(e,t.label),wa=(e,t)=>U(e,t.color),Ul=(e,t)=>U(e,t.size),Wl=(e,t)=>U(e,t.alpha),Hl=(e,t)=>U(e,t.group),Kl=(e,t)=>U(e,t.strokeWidth),Sn={variable:l.POSITION_VARIABLES.yRaw};function xt(e,t){return O(e)?Sn:t.y??Sn}function ke(e){return U(e.data,xt(e.position,e.mapping))}function At(e){return e[l.VISUAL_VARIABLES.color]}function Ea(e){return e[l.VISUAL_VARIABLES.alpha]}function Sr(e){return e[l.VISUAL_VARIABLES.size]}function sr(e){return e[l.VISUAL_VARIABLES.strokeWidth]}function Va(e){return e[l.VISUAL_VARIABLES.lineType]}var or=(e,t,r)=>{const n=l.parseValue(e,t,r);return n!==null||!l.isTemporalValueFormat(t)?n:l.readISOInstant(e)},Ra=(e,t)=>{const r=l.toExplicitValueFormat(e.data.getValueFormat(pe(e)));return n=>({...n,anchorValue:or(n.anchorValue,r,t),...n.groupValue!==void 0&&{groupValue:or(n.groupValue,l.toExplicitValueFormat(e.data.getValueFormat(l.GROUP_VARIABLES.group)),t)}})},Ca=e=>{const t=l.extractVariableName(e.mapping.y),r=ke(e);return(n,a)=>t!==null&&a===t?r(n):n[a]??null},zl=["lt","lte","gt","gte","range"],Yl={highlight:{subject:"Highlight predicate",effect:"dropping this highlight"},"selection-anchor":{subject:"Selection anchor predicate",effect:"dropping this annotation"},"style-rule":{subject:"Style rule predicate",effect:"dropping this rule"}},J=()=>!1,ye=()=>!0;function It(e,t){return{hasVariable:r=>e.data.hasVariable(r),getType:r=>e.data.getType(r),getValueFormat:r=>e.data.getValueFormat(r),readValue:Ca(e),parsingLocale:t}}function le(e,t){if("and"in e){const r=e.and.map(n=>le(n,t)).filter(n=>n!==ye);return r.includes(J)?J:r.length===0?ye:n=>{for(const a of r)if(!a(n))return!1;return!0}}if("or"in e){const r=e.or.map(n=>le(n,t)).filter(n=>n!==J);return r.includes(ye)?ye:r.length===0?J:n=>{for(const a of r)if(a(n))return!0;return!1}}if("not"in e){const r=le(e.not,t);return r===J?ye:r===ye?J:n=>!r(n)}return Xl(e,t)}function ce(e,t,r="highlight"){return"and"in e?e.and.flatMap(n=>ce(n,t,r)):"or"in e?e.or.flatMap(n=>ce(n,t,r)):"not"in e?ce(e.not,t,r):ql(e,t,r)}function ql(e,t,r){const{subject:n,effect:a}=Yl[r];if(!t.hasVariable(e.variable))return[{code:"UNKNOWN_VARIABLE",message:`${n} references unknown variable '${e.variable}' — ${a}.`,context:{variableName:e.variable},suggestion:`Map '${e.variable}' in the layer or correct the variable name in the predicate.`}];const i=jl(e);return i!==null&&t.getType(e.variable)==="categorical"?[{code:"INVALID_PREDICATE_OPERATOR",message:`${n} uses ordering operator '${i}' on categorical variable '${e.variable}' — ${a}. Use 'eq' or 'oneOf' instead.`,context:{variableName:e.variable},suggestion:"Use 'eq' or 'oneOf' for categorical variables."}]:[]}function Xl(e,t){if(!t.hasVariable(e.variable))return J;const r=l.toExplicitValueFormat(t.getValueFormat(e.variable)),n=a=>or(a,r,t.parsingLocale);if("eq"in e){const a=n(e.eq);return i=>l.areDataValuesEqual(t.readValue(i,e.variable),a)}if("oneOf"in e){const a=e.oneOf.map(n);return i=>{const s=t.readValue(i,e.variable);for(const o of a)if(l.areDataValuesEqual(s,o))return!0;return!1}}if("lt"in e){const a=n(e.lt);return i=>ve(t.readValue(i,e.variable),a)==="less"}if("lte"in e){const a=n(e.lte);return i=>{const s=ve(t.readValue(i,e.variable),a);return s==="less"||s==="equal"}}if("gt"in e){const a=n(e.gt);return i=>ve(t.readValue(i,e.variable),a)==="greater"}if("gte"in e){const a=n(e.gte);return i=>{const s=ve(t.readValue(i,e.variable),a);return s==="greater"||s==="equal"}}if("range"in e){const[a,i]=e.range,s=n(a),o=n(i);return c=>{const u=t.readValue(c,e.variable),d=ve(u,s),m=ve(u,o);return d==="incomparable"||m==="incomparable"?!1:(d==="greater"||d==="equal")&&(m==="less"||m==="equal")}}return J}function jl(e){for(const t of zl)if(t in e)return t;return null}function ve(e,t){if(e===null||t===null)return"incomparable";if(l.isStrictTemporalDataValue(e)&&l.isStrictTemporalDataValue(t)){const r=e.getTime(),n=t.getTime();return r<n?"less":r>n?"greater":"equal"}return l.isStrictNumericDataValue(e)&&l.isStrictNumericDataValue(t)?e<t?"less":e>t?"greater":"equal":"incomparable"}var Zl=(e,t,r,n,a,i)=>{const s=Da(e,t,r.predicate,n,a,i);if(s===null)return null;const o=ka(r.padding),c=o===null?ec(s,r.padding):s,u={x:c.xMin,y:c.yMin,width:Math.max(0,c.xMax-c.xMin),height:Math.max(0,c.yMax-c.yMin)};return o===null?u:{...u,defer:o}},Jl=(e,t,r,n,a,i)=>{const s=Da(e,t,r.predicate,n,a,i);return s===null?null:Ge(s,r.align)},ka=e=>e===void 0||typeof e=="number"||e.unit!=="px"?null:{type:"px-offset",x:e.x??0,y:e.y??0},Da=(e,t,r,n,a,i)=>{if(t.has(r))return t.get(r)??null;let s=null,o=!1;const c=new Map;for(const u of n){const d=ce(r,u.data,"selection-anchor");if(d.length>0){for(const p of d)c.set(`${p.code}:${p.message}`,p);continue}o=!0;const{resolveAnchorBox:m}=e.geomRegistry.get(u.geom);if(m===void 0)continue;const h=le(r,It(u,i));if(h!==J)for(const p of u.data){if(!h(p))continue;const f=m(p,a);f!==null&&(s=s===null?f:Ql(s,f))}}if(!o)for(const u of c.values())e.diagnostics.addWarning(u);return t.set(r,s),s},Ql=(e,t)=>({xMin:Math.min(e.xMin,t.xMin),xMax:Math.max(e.xMax,t.xMax),yMin:Math.min(e.yMin,t.yMin),yMax:Math.max(e.yMax,t.yMax)}),ec=(e,t)=>{if(t===void 0)return e;const{x:r=0,y:n=0}=typeof t=="number"?{x:t,y:t}:t;return{xMin:e.xMin-r,xMax:e.xMax+r,yMin:e.yMin-n,yMax:e.yMax+n}},ct=(e,t,r)=>{const n=rc(e,t,r);return n===null?null:n.defer?.type==="annotation-ref"?n:nc(n,t.offset,e.coordSystem)},Pa=(e,t)=>t.anchorType==="selection"?Zl(e.container,e.selectionBoxCache,t,e.layers,e.coordSystem,e.parsingLocale):t.anchorType==="annotation"?{x:0,y:0,width:0,height:0,defer:{type:"annotation-ref",ref:t.ref,align:"center"}}:{x:t.x,y:1-t.y-t.height,width:t.width,height:t.height},xr=(e,t,r)=>lr(e,t,r)?.point??null,lr=({container:e,layers:t,coordSystem:r,parsingLocale:n},a,i)=>{for(const s of t){const{resolveAnchorPosition:o}=e.geomRegistry.get(s.geom);if(o===void 0||a.layerId!==void 0&&s.id!==a.layerId||a.layerId===void 0&&!s.interactive)continue;const c=ke(s),u=pe(s),{anchorValue:d,groupValue:m}=Ra(s,n)(a);let h=-1;for(const p of s.data){if(h+=1,!l.areDataValuesEqual(p[u]??null,d)||m!==void 0&&!l.areDataValuesEqual(G(p),m))continue;const f=o(p,{coordSystem:r,position:s.position,purpose:i,align:a.align});if(f===null)continue;const g=Oa(s,p,c);if(g===null)continue;const y=bt(s,p);if(y!==null)return{point:{...f,...g,anchor:a.align===void 0?y:{...y,align:a.align}},layerId:s.id,observationIndex:h}}}return null},tc=(e,t)=>{const{layers:r,coordSystem:n,scales:a,parsingLocale:i}=e;if(n.type!=="cartesian")return null;const s=a.x,o=a.y;if(s===void 0||o===void 0||s.kind!=="position"||o.kind!=="position")return null;const c=An(t.x,"x",r,i),u=An(t.y,"y",r,i);if(c===null||u===null)return null;const d=s.map(c),m=o.map(u);if(!Ee(d,m))return null;const h=xn(d,s,ac(e)),p=xn(m,o),f=bn(n.mainAxis,{main:h.min,cross:p.min}),g=bn(n.mainAxis,{main:h.max,cross:p.max});return Ge({xMin:f.x,xMax:g.x,yMin:f.y,yMax:g.y},t.align??"center")},Oa=(e,t,r)=>{const n=r(t);return l.isStrictNumericDataValue(n)?{geom:e.geom,measurementValue:n,valueFormat:Nl(Ia(e),t),yScaleType:e.yScaleType,color:At(t)}:null},rc=(e,t,r)=>{switch(t.anchorType){case"panel":return{x:t.x,y:1-t.y};case"axis":return tc(e,t);case"selection":return Jl(e.container,e.selectionBoxCache,t,e.layers,e.coordSystem,e.parsingLocale);case"annotation":return{x:0,y:0,defer:{type:"annotation-ref",ref:t.ref,align:t.align??"center",offset:t.offset}};case"observation":return xr(e,ic(t),r)}},nc=(e,t,r)=>{if(t===void 0||r.type==="polar")return e;const n=ka(t);return n!==null?{...e,defer:n}:{...e,x:e.x+(t.x??0),y:e.y-(t.y??0)}},xn=(e,t,r=1)=>{const{bandwidth:n}=t;if(n===null||n<=0)return{min:e,max:e};const a=n*r/2;return{min:e-a,max:e+a}},ac=({container:e,layers:t})=>{let r=0;for(const n of t){const a=e.geomRegistry.get(n.geom).resolveBandFraction?.(n.params);a!==void 0&&(r=Math.max(r,a))}return r>0?r:1},ic=e=>({layerId:e.layerId,anchorValue:e.anchorValue,groupValue:e.groupValue,align:e.align}),An=(e,t,r,n)=>{for(const a of r){const i=l.extractVariableName(a.mapping[t]);if(!(i===null||i===l.CONSTANT_VARIABLES.x))return l.parseValue(e,l.toExplicitValueFormat(a.data.getValueFormat(i)),n)}return e},sc=class extends l.Stage{constructor(e){super(),this.container=e}dependencies(e){return[e.annotations,e.layers,e.coordSystem,e.scales.x,e.scales.y,e.config.parsingLocale]}run(e){const{annotations:t,layers:r,coordSystem:n,scales:a,config:i}=e,s={container:this.container,layers:r,coordSystem:n,scales:a,selectionBoxCache:new Map,parsingLocale:i.parsingLocale},o={differenceArrows:yc(s,t.differenceArrows),shapes:uc(s,t.shapes),arrows:mc(s,t.arrows),textAnnotations:hc(s,t.textAnnotations),images:dc(s,t.images),stickers:pc(s,t.stickers),pinnedNumbers:fc(s,t.pinnedNumbers),comments:gc(s,t.comments)};return oc(this.container,o),lc(this.container,o),o}},Ma=(e,t,r)=>e!==null?e:!l.areDataValuesEqual(t.anchor.groupValue??null,r.anchor.groupValue??null)||t.color===void 0||t.color!==r.color?null:t.color,Z=(e,t,r,n)=>{e.diagnostics.addWarning({code:"ANNOTATION_ANCHOR_UNRESOLVED",message:`Annotation "${r}" (${t}) ${n} — dropping this annotation.`,context:{annotationId:r,kind:t},suggestion:"Check that the anchor points at data, an axis value or a panel position that exists."})},oc=(e,t)=>{const r=new Set;for(const n of Object.values(t))for(const{id:a}of n){if(r.has(a)){e.diagnostics.addWarning({code:"ANNOTATION_DUPLICATE_ID",message:`More than one annotation carries id "${a}" — references to it resolve to the first, and the rest cannot be addressed.`,context:{annotationId:a},suggestion:"Give each annotation its own id."});continue}r.add(a)}},lc=(e,t)=>{const r=new Set;for(const n of Object.values(t))for(const a of n)r.add(a.id);for(const{id:n,ref:a}of cc(t))r.has(a)||e.diagnostics.addWarning({code:"ANNOTATION_REF_NOT_FOUND",message:`Annotation "${n}" references id "${a}", whose annotation could not be anchored and was dropped.`,context:{annotationId:n,ref:a},suggestion:"Fix the anchor on the target annotation or point this reference at one that resolves."})},cc=e=>{const t=[],r=(n,a)=>{a.defer?.type==="annotation-ref"&&t.push({id:n,ref:a.defer.ref})};for(const n of e.shapes)r(n.id,n.region);for(const n of e.images)r(n.id,n.region);for(const n of e.arrows)r(n.id,n.start),r(n.id,n.end);for(const n of e.textAnnotations)r(n.id,n.at);for(const n of e.stickers)r(n.id,n.at);return t},uc=(e,t)=>{const r=[];for(const n of t){const a=Pa(e,n.region);if(a===null){Z(e.container,"shape",n.id,"has a region anchor that resolves to nothing");continue}r.push({id:n.id,kind:n.kind,zOrder:n.zOrder,region:a,fillColor:n.fillColor,fillOpacity:n.fillOpacity,strokeWidth:n.strokeWidth,strokeColor:n.strokeColor})}return r},dc=(e,t)=>{const r=[];for(const n of t){const a=Pa(e,n.region);if(a===null){Z(e.container,"image",n.id,"has a region anchor that resolves to nothing");continue}r.push({id:n.id,src:n.src,zOrder:n.zOrder,region:a,fit:n.fit,opacity:n.opacity})}return r},mc=(e,t)=>{const r=[];for(const n of t){const a=ct(e,n.start,"pin"),i=ct(e,n.end,"pin");if(a===null||i===null){Z(e.container,"arrow",n.id,`has ${_a(a,i)} resolving to nothing`);continue}r.push({id:n.id,start:a,end:i,color:n.color,thickness:n.thickness,startArrowheadStyle:n.startArrowheadStyle,endArrowheadStyle:n.endArrowheadStyle,lineStyle:n.lineStyle,hasStickerStyle:n.hasStickerStyle})}return r},hc=(e,t)=>{const r=[];for(const n of t){const a=ct(e,n.at,"pin");if(a===null){Z(e.container,"text",n.id,"has a point anchor that resolves to nothing");continue}r.push({id:n.id,content:n.content,at:a,width:n.width,align:n.align,backgroundColor:n.backgroundColor,backgroundColorStyle:n.backgroundColorStyle})}return r},pc=(e,t)=>{const r=[];for(const n of t){const a=ct(e,n.at,"pin");if(a===null){Z(e.container,"sticker",n.id,"has a point anchor that resolves to nothing");continue}r.push({id:n.id,at:a,sticker:n.sticker})}return r},fc=(e,t)=>{const r=[];for(const n of t){const a=xr(e,n.at,"pin");if(a===null){Z(e.container,"pinnedNumber",n.id,"matches no observation");continue}r.push({id:n.id,at:a})}return r},gc=(e,t)=>{const r=[];for(const n of t){const a=xr(e,n.at,"pin");if(a===null){Z(e.container,"comment",n.id,"matches no observation");continue}r.push({id:n.id,at:a,content:n.content})}return r},yc=(e,t)=>{if(e.coordSystem.type!=="cartesian"){for(const n of t)Z(e.container,"differenceArrow",n.id,"needs a cartesian coord system");return[]}const r=[];for(const n of t){const a=lr(e,n.start,"value"),i=lr(e,n.end,"value");if(a===null||i===null){Z(e.container,"differenceArrow",n.id,`has ${_a(a,i)} matching no observation`);continue}if(a.layerId===i.layerId&&a.observationIndex===i.observationIndex){Z(e.container,"differenceArrow",n.id,"has both ends on the same observation");continue}vc(e,n,a.point,i.point),r.push({id:n.id,start:a.point,end:i.point,color:Ma(n.color,a.point,i.point),ownColor:n.color,size:n.size,label:n.label,labelCrossPosition:n.labelCrossPosition})}return r},_a=(e,t)=>e===null&&t===null?"start and end anchors":e===null?"a start anchor":"an end anchor",vc=(e,t,r,n)=>{Sa(r,n)||e.container.diagnostics.addWarning({code:"INCOMPARABLE_ARROW_ENDPOINTS",message:`Difference arrow "${t.id}" measures between endpoints on different bases, so its label reports a quantity that does not exist.`,context:{annotationId:t.id,expected:ar(r),actual:ar(n)},suggestion:"Point both ends at observations sharing one y scale and one unit, or label the arrow as a proportion."})};function Na(e){return e instanceof l.VizError?{severity:"error",kind:e.kind,code:e.code,message:e.message,...e.context!==void 0?{context:e.context}:{},...e.suggestion!==void 0?{suggestion:e.suggestion}:{}}:{severity:"error",kind:"internal",code:"INTERNAL_INVARIANT",message:e instanceof Error?e.message:String(e)}}function E(e,t){return Fa(e,t)}function I(e,t){for(const r of Object.keys(t)){const n=t[r];if(n!==void 0&&n!==e[r])return{...e,...t}}return e}function Ba(e,t,r){if(e[t]===r)return e;const n=[...e];return n[t]=r,n}function Fa(e,t){let r=!1;const n={...e};for(const[a,i]of Object.entries(t)){const s=e[a];if(l.isPlainObject(i)&&l.isPlainObject(s)){const o=Fa(s,i);o!==s&&(n[a]=o,r=!0)}else i!==void 0&&i!==s&&(n[a]=i,r=!0)}return r?n:e}function Tt(e){return{pipe:t=>{const r=t(e);return Tt({...e,...r})},result:()=>e}}function bc(e,t,r){const n=Ac(r);return{...t,background:Sc(e,t.background,n),border:xc(e,t.border,n)}}function Sc(e,t,r){if(t.type==="tinted"){const n=t.color??r;return n?{type:"tinted",color:n}:(e.diagnostics.addWarning({code:"UNRESOLVABLE_COLOR",message:"Could not resolve a colour for the tinted background — falling back to the theme background.",suggestion:"Set an explicit background colour, or add a colour scale the tint can derive from."}),{type:"theme"})}return t}function xc(e,t,r){if(t.type==="tinted"||t.type==="gradient"){const n=t.color??r;return n?{...t,color:n}:(e.diagnostics.addWarning({code:"UNRESOLVABLE_COLOR",message:`Could not resolve a colour for the ${t.type} border — dropping the border.`,suggestion:"Set an explicit border colour, or add a colour scale the tint can derive from."}),{type:"none"})}return t}function Ac(e){const t=e.color,r=t?.domain[0];if(!r)return;const n=t.map(r);if(typeof n=="string")return n}var Ic=class extends l.Stage{constructor(e){super(),this.container=e}dependencies(e){return[e.scales,e.config]}run(e){const{scales:t,config:r}=e;return{...r,appearance:bc(this.container,r.appearance,t)}}};function Tc(e,t="kind"){const r=new Map;r.set(t,[]);for(const a of e)for(const i of a.observations)for(const s of Object.keys(i))r.has(s)||r.set(s,[]);for(const a of e)for(const i of a.observations)for(const[s,o]of r)o.push(s===t?a.kind:i[s]??null);const n={};for(const[a,i]of r)n[a]={type:$a(i),values:i};return new l.Dataset(n)}function $a(e){const t=Array.isArray(e)?e:[e];for(const r of t)if(r!==null)return typeof r=="number"?"numeric":r instanceof Date?"temporal":"categorical";return"categorical"}var Lc=class extends l.Stage{dependencies(e){return[e.data,e.mapping]}run(e){let t=e.data,r=e.mapping;r.x===""&&(t=t.addConstantVariable(l.CONSTANT_VARIABLES.x,"categorical",""),r={...r,x:l.CONSTANT_VARIABLES.x});for(const n of Object.keys(r)){const a=l.extractConstantValue(r[n]);if(a===void 0)continue;const i=l.prefixInternalVariable(`const_${n}`);t=t.addConstantVariable(i,$a(a),a),r={...r,[n]:i}}return{data:t,mapping:r}}},wc=(e,t)=>{let r=t;for(const n of Object.keys(t)){const a=t[n];if(typeof a!="string")continue;const i=e.getConstant(a);i!==void 0&&(r={...r,[n]:a===l.CONSTANT_VARIABLES.x?"":{value:i.value}})}return r},fe=class{constructor(){this.perLayerMemo=l.createPerKeyMemo(),this.listMemo=l.createSingleSlotMemo()}get stats(){return l.sumMemoStats(this.perLayerMemo.stats,this.listMemo.stats)}compile(e){const t=this.dependencies(e),r=e.layers.map(n=>this.perLayerMemo(n,t,()=>this.compileLayer(n,e)));return this.listMemo(r,()=>r)}},Ec=class extends l.Stage{constructor(e){super(),this.registry=e}dependencies(e){return[e.coordSpec,e.scales,e.layers]}run(e){return this.registry.get(e.coordSpec.coordType).setup(e)}},Vc=class extends fe{constructor(e){super(),this.registry=e}dependencies(e){return[e.coordSpec,e.coordSystem]}compileLayer(e,t){const[r]=this.registry.get(t.coordSpec.coordType).transform({coordSpec:t.coordSpec,coordSystem:t.coordSystem,layers:[e]});if(!r)throw new l.InternalError({message:`CoordCompiler: strategy '${t.coordSpec.coordType}' did not return a transformed layer`});return r}},Rc=class{constructor(e){this.setupStage=new Ec(e),this.transformStage=new Vc(e)}get setupStats(){return this.setupStage.stats}get transformStats(){return this.transformStage.stats}setup(e){return this.setupStage.compile(e)}transform(e){return this.transformStage.compile(e)}},Cc=class{constructor(){this.coordType="cartesian"}setup(e){if(e.coordSpec.coordType!=="cartesian")throw new l.InternalError({message:`Invalid coordinate type: ${e.coordSpec.coordType}`});return{coordSystem:{type:"cartesian",mainAxis:"x",axisMapping:{x:{position:"bottom",geometry:"linear"},y:{position:"right",geometry:"linear"}}},scales:e.scales}}transform(e){return e.layers}},kc=class{constructor(){this.coordType="flip"}setup(e){if(e.coordSpec.coordType!=="flip")throw new l.InternalError({message:`Invalid coordinate type: ${e.coordSpec.coordType}`});return{coordSystem:{type:"cartesian",mainAxis:"y",axisMapping:{x:{position:"left",geometry:"linear"},y:{position:"bottom",geometry:"linear"}}},scales:Pc(e.scales,e.layers)}}transform(e){return e.layers.map(t=>Mc(t))}},Dc=[[l.POSITION_VARIABLES.x,l.POSITION_VARIABLES.y],[l.POSITION_VARIABLES.xMin,l.POSITION_VARIABLES.yMin],[l.POSITION_VARIABLES.xMax,l.POSITION_VARIABLES.yMax]],In=l.prefixInternalVariable("flipSwap"),Pc=(e,t)=>Oc(t)?e.map(r=>r.scaledAesthetic!=="x"||r.scaleType!=="continuous"&&r.scaleType!=="datetime"&&r.scaleType!=="discrete"?r:{...r,reverse:!r.reverse}):e,Oc=e=>{for(const t of e){const r=l.extractVariableName(t.mapping.x);if(!r||!t.data.hasVariable(r))continue;const n=t.data.getType(r);if(n==="categorical"||n==="temporal")return!0}return!1},Mc=e=>{let t=e.data;for(const[r,n]of Dc){const a=t.hasVariable(r),i=t.hasVariable(n);a&&i?t=t.renameVariable(r,In).renameVariable(n,r).renameVariable(In,n):a?t=t.renameVariable(r,n):i&&(t=t.renameVariable(n,r))}return{...e,data:t}},ue=Math.PI*2,_c=8,Nc=1e-9,Ga=(e,t)=>Math.abs(t-e)>=ue-Nc,Ve=e=>(e%ue+ue)%ue,Ua=(e,t,r)=>{if(Ga(t,r))return!0;const n=Ve(r-t);return Ve(e-t)<=n},ut=(e,t)=>{const r=Math.abs(Ve(e)-Ve(t));return Math.min(r,ue-r)},Wa=(e,t,r)=>e*ue+t+r,dt=(e,t)=>({x:t*Math.sin(e),y:t*Math.cos(e)}),Ha=(e,t)=>({angle:Ve(Math.atan2(e,t)),radius:Math.hypot(e,t)}),Ar=(e,t)=>{const r=e.x-.5,n=e.y-.5;return{x:t>=1?r*2*t:r*2,y:t>=1?n*2:n*2/t}},Lt=(e,t)=>{const{x:r,y:n}=Ar(e,t);return Ha(r,n)};function Ka(e){const t=new Set,r=[];for(const n of e){const a=n instanceof Date?n.getTime():String(n);t.has(a)||(t.add(a),r.push(n))}return r}var za=(e,t)=>Ka(t.domain!==null&&t.domain.length>0?t.domain:e),Bc=class{constructor(){this.coordType="polar"}setup(e){if(e.coordSpec.coordType!=="polar")throw new l.InternalError({message:`Invalid coordinate type: ${e.coordSpec.coordType}`});const{params:t}=e.coordSpec,r=t.startAngle*(Math.PI/180),n=Gc(t,e.scales,e.layers),a=Wc(t,e.scales,e.layers);return{coordSystem:{type:"polar",axisMapping:t.theta==="x"?{x:{position:"bottom",geometry:"circular"},y:{position:"left",geometry:"radial"}}:{x:{position:"left",geometry:"radial"},y:{position:"bottom",geometry:"circular"}},innerRadius:t.innerRadius,startAngle:r,spokeRotation:n,bandAxis:a},scales:e.scales}}transform(e){if(e.coordSpec.coordType!=="polar")throw new l.InternalError({message:`Invalid coordinate type: ${e.coordSpec.coordType}`});if(e.coordSystem.type!=="polar")throw new l.InternalError({message:"PolarCoord.transform received a non-polar coord system"});const{params:t}=e.coordSpec,{startAngle:r,spokeRotation:n}=e.coordSystem,a=$c(r,n),i=Hc(t);return e.layers.map(s=>Kc(t.theta==="y"?zc(s):s,a,i))}},Fc=[[l.POSITION_VARIABLES.x,l.POSITION_VARIABLES.y],[l.POSITION_VARIABLES.xMin,l.POSITION_VARIABLES.yMin],[l.POSITION_VARIABLES.xMax,l.POSITION_VARIABLES.yMax]];function $c(e,t){return r=>Wa(r,e,t)}function Gc(e,t,r){const n=t.find(i=>i.scaledAesthetic===e.theta);if(n===void 0||n.scaleType!=="discrete")return 0;const a=Uc(n,e,r);return a===0?0:-Math.PI/a}function Uc(e,t,r){const n=[];for(const a of r){const i=l.extractVariableName(a.mapping[t.theta]);if(!(i===null||!a.data.hasVariable(i)))for(const s of a.data.getValues(i))n.push(s)}return za(n,e).length}function Wc(e,t,r){if(e.theta==="x")return"x";const n=t.find(i=>i.scaledAesthetic==="x")?.scaleType==="discrete",a=r.some(i=>i.position==="fill");return n&&!a?"y":null}function Hc(e){const{innerRadius:t}=e;return r=>t+r*(1-t)}function Kc(e,t,r){let n=e.data;return n=be(n,l.POSITION_VARIABLES.x,t),n=be(n,l.POSITION_VARIABLES.xMin,t),n=be(n,l.POSITION_VARIABLES.xMax,t),n=be(n,l.POSITION_VARIABLES.y,r),n=be(n,l.POSITION_VARIABLES.yMin,r),n=be(n,l.POSITION_VARIABLES.yMax,r),{...e,data:n}}function be(e,t,r){if(!e.hasVariable(t))return e;const n=e.getValues(t,{type:"numeric"}).map(a=>a===null?null:r(a));return e.addVariable(t,"numeric",n)}function zc(e){let t=e.data;for(const[r,n]of Fc){const a=t.hasVariable(r),i=t.hasVariable(n);if(!a&&!i)continue;const s=a?t.getValues(r):null,o=i?t.getValues(n):null;s&&(t=t.addVariable(n,"numeric",s)),o&&(t=t.addVariable(r,"numeric",o))}return{...e,data:t}}var Yc=class extends l.Registry{constructor(){super("coord"),this.register("cartesian",new Cc),this.register("flip",new kc),this.register("polar",new Bc)}},qc=new Set(["min","max","scalar"]),Xc={x:{min:l.POSITION_VARIABLES.xMin,max:l.POSITION_VARIABLES.xMax},y:{min:l.POSITION_VARIABLES.yMin,max:l.POSITION_VARIABLES.yMax}};function jc(e){const t=new Set;for(const r of e)r.role==="point"?t.add(r.axis):(r.role==="min"||r.role==="max")&&l.isDefined(r.aes)&&t.add(r.aes);return[...t]}function Zc(e){const t=new Set;for(const r of e)r.role==="point"&&t.add(r.axis),l.isDefined(r.aes)&&t.add(r.aes);return[...t]}function Jc(e,t,r){let n=e;for(const a of t){if(a.role!=="min"&&a.role!=="max"||!l.isDefined(a.aes))continue;const i=Xc[a.axis][a.role];if(n.hasVariable(i))continue;const s=l.extractVariableName(r[a.aes]);!l.isDefined(s)||!n.hasVariable(s)||(n=n.addVariable(i,"numeric",n.getValues(s,{type:"numeric"})))}return n}var Qc=class{constructor(e){this.container=e}compile(e,t){const r=this.container.geomRegistry.get(e),n=r.compile(t),a={...t.mapping,...n.mapping};return{...n,data:Jc(n.data,r.positionRoles,a)}}},Ya=new Set(["x","y","ySecondary"]),wt=new Set(["color","size","alpha","strokeWidth","lineType"]),Et=e=>Ya.has(e),Ir=e=>wt.has(e),eu=e=>Et(e)||Ir(e);function ge(e){return e==="secondary"?"ySecondary":"y"}function qa(e,t){return e==="y"?ge(t):"x"}function F(e){return e==="ySecondary"?"y":e}var Ue=(e,t)=>{if(l.isDefined(t.group)){const a=l.extractVariableName(t.group);if(a!==null)return[a]}const r=new Set([l.extractVariableName(t.x),l.extractVariableName(t.y)].filter(l.isDefined)),n=new Set;for(const a of wt){const i=l.extractVariableName(t[a]);l.isDefined(i)&&(r.has(i)||e.hasVariable(i)&&e.getType(i)==="categorical"&&n.add(i))}return[...n]},Vt=(e,t)=>e.hasVariable(l.GROUP_VARIABLES.group)?e.getValues(l.GROUP_VARIABLES.group,{distinct:!0,skipNulls:!0}).length>1:Ue(e,t).some(r=>e.getValues(r,{distinct:!0,skipNulls:!0}).length>1),tu=class{compute({data:e,mapping:t}){const r=Ue(e,t);if(r.length===0)return{data:e.addConstantVariable(l.GROUP_VARIABLES.group,"categorical",null)};const n=e.size(),a=r.map(s=>e.getValues(s)),i=new Array(n);for(let s=0;s<n;s++)i[s]=l.getStableKey(a.map(o=>o[s]));return{data:e.addVariable(l.GROUP_VARIABLES.group,"categorical",i)}}},ru=e=>{if(e===void 0)return{};const t={};for(const r of e.columns)r.label!==void 0&&(t[r.key]=r.label);return t},nu=(e,t,r)=>{const n=me(t,"color");return n===null?{}:(e?.columns??[]).some(a=>a.key===n)?{}:r};function me(e,t){const r=F(t);for(const n of Xa(t,e)){const a=l.extractVariableName(n.mapping[r]);if(l.isDefined(a))return a}return null}var Tr=(e,t)=>e===null?null:t[e]??e,au=(e,t)=>e===null?null:t[String(e)]??null,he=({layers:e,scaleType:t,variableName:r})=>{if(r===null)return _t(t);for(const n of e){if(!n.data.hasVariable(r))continue;const a=n.data.getValueFormat(r),i=a.type==="lookup"?a.fallback:a;return su(i,t)?i:_t(t)}return _t(t)},iu=(e,t)=>t!=="y"&&t!=="ySecondary"?!1:Xa(t,e).some(r=>r.position==="fill");function Xa(e,t){return e==="ySecondary"?t.filter(r=>r.yScaleType==="secondary"):e==="y"?t.filter(r=>r.yScaleType==="primary"):t}var _t=e=>{switch(e){case"continuous":return{type:"decimal"};case"datetime":return{type:"date"};case"discrete":case"palette":case"identity":return{type:"text"}}},su=(e,t)=>{switch(t){case"continuous":return l.isNumericValueFormat(e);case"datetime":return l.isTemporalValueFormat(e);case"discrete":case"palette":case"identity":return!0}},ou=[{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}],Tn={year:0,quarter:1,month:2,week:3,day:4,hour:5},Se=40,lu=(e,t,r)=>{const n=r.unit==="quarter"?r.step*3:r.step;return mu(r.unit).range(e,new Date(t.valueOf()+1),n)},cu=({unit:e,step:t,start:r,stop:n})=>{const a=(0,Dl.differenceInDays)(n,r);switch(e){case"hour":return 24*a/t>Se;case"day":return a/t>Se;case"week":return a/(7*t)>Se;case"month":return a/(30*t)>Se;case"quarter":return a/(90*t)>Se;case"year":return a/(365*t)>Se}},uu=(e,t)=>{const r=!l.isDateWithoutYearValueFormat(t);switch(e.unit){case"year":return r?{type:"year"}:{type:"month"};case"quarter":return{type:"quarter"};case"month":return r?{type:"month_year"}:{type:"month"};case"week":return r?{type:"weekly_date_range_with_year"}:{type:"weekly_date_range"};case"day":return r?{type:"date"}:{type:"day_month"};case"hour":return r?{type:"datetime"}:{type:"time"}}},du=(e,t)=>{const r=hu(t);return r===null?!1:Tn[e]>Tn[r]},mu=e=>{switch(e){case"hour":return Me.utcHour;case"day":return Me.utcDay;case"week":return Me.utcMonday;case"month":case"quarter":return Me.utcMonth;case"year":return Me.utcYear}},hu=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}},ja={left:"right",right:"left",top:"bottom",bottom:"top"},pu={x:!0,y:!0,ySecondary:!1},fu=20,Ln=new Set(["top","bottom"]),gu={type:"percentage"};function yu(e,t){const{scales:r,config:n,layers:a,coordSystem:i,variableLabels:s,geomRegistry:o}=e;if(xa(a))return[];if(i.type==="polar"&&i.bandAxis===null)return[];const c=Su(o,a,i.type,n),u=new Set(t.map(h=>h.position)),d=Au(Za(n.axes.y.position,i.axisMapping.y.position),u),m=[];for(const h of Ya){const p=r[h];if(!l.isDefined(p)||p.kind!=="position")continue;const f=vu({scaleAestheticKey:h,scale:p,config:n,layers:a,axisMapping:i.axisMapping,resolvedYPosition:d,gridOverrides:c,variableLabels:s});m.push(f)}return m}function vu(e){const{scaleAestheticKey:t,scale:r,config:n,layers:a,axisMapping:i,resolvedYPosition:s,gridOverrides:o,variableLabels:c}=e,u=F(t),{axisConfig:d,position:m,geometry:h}=xu(t,n,i,s),p=me(a,t),f=iu(a,t)?gu:he({layers:a,scaleType:r.spec.scaleType,variableName:p});return{scaleAestheticKey:t,aesthetic:u,position:m,geometry:h,label:bu(d,p,c),isVisible:d.isVisible,tickCandidates:Tu(r,f,d.ticks.mode),valueFormat:f,tickMode:d.ticks.mode,ticksVisible:d.ticks.isVisible,gridVisible:Iu(d,o,t),gridLineStyle:d.grid.lineStyle,gridLineWidth:d.grid.lineWidth,scaleType:r.spec.scaleType,bandwidth:r.bandwidth??void 0}}function bu(e,t,r){return e.label?e.label:t?r[t]??null:null}function Su(e,t,r,n){const a=t.flatMap(o=>{const c=e.get(o.geom).grid[r];return c?[c]:[]}),i=a.some(o=>o.hideGridX),s=a.some(o=>o.hideGridY);return{x:{gridVisible:wn(i,n.axes.x.grid.isVisible)},y:{gridVisible:wn(s,n.axes.y.grid.isVisible)}}}function wn(e,t){if(e&&t===null)return!1}function xu(e,t,r,n){switch(e){case"x":return{axisConfig:t.axes[e],position:Za(t.axes[e].position,r[e].position),geometry:r.x.geometry};case"y":return{axisConfig:t.axes[e],position:n,geometry:r.y.geometry};case"ySecondary":{const a=ja[n],i=(0,yt.merge)({isVisible:t.axes.y.isVisible,label:null,position:a,grid:t.axes.y.grid,ticks:t.axes.y.ticks},t.axes.ySecondary);return{axisConfig:i,position:i.position,geometry:r.y.geometry}}}}function Za(e,t){return Ln.has(e)===Ln.has(t)?e:t}function Au(e,t){return t.has(e)?ja[e]:e}function Iu(e,t,r){const{gridVisible:n}=r==="x"?t.x:t.y;return n??e.grid.isVisible??pu[r]}var Tu=(e,t,r)=>{const n=e.spec.scaleType==="continuous"||e.spec.scaleType==="datetime";if(r==="edges"&&n){const a=wu(e);if(a)return[a]}if(e.spec.scaleType==="continuous"){const a=new Set,i=[];for(let s=1;s<=fu;s++){const o=e.generateTicks({count:s}),c=l.getStableKey(o);a.has(c)||(a.add(c),i.push({ticks:o.map(u=>Re(e,u))}))}return i}return e.spec.scaleType==="datetime"?Lu(e,t):[{ticks:e.generateTicks().map(a=>Re(e,a))}]},Lu=(e,t)=>{const[r,n]=e.domain;if(!l.isStrictTemporalDataValue(r)||!l.isStrictTemporalDataValue(n))return[{ticks:e.generateTicks().map(o=>Re(e,o))}];const a=new Set,i=[],s=(o,c)=>{if(o.length===0)return;const u=l.getStableKey(o);a.has(u)||(a.add(u),i.push({ticks:o.map(d=>Re(e,d)),valueFormat:c}))};for(const o of ou)cu({...o,start:r,stop:n})||du(o.unit,t)||s(e.generateTicks({interval:o}),uu(o,t));return s(e.generateTicks({atInputs:!0})),i.sort((o,c)=>o.ticks.length-c.ticks.length),i},wu=e=>{const{domain:t}=e,r=t[0],n=t.at(-1);return!l.isDefined(r)||!l.isDefined(n)||l.getStableKey([r])===l.getStableKey([n])?null:{ticks:[Re(e,r),Re(e,n)]}},Re=(e,t)=>({value:t,position:e.map(t)});function Ja({scale:e,aesthetics:t,layers:r}){const n=Eu({layers:r,aesthetics:t}),a=Qa({layers:r,aesthetics:t});return e.domain.map(i=>({value:i,geom:n(i),owner:a(i)}))}function Eu({layers:e,aesthetics:t}){const r=Qa({layers:e,aesthetics:t}),n=e.find(i=>t.some(s=>l.isDefined(i.mapping[s]))),a=n?n.geom:"bar";return i=>{const s=r(i);return s?s.layer.geom:a}}function Qa({layers:e,aesthetics:t,layerFilter:r}){const n=new Map;for(const[a,i]of e.entries()){if(r&&!r(i))continue;const s=t.find(c=>l.isDefined(i.mapping[c]));if(s===void 0)continue;const o=l.extractVariableName(i.mapping[s]);if(!(o===null||!i.data.hasVariable(o)))for(const c of i.data.getValues(o,{distinct:!0})){const u=l.getStableKey(c);n.has(u)||n.set(u,{layer:i,layerIndex:a})}}return a=>n.get(l.getStableKey(a))}var Lr=e=>{if(e.kind==="identity")return!1;const t=e.spec.scaleType;return t!=="continuous"&&t!=="datetime"};function Vu({scales:e,layers:t,valueLabels:r}){const n=e.color;if(n===void 0||!Lr(n))return[];if(!t.some(o=>l.isDefined(o.mapping.color)))return[];const a=me(t,"color");if(ei({colorVariableName:a,xVariableName:me(t,"x"),mapsColorAcrossMultipleLayers:Cu(t)>1,isMergedWithAnotherAesthetic:Ru(e,t,a)}))return[];const i=n.spec.scaleType,s=t.findIndex(o=>l.isDefined(o.mapping.color));return Ja({scale:n,aesthetics:["color"],layers:t}).map(({value:o,geom:c,owner:u})=>{const d=u?.layerIndex??s,m=t[d],h=m?l.extractVariableName(m.mapping.color):null;return{value:o,color:String(n.map(o)),geom:c,layerIndex:d,valueFormat:he({layers:m?[m]:t,scaleType:i,variableName:h}),label:au(o,r)}})}var ei=({colorVariableName:e,xVariableName:t,mapsColorAcrossMultipleLayers:r,isMergedWithAnotherAesthetic:n})=>n?!1:e===null||l.isInternalVariable(e)?!r:t!==null&&e===t;function Ru(e,t,r){if(r===null)return!1;for(const n of wt){if(n==="color")continue;const a=e[n];if(!(a===void 0||!Lr(a))&&me(t,n)===r)return!0}return!1}var Cu=e=>e.filter(t=>l.isDefined(t.mapping.color)).length;function ti(e,t){return e.get(t.geom).summaries.perGroupHeadline===!0}function ku(e,t,r,n){const a=r.findIndex(i=>ti(e,i));return a===-1?[]:t.length<2?[{value:null,swatch:null,layerIndex:a,groupLabelFormat:{type:"text"},label:Tr(l.extractVariableName(r[a]?.mapping.y),n)}]:t.map(i=>({value:i.value,swatch:{color:i.color,geom:i.geom},layerIndex:i.layerIndex,groupLabelFormat:i.valueFormat,label:i.label}))}function En(e,t,r){if(r===null||t===null)return[...e];const n=l.getStableKey(r);return e.filter((a,i)=>l.getStableKey(t[i]??null)===n)}var Du=(e,t)=>{switch(t){case"total":{const{sum:r,count:n}=Vn(e);return n===0?null:r}case"average":{const{sum:r,count:n}=Vn(e);return n===0?null:r/n}case"current":return e.at(-1)??null}},Pu=(e,t)=>{if(e.length<2)return null;const r=e.at(-1),n=t==="previous"?e.at(-2):e.at(0);return r===void 0||n===void 0||r.cross===null||n.cross===null||n.cross===0?null:{variation:(r.cross-n.cross)/n.cross,against:n.main}},Vn=e=>e.reduce((t,r)=>r===null?t:{sum:t.sum+r,count:t.count+1},{sum:0,count:0});function Ou(e){const{config:t,coordSystem:r}=e,n=t.headline.show;return n==="none"||n==="conversion"?null:r.type==="polar"?Mu(e,n):_u(e,n)}function Mu(e,t){if(t!=="total")return null;const{scales:r,layers:n}=e,a=n.find(o=>o.summary.grandTotal!==void 0);if(a===void 0)return null;const i=a.summary.grandTotal;if(i===void 0)return null;const s=l.extractVariableName(a.mapping.y);return s===null?null:{kind:"grandTotal",value:i,valueFormat:he({layers:[a],scaleType:r.y?.spec.scaleType??"continuous",variableName:s})}}function _u(e,t){const{config:r,scales:n,layers:a,variableLabels:i,colorGroups:s,geomRegistry:o}=e;if(!a.some(d=>ti(o,d)))return null;const c=ku(o,s,a,i);if(c.length===0)return null;const u=c.map(d=>Nu({group:d,show:t,compareWith:r.headline.compareWith,layers:a,scales:n})).filter(d=>d!==null);return u.length===0?null:{kind:"perGroup",items:u}}function Nu({group:e,show:t,compareWith:r,layers:n,scales:a}){const i=n[e.layerIndex];if(i===void 0)return null;const s=l.extractVariableName(i.mapping.y);if(s===null||t==="total"&&i.position==="fill")return null;const o=l.extractVariableName(i.mapping.x),c=l.extractVariableName(i.mapping.color),u=i.yScaleType==="secondary"?a.ySecondary:a.y,d=he({layers:[i],scaleType:u?.spec.scaleType??"continuous",variableName:s}),m=$u(i.data,o),h=he({layers:[i],scaleType:m?"datetime":a.x?.spec.scaleType??"discrete",variableName:o}),p=Gu(i.data,o),f=p.getValues(s,{type:"numeric"}),g=o!==null?p.getValues(o):[],y=c!==null?p.getValues(c):null,v=En(f,y,e.value),x=En(g,y,e.value);return{value:e.value,swatch:e.swatch,aggregate:Du(v,t),valueFormat:d,groupLabelFormat:e.groupLabelFormat,mainValueFormat:h,label:e.label,observationLabel:Bu(t,m,x),comparison:Fu(t,r,m,x,v)}}function Bu(e,t,r){if(e==="current"){const i=r.at(-1);return i===void 0?null:{kind:"point",value:i}}if(!t)return null;const n=r.at(0),a=r.at(-1);return n===void 0||a===void 0?null:{kind:"range",from:n,to:a}}function Fu(e,t,r,n,a){if(e!=="current"||!r)return null;const i=t==="none"?"first":t;return Pu(n.map((s,o)=>({main:s,cross:a[o]??null})),i)}function $u(e,t){return t!==null&&e.hasVariable(t)&&e.getType(t)==="temporal"}function Gu(e,t){return t===null||!["numeric","temporal"].includes(e.getType(t))?e:e.orderBy(t)}var Uu=3;function Wu({scales:e,config:t,layers:r,coordSystem:n,variableLabels:a,colorGroups:i,geomRegistry:s}){if(t.legend.position==="none")return[];const o=new Map(i.map(g=>[l.getStableKey(g.value),g])),c=Zu(Yu({scales:e,layers:r})),u=me(r,"x"),d=c.map(g=>{if(Xu(g,u,r))return null;const y=Qu({group:g,variableLabels:a,layers:r,colorGroupsByValue:o});return y.items.length===0?null:{group:g,built:y}}).filter(l.isDefined);if(d.length===0)return[];const m=Hu(d);if(t.legend.position==="auto"&&ad(s,m,r,n))return[];const h=id(s,t.legend.position,m,r,n),p=od(s,t.legend.display,h,r,n),f=p==="direct"?dd(r):null;return d.map(({built:g})=>Ku(g,h,p,t.legend.align,f))}function Hu(e){return e.reduce((t,{group:r,built:n})=>t+(r.some(a=>a.guideType!=="discrete")?1:n.items.length),0)}function Ku(e,t,r,n,a){const i=zu(n,t);return r!=="direct"||a===null?{...e,position:t,display:r,align:i}:{...e,position:t,display:r,align:i,items:e.items.map(s=>({...s,normalizedY:a.get(String(s.value))??null}))}}function zu(e,t){return e!=="auto"?e:t==="top"||t==="bottom"?"start":"center"}function Yu(e){const{scales:t,layers:r}=e,n=[];for(const a of wt){const i=t[a];if(i===void 0||i.kind==="identity"||!qu(a,r))continue;const s=me(r,a),o=ud(a,i);n.push({scaleAestheticKey:a,scale:i,variableName:s,guideType:o})}return n}function qu(e,t){const r=F(e);return t.some(n=>l.isDefined(n.mapping[r]))}function Xu(e,t,r){const[n]=e;return n.scaleAestheticKey!=="color"?!1:ei({colorVariableName:n.variableName,xVariableName:t,mapsColorAcrossMultipleLayers:ju(n.scaleAestheticKey,r),isMergedWithAnotherAesthetic:e.length>1})}function ju(e,t){const r=F(e);return t.filter(n=>l.isDefined(n.mapping[r])).length>1}function Zu(e){const t=new Map;for(const r of e){const n=cd(r),a=t.get(n);a?a.push(r):t.set(n,[r])}return[...t.values()]}function Ju(e,t,r){if(t==="lineType"){e.lineType=r;return}if(t==="color"){e.color=String(r);return}e[t]=r}function Qu({group:e,variableLabels:t,layers:r,colorGroupsByValue:n}){const a=e[0],i=e.map(c=>F(c.scaleAestheticKey)),s=Ja({scale:a.scale,aesthetics:i,layers:r}),o=he({layers:r,scaleType:a.scale.spec.scaleType,variableName:a.variableName});return{aesthetics:e.map(c=>c.scaleAestheticKey),title:Tr(a.variableName,t),items:s.map(c=>ed(c,e,i,o,n))}}function ed(e,t,r,n,a){const i={};for(const o of t)Ju(i,o.scaleAestheticKey,o.scale.map(e.value));const s=rd(e,t,r,n,a);return{value:e.value,label:td(t,e,a),visual:i,normalizedY:null,geom:e.geom,valueFormat:s}}function td(e,t,r){return e[0].scaleAestheticKey!=="color"?null:r.get(l.getStableKey(t.value))?.label??null}function rd(e,t,r,n,a){if(t[0].scaleAestheticKey==="color")return a.get(l.getStableKey(e.value))?.valueFormat??n;const i=e.owner?.layer,s=nd(i,r);return i===void 0||s===null?n:he({layers:[i],scaleType:t[0].scale.spec.scaleType,variableName:s})}function nd(e,t){if(e===void 0)return null;for(const r of t){const n=e.mapping[r];if(n===void 0)continue;const a=l.extractVariableName(n);if(a!==null)return a}return null}function ad(e,t,r,n){if(t>1)return!1;const a=n.type==="polar";return r.some(i=>e.get(i.geom).legend.suppressWhenSingleItem||a)}function id(e,t,r,n,a){if(t!=="auto")return t;if(a.type==="polar")return"top";let i=!1,s=!1,o=!1;for(const u of n){const{sidePlacement:d}=e.get(u.geom).legend;d==="whenCrowded"&&(i=!0),d==="whenStackedVertical"&&(s=!0,O(u.position)&&(o=!0))}const c=r>=Uu;return i&&s?"top":i?c?"right":"top":o?ld(a)?"top":c?"right":"top":"top"}function sd(e,t){if(t.length!==1)return!1;const r=t[0];return r?e.get(r.geom).legend.directLabelSupport?.[r.position]===!0:!1}function od(e,t,r,n,a){if(!(r==="right"&&a.type==="cartesian"&&a.mainAxis==="x"))return"pill";switch(t){case"pill":return"pill";case"direct":return"direct";case"auto":return sd(e,n)?"direct":"pill"}}function ld(e){return e.type==="cartesian"&&e.mainAxis==="y"}function cd(e){const t=e.scale.domain.map(l.getStableKey);return JSON.stringify([e.variableName,e.guideType,...t])}function ud(e,t){return Lr(t)?"discrete":`continuous:${e}`}function dd(e){const t=e[0];if(!t)return new Map;const r=new Map;return t.data.groupBy(l.GROUP_VARIABLES.group).forEach(n=>{const a=n.findLast(u=>l.isDefined(P(u))||l.isDefined(w(u)));if(!a)return;const i=G(a);if(!l.isDefined(i))return;const s=N(a),o=P(a)??w(a);if(!l.isDefined(o))return;const c=l.isDefined(s)?(s+o)/2:o;r.set(String(i),c)}),r}var md=class extends l.Stage{constructor(e){super(),this.container=e}dependencies(e){return[e.scales,e.config.axes,e.config.legend,e.config.headline,e.config.panel,e.layers,e.coordSystem,e.originalData]}run(e){const t=ru(e.originalData),r=Vu({scales:e.scales,layers:e.layers,valueLabels:nu(e.originalData,e.layers,t)}),n={scales:e.scales,config:e.config,layers:e.layers,coordSystem:e.coordSystem,variableLabels:t,colorGroups:r,geomRegistry:this.container.geomRegistry},a=Ou(n),i=pd(a,Wu(n));return{axes:yu(n,i),legends:i,headline:a,panel:{border:hd(e.config.panel.border),cornerRadius:e.config.panel.cornerRadius},colorGroups:r,variableLabels:t}}},hd=e=>{const t=r=>({isVisible:e[r].isVisible,lineStyle:e[r].lineStyle,lineWidth:e[r].lineWidth,color:e[r].color});return{top:t("top"),right:t("right"),bottom:t("bottom"),left:t("left")}},pd=(e,t)=>e?.kind!=="perGroup"||t.some(r=>r.display==="direct")?t:[],fd=e=>l.getStableKey([G(e)]),wr=(e,t)=>l.getStableKey([t!==null?e[t]??null:null]),gd=e=>e!=="data-point",mt=(e,t,r)=>{switch(e){case"series":return fd(t);case"x-value":return wr(t,r)}},yd={bar:"observation-rerender",rule:null,line:"overlay-anchor",area:"overlay-anchor",point:"overlay-anchor"};function ri(e){const t=yd[e]??null;return t===null?null:{strategy:t,composition:ni()}}function ni(){return{isDimmed:!1,matchedLayer:null,overlayCandidates:[]}}var vd=class extends fe{constructor(e){super(),this.container=e}dependencies(e){return[e.highlights,e.config.parsingLocale]}compileLayer(e,t){const r=e.highlight;if(r===null)return e;const n=t.highlights.filter(({layerId:i})=>i===void 0||i===e.id);if(n.length===0)return e;const a=bd({layer:e,highlights:n,parsingLocale:t.config.parsingLocale,strategy:r.strategy,container:this.container});return{...e,highlight:{...r,composition:a}}}};function bd({layer:e,highlights:t,parsingLocale:r,strategy:n,container:a}){const i=t.filter(L=>{const B=ce(L.predicate,e.data);for(const q of B)a.diagnostics.addWarning({...q,message:`${q.message} Dropping this highlight.`});return B.length===0}),s=l.extractVariableName(e.mapping.x),o=It(e,r),c=i.map(L=>({predicate:le(L.predicate,o),scope:L.scope})),u=c.some(({scope:L})=>L==="series"),d=c.some(({scope:L})=>L==="x-value"),m=n==="overlay-anchor",h=e.data.size(),p=u?new Array(h):null,f=d?new Array(h):null,g=m?new Array(h):null,y=new Uint8Array(h),v=new Set,x=new Set;let T=!1,A=0;for(const L of e.data){let B,q;p!==null&&(B=mt("series",L,s),p[A]=B),f!==null&&(q=mt("x-value",L,s),f[A]=q),g!==null&&(g[A]=L);for(const{predicate:Ze,scope:Je}of c)if(Ze(L))switch(Je){case"series":B!==void 0&&v.add(B);break;case"x-value":q!==void 0&&x.add(q);break;case"data-point":y[A]=1,T=!0;break}A++}if(v.size===0&&x.size===0&&!T)return ni();const _=new Uint8Array(h),Y=[];let ee=0;for(let L=0;L<h;L++){const B=p?.[L],q=f?.[L],Ze=B!==void 0&&v.has(B),Je=q!==void 0&&x.has(q),fn=y[L]===1;if(n==="observation-rerender")(Ze||fn||Je)&&(_[L]=1,ee++);else if(Ze)_[L]=1,ee++;else if(fn||Je){const gn=g?.[L];gn!==void 0&&Y.push({observation:gn,observationIndex:L})}}const ie=ee>0?{...e,data:e.data.filterByMask(_)}:null;return{isDimmed:(n==="observation-rerender"||v.size>0)&&ie!==null,matchedLayer:ie,overlayCandidates:Y}}var Sd=l.prefixInternalVariable("__ungrouped__");function xd(e){const t=e.getVariableNames().filter(a=>e.getType(a)==="temporal"&&l.isDateWithoutYearValueFormat(e.getValueFormat(a)));if(t.length===0)return e;const r=e.getValues(l.GROUP_VARIABLES.group,{type:"categorical"});let n=e;for(const a of t){const i=n.getValues(a,{type:"temporal"}),s=new Map,o=i.map((c,u)=>{if(c===null)return null;const d=r[u]??Sd;let m=s.get(d);return m||(m=new l.ChronologicalDateManager,s.set(d,m)),m.incrementYearIfNeeded(c)});n=n.addVariable(a,"temporal",o)}return n}var Ad=()=>({defaults:[],overrides:[],warnings:[]}),Id=class extends fe{constructor(e,t,r,n,a,i){super(),this.container=e,this.transformCompiler=t,this.statCompiler=r,this.groupCompiler=n,this.geomCompiler=a,this.positionAdjusterCompiler=i}dependencies(e){return[e.data,e.mapping,Rn(e)]}compileLayer(e,t){const r=this.transformCompiler.compile({data:t.data,transforms:e.transforms}),n={...t.mapping,...e.mapping};return this.runLayerPipeline(e,r,n,Rn(t))}runLayerPipeline(e,t,r,n){const a=Tt({data:t,mapping:r}).pipe(({data:s,mapping:o})=>{const c=this.statCompiler.compute(e.stat,{data:s,mapping:o,xScaleIsDiscrete:n});return{data:c.data,mapping:{...o,...c.mapping}}}).pipe(({data:s,mapping:o})=>({data:this.groupCompiler.compute({data:s,mapping:o}).data,mapping:o})).pipe(({data:s,mapping:o})=>({data:xd(s),mapping:o})).pipe(({data:s,mapping:o})=>{const c=this.geomCompiler.compile(e.geom,{data:s,mapping:o,params:e.params});return{data:c.data,mapping:{...o,...c.mapping}}}).pipe(({data:s,mapping:o})=>{const c=this.positionAdjusterCompiler.adjust(e.position,{data:s,mapping:o});return{data:c.data,mapping:{...o,...c.mapping}}}).result(),i=this.container.geomRegistry.get(e.geom);return{...a,id:e.id,geom:e.geom,position:e.position,yScaleType:e.yScaleType,params:e.params,interactive:e.interactive,dataLabels:e.dataLabels,summary:{},spatialKind:i.spatialKind,identityKey:i.identityKey,tooltip:i.tooltip,highlight:ri(e.geom),styles:Ad()}}};function Rn(e){return e.scales.some(t=>t.scaledAesthetic==="x"&&t.scaleType==="discrete")}function ai(e,t){const[r]=t;if(r){for(const n of t)e.addError(n);throw new l.UserInputError(r)}}var Td=new Set(["label","group"]),Ld=class{constructor(e,t,r,n){this.container=e,this.transformCompiler=t,this.statRegistry=r,this.layerCompiler=n}get stats(){return this.layerCompiler.stats}compile(e){this.checkPreCompile(e);const t=this.layerCompiler.compile(e);return this.checkPostCompile(t),t}checkPreCompile(e){const t=[];e.layers.forEach((r,n)=>{const a=this.transformCompiler.compile({data:e.data,transforms:r.transforms}),i={...e.mapping,...r.mapping},s={layerId:r.id,layerIndex:n,geom:r.geom,stat:r.stat,effectiveMapping:i,data:a,coordType:e.coords.coordType,dataLabels:r.dataLabels};t.push(...this.validateLayer(s));const o=[...this.collectUndeclaredAesthetics(s),...this.collectPanelJustifyWarnings(s)];for(const c of o)this.container.diagnostics.addWarning(c)}),ai(this.container.diagnostics,t)}checkPostCompile(e){xa(e)&&this.container.diagnostics.addWarning({code:"EMPTY_DATASET",message:"No data to plot — every layer resolved to zero observations.",suggestion:"Check the dataset has rows and that transforms (filters, joins) are not removing them all."})}validateLayer(e){return[...this.validateRequiredAesthetics(e),...this.validateVariableExistence(e),...this.validatePositionalAestheticTypes(e),...this.validateGeomMapping(e),...this.validateCoordSupport(e)]}collectPanelJustifyWarnings({geom:e,effectiveMapping:t,data:r,layerIndex:n,coordType:a,dataLabels:i}){const{justify:s,showDataLabels:o}=i;if(!o||s!=="panel-start"&&s!=="panel-end")return[];if(a==="polar"||!this.container.geomRegistry.get(e).isComposite)return[];if(!Vt(r,t))return[];const c=s==="panel-end"?"end":"start";return[{code:"DATA_LABEL_PLACEMENT_COERCED",message:`Multiple ${e} groups would all pin their labels to the same panel edge; justify '${s}' will render as '${c}'.`,context:{layerIndex:n,expected:c,actual:s},suggestion:`Use justify '${c}' for this layer.`}]}validateRequiredAesthetics({layerId:e,layerIndex:t,geom:r,stat:n,effectiveMapping:a}){const i=[],{positionRoles:s,aesthetics:o}=this.container.geomRegistry.get(r),c=[...jc(s),...o.filter(m=>m.required).map(m=>m.name)],{computedVariables:u}=this.statRegistry.get(n.type),d=u;for(const m of c)d.has(m)||l.isDefined(a[m])||i.push({code:"MISSING_AESTHETIC",message:`Layer '${e}': geom '${r}' requires aesthetic '${m}'`,context:{layerIndex:t,aesthetic:m}});return i}validateVariableExistence({layerId:e,layerIndex:t,geom:r,stat:n,effectiveMapping:a,data:i}){const s=[],{computedVariables:o}=this.statRegistry.get(n.type),{derivedVariables:c}=this.container.geomRegistry.get(r),u=o,d=new Set(c);for(const[m,h]of Object.entries(a)){if(u.has(m))continue;const p=l.extractVariableName(h);p===null||p===""||d.has(p)||i.hasVariable(p)||s.push({code:"UNKNOWN_VARIABLE",message:`Layer '${e}': aesthetic '${m}' references variable '${p}' which does not exist in the dataset`,context:{layerIndex:t,aesthetic:m,variableName:p}})}return s}validatePositionalAestheticTypes({layerId:e,layerIndex:t,geom:r,stat:n,effectiveMapping:a,data:i}){const{positionRoles:s}=this.container.geomRegistry.get(r),{computedVariables:o}=this.statRegistry.get(n.type),c=o,u=[];for(const d of s){if(!qc.has(d.role)||!l.isDefined(d.aes)||c.has(d.aes)||d.role==="scalar"&&d.aes===d.axis)continue;const m=l.extractVariableName(a[d.aes]);if(m===null||!i.hasVariable(m))continue;const h=i.getType(m);h!=="numeric"&&u.push({code:"INCOMPATIBLE_TYPE",message:`Layer '${e}': aesthetic '${d.aes}' must be numeric, but variable '${m}' is ${h}`,context:{layerIndex:t,aesthetic:d.aes,variableName:m,variableType:h},suggestion:this.suggestNumericAestheticFix(d.aes,d.axis,a,i)})}return u}suggestNumericAestheticFix(e,t,r,n){const a=t==="y"?"x":"y";if(e===t){const i=l.extractVariableName(r[a]);if(i!==null&&n.hasVariable(i)&&n.getType(i)==="numeric")return`Swap the '${a}' and '${t}' mappings so the numeric variable is on '${t}'. Add coord.flip() to orient the graph horizontally.`}return`Map '${e}' to a numeric variable.`}validateGeomMapping({layerId:e,layerIndex:t,geom:r,stat:n,effectiveMapping:a}){const{validateMapping:i}=this.container.geomRegistry.get(r);if(i===void 0)return[];const{computedVariables:s}=this.statRegistry.get(n.type);return i({mapping:a,computedVariables:s}).map(o=>({...o,message:`Layer '${e}': ${o.message}`,context:{...o.context,layerIndex:t}}))}validateCoordSupport({layerId:e,layerIndex:t,geom:r,coordType:n}){const{supportedCoordTypes:a}=this.container.geomRegistry.get(r);return a.includes(n)?[]:[{code:"UNSUPPORTED_COORD",message:`Layer '${e}': geom '${r}' is not supported under ${n} coords`,context:{layerIndex:t}}]}collectUndeclaredAesthetics({layerId:e,layerIndex:t,geom:r,stat:n,effectiveMapping:a}){const{positionRoles:i,aesthetics:s}=this.container.geomRegistry.get(r),{computedVariables:o}=this.statRegistry.get(n.type),c=new Set([...Zc(i),...s.map(h=>h.name)]),u=Td,d=o,m=[];for(const h of Object.keys(a))l.isDefined(a[h])&&(c.has(h)||u.has(h)||d.has(h)||m.push({code:"UNDECLARED_AESTHETIC",message:`Layer '${e}': geom '${r}' does not declare aesthetic '${h}'; the mapping is ignored`,context:{layerIndex:t,aesthetic:h}}));return m}},re=class{constructor(){this.positionRoles=[],this.identityKey="x-group",this.defaultPosition="identity",this.defaultInteractive=!0,this.aesthetics=[],this.derivedVariables=[],this.highlightStrategy="overlay-anchor",this.supportedCoordTypes=["cartesian","flip"],this.spatialKind="points",this.grid={},this.legend={},this.dataLabelCoordTypes=[],this.isComposite=!1,this.tooltip=[],this.summaries={}}resolveParams(e){return(0,yt.merge)({},this.defaultParams,e.params)}},Er=(e,t)=>{const r=l.extractVariableName(t.x);return!r||!["numeric","temporal"].includes(e.getType(r))?e:e.orderBy(r,"asc")},Vr=(e,{coordSystem:t})=>{if(t.type==="polar")return null;const r=V(e),n=w(e);return!l.isStrictNumericDataValue(r)||!l.isStrictNumericDataValue(n)?null:{x:r,y:n}},wd=class extends re{constructor(...e){super(...e),this.type="area",this.supportedCoordTypes=["cartesian","polar","flip"],this.defaultParams={interpolate:"linear",missingValues:"zero"},this.defaultPosition="stack",this.positionRoles=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"min",valueKind:"value"},{axis:"y",role:"max",valueKind:"value",aes:"y"}],this.aesthetics=[{kind:"visual",name:"color"},{kind:"visual",name:"strokeWidth"},{kind:"visual",name:"lineType"},{kind:"visual",name:"alpha"}],this.summaries={perGroupHeadline:!0},this.dataLabels={cartesian:{offset:8},flip:{offset:8}},this.dataLabelCoordTypes=["cartesian","flip"],this.isComposite=!0,this.legend={suppressWhenSingleItem:!0,sidePlacement:"whenCrowded",directLabelSupport:{stack:!0,dodge:!0,identity:!0,fill:!0}},this.spatialKind="buckets",this.resolveAnchorPosition=Vr}resolveParams(e){const t=super.resolveParams(e);return t.missingValues==="gap"?{...t,missingValues:"zero"}:t}compile({data:e,mapping:t}){return e=Er(e,t),e.hasVariable(l.POSITION_VARIABLES.yMin)||(e=e.addConstantVariable(l.POSITION_VARIABLES.yMin,"numeric",0)),{data:e,mapping:{}}}},Cn=.7,Ed=.1,ii=e=>{const t=e[l.STACK_VARIABLES.role];return t??"solo"},Vd=class extends re{constructor(...e){super(...e),this.type="bar",this.defaultParams={width:Cn},this.defaultPosition="dodge",this.positionRoles=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"min",valueKind:"value"},{axis:"y",role:"max",valueKind:"value",aes:"y"}],this.aesthetics=[{kind:"visual",name:"color"},{kind:"visual",name:"alpha"}],this.summaries={grandTotal:!0,stackTotals:!0,perGroupHeadline:!0},this.grid={cartesian:{hideGridX:!0},flip:{hideGridX:!0}},this.legend={suppressWhenSingleItem:!0,sidePlacement:"whenStackedVertical",directLabelSupport:{stack:!0,fill:!0}},this.scaleConstraints={discreteMainAxis:!0,zeroBaseline:!0},this.dataLabels={polar:{format:"percentage"}},this.dataLabelCoordTypes=["cartesian","flip","polar"],this.highlightStrategy="observation-rerender",this.supportedCoordTypes=["cartesian","polar","flip"],this.spatialKind="rects",this.resolveAnchorBox=nr,this.resolveDataLabelDefaults=t=>O(t)?{justify:"center"}:{},this.resolveBandFraction=t=>t.width,this.resolveAnchorPosition=(t,{coordSystem:r,position:n,purpose:a,align:i})=>{if(r.type==="polar")return Rd(t);if(i!==void 0){const m=nr(t,r);return m===null?null:Ge(m,i)}const s=O(n),o={isSolo:!s||ii(t)==="solo",isNegative:s&&Cd(t),purpose:a};if(r.mainAxis==="x"){const m=K(t),h=z(t),p=kn({lowerBound:N(t),upperBound:P(t)??w(t),options:o});return m===null||h===null||p===null?null:{x:(m+h)/2,y:p}}const c=N(t),u=P(t),d=kn({lowerBound:K(t),upperBound:z(t)??V(t),options:o});return c===null||u===null||d===null?null:{x:d,y:(c+u)/2}}}resolveParams(e){const t=super.resolveParams(e),{diagnostics:r}=e;return{...t,width:this.resolveWidthParam(t.width,r)}}compile({data:e,mapping:t,params:r}){const{width:n}=r;e=Er(e,t),e.hasVariable(l.POSITION_VARIABLES.yMin)||(e=e.addConstantVariable(l.POSITION_VARIABLES.yMin,"numeric",0));const a=n/2;return e=e.addConstantVariable(l.POSITION_VARIABLES.xMin,"numeric",-a).addConstantVariable(l.POSITION_VARIABLES.xMax,"numeric",a),{data:e,mapping:{}}}resolveWidthParam(e,t){const r=typeof e=="number"&&Number.isFinite(e)?e:null;if(r!==null&&r>0&&r<=1)return r;const n=r!==null&&r>1?1:Cn;return t?.addWarning({code:"INVALID_GEOM_PARAM",message:`Bar width must be a fraction in (0, 1], got ${String(e)}; falling back to ${n}.`,context:{geom:this.type,param:"width",expected:"0 < width <= 1",actual:r??String(e)},suggestion:"Set params.width to a fraction of the category band in (0, 1]."}),n}},Rd=e=>{const t=K(e),r=z(e),n=N(e),a=P(e);if(t===null||r===null||n===null||a===null)return null;const i=(t+r)/2,s=(n+a)/2;return{x:.5+.5*s*Math.sin(i),y:.5-.5*s*Math.cos(i)}},Cd=e=>{const t=vr(e);return l.isStrictNumericDataValue(t)&&t<0},kn=e=>{const{lowerBound:t,upperBound:r,options:n}=e,a=n.isNegative?t:r;if(a===null)return null;if(n.purpose==="value"||n.isSolo)return a;const i=n.isNegative?r:t;return i===null?null:(i+a)/2},kd=class extends re{constructor(...e){super(...e),this.type="line",this.supportedCoordTypes=["cartesian","polar","flip"],this.defaultParams={interpolate:"linear",missingValues:"gap"},this.positionRoles=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"}],this.aesthetics=[{kind:"visual",name:"color"},{kind:"visual",name:"strokeWidth"},{kind:"visual",name:"lineType"},{kind:"visual",name:"alpha"}],this.summaries={perGroupHeadline:!0},this.dataLabels={cartesian:{offset:8},flip:{offset:8}},this.dataLabelCoordTypes=["cartesian","flip"],this.isComposite=!0,this.legend={suppressWhenSingleItem:!0,sidePlacement:"whenCrowded",directLabelSupport:{stack:!0,dodge:!0,identity:!0,fill:!0}},this.spatialKind="buckets",this.resolveAnchorBox=nr,this.resolveAnchorPosition=Vr}compile(e){return{data:Er(e.data,e.mapping),mapping:{}}}},Dd=class extends re{constructor(...e){super(...e),this.type="point",this.supportedCoordTypes=["cartesian","polar","flip"],this.defaultParams={},this.positionRoles=[{axis:"x",role:"point",valueKind:"value"},{axis:"y",role:"point",valueKind:"value"}],this.aesthetics=[{kind:"visual",name:"color"},{kind:"visual",name:"size"},{kind:"visual",name:"alpha"}],this.summaries={perGroupHeadline:!0},this.dataLabelCoordTypes=["cartesian","flip"],this.resolveAnchorPosition=Vr,this.resolveDefaultLabelSource=t=>{const r=l.extractVariableName(t.size);return r!==null?{variable:r}:null}}compile({data:e}){return{data:e,mapping:{}}}},Pd=class extends re{constructor(...e){super(...e),this.type="rule",this.defaultParams={labelPosition:"start"},this.defaultInteractive=!1,this.positionRoles=[{axis:"y",role:"scalar",valueKind:"value",aes:"y"},{axis:"x",role:"scalar",valueKind:"value",aes:"x"}],this.highlightStrategy=null,this.spatialKind="noop",this.validateMapping=({mapping:t,computedVariables:r})=>{const n=r.has("x")||l.isStrictNumericDataValue(l.extractConstantValue(t.x)),a=r.has("y")||l.isStrictNumericDataValue(l.extractConstantValue(t.y));return n&&a?[{code:"INVALID_RULE_MAPPING",message:"rule geom requires exactly one of 'x' or 'y', both were provided"}]:!n&&!a?[{code:"INVALID_RULE_MAPPING",message:"rule geom requires a numeric value on 'x' or 'y'"}]:[]}}compile({data:e,mapping:t}){const r=Dn(t.y,e);if(r!==null)return{data:new l.Dataset({[l.RULE_VARIABLES.y]:{type:"numeric",values:[r.value],valueFormat:r.sourceFormat}}),mapping:{y:l.RULE_VARIABLES.y,x:void 0}};const n=Dn(t.x,e);return n!==null?{data:new l.Dataset({[l.RULE_VARIABLES.x]:{type:"numeric",values:[n.value],valueFormat:n.sourceFormat}}),mapping:{x:l.RULE_VARIABLES.x,y:void 0}}:{data:new l.Dataset,mapping:{x:void 0,y:void 0}}}},Dn=(e,t)=>{const r=l.extractConstantValue(e);if(l.isStrictNumericDataValue(r))return{value:r,sourceFormat:void 0};const n=l.extractVariableName(e);if(n===null||!l.isStatVariable(n)||!t.hasVariable(n))return null;const[a]=t.getValues(n);return l.isStrictNumericDataValue(a)?{value:a,sourceFormat:t.getValueFormat(n)}:null},si=[new Vd,new Dd,new kd,new wd,new Pd],We=class extends l.Registry{constructor(){super("geom");for(const e of si)this.register(e.type,e)}},De=class{compute(e){return e.data.size()===0?{data:e.data,mapping:{}}:this.computeStat(e)}},Od=class extends De{constructor(...e){super(...e),this.type="count",this.computedVariables=new Set(["y"])}computeStat({data:e,mapping:t}){const r=l.extractVariableName(t.x);if(!l.isDefined(r))throw new l.UserInputError({code:"MISSING_STAT_VARIABLE",message:"'x' variable is required for 'count' stat",context:{aesthetic:"x"},suggestion:"Map a variable to 'x' when using the 'count' stat."});if(l.extractVariableName(t.y)!==null)throw new l.UserInputError({code:"CONFLICTING_STAT_MAPPING",message:"Cannot map 'y' variable together with 'count' stat",context:{aesthetic:"y"},suggestion:"Remove the 'y' mapping; the 'count' stat computes it."});const n=[...new Set([r,...Ue(e,t)])];return{data:e.groupBy(...n).rollup({[l.STAT_VARIABLES.count]:{variableName:r,aggregation:"count"}}),mapping:{y:l.STAT_VARIABLES.count}}}},Md=class extends De{constructor(...e){super(...e),this.type="identity",this.computedVariables=new Set}computeStat({data:e}){return{data:e,mapping:{}}}},_d=class extends De{constructor(...e){super(...e),this.type="mean",this.computedVariables=new Set(["y"])}computeStat({data:e,mapping:t}){const r=l.extractVariableName(t.y);if(!l.isDefined(r))throw new l.UserInputError({code:"MISSING_STAT_VARIABLE",message:"'y' variable is required for 'mean' stat",context:{aesthetic:"y"},suggestion:"Map a numeric variable to 'y' when using the 'mean' stat."});return{data:e.rollup({[l.STAT_VARIABLES.mean]:{variableName:r,aggregation:"mean"}}),mapping:{y:l.STAT_VARIABLES.mean}}}},Nd=2,oi=1440*60*1e3,Bd=class extends De{constructor(...e){super(...e),this.type="smooth",this.computedVariables=new Set}computeStat({data:e,mapping:t,spec:r,xScaleIsDiscrete:n}){if(r.type!=="smooth")throw new l.InternalError({message:`SmoothStat received a spec of type '${r.type}'`});const a=l.extractVariableName(t.x),i=l.extractVariableName(t.y);if(!l.isDefined(a))throw new l.UserInputError({code:"MISSING_STAT_VARIABLE",message:"'x' variable is required for 'smooth' stat",context:{aesthetic:"x"},suggestion:"Map a variable to 'x' when using the 'smooth' stat."});if(!l.isDefined(i))throw new l.UserInputError({code:"MISSING_STAT_VARIABLE",message:"'y' variable is required for 'smooth' stat",context:{aesthetic:"y"},suggestion:"Map a numeric variable to 'y' when using the 'smooth' stat."});const s=e.getType(a),o=e.getType(i);if(o!=="numeric")throw new l.UserInputError({code:"INCOMPATIBLE_TYPE",message:`'smooth' stat requires a numeric 'y' (got '${o}' for variable '${i}')`,context:{aesthetic:"y",variableName:i,variableType:o}});const c=Ue(e,t),u=Kd(a,s,i,c,e);return c.length===0?Pn({data:e,xVariable:a,xType:s,yVariable:i,spec:r,output:u,groupObservation:{},xScaleIsDiscrete:n}):e.groupBy(...c).forEach(d=>{const m=zd(d,c);Pn({data:d,xVariable:a,xType:s,yVariable:i,spec:r,output:u,groupObservation:m,xScaleIsDiscrete:n})}),{data:u.build(),mapping:{}}}},Pn=({data:e,xVariable:t,xType:r,yVariable:n,spec:a,output:i,groupObservation:s,xScaleIsDiscrete:o})=>{const{observations:c,temporalOrigin:u}=Fd({data:e,xVariable:t,yVariable:n,xType:r});c.length<Nd||(o?Hd({observations:c,spec:a,output:i,groupObservation:s}):Ud({observations:c,xType:r,temporalOrigin:u,spec:a,output:i,groupObservation:s}))},Fd=({data:e,xVariable:t,yVariable:r,xType:n})=>{const a=e.getValues(t),i=e.getValues(r,{type:"numeric"}),s=n==="temporal"?$d(a):null,o=[],c=new Map;for(let u=0;u<a.length;u++){const d=a[u],m=i[u];if(!l.isDefined(d)||!l.isDefined(m)||!Number.isFinite(m))continue;const h=Gd({xValue:d,xType:n,categoryRank:c,temporalOrigin:s});h!==null&&o.push({x:h,y:m,originalX:d})}return{observations:o,temporalOrigin:s}},$d=e=>{let t=null;for(const r of e){if(!l.isStrictTemporalDataValue(r))continue;const n=r.getTime();(t===null||n<t)&&(t=n)}return t},Gd=({xValue:e,xType:t,categoryRank:r,temporalOrigin:n})=>{switch(t){case"numeric":return!l.isStrictNumericDataValue(e)||!Number.isFinite(e)?null:e;case"temporal":{if(!l.isStrictTemporalDataValue(e))return null;const a=e.getTime();return n===null?a:(a-n)/oi+1}case"categorical":{if(!l.isStrictCategoricalDataValue(e))return null;const a=r.get(e);if(a!==void 0)return a;const i=r.size+1;return r.set(e,i),i}default:throw new l.InternalError({message:`Unexpected xType: ${t}`})}},Ud=({observations:e,xType:t,temporalOrigin:r,spec:n,output:a,groupObservation:i})=>{const s=li(n,e);for(const[o,c]of s){if(!Number.isFinite(o)||!Number.isFinite(c))continue;const u=t==="temporal"?Wd(o,r):o;a.push({x:u,y:c,groupObservation:i})}},Wd=(e,t)=>t===null?new Date(e):new Date((e-1)*oi+t),Hd=({observations:e,spec:t,output:r,groupObservation:n})=>{const a=new Map;for(const o of e)a.has(o.x)||a.set(o.x,o.originalX);const i=[...a.keys()].sort((o,c)=>o-c);if(t.method==="loess"){const o=li(t,e),c=new Map;for(const[u,d]of o)Number.isFinite(d)&&(c.has(u)||c.set(u,d));for(const u of i){const d=c.get(u),m=a.get(u);d===void 0||m===void 0||r.push({x:m,y:d,groupObservation:n})}return}const s=ci(t,e);for(const o of i){const c=a.get(o),u=s.predict(o);c===void 0||!Number.isFinite(u)||r.push({x:c,y:u,groupObservation:n})}},li=(e,t)=>e.method==="loess"?(0,se.regressionLoess)().x(r=>r.x).y(r=>r.y).bandwidth(e.bandwidth)(t):ci(e,t),ci=(e,t)=>{const r=a=>a.x,n=a=>a.y;switch(e.method){case"linear":return(0,se.regressionLinear)().x(r).y(n)(t);case"exponential":return(0,se.regressionExp)().x(r).y(n)(t);case"logarithmic":return(0,se.regressionLog)().x(r).y(n)(t);case"quadratic":return(0,se.regressionQuad)().x(r).y(n)(t);case"power":return(0,se.regressionPow)().x(r).y(n)(t);case"polynomial":return(0,se.regressionPoly)().x(r).y(n).order(e.order)(t);case"loess":throw new l.InternalError({message:"'loess' does not expose a 'predict' function"})}},Kd=(e,t,r,n,a)=>{const i=[],s=[],o=Object.fromEntries(n.map(c=>[c,[]]));return{push:({x:c,y:u,groupObservation:d})=>{i.push(c),s.push(u);for(const m of n)o[m]?.push(d[m]??null)},build:()=>{const c={[e]:{type:t,values:i,valueFormat:a.getValueFormat(e)},[r]:{type:"numeric",values:s,valueFormat:a.getValueFormat(r)}};for(const u of n)c[u]={type:a.getType(u),values:o[u]??[],valueFormat:a.getValueFormat(u)};return new l.Dataset(c)}}},zd=(e,t)=>{const r={};for(const n of t)r[n]=e.getValues(n)[0]??null;return r},Yd=[new Md,new Od,new Bd,new _d],qd=class extends l.Registry{constructor(){super("stat");for(const e of Yd)this.register(e.type,e)}};function Xd({geoms:e,stats:t,transforms:r}){const n=new We,a=new qd,i=new l.TransformRegistry;for(const s of e)n.register(s.type,s);for(const s of t)a.register(s.type,s);for(const s of r)i.register(s.transformType,s);return{geomRegistry:n,statRegistry:a,transformRegistry:i}}function Rr(e){if("definition"in e)return e.definition;if(di(e)||mi(e)||hi(e))return e}function ui(e){const t=[],r=[],n=[];for(const a of e){const i=Rr(a);i&&(di(i)?t.push(i):mi(i)?r.push(i):hi(i)&&n.push(i))}return{geoms:t,stats:r,transforms:n,warnings:[...Nt("geom",t,a=>a.type),...Nt("stat",r,a=>a.type),...Nt("transform",n,a=>a.transformType),...jd(t)]}}function jd(e){const t=[];for(const r of e)r.spatialKind!=="render-hit-test"||r.identityKey!=="x-group"||t.push({code:"RENDER_HIT_TEST_IDENTITY",message:`The render-hit-test geom '${r.type}' uses the default 'x-group' identity, which has no meaning for render-owned geometry; its hover lookup will be empty.`,context:{kind:"geom",requested:r.type},suggestion:"Declare 'identityKey' as a column the geom owns (`{ variable: '<column>' }`) or 'index', so a hit-test result resolves to an observation."});return t}function Nt(e,t,r){const n=new Map;for(const i of t){const s=r(i),o=n.get(s);o?o.add(i):n.set(s,new Set([i]))}const a=[];for(const[i,s]of n)s.size<2||a.push({code:"DUPLICATE_REGISTERED_TYPE",message:`Multiple plugins register the ${e} '${i}' (${s.size} definitions); the last in the array wins.`,context:{kind:e,requested:i},suggestion:`Remove the duplicate ${e} plugin(s) named '${i}', or rename them so each registers a distinct ${e}.`});return a}var di=e=>e instanceof re,mi=e=>e instanceof De,hi=e=>"transformType"in e&&typeof e.apply=="function",Zd=class{constructor(e){this.registry=e}adjust(e,t){return this.registry.get(e).adjust(t)}},Rt=class{},Jd=class extends Rt{constructor(...e){super(...e),this.type="dodge"}adjust({data:e,mapping:t}){if(!l.extractVariableName(t.x))return{data:e,mapping:{}};const r=e.getValues(l.GROUP_VARIABLES.group,{type:"categorical",distinct:!0,skipNulls:!0});if(r.length===0)return{data:e,mapping:{}};const n=e.size(),a=e.getValues(l.GROUP_VARIABLES.group,{type:"categorical"}),i=Qd(e)??[-.7/2,.7/2],s=r.length>1?Ed:0,o=(0,j.scaleBand)().domain(r.map(String)).range(i).paddingInner(s).paddingOuter(0),c=o.bandwidth(),u=new Array(n).fill(null),d=new Array(n).fill(null);for(let m=0;m<n;m++){const h=a[m];if(!l.isDefined(h))continue;const p=o(String(h));l.isDefined(p)&&(u[m]=p,d[m]=p+c)}return{data:e.addVariable(l.POSITION_VARIABLES.xMin,"numeric",u).addVariable(l.POSITION_VARIABLES.xMax,"numeric",d),mapping:{}}}},Qd=e=>{const t=e.getConstant(l.POSITION_VARIABLES.xMin)?.value,r=e.getConstant(l.POSITION_VARIABLES.xMax)?.value;return typeof t!="number"||typeof r!="number"?null:[t,r]},On=l.prefixInternalVariable("__ungrouped__"),pi=(e,t)=>{const r=l.extractVariableName(t.x),n=l.extractVariableName(t.y);if(!r||!n)return null;const a=e.getValues(l.GROUP_VARIABLES.group,{type:"categorical",distinct:!0,skipNulls:!0}),i=a.length===0,s=i?[On]:a,o=e.getValues(r),c=e.getValues(n,{type:"numeric"}),u=e.getValues(l.GROUP_VARIABLES.group,{type:"categorical"}),d=e.size(),m=new Map;for(let h=0;h<d;h++){const p=l.getStableKey(o[h]??null),f=u[h],g=i?On:f;if(!l.isDefined(g))continue;let y=m.get(p);y||(y=new Map,m.set(p,y));let v=y.get(g);v||(v=[],y.set(g,v)),v.push(h)}return{yValues:c,observationIndicesByXAndGroup:m,uniqueGroupKeys:s,observationCount:d}},fi=(e,t,r,n)=>{const a=new Array(n).fill(null);for(const[,i]of r){const s=[];let o=-1,c=1/0,u=-1/0,d=-1,m=1/0,h=-1/0;for(const p of i.values())for(const f of p){const g=e[f],y=t[f];!l.isDefined(g)||!l.isDefined(y)||(s.push(f),(g<c||g===c&&y>u)&&(o=f,c=g,u=y),(y>h||y===h&&g<m)&&(d=f,m=g,h=y))}for(const p of s)a[p]=em(p===o,p===d)}return a},em=(e,t)=>e&&t?"solo":e?"floor":t?"ceiling":"middle",tm=class extends Rt{constructor(...e){super(...e),this.type="fill"}adjust({data:e,mapping:t}){const r=pi(e,t);if(r===null)return{data:e,mapping:{}};const{yValues:n,observationIndicesByXAndGroup:a,uniqueGroupKeys:i,observationCount:s}=r,o=[...n],c=new Array(s).fill(0);for(const[,d]of a){let m=0,h=0;for(const g of i){const y=d.get(g);if(y!==void 0)for(const v of y){const x=n[v];x!=null&&(x>=0?m+=x:h-=x)}}let p=0,f=0;for(const g of i){const y=d.get(g);if(y!==void 0)for(const v of y){const x=n[v];if(x===void 0)continue;if(x===null){c[v]=null,o[v]=null;continue}const T=x>=0?m:h;if(T===0){c[v]=0,o[v]=0;continue}const A=x/T;x>=0?(c[v]=p,o[v]=p+=A):(o[v]=f,c[v]=f+=A)}}}const u=fi(c,o,a,s);return{data:e.addVariable(l.POSITION_VARIABLES.yMin,"numeric",c).addVariable(l.POSITION_VARIABLES.yMax,"numeric",o).addVariable(l.POSITION_VARIABLES.yRaw,"numeric",n).addVariable(l.STACK_VARIABLES.role,"categorical",u),mapping:{}}}},rm=class extends Rt{constructor(...e){super(...e),this.type="identity"}adjust({data:e}){return{data:e,mapping:{}}}},nm=class extends Rt{constructor(...e){super(...e),this.type="stack"}adjust({data:e,mapping:t}){const r=pi(e,t);if(r===null)return{data:e,mapping:{}};const{yValues:n,observationIndicesByXAndGroup:a,uniqueGroupKeys:i,observationCount:s}=r,o=[...n],c=new Array(s).fill(0);for(const[,h]of a){let p=0,f=0;for(const g of i){const y=h.get(g);if(y!==void 0)for(const v of y){const x=n[v];if(x!==void 0){if(x===null){c[v]=null,o[v]=null;continue}x>=0?(c[v]=p,o[v]=p+=x):(o[v]=f,c[v]=f+=x)}}}}const u=fi(c,o,a,s);let d=e.addVariable(l.POSITION_VARIABLES.yMin,"numeric",c).addVariable(l.POSITION_VARIABLES.yMax,"numeric",o).addVariable(l.POSITION_VARIABLES.yRaw,"numeric",n).addVariable(l.STACK_VARIABLES.role,"categorical",u);const m=l.extractVariableName(t.y);return m!==null&&(d=d.addVariable(m,"numeric",o)),{data:d,mapping:{}}}},am=class extends l.Registry{constructor(){super("position"),this.register("identity",new rm),this.register("stack",new nm),this.register("fill",new tm),this.register("dodge",new Jd)}},im=class{map({data:e,layer:t,getPositionScale:r,geomRegistry:n}){let a=e;const i=n.get(t.geom);for(const s of i.positionRoles){if(s.role!=="scalar"||!l.isDefined(s.aes)||Ir(s.aes))continue;const o=l.extractVariableName(t.mapping[s.aes]);if(!l.isDefined(o)||!a.hasVariable(o))continue;const c=r(qa(s.axis,t.yScaleType));if(!c)continue;const u=a.getValues(o,{type:"numeric"}).map(d=>l.isDefined(d)?c.map(d):null);a=a.addVariable(l.resolveScaledAestheticVariable(s.aes),"numeric",u)}return a}},sm=class{map({data:e,layer:t,getPositionScale:r}){const n=l.extractVariableName(t.mapping.x),a=r("x");if(!n||!a)return e;const i=e.getValues(n).map(s=>l.isDefined(s)?a.map(s):null);return e.addVariable(l.POSITION_VARIABLES.x,"numeric",i)}},om=class{map({data:e,getPositionScale:t}){const r=t("x");if(!r?.bandwidth||!e.hasVariable(l.POSITION_VARIABLES.x)||!e.hasVariable(l.POSITION_VARIABLES.xMin)||!e.hasVariable(l.POSITION_VARIABLES.xMax))return e;const n="reverse"in r.spec&&r.spec.reverse===!0,a=e.getValues(l.POSITION_VARIABLES.x,{type:"numeric"}),i=e.getValues(l.POSITION_VARIABLES.xMin,{type:"numeric"}),s=e.getValues(l.POSITION_VARIABLES.xMax,{type:"numeric"}),o=e.size(),c=new Array(o),u=new Array(o);for(let d=0;d<o;d++){const m=a[d],h=i[d],p=s[d];if(l.isDefined(m)&&l.isDefined(h)&&l.isDefined(p)){const f=n?-p:h,g=n?-h:p;c[d]=m+f*r.bandwidth,u[d]=m+g*r.bandwidth}else c[d]=null,u[d]=null}return e.addVariable(l.POSITION_VARIABLES.xMin,"numeric",c).addVariable(l.POSITION_VARIABLES.xMax,"numeric",u)}},lm=class{map({data:e,layer:t,getPositionScale:r}){const n=l.extractVariableName(t.mapping.y),a=r(ge(t.yScaleType));if(!n||!a)return e;const i=e.getValues(n).map(s=>l.isDefined(s)?a.map(s):null);return e.addVariable(l.POSITION_VARIABLES.y,"numeric",i)}},cm=class{map({data:e,layer:t,getPositionScale:r}){const n=r(ge(t.yScaleType));if(!n||!e.hasVariable(l.POSITION_VARIABLES.yMin)||!e.hasVariable(l.POSITION_VARIABLES.yMax))return e;const a=e.getValues(l.POSITION_VARIABLES.yMin,{type:"numeric"}),i=e.getValues(l.POSITION_VARIABLES.yMax,{type:"numeric"}),s=e.size(),o=new Array(s),c=new Array(s);for(let u=0;u<s;u++){const d=a[u],m=i[u];l.isDefined(d)&&l.isDefined(m)?(o[u]=n.map(d),c[u]=n.map(m)):(o[u]=null,c[u]=null)}return e.addVariable(l.POSITION_VARIABLES.yMin,"numeric",o).addVariable(l.POSITION_VARIABLES.yMax,"numeric",c)}},um=[new sm,new lm,new om,new cm,new im];function dm(e,t){const r=e[t];return r?.kind==="position"?r:null}var mm=class extends fe{constructor(e,t=um){super(),this.container=e,this.mappers=t}dependencies(e){return[e.scales.x,e.scales.y,e.scales.ySecondary]}compileLayer(e,t){const r=a=>dm(t.scales,a);let n=e.data;for(const a of this.mappers)n=a.map({data:n,layer:e,getPositionScale:r,geomRegistry:this.container.geomRegistry});return{...e,data:n}}},hm=class extends l.Stage{constructor(e,t){super(),this.container=e,this.registry=t}dependencies(e){return[e.layers,e.scales]}run(e){this.validateScaleTypeCompatibility(e);const t=new Map;for(const a of e.scales)t.set(a.scaledAesthetic,a);const r=this.collectValues(e.layers,t),n={};for(const[a,i]of t){const s=r.get(a)??[];n[a]=this.registry.get(i.scaleType).compile(i,s)}return n}validateScaleTypeCompatibility(e){const t=[];for(const r of e.scales){const{compatibleDataTypes:n}=this.registry.get(r.scaleType),a=F(r.scaledAesthetic),i=e.layers.find(c=>l.isDefined(c.mapping[a]));if(!i)continue;const s=l.extractVariableName(i.mapping[a]);if(!l.isDefined(s)||!i.data.hasVariable(s))continue;const o=i.data.getType(s);if(n.includes(o)||t.push({code:"INCOMPATIBLE_TYPE",message:`Scale '${r.scaledAesthetic}' (${r.scaleType}) is incompatible with variable '${s}' (${o})`,context:{aesthetic:a,variableName:s,scaleType:r.scaleType,variableType:o}}),r.scaledAesthetic==="lineType"&&o!=="categorical"){const c=o==="temporal"?"Bucket the variable into categorical periods (e.g. quarter, year) first.":"Bin the variable into categorical buckets first.";t.push({code:"INCOMPATIBLE_TYPE",message:`Scale 'lineType' is discrete-only and cannot be mapped to ${o} variable '${s}'. ${c}`,context:{aesthetic:a,variableName:s,scaleType:r.scaleType,variableType:o},suggestion:c})}}ai(this.container.diagnostics,t)}collectValues(e,t){const r=new Map;for(const n of e){const a=this.resolveCustomPositionalAxes(n);for(const[i,s]of Object.entries(n.mapping)){if(!l.isDefined(s))continue;const o=i==="y"?ge(n.yScaleType):i,c=a.get(i)??(eu(o)?o:void 0);if(!l.isDefined(c)||!t.has(c))continue;const u=this.resolveVariables(i,s,n.data);this.collectFromVariables(n.data,u,c,r)}}return r}resolveCustomPositionalAxes(e){const t=new Map,r=this.container.geomRegistry.get(e.geom);for(const n of r.positionRoles)n.role!=="scalar"||!l.isDefined(n.aes)||Ir(n.aes)||t.set(n.aes,qa(n.axis,e.yScaleType));return t}resolveVariables(e,t,r){if(e==="y"&&this.hasPositionAdjustedY(r))return[l.POSITION_VARIABLES.yMin,l.POSITION_VARIABLES.yMax];const n=l.extractVariableName(t);return!n||!r.hasVariable(n)?[]:[n]}hasPositionAdjustedY(e){return e.hasVariable(l.POSITION_VARIABLES.yMin)&&e.hasVariable(l.POSITION_VARIABLES.yMax)}collectFromVariables(e,t,r,n){if(t.length===0)return;let a=[];for(const s of t)a=a.concat(e.getValues(s));const i=n.get(r);n.set(r,i?i.concat(a):a)}},pm=["rgb","lab","hcl","hsl"],fm=["viridis","magma","inferno","plasma","cividis","turbo","Blues","Greens","Greys","Oranges","Purples","Reds"],gi=["RdBu","BrBG","PuOr","Spectral"],yi={"red-blue":"RdBu","brown-teal":"BrBG","purple-orange":"PuOr",spectral:"Spectral"},gm=new Set(gi.map(e=>e.toLowerCase()));function vi(e){const t=e.toLowerCase(),r=yi[t];return r?r.toLowerCase():t}function ym(e){return gm.has(vi(e))}var vm={rgb:Le.interpolateRgb,lab:Le.interpolateLab,hcl:Le.interpolateHcl,hsl:Le.interpolateHsl},bm={viridis:k.interpolateViridis,magma:k.interpolateMagma,inferno:k.interpolateInferno,plasma:k.interpolatePlasma,cividis:k.interpolateCividis,turbo:k.interpolateTurbo,blues:k.interpolateBlues,greens:k.interpolateGreens,greys:k.interpolateGreys,oranges:k.interpolateOranges,purples:k.interpolatePurples,reds:k.interpolateReds,rdbu:k.interpolateRdBu,brbg:k.interpolateBrBG,puor:k.interpolatePuOr,spectral:k.interpolateSpectral};function Cr(e){const t=xm(e);return e.reverse?r=>t(1-r):t}function Sm(e={},t=2){const r=Cr({range:e.range??null,scheme:e.scheme??null,interpolate:e.interpolate??l.CONTINUOUS_SCALE_DEFAULTS.interpolate,reverse:e.reverse??!1});return t<2?t===1?[r(0)]:[]:Array.from({length:t},(n,a)=>r(a/(t-1)))}function xm(e){const t=vm[e.interpolate];if(e.range&&e.range.length>=2)return(0,Le.piecewise)(t,e.range.map(r=>String(r)));if(e.scheme){const r=bm[vi(e.scheme)];if(r)return r}return(0,Le.piecewise)(t,[...l.DEFAULT_SEQUENTIAL_RAMP])}var He=class{createPositionScale(e,t){return{kind:"position",aesthetic:F(e.scaledAesthetic),spec:e,...t}}createVisualScale(e,t){return{kind:"visual",aesthetic:F(e.scaledAesthetic),spec:e,...t}}},Am=class extends He{constructor(e){super(),this.container=e,this.compatibleDataTypes=["numeric"]}compile(e,t){if(e.scaleType!=="continuous")throw new l.InternalError({message:"ContinuousScale.compile received non-continuous spec"});const r=Et(e.scaledAesthetic),n=e.scaledAesthetic==="color",a=this.computeDataDomain(t,e);return n?this.buildColorScale(a,e):r?this.buildPositionScale(a,e):this.buildVisualScale(a,e)}computeDataDomain(e,t){let r=1/0,n=-1/0;for(const a of e)typeof a=="number"&&(a<r&&(r=a),a>n&&(n=a));return r===1/0?[0,0]:(t.zero&&(r>0&&(r=0),n<0&&(n=0)),[r,n])}createD3Scale(e,t,r){let n=[r.domainMin??e[0],r.domainMax??e[1]];const a=r.transform==="log"&&Im(n);r.transform==="log"&&!a&&this.container.diagnostics.addWarning({code:"INCOMPATIBLE_SCALE_DOMAIN",message:`Log scale on '${r.scaledAesthetic}' needs a strictly positive or negative domain, but the domain is [${e[0]}, ${e[1]}] — rendering a linear scale instead.`,context:{aesthetic:F(r.scaledAesthetic),scaleType:r.scaleType,actual:e},suggestion:"Filter out non-positive values or set a positive domainMin so the log scale can apply."});const i=a?(0,j.scaleLog)():r.transform==="sqrt"?(0,j.scaleSqrt)():(0,j.scaleLinear)();r.nice&&!a&&(n=i.copy().domain(n).nice().domain());const s=r.domainMin??n[0],o=r.domainMax??n[1];return i.domain([s,o]).range(t).clamp(r.clamp)}buildPositionScale(e,t){const r=t.reverse?[1,0]:[0,1],n=this.createD3Scale(e,r,t);return this.createPositionScale(t,{map:n,domain:n.domain(),bandwidth:null,generateTicks:a=>a&&"count"in a?n.ticks(a.count):n.ticks()})}buildVisualScale(e,t){const r=Tm(t.range)??[0,1],n=t.reverse?[r[1],r[0]]:r,a=this.createD3Scale(e,n,t);return this.createVisualScale(t,{map:a,domain:a.domain(),generateTicks:i=>i&&"count"in i?a.ticks(i.count):a.ticks()})}buildColorScale(e,t){const r=Cr(t),n=t.domainMid;if(n!==null){const[a,i]=this.resolveColorDomain(e,t);if(n>a&&n<i){const[s,o]=this.symmetrizeDomain([a,i],t,n);return this.buildDivergingColorScale([s,n,o],t,r)}}return this.buildSequentialColorScale(e,t,r)}buildSequentialColorScale(e,t,r){const n=this.createD3Scale(e,[0,1],t),a=i=>typeof i!="number"||!Number.isFinite(i)?null:r(n(i));return this.createVisualScale(t,{map:a,domain:n.domain(),generateTicks:i=>i&&"count"in i?n.ticks(i.count):n.ticks()})}buildDivergingColorScale(e,t,r){const n=(0,j.scaleLinear)().domain(e).range([0,.5,1]).clamp(t.clamp),a=i=>typeof i!="number"||!Number.isFinite(i)?null:r(n(i));return this.createVisualScale(t,{map:a,domain:e,generateTicks:i=>i&&"count"in i?n.ticks(i.count):n.ticks()})}resolveColorDomain(e,t){let r=t.domainMin??e[0],n=t.domainMax??e[1];if(t.nice){const a=(0,j.scaleLinear)().domain([r,n]).nice().domain();r=t.domainMin??a[0],n=t.domainMax??a[1]}return[r,n]}symmetrizeDomain(e,t,r){if(!t.symmetric)return e;const n=Math.max(Math.abs(e[0]-r),Math.abs(e[1]-r));return[t.domainMin??r-n,t.domainMax??r+n]}},Im=e=>{const[t,r]=e;return t>0&&r>0||t<0&&r<0};function Tm(e){if(!e)return null;const[t,r]=e;return typeof t=="number"&&typeof r=="number"?[t,r]:null}var Lm=class extends He{constructor(...e){super(...e),this.compatibleDataTypes=["temporal"]}compile(e,t){if(e.scaleType!=="datetime")throw new l.InternalError({message:"DatetimeScale.compile received non-datetime spec"});const r=Et(e.scaledAesthetic),n=this.computeDataDomain(t);if(!r)throw new l.UserInputError({code:"INCOMPATIBLE_TYPE",message:"Datetime scale is not supported for non-position aesthetics",context:{aesthetic:e.scaledAesthetic},suggestion:"Use a continuous or discrete scale for non-position aesthetics (color, size, alpha, strokeWidth)."});return this.buildScale(n,e,this.collectInputDates(t))}collectInputDates(e){const t=new Set,r=[];for(const n of e){if(!(n instanceof Date))continue;const a=n.getTime();t.has(a)||(t.add(a),r.push(n))}return r.sort((n,a)=>n.getTime()-a.getTime()),r}computeDataDomain(e){let t=1/0,r=-1/0;for(const n of e){if(!(n instanceof Date))continue;const a=n.getTime();a<t&&(t=a),a>r&&(r=a)}return t===1/0?[]:[new Date(t),new Date(r)]}createD3Scale(e,t,r){const n=wm(e)?e:[],a=(0,j.scaleUtc)().domain(n).range(t).clamp(r.clamp);if(r.nice&&a.nice(),l.isDefined(r.domainMin)||l.isDefined(r.domainMax)){const[i,s]=a.domain();i!==void 0&&s!==void 0&&a.domain([r.domainMin??i,r.domainMax??s])}return a}buildScale(e,t,r){const n=t.reverse?[1,0]:[0,1],a=this.createD3Scale(e,n,t),[i,s]=a.domain(),o=i&&s?r.filter(c=>c>=i&&c<=s):[];return this.createPositionScale(t,{map:a,domain:a.domain(),bandwidth:null,generateTicks:c=>c&&"atInputs"in c?o:c&&"interval"in c?i&&s?lu(i,s,c.interval):[]:a.ticks(c?.count)})}},wm=e=>e.length===2&&l.isStrictTemporalDataValue(e[0])&&l.isStrictTemporalDataValue(e[1]),Em=class extends He{constructor(...e){super(...e),this.compatibleDataTypes=["categorical","numeric","temporal"]}compile(e,t){if(e.scaleType!=="discrete")throw new l.InternalError({message:"DiscreteScale.compile received non-discrete spec"});const r=Et(e.scaledAesthetic),n=za(t,e);return r?this.buildPositionScale(n,e):this.buildVisualScale(n,e)}buildPositionScale(e,t){const r=e.map(String),n=t.padding??l.DISCRETE_SCALE_DEFAULTS.padding,a=t.reverse?[1,0]:[0,1],i=(0,j.scaleBand)().domain(r).range(a).paddingInner(n).paddingOuter(n/2),s=i.bandwidth()/2;return this.createPositionScale(t,{map:o=>(i(String(o))??NaN)+s,domain:e,bandwidth:i.bandwidth(),generateTicks:()=>[...e]})}buildVisualScale(e,t){const r=e.map(String),n=t.range&&t.range.length>0?(0,j.scaleOrdinal)().domain(r).range(t.range).unknown(t.range[0]):null;return this.createVisualScale(t,{map:a=>{const i=String(a);return n?n(i):i},domain:e,generateTicks:()=>e})}},Vm=class extends He{constructor(...e){super(...e),this.compatibleDataTypes=["numeric","categorical","temporal"]}compile(e){if(e.scaleType!=="identity")throw new l.InternalError({message:"IdentityScale.compile received non-identity spec"});return{kind:"identity",aesthetic:F(e.scaledAesthetic),spec:e,map:t=>t,domain:[],generateTicks:()=>[]}}},Rm=class extends He{constructor(...e){super(...e),this.compatibleDataTypes=["categorical","temporal","numeric"]}compile(e,t){if(e.scaleType!=="palette")throw new l.InternalError({message:"PaletteScale.compile received non-palette spec"});const r=Ka(t),n=l.resolvePaletteRange(e.palette,r.length),a=l.applyOverrides(n.length>0?n:[...l.DEFAULT_COLOR_PALETTE],e.overrides),i=(0,j.scaleOrdinal)().domain(r.map(String)).range(a).unknown(a[0]);return this.createVisualScale(e,{map:s=>i(String(s)),domain:r,generateTicks:()=>r})}},Cm=class extends l.Registry{constructor(e){super("scale"),this.register("continuous",new Am(e)),this.register("discrete",new Em),this.register("datetime",new Lm),this.register("identity",new Vm),this.register("palette",new Rm)}},at={color:null,size:"small",labelCrossPosition:.5},xe={kind:"rectangle",zOrder:"foreground",fillColor:"transparent",fillOpacity:1,strokeWidth:1,strokeColor:null},Bt={zOrder:"foreground",fit:"contain",opacity:1},km={x:8,y:8,unit:"px"},Ft={align:"center",backgroundColor:null,backgroundColorStyle:"opaque"},Ae={color:null,thickness:"medium",startArrowheadStyle:"none",endArrowheadStyle:"line-arrow",lineStyle:"solid",hasStickerStyle:!1},Dm={top:{x:0,y:-1},bottom:{x:0,y:1},left:{x:-1,y:0},right:{x:1,y:0},"top-left":{x:-1,y:-1},"top-right":{x:1,y:-1},"bottom-left":{x:-1,y:1},"bottom-right":{x:1,y:1}},Pm=(e,t,r)=>{const n=Om(e,t),a=Nm(n);return{differenceArrows:(n.differenceArrows??[]).map(i=>Fm(e,i,r)).filter(l.isDefined),shapes:(n.shapes??[]).map(i=>Wm(e,i,a)).filter(l.isDefined),arrows:(n.arrows??[]).map(i=>zm(e,i,r,a)).filter(l.isDefined),textAnnotations:(n.textAnnotations??[]).map(i=>Bm(e,i,r,a)).filter(l.isDefined),stickers:(n.stickers??[]).map(i=>$m(e,i,r,a)).filter(l.isDefined),images:(n.images??[]).map(i=>Hm(e,i,a)).filter(l.isDefined),pinnedNumbers:(n.pinnedNumbers??[]).map(i=>Gm(e,i,r)).filter(l.isDefined),comments:(n.comments??[]).map(i=>Um(e,i,r)).filter(l.isDefined)}},Om=(e,t)=>{if(t===void 0)return{};if(!Mm(t))return t;const r=new Set,n=a=>a.id===void 0?a:r.has(a.id)?(e.diagnostics.addWarning({code:"ANNOTATION_DUPLICATE_ID",message:`More than one annotation declares id "${a.id}" — giving this one a generated id, so references to "${a.id}" point at the first.`,context:{annotationId:a.id},suggestion:"Give each annotation its own id."}),{...a,id:C()}):(r.add(a.id),a);return{differenceArrows:t.differenceArrows?.map(a=>n(a)),shapes:t.shapes?.map(a=>n(a)),arrows:t.arrows?.map(a=>n(a)),textAnnotations:t.textAnnotations?.map(a=>n(a)),images:t.images?.map(a=>n(a)),stickers:t.stickers?.map(a=>n(a)),pinnedNumbers:t.pinnedNumbers?.map(a=>n(a)),comments:t.comments?.map(a=>n(a))}},Mm=e=>{const t=new Set;for(const r of _m(e))if(r.id!==void 0){if(t.has(r.id))return!0;t.add(r.id)}return!1},_m=e=>[...e.differenceArrows??[],...e.shapes??[],...e.arrows??[],...e.textAnnotations??[],...e.images??[],...e.stickers??[],...e.pinnedNumbers??[],...e.comments??[]],Nm=e=>{const t=new Set,r=[e.differenceArrows,e.shapes,e.arrows,e.textAnnotations,e.images,e.stickers,e.pinnedNumbers,e.comments];for(const n of r)for(const a of n??[])a.id!==void 0&&t.add(a.id);return t},kr=(e,t,r,n)=>{if(r.has(t))return!0;const a=n===void 0?"An annotation":`Annotation "${n}"`;return e.diagnostics.addWarning({code:"ANNOTATION_REF_NOT_FOUND",message:`${a} references id "${t}" but no annotation declares that id — dropping this annotation.`,context:{ref:t,...n!==void 0?{annotationId:n}:{}},suggestion:"Reference the explicit id of another annotation in the same spec, or set an id on the target."}),!1},Bm=(e,t,r,n)=>{const a=ht(e,t.at,r,n,t.id);return a===null?null:{id:t.id??C(),content:t.content,at:a,width:t.width,align:t.align??Ft.align,backgroundColor:t.backgroundColor??Ft.backgroundColor,backgroundColorStyle:t.backgroundColorStyle??Ft.backgroundColorStyle}},Fm=(e,t,r)=>{const n=Fe(e,t.start,r),a=Fe(e,t.end,r);return n===null||a===null?null:{id:t.id??C(),start:n,end:a,label:t.label,color:t.color??at.color,size:t.size??at.size,labelCrossPosition:t.labelCrossPosition??at.labelCrossPosition}},Fe=(e,t,r)=>{const n=t.align!==void 0?{align:t.align}:{};return t.layerId===void 0?{anchorValue:t.anchorValue,groupValue:t.groupValue,...n}:r.some(a=>a.id===t.layerId)?{layerId:t.layerId,anchorValue:t.anchorValue,groupValue:t.groupValue,...n}:(e.diagnostics.addWarning({code:"UNKNOWN_LAYER_ID",message:`Annotation references layerId "${t.layerId}", which no layer carries — dropping this annotation.`,context:{layerId:t.layerId,available:r.map(a=>a.id)},suggestion:"Reference an existing layer id, or omit layerId to anchor against the data directly."}),null)},ht=(e,t,r,n,a)=>{if(t.anchorType==="annotation")return kr(e,t.ref,n,a)?t:null;if(t.anchorType==="panel"||t.anchorType==="axis"||t.anchorType==="selection")return t;const i=Fe(e,t,r);return i===null?null:{anchorType:"observation",...i,...t.offset!==void 0?{offset:t.offset}:{}}},$m=(e,t,r,n)=>{const a=ht(e,t.at,r,n,t.id);return a===null?null:{id:t.id??C(),at:a,sticker:t.sticker}},Gm=(e,t,r)=>{const n=Fe(e,t.at,r);return n===null?null:{id:t.id??C(),at:n}},Um=(e,t,r)=>{const n=Fe(e,t.at,r);return n===null?null:{id:t.id??C(),at:n,content:t.content}},Wm=(e,t,r)=>t.region.anchorType==="annotation"&&!kr(e,t.region.ref,r,t.id)?null:{id:t.id??C(),kind:t.kind??xe.kind,zOrder:t.zOrder??xe.zOrder,region:Km(t.region),fillColor:t.fillColor??xe.fillColor,fillOpacity:t.fillOpacity??xe.fillOpacity,strokeWidth:t.strokeWidth??xe.strokeWidth,strokeColor:t.strokeColor??xe.strokeColor},Hm=(e,t,r)=>t.region.anchorType==="annotation"&&!kr(e,t.region.ref,r,t.id)?null:{id:t.id??C(),src:t.src,zOrder:t.zOrder??Bt.zOrder,region:t.region,fit:t.fit??Bt.fit,opacity:t.opacity??Bt.opacity},Km=e=>e.anchorType!=="selection"||e.padding!==void 0?e:{...e,padding:km},Mn=e=>{if(e.anchorType==="panel"||e.anchorType==="axis"||e.offset!==void 0||e.align===void 0)return e;const t=Dm[e.align];return t===void 0?e:{...e,offset:{x:t.x*4,y:t.y*4,unit:"px"}}},zm=(e,t,r,n)=>{const a=ht(e,t.start,r,n,t.id),i=ht(e,t.end,r,n,t.id);return a===null||i===null?null:{id:t.id??C(),start:Mn(a),end:Mn(i),color:t.color??Ae.color,thickness:t.thickness??Ae.thickness,startArrowheadStyle:t.startArrowheadStyle??Ae.startArrowheadStyle,endArrowheadStyle:t.endArrowheadStyle??Ae.endArrowheadStyle,lineStyle:t.lineStyle??Ae.lineStyle,hasStickerStyle:t.hasStickerStyle??Ae.hasStickerStyle}},Ym={parsingLocale:"en-US",legend:{position:"auto",display:"auto",align:"auto"},axes:{x:{isVisible:!0,label:null,position:"bottom",grid:{isVisible:null,lineStyle:"dashed",lineWidth:null},ticks:{isVisible:!0,mode:"auto"}},y:{isVisible:!0,label:null,position:"right",grid:{isVisible:null,lineStyle:"dashed",lineWidth:null},ticks:{isVisible:!1,mode:"auto"}}},panel:{border:{top:{isVisible:!0,lineStyle:"dashed",lineWidth:null,color:null},right:{isVisible:!0,lineStyle:"dashed",lineWidth:null,color:null},bottom:{isVisible:!0,lineStyle:"dashed",lineWidth:null,color:null},left:{isVisible:!0,lineStyle:"dashed",lineWidth:null,color:null}},cornerRadius:8,overflow:{dataLabels:{x:"inside",y:"inside"},differenceArrows:{x:"outside",y:"outside"}}},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,brandMark:{enabled:!1,placement:"footer",variant:"full"},isBrandMarkVisible:!1},appearance:{textScale:1,background:{type:"theme"},border:{type:"none"},cornerRadius:8},layout:{padding:null,gaps:{}}};function qm(e){const t=(0,yt.merge)({},Ym,e);return t.content=Xm(t.content,e?.content),t}var Xm=(e,t)=>{const r=t?.brandMark?.enabled??t?.isBrandMarkVisible??e.brandMark.enabled,n={...e.brandMark,enabled:r};return{...e,brandMark:n,isBrandMarkVisible:r}},jm={xLimits:null,yLimits:null},$t={theta:"x",startAngle:0,innerRadius:0};function Zm(e){const t=e??{type:"coord",coordType:"cartesian"},r=(0,lt.default)({},jm,t.params??{});switch(t.coordType){case"cartesian":case"flip":return{...t,params:r};case"polar":return{...t,params:{...r,theta:t.params?.theta??$t.theta,startAngle:t.params?.startAngle??$t.startAngle,innerRadius:t.params?.innerRadius??$t.innerRadius}}}}function Jm(e,t,r){const n=[];for(const a of t){if(a.layerId!==void 0&&!r.some(i=>i.id===a.layerId)){e.diagnostics.addWarning({code:"UNKNOWN_LAYER_ID",message:`Highlight references layerId "${a.layerId}", which no layer carries — dropping this highlight.`,context:{layerId:a.layerId,available:r.map(i=>i.id)},suggestion:"Reference an existing layer id, or omit layerId to apply the highlight across all layers."});continue}n.push({type:"highlight",id:a.id??C(),predicate:a.predicate,scope:a.scope??"data-point",...a.layerId!==void 0?{layerId:a.layerId}:{}})}return n}var Qm=class{constructor(){this.diagnostics=[],this.persistent=[]}addWarning(e,t={}){const r={...e,severity:"warning",kind:"user-input"};t.persistent?this.persistent.push(r):this.diagnostics.push(r)}addError(e){this.diagnostics.push({...e,severity:"error",kind:"user-input"})}reset(){this.diagnostics=[]}drain(){const e=this.persistent.length===0?this.diagnostics:[...this.persistent,...this.diagnostics];if(e.length===0)return{errors:[],warnings:[]};const t=_n(e.filter(n=>n.severity==="error")),r=_n(e.filter(n=>n.severity==="warning"));return this.diagnostics=[],{errors:t,warnings:r}}},eh=class{constructor(e,t){this.sink=e,this.baseContext=t}addWarning(e,t){this.sink.addWarning(this.stampBaseContext(e),t)}addError(e){this.sink.addError(this.stampBaseContext(e))}stampBaseContext(e){const t=e.context??{};return{...e,context:{...t,...this.baseContext}}}};function _n(e){const t=new Set;return e.filter(r=>{const n=JSON.stringify(r);return t.has(n)?!1:(t.add(n),!0)})}var th={showDataLabels:!1,format:"absolute",showStackTotals:!1,showCategoryLabels:!1,labelSource:{variable:l.POSITION_VARIABLES.yRaw},position:"auto",justify:"end",align:"center",offset:4,categoryPosition:"inside",categoryJustify:"start",categoryAlign:"center",categoryOffset:4};function bi(e,t){const r=e??t,n=typeof r=="string"?r:r.type;if(n==="smooth"){const a=typeof r=="string"?void 0:r;return{type:"smooth",method:a?.method??"linear",order:a?.order??3,bandwidth:a?.bandwidth??.3}}return{type:n}}function Dr(e,t,r,n,a,i){const s=a!==void 0&&i!==void 0?new eh(a,{layerIndex:i}):a,o=e.get(n.geom),c=n.position??o.defaultPosition,u=ih({dataLabels:oh(e,t,n,c,r),geom:o,position:c,coordType:r,diagnostics:s});return ah({diagnostics:s,coordType:r,geom:o,position:c,dataLabels:u}),{id:n.id??C(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:bi(n.stat,"identity"),position:c,yScaleType:n.yScaleType??"primary",params:o.resolveParams({params:n.params,diagnostics:s}),transforms:n.transforms??[],interactive:n.interactive??o.defaultInteractive,dataLabels:u}}function rh(e,t,r,n,a){const i=n.map((s,o)=>Dr(e,t,r,s,a,o));return lh(e,i)}var nh=(e,t,r,n)=>n.label!==void 0?n.label:ch(e,t,r,n),ah=({diagnostics:e,coordType:t,geom:r,position:n,dataLabels:a})=>{if(e===void 0)return;const i=r.type==="bar"&&t==="polar",s=r.type==="bar"&&t!=="polar";if(a.showDataLabels&&!r.dataLabelCoordTypes.includes(t)){e.addWarning({code:"DATA_LABELS_UNSUPPORTED",message:`Data labels are not supported for geom '${r.type}' under '${t}' coords; none will render.`,suggestion:"Turn off showDataLabels for this layer."});return}a.showDataLabels&&a.position==="outside"&&s&&O(n)&&e.addWarning({code:"DATA_LABEL_PLACEMENT_COERCED",message:"Stacked bar segments only place data labels inside; position 'outside' will render as 'inside'.",context:{expected:"inside",actual:"outside"},suggestion:"Use position 'inside' or 'auto', or enable showStackTotals for a label above the stack."}),a.showStackTotals&&!(s&&n==="stack")&&e.addWarning({code:"DATA_LABEL_SETTING_IGNORED",message:"showStackTotals only applies to stacked cartesian bars; it will be ignored.",suggestion:"Turn off showStackTotals, or use a bar geom with position 'stack'."}),a.showCategoryLabels&&a.showDataLabels&&!i&&e.addWarning({code:"DATA_LABEL_SETTING_IGNORED",message:"showCategoryLabels only applies to polar bars (pie / donut); it will be ignored.",suggestion:"Turn off showCategoryLabels for this layer."})},ih=({dataLabels:e,geom:t,position:r,coordType:n,diagnostics:a})=>{const{justify:i,showDataLabels:s}=e;if(i!=="panel-start"&&i!=="panel-end")return e;const o=sh(t,r,n);if(o===null)return e;const c=i==="panel-end"?"end":"start";return s&&a?.addWarning({code:"DATA_LABEL_PLACEMENT_COERCED",message:`${o}; justify '${i}' will render as '${c}'.`,context:{expected:c,actual:i},suggestion:`Use justify '${c}' for this layer.`}),{...e,justify:c}},sh=(e,t,r)=>r==="polar"?"Panel-edge anchors do not apply under polar coords":e.type==="bar"&&O(t)?"Stacked bar segments would all pin their labels to the same panel edge":null,oh=(e,t,r,n,a)=>{const i={...t,...r.mapping},s=nh(e,r.geom,n,i),o=e.get(r.geom);return{...(0,yt.merge)({},th,o.resolveDataLabelDefaults?.(n)??{},o.dataLabels?.[a]??{},r.dataLabels??{}),labelSource:s}},lh=(e,t)=>{const r=new Set;for(const n of t)n.position==="fill"&&r.add(n.yScaleType);return r.size===0?t:t.map(n=>{if(!r.has(n.yScaleType)||!e.get(n.geom).positionRoles.some(s=>s.axis==="y"&&s.role==="scalar"))return n;const a=l.extractConstantValue(n.mapping.y);if(!l.isStrictNumericDataValue(a))return n;const i=Math.min(1,Math.max(0,a));return{...n,mapping:{...n.mapping,y:{value:i}}}})},ch=(e,t,r,n)=>e.get(t).resolveDefaultLabelSource?.(n)??xt(r,n),Si={x:"position",y:"position",ySecondary:"position",color:"color-range",size:"continuous-range",alpha:"continuous-range",strokeWidth:"continuous-range",lineType:"discrete-only"},uh={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 xi(e,t,r,n,a,i){switch(t.scaleType){case"inferred":return xi(e,hh(e,t,r,n,a),r,n,a,i);case"continuous":{const s=Si[t.scaledAesthetic],o=s==="continuous-range"&&t.scaledAesthetic in l.NON_POSITION_RANGE_DEFAULTS?l.NON_POSITION_RANGE_DEFAULTS[t.scaledAesthetic]:null,c=t.scaledAesthetic==="size"&&s==="continuous-range"?"sqrt":l.CONTINUOUS_SCALE_DEFAULTS.transform;return{type:t.type,scaledAesthetic:t.scaledAesthetic,scaleType:t.scaleType,transform:t.transform??c,reverse:t.reverse??l.CONTINUOUS_SCALE_DEFAULTS.reverse,nice:t.nice??l.CONTINUOUS_SCALE_DEFAULTS.nice,zero:t.zero??l.CONTINUOUS_SCALE_DEFAULTS.zero,clamp:t.clamp??s!=="position",domainMin:t.domainMin??l.CONTINUOUS_SCALE_DEFAULTS.domainMin,domainMax:t.domainMax??l.CONTINUOUS_SCALE_DEFAULTS.domainMax,range:t.range??o??null,scheme:ph(e,t),interpolate:t.interpolate??l.CONTINUOUS_SCALE_DEFAULTS.interpolate,domainMid:t.domainMid??l.CONTINUOUS_SCALE_DEFAULTS.domainMid,symmetric:t.symmetric??l.isDefined(t.domainMid)}}case"datetime":return{type:t.type,scaledAesthetic:t.scaledAesthetic,scaleType:t.scaleType,domainMin:t.domainMin??l.DATETIME_SCALE_DEFAULTS.domainMin,domainMax:t.domainMax??l.DATETIME_SCALE_DEFAULTS.domainMax,nice:t.nice??l.DATETIME_SCALE_DEFAULTS.nice,reverse:t.reverse??l.DATETIME_SCALE_DEFAULTS.reverse,clamp:t.clamp??!1};case"discrete":return{type:t.type,scaledAesthetic:t.scaledAesthetic,scaleType:t.scaleType,range:t.range??l.DISCRETE_SCALE_DEFAULTS.range,domain:t.domain??l.DISCRETE_SCALE_DEFAULTS.domain,padding:t.padding??l.DISCRETE_SCALE_DEFAULTS.padding,reverse:t.reverse??l.DISCRETE_SCALE_DEFAULTS.reverse};case"palette":return{type:t.type,scaledAesthetic:t.scaledAesthetic,scaleType:t.scaleType,palette:l.resolvePaletteConfig(e,t.palette,i),overrides:l.resolvePaletteOverrides(e,t.overrides,t.palette,i)};case"identity":return{type:t.type,scaledAesthetic:t.scaledAesthetic,scaleType:t.scaleType};default:throw new l.InternalError({message:`Unknown scale type: ${t.scaleType}`})}}function dh(e,t,r,n,a,i,s){const o=vh(yh(r,n)),c=new Map;for(const d of o)c.set(d.scaledAesthetic,d);const u=[...c.values()].map(d=>xi(e,d,t,n,a,s));return i.coordType==="polar"?mh(u):u}var mh=e=>e.map(t=>t.scaleType==="discrete"?{...t,padding:0}:t);function hh(e,t,r,n,a){const i=F(t.scaledAesthetic),s=t.scaledAesthetic==="ySecondary"?gh(n,a):a[i],{layer:o,scaleConstraints:c}=fh(e,n);if(t.scaledAesthetic==="x"&&c?.discreteMainAxis)return l.discrete(t.scaledAesthetic,t.options);const u=o?.yScaleType==="secondary"?"ySecondary":"y";if(c?.zeroBaseline&&o&&t.scaledAesthetic===u){const p=t.options,f=o.position==="fill";return l.continuous(t.scaledAesthetic,{...p,zero:!0,...f&&{nice:!1}})}const d=l.extractVariableName(s);if(!l.isDefined(d)||!r.hasVariable(d))return l.continuous(t.scaledAesthetic,t.options);const m=r.getType(d),h=Si[t.scaledAesthetic];switch(uh[m][h]){case"discrete":return l.discrete(t.scaledAesthetic,t.options);case"datetime":return l.datetime(t.scaledAesthetic,t.options);case"continuous":return l.continuous(t.scaledAesthetic,t.options);default:return l.identity(t.scaledAesthetic)}}function ph(e,t){const r=t.scheme??l.CONTINUOUS_SCALE_DEFAULTS.scheme;return r===null?null:l.isDefined(t.range)?(e.diagnostics.addWarning({code:"CONFLICTING_COLOR_RAMP",message:`The color scale sets both a 'scheme' ('${r}') and an explicit 'range'; the range wins and the scheme is ignored.`,context:{aesthetic:F(t.scaledAesthetic),scaleType:t.scaleType},suggestion:"Set either a scheme or a range, not both."}),null):(!l.isDefined(t.domainMid)&&ym(r)&&e.diagnostics.addWarning({code:"DIVERGING_SCHEME_WITHOUT_MIDPOINT",message:`The color scale uses a diverging scheme ('${r}') without 'domainMid', so its neutral colour lands at the data midpoint rather than a meaningful centre.`,context:{aesthetic:F(t.scaledAesthetic),scaleType:t.scaleType,actual:r},suggestion:"Set 'domainMid' (e.g. 0) to centre the neutral colour."}),r)}function fh(e,t){for(const r of t){const{scaleConstraints:n}=e.geomRegistry.get(r.geom);if(n!==void 0)return{layer:r,scaleConstraints:n}}return{}}function gh(e,t){const r=e.find(n=>n.yScaleType==="secondary");return r?r.mapping.y??t.y:t.y}function yh(e,t){return!t.some(r=>r.yScaleType==="secondary")||e.some(r=>r.scaledAesthetic==="ySecondary")?e:[...e,l.inferred("ySecondary")]}function vh(e){return e.some(t=>t.scaledAesthetic==="color")?e:[...e,l.palette("color")]}var bh=e=>{const t=new Set;e!==void 0&&Ai(e,t,new Set);const r={tokens:{},defaults:[],overrides:[]};for(const n of t)Object.assign(r.tokens,n.tokens),r.defaults.push(...n.defaults??[]),r.overrides.push(...n.overrides??[]);return r},Ai=(e,t,r)=>{if(!r.has(e)){r.add(e);for(const n of e.extends??[])Ai(n,t,r);t.delete(e),t.add(e),r.delete(e)}};function Sh(e,t,r){const n=Zm(t.coords),a=rh(e.geomRegistry,t.mapping,n.coordType,t.layers,e.diagnostics),i=dh(e,t.data,t.scales,a,t.mapping,n,r),s=qm(t.config),o=Jm(e,t.highlights,a),c=Pm(e,t.annotations,a),u=bh(t.styles);return{data:t.data,mapping:t.mapping,layers:a,scales:i,transforms:t.transforms,highlights:o,styles:u,annotations:c,coords:n,config:s}}var Ii=class{constructor(e){this.container=e}compile({input:e,dataset:t,customPalettes:r}){return Sh(this.container,{...e,data:t},r)}},xh=class{constructor(e){this.registry=e}compute(e,t){return this.registry.get(e.type).compute({data:t.data,mapping:t.mapping,spec:e,xScaleIsDiscrete:t.xScaleIsDiscrete})}},Ah=class extends fe{constructor(e){super(),this.container=e}compile(e){const t=super.compile(e);for(const r of wh(e.styles,t))this.container.diagnostics.addWarning(r);for(const r of Eh(e.styles))this.container.diagnostics.addWarning(r);for(const r of Vh(e.styles))this.container.diagnostics.addWarning(r);for(const r of t)for(const n of r.styles.warnings)this.container.diagnostics.addWarning(n);return t}dependencies(e){return[e.styles,e.config.parsingLocale]}compileLayer(e,t){const r=ki({layer:e,layerIndex:t.layers.indexOf(e),styles:t.styles,parsingLocale:t.config.parsingLocale});return{...e,styles:r}}},Ti=["color","alpha","saturation"],Li={bar:["color","alpha","saturation","borderRadius","borderColor","borderWidth"],line:["color","alpha","saturation","strokeWidth","lineType","fillAlpha"],area:["color","alpha","saturation","strokeWidth","lineType","strokeAlpha"],point:["color","alpha","saturation","size","borderColor","borderWidth"],rule:["color","strokeWidth","lineType"]},Ih=[...new Set([...Ti,...Object.values(Li).flatMap(e=>e??[])])],Th=(e,t,r="en-US")=>ki({layer:e,layerIndex:0,styles:{tokens:t.tokens??{},defaults:t.defaults??[],overrides:t.overrides??[]},parsingLocale:r}),wi=e=>(e!==void 0?Li[e]:void 0)??Ti,Lh=(e,t,r)=>{const n=[];return l.BUILTIN_STYLES.defaults.forEach((a,i)=>{const s=a.select.kind;if(s!==void 0&&s!==e)return;const o={list:"builtin"},c=Di({declarations:a.declarations,vocabulary:wi(s),tokens:t,location:`builtin[${i}]`,origin:o,warnings:r});Object.keys(c).length!==0&&n.push({declarations:c,matches:Ei,...a.when?.state===void 0?{}:{state:a.when.state},origin:o})}),n},Ei=()=>!0,Vi=(e,t)=>{e.defaults.forEach((r,n)=>t(r,"defaults",n)),e.overrides.forEach((r,n)=>t(r,"overrides",n))},wh=(e,t)=>{const r=new Set(t.map(a=>a.id)),n=[];return Vi(e,(a,i,s)=>{const o=a.select.layer;o===void 0||r.has(o)||n.push({code:"INVALID_STYLE_RULE",message:`Style ${i}[${s}] targets unknown layer '${o}'.`,context:{param:"layer",actual:o,...a.id===void 0?{}:{styleEntryId:a.id}},suggestion:"Set 'layer' to the id of a layer in the spec."})}),n},Eh=e=>{const t=[];return Vi(e,(r,n,a)=>{const i=r.when?.state;i===void 0||Ri(i)||t.push({code:"INVALID_STYLE_RULE",message:`Style ${n}[${a}] scopes to unknown state '${i}'.`,context:{param:"state",actual:String(i),...r.id===void 0?{}:{styleEntryId:r.id}},suggestion:`Set 'state' to one of ${l.STYLE_STATES.map(s=>`'${s}'`).join(", ")}.`})}),t},Ri=e=>l.STYLE_STATES.includes(e),Vh=e=>{const t=[];for(const[r,n]of Object.entries(e.tokens))Ci(n)||t.push({code:"INVALID_STYLE_RULE",message:`Style token '${r}' has an invalid value: ${pt(n)}.`,context:{param:"tokens",actual:pt(n)},suggestion:`Set '${r}' to a non-empty color string or a { light, dark } pair of colors.`});return t},Ci=e=>typeof e=="string"?e.trim().length>0:l.isLightDarkColor(e)&&e.light.trim().length>0&&e.dark.trim().length>0,pt=e=>typeof e=="object"&&e!==null?JSON.stringify(e):String(e),ki=e=>{const{layer:t,layerIndex:r,styles:n,parsingLocale:a}=e,i=It(t,a),s=[],o={...l.BUILTIN_STYLES.tokens,...n.tokens},c=(u,d)=>{const m=[];return u.forEach((h,p)=>{const f=h.select.kind;if(f!==void 0&&f!==t.geom||h.select.layer!==void 0&&h.select.layer!==t.id)return;const g=h.when?.state;if(g!==void 0&&!Ri(g))return;const y={list:d,index:p,...h.id===void 0?{}:{id:h.id}},v=h.when?.where;if(v!==void 0){const T=ce(v,t.data,"style-rule");if(T.length>0){for(const A of T)s.push({...A,code:"INVALID_STYLE_RULE",message:`Style ${d}[${p}]: ${A.message}`,context:{...A.context,layerIndex:r,...h.id===void 0?{}:{styleEntryId:h.id}}});return}}const x=Di({declarations:h.declarations,vocabulary:wi(f),tokens:o,location:`${d}[${p}]`,origin:y,warnings:s});Object.keys(x).length!==0&&m.push({declarations:x,matches:v===void 0?Ei:le(v,i),...g===void 0?{}:{state:g},origin:y})}),m};return{defaults:[...Lh(t.geom,o,s),...c(n.defaults,"defaults")],overrides:c(n.overrides,"overrides"),warnings:s}},Di=e=>{const{declarations:t,vocabulary:r,tokens:n,location:a,origin:i,warnings:s}=e,o={},c=i.list==="builtin"||i.id===void 0?{}:{styleEntryId:i.id},u=(p,f,g)=>{s.push({code:"INVALID_STYLE_RULE",message:`Style ${a} declaration '${p}' ignored: expected ${f}, got ${pt(g)}.`,context:{param:p,expected:f,actual:pt(g),...c},suggestion:`Set '${p}' to ${f}.`})},d=(p,f)=>{if(typeof f=="string"){if(f.trim().length>0)return f;u(p,"a non-empty color string",f);return}if(l.isStyleTokenRef(f)){const g=n[f.token];if(g===void 0){s.push({code:"INVALID_STYLE_RULE",message:`Style ${a} declaration '${p}' ignored: unknown token '${f.token}'.`,context:{param:p,actual:f.token,...c},suggestion:`Declare '${f.token}' in the stylesheet's tokens.`});return}return Ci(g)?typeof g=="string"?g:{light:g.light,dark:g.dark}:void 0}if(l.isLightDarkColor(f)&&f.light.trim().length>0&&f.dark.trim().length>0)return{light:f.light,dark:f.dark};u(p,"a non-empty color string, a { light, dark } pair, or a token(...) reference",f)};for(const p of Object.keys(t)){if(t[p]===void 0||r.includes(p))continue;const f=Ih.includes(p);s.push({code:"INVALID_STYLE_RULE",message:`Style ${a} declaration '${p}' ignored: ${f?"not in this entry's vocabulary":"not a style property"}.`,context:{param:p,...c},suggestion:f?`Declare '${p}' on an entry whose kind supports it (e.g. style.geom.bar).`:`Remove the unknown declaration '${p}'.`})}for(const p of["color","borderColor"]){const f=t[p];if(f===void 0||!r.includes(p))continue;const g=d(p,f);g!==void 0&&(o[p]=g)}for(const p of["alpha","saturation","strokeAlpha","fillAlpha"]){const f=t[p];f===void 0||!r.includes(p)||(Number.isFinite(f)&&f>=0&&f<=1?o[p]=f:u(p,"a number in [0, 1]",f))}for(const p of["borderWidth","strokeWidth","size"]){const f=t[p];f===void 0||!r.includes(p)||(Number.isFinite(f)&&f>=0?o[p]=f:u(p,"a non-negative number of pixels",f))}const{borderRadius:m,lineType:h}=t;return m!==void 0&&r.includes("borderRadius")&&(l.isBorderRadiusToken(m)?o.borderRadius=m:u("borderRadius",`one of ${l.BORDER_RADIUS_TOKENS.map(p=>`'${p}'`).join(", ")}`,m)),h!==void 0&&r.includes("lineType")&&(Ta(h)?o.lineType=h:u("lineType",`one of ${br.map(p=>`'${p}'`).join(", ")}`,h)),o},Rh=({layer:e})=>{if(e.position==="stack")return;const t=l.extractVariableName(e.mapping.y);if(t===null)return;let r=0,n=0;for(const a of e.data){const i=a[t];l.isStrictNumericDataValue(i)&&(r+=i,n+=Math.abs(i))}return{grandTotal:r,absoluteGrandTotal:n}},Ch=({layer:e})=>{if(e.position!=="stack")return;const t=l.extractVariableName(e.mapping.x);if(t===null||!e.data.hasVariable(l.POSITION_VARIABLES.yMin)||!e.data.hasVariable(l.POSITION_VARIABLES.yMax))return;const r=new Map;for(const a of e.data){const i=a[t],s=N(a),o=P(a),c=K(a),u=z(a),d=vr(a);if(!l.isDefined(i)||!l.isDefined(s)||!l.isDefined(o)||!l.isDefined(c)||!l.isDefined(u)||!l.isDefined(d))continue;const m=d>=0;if(Math.abs(d)===0)continue;const h=wr(a,t),p={yMin:s,yMax:o},f=r.get(h);if(f===void 0){r.set(h,{total:d,topPositive:m?p:null,bottomNegative:m?null:p,anchorXMin:c,anchorXMax:u});continue}f.total+=d,m?(f.topPositive===null||o>f.topPositive.yMax)&&(f.topPositive=p):(f.bottomNegative===null||s<f.bottomNegative.yMin)&&(f.bottomNegative=p)}const n=[];for(const[a,i]of r){const s=i.topPositive??i.bottomNegative;s!==null&&n.push({xKey:a,total:i.total,anchor:{xMin:i.anchorXMin,xMax:i.anchorXMax,yMin:s.yMin,yMax:s.yMax,direction:i.topPositive!==null?"positive":"negative"}})}return n},kh=class extends fe{constructor(e){super(),this.container=e}dependencies(){return[]}compileLayer(e){const t=this.container.geomRegistry.get(e.geom),r={};if(t.summaries.stackTotals){const n=Ch({layer:e});n!==void 0&&(r.stackTotals=n)}if(t.summaries.grandTotal){const n=Rh({layer:e});n!==void 0&&(r.grandTotal=n.grandTotal,r.absoluteGrandTotal=n.absoluteGrandTotal)}return{...e,summary:r}}},Dh=class extends l.Stage{constructor(e){super(),this.registry=e}key(e){return e.data}dependencies(e){return[e.transforms]}run(e){return e.transforms.reduce((t,r)=>this.registry.get(r.transformType).apply(t,r),e.data)}},Nn={color:"categorical",size:"numeric",alpha:"numeric",strokeWidth:"numeric",lineType:"categorical"},Ph=["color","size","alpha","strokeWidth","lineType"],Oh=class extends fe{dependencies(e){return Ph.map(t=>e.scales[t])}compileLayer(e,t){let r=e.data;const n=Object.entries(l.VISUAL_VARIABLES);for(const[a,i]of n){const s=l.extractConstantValue(e.mapping[a]);if(s!==void 0){r=r.deriveVariable(i,Nn[a],()=>s);continue}const o=l.extractVariableName(e.mapping[a]),c=t.scales[a];if(!c||c.kind!=="visual")continue;const u=Mh(o,c);u&&(r=r.deriveVariable(i,Nn[a],u))}return{...e,data:r}}},Mh=(e,t)=>e?r=>l.isDefined(r[e])?t.map(r[e]):null:null;function _h(e=new We){return{diagnostics:new Qm,geomRegistry:e}}var Pi=class{constructor(e,t,r,n,a,i,s,o,c,u,d,m,h,p,f,g){this.container=e,this.dataCompiler=t,this.specCompiler=r,this.transformCompiler=n,this.constantMappingCompiler=a,this.layerPhasedCompiler=i,this.scaleCompiler=s,this.coordCompiler=o,this.positionMapperCompiler=c,this.visualMapperCompiler=u,this.guideCompiler=d,this.summariseCompiler=m,this.stylesCompiler=h,this.highlightsCompiler=p,this.configCompiler=f,this.annotationsCompiler=g,this.lastCompile=null,this.lastDiagnostics=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.layerPhasedCompiler.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:"styles",getStats:()=>this.stylesCompiler.stats},{name:"highlights",getStats:()=>this.highlightsCompiler.stats},{name:"config",getStats:()=>this.configCompiler.stats},{name:"annotations",getStats:()=>this.annotationsCompiler.stats}]}compile(e){try{const t=this.runCompile(()=>(this.lastData=e.data,this.runPipeline({spec:this.specCompiler.compile({input:e.input,customPalettes:e.customPalettes??{},dataset:this.dataCompiler.compile(e.data)})})));return this.toOkResult(t)}catch(t){return this.toErrorResult(t)}}recompile(e){try{const t=this.runCompile(()=>{if(e.data===void 0)return this.runPipeline({spec:e.spec});this.lastData=e.data;const r=wc(e.spec.data,e.spec.mapping);return this.runPipeline({spec:I(e.spec,{data:this.dataCompiler.compile(e.data),mapping:r})})});return this.toOkResult(t)}catch(t){return this.toErrorResult(t)}}getCacheStats(){const e={};for(const{name:t,getStats:r}of this.stages)e[t]={...r()};return e}getLastCompile(){return this.lastCompile}getDiagnostics(){return this.lastDiagnostics}runCompile(e){this.container.diagnostics.reset();const t=this.trackCompile(e);return this.lastDiagnostics=this.container.diagnostics.drain(),t}toOkResult(e){return{ok:!0,compiled:e,warnings:this.lastDiagnostics?.warnings??[]}}toErrorResult(e){const t=this.container.diagnostics.drain();return this.lastDiagnostics=t,{ok:!1,errors:t.errors.length>0?t.errors:[Na(e)],warnings:t.warnings}}trackCompile(e){if(!l.IS_DEV)return e();const t=this.getCacheStats(),r=performance.now(),n=e(),a=performance.now()-r,i={};for(const{name:s,getStats:o}of this.stages){const c=o();i[s]={hits:c.hits-t[s].hits,misses:c.misses-t[s].misses}}return this.lastCompile={stages:i,durationMs:a},n}runPipeline({spec:e}){return Tt({spec:e}).pipe(({spec:t})=>({spec:I(t,{data:this.transformCompiler.compile({data:t.data,transforms:t.transforms})})})).pipe(({spec:t})=>{const r=this.constantMappingCompiler.compile({data:t.data,mapping:t.mapping});return{spec:I(t,{data:r.data,mapping:r.mapping})}}).pipe(({spec:t})=>({layers:this.layerPhasedCompiler.compile({data:t.data,layers:t.layers,mapping:t.mapping,coords:t.coords,scales:t.scales})})).pipe(({spec:t,layers:r})=>this.coordCompiler.setup({coordSpec:t.coords,scales:t.scales,layers:r})).pipe(({layers:t,scales:r})=>({scales:this.scaleCompiler.compile({layers:t,scales:r})})).pipe(({spec:t,scales:r})=>({config:this.configCompiler.compile({config:t.config,scales:r})})).pipe(({layers:t,scales:r})=>({layers:this.positionMapperCompiler.compile({layers:t,scales:r})})).pipe(({layers:t,scales:r})=>({layers:this.visualMapperCompiler.compile({layers:t,scales:r})})).pipe(({spec:t,layers:r,coordSystem:n})=>({layers:this.coordCompiler.transform({coordSpec:t.coords,coordSystem:n,layers:r})})).pipe(({layers:t})=>({layers:this.summariseCompiler.compile({layers:t})})).pipe(({spec:t,scales:r,layers:n,coordSystem:a})=>({guides:this.guideCompiler.compile({scales:r,config:t.config,layers:n,coordSystem:a,originalData:this.lastData})})).pipe(({spec:t,layers:r})=>({layers:this.stylesCompiler.compile({layers:r,styles:t.styles,config:t.config})})).pipe(({spec:t,layers:r})=>({layers:this.highlightsCompiler.compile({layers:r,highlights:t.highlights,config:t.config})})).pipe(({spec:t,layers:r,coordSystem:n,scales:a})=>({annotations:this.annotationsCompiler.compile({annotations:t.annotations,layers:r,coordSystem:n,scales:a,config:t.config})})).result()}},Nh=["data","transform","constantMapping","layer","coordSetup","scale","positionMapper","visualMapper","coordTransform","summarise","guide","styles","highlights","config","annotations"],Bh=({plugins:e=[]}={})=>{const t=ui(e),{geomRegistry:r,statRegistry:n,transformRegistry:a}=Xd(t),i=_h(r),s=new Cm(i),o=new Dh(a);for(const c of t.warnings)i.diagnostics.addWarning(c,{persistent:!0});return new Pi(i,new l.DataCompiler,new Ii(i),o,new Lc,new Ld(i,o,n,new Id(i,o,new xh(n),new tu,new Qc(i),new Zd(new am))),new hm(i,s),new Rc(new Yc),new mm(i),new Oh,new md(i),new kh(i),new Ah(i),new vd(i),new Ic(i),new sc(i))};function Fh(e,t){return e.geom===t}function Oi(...e){let t={},r;const[n,...a]=e;l.isDefined(n)&&!$h(n)?(t=n,r=a):r=e;const i={mapping:t,layers:[],scales:[],transforms:[],highlights:[],config:{}};return r.reduce((s,o)=>_i(s,o),i)}function Mi(e,...t){return t.reduce((r,n)=>_i(r,n),e)}function $h(e){return typeof e=="object"&&e!==null&&"type"in e}function _i(e,t){switch(t.type){case"scale":return{...e,scales:[...e.scales,t]};case"coord":return{...e,coords:t};case"config":return{...e,config:(0,lt.default)({},e.config,t.config)};case"layer":return{...e,layers:[...e.layers,t]};case"transform":return{...e,transforms:[...e.transforms,t]};case"mapping":return{...e,mapping:{...e.mapping,...t.mapping}};case"highlight":return{...e,highlights:[...e.highlights,t]};case"styles":return{...e,styles:e.styles===void 0?t:{...t,extends:[e.styles,...t.extends??[]]}};case"annotation":return Gh(e,t);default:throw new l.InternalError({message:`Unknown spec item type: ${t.type}`})}}function Gh(e,t){const r={...e.annotations};switch(t.kind){case"differenceArrow":r.differenceArrows=[...r.differenceArrows??[],t.annotation];break;case"shape":r.shapes=[...r.shapes??[],t.annotation];break;case"arrow":r.arrows=[...r.arrows??[],t.annotation];break;case"text":r.textAnnotations=[...r.textAnnotations??[],t.annotation];break;case"image":r.images=[...r.images??[],t.annotation];break;case"sticker":r.stickers=[...r.stickers??[],t.annotation];break;case"pinnedNumber":r.pinnedNumbers=[...r.pinnedNumbers??[],t.annotation];break;case"comment":r.comments=[...r.comments??[],t.annotation];break;default:throw new Error(`Unknown annotation kind: ${t.kind}`)}return{...e,annotations:r}}function Uh(e){const t=e?.plugins??[],r=Hh(t);return{geom:{...l.geom,...r.geom},stat:{...l.stat,...r.stat},transform:{...l.transform,...r.transform},scale:l.scale,coord:l.coord,createSpec:Oi,pipe:Mi,plugins:t}}var Wh=e=>(t={})=>l.buildLayerInput(e,t);function Hh(e){const{geoms:t,stats:r,transforms:n}=ui(e),a={};for(const o of t)a[o.type]=Wh(o.type);const i={};for(const o of r)i[o.type]=()=>({type:o.type});const s={};for(const o of n)s[o.transformType]=c=>({type:"transform",transformType:o.transformType,options:c?.options});return{geom:a,stat:i,transform:s}}var Kh=24,zh={header:{after:10,before:0},headline:{after:4,before:0},topLegend:{after:8,before:0},topAxisLabel:{after:8,before:0},topAxis:{after:0,before:0},bottomAxis:{after:4,before:0},bottomAxisLabel:{after:16,before:0},bottomLegend:{after:10,before:16},footer:{after:0,before:16}},Yh={leftLegend:{after:10,before:0},leftAxis:{after:4,before:0},rightAxis:{after:10,before:4}},Gt="…",Ni=(e,t,r)=>{if(t<=0||e.length===0)return"";if(r(e)<=t)return e;if(r(Gt)>t)return"";let n=0,a=e.length-1,i=0;for(;n<=a;){const s=n+a>>>1;r(e.slice(0,s)+Gt)<=t?(i=s,n=s+1):a=s-1}return e.slice(0,i)+Gt};var M={timeZone:"UTC"},D=e=>t=>{if(!l.isStrictTemporalDataValue(t))return"–";try{return e(t)}catch{return"n/a"}},ne=e=>t=>l.isStrictNumericDataValue(t)?e(t):"–",Pr=e=>t=>l.isStrictCategoricalDataValue(t)?t:"–",qh=tr.default.humanizer({language:"en",spacer:"",delimiter:" ",languages:{en:{y:()=>"y",mo:()=>"mo",w:()=>"w",d:()=>"d",h:()=>"h",m:()=>"m",s:()=>"s",ms:()=>"ms"}}}),Bi=({valueFormat:e,locale:t,numberFormat:r,intlOptions:n})=>ne(a=>{const i=typeof r.decimals=="number"?r.decimals:2,s=_r(a,i),{base:o,suffix:c}=Mr(a,r.abbreviation),u={...s,...l.isCurrencyValueFormat(e)?{style:"currency",currencyDisplay:"narrowSymbol",currency:e.iso}:{},...n};return`${Intl.NumberFormat(t,u).format(o)}${c}`}),Fi=({locale:e,numberFormat:t,intlOptions:r})=>ne(n=>{const{base:a,suffix:i}=Mr(n,t.abbreviation),s={..._r(a,t.decimals),...r};return`${Intl.NumberFormat(e,s).format(a)}${i}`}),Or=e=>ne(t=>qh(t)),$i=({locale:e,intlOptions:t})=>ne(r=>Intl.NumberFormat(e,{maximumFractionDigits:0,...t}).format(r)),Gi=({locale:e,numberFormat:t,intlOptions:r})=>ne(n=>{const a=_r(n,t.decimals);return Intl.NumberFormat(e,{...a,...r,style:"percent"}).format(n)}),Mr=(e,t="none")=>{switch(t){case"none":return{base:e,suffix:""};case"auto":{const r=Xh(e);return Mr(e,r)}default:return{base:e/l.SUFFIX_MULTIPLIERS[t],suffix:t}}},_r=(e,t)=>{if(typeof t=="number")return{minimumFractionDigits:t,maximumFractionDigits:t};const r=Math.ceil(Math.log10(Math.abs(e))),n=r>=3?0:r===2?1:2;return{minimumFractionDigits:t==="auto"?0:n,maximumFractionDigits:n}},Xh=e=>{const t=Math.abs(e);return t>=l.SUFFIX_MULTIPLIERS.b?"b":t>=l.SUFFIX_MULTIPLIERS.m?"m":t>=l.SUFFIX_MULTIPLIERS.k?"k":"none"},jh=({locale:e,intlOptions:t})=>D(r=>Intl.DateTimeFormat(e,{dateStyle:"medium",...M,...t}).format(r)),Zh=({locale:e,intlOptions:t})=>D(r=>{const n=Intl.DateTimeFormat(e,{dateStyle:"medium",timeStyle:"medium",...M,...t}).formatToParts(r);return Jh(n.map(Qh))}),Ui=({locale:e,intlOptions:t})=>D(r=>Intl.DateTimeFormat(e,{day:"numeric",month:"long",...M,...t}).format(r)),Wi=({locale:e,intlOptions:t})=>D(r=>Intl.DateTimeFormat(e,{month:"long",...M,...t}).format(r)),Nr=({locale:e,intlOptions:t})=>D(r=>Intl.DateTimeFormat(e,{month:"short",year:"numeric",...M,...t}).format(r)),Br=e=>D(t=>`Q${Math.floor(t.getUTCMonth()/3)+1} ${t.getUTCFullYear()}`),Hi=({locale:e,intlOptions:t})=>D(r=>{const n=(0,va.addDays)(r,6);return Intl.DateTimeFormat(e,{day:"numeric",month:"long",...M,...t,year:void 0}).formatRange(r,n)}),Ki=({locale:e,intlOptions:t})=>D(r=>{const n=(0,va.addDays)(r,6);return Intl.DateTimeFormat(e,{dateStyle:"medium",...M,...t}).formatRange(r,n)}),Fr=({locale:e,intlOptions:t})=>D(r=>Intl.DateTimeFormat(e,{year:"numeric",...M,...t}).format(r)),zi=({locale:e,intlOptions:t})=>D(r=>Intl.DateTimeFormat(e,{timeStyle:"short",...M,...t}).format(r)),Jh=e=>e.map(t=>t.value).join(""),Qh=e=>e.type!=="literal"||e.value!==", "?e:{type:"literal",value:" • "},Bn=1e3,ep=({valueFormat:e,locale:t,tickValues:r,intlOptions:n})=>ne(a=>{const i={...Gr(a,r),notation:"compact",...l.isCurrencyValueFormat(e)?{style:"currency",currencyDisplay:"narrowSymbol",currency:e.iso}:{},...n};return $r(a,t,i)}),tp=({locale:e,tickValues:t,intlOptions:r})=>ne(n=>{const a={...Gr(n,t),notation:"compact",...r};return $r(n,e,a)}),rp=({locale:e,tickValues:t,intlOptions:r})=>ne(n=>{const a={...Gr(n,t),notation:"compact",...r,style:"percent"};return $r(n,e,a)}),$r=(e,t,r)=>Intl.NumberFormat(t,r).formatToParts(e).map(n=>n.type==="compact"?n.value.toLowerCase():n.value).join(""),Yi=e=>Math.abs(e)>Bn?Yi(e/Bn):Number.isInteger(e),np=e=>{if(e.length<2)return!1;const[t,r]=e;return typeof t!="number"||typeof r!="number"?!1:Math.abs(r-t)<1},Gr=(e,t)=>Yi(e)?{minimumFractionDigits:0,maximumFractionDigits:0}:np(t)?{minimumFractionDigits:0,maximumFractionDigits:4}:{minimumFractionDigits:0,maximumFractionDigits:1},ap=({locale:e,intlOptions:t})=>D(r=>Intl.DateTimeFormat(e,{day:"numeric",month:"short",...M,...t}).format(r)),ip=({locale:e,intlOptions:t})=>D(r=>Intl.DateTimeFormat(e,{month:"short",...M,...t}).format(r)),sp=({locale:e,intlOptions:t})=>D(r=>Intl.DateTimeFormat(e,{day:"numeric",month:"short",...M,...t}).format(r)),op=({locale:e,intlOptions:t})=>D(r=>Intl.DateTimeFormat(e,{timeStyle:"short",...M,...t}).format(r)),Ur=e=>{const{valueFormat:t}=e;switch(t.type){case"currency":return ep(e);case"date":case"datetime":return ap(e);case"day_month":case"weekly_date_range":case"weekly_date_range_with_year":return sp(e);case"decimal":case"integer":return tp(e);case"duration":return Or(e);case"month":return ip(e);case"month_year":return Nr(e);case"percentage":return rp(e);case"quarter":return Br(e);case"text":return Pr(e);case"time":return op(e);case"year":return Fr(e);case"lookup":return Ur({...e,valueFormat:t.fallback});default:throw new l.InternalError({message:`Unhandled value format: ${t.type}`})}},lp=.9,cp=1/3,up=1/4,dp=e=>e.formattedAxis.position==="top"||e.formattedAxis.position==="bottom"?mp(e):hp(e),mp=({formattedAxis:e,bandwidthPx:t,panelRect:r,measureLabel:n})=>{const{widths:a,maxWidth:i,maxHeight:s}=qi(e.ticks,n),o=pp(e.ticks,r.width),c=o*lp;if(i<=c)return{...e,labelRotation:0,labelMaxWidthPx:null};if(o>=50){const d=ur(c);return{...e,ticks:cr(e.ticks,a,d,n),labelRotation:0,labelMaxWidthPx:d}}if(s+8>t)return{...e,ticks:[],labelRotation:0,labelMaxWidthPx:null};const u=ur(r.height*cp);return{...e,ticks:cr(e.ticks,a,u,n),labelRotation:-90,labelMaxWidthPx:u}},hp=({formattedAxis:e,bandwidthPx:t,panelRect:r,measureLabel:n})=>{const{widths:a,maxWidth:i,maxHeight:s}=qi(e.ticks,n);if(s>t)return{...e,ticks:[],labelRotation:0,labelMaxWidthPx:null};const o=ur(r.width*up);return i<=o?{...e,labelRotation:0,labelMaxWidthPx:null}:{...e,ticks:cr(e.ticks,a,o,n),labelRotation:0,labelMaxWidthPx:o}},pp=(e,t)=>{const r=e[0],n=e[1];return r===void 0||n===void 0?t:Math.abs(n.position-r.position)*t},qi=(e,t)=>{const r=[];let n=0,a=0;for(const i of e){const{width:s,height:o}=t(i.formattedLabel);r.push(s),s>n&&(n=s),o>a&&(a=o)}return{widths:r,maxWidth:n,maxHeight:a}},cr=(e,t,r,n)=>{const a=i=>n(i).width;return e.map((i,s)=>(t[s]??0)<=r?i:{...i,formattedLabel:Ni(i.formattedLabel,r,a)})},ur=e=>Math.max(0,Math.floor(e)),fp=(e,t,r,n)=>{if(e.length===0)return!0;const a=t==="top"||t==="bottom",i=a?60:40;let s=r-(e.length-1)*i;for(const o of e){const{width:c,height:u}=n(o);if(s-=a?c:u,s<0)return!1}return!0},gp=({axis:e,availableSpacePx:t,measureLabel:r,resolveFormatter:n})=>{const{tickCandidates:a,position:i}=e;if(a.length===0)return[];const s=new Map,o=m=>{const h=s.get(m);if(h)return h;const p=a[m],f=p?yp(p.ticks,n(p)):[];return s.set(m,f),f};let c=0,u=a.length-1,d=-1;for(;c<=u;){const m=c+u>>>1;fp(o(m).map(h=>h.formattedLabel),i,t,r)?(d=m,c=m+1):u=m-1}return d>=0?o(d):o(0)},yp=(e,t)=>e.map(r=>({...r,formattedLabel:t(r.value)})),Fn=.5,Ke=e=>({x:0,y:0,width:e.width,height:e.height}),Wr=e=>e==="panel-end"?"end":e==="panel-start"?"start":e,ze=({box:e,panel:t,frame:r,placement:n,justify:a,align:i,offset:s,alignOffset:o,labelWidth:c,labelHeight:u})=>{const d=a==="panel-start"||a==="panel-end",m=(r.valueAxis==="x"?e.height:e.width)===0,h={anchor:bp(a,r.valueDirectionSign),placement:d?"inside":n,offset:s},p={anchor:Sp(i),placement:m?n:"inside",offset:m?o??s:0},f=d?t:e,g=r.valueAxis==="x"?f:e,y=r.valueAxis==="y"?f:e,v=r.valueAxis==="x"?h:p,x=r.valueAxis==="x"?p:h,T=Gn(v,{min:g.x,max:g.x+g.width,halfExtent:c/2}),A=Gn(x,{min:y.y,max:y.y+y.height,halfExtent:u/2});return{x:T,y:A,position:vp(e,T,A,c,u)}},$n=(e,t,r,n)=>r-n>=e-Fn&&r+n<=t+Fn,vp=(e,t,r,n,a)=>{if(e.width===0&&e.height===0)return"outside";const i=e.width===0||$n(e.x,e.x+e.width,t,n/2),s=e.height===0||$n(e.y,e.y+e.height,r,a/2);return i&&s?"inside":"outside"},bp=(e,t)=>e==="center"?"center":(e==="end"||e==="panel-end")==(t===1)?"max":"min",Sp=e=>e==="center"?"center":e==="start"?"min":"max",Gn=({anchor:e,placement:t,offset:r},{min:n,max:a,halfExtent:i})=>{if(e==="center")return(n+a)/2;if(t==="inside"&&n===a)return n;const s=r+i;return e==="min"?t==="inside"?n+s:n-s:t==="inside"?a-s:a+s},xp=(e,t,r,n,a)=>{const i=t??e,s=1-Math.max(e,i);return{box:{x:r*n,y:s*a,width:0,height:Math.abs(e-i)*a},frame:{valueAxis:"y",valueDirectionSign:e>=i?-1:1}}},Ap=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;const{offset:r}=e.layer.dataLabels,n=Tp(e.layer);for(const a of e.layer.data){const i=V(a),s=P(a)??w(a);if(i===null||s===null||!Ee(i,s))continue;const o=e.formatLabel(a);if(o==="")continue;const{width:c,height:u}=e.measureDataLabel("dataLabel",o),{box:d,frame:m}=xp(s,N(a),i,e.panelRect.width,e.panelRect.height),h=ze({box:d,panel:Ke(e.panelRect),frame:m,...n,offset:r,labelWidth:c,labelHeight:u});t.push({layerId:e.layer.id,x:h.x,y:h.y,text:o,width:c,height:u,isRotated:!1,target:"observation",position:"outside"})}return t},Ip={place:Ap,getPercentageValueStrategy:e=>e.position==="fill"?"fill":O(e.position)?"stack":"none"},Tp=e=>{const{position:t,justify:r,align:n}=e.dataLabels;return t==="auto"?{placement:"outside",justify:"end",align:"center"}:{placement:t,justify:Vt(e.data,e.mapping)?Wr(r):r,align:n}},Qe=6,Lp=e=>{const t=[],r=O(e.layer.position),n=e.coordSystem.mainAxis==="y";if(e.layer.dataLabels.showDataLabels){const{entries:a,shouldRotate:i}=Ep({layer:e.layer,mainAxis:e.coordSystem.mainAxis,panelRect:e.panelRect,measureDataLabel:e.measureDataLabel,formatLabel:e.formatLabel,isFlipped:n});for(const s of a){const o=e.layer.dataLabels.position==="auto"?Cp({mainAxis:e.coordSystem.mainAxis,isStacked:r,isNegativeBar:s.isNegative,shouldRotate:i,bounds:s.bounds,labelWidth:s.labelWidth,labelHeight:s.labelHeight,panelWidth:e.panelRect.width,panelHeight:e.panelRect.height,offset:e.layer.dataLabels.offset}):kp(e.layer.dataLabels,e.coordSystem.mainAxis,r,s,Ke(e.panelRect));o!==null&&t.push({layerId:e.layer.id,x:o.x,y:o.y,text:s.text,width:s.labelWidth,height:s.labelHeight,isRotated:o.isRotated,target:"observation",position:o.position})}}if(e.layer.dataLabels.showCategoryLabels)for(const a of Dp(e,r))t.push(a);if(e.layer.dataLabels.showStackTotals){const a=_p({layer:e.layer,mainAxis:e.coordSystem.mainAxis,panelRect:e.panelRect,measureDataLabel:e.measureDataLabel,formatAbsolute:e.formatAbsolute});for(const i of a)t.push(i)}return t},wp={place:Lp,getPercentageValueStrategy:e=>e.position==="fill"?"fill":O(e.position)?"stack":"absoluteGrandTotal"},Ep=({layer:e,mainAxis:t,panelRect:r,measureDataLabel:n,formatLabel:a,isFlipped:i})=>{const s=[];let o=!1;const c=l.extractVariableName(e.mapping.y);for(const u of e.data){const d=ji(t,u);if(d===null)continue;const m=a(u);if(m==="")continue;const{width:h,height:p}=n("dataLabel",m),f=Hr(d,r);h>f.width&&(o=!0);const g=c===null?null:u[c],y=l.isStrictNumericDataValue(g)&&g<0;s.push({isNegative:y,text:m,labelWidth:h,labelHeight:p,bounds:f})}return{entries:s,shouldRotate:!i&&o}},Hr=(e,t)=>({x:e.x*t.width,y:e.y*t.height,width:e.width*t.width,height:e.height*t.height}),Xi=(e,t,r,n,a)=>{if(e==="x"){let o=1-a,c=a-n;return c<0&&(o+=c,c=-c),{x:t,y:o,width:r-t,height:c}}let i=t,s=r-t;return s<0&&(i+=s,s=-s),{x:i,y:1-a,width:s,height:a-n}},ji=(e,t)=>{const r=K(t),n=z(t),a=N(t),i=P(t)??w(t);return r===null||n===null||a===null||i===null?null:Xi(e,r,n,a,i)},Vp=(e,t)=>{const{xMin:r,xMax:n,yMin:a,yMax:i}=t.anchor;return Xi(e,r,n,a,i)},Rp=(e,t)=>e==="x"?t?"bottom":"top":t?"left":"right",Zi=(e,t,r)=>r?{width:t,height:e}:{width:e,height:t},Cp=e=>e.isStacked?Pp({bounds:e.bounds,labelWidth:e.labelWidth,labelHeight:e.labelHeight,isRotated:e.shouldRotate}):Mp({edge:Rp(e.mainAxis,e.isNegativeBar),bounds:e.bounds,labelWidth:e.labelWidth,labelHeight:e.labelHeight,isRotated:e.shouldRotate,panelWidth:e.panelWidth,panelHeight:e.panelHeight,offset:e.offset}),Ji=(e,t)=>e==="x"?{valueAxis:"y",valueDirectionSign:t?1:-1}:{valueAxis:"x",valueDirectionSign:t?-1:1},kp=(e,t,r,n,a)=>{if(e.position==="auto")return null;const i=r&&e.position==="outside"?"inside":e.position,s=ze({box:n.bounds,panel:a,frame:Ji(t,n.isNegative),placement:i,justify:e.justify,align:e.align,offset:e.offset,labelWidth:n.labelWidth,labelHeight:n.labelHeight});return{x:s.x,y:s.y,isRotated:!1,position:s.position}},Dp=(e,t)=>{const r=[],{categoryPosition:n,categoryJustify:a,categoryAlign:i,categoryOffset:s}=e.layer.dataLabels,o=t&&n==="outside"?"inside":n,c=e.coordSystem.mainAxis,u=Ke(e.panelRect),d=l.extractVariableName(e.layer.mapping.y);for(const m of e.layer.data){const h=ji(c,m);if(h===null)continue;const p=e.formatCategory(m);if(p===null||p==="")continue;const{width:f,height:g}=e.measureDataLabel("categoryLabel",p),y=Hr(h,e.panelRect),v=d===null?null:m[d],x=l.isStrictNumericDataValue(v)&&v<0,T=ze({box:y,panel:u,frame:Ji(c,x),placement:o,justify:a,align:i,offset:s,labelWidth:f,labelHeight:g});r.push({layerId:e.layer.id,x:T.x,y:T.y,text:p,width:f,height:g,isRotated:!1,target:"category",position:T.position})}return r},Pp=({bounds:e,labelWidth:t,labelHeight:r,isRotated:n})=>{const a=Zi(t,r,n);return a.width>e.width||a.height>e.height?null:{x:e.x+e.width/2,y:e.y+e.height/2,isRotated:n,position:"inside"}},Op=(e,t,r,n)=>{switch(e){case"top":return{edgeCoord:t.y,outwardSign:-1,panelExtent:n};case"bottom":return{edgeCoord:t.y+t.height,outwardSign:1,panelExtent:n};case"left":return{edgeCoord:t.x,outwardSign:-1,panelExtent:r};case"right":return{edgeCoord:t.x+t.width,outwardSign:1,panelExtent:r}}},Mp=({edge:e,bounds:t,labelWidth:r,labelHeight:n,isRotated:a,panelWidth:i,panelHeight:s,offset:o})=>{const c=e==="top"||e==="bottom",u=t.x+t.width/2,d=t.y+t.height/2,m=Zi(r,n,a),h=c?m.height:m.width,p=c?m.width:m.height,f=c?t.height:t.width,g=c?t.width:t.height,y=h/2,{edgeCoord:v,outwardSign:x,panelExtent:T}=Op(e,t,i,s);if(h+o<f){if(p>g)return null;if(a)return{x:u,y:d,isRotated:!0,position:"inside"};const _=v-x*(y+o);return{...c?{x:u,y:_}:{x:_,y:d},isRotated:!1,position:"inside"}}const A=v+x*(y+o);return A-y<0||A+y>T?null:{...c?{x:u,y:A}:{x:A,y:d},isRotated:a,position:"outside"}},_p=({layer:e,mainAxis:t,panelRect:r,measureDataLabel:n,formatAbsolute:a})=>{const i=[],s=e.summary.stackTotals;if(s===void 0||s.length===0)return i;const o=t==="y";for(const c of s){const u=Hr(Vp(t,c),r),d=a(c.total),{width:m,height:h}=n("stackTotal",d),p=c.anchor.direction==="positive";let f,g;o?(f=p?u.x+u.width+Qe+m/2:u.x-Qe-m/2,g=u.y+u.height/2):(f=u.x+u.width/2,g=p?u.y-Qe-h/2:u.y+u.height+Qe+h/2),i.push({layerId:e.id,x:f,y:g,text:d,width:m,height:h,isRotated:!1,target:"aggregate",position:"outside"})}return i},Np=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;const{offset:r}=e.layer.dataLabels,n=Fp(e.layer);for(const a of e.layer.data){const i=V(a),s=w(a);if(i===null||s===null||!Ee(i,s))continue;const o=e.formatLabel(a);if(o==="")continue;const{width:c,height:u}=e.measureDataLabel("dataLabel",o),d=ze({box:{x:i*e.panelRect.width,y:(1-s)*e.panelRect.height,width:0,height:0},panel:Ke(e.panelRect),frame:{valueAxis:"y",valueDirectionSign:-1},...n,offset:r,labelWidth:c,labelHeight:u});t.push({layerId:e.layer.id,x:d.x,y:d.y,text:o,width:c,height:u,isRotated:!1,target:"observation",position:d.position})}return t},Bp={place:Np,getPercentageValueStrategy:()=>"none"},Fp=e=>{const{position:t,justify:r,align:n}=e.dataLabels;return t==="auto"?{placement:"outside",justify:"end",align:"center"}:{placement:t,justify:Vt(e.data,e.mapping)?Wr(r):r,align:n}},$p={color:At,alpha:Ea,strokeWidth:sr,lineType:Va,size:Sr,borderWidth:sr},Kr=(e={})=>{const t=e.colorScheme??"light",r=new WeakMap;return{geomReaders:i=>{const s=r.get(i);if(s!==void 0)return s;const o=Gp(i.styles,t);return r.set(i,o),o},explain:(i,s,o,c)=>{if(c!==void 0){const h=Be(i.styles.overrides,s,o,c,t);if(h!==void 0)return{value:h.value,tier:"override",origin:h.origin,state:c};const p=Be(i.styles.defaults,s,o,c,t);if(p!==void 0)return{value:p.value,tier:"default",origin:p.origin,state:c}}const u=Be(i.styles.overrides,s,o,void 0,t);if(u!==void 0)return{value:u.value,tier:"override",origin:u.origin};const d=Qi(s,o);if(d!==void 0)return{value:d,tier:"data"};const m=Be(i.styles.defaults,s,o,void 0,t);return m!==void 0?{value:m.value,tier:"default",origin:m.origin}:{value:void 0,tier:"unresolved"}}}},Gp=(e,t)=>({get:(n,a,i)=>{if(i!==void 0){const c=et(e.overrides,n,a,i,t);if(c!==void 0)return c;const u=et(e.defaults,n,a,i,t);if(u!==void 0)return u}const s=et(e.overrides,n,a,void 0,t);if(s!==void 0)return s;const o=Qi(n,a);return o!==void 0?o:et(e.defaults,n,a,void 0,t)}}),et=(e,t,r,n,a)=>Be(e,t,r,n,a)?.value,Be=(e,t,r,n,a)=>{for(let i=e.length-1;i>=0;i--){const s=e[i];if(s===void 0||s.state!==n)continue;const o=s.declarations[t];if(o!==void 0&&s.matches(r))return{value:Up(o,a),origin:s.origin}}},Up=(e,t)=>l.isLightDarkColor(e)?e[t]:e,Qi=(e,t)=>{const r=$p[e];if(r!==void 0)return r(t)??void 0},Wp=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;const{offset:r}=e.layer.dataLabels,n=Kp(e.layer),a=n.justify==="panel-start"||n.justify==="panel-end",i=Kr().geomReaders(e.layer);for(const s of e.layer.data){const o=V(s),c=w(s);if(o===null||c===null||!Ee(o,c))continue;const u=e.formatLabel(s);if(u==="")continue;const{width:d,height:m}=e.measureDataLabel("dataLabel",u),h=i.get("size",s)/2,p=ze({box:{x:o*e.panelRect.width,y:(1-c)*e.panelRect.height,width:0,height:0},panel:Ke(e.panelRect),frame:{valueAxis:"y",valueDirectionSign:-1},...n,offset:a?r:r+h,alignOffset:r+h,labelWidth:d,labelHeight:m});t.push({layerId:e.layer.id,x:p.x,y:p.y,text:u,width:d,height:m,isRotated:!1,target:"observation",position:p.position})}return t},Hp={place:Wp,getPercentageValueStrategy:()=>"none"},Kp=e=>{const{position:t,justify:r,align:n}=e.dataLabels;return t==="auto"?{placement:"outside",justify:"end",align:"center"}:{placement:t,justify:r,align:n}};function zr(e){return{startAngle:e[l.POSITION_VARIABLES.xMin],endAngle:e[l.POSITION_VARIABLES.xMax]}}function Yr(e){return{innerRadius:e[l.POSITION_VARIABLES.yMin],outerRadius:e[l.POSITION_VARIABLES.yMax]??e[l.POSITION_VARIABLES.y]}}var zp=" · ",Ut=2,$e=(e,t,r,n)=>{const a=Math.abs(e==="radial"?Math.sin(t):Math.cos(t)),i=Math.abs(e==="radial"?Math.cos(t):Math.sin(t));return a*(r/2)+i*(n/2)},Yp=({wedge:e,labelRadius:t,labelAngle:r,labelWidth:n,labelHeight:a})=>{const i=$e("radial",r,n,a);if(!(t-i>=e.innerRadiusPx-Ut&&t+i<=e.outerRadiusPx+Ut)||t<=0)return!1;const s=Math.abs(e.endAngle-e.startAngle)/2,o=$e("tangential",r,n,a)/t,c=Ut/t;return Math.abs(r-e.midAngle)+o<=s+c},qp=({x:e,y:t,labelWidth:r,labelHeight:n,panelRect:a})=>e-r/2>=0&&e+r/2<=a.width&&t-n/2>=0&&t+n/2<=a.height,Xp=({wedge:e,isRadialBar:t,offset:r,labelWidth:n,labelHeight:a})=>t?{labelRadius:(e.innerRadiusPx+e.outerRadiusPx)/2,labelAngle:e.midAngle,position:"inside"}:{labelRadius:e.outerRadiusPx+r+$e("radial",e.midAngle,n,a),labelAngle:e.midAngle,position:"outside"},jp=({wedge:e,placement:t,justify:r,align:n,offset:a,labelWidth:i,labelHeight:s})=>{const o=n==="start"?e.startAngle:n==="end"?e.endAngle:e.midAngle,c=a+$e("radial",o,i,s);let u;if(r==="center")u=(e.innerRadiusPx+e.outerRadiusPx)/2;else if(r==="end")u=t==="inside"?e.outerRadiusPx-c:e.outerRadiusPx+c;else if(t==="inside")u=e.innerRadiusPx+c;else{const m=e.innerRadiusPx-c;u=m>=0?m:e.innerRadiusPx+c}let d=o;if(n!=="center"&&u>0){const m=$e("tangential",o,i,s)/u;d=o+(n==="start"?1:-1)*m}return{labelRadius:u,labelAngle:d,position:Yp({wedge:e,labelRadius:u,labelAngle:d,labelWidth:i,labelHeight:s})?"inside":"outside"}},Zp=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;const{position:r,justify:n,align:a,offset:i,showCategoryLabels:s}=e.layer.dataLabels,o=e.coordSystem.bandAxis==="y",c=e.panelRect.width/2,u=e.panelRect.height/2,d=Math.min(e.panelRect.width,e.panelRect.height)/2;for(const m of e.layer.data){const{startAngle:h,endAngle:p}=zr(m),{innerRadius:f,outerRadius:g}=Yr(m);if(h===null||p===null||g===null)continue;const y=e.formatLabel(m);if(y==="")continue;const v=s?e.formatCategory(m):null,x=v===null?y:`${v}${zp}${y}`,{width:T,height:A}=e.measureDataLabel("dataLabel",x),_={startAngle:h,endAngle:p,midAngle:(h+p)/2,innerRadiusPx:(f??0)*d,outerRadiusPx:g*d},{labelRadius:Y,labelAngle:ee,position:ie}=r==="auto"?Xp({wedge:_,isRadialBar:o,offset:i,labelWidth:T,labelHeight:A}):jp({wedge:_,placement:r,justify:Wr(n),align:a,offset:i,labelWidth:T,labelHeight:A}),L=c+Math.sin(ee)*Y,B=u-Math.cos(ee)*Y;r==="auto"&&!qp({x:L,y:B,labelWidth:T,labelHeight:A,panelRect:e.panelRect})||t.push({layerId:e.layer.id,x:L,y:B,text:x,width:T,height:A,isRotated:!1,target:"observation",position:ie})}return t},Jp={place:Zp,getPercentageValueStrategy:()=>"absoluteGrandTotal"},Qp=e=>{const t=R({...e,valueFormat:e.valueFormat.fallback}),r={};for(const[a,i]of Object.entries(e.valueFormat.cases))r[a]=R({...e,valueFormat:i});const n=e.valueFormat.byVariable;return(a,i)=>{if(i===void 0||i[n]===void 0)return t(a);const s=l.getStableKey(i[n]),o=r[s];return o!==void 0?o(a,i):t(a)}},R=e=>{switch(e.valueFormat.type){case"currency":return Bi(e);case"date":return jh(e);case"datetime":return Zh(e);case"day_month":return Ui(e);case"decimal":return Fi(e);case"duration":return Or(e);case"integer":return $i(e);case"month":return Wi(e);case"month_year":return Nr(e);case"percentage":return Gi(e);case"quarter":return Br(e);case"text":return Pr(e);case"weekly_date_range":return Hi(e);case"weekly_date_range_with_year":return Ki(e);case"year":return Fr(e);case"time":return zi(e);case"lookup":return Qp({...e,valueFormat:e.valueFormat});default:{const t=e.valueFormat;throw new l.InternalError({message:`Unhandled value format: ${t.type}`})}}};function qr({layer:e,numberFormat:t,locale:r}){return R({valueFormat:Ia(e),locale:r,numberFormat:t})}var ef=(e,t)=>{const r=l.extractVariableName(t.x);return r!==null&&r!==l.CONSTANT_VARIABLES.x?{read:St(e,t),variable:r}:{read:G,variable:l.GROUP_VARIABLES.group}},es=({layer:e,coordSystem:t,axes:r,numberFormat:n,panelRect:a,measureDataLabel:i,formattingLocale:s,percentageValueStrategy:o})=>{const c=qr({layer:e,numberFormat:n,locale:s});return{layer:e,coordSystem:t,panelRect:a,measureDataLabel:i,formatLabel:sf({layer:e,numberFormat:n,axes:r,locale:s,absoluteFormatter:c,percentageValueStrategy:o}),formatAbsolute:c,formatCategory:tf({layer:e,numberFormat:n,locale:s})}},tf=({layer:e,numberFormat:t,locale:r})=>{const{read:n,variable:a}=ef(e.data,e.mapping),i=R({valueFormat:e.data.hasVariable(a)?e.data.getValueFormat(a):{type:"text"},locale:r,numberFormat:t});return s=>{const o=n(s);return o===null?null:i(o,s)}},rf=(e,t)=>{switch(t){case"stack":return nf(e);case"fill":return af(e);case"absoluteGrandTotal":return()=>e.summary.absoluteGrandTotal??null;case"none":return()=>null}},nf=e=>{const t=l.extractVariableName(e.mapping.x);let r=null,n=!1;return a=>{const i=e.summary.stackTotals;if(i===void 0||i.length===0||t===null)return null;if(!n){r=new Map;for(const c of i)r.set(c.xKey,c);n=!0}const s=a[t];if(s==null)return null;const o=r?.get(wr(a,t));return o===void 0?null:o.total}},af=e=>{const t=ke(e);return r=>{const n=N(r),a=P(r);if(!l.isStrictNumericDataValue(n)||!l.isStrictNumericDataValue(a))return null;const i=Math.abs(a-n);if(i===0)return null;const s=t(r);return l.isStrictNumericDataValue(s)?s/i:null}},sf=({layer:e,numberFormat:t,axes:r,locale:n,absoluteFormatter:a,percentageValueStrategy:i})=>{const s=U(e.data,e.dataLabels.labelSource),o=rf(e,i),c=of({layer:e,numberFormat:t,axes:r,locale:n,absoluteFormatter:a}),u=R({valueFormat:{type:"percentage"},locale:n,numberFormat:t}),d=e.dataLabels.format==="percentage"&&ts(e);return m=>{const h=s(m);if(h===null)return"";if(!d||!l.isStrictNumericDataValue(h))return c(h,m);const p=o(m);return p===null||p===0?c(h,m):u(h/p)}},of=({layer:e,numberFormat:t,axes:r,locale:n,absoluteFormatter:a})=>{const i=e.dataLabels.labelSource,s=l.extractVariableName(i);if(s!==null){if(ts(e))return a;const o=lf(e,r,t,n,s);if(o!==null)return o}return R({valueFormat:cf(e.data,i),locale:n,numberFormat:t})},ts=e=>{const t=l.extractVariableName(e.dataLabels.labelSource);return t===null?!1:t===l.extractVariableName(xt(e.position,e.mapping))},lf=(e,t,r,n,a)=>{const i=l.extractVariableName(e.mapping.x);if(i===null||i!==a)return null;const s=t.find(o=>o.scaleAestheticKey==="x");return s===void 0?null:R({valueFormat:s.valueFormat,locale:n,numberFormat:r})},cf=(e,t)=>{const r=l.extractConstantValue(t);if(r!==void 0)return l.isNumericDataValue(r)?{type:"decimal"}:l.isTemporalDataValue(r)?{type:"date"}:{type:"text"};const n=l.extractVariableName(t);return n===null||!e.hasVariable(n)?{type:"text"}:e.getValueFormat(n)},rs={bar:{cartesian:wp,polar:Jp},line:{cartesian:Bp},point:{cartesian:Hp},area:{cartesian:Ip}},uf=({layers:e,coordSystem:t,axes:r,numberFormat:n,parsingLocale:a,panelRect:i,measureDataLabel:s,formattingLocale:o,plotBottomY:c,isFooterChromeReserved:u})=>{const d=[],m=o??a,h=t.type;for(const p of e){if(!p.dataLabels.showDataLabels&&!p.dataLabels.showStackTotals&&!p.dataLabels.showCategoryLabels)continue;const f=p.geom,g=rs[f]?.[h];if(g===void 0)continue;const y=es({layer:p,coordSystem:t,axes:r,numberFormat:n,panelRect:i,measureDataLabel:s,formattingLocale:m,percentageValueStrategy:g.getPercentageValueStrategy(p)}),v=g.place(y);for(const x of v)df(x,h,c,u)||d.push(x)}return{labels:d}},df=(e,t,r,n)=>t==="polar"&&n&&e.position==="outside"&&e.y+e.height/2>r;function*mf({layers:e,coordSystem:t,axes:r,numberFormat:n,panelRect:a,measureDataLabel:i,locale:s}){if(!(t.type!=="cartesian"||a.width<=0||a.height<=0))for(const o of e){if(!o.dataLabels.showDataLabels&&!o.dataLabels.showStackTotals)continue;const c=rs[o.geom]?.cartesian;if(c===void 0)continue;const u=es({layer:o,coordSystem:t,axes:r,numberFormat:n,panelRect:a,measureDataLabel:i,formattingLocale:s,percentageValueStrategy:c.getPercentageValueStrategy(o)});for(const d of c.place(u))yield{x:a.x+d.x-d.width/2,y:a.y+d.y-d.height/2,width:d.width,height:d.height}}}var Wt={abbreviation:"none",decimals:"auto"},ns=({locale:e,kind:t,startValue:r,endValue:n,valueFormat:a})=>{if(r===null||n===null)return"n/a";switch(t){case"absolute-difference":return R({valueFormat:a,locale:e,numberFormat:Wt,intlOptions:{signDisplay:"always"}})(n-r);case"relative-difference":{const i=n-r;if(i===0)return"0%";const s=i/r;return s===Number.POSITIVE_INFINITY?"∞":s===Number.NEGATIVE_INFINITY?"-∞":R({valueFormat:{type:"percentage"},locale:e,numberFormat:Wt,intlOptions:{signDisplay:"always"}})(s)}case"proportion":{if(n-r===0)return"=";const i=n/r;return i===Number.POSITIVE_INFINITY?"∞":i===Number.NEGATIVE_INFINITY?"-∞":`${R({valueFormat:{type:"decimal"},locale:e,numberFormat:Wt,intlOptions:{maximumFractionDigits:1}})(i)}x`}}},Ht=6,Kt=6,zt=15,Yt=5,qt=15,as=(e,t)=>{switch(e){case"small":return{arrowStartGap:Ht,arrowEndGap:Kt,offsetFromHigherObservation:zt,arrowheadSize:Yt,curveRadius:qt,strokeWidth:2,labelLineHeight:12*t,labelPaddingX:6,labelPaddingY:3,labelStrokeWidth:1,labelFontWeight:500};case"medium":return{arrowStartGap:Ht*1.5,arrowEndGap:Kt*1.5,offsetFromHigherObservation:zt*1.25,arrowheadSize:Yt*1.5,curveRadius:qt*1.25,strokeWidth:3,labelLineHeight:16*t,labelPaddingX:8,labelPaddingY:4,labelStrokeWidth:1.5,labelFontWeight:500};case"large":return{arrowStartGap:Ht*2,arrowEndGap:Kt*2,offsetFromHigherObservation:zt*1.75,arrowheadSize:Yt*2.5,curveRadius:qt*1.5,strokeWidth:5,labelLineHeight:20*t,labelPaddingX:10,labelPaddingY:5,labelStrokeWidth:2,labelFontWeight:600}}},hf=(e,t,r,n)=>{const a=n.offsetFromHigherObservation+n.arrowheadSize+n.arrowEndGap;return e?Math.max(t.x,r.x)+a:Math.min(t.y,r.y)-a},pf=(e,t,r,{arrowStartGap:n,arrowEndGap:a,curveRadius:i})=>{const s={x:e.x,y:e.y-n},o={x:e.x,y:r},c={x:t.x,y:r},u={x:t.x,y:t.y-a},d=t.x>e.x?1:-1;return`
2
+ M ${s.x} ${s.y}
3
+ L ${o.x} ${o.y+i}
4
+ Q ${o.x} ${o.y} ${o.x+d*i} ${o.y}
5
+ L ${c.x-d*i} ${c.y}
6
+ Q ${c.x} ${c.y} ${c.x} ${c.y+i}
7
+ L ${u.x} ${u.y}
8
+ `},ff=(e,t,r,{arrowStartGap:n,arrowEndGap:a,curveRadius:i})=>{const s={x:e.x+n,y:e.y},o={x:r,y:e.y},c={x:r,y:t.y},u={x:t.x+a,y:t.y},d=t.y>e.y?1:-1;return`
9
+ M ${s.x} ${s.y}
10
+ L ${o.x-i} ${o.y}
11
+ Q ${o.x} ${o.y} ${o.x} ${o.y+d*i}
12
+ L ${c.x} ${c.y-d*i}
13
+ Q ${c.x} ${c.y} ${c.x-i} ${c.y}
14
+ L ${u.x} ${u.y}
15
+ `},gf=(e,t,{arrowEndGap:r,arrowheadSize:n})=>e?`
16
+ M ${t.x+r+n} ${t.y-n}
17
+ L ${t.x+r} ${t.y}
18
+ L ${t.x+r+n} ${t.y+n}
22
19
  `:`
23
- M ${t.x-r} ${t.y-n-r}
24
- L ${t.x} ${t.y-n}
25
- L ${t.x+r} ${t.y-n-r}
26
- `,ah=(e,t,n,r,o,s=.5)=>{if(e){const i=Math.min(t.y,n.y);return{x:r,y:i+s*o}}return{x:Math.min(t.x,n.x)+s*o,y:r}},ih=(e,t,n)=>Math.abs(e?t.y-n.y:t.x-n.x),ch=({arrow:e,mainAxis:t,panelWidth:n,panelHeight:r,textScale:o,locale:s})=>{const a=t==="y",i={x:e.start.x*n,y:(1-e.start.y)*r},c={x:e.end.x*n,y:(1-e.end.y)*r},l=cr(e.size,o),u=nh(a,i,c,l),d=(a?oh:rh)(i,c,u,l),p=sh(a,c,l),m=ih(a,i,c),f=ah(a,i,c,u,m,e.labelCrossPosition),y=ma({locale:s,kind:e.label,startValue:e.start.measurementValue,endValue:e.end.measurementValue});return{id:e.id,linePath:d,arrowheadPath:p,labelPosition:f,labelText:y,color:e.color,strokeWidth:l.strokeWidth,labelLineHeight:l.labelLineHeight,labelPaddingX:l.labelPaddingX,labelPaddingY:l.labelPaddingY,labelStrokeWidth:l.labelStrokeWidth,labelFontWeight:l.labelFontWeight}},lh=100,uh=({items:e,containerHeight:t,labelHeight:n})=>{const r=e.map(l=>{const u=(1-l.normalizedY)*t;return{anchorY:u,y:u,payload:l.payload}}).sort((l,u)=>l.y-u.y),o=n/2;let s=!1,a=!0,i=0;for(;a;){a=!1,i++;for(let l=0;l<r.length-1;l++){const u=r[l],d=r[l+1];if(!u||!d)continue;const p=u.y+o,m=d.y-o;if(p>m){a=!0,s=!0;const y=(p-m)/2+1;u.y-=y,d.y+=y,u.y<0&&(u.y=0),d.y>t&&(d.y=t)}}if(i>lh)break}return{placements:r.filter(l=>l.y>=0&&l.y<=t).map(l=>({y:l.y,anchorY:l.anchorY,payload:l.payload})),hasOverlap:s}},dh=({headline:e,show:t,numberFormat:n,parsingLocale:r,formattingLocale:o})=>{if(e===null)return null;const s=o??r;return e.kind==="grandTotal"?ph(e,s,n):mh(e,t,s,n)},ph=(e,t,n)=>({kind:"grandTotal",value:D({valueFormat:e.valueFormat,locale:t,numberFormat:n})(e.value)}),mh=(e,t,n,r)=>{const o=D({valueFormat:{type:"percentage"},locale:n,numberFormat:r}),s=gh(t,e.items.length>1);return{kind:"perGroup",items:e.items.map(i=>{const c=D({valueFormat:i.valueFormat,locale:n,numberFormat:r}),l=D({valueFormat:i.groupLabelFormat,locale:n,numberFormat:r}),u=ir({valueFormat:i.mainValueFormat,locale:n,numberFormat:r,tickValues:[]}),d=i.label??l(i.value);return{swatch:i.swatch,label:`${s}${d}`,value:i.aggregate===null?null:c(i.aggregate),observationLabel:yh(i.observationLabel,u),comparison:fh(i.comparison,u,o)}})}},fh=(e,t,n)=>e===null?null:{direction:hh(e.variation),percentage:n(Math.abs(e.variation)),reference:`from ${t(e.against)}`},hh=e=>e>0?"up":e<0?"down":"flat",yh=(e,t)=>e===null?null:e.kind==="point"?t(e.value):`${t(e.from)} – ${t(e.to)}`,gh=(e,t)=>{switch(e){case"total":return"Total ";case"average":return t?"Avg. ":"Average ";default:return""}},bh=({legends:e,numberFormat:t,parsingLocale:n,formattingLocale:r})=>{const o=r??n;return e.map(s=>vh(s,o,t))},vh=(e,t,n)=>({...e,items:e.items.map(r=>{const o=D({valueFormat:r.valueFormat,locale:t,numberFormat:n});return{...r,formattedLabel:r.label??o(r.value)}})});function Ht(e,t){return e.axes.find(n=>n.scaleAestheticKey===t)??null}function Sh(e,t){return e.legends.find(n=>n.aesthetics.includes(t))??null}const xh=({guides:e,numberFormat:t,layer:n,locale:r})=>{const o=n.data.getFirst();if(!o)return null;const s=n.mapping.y!==void 0,i=(s?Es:zn)(n.data,n.mapping)(o);if(i===null)return null;const c=s?lt(n.yScaleType):"x",l=Ht(e,c)?.valueFormat??{type:"decimal"};return D({valueFormat:l,locale:r,numberFormat:t})(i)},wh=800,Io=400,Ah={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}}},Th=e=>Math.max(1,(e-Io)/(wh-Io)+1),Mh=(e,t)=>{const n=Th(t),r=Ah[e];return{strokeWidth:Math.min(r.strokeWidth.targetValue,r.strokeWidth.minValue*n),arrowheadLength:Math.min(r.arrowheadLength.targetValue,r.arrowheadLength.minValue*n)}},wt=Math.PI/4,kn=1.5,Lh=({startX:e,startY:t,endX:n,endY:r})=>`M ${e} ${t} L ${n} ${r}`,Co=(e,t,n)=>{if(n<=0)return"";const{startX:r,startY:o,endX:s,endY:a}=t,i=e==="start"?r:s,c=e==="start"?o:a,l=e==="start"?Math.atan2(o-a,r-s):Math.atan2(a-o,s-r),u=i-n*Math.cos(l-wt),d=c-n*Math.sin(l-wt),p=i-n*Math.cos(l+wt),m=c-n*Math.sin(l+wt);return`M ${i} ${c} L ${u} ${d} M ${i} ${c} L ${p} ${m}`},Vh=(e,t)=>e==="solid"?null:`${t*kn} ${t*kn*2}`,kh=(e,t)=>t?e*kn:0,Eh=64,Ih=({arrow:e,panelWidth:t,panelHeight:n})=>{const r={startX:e.start.x*t,startY:e.start.y*n,endX:e.end.x*t,endY:e.end.y*n};if(r.startX===r.endX&&r.startY===r.endY)return null;const{strokeWidth:o,arrowheadLength:s}=Mh(e.thickness,t),a=Math.hypot(r.endX-r.startX,r.endY-r.startY),i=Ch(s,a),c=e.startArrowheadStyle==="line-arrow",l=e.endArrowheadStyle==="line-arrow",d=c||l?i*Math.sin(Math.PI/4):0;return{id:e.id,linePath:Lh(r),startArrowheadPath:c?Co("start",r,i):"",endArrowheadPath:l?Co("end",r,i):"",color:e.color,strokeWidth:o,dashArray:Vh(e.lineStyle,o),hasStickerStyle:e.hasStickerStyle,startX:r.startX,startY:r.startY,endX:r.endX,endY:r.endY,dashOffset:kh(o,c),arrowheadExtent:d}},Ch=(e,t)=>Math.min(e,t*e/Eh);function La(e,t){return dr(e.buckets,t,n=>n.main)}function Fh(e,t){return dr(e.bands,t,n=>n.bandCenter)}function Dh(e,t){return dr(e.columns,t,n=>n.mainMid)}function dr(e,t,n){if(e.length===0)return null;let r=0,o=e.length;for(;r<o;){const i=r+o>>>1,c=e[i];c&&n(c)<t?r=i+1:o=i}const s=e[r-1],a=e[r];return s?a&&Math.abs(n(a)-t)<Math.abs(n(s)-t)?a:s:a??null}function pr(e,t,n){return Math.hypot(e*n,t)}function _h(e,t,n,r){if(e.points.length===0)return null;const o=e.delaunay;if(!o)return null;const s=o.find(t.x*n,t.y,r??void 0),a=e.points[s];return a?{hit:{layerId:e.layerId,pointIndex:a.pointIndex,x:a.x,y:a.y,observation:a.observation},index:e,distance:pr(a.x-t.x,a.y-t.y,n)}:null}function Rh(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 Fo(e,t){return{group:Ph(e),related:Bh(e,t)}}function Ph(e){switch(e.kind){case"buckets":{const t=e.match.index;return K(t.position)?Nh(t,e.match):[]}case"rects":{const t=e.match.index;return K(t.position)?Oh(t,e.match):$h(t,e.match)}case"points":case"arcs":case"polar-points":case"render-hit-test":return[]}}function Nh(e,t){const n=[];for(const r of t.bucket.entries)r.pointIndex!==t.hit.pointIndex&&n.push({layerId:e.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation});return n}function Oh(e,t){const n=[];for(const r of t.column.rects)r.pointIndex!==t.hit.pointIndex&&n.push(mr(e,r));return n}function $h(e,t){const n=e.bands.find(o=>o.columns.includes(t.column));if(!n)return[];const r=[];for(const o of n.columns)for(const s of o.rects)s.pointIndex!==t.hit.pointIndex&&r.push(mr(e,s));return r}function Bh(e,t){const n=new Map;if(e.kind==="arcs"||e.kind==="polar-points")return n;for(const r of t){if(r.layerId!==e.match.index.layerId){zh(n,r,e.match.hit);continue}e.kind==="buckets"&&(K(r.position)||r.kind==="buckets"&&Gh(n,r,e.match))}return n}function Gh(e,t,n){for(const r of n.bucket.entries){if(r.pointIndex===n.hit.pointIndex)continue;kt(e,t.layerId).push({layerId:t.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation})}}function zh(e,t,n){switch(t.kind){case"buckets":{const r=La(t,ot(t.mainAxis,n));if(!r)return;const o=kt(e,t.layerId);for(const s of r.entries)o.push({layerId:t.layerId,pointIndex:s.pointIndex,x:s.x,y:s.y,observation:s.observation});return}case"rects":{const r=Fh(t,ot(t.mainAxis,n));if(!r)return;const o=kt(e,t.layerId);for(const s of r.columns)for(const a of s.rects)o.push(mr(t,a));return}case"points":{const r=Rh(t,n);if(!r)return;kt(e,t.layerId).push({layerId:t.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation});return}case"arcs":case"polar-points":return;case"noop":return;case"render-hit-test":return}}function kt(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 Uh(e){const t=Yh(e);return{kind:"arcs",layerId:e.id,position:e.position,arcs:t}}function Yh(e){const t=e.data;if(t.size()===0)return[];const n=[g.xMin,g.xMax,g.yMin,g.yMax];for(const l of n)if(!t.hasVariable(l))return[];const r=t.getValues(g.xMin,{type:"numeric"}),o=t.getValues(g.xMax,{type:"numeric"}),s=t.getValues(g.yMin,{type:"numeric"}),a=t.getValues(g.yMax,{type:"numeric"}),i=[];let c=0;for(const l of t){const u=r[c],d=o[c],p=s[c],m=a[c];if(!h(u)||!h(d)||!h(p)||!h(m)){c++;continue}i.push({pointIndex:c,startAngle:u,endAngle:d,innerRadius:p,outerRadius:m,observation:l}),c++}return i}const Wh=1e-9;function Hh(e,t){const n=Kh(e,t);n.sort((o,s)=>o.main-s.main);const r=[];for(const o of n){const s=r[r.length-1];s&&Math.abs(s.main-o.main)<=Wh?s.entries.push(o.entry):r.push({main:o.main,entries:[o.entry]})}return{kind:"buckets",layerId:e.id,position:e.position,mainAxis:t,buckets:r}}function Kh(e,t){const n=e.data;if(n.size()===0)return[];const o=n.hasVariable(g.x),s=n.hasVariable(g.y);if(!o||!s)return[];const a=n.getValues(g.x,{type:"numeric"}),i=n.getValues(g.y,{type:"numeric"}),c=t==="y",l=c?g.xMin:g.yMin,u=c?g.xMax:g.yMax,d=K(e.position),p=d?n.getValues(l,{type:"numeric"}):null,m=d?n.getValues(u,{type:"numeric"}):null,f=n.hasVariable(P.group)?n.getValues(P.group,{type:"categorical"}):null,y=[];let b=0;for(const x of n){const S=a[b],w=i[b];if(!h(S)||!h(w)){b+=1;continue}const I=f?.[b]??null,_=c?w:S;if(d){const j=p?.[b],Ue=m?.[b];if(!h(j)||!h(Ue)){b+=1;continue}const T=c?Ue:S,te=c?w:Ue;y.push({main:_,entry:{isStacked:d,pointIndex:b,x:T,y:te,stackMin:j,stackMax:Ue,groupKey:I,observation:x}})}else y.push({main:_,entry:{isStacked:d,pointIndex:b,x:S,y:w,groupKey:I,observation:x}});b+=1}return y}function Xh(e){return{kind:"noop",layerId:e.id,position:e.position}}function jh(e,t){const n={kind:"points",layerId:e.id,position:e.position,points:qh(e),delaunay:null,delaunayAspectRatio:null};return Va(n,t),n}function Va(e,t){e.delaunay&&e.delaunayAspectRatio===t||(e.delaunay=Oa.Delaunay.from(e.points,n=>n.x*t,n=>n.y),e.delaunayAspectRatio=t)}function qh(e){const t=e.data;if(t.size()===0)return[];if(!t.hasVariable(g.x)||!t.hasVariable(g.y))return[];const n=t.getValues(g.x,{type:"numeric"}),r=t.getValues(g.y,{type:"numeric"}),o=[];let s=0;for(const a of t){const i=n[s],c=r[s];s+=1,!(!h(i)||!h(c))&&o.push({pointIndex:o.length,x:i,y:c,observation:a})}return o}function Qh(e){return{kind:"polar-points",layerId:e.id,position:e.position,points:Zh(e)}}function Zh(e){const t=e.data;if(t.size()===0)return[];if(!t.hasVariable(g.x)||!t.hasVariable(g.y))return[];const n=t.getValues(g.x,{type:"numeric"}),r=t.getValues(g.y,{type:"numeric"}),o=[];let s=0;for(const a of t){const i=n[s],c=r[s];s+=1,!(!h(i)||!h(c))&&o.push({pointIndex:o.length,angle:i,radius:c,observation:a})}return o}const Jh=1e6;function ey(e,t){const n=ty(e,t);n.sort((i,c)=>i.mainMid-c.mainMid);const r=new Map,o=new Map;for(const i of n){const c=Do(i.mainMid);let l=r.get(c);if(!l){l={mainMid:i.mainMid,columnKey:c,rects:[]},r.set(c,l);const u=Do(i.bandCenter);let d=o.get(u);d||(d={bandCenter:i.bandCenter,bandKey:u,columns:[]},o.set(u,d)),d.columns.push(l)}l.rects.push(i.entry)}const s=[...r.values()].sort((i,c)=>i.mainMid-c.mainMid),a=[...o.values()].sort((i,c)=>i.bandCenter-c.bandCenter);for(const i of a)i.columns.sort((c,l)=>c.mainMid-l.mainMid);return{kind:"rects",layerId:e.id,position:e.position,mainAxis:t,columns:s,bands:a}}function Do(e){return String(Math.round(e*Jh))}function ty(e,t){const n=e.data;if(n.size()===0)return[];if(!(n.hasVariable(g.xMin)&&n.hasVariable(g.xMax)&&n.hasVariable(g.yMin)&&n.hasVariable(g.yMax)))return[];const o=n.getValues(g.xMin,{type:"numeric"}),s=n.getValues(g.xMax,{type:"numeric"}),a=n.getValues(g.yMin,{type:"numeric"}),i=n.getValues(g.yMax,{type:"numeric"}),c=t==="y",l=c?g.y:g.x,u=n.hasVariable(l)?n.getValues(l,{type:"numeric"}):null,d=n.hasVariable(P.group)?n.getValues(P.group,{type:"categorical"}):null,p=[];let m=0;for(const f of n){const y=o[m],b=s[m],x=a[m],S=i[m];if(!h(y)||!h(b)||!h(x)||!h(S)){m++;continue}const w=c?(x+S)/2:(y+b)/2,I=u?.[m]??w;p.push({mainMid:w,bandCenter:I,entry:{pointIndex:m,xMin:y,xMax:b,yMin:x,yMax:S,segmentKey:d?.[m]??null,observation:f}}),m++}return p}function ny(e){const t=new Map;let n=0;for(const r of e.data)t.set(Bt(r),{pointIndex:n,observation:r}),n++;return{kind:"render-hit-test",layerId:e.id,position:e.position,byKey:t}}function _o(e,t,n){switch(e.spatialMap.kind){case"points":return jh(e,n);case"buckets":return Hh(e,Ro(t));case"rects":return ey(e,Ro(t));case"arcs":return Uh(e);case"polar-points":return Qh(e);case"noop":return Xh(e);case"render-hit-test":return ny(e);default:{const r=e.spatialMap.kind;throw new Error(`buildLayerIndex: unhandled spatial-map kind ${String(r)}`)}}}function Ro(e){if(e.type!=="cartesian")throw new Error("buildLayerIndex: a bucket or rect hit-test requires a cartesian coord system");return e.mainAxis}const Z=Math.PI*2,ry=1e-9;function oy(e,t,n){if(e.arcs.length===0)return null;const{angle:r,radius:o}=sy(t,n);for(const s of e.arcs)if(!(o<s.innerRadius||o>s.outerRadius)&&ay(r,s))return{hit:{layerId:e.layerId,pointIndex:s.pointIndex,x:(s.startAngle+s.endAngle)/2,y:(s.innerRadius+s.outerRadius)/2,observation:s.observation},index:e};return null}function sy(e,t){const n=e.x-.5,r=e.y-.5,o=t>=1?n*2*t:n*2,s=t>=1?r*2:r*2/t,a=Math.hypot(o,s);return{angle:(Math.atan2(o,s)%Z+Z)%Z,radius:a}}function ay(e,t){const n=t.endAngle-t.startAngle;if(Math.abs(n)>=Z-ry)return!0;const r=(n%Z+Z)%Z;return((e-t.startAngle)%Z+Z)%Z<=r}function iy(e,t,n){if(e.points.length===0)return null;const r=t.x-.5,o=t.y-.5,s=n>=1?r*2*n:r*2,a=n>=1?o*2:o*2/n;let i=e.points[0];if(!i)return null;let c=Number.POSITIVE_INFINITY;for(const l of e.points){const u=l.radius*Math.sin(l.angle),d=l.radius*Math.cos(l.angle),p=Math.hypot(u-s,d-a);p<c&&(c=p,i=l)}return{hit:{layerId:e.layerId,pointIndex:i.pointIndex,x:i.angle,y:i.radius,observation:i.observation},index:e,distance:c}}function cy(e,t,n){const r=n.get(e.layerId);if(!r)return null;const o=r({x:t.x,y:1-t.y});if(!o)return null;const s=e.byKey.get(o.key);return s?{hit:{layerId:e.layerId,pointIndex:s.pointIndex,x:t.x,y:t.y,observation:s.observation},index:e}:null}function ly(e,t,n){if(e.buckets.length===0)return null;const{main:r,cross:o}=vf(e.mainAxis,t),s=La(e,r),a=s?.entries??[];if(!s||!Fn(a))return null;const i=my(a,o,e.mainAxis);return{hit:{layerId:e.layerId,pointIndex:i.pointIndex,x:i.x,y:i.y,observation:i.observation},index:e,bucket:s,distance:pr(i.x-t.x,i.y-t.y,n)}}function uy(e,t,n){if(e.columns.length===0)return null;const r=ot(e.mainAxis,t),o=Dh(e,r),s=o?.rects??[];if(!o||!Fn(s))return null;const a=K(e.position)?dy(s,t,e.mainAxis):py(s,t,n);return{hit:{layerId:e.layerId,pointIndex:a.pointIndex,x:(a.xMin+a.xMax)/2,y:(a.yMin+a.yMax)/2,observation:a.observation},index:e,column:o,distance:ka(a,t,n)}}function dy(e,t,n){const r=Wt(n,t);return fr(e,s=>fy(s,n,r),{shortCircuitOnZero:!0})}function py(e,t,n){return fr(e,o=>ka(o,t,n))}function my(e,t,n){return fr(e,o=>Math.abs(Wt(n,o)-t))}function fr(e,t,{shortCircuitOnZero:n=!1}={}){let r=e[0],o=t(r);if(n&&o===0)return r;for(let s=1;s<e.length;s+=1){const a=e[s];if(a===void 0)continue;const i=t(a);if(n&&i===0)return a;i<o&&(r=a,o=i)}return r}function ka(e,t,n){const r=En(t.x,e.xMin,e.xMax),o=En(t.y,e.yMin,e.yMax);return pr(r,o,n)}function fy(e,t,n){const r=t==="x"?e.yMin:e.xMin,o=t==="x"?e.yMax:e.xMax;return En(n,r,o)}function En(e,t,n){return e<t?t-e:e>n?e-n:0}const hy=new Map,yy=.05;function gy({layers:e,cursor:t,aspectRatio:n,warmStarts:r,hitTesters:o=hy}){const s={match:null,distance:Number.POSITIVE_INFINITY},a={match:null,distance:Number.POSITIVE_INFINITY};let i=null;for(const c of e){if(c.kind==="arcs"){const u=oy(c,t,n);return u?{kind:"arcs",match:u}:null}if(c.kind==="polar-points"){const u=iy(c,t,n);return u?{kind:"polar-points",match:u}:null}if(c.kind==="render-hit-test"){const u=cy(c,t,o);u&&(i={kind:"render-hit-test",match:u});continue}const l=vy({layer:c,cursor:t,aspectRatio:n,warmStarts:r});if(l){if(l.kind==="rects"){l.match.distance<s.distance&&(s.match=l,s.distance=l.match.distance);continue}l.match.distance<a.distance&&(a.match=l,a.distance=l.match.distance)}}return i||by({rect:s,continuous:a})}function by({rect:e,continuous:t}){return e.match&&t.match?t.distance<=e.distance+yy?t.match:e.match:e.match??t.match}function vy({layer:e,cursor:t,aspectRatio:n,warmStarts:r}){switch(e.kind){case"buckets":{const o=ly(e,t,n);return o?{kind:"buckets",match:o}:null}case"rects":{const o=uy(e,t,n);return o?{kind:"rects",match:o}:null}case"points":{const o=r.get(e.layerId)??null,s=_h(e,t,n,o);return s?{kind:"points",match:s}:null}case"noop":return null}}const ve={primary:null,group:[],related:new Map},Sy=1;class xy{constructor({layers:t,coordSystem:n}){this.layerIndexes=[],this.layerRefs=[],this.aspectRatio=Sy,this.warmStarts=new Map,this.cachedState=ve,this.cachedKey=null,this.nonInteractiveLayerIds=new Set,this.hitTesters=new Map,this.layerIndexes=t.map(r=>_o(r,n,this.aspectRatio)),this.layerRefs=t.map(r=>Po(r,n)),this.nonInteractiveLayerIds=No(t)}update({layers:t,coordSystem:n}){const r=new Map;for(let a=0;a<this.layerIndexes.length;a+=1){const i=this.layerIndexes[a],c=this.layerRefs[a];!i||!c||r.set(i.layerId,{index:i,ref:c})}const o=[],s=[];for(const a of t){const i=r.get(a.id),c=Po(a,n);if(i!==void 0&&wy(i.ref,c)){o.push(i.index),s.push(i.ref);continue}this.warmStarts.delete(a.id),o.push(_o(a,n,this.aspectRatio)),s.push(c)}for(const a of this.warmStarts.keys())t.some(i=>i.id===a)||this.warmStarts.delete(a);this.layerIndexes=o,this.layerRefs=s,this.nonInteractiveLayerIds=No(t),this.invalidateCache()}setViewport(t){this.aspectRatio=t.width/t.height;for(const n of this.layerIndexes)n.kind==="points"&&Va(n,this.aspectRatio)}setHitTesters(t){this.hitTesters=t}hoverByKey(t,n){const r=this.layerIndexes.find(l=>l.layerId===t);if(!r||r.kind!=="render-hit-test")return ve;const o=r.byKey.get(n);if(!o)return ve;const s={layerId:t,pointIndex:o.pointIndex,x:0,y:0,observation:o.observation},a={kind:"render-hit-test",match:{hit:s,index:r}},{group:i,related:c}=Fo(a,this.layerIndexes);return{primary:s,group:i,related:c}}query(t){if(this.layerIndexes.length===0)return ve;const n=this.nonInteractiveLayerIds.size===0?this.layerIndexes:this.layerIndexes.filter(c=>!this.nonInteractiveLayerIds.has(c.layerId)),r=gy({layers:n,aspectRatio:this.aspectRatio,warmStarts:this.warmStarts,hitTesters:this.hitTesters,cursor:t});if(!r)return this.invalidateCache(),ve;const o=r.match.hit;this.warmStarts.set(o.layerId,o.pointIndex);const s=`${o.layerId}:${o.pointIndex}`;if(this.cachedKey===s)return this.cachedState;const{group:a,related:i}=Fo(r,n);return this.cachedKey=s,this.cachedState={primary:o,group:a,related:i},this.cachedState}invalidateCache(){this.cachedKey=null,this.cachedState=ve}}function Po(e,t){return{data:e.data,geom:e.geom,position:e.position,coord:t}}function No(e){const t=new Set;for(const n of e)n.interactive||t.add(n.id);return t}function wy(e,t){return e.data===t.data&&e.geom===t.geom&&e.position===t.position&&e.coord===t.coord}const Ay=({locale:e,intlOptions:t})=>O(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"long",year:"numeric",weekday:"long",...$,...t}).format(n)),Ty=({locale:e,intlOptions:t})=>O(n=>{const r=n.getUTCSeconds()!==0;return Intl.DateTimeFormat(e,{day:"2-digit",month:"short",year:"numeric",weekday:"short",hour:"2-digit",minute:"2-digit",second:r?"2-digit":void 0,...$,...t}).format(n)}),Ft=e=>{const{valueFormat:t}=e;switch(t.type){case"currency":return ra(e);case"date":return Ay(e);case"datetime":return Ty(e);case"day_month":return aa(e);case"decimal":return Zn(e);case"duration":return Jn();case"integer":return oa(e);case"month":return ia(e);case"month_year":return nr(e);case"percentage":return sa(e);case"quarter":return rr();case"text":return Qn();case"time":return ua(e);case"weekly_date_range":return ca(e);case"weekly_date_range_with_year":return la(e);case"year":return or(e);case"lookup":return Ft({...e,valueFormat:t.fallback});default:{const n=t;throw new Error(`Unhandled value format: ${n.type}`)}}},My={type:"decimal"},Ly=({layers:e,coordSystem:t,scales:n,guides:r,numberFormat:o,parsingLocale:s,hover:a,formattingLocale:i})=>{const{primary:c}=a;if(c===null)return null;const l=i??s;return{header:Vy({layers:e,coordSystem:t,guides:r,primary:c,locale:l,numberFormat:o}),rows:ky({layers:e,coordSystem:t,scales:n,guides:r,hover:a,locale:l,numberFormat:o})}};function Vy(e){if(e.coordSystem.type!=="cartesian")return null;const t=Ht(e.guides,"x");if(!t)return null;const n=e.layers.find(a=>a.id===e.primary.layerId);if(!n)return null;const r=n.semanticMap.encodings.find(a=>a.aesthetic==="x");if(!r)return null;const o=e.primary.observation[r.variable];return h(o)?Ft({valueFormat:t.valueFormat,locale:e.locale,numberFormat:e.numberFormat})(o):null}function ky(e){const t=[],n=e.scales.color??null,r=Fy({guides:e.guides,locale:e.locale,numberFormat:e.numberFormat});for(const o of e.layers){const s=Iy(o,e.hover);if(s.length===0)continue;if(o.semanticMap.detailRows.length>0){const{primary:m}=e.hover;m!==null&&m.layerId===o.id&&t.push(...Ey({layer:o,observation:m.observation,coordSystem:e.coordSystem,locale:e.locale,numberFormat:e.numberFormat}));continue}const a=Is(o.data,o.mapping),i=Cy(s,o,n,a),c=Hl(o.semanticMap),l=D({valueFormat:_y(o),locale:e.locale,numberFormat:e.numberFormat}),u=Dy(e.guides,o),d=o.mapping.color!==void 0,p=rt(o.swatchShape,e.coordSystem);for(const m of i){const f=d?a(m.observation):null,y=_n(m.observation)??null,b=Ho(m.observation),x=d&&f!==null?r(f):u,S=Ry(c,m),w=S===null?"":l(S,m.observation);t.push({swatchColor:y,swatchShape:p,swatchLineType:b,label:x,value:w,isPrimary:m===e.hover.primary,key:`${m.layerId}:${m.pointIndex}`})}}return t}function Ey(e){const t=rt(e.layer.swatchShape,e.coordSystem);return e.layer.semanticMap.detailRows.map((n,r)=>{const o=D({valueFormat:n.valueFormat,locale:e.locale,numberFormat:e.numberFormat}),s=e.observation[n.variable]??null;return{swatchColor:null,swatchShape:t,swatchLineType:"solid",label:n.label,value:s===null?"":o(s,e.observation),isPrimary:!1,key:`${e.layer.id}:detail:${r}`}})}function Iy(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 Cy(e,t,n,r){if(n===null||t.mapping.color===void 0)return e;const o=new Map;return n.domain.forEach((s,a)=>{o.set(E(s),a)}),e.map((s,a)=>{const i=r(s.observation),c=i===null?null:E(i),l=c===null?Number.POSITIVE_INFINITY:o.get(c)??Number.POSITIVE_INFINITY;return{hit:s,originalIndex:a,rank:l}}).sort((s,a)=>s.rank===a.rank?s.originalIndex-a.originalIndex:s.rank-a.rank).map(s=>s.hit)}function Fy({guides:e,locale:t,numberFormat:n}){const r=new Map(e.colorGroups.map(s=>[E(s.value),{label:s.label,format:Ft({valueFormat:s.valueFormat,locale:t,numberFormat:n})}])),o=Ft({valueFormat:{type:"text"},locale:t,numberFormat:n});return s=>{const a=r.get(E(s));return a===void 0?o(s):a.label??a.format(s)}}function Dy(e,t){const n=lt(t.yScaleType);return Ht(e,n)?.label??""}function _y(e){return e.semanticMap.encodings.find(n=>n.aesthetic==="y")?.valueFormat??My}function Ry(e,t){return e(t.observation).encodings.find(r=>r.aesthetic==="y")?.value??null}const Ea={differenceArrow(e){return{type:"annotation",kind:"differenceArrow",annotation:e}},shape(e){return{type:"annotation",kind:"shape",annotation:e}},freeformArrow(e){return{type:"annotation",kind:"freeformArrow",annotation:e}},text(e){return{type:"annotation",kind:"text",annotation:e}},sticker(e){return{type:"annotation",kind:"sticker",annotation:e}},pinnedNumber(e){return{type:"annotation",kind:"pinnedNumber",annotation:e}},comment(e){return{type:"annotation",kind:"comment",annotation:e}}},Py={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 Ia(...e){let t={},n;const[r,...o]=e;h(r)&&!Oy(r)?(t=r,n=o):n=e;const s={mapping:t,layers:[],scales:[],transforms:[],highlights:[],config:{}};return n.reduce((a,i)=>Ca(a,i),s)}function Ny(e,...t){return t.reduce((n,r)=>Ca(n,r),e)}function Oy(e){return typeof e=="object"&&e!==null&&"type"in e}function Ca(e,t){switch(t.type){case"scale":return{...e,scales:[...e.scales,t]};case"coord":return{...e,coords:t};case"config":return{...e,config:$o({},e.config,t.config)};case"layer":return{...e,layers:[...e.layers,t]};case"transform":return{...e,transforms:[...e.transforms,t]};case"mapping":return{...e,mapping:{...e.mapping,...t.mapping}};case"highlight":return{...e,highlights:[...e.highlights,t]};case"annotation":return $y(e,t);default:{const n=t;throw new Error(`Unknown spec item type: ${n.type}`)}}}function $y(e,t){const n={...e.annotations};switch(t.kind){case"differenceArrow":n.differenceArrows=[...n.differenceArrows??[],t.annotation];break;case"shape":n.shapes=[...n.shapes??[],t.annotation];break;case"freeformArrow":n.freeformArrows=[...n.freeformArrows??[],t.annotation];break;case"text":n.textAnnotations=[...n.textAnnotations??[],t.annotation];break;case"sticker":n.stickers=[...n.stickers??[],t.annotation];break;case"pinnedNumber":n.pinnedNumbers=[...n.pinnedNumbers??[],t.annotation];break;case"comment":n.comments=[...n.comments??[],t.annotation];break;case"custom":n.custom=[...n.custom??[],t.annotation];break;default:{const r=t;throw new Error(`Unknown annotation kind: ${r.kind}`)}}return{...e,annotations:n}}function By(e){const t={};for(const s of e.geoms??[]){const a=s;t[a.type]=(i={})=>({type:"layer",geom:a.type,mapping:i.aes,stat:i.stat,params:{...a.defaultParams,...i.params},position:i.position,yScaleType:i.yScaleType,transforms:i.transforms,interactive:i.interactive,dataLabels:i.dataLabels})}const n={};for(const s of e.stats??[]){const a=s;n[a.type]=(i={})=>({type:a.type,...i})}const r={};for(const s of e.transforms??[]){const a=s;r[a.transformType]=(i={})=>({type:"transform",transformType:a.transformType,options:i})}const o={};for(const s of e.annotations??[]){const a=s;o[a.type]=i=>(Gy(a,i.coordinates),{type:"annotation",kind:"custom",annotation:{id:i.id,type:a.type,coordinates:i.coordinates,params:{...a.defaultParams,...i.params},zOrder:i.zOrder}})}return{geom:{...C,...t},stat:{...zt,...n},transform:{...pe,...r},annotation:{...Ea,...o},createSpec:Ia}}function Gy(e,t){const n=e.coordinates;if(n!==void 0){if(n.min!==void 0&&t.length<n.min)throw new Error(`Annotation '${e.type}' requires at least ${n.min} coordinate(s), got ${t.length}.`);if(n.max!==void 0&&t.length>n.max)throw new Error(`Annotation '${e.type}' accepts at most ${n.max} coordinate(s), got ${t.length}.`)}}function zy(e,t={}){return{type:"highlight",id:t.id,predicate:e,scope:t.scope,layerIndex:t.layerIndex}}function Uy(e){return{mapping:e.mapping,layers:e.layers,scales:e.scales.map(Wy),transforms:e.transforms,highlights:e.highlights.map(t=>Yy(t,e.layers)),coords:e.coords,config:e.config}}function Yy(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 Wy(e){return e.scaleType==="palette"?Hy(e):e}function Hy(e){return{...e,palette:Ky(e.palette)}}function Ky(e){return e.type==="custom"?{type:"custom",id:e.id}:e}const Xy={point:{position:Fe.position,params:Fe.params,interactive:!0},line:{position:Qe.position,params:Qe.params,interactive:!0},area:{position:Ze.position,params:Ze.params,interactive:!0},bar:{position:Je.position,params:Je.params,interactive:!0},rule:{position:ue.position,params:ue.params,interactive:ue.interactive}};function jy(e){try{if(Cn(e.transforms)>0||Cn(e.highlights)>0||e.annotations&&Object.keys(e.annotations).length>0)return null;const t=Zy(e.coords),n=[`createSpec(${oe(e.mapping)})`];for(const s of e.layers){const a=qy(In(s));if(a===null)return null;n.push(a)}for(const s of e.scales){const a=Qy(In(s));a&&n.push(a)}t&&n.push(t);const r=st(e.config,Ks);return W(r)&&Object.keys(r).length>0&&n.push(`config(${oe(r)})`),`pipe(
27
- ${n.map(s=>eg(s,2)).join(`,
28
- `)},
29
- )`}catch{return null}}function qy(e){const t=String(e.geom),n=Xy[t];if(!n||Cn(e.transforms)>0)return null;const r={},o=st(e.params??{},n.params);W(o)&&Object.keys(o).length>0&&(r.params=o),typeof e.position=="string"&&e.position!==n.position&&(r.position=e.position),typeof e.interactive=="boolean"&&e.interactive!==n.interactive&&(r.interactive=e.interactive),typeof e.yScaleType=="string"&&e.yScaleType!=="primary"&&(r.yScaleType=e.yScaleType),W(e.mapping)&&Object.keys(e.mapping).length>0&&(r.aes=e.mapping);const a=(Array.isArray(e.stat)?e.stat:[]).filter(c=>c.type!=="identity");if(a.length===1?r.stat=a[0]:a.length>1&&(r.stat=a),W(e.dataLabels)){const c=st(Oo(e.dataLabels,"labelSource"),Oo(In(zs),"labelSource"));W(c)&&Object.keys(c).length>0&&(r.dataLabels=c)}const i=Object.keys(r).length>0;return`geom.${t}(${i?oe(r):""})`}function Qy(e){const t=String(e.scaledAesthetic),n=e.scaleType;if(t==="x"||t==="y"||t==="ySecondary"){const o={};if(n==="continuous")h(e.domainMin)||(o.domainMin=e.domainMin),h(e.domainMax)||(o.domainMax=e.domainMax),typeof e.transform=="string"&&e.transform!=="linear"&&(o.transform=e.transform),e.reverse===!0&&(o.reverse=!0);else if(n==="datetime")h(e.domainMin)||(o.domainMin=e.domainMin),h(e.domainMax)||(o.domainMax=e.domainMax),e.reverse===!0&&(o.reverse=!0);else if(n==="discrete")e.reverse===!0&&(o.reverse=!0),typeof e.padding=="number"&&e.padding!==.1&&(o.padding=e.padding),Array.isArray(e.domain)&&e.domain.length>0&&(o.domain=e.domain),Array.isArray(e.range)&&e.range.length>0&&(o.range=e.range);else throw new Error(`unhandled position scale type: ${String(n)}`);return`scale.${t}(${Object.keys(o).length>0?oe(o):""})`}if(n==="palette"){const o=e.palette;return!W(o)||o.type==="default"?void 0:`scale.${t}.palette(${oe({palette:o})})`}throw new Error(`unhandled visual scale type: ${String(n)}`)}function Zy(e){if(!W(e))return;const t=e.coordType;if(t!=="cartesian"){if(t==="flip"){const n=st(e.params??{},{xLimits:null,yLimits:null});return`coord.flip(${W(n)&&Object.keys(n).length>0?oe(n):""})`}throw new Error(`unhandled coord type: ${String(t)}`)}}function st(e,t){if(!ie.isEqual(e,t)){if(W(e)&&W(t)){const n={};for(const r of Object.keys(e)){const o=st(e[r],t[r]);o!==void 0&&(n[r]=o)}return Object.keys(n).length>0?n:void 0}return e}}function oe(e,t=0){if(e===null)return"null";if(typeof e=="string")return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`;if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e)){if(e.length===0)return"[]";const n=`[${e.map(o=>oe(o,t)).join(", ")}]`;if(!n.includes(`
30
- `)&&n.length<=60)return n;const r=" ".repeat(t+2);return`[
31
- ${e.map(o=>r+oe(o,t+2)).join(`,
32
- `)}
33
- ${" ".repeat(t)}]`}if(W(e)){const n=Object.keys(e);if(n.length===0)return"{}";const r=a=>`${Jy(a)}: ${oe(e[a],t+2)}`,o=`{ ${n.map(r).join(", ")} }`;if(!o.includes(`
34
- `)&&o.length<=60)return o;const s=" ".repeat(t+2);return`{
35
- ${n.map(a=>s+r(a)).join(`,
36
- `)}
37
- ${" ".repeat(t)}}`}throw new Error(`cannot render value of type ${typeof e}`)}function Jy(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:`'${e.replace(/'/g,"\\'")}'`}function eg(e,t){const n=" ".repeat(t);return e.split(`
38
- `).map(r=>n+r).join(`
39
- `)}function W(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function In(e){return W(e)?e:{}}function Oo(e,t){const{[t]:n,...r}=e;return r}function Cn(e){return Array.isArray(e)?e.length:0}function M(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=M({...n,description:`Set ${t.axis} axis label to ${t.label??"(none)"}`})}apply(t){const{axis:n,label:r}=this.params,o=t.config.axes[n].label??null,s=N(t,{config:{axes:{[n]:{label:r}}}}),a=new hr({axis:n,label:o},this.metadata);return{spec:s,revert:a}}}const tg={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=M({...n,description:`Set ${t.axis} axis label mode to ${t.labelMode}`})}apply(t){const{axis:n,labelMode:r}=this.params,o=t.config.axes[n].ticks.mode,s=N(t,{config:{axes:{[n]:{ticks:{mode:r}}}}}),a=new yr({axis:n,labelMode:o},this.metadata);return{spec:s,revert:a}}}const ng={type:"set-axis-label-mode",deserialize:(e,t)=>new yr(e,t)};class Kt{constructor(t,n={}){this.type="set-axis-position",this.params=t,this.metadata=M({...n,description:`Set ${t.axis} axis position to ${t.position}`})}apply(t){const{axis:n,position:r}=this.params,o=N(t,{config:{axes:{[n]:{position:r}}}}),s=n==="x"?{axis:"x",position:t.config.axes.x.position}:{axis:"y",position:t.config.axes.y.position},a=new Kt(s,this.metadata);return{spec:o,revert:a}}}const rg={type:"set-axis-position",deserialize:(e,t)=>new Kt(e,t)};class gr{constructor(t,n={}){this.type="set-axis-ticks-visibility",this.params=t,this.metadata=M({...n,description:`Set ${t.axis} axis ticks visibility to ${t.isVisible}`})}apply(t){const{axis:n,isVisible:r}=this.params,o=t.config.axes[n].ticks.isVisible,s=N(t,{config:{axes:{[n]:{ticks:{isVisible:r}}}}}),a=new gr({axis:n,isVisible:o},this.metadata);return{spec:s,revert:a}}}const og={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=M({...n,description:`Set ${t.axis} axis visibility to ${t.isVisible}`})}apply(t){const{axis:n,isVisible:r}=this.params,o=t.config.axes[n].isVisible,s=N(t,{config:{axes:{[n]:{isVisible:r}}}}),a=new br({axis:n,isVisible:o},this.metadata);return{spec:s,revert:a}}}const sg={type:"set-axis-visibility",deserialize:(e,t)=>new br(e,t)};class Xt{constructor(t,n={}){this.type="set-content-caption",this.params=t,this.metadata=M({...n,description:"Set chart caption"})}apply(t){const n=t.config.content.caption;if(n===this.params.caption)return null;const r=N(t,{config:{content:{caption:this.params.caption}}}),o=new Xt({caption:n},this.metadata);return{spec:r,revert:o}}}const ag={type:"set-content-caption",deserialize:(e,t)=>new Xt(e,t)};class jt{constructor(t,n={}){this.type="set-content-subtitle",this.params=t,this.metadata=M({...n,description:"Set chart subtitle"})}apply(t){const n=t.config.content.subtitle;if(n===this.params.subtitle)return null;const r=N(t,{config:{content:{subtitle:this.params.subtitle}}}),o=new jt({subtitle:n},this.metadata);return{spec:r,revert:o}}}const ig={type:"set-content-subtitle",deserialize:(e,t)=>new jt(e,t)};class qt{constructor(t,n={}){this.type="set-content-title",this.params=t,this.metadata=M({...n,description:"Set chart title"})}apply(t){const n=t.config.content.title;if(n===this.params.title)return null;const r=N(t,{config:{content:{title:this.params.title}}}),o=new qt({title:n},this.metadata);return{spec:r,revert:o}}}const cg={type:"set-content-title",deserialize:(e,t)=>new qt(e,t)};class vr{constructor(t,n={}){this.type="set-grid-visibility",this.params=t,this.metadata=M({...n,description:`Set grid visibility to x=${t.xIsVisible}, y=${t.yIsVisible}`})}apply(t){const n=t.config.axes.x.grid.isVisible,r=t.config.axes.y.grid.isVisible,o=N(t,{config:{axes:{x:{grid:{isVisible:this.params.xIsVisible}},y:{grid:{isVisible:this.params.yIsVisible}}}}}),s=new vr({xIsVisible:n,yIsVisible:r},this.metadata);return{spec:o,revert:s}}}const lg={type:"set-grid-visibility",deserialize:(e,t)=>new vr(e,t)};class Sr{constructor(t,n={}){this.type="set-headline-compare-with",this.params=t,this.metadata=M({...n,description:`Set headline compare with to ${t.compareWith}`})}apply(t){const n=t.config.headline.compareWith,r=N(t,{config:{headline:{compareWith:this.params.compareWith}}}),o=new Sr({compareWith:n},this.metadata);return{spec:r,revert:o}}}const ug={type:"set-headline-compare-with",deserialize:(e,t)=>new Sr(e,t)};class xr{constructor(t,n={}){this.type="set-headline-position",this.params=t,this.metadata=M({...n,description:`Set headline position to ${t.position}`})}apply(t){const n=t.config.headline.position,r=N(t,{config:{headline:{position:this.params.position}}}),o=new xr({position:n},this.metadata);return{spec:r,revert:o}}}const dg={type:"set-headline-position",deserialize:(e,t)=>new xr(e,t)};class Qt{constructor(t,n={}){this.type="set-headline-show",this.params=t,this.metadata=M({...n,description:`Set headline show to ${t.show}`})}apply(t){const n=t.config.headline.show,r=N(t,{config:{headline:{show:this.params.show}}}),o=new Qt({show:n},this.metadata);return{spec:r,revert:o}}}const pg={type:"set-headline-show",deserialize:(e,t)=>new Qt(e,t)};class wr{constructor(t,n={}){this.type="set-headline-size",this.params=t,this.metadata=M({...n,description:`Set headline size to ${t.size}`})}apply(t){const n=t.config.headline.size,r=N(t,{config:{headline:{size:this.params.size}}}),o=new wr({size:n},this.metadata);return{spec:r,revert:o}}}const mg={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=M({...n,description:`Set legend position to ${t.position}`})}apply(t){const n=t.config.legend.position,r=N(t,{config:{legend:{position:this.params.position}}}),o=new Ar({position:n},this.metadata);return{spec:r,revert:o}}}const fg={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=M({...n,description:`Set number format abbreviation to ${t.abbreviation}`})}apply(t){const n=t.config.numberFormat.abbreviation,r=N(t,{config:{numberFormat:{abbreviation:this.params.abbreviation}}}),o=new Tr({abbreviation:n},this.metadata);return{spec:r,revert:o}}}const hg={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=M({...n,description:`Set number format decimals to ${t.decimals}`})}apply(t){const n=t.config.numberFormat.decimals,r=N(t,{config:{numberFormat:{decimals:this.params.decimals}}}),o=new Mr({decimals:n},this.metadata);return{spec:r,revert:o}}}const yg={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=M({...n,description:`Set line interpolation to ${t.interpolate}`})}apply(t){const n=this.params.layerId?Yt(t.layers,this.params.layerId):pt(t.layers,"line","area");if(!Ut(n,"line","area"))return null;const r=n.params.interpolate,o=jn(t,n.id,{...n,params:{...n.params,interpolate:this.params.interpolate}}),s=new Lr({layerId:n.id,interpolate:r},this.metadata);return{spec:o,revert:s}}}const gg={type:"set-line-interpolation",deserialize:(e,t)=>new Lr(e,t)};class Zt{constructor(t,n={}){this.type="set-line-width",this.params=t,this.metadata=M({...n,description:`Set line width to ${t.lineWidth}`})}apply(t){const n=this.params.layerId?Yt(t.layers,this.params.layerId):pt(t.layers,"line","area");if(!Ut(n,"line","area"))return null;const r=n.params.lineWidth,o=jn(t,n.id,{...n,params:{...n.params,lineWidth:this.params.lineWidth}}),s=new Zt({layerId:n.id,lineWidth:r},this.metadata);return{spec:o,revert:s}}}const bg={type:"set-line-width",deserialize:(e,t)=>new Zt(e,t)};class Vr{constructor(t,n={}){this.type="set-point-size",this.params=t,this.metadata=M({...n,description:`Set point size to ${t.size}`})}apply(t){const n=this.params.layerId?Yt(t.layers,this.params.layerId):pt(t.layers,"point");if(!Ut(n,"point"))return null;const r=n.params.size,o=jn(t,n.id,{...n,params:{...n.params,size:this.params.size}}),s=new Vr({layerId:n.id,size:r},this.metadata);return{spec:o,revert:s}}}const vg={type:"set-point-size",deserialize:(e,t)=>new Vr(e,t)};class Dt{constructor(t,n={}){this.type="toggle-line-points",this.params=t,this.metadata=M({...n,description:`${t.showPoints?"Show":"Hide"} line points`})}apply(t){const n=this.params.layerId?Yt(t.layers,this.params.layerId):pt(t.layers,"line");return Ut(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??Xs(t.mapping,t.coords.coordType,C.point({aes:{...n.mapping},interactive:!1})),o={...t,layers:[...t.layers,r]},s=new Dt({layerId:n.id,showPoints:!1},this.metadata);return{spec:o,revert:s}}removePointLayer(t,n){const r=this.findAssociatedPointLayer(t,n);if(!r)return null;const o=Lp(t,r.id),s=new Dt({layerId:n.id,showPoints:!0,removedLayer:r},this.metadata);return{spec:o,revert:s}}findAssociatedPointLayer(t,n){return t.layers.find(r=>r.geom==="point"&&$a(r.mapping,n.mapping))}}const Sg={type:"toggle-line-points",deserialize:(e,t)=>new Dt(e,t)};function Jt(e,t){return e.scales.find(n=>n.scaledAesthetic===t)}function en(e,t,n){const r=e.scales.map(o=>o.scaledAesthetic===t?n:o);return{...e,scales:r}}function tn(e){const t=e.replace(/([A-Z])/g," $1").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}class nn{constructor(t,n={}){this.type="set-scale-domain",this.params=t,this.metadata=M({...n,description:`Set ${tn(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},o={...n,...this.params.domainMin!==void 0&&{domainMin:this.params.domainMin},...this.params.domainMax!==void 0&&{domainMax:this.params.domainMax}},s=en(t,this.params.scaledAesthetic,o),a={scaledAesthetic:this.params.scaledAesthetic};this.params.domainMin!==void 0&&(a.domainMin=r.min),this.params.domainMax!==void 0&&(a.domainMax=r.max);const i=new nn(a,this.metadata);return{spec:s,revert:i}}}const xg={type:"set-scale-domain",deserialize:(e,t)=>new nn(e,t)};class kr{constructor(t,n={}){this.type="set-scale-palette",this.params=t,this.metadata=M({...n,description:`Set ${tn(t.scaledAesthetic)} palette`})}apply(t){const n=Jt(t,this.params.scaledAesthetic);if(n?.scaleType!=="palette")return null;const r=en(t,this.params.scaledAesthetic,{...n,scaledAesthetic:this.params.scaledAesthetic,palette:this.params.palette}),o=new kr({scaledAesthetic:this.params.scaledAesthetic,palette:n.palette},this.metadata);return{spec:r,revert:o}}}const wg={type:"set-scale-palette",deserialize:(e,t)=>new kr(e,t)};class Er{constructor(t,n={}){this.type="set-scale-reverse",this.params=t,this.metadata=M({...n,description:`Set ${tn(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,o=en(t,this.params.scaledAesthetic,{...n,reverse:this.params.reverse}),s=new Er({scaledAesthetic:this.params.scaledAesthetic,reverse:r},this.metadata);return{spec:o,revert:s}}}const Ag={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=M({...n,description:`Set ${tn(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,o=en(t,this.params.scaledAesthetic,{...n,transform:this.params.transform}),s=new Ir({scaledAesthetic:this.params.scaledAesthetic,transform:r},this.metadata);return{spec:o,revert:s}}}const Tg={type:"set-scale-transform",deserialize:(e,t)=>new Ir(e,t)};class Fa{constructor(){this.descriptors=new Map}register(t){if(this.descriptors.has(t.type))throw new Error(`CommandRegistry: descriptor for type '${t.type}' is already registered`);this.descriptors.set(t.type,t)}serialize(t){return{type:t.type,params:t.params,metadata:t.metadata}}deserialize(t){return this.getDescriptor(t.type).deserialize(t.params,t.metadata)}getRegisteredTypes(){return[...this.descriptors.keys()]}getDescriptor(t){const n=this.descriptors.get(t);if(!n)throw new Error(`CommandRegistry: no descriptor registered for type '${t}'`);return n}}const L=new Fa;L.register(gg);L.register(bg);L.register(vg);L.register(Sg);L.register(xg);L.register(wg);L.register(Ag);L.register(Tg);L.register(tg);L.register(ng);L.register(rg);L.register(og);L.register(sg);L.register(ag);L.register(ig);L.register(cg);L.register(lg);L.register(ug);L.register(dg);L.register(pg);L.register(mg);L.register(fg);L.register(hg);L.register(yg);class Mg{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,Fr="normal",Da={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},Lg=e=>{const t=e.style??Fr,n=e.weight??Cr,r=e.family.includes(",")?e.family:`'${e.family}'`;return`${t} ${n} ${e.size}px ${r}`},Vg=e=>typeof e=="string"?e:_a(e),_a=e=>e.text!==void 0?e.text:e.content?e.content.map(_a).join(""):"",Ra=e=>typeof e!="string"?e??Cr:Da[e],kg="\0";class Eg{constructor(t){this.inner=t,this.cache=new Map}measureText(t,n){const r=this.getCacheKey(t,n),o=this.cache.get(r);if(o)return o;const s=this.inner.measureText(t,n);return this.cache.set(r,s),s}getCacheKey(t,n){return[n.family,n.size,Ra(n.weight),n.style??Fr,t].join(kg)}}const Ig={" ":.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},Cg=.55,Fg=1.05,Dg=.84,_g=.21;class Rg{measureText(t,n){let r=0;for(const i of t)r+=(Ig[i]??Cg)*n.size;Ra(n.weight)>=Da.semiBold&&(r*=Fg);const s=Dg*n.size,a=_g*n.size;return{width:r,height:s+a,ascent:s,descent:a}}}class Pg extends ze{constructor(t){super(),this.type=t.type,this.computedVariables=new Set(t.computedVariables??[]),this.computedColumns=new Set(t.computedColumns??[]),this.computeFn=t.compute}computeStat(t){return this.computeFn({...t,column:n=>this.namespaceColumn(n)})}namespaceColumn(t){if(!this.computedColumns.has(t)){const n=[...this.computedColumns].map(r=>`'${r}'`).join(", ")||"(none)";throw new Error(`Stat '${this.type}': column('${t}') is not declared in computedColumns ${n}`)}return A(`${this.type}_${t}`)}}function Ng(e){const t=e;return new Pg(t)}class Og{constructor(t){this.transformType=t.transformType,this.applyFn=t.apply}apply(t,n){const r=n.options??{};return this.applyFn(t,r)}}function $g(e){const t=e;return new Og(t)}function Bg(e,t,n){const r=e[t];return typeof r=="number"?r:n??null}function Gg(e,t,n){const r=e[t];return typeof r=="string"?r:n??null}class zg{constructor(){this.columnTypes=new Map,this.kindColumns=new Map,this.rows=[]}kind(t,n){if(this.kindColumns.has(t))throw new Error(`createMarkTable: kind "${t}" is already declared.`);for(const[r,o]of Object.entries(n)){const s=this.columnTypes.get(r);if(s!==void 0&&s!==o)throw new Error(`createMarkTable: column "${r}" is declared as both "${s}" and "${o}".`);this.columnTypes.set(r,o)}return this.kindColumns.set(t,Object.keys(n)),this}push(t,n){const r=this.kindColumns.get(t);if(!r)throw new Error(`createMarkTable: cannot push to undeclared kind "${t}".`);for(const o of r)if(!(o in n))throw new Error(`createMarkTable: row for kind "${t}" is missing column "${o}".`);for(const o of Object.keys(n))if(!r.includes(o))throw new Error(`createMarkTable: column "${o}" is not declared for kind "${t}".`);return this.rows.push({kind:t,values:n}),this}toDataset(t){const{kindColumn:n}=t;if(this.columnTypes.has(n))throw new Error(`createMarkTable: kindColumn "${n}" collides with a declared column.`);const r={[n]:{type:"categorical",values:this.rows.map(o=>o.kind)}};for(const[o,s]of this.columnTypes)r[o]={type:s,values:this.rows.map(a=>{const i=a.values[o];return i===void 0?null:i})};return new V(r)}}function Ug(){return new zg}function Yg(e){return{type:e.type,defaultParams:e.defaultParams??{},coordinates:e.coordinates}}function Wg(e,t,n,r,o){const s=n-t;return s===0?r:r+(e-t)/s*(o-r)}exports.BORDER_PRESETS=Bs;exports.BORDER_PRESET_GRADIENTS=Py;exports.BUILTIN_GEOM_NAMES=Ls;exports.COMPILER_STAGE_KEYS=cm;exports.CachedTextMeasurer=Eg;exports.CommandRegistry=Fa;exports.CommandStackManager=Mg;exports.Compiler=ta;exports.DEFAULT_COLOR_PALETTE=Wn;exports.DEFAULT_FONT_STYLE=Fr;exports.DEFAULT_FONT_WEIGHT=Cr;exports.DEFAULT_LOCALE=Pt;exports.Dataset=V;exports.GEOM_NAMES=Ms;exports.GROUP_VARIABLES=P;exports.Geom=Ne;exports.HeuristicTextMeasurer=Rg;exports.HoverEngine=xy;exports.LAYOUT_PADDING=ha;exports.LayoutCompiler=pf;exports.MONO_BASES=Ps;exports.NEON_BASES=Ns;exports.POSITION_VARIABLES=g;exports.RESTING_HOVER_STATE=ve;exports.SetAxisPositionCommand=Kt;exports.SetContentCaptionCommand=Xt;exports.SetContentSubtitleCommand=jt;exports.SetContentTitleCommand=qt;exports.SetHeadlineShowCommand=Qt;exports.SetLineWidthCommand=Zt;exports.SetScaleDomainCommand=nn;exports.SpecResolver=Qs;exports.Stat=ze;exports.VISUAL_VARIABLES=fe;exports.annotation=Ea;exports.buildAverageLineSymbols=yf;exports.buildDataLabelsContent=th;exports.buildFontString=Lg;exports.buildLayerYValueFormatter=Ta;exports.buildTooltipContent=Ly;exports.commandRegistry=L;exports.computeDifferenceArrow=ch;exports.computeDirectLabelsLayout=uh;exports.computeFreeformArrow=Ih;exports.config=Gs;exports.convertSpecToInput=Uy;exports.coord=B;exports.createAlphaValueReader=Pl;exports.createColorValueReader=Is;exports.createCommandMetadata=M;exports.createCompiler=lm;exports.createEmptyHighlight=Cs;exports.createGraphyBuilder=By;exports.createGroupValueReader=Nl;exports.createLabelValueReader=_l;exports.createMarkTable=Ug;exports.createRawValueReader=X;exports.createSegmentYReader=Un;exports.createSizeValueReader=Rl;exports.createSpec=Ia;exports.createStrokeWidthValueReader=Ol;exports.createValueFormatter=D;exports.createXValueReader=zn;exports.createYValueReader=Es;exports.defineAnnotation=Yg;exports.defineStat=Ng;exports.defineTransform=$g;exports.extractConstantValue=se;exports.extractPlainText=Vg;exports.extractVariableName=v;exports.findAxisGuide=Ht;exports.findLegendForAesthetic=Sh;exports.formatHeadline=dh;exports.formatLegends=bh;exports.formatRuleValue=xh;exports.geom=C;exports.getAlpha=Za;exports.getAngleExtent=wa;exports.getColor=_n;exports.getCrossAxisCoordinate=Wt;exports.getDifferenceArrowDimensions=cr;exports.getGroup=_e;exports.getIdentityKey=Bt;exports.getLineType=Ho;exports.getMainAxisCoordinate=ot;exports.getRadiusExtent=Aa;exports.getSize=Wo;exports.getStrokeWidth=Ja;exports.getX=Oe;exports.getXMax=Ce;exports.getXMin=nt;exports.getY=ae;exports.getYMax=J;exports.getYMin=Ae;exports.getYRaw=gs;exports.highlight=zy;exports.interpolateInScaledInterval=Wg;exports.isBuiltinGeomName=Vs;exports.isCartesian=Sf;exports.isCompilerCachingEnabled=Ga;exports.isDefined=h;exports.isGraphConfig=Os;exports.isLayerOf=um;exports.isStackedPosition=K;exports.mapping=Ya;exports.pipe=Ny;exports.prefixInternalVariable=A;exports.readAesthetic=Dn;exports.readNumber=Bg;exports.readString=Gg;exports.resolveHeadlinePlacement=lf;exports.resolveSegmentYSource=ut;exports.resolveYScaleAesthetic=lt;exports.scale=xe;exports.setCompilerCachingEnabled=Ba;exports.sortByXIfContinuous=Nt;exports.specToBuilderSource=jy;exports.stat=zt;exports.transform=pe;exports.variableFor=U;
20
+ M ${t.x-n} ${t.y-r-n}
21
+ L ${t.x} ${t.y-r}
22
+ L ${t.x+n} ${t.y-r-n}
23
+ `,yf=(e,t,r,n,a,i=.5)=>e?{x:n,y:Math.min(t.y,r.y)+i*a}:{x:Math.min(t.x,r.x)+i*a,y:n},vf=(e,t,r)=>Math.abs(e?t.y-r.y:t.x-r.x),is=({arrow:e,mainAxis:t,panelWidth:r,panelHeight:n,textScale:a,locale:i})=>{const s=t==="y",o={x:e.start.x*r,y:(1-e.start.y)*n},c={x:e.end.x*r,y:(1-e.end.y)*n},u=as(e.size,a),d=hf(s,o,c,u),m=(s?ff:pf)(o,c,d,u),h=gf(s,c,u),p=yf(s,o,c,d,vf(s,o,c),e.labelCrossPosition),f=ns({locale:i,kind:e.label,startValue:e.start.measurementValue,endValue:e.end.measurementValue,valueFormat:e.start.valueFormat});return{id:e.id,start:o,end:c,linePath:m,arrowheadPath:h,labelPosition:p,labelText:f,color:e.color,strokeWidth:u.strokeWidth,labelLineHeight:u.labelLineHeight,labelPaddingX:u.labelPaddingX,labelPaddingY:u.labelPaddingY,labelStrokeWidth:u.labelStrokeWidth,labelFontWeight:u.labelFontWeight}};function*bf({annotations:e,mainAxis:t,panelRect:r,textScale:n,locale:a,measureLabel:i}){for(const s of e.differenceArrows){if(!Ee(s.start.x,s.start.y)||!Ee(s.end.x,s.end.y))continue;const o=is({arrow:s,mainAxis:t,panelWidth:r.width,panelHeight:r.height,textScale:n,locale:a}),c=i(o.labelText,s.size).width+2*o.labelPaddingX,u=o.labelLineHeight+2*o.labelPaddingY;yield{x:r.x+o.labelPosition.x-c/2,y:r.y+o.labelPosition.y-u/2,width:c,height:u}}}var Sf=e=>{const t=e.padding,r=Un(e.rows,t?.top??0,t?.bottom??0),n=Un(e.cols,t?.left??0,t?.right??0);return{rows:r.tracks,cols:n.tracks,placements:Tf(e.placements,r.nameToIndex,n.nameToIndex),width:e.containerSize.width,height:e.containerSize.height}},xf=e=>{const t=Wn(e.rows,e.height),r=Wn(e.cols,e.width),n=Hn(t),a=Hn(r),i=new Map;for(const s of e.placements){const o=s.rowSpan??1,c=s.colSpan??1,u=a[s.col]??0,d=n[s.row]??0,m=Kn(r,s.col,c),h=Kn(t,s.row,o);i.set(s.name,{x:u,y:d,width:Math.max(0,m),height:Math.max(0,h)})}return i},Un=(e,t,r)=>{const n=[],a=new Map;t>0&&n.push({type:"fixed",pixels:t});let i=0;for(let s=0;s<e.length;s++){const o=e[s];if(!o)continue;dr(o)&&i>0&&(n.push({type:"fixed",pixels:i}),i=0),a.set(o.name,n.length),n.push(Af(o));const c=If(e,s);if(dr(o)&&c){const u=o.gaps?.after??0,d=c.gaps?.before??0;u>=d?u>0&&n.push({type:"fixed",pixels:u}):i=d}}return r>0&&n.push({type:"fixed",pixels:r}),{tracks:n,nameToIndex:a}},Af=e=>typeof e.size=="number"?{type:"fixed",pixels:e.size}:{type:"flex",weight:e.size.flex},dr=e=>typeof e.size=="number"?e.size>0:e.size.flex>0,If=(e,t)=>{for(let r=t+1;r<e.length;r++){const n=e[r];if(n&&dr(n))return n}},Tf=(e,t,r)=>{const n=[];for(const a of e){const i=t.get(a.row),s=r.get(a.col);if(i===void 0||s===void 0)continue;const o=a.rowEnd!==void 0?t.get(a.rowEnd):i,c=a.colEnd!==void 0?r.get(a.colEnd):s;o===void 0||c===void 0||n.push({name:a.name,row:i,col:s,rowSpan:Math.max(1,o-i+1),colSpan:Math.max(1,c-s+1)})}return n},Wn=(e,t)=>{let r=0,n=0;for(const i of e)i.type==="fixed"?r+=i.pixels:n+=i.weight;const a=Math.max(0,t-r);return e.map(i=>i.type==="fixed"?i.pixels:n===0?0:i.weight/n*a)},Hn=e=>{const t=new Array(e.length);let r=0;for(let n=0;n<e.length;n++)t[n]=r,r+=e[n]??0;return t},Kn=(e,t,r)=>{let n=0;const a=Math.min(t+r,e.length);for(let i=t;i<a;i++)n+=e[i]??0;return n},Ce={top:0,right:0,bottom:0,left:0},ss={outer:Ce,inner:Ce},Lf={top:24,right:24,bottom:24,left:24},wf=(e,t,r,n=Ce,a=ss,i=Lf,s={})=>{const o={top:a.inner.top+n.top,right:a.inner.right+n.right,bottom:a.inner.bottom+n.bottom,left:a.inner.left+n.left},c=r.axes.top>0||r.axesLabels.top>0?r.axesLabels.top:Math.max(r.axesLabels.top,r.axesLabels.left,r.axesLabels.right),u=zn(zh,s),d=zn(Yh,s);return Sf({rows:[{name:"header",size:t.headerSize.height,gaps:u.header},{name:"topLegend",size:r.legends.top,gaps:u.topLegend},{name:"headline",size:r.headline,gaps:u.headline},{name:"topAxisLabel",size:c,gaps:u.topAxisLabel},{name:"topAxis",size:r.axes.top,gaps:u.topAxis},{name:"topPanelOuter",size:a.outer.top},{name:"topPanelInner",size:o.top},{name:"panel",size:{flex:1}},{name:"bottomPanelInner",size:o.bottom},{name:"bottomPanelOuter",size:a.outer.bottom},{name:"bottomAxis",size:r.axes.bottom,gaps:u.bottomAxis},{name:"bottomAxisLabel",size:r.axesLabels.bottom,gaps:u.bottomAxisLabel},{name:"bottomLegend",size:r.legends.bottom,gaps:u.bottomLegend},{name:"footer",size:t.footerSize.height,gaps:u.footer}],cols:[{name:"leftLegend",size:r.legends.left,gaps:d.leftLegend},{name:"leftAxis",size:r.axes.left,gaps:d.leftAxis},{name:"leftPanelOuter",size:a.outer.left},{name:"leftPanelInner",size:o.left},{name:"panel",size:{flex:1}},{name:"rightPanelInner",size:o.right},{name:"rightPanelOuter",size:a.outer.right},{name:"rightAxis",size:r.axes.right,gaps:d.rightAxis},{name:"rightLegend",size:r.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:"panelFrame",row:"topPanelInner",rowEnd:"bottomPanelInner",col:"leftPanelInner",colEnd:"rightPanelInner"},{name:"panel",row:"panel",col:"panel"},...Vf(r.axes),...Rf(r.axesLabels,r.axes),...Cf(r.legends)],containerSize:e,padding:i})},Ef=(e,t)=>l.isDefined(t)?typeof t=="number"?{before:e.before,after:Xt(t,e.after)}:{before:Xt(t.before,e.before),after:Xt(t.after,e.after)}:e,Xt=(e,t)=>typeof e=="number"&&Number.isFinite(e)?e:t,zn=(e,t)=>{const r={};for(const n of Object.keys(e))r[n]=Ef(e[n],t[n]);return r},Vf=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},Rf=(e,t)=>{const r=[];return e.top>0||t.top>0?(e.top>0&&r.push({name:"topAxisLabel",row:"topAxisLabel",col:"panel"}),e.left>0&&r.push({name:"leftAxisLabel",row:"topAxis",col:"leftAxis"}),e.right>0&&r.push({name:"rightAxisLabel",row:"topAxis",col:"rightAxis"})):(e.left>0&&r.push({name:"leftAxisLabel",row:"topAxisLabel",col:"leftAxis"}),e.right>0&&r.push({name:"rightAxisLabel",row:"topAxisLabel",col:"rightAxis"})),e.bottom>0&&r.push({name:"bottomAxisLabel",row:"bottomAxisLabel",col:"panel"}),r},Cf=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};var kf=class{constructor(e){this.outer={...Ce},this.inner={...Ce},this.currentPanelRect=e}resolve(){return{outer:{...this.outer},inner:{...this.inner}}}add(e,t){const r=this.computeEdgeOverflow(e,8),n=this.computeEdgeOverflow(e,0);this.growEdge("left",t.x,r.left,n.left),this.growEdge("right",t.x,r.right,n.right),this.growEdge("top",t.y,r.top,n.top),this.growEdge("bottom",t.y,r.bottom,n.bottom)}computeEdgeOverflow(e,t){const r=this.currentPanelRect;return{top:Math.max(Math.ceil(r.y+t-e.y),0),right:Math.max(Math.ceil(e.x+e.width-(r.x+r.width-t)),0),bottom:Math.max(Math.ceil(e.y+e.height-(r.y+r.height-t)),0),left:Math.max(Math.ceil(r.x+t-e.x),0)}}growEdge(e,t,r,n){t!=="none"&&(t==="outside"?n>0&&(this.outer[e]=Math.max(this.outer[e],n)):r>0&&(this.inner[e]=Math.max(this.inner[e],r)))}},Df=["top","right","bottom","left"],jt=(e,t)=>{const r={};for(const n of Df){const a=e.get(`${n}${t}`);a&&(r[n]=a)}return r};function Yn(e,t){return e.top===t.top&&e.right===t.right&&e.bottom===t.bottom&&e.left===t.left}var mr=["large","medium","small"],Pf=({size:e,availableWidth:t,measureStripWidth:r})=>{if(e!=="auto")return e;for(const n of mr)if(r(n)<=t)return n;return"small"},Of=({size:e,availableWidth:t,measureStripWidth:r})=>{const n=e==="auto"?0:mr.indexOf(e);for(const a of mr.slice(n))if(r(a)<=t)return a;return null},Mf=({itemWidths:e,gap:t,availableWidth:r})=>{let n=0,a=0;for(const i of e){const s=a===0?i:n+t+i;if(s>r)break;n=s,a+=1}return a},_f=({headline:e,containerSize:t,measurer:r})=>{if(os(e))return 0;const n=ls(e,t.width,r);return r.measureHeadline(e.formatted,n).height},Nf=({headline:e,layout:t,containerSize:r,measurer:n,itemGap:a})=>{if(os(e)){const o=Bf(t.panel,e.innerRadius),c=Of({size:e.size,availableWidth:o.width,measureStripWidth:cs(e,n)});return c===null?null:{rect:o,resolvedSize:c,visibleItemCount:1}}const i=ls(e,r.width,n);if(e.formatted.kind!=="perGroup")return{rect:t.headline,resolvedSize:i,visibleItemCount:1};const s=Mf({itemWidths:n.measureHeadlineItemWidths(e.formatted,i),gap:a,availableWidth:t.headline.width});return s===0?null:{rect:t.headline,resolvedSize:i,visibleItemCount:s}},os=e=>e.formatted.kind==="grandTotal"&&e.position==="center"&&e.innerRadius>0,Bf=(e,t)=>{const r=t*(Math.min(e.width,e.height)/2)*Math.SQRT2,n=e.x+e.width/2,a=e.y+e.height/2;return{x:n-r/2,y:a-r/2,width:r,height:r}},ls=(e,t,r)=>Pf({size:e.size,availableWidth:t,measureStripWidth:cs(e,r)}),cs=(e,t)=>r=>t.measureHeadline(e.formatted,r).width,Ie={x:0,y:0,width:0,height:0},Ff="0000",$f=3,_e=e=>typeof e=="number"&&Number.isFinite(e)?e:24,Gf=e=>e.plot.y+e.plot.height-e.panel.y,Uf=e=>{if(typeof e=="object"&&e!==null)return{top:_e(e.top),right:_e(e.right),bottom:_e(e.bottom),left:_e(e.left)};const t=_e(e);return{top:t,right:t,bottom:t,left:t}},Wf=class{constructor(e){this.measurer=e}compile(e){return Tt({axes:e.axes,numberFormat:e.numberFormat,formattedLegends:e.formattedLegends,containerSize:e.containerSize,externalMeasurements:e.externalMeasurements,panelOverflow:ss,panelBorder:e.panelBorder??Ce,headline:e.headline,locale:e.formattingLocale??e.parsingLocale,padding:Uf(e.layout.padding),gaps:e.layout.gaps}).pipe(({axes:t,numberFormat:r,locale:n})=>({axisBundles:t.map(a=>({axis:a,resolveFormatter:Hf(a,n,r),formatted:this.seedAxis(a)}))})).pipe(({axisBundles:t,formattedLegends:r,containerSize:n,externalMeasurements:a,panelOverflow:i,panelBorder:s,headline:o,padding:c,gaps:u})=>({layout:this.resolveLayout({axes:t.map(d=>d.formatted),formattedLegends:r,containerSize:n,externalMeasurements:a,panelOverflow:i,panelBorder:s,headline:o,padding:c,gaps:u})})).pipe(({axisBundles:t,layout:r})=>({axisBundles:t.map(n=>qn(n.axis.position)?{...n,formatted:this.finalizeAxis(n.axis,n.resolveFormatter,r.panelFrame)}:n)})).pipe(({axisBundles:t,formattedLegends:r,containerSize:n,externalMeasurements:a,panelOverflow:i,panelBorder:s,headline:o,padding:c,gaps:u})=>({layout:this.resolveLayout({axes:t.map(d=>d.formatted),formattedLegends:r,containerSize:n,externalMeasurements:a,panelOverflow:i,panelBorder:s,headline:o,padding:c,gaps:u})})).pipe(({axisBundles:t,layout:r})=>({formattedAxes:t.map(n=>qn(n.axis.position)?n.formatted:this.finalizeAxis(n.axis,n.resolveFormatter,r.panelFrame))})).pipe(({formattedAxes:t,formattedLegends:r,containerSize:n,externalMeasurements:a,panelOverflow:i,panelBorder:s,headline:o,padding:c,gaps:u})=>({layout:this.resolveLayout({axes:t,formattedLegends:r,containerSize:n,externalMeasurements:a,panelOverflow:i,panelBorder:s,headline:o,padding:c,gaps:u})})).pipe(({formattedAxes:t,formattedLegends:r,containerSize:n,externalMeasurements:a,layout:i,panelOverflow:s,panelBorder:o,headline:c,locale:u,padding:d,gaps:m})=>({formattedAxes:t,layout:this.settlePanelOverflow({input:e,layout:i,formattedAxes:t,formattedLegends:r,containerSize:n,externalMeasurements:a,panelOverflow:s,panelBorder:o,headline:c,locale:u,padding:d,gaps:m})})).pipe(({formattedAxes:t,layout:r})=>{const n=this.applyPolarPanelInset(e,t,r);return{formattedAxes:t,layout:n,plotBottomY:Gf(n)}}).result()}measurePanelOverflow(e,t,r,n){if(!e.overflowStrategy||e.coordSystem?.type!=="cartesian")return n;const a=new kf(t);if(e.annotations&&e.overflowStrategy.differenceArrows)for(const s of bf({annotations:e.annotations,mainAxis:e.coordSystem.mainAxis,panelRect:t,textScale:e.textScale??1,locale:r,measureLabel:this.measurer.measureDifferenceArrowLabel}))a.add(s,e.overflowStrategy.differenceArrows);if(e.layers&&e.layers.length>0&&e.overflowStrategy.dataLabels)for(const s of mf({layers:e.layers,coordSystem:e.coordSystem,axes:e.axes,numberFormat:e.numberFormat,panelRect:t,measureDataLabel:this.measurer.measureDataLabel,locale:r}))a.add(s,e.overflowStrategy.dataLabels);const i=a.resolve();return Yn(i.inner,n.inner)&&Yn(i.outer,n.outer)?n:i}settlePanelOverflow({input:e,layout:t,formattedAxes:r,formattedLegends:n,containerSize:a,externalMeasurements:i,panelOverflow:s,panelBorder:o,headline:c,locale:u,padding:d,gaps:m}){let h=t,p=s;for(let f=0;f<$f;f++){const g=this.measurePanelOverflow(e,h.panelFrame,u,p);if(g===p)break;p=g,h=this.resolveLayout({axes:r,formattedLegends:n,containerSize:a,externalMeasurements:i,panelOverflow:g,panelBorder:o,headline:c,padding:d,gaps:m})}return h}applyPolarPanelInset(e,t,r){if(e.coordSystem?.type!=="polar")return r;const n=this.measurePolarRimInset(t),{panel:a}=r,i=a.width-n.horizontal*2,s=a.height-n.vertical*2;return i<=0||s<=0?Xn(r,a,0,0):Xn(r,a,n.horizontal,n.vertical)}measurePolarRimInset(e){const t=e.find(a=>a.geometry==="circular");if(!t)return{horizontal:0,vertical:0};let r=0,n=0;for(const a of t.ticks){const i=this.measurer.measureTickLabel(a.formattedLabel);r=Math.max(r,i.width),n=Math.max(n,i.height)}return r===0?{horizontal:0,vertical:0}:{horizontal:r+8,vertical:n+8}}seedAxis(e){const{tickCandidates:t,...r}=e;return{...r,ticks:[{value:0,position:0,formattedLabel:Ff}],labelRotation:0,labelMaxWidthPx:null}}finalizeAxis(e,t,r){const n=e.position==="top"||e.position==="bottom"?r.width:r.height,a=gp({axis:e,availableSpacePx:n,measureLabel:this.measurer.measureTickLabel,resolveFormatter:t}),{tickCandidates:i,...s}=e,o={...s,ticks:a,labelRotation:0,labelMaxWidthPx:null};return e.geometry!=="linear"?o:e.scaleType==="discrete"&&e.bandwidth!==void 0?dp({formattedAxis:o,bandwidthPx:e.bandwidth*n,panelRect:r,measureLabel:this.measurer.measureTickLabel}):o}resolveLayout({axes:e,formattedLegends:t,containerSize:r,externalMeasurements:n,panelOverflow:a,panelBorder:i,headline:s,padding:o,gaps:c}){const u=xf(wf(r,n,this.measureGuides(e,t,s,r),i,a,o,c));return{header:u.get("header")??Ie,headline:u.get("headline")??Ie,footer:u.get("footer")??Ie,plot:u.get("plot")??Ie,panelFrame:u.get("panelFrame")??Ie,panel:u.get("panel")??Ie,axes:jt(u,"Axis"),axisLabels:jt(u,"AxisLabel"),legends:jt(u,"Legend")}}measureGuides(e,t,r,n){const a={top:0,right:0,bottom:0,left:0},i={top:0,right:0,bottom:0,left:0};for(const o of e)o.isVisible&&o.geometry==="linear"&&(a[o.position]=this.measurer.measureAxis(o),o.label!==null&&(i[o.position]=this.measurer.measureAxisLabel(o)));const s={top:0,right:0,bottom:0,left:0};for(const o of t)s[o.position]=this.measurer.measureLegend(o);return{axes:a,axesLabels:i,legends:s,headline:this.measureHeadlineBand(r,n)}}measureHeadlineBand(e,t){return e===void 0?0:_f({headline:e,containerSize:t,measurer:this.measurer})}},qn=e=>e==="left"||e==="right",Xn=(e,t,r,n)=>{const a=t.width-r*2,i=t.height-n*2,s=Math.min(a,i);return{...e,panel:{x:t.x+r+(a-s)/2,y:t.y+n+(i-s)/2,width:s,height:s}}},Hf=(e,t,r)=>{const n=e.tickCandidates.flatMap(i=>i.ticks.map(s=>s.value)),a=new WeakMap;return i=>{const s=a.get(i);if(s)return s;const o=Ur({valueFormat:i.valueFormat??e.valueFormat,locale:t,numberFormat:r,tickValues:n});return a.set(i,o),o}},Kf=(e=[])=>{const t=zf(e);return{resolve:(r,n,a)=>t.has(r)?t.get(r).resolveAnchorPosition?.(n,a)??null:null,hasCapability:r=>t.has(r)&&t.get(r).resolveAnchorPosition!==void 0}},zf=e=>{const t=new We;for(const r of e){const n=Rr(r);n instanceof re&&t.register(n.type,n)}return t};function Yf(e){return e}function Q(e){return 1-e}var oe=e=>`${Number.parseFloat((e*100).toFixed(4))}%`,us=(e,t,r)=>{if(r.type!=="polar")return{x:e.x*t.width,y:Q(e.y)*t.height};const n=Math.min(t.width,t.height),a=(t.width-n)/2,i=(t.height-n)/2;return{x:a+e.x*n,y:i+e.y*n}},qf=class{constructor(e,t,r,n){this.annotations=e,this.panelRect=t,this.coordSystem=r,this.measuredBoxes=n,this.index=null,this.boxes=new Map,this.resolvingStack=[],this.cyclic=new Set,this.missingRefs=new Set}cyclicIds(){return[...this.cyclic]}missingRefIds(){return[...this.missingRefs]}resolvePoint(e){if(e.defer===void 0)return e;const t=this.coordSystem.type==="polar";if(e.defer.type==="px-offset"){if(t)return tt(e);const{x:s,y:o}=hr(e.defer,this.panelRect);return tt({...e,x:e.x+s,y:e.y-o})}if(t)return null;const r=this.boxOf(e.defer.ref);if(r===null)return null;const n=Ge(r,e.defer.align),{x:a,y:i}=Xf(n,e.defer.offset,this.panelRect);return{x:a,y:i}}resolveRegion(e){if(e.defer===void 0)return e;const t=this.coordSystem.type==="polar";if(e.defer.type==="px-offset"){if(t)return tt(e);const{x:i,y:s}=hr(e.defer,this.panelRect);return tt({...e,x:e.x-i,y:e.y-s,width:Math.max(0,e.width+2*i),height:Math.max(0,e.height+2*s)})}if(t)return null;const r=this.boxOf(e.defer.ref);if(r===null)return null;const n=r.xMax-r.xMin,a=r.yMax-r.yMin;return n<=0||a<=0?null:{x:r.xMin,y:r.yMin,width:n,height:a}}getTargetIndex(){if(this.index!==null)return this.index;const{annotations:e}=this,t=new Map,r=(n,a)=>{t.has(n)||t.set(n,a)};for(const n of e.shapes)r(n.id,{kind:"shape",annotation:n});for(const n of e.images)r(n.id,{kind:"image",annotation:n});for(const n of e.arrows)r(n.id,{kind:"arrow",annotation:n});for(const n of e.textAnnotations)r(n.id,{kind:"text",annotation:n});for(const n of e.stickers)r(n.id,{kind:"sticker",annotation:n});for(const n of e.differenceArrows)r(n.id,{kind:"differenceArrow",annotation:n});for(const n of e.pinnedNumbers)r(n.id,{kind:"pinnedNumber",annotation:n});for(const n of e.comments)r(n.id,{kind:"comment",annotation:n});return this.index=t,t}boxOf(e){const t=this.boxes.get(e);if(t!==void 0)return t;const r=this.resolvingStack.indexOf(e);if(r!==-1){for(const i of this.resolvingStack.slice(r))this.cyclic.add(i);return null}const n=this.getTargetIndex().get(e);if(n===void 0)return this.missingRefs.add(e),null;this.resolvingStack.push(e);const a=this.deriveBox(e,n);return this.resolvingStack.pop(),this.boxes.set(e,a),a}deriveBox(e,t){switch(t.kind){case"shape":case"image":{const r=this.resolveRegion(t.annotation.region);return r===null?null:jf(r)}case"arrow":{const r=this.resolvePoint(t.annotation.start),n=this.resolvePoint(t.annotation.end);return r===null||n===null?null:jn(r,n)}case"text":{const r=this.resolvePoint(t.annotation.at);if(r===null)return null;const n=this.measuredBoxes?.get(e);if(n===void 0||n.height<=0||this.panelRect.height<=0)return null;const a=t.annotation.width,i=n.height/this.panelRect.height,s=ba(t.annotation.align),o=r.x-s.x*a,c=r.y+(1-s.y)*i;return{xMin:o,xMax:o+a,yMin:c-i,yMax:c}}case"sticker":{const r=this.resolvePoint(t.annotation.at);return r===null?null:Zn(r)}case"differenceArrow":return jn(t.annotation.start,t.annotation.end);case"pinnedNumber":case"comment":return Zn(t.annotation.at)}}},hr=(e,t)=>({x:t.width>0?e.x/t.width:0,y:t.height>0?e.y/t.height:0}),Xf=(e,t,r)=>{if(t===void 0)return e;const n=t.x??0,a=t.y??0;if(t.unit==="px"){const{x:i,y:s}=hr({type:"px-offset",x:n,y:a},r);return{x:e.x+i,y:e.y-s}}return{x:e.x+n,y:e.y-a}},jf=e=>({xMin:e.x,xMax:e.x+e.width,yMin:e.y,yMax:e.y+e.height}),jn=(e,t)=>({xMin:Math.min(e.x,t.x),xMax:Math.max(e.x,t.x),yMin:Math.min(e.y,t.y),yMax:Math.max(e.y,t.y)}),Zn=e=>({xMin:e.x,xMax:e.x,yMin:e.y,yMax:e.y}),tt=e=>{const t={...e};return delete t.defer,t},Zf=e=>{const{annotations:t,panelRect:r,coordSystem:n,measuredBoxes:a,onCycle:i,onMissingRef:s}=e;if(!Jf(t))return t;const o=new qf(t,r,n,a),c={...t,shapes:Ne(t.shapes,m=>m.region.defer!==void 0,m=>{const h=o.resolveRegion(m.region);return h===null?null:{...m,region:h}}),images:Ne(t.images,m=>m.region.defer!==void 0,m=>{const h=o.resolveRegion(m.region);return h===null?null:{...m,region:h}}),arrows:Ne(t.arrows,m=>m.start.defer!==void 0||m.end.defer!==void 0,m=>{const h=o.resolvePoint(m.start),p=o.resolvePoint(m.end);return h===null||p===null?null:{...m,start:h,end:p}}),textAnnotations:Ne(t.textAnnotations,m=>m.at.defer!==void 0,m=>{const h=o.resolvePoint(m.at);return h===null?null:{...m,at:h}}),stickers:Ne(t.stickers,m=>m.at.defer!==void 0,m=>{const h=o.resolvePoint(m.at);return h===null?null:{...m,at:h}})},u=o.cyclicIds();u.length>0&&i?.(u);const d=o.missingRefIds();return d.length>0&&s?.(d),c},Ne=(e,t,r)=>e.some(t)?e.flatMap(n=>{if(!t(n))return[n];const a=r(n);return a===null?[]:[a]}):e,Jf=e=>e.shapes.some(t=>t.region.defer!==void 0)||e.images.some(t=>t.region.defer!==void 0)||e.arrows.some(t=>t.start.defer!==void 0||t.end.defer!==void 0)||e.textAnnotations.some(t=>t.at.defer!==void 0)||e.stickers.some(t=>t.at.defer!==void 0),Qf=800,Jn=400,eg={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}}},tg=e=>Math.max(1,(e-Jn)/(Qf-Jn)+1),rg=(e,t)=>{const r=tg(t),n=eg[e];return{strokeWidth:Math.min(n.strokeWidth.targetValue,n.strokeWidth.minValue*r),arrowheadLength:Math.min(n.arrowheadLength.targetValue,n.arrowheadLength.minValue*r)}},rt=Math.PI/4,pr=1.5,ng=({startX:e,startY:t,endX:r,endY:n})=>`M ${e} ${t} L ${r} ${n}`,Qn=(e,t,r)=>{if(r<=0)return"";const{startX:n,startY:a,endX:i,endY:s}=t,o=e==="start"?n:i,c=e==="start"?a:s,u=e==="start"?Math.atan2(a-s,n-i):Math.atan2(s-a,i-n);return`M ${o} ${c} L ${o-r*Math.cos(u-rt)} ${c-r*Math.sin(u-rt)} M ${o} ${c} L ${o-r*Math.cos(u+rt)} ${c-r*Math.sin(u+rt)}`},ag=(e,t)=>e==="solid"?null:`${t*pr} ${t*pr*2}`,ig=(e,t)=>t?e*pr:0,sg=64,og=({arrow:e,panelWidth:t,panelHeight:r})=>{const n={startX:e.start.x*t,startY:(1-e.start.y)*r,endX:e.end.x*t,endY:(1-e.end.y)*r};if(n.startX===n.endX&&n.startY===n.endY)return null;const{strokeWidth:a,arrowheadLength:i}=rg(e.thickness,t),s=Math.hypot(n.endX-n.startX,n.endY-n.startY),o=lg(i,s),c=e.startArrowheadStyle==="line-arrow",u=e.endArrowheadStyle==="line-arrow",d=c||u?o*Math.sin(Math.PI/4):0;return{id:e.id,linePath:ng(n),startArrowheadPath:c?Qn("start",n,o):"",endArrowheadPath:u?Qn("end",n,o):"",color:e.color,strokeWidth:a,dashArray:ag(e.lineStyle,a),hasStickerStyle:e.hasStickerStyle,startX:n.startX,startY:n.startY,endX:n.endX,endY:n.endY,dashOffset:ig(a,c),arrowheadExtent:d}},lg=(e,t)=>Math.min(e,t*e/sg);function cg(e,t){const r=new Map;if(!t||t.kind!=="visual"||t.domain.length<=1)return r;for(const n of e){if(n.geom!=="rule"||n.stat.type!=="mean")continue;const a=n.transforms.find(m=>m.transformType==="filter"&&m.options.operator==="eq"),i=l.extractVariableName(n.mapping.y);let s,o,c;if(a?.transformType==="filter"&&typeof a.options.value=="string")s="color",o=a.options.variableName,c=a.options.value;else if(i!==null)s="y",o=i,c=i;else continue;const u=ug(e,s,o);if(u===null)continue;const d=t.map(c);l.isStrictCategoricalDataValue(d)&&r.set(n.id,{geom:u.geom,color:d})}return r}function ug(e,t,r){let n=null;for(const a of e)if(a.geom!=="rule"&&(n===null&&(n=a),l.extractVariableName(a.mapping[t])===r))return a;return n}var ds=(e,t)=>({x:e.x/t.width,y:1-e.y/t.height}),dg=0,mg=(e,t)=>e.filter(r=>r.inView).map(r=>({shape:{kind:"rect",rect:r.miniRect},cursor:ds(r.anchorPx,t),tooltip:{kind:"pinned",point:r.anchorPx,placement:r.placement,annotationId:r.id},priority:dg})),hg=9,pg=8,fg=2,ms=e=>typeof e=="string"?e:hs(e),hs=e=>e.text!==void 0?e.text:e.content?e.content.map(hs).join(""):"",ea={top:"bottom",bottom:"top",right:"left",left:"right"};function gg(e,t,r){return r.type==="polar"?bg(e,t):r.mainAxis==="y"?["right","left","top","bottom"]:["top","bottom","right","left"]}function fr(e,t,r){const{width:n,height:a}=r;switch(t){case"top":return{x:e.x-n/2,y:e.y-9-a,width:n,height:a};case"bottom":return{x:e.x-n/2,y:e.y+9,width:n,height:a};case"right":return{x:e.x+9,y:e.y-a/2,width:n,height:a};case"left":return{x:e.x-9-n,y:e.y-a/2,width:n,height:a}}}function ta(e,t){return e.x>=0&&e.y>=0&&e.x+e.width<=t.width&&e.y+e.height<=t.height}function yg(e,t){return{...t,x:Math.max(0,Math.min(t.x,e.width-t.width)),y:Math.max(0,Math.min(t.y,e.height-t.height))}}function vg(e,t,r=2){return e.x<t.x+t.width-r&&e.x+e.width>t.x+r&&e.y<t.y+t.height-r&&e.y+e.height>t.y+r}function bg(e,t){const r=e.x-t.width/2,n=e.y-t.height/2,a=r>=0?"right":"left",i=n>=0?"bottom":"top",[s,o]=Math.abs(r)>=Math.abs(n)?[a,i]:[i,a];return[s,ea[s],o,ea[o]]}function Sg(e){const{pinnedNumbers:t,comments:r,panelRect:n,coordSystem:a,measurer:i,formatPinnedNumber:s}=e,o=[...t.map(d=>{const{id:m,at:h}=d;return ra(m,"pinned-number",h,s(d),i,n,a)}),...r.map(({id:d,at:m,content:h})=>ra(d,"comment",m,ms(h),i,n,a))];o.sort((d,m)=>d.anchorPx.x-m.anchorPx.x||d.anchorPx.y-m.anchorPx.y);const c=[],u=[];for(const d of o){if(!d.inView){c.push(na(n,d,"top"));continue}const m=na(n,d,Ag(n,d,a,u));c.push(m),u.push(m.miniRect)}return c}function ra(e,t,r,n,a,i,s){const o=us(r,i,s);return{id:e,kind:t,anchor:r,anchorPx:o,mini:a(t,n),inView:xg(o,i)}}function xg(e,t){return e.x>=-8&&e.y>=-8&&e.x<=t.width+8&&e.y<=t.height+8}function Ag(e,t,r,n){const a=gg(t.anchorPx,e,r);for(const i of a){const s=fr(t.anchorPx,i,t.mini);if(ta(s,e)&&!n.some(o=>vg(s,o)))return i}for(const i of a)if(ta(fr(t.anchorPx,i,t.mini),e))return i;return"top"}function na(e,t,r){return{id:t.id,kind:t.kind,anchorPx:t.anchorPx,placement:r,miniRect:yg(e,fr(t.anchorPx,r,t.mini)),text:t.mini.text,inView:t.inView}}var Te=["top","right","bottom","left"],aa={top:"topLeft",right:"topRight",bottom:"bottomRight",left:"bottomLeft"},Ig={top:"topRight",right:"bottomRight",bottom:"bottomLeft",left:"topLeft"},Tg={topLeft:["left","top"],topRight:["top","right"],bottomRight:["right","bottom"],bottomLeft:["bottom","left"]},Lg=(e,t,r)=>{const n=Math.max(0,Math.min(r,t.width/2,t.height/2)),a=o=>{const[c,u]=Tg[o];return n>0&&e[c].isVisible&&e[u].isVisible},i=Eg(t,n),s=Vg(t,n,a);return Rg(e).map(o=>({lineStyle:e[o.firstEdge].lineStyle,lineWidth:e[o.firstEdge].lineWidth,color:e[o.firstEdge].color,segments:Cg(o,i,s,a)}))},wg=e=>{const t=r=>r.isVisible?r.lineWidth??1:0;return{top:t(e.top),right:t(e.right),bottom:t(e.bottom),left:t(e.left)}},Eg=(e,t)=>{const{x:r,y:n,width:a,height:i}=e;return{topLeft:{cx:r+t,cy:n+t,startAngle:Math.PI,endAngle:Math.PI*1.5,radius:t},topRight:{cx:r+a-t,cy:n+t,startAngle:Math.PI*1.5,endAngle:Math.PI*2,radius:t},bottomRight:{cx:r+a-t,cy:n+i-t,startAngle:0,endAngle:Math.PI*.5,radius:t},bottomLeft:{cx:r+t,cy:n+i-t,startAngle:Math.PI*.5,endAngle:Math.PI,radius:t}}},Vg=(e,t,r)=>{const{x:n,y:a,width:i,height:s}=e,o=c=>r(c)?t:0;return{top:{start:{x:n+o("topLeft"),y:a},end:{x:n+i-o("topRight"),y:a}},right:{start:{x:n+i,y:a+o("topRight")},end:{x:n+i,y:a+s-o("bottomRight")}},bottom:{start:{x:n+i-o("bottomRight"),y:a+s},end:{x:n+o("bottomLeft"),y:a+s}},left:{start:{x:n,y:a+s-o("bottomLeft")},end:{x:n,y:a+o("topLeft")}}}},Rg=e=>{const t=s=>e[s].isVisible,r=(s,o)=>{const c=(Te.indexOf(s)+o+Te.length)%Te.length;return Te[c]},n=s=>{const o=r(s,-1);return!t(o)||e[o].lineStyle!==e[s].lineStyle||e[o].lineWidth!==e[s].lineWidth||e[o].color!==e[s].color},a=Te.filter(t);if(a.length===0)return[];const i=a.filter(n);return i.length===0?[{firstEdge:"top",edges:[...Te],isClosed:!0}]:i.map(s=>{const o=[s];for(let c=r(s,1);t(c)&&!n(c);c=r(c,1))o.push(c);return{firstEdge:s,edges:o,isClosed:!1}})},Cg=(e,t,r,n)=>{const a=(m,h,p)=>({type:"arc",cx:m.cx,cy:m.cy,radius:m.radius,startAngle:h,endAngle:p}),i=m=>(m.startAngle+m.endAngle)/2,s=[],o=e.firstEdge,c=e.edges[e.edges.length-1],u=aa[o];if(!e.isClosed&&n(u)){const m=t[u],h=i(m),p=kg(m,h);s.push({type:"move",x:p.x,y:p.y}),s.push(a(m,h,m.endAngle))}else s.push({type:"move",x:r[o].start.x,y:r[o].start.y});s.push({type:"line",x:r[o].end.x,y:r[o].end.y});for(const m of e.edges.slice(1)){const h=aa[m];if(n(h)){const p=t[h];s.push(a(p,p.startAngle,p.endAngle))}s.push({type:"line",x:r[m].end.x,y:r[m].end.y})}const d=Ig[c];if(e.isClosed){if(n(d)){const m=t[d];s.push(a(m,m.startAngle,m.endAngle))}s.push({type:"close"})}else if(n(d)){const m=t[d];s.push(a(m,m.startAngle,i(m)))}return s},kg=(e,t)=>({x:e.cx+e.radius*Math.cos(t),y:e.cy+e.radius*Math.sin(t)}),Dg=6,Pg=2,Og=4,Mg=2,ia=11,_g=(e,t)=>{switch(e){case"dataLabel":case"categoryLabel":return{fontSize:ia*t,fontWeight:500,paddingX:6,paddingY:2};case"stackTotal":return{fontSize:ia*t,fontWeight:600,paddingX:4,paddingY:2}}},Ng=({labelPosition:e,measuredTextWidth:t,labelLineHeight:r,labelPaddingX:n,labelPaddingY:a})=>{const i=t+2*n,s=r+2*a;return{x:e.x-i/2,y:e.y-s/2,width:i,height:s}},Bg=100,Fg=({items:e,containerHeight:t,labelHeight:r})=>{const n=e.map(c=>{const u=(1-c.normalizedY)*t;return{anchorY:u,y:u,payload:c.payload}}).sort((c,u)=>c.y-u.y),a=r/2;let i=!1,s=!0,o=0;for(;s;){s=!1,o++;for(let c=0;c<n.length-1;c++){const u=n[c],d=n[c+1];if(!u||!d)continue;const m=u.y+a,h=d.y-a;if(m>h){s=!0,i=!0;const p=(m-h)/2+1;u.y-=p,d.y+=p,u.y<0&&(u.y=0),d.y>t&&(d.y=t)}}if(o>Bg)break}return{placements:n.filter(c=>c.y>=0&&c.y<=t).map(c=>({y:c.y,anchorY:c.anchorY,payload:c.payload})),hasOverlap:i}},$g=(e,t)=>{const r=Ca(e),n=Ug(t,Gg(e),r);if(n===null)return null;const a=Wg(e,n,r)?Hg(e,t,n,r):n,[i]=a;return i===void 0?null:a.length===1?i:{and:a}},Gg=e=>{const t=Ue(e.data,e.mapping),r=pe(e);return r===l.GROUP_VARIABLES.group?[...new Set(t)]:[...new Set([r,...t])]},Ug=(e,t,r)=>{const n=[];for(const a of t){const i=r(e,a);if(i===null)return null;n.push({variable:a,eq:i})}return n},Wg=(e,t,r)=>{let n=0;for(const a of e.data)if(t.every(i=>l.areDataValuesEqual(r(a,i.variable),i.eq))&&(n+=1,n>1))return!0;return!1},Hg=(e,t,r,n)=>{const a=l.extractVariableName(e.mapping.y);if(a===null||r.some(s=>s.variable===a))return r;const i=n(t,a);return i===null?r:[...r,{variable:a,eq:i}]},Xr=(e,t)=>{if(t.kind==="circle"){const n=e.x-t.center.x,a=e.y-t.center.y;return n*n+a*a<=t.radius*t.radius}const{rect:r}=t;return e.x>=r.x&&e.x<=r.x+r.width&&e.y>=r.y&&e.y<=r.y+r.height},Kg=(e,t)=>{for(const r of t)if(Xr(e,r.shape))return r;return null},zg=e=>{const t=[];for(const r of e.values())t.push(...r);return t.sort((r,n)=>n.priority-r.priority)},Yg=(e,t)=>e===t?!0:e.length!==t.length?!1:e.every((r,n)=>qg(r,t[n])),qg=(e,t)=>t===void 0?!1:e.priority===t.priority&&e.cursor.x===t.cursor.x&&e.cursor.y===t.cursor.y&&Xg(e.shape,t.shape)&&jg(e.tooltip,t.tooltip),Xg=(e,t)=>{if(e.kind!==t.kind)return!1;if(e.kind==="circle"){const n=t;return e.center.x===n.center.x&&e.center.y===n.center.y&&e.radius===n.radius}const{rect:r}=t;return e.rect.x===r.x&&e.rect.y===r.y&&e.rect.width===r.width&&e.rect.height===r.height},jg=(e,t)=>{if(e.kind!==t.kind)return!1;if(e.kind==="cursor")return!0;const r=t;return e.point.x===r.point.x&&e.point.y===r.point.y&&e.placement===r.placement&&e.annotationId===r.annotationId},Zg=100,Jg=e=>({shape:{kind:"circle",center:e.center,radius:e.radius},cursor:e.target.cursor,tooltip:{kind:"cursor"},priority:Zg}),Qg=(e,t)=>Xr(e,{kind:"circle",center:t.center,radius:t.radius}),ey=(e,t)=>e===t?!0:e===null||t===null?!1:e.center.x===t.center.x&&e.center.y===t.center.y&&e.radius===t.radius&&ty(e.target,t.target),ty=(e,t)=>e.kind===t.kind&&e.cursor.x===t.cursor.x&&e.cursor.y===t.cursor.y,ry=({layer:e,highlights:t,observation:r,parsingLocale:n})=>{if(e.highlight===null)return[];const a=It(e,n),i=ny(e,r);return t.filter(s=>{if(s.layerId!==void 0&&s.layerId!==e.id||ce(s.predicate,e.data).length>0)return!1;const o=le(s.predicate,a);return o(r)?!0:gd(s.scope)&&i(s.scope).some(o)})},ny=(e,t)=>{const r=l.extractVariableName(e.mapping.x),n=new Map;return a=>{const i=n.get(a);if(i!==void 0)return i;const s=mt(a,t,r),o=[];for(const c of e.data)mt(a,c,r)===s&&o.push(c);return n.set(a,o),o}},it=({layer:e,from:t,step:r,accepts:n,excluding:a,cycles:i=!1})=>{const s=e.data.size();for(let o=0;o<s;o+=1){const c=t+o*r,u=i?iy(c,s):c;if(u<0||u>=s)break;const d=e.data.getAt(u);if(d===null||!n(d))continue;const m=bt(e,d);if(m!==null&&!a.some(h=>fs(m,h)))return{anchor:m,observation:d}}return null},ps=(e,t,r)=>{let n=0;for(const a of e.data){if(ay(a,t,r))return n;n+=1}return-1},ay=(e,t,r)=>l.areDataValuesEqual(e[r]??null,t.anchorValue)?t.groupValue===void 0?!0:l.areDataValuesEqual(G(e),t.groupValue):!1,fs=(e,t)=>e.layerId===t.layerId&&l.areDataValuesEqual(e.anchorValue,t.anchorValue)&&l.areDataValuesEqual(e.groupValue??null,t.groupValue??null),iy=(e,t)=>(e%t+t)%t,sy=({layer:e,at:t,coordSystem:r})=>{if(r.type!=="cartesian")return null;const n=pe(e),a=ps(e,t,n),i=e.data.getAt(a);if(i===null)return null;const s=G(i),o=h=>l.areDataValuesEqual(G(h),s),c=[t],u=it({layer:e,excluding:c,from:a+1,step:1,accepts:o});if(u!==null)return{start:t,end:u.anchor};const d=it({layer:e,excluding:c,from:a-1,step:-1,accepts:o});if(d!==null)return{start:d.anchor,end:t};const m=it({layer:e,excluding:c,from:0,step:1,accepts:h=>!o(h)&&l.areDataValuesEqual(h[n]??null,t.anchorValue)});return m!==null?{start:t,end:m.anchor}:null},oy=({resolver:e,layer:t,observation:r,coordSystem:n,align:a,readSegmentY:i})=>{const s=e.resolve(t.geom,r,{coordSystem:n,position:t.position,purpose:"value",align:a});if(s===null)return null;const o=Oa(t,r,i??ke(t));if(o===null)return null;const c=bt(t,r);return c===null?null:{...s,...o,anchor:a===void 0?c:{...c,align:a}}},ly=({layer:e,from:t,partner:r,axis:n,step:a,canLandOn:i})=>{const s=pe(e),o=ps(e,t,s),c=e.data.getAt(o);if(c===null)return null;const u=cy(c),d=n==="main"?u:m=>!u(m)&&l.areDataValuesEqual(m[s]??null,t.anchorValue);return it({layer:e,excluding:[t,r],from:o+a,step:a,accepts:m=>d(m)&&i(m),cycles:n!=="main"})},cy=e=>{const t=G(e);return r=>l.areDataValuesEqual(G(r),t)};function uy({numberFormat:e,locale:t}){const r=new Map;return n=>{let a=r.get(n.valueFormat);return a??=R({valueFormat:n.valueFormat,locale:t,numberFormat:e}),r.set(n.valueFormat,a),a(n.measurementValue)}}var dy=({headline:e,show:t,numberFormat:r,parsingLocale:n,formattingLocale:a,t:i})=>{if(e===null)return null;const s=a??n;return e.kind==="grandTotal"?my(e,s,r):hy(e,t,s,r,i)},my=(e,t,r)=>({kind:"grandTotal",value:R({valueFormat:e.valueFormat,locale:t,numberFormat:r})(e.value)}),hy=(e,t,r,n,a)=>{const i=R({valueFormat:{type:"percentage"},locale:r,numberFormat:n}),s=e.items.length>1;return{kind:"perGroup",items:e.items.map(o=>{const c=R({valueFormat:o.valueFormat,locale:r,numberFormat:n}),u=R({valueFormat:o.groupLabelFormat,locale:r,numberFormat:n}),d=Ur({valueFormat:o.mainValueFormat,locale:r,numberFormat:n,tickValues:[]}),m=o.label??u(o.value);return{swatch:o.swatch,label:yy(t,s,m,a),value:o.aggregate===null?null:c(o.aggregate),observationLabel:gy(o.observationLabel,d),comparison:py(o.comparison,d,i,a)}})}},py=(e,t,r,n)=>e===null?null:{direction:fy(e.variation),percentage:r(Math.abs(e.variation)),reference:n("graph.headlineMetrics.comparisonReference",{value:t(e.against)})},fy=e=>e>0?"up":e<0?"down":"flat",gy=(e,t)=>e===null?null:e.kind==="point"?t(e.value):`${t(e.from)} – ${t(e.to)}`,yy=(e,t,r,n)=>{switch(e){case"total":return n("graph.headlineMetrics.total",{value:r});case"average":return t?n("graph.headlineMetrics.averageShort",{value:r}):n("graph.headlineMetrics.averageLong",{value:r});case"current":case"conversion":case"none":return r}},vy=({legends:e,numberFormat:t,parsingLocale:r,formattingLocale:n})=>{const a=n??r;return e.map(i=>by(i,a,t))},by=(e,t,r)=>({...e,items:e.items.map(n=>{const a=R({valueFormat:n.valueFormat,locale:t,numberFormat:r});return{...n,formattedLabel:n.label??a(n.value)}})});function jr(e,t){return e.axes.find(r=>r.scaleAestheticKey===t)??null}function Sy(e,t){return e.legends.find(r=>r.aesthetics.includes(t))??null}var xy=({guides:e,numberFormat:t,layer:r,locale:n})=>{const a=r.data.getFirst();if(!a)return null;const i=r.mapping.y!==void 0,s=(i?La:St)(r.data,r.mapping)(a);return s===null?null:R({valueFormat:jr(e,i?ge(r.yScaleType):"x")?.valueFormat??{type:"decimal"},locale:n,numberFormat:t})(s)},Ay=12,Iy=4,Ty=4,Ly=12,wy=4,Ey=e=>{const{value:t,observationLabel:r,comparison:n,swatch:a,label:i}=e;return[{role:"valueRow",gap:4,segments:Zt([nt("value","value",t??"–"),nt("observation","label",r)])},{role:"trendRow",gap:4,ariaLabel:n===null?void 0:ky(n),segments:Zt([Ry(n),Cy(n),nt("trendReference","label",n?.reference??null)])},{role:"groupRow",gap:4,segments:Zt([Vy(a),nt("label","label",i)])}].filter(s=>s.segments.length>0)},nt=(e,t,r)=>r===null?null:{kind:"text",textRole:e,fontRole:t,text:r},Vy=e=>e===null?null:{kind:"swatch",swatch:e,size:12},Ry=e=>e===null?null:{kind:"trendArrow",direction:e.direction,size:12},Cy=e=>e===null?null:{kind:"text",textRole:"trendPercentage",fontRole:"label",text:e.percentage,trendDirection:e.direction},ky=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}`}},Zt=e=>e.filter(t=>t!==null),Ct=e=>e==="catmull-rom"?de.curveCatmullRom:de.curveLinear,Dy=e=>{switch(e){case"dashed":return"8 4";case"dotted":return"2 2";case"solid":return}},Py=(e,t)=>{const r=Ct(t.interpolate),n=(0,de.area)().curve(r),a=(0,de.line)().curve(r);if(e.mainAxis==="y"){const i=c=>Q(w(c)??0),s=c=>K(c)??0,o=c=>z(c)??V(c)??0;n.y(i).x0(s).x1(o),a.y(i).x(o)}else{const i=c=>V(c)??0,s=c=>Q(N(c)??0),o=c=>Q(P(c)??w(c)??0);n.x(i).y0(s).y1(o),a.x(i).y(o)}if(t.missingValues==="gap"){const i=s=>V(s)!==null&&w(s)!==null;n.defined(i),a.defined(i)}return{lineGenerator:a,areaGenerator:n}},Oy=(e,t)=>t!=="connect"?e:e.filter(r=>V(r)!==null&&w(r)!==null),Zr={none:0,xs:2,sm:4,md:8,lg:12,xl:16},My="sm",gs=e=>{if(e.borderRadius==="full"){const{width:t,height:r}=e.bounds;return(e.mainAxis==="x"?t:r)/2}return Zr[e.borderRadius??"sm"]},_y=e=>{const t=gs(e);return e.borderRadius==="full"?e.mainAxis==="x"?{rx:t}:{ry:t}:{rx:t}},Ny=e=>({outlineWidth:e*2,separatorWidth:e,insetOffset:e/2}),ys=(e,t)=>{const r=K(t),n=z(t),a=N(t),i=P(t)??w(t);if(r===null||n===null||a===null||i===null)return null;if(e==="x"){let c=1-i,u=i-a;return u<0&&(c+=u,u=-u),{x:r,y:c,width:n-r,height:u}}let s=r,o=n-r;return o<0&&(s+=o,o=-o),{x:s,y:1-i,width:o,height:i-a}},vs=(e,t)=>e==="x"?`${H(t.x)}-${H(t.width)}`:`${H(t.y)}-${H(t.height)}`,By=e=>{let t=1/0,r=1/0,n=-1/0,a=-1/0;for(const i of e)i.x<t&&(t=i.x),i.y<r&&(r=i.y),i.x+i.width>n&&(n=i.x+i.width),i.y+i.height>a&&(a=i.y+i.height);return{x:t,y:r,width:n-t,height:a-r}},Fy=e=>{const t=(0,de.line)().x(r=>V(r)??0).y(r=>Q(w(r)??0)).curve(Ct(e.interpolate));return e.missingValues==="gap"&&t.defined(bs),t},$y=e=>{const t=(0,de.area)().x(r=>V(r)??0).y0(()=>1).y1(r=>Q(w(r)??0)).curve(Ct(e.interpolate));return e.missingValues==="gap"&&t.defined(bs),t},Gy=(e,t)=>t!=="connect"?e:e.filter(r=>V(r)!==null&&w(r)!==null),bs=e=>V(e)!==null&&w(e)!==null,Ss=(0,de.arc)().cornerRadius(e=>e.cornerRadius??0);Ss.digits(8);var Uy=200,Wy=e=>Ss(e)??void 0,Hy=(e,t)=>e==="full"?Math.max(0,t)/2:Zr[e??"sm"]/Uy,xs=(e,t)=>e==="x"?`${H(t.startAngle)}-${H(t.endAngle)}`:e==="y"?`${H(t.innerRadius)}-${H(t.outerRadius)}`:"sweep",Ky=e=>{let t=1/0,r=-1/0,n=1/0,a=-1/0;for(const i of e)t=Math.min(t,i.startAngle,i.endAngle),r=Math.max(r,i.startAngle,i.endAngle),n=Math.min(n,i.innerRadius,i.outerRadius),a=Math.max(a,i.innerRadius,i.outerRadius);return{startAngle:t,endAngle:r,innerRadius:n,outerRadius:a}},sa="#FFFFFF",Jt="#1A1A1A",zy=(e,t)=>e==="solid"?[]:e==="dotted"?[0,t*2]:[t*2,t*3],Yy=e=>{try{return(0,yn.getContrast)(e,sa)>(0,yn.getContrast)(e,Jt)?sa:Jt}catch{return Jt}},kt=(e,t,r)=>{const n=St(e,t);return a=>{const i=G(a)??"default",s=n(a);return`${r}-${i}${s!==null&&s!==""?`-${s}`:""}`}},qy=()=>(e,t)=>At(e)??`default-${t}`;function Jr(e,t,r){return Math.hypot(e*r,t)}function ft(e,t,r){return e<t?t-e:e>r?e-r:0}function ae(e,t,{shortCircuitOnZero:r=!1}={}){let n=e[0],a=t(n);if(r&&a===0)return n;for(let i=1;i<e.length;i+=1){const s=e[i];if(s===void 0)continue;const o=t(s);if(r&&o===0)return s;o<a&&(n=s,a=o)}return n}function Xy(e,t,r,n){if(e.points.length===0)return null;const a=e.delaunay;if(!a)return null;const i=a.find(t.x*r,t.y,n??void 0),s=e.points[i];return s?{hit:{anchored:!0,layerId:e.layerId,pointIndex:s.pointIndex,x:s.x,y:s.y,observation:s.observation},index:e,distance:Jr(s.x-t.x,s.y-t.y,r)}:null}function jy(e,t){if(e.points.length===0||!e.delaunay||e.delaunayAspectRatio===null)return null;const r=e.delaunay.find(t.x*e.delaunayAspectRatio,t.y);return e.points[r]??null}function As(e,t){return Qr(e.buckets,t,r=>r.main)}function Zy(e,t){return Qr(e.bands,t,r=>r.bandCenter)}function Is(e,t){return Qr(e.columns,t,r=>r.mainMid)}function Qr(e,t,r){if(e.length===0)return null;let n=0,a=e.length;for(;n<a;){const o=n+a>>>1,c=e[o];c&&r(c)<t?n=o+1:a=o}const i=e[n-1],s=e[n];return i?s&&Math.abs(r(s)-t)<Math.abs(r(i)-t)?s:i:s??null}function Jy(e,t){return{group:Qy(e),related:nv(e,t)}}function Qy(e){switch(e.kind){case"buckets":{const t=e.match.index;return O(t.position)?ev(t.layerId,e.match.bucket,e.match.hit.pointIndex):[]}case"banded":{const{index:t,column:r,hit:n}=e.match;return O(t.position)?tv(t.layerId,r,n.pointIndex):rv(t.bands,t.layerId,r,n.pointIndex)}case"points":case"enclosure":case"render-hit-test":return[]}}function ev(e,t,r){const n=[];for(const a of t.entries)a.pointIndex!==r&&n.push({anchored:!0,layerId:e,pointIndex:a.pointIndex,x:a.x,y:a.y,observation:a.observation});return n}function tv(e,t,r){const n=[];for(const a of t.rects)a.pointIndex!==r&&n.push(en(e,a));return n}function rv(e,t,r,n){const a=e.find(s=>s.columns.includes(r));if(!a)return[];const i=[];for(const s of a.columns)for(const o of s.rects)o.pointIndex!==n&&i.push(en(t,o));return i}function nv(e,t){const r=new Map;if(e.kind==="render-hit-test"||e.kind==="enclosure")return r;const n=e.match.index,a=n.projection==="polar";for(const i of t){if(i.layerId!==n.layerId){a||iv(r,i,e.match.hit);continue}e.kind==="buckets"&&(O(i.position)||i.kind==="buckets"&&av(r,i.layerId,e.match.bucket,e.match.hit.pointIndex))}return r}function av(e,t,r,n){for(const a of r.entries)a.pointIndex!==n&&st(e,t).push({anchored:!0,layerId:t,pointIndex:a.pointIndex,x:a.x,y:a.y,observation:a.observation})}function iv(e,t,r){switch(t.kind){case"buckets":{const n=As(t,we(t.mainAxis,r));if(!n)return;const a=st(e,t.layerId);for(const i of n.entries)a.push({anchored:!0,layerId:t.layerId,pointIndex:i.pointIndex,x:i.x,y:i.y,observation:i.observation});return}case"banded":{const n=Zy(t,we(t.mainAxis,r));if(!n)return;const a=st(e,t.layerId);for(const i of n.columns)for(const s of i.rects)a.push(en(t.layerId,s));return}case"points":{const n=jy(t,r);if(!n)return;st(e,t.layerId).push({anchored:!0,layerId:t.layerId,pointIndex:n.pointIndex,x:n.x,y:n.y,observation:n.observation});return}case"enclosure":return;case"noop":return;case"render-hit-test":return}}function st(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}function en(e,t){return{anchored:!0,layerId:e,pointIndex:t.pointIndex,x:(t.xMin+t.xMax)/2,y:(t.yMin+t.yMax)/2,observation:t.observation}}function Ts(e,t,r){const{columns:n,bands:a}=sv(e,t);return{kind:"banded",layerId:e.id,geom:e.geom,position:e.position,projection:r,mainAxis:t,columns:n,bands:a}}function sv(e,t){const r=ov(e,t);r.sort((o,c)=>o.mainMid-c.mainMid);const n=new Map,a=new Map;for(const o of r){const c=H(o.mainMid);let u=n.get(c);if(!u){u={mainMid:o.mainMid,rects:[]},n.set(c,u);const d=H(o.bandCenter);let m=a.get(d);m||(m={bandCenter:o.bandCenter,columns:[]},a.set(d,m)),m.columns.push(u)}u.rects.push(o.entry)}const i=[...n.values()].sort((o,c)=>o.mainMid-c.mainMid),s=[...a.values()].sort((o,c)=>o.bandCenter-c.bandCenter);for(const o of s)o.columns.sort((c,u)=>c.mainMid-u.mainMid);return{columns:i,bands:s}}function ov(e,t){const r=e.data;if(r.size()===0)return[];if(!(r.hasVariable(l.POSITION_VARIABLES.xMin)&&r.hasVariable(l.POSITION_VARIABLES.xMax)&&r.hasVariable(l.POSITION_VARIABLES.yMin)&&r.hasVariable(l.POSITION_VARIABLES.yMax)))return[];const n=r.getValues(l.POSITION_VARIABLES.xMin,{type:"numeric"}),a=r.getValues(l.POSITION_VARIABLES.xMax,{type:"numeric"}),i=r.getValues(l.POSITION_VARIABLES.yMin,{type:"numeric"}),s=r.getValues(l.POSITION_VARIABLES.yMax,{type:"numeric"}),o=t==="y",c=o?l.POSITION_VARIABLES.y:l.POSITION_VARIABLES.x,u=r.hasVariable(c)?r.getValues(c,{type:"numeric"}):null,d=[];let m=0;for(const h of r){const p=n[m],f=a[m],g=i[m],y=s[m];if(!l.isDefined(p)||!l.isDefined(f)||!l.isDefined(g)||!l.isDefined(y)){m++;continue}const v=o?(g+y)/2:(p+f)/2,x=u?.[m]??v;d.push({mainMid:v,bandCenter:x,entry:{pointIndex:m,xMin:Math.min(p,f),xMax:Math.max(p,f),yMin:Math.min(g,y),yMax:Math.max(g,y),observation:h}}),m++}return d}var lv=1e-9;function Ls(e,t,r){const n=cv(e,t);n.sort((i,s)=>i.main-s.main);const a=[];for(const i of n){const s=a[a.length-1];s&&Math.abs(s.main-i.main)<=lv?s.entries.push(i.entry):a.push({main:i.main,entries:[i.entry]})}return{kind:"buckets",layerId:e.id,geom:e.geom,position:e.position,projection:r,mainAxis:t,buckets:a}}function cv(e,t){const r=e.data;if(r.size()===0)return[];const n=r.hasVariable(l.POSITION_VARIABLES.x),a=r.hasVariable(l.POSITION_VARIABLES.y);if(!n||!a)return[];const i=r.getValues(l.POSITION_VARIABLES.x,{type:"numeric"}),s=r.getValues(l.POSITION_VARIABLES.y,{type:"numeric"}),o=t==="y",c=o?l.POSITION_VARIABLES.xMin:l.POSITION_VARIABLES.yMin,u=o?l.POSITION_VARIABLES.xMax:l.POSITION_VARIABLES.yMax,d=O(e.position),m=d?r.getValues(c,{type:"numeric"}):null,h=d?r.getValues(u,{type:"numeric"}):null,p=r.hasVariable(l.GROUP_VARIABLES.group)?r.getValues(l.GROUP_VARIABLES.group,{type:"categorical"}):null,f=[];let g=0;for(const y of r){const v=i[g],x=s[g];if(!l.isDefined(v)||!l.isDefined(x)){g+=1;continue}const T=p?.[g]??null,A=o?x:v;if(d){const _=m?.[g],Y=h?.[g];if(!l.isDefined(_)||!l.isDefined(Y)){g+=1;continue}const ee=o?Y:v,ie=o?x:Y;f.push({main:A,entry:{isStacked:d,pointIndex:g,x:ee,y:ie,stackMin:_,stackMax:Y,groupKey:T,observation:y}})}else f.push({main:A,entry:{isStacked:d,pointIndex:g,x:v,y:x,groupKey:T,observation:y}});g+=1}return f}function uv(e){return{kind:"enclosure",layerId:e.id,geom:e.geom,position:e.position,projection:"polar",cells:dv(e)}}function dv(e){const t=e.data;if(t.size()===0)return[];const r=[l.POSITION_VARIABLES.xMin,l.POSITION_VARIABLES.xMax,l.POSITION_VARIABLES.yMin,l.POSITION_VARIABLES.yMax];for(const u of r)if(!t.hasVariable(u))return[];const n=t.getValues(l.POSITION_VARIABLES.xMin,{type:"numeric"}),a=t.getValues(l.POSITION_VARIABLES.xMax,{type:"numeric"}),i=t.getValues(l.POSITION_VARIABLES.yMin,{type:"numeric"}),s=t.getValues(l.POSITION_VARIABLES.yMax,{type:"numeric"}),o=[];let c=0;for(const u of t){const d=n[c],m=a[c],h=i[c],p=s[c];if(!l.isDefined(d)||!l.isDefined(m)||!l.isDefined(h)||!l.isDefined(p)){c++;continue}o.push({pointIndex:c,xMin:d,xMax:m,yMin:h,yMax:p,observation:u}),c++}return o}function ws(e){return{kind:"noop",layerId:e.id,geom:e.geom,position:e.position,projection:"cartesian"}}function mv(e,t){const r={kind:"points",layerId:e.id,geom:e.geom,position:e.position,projection:"cartesian",points:Vs(e),delaunay:null,delaunayAspectRatio:null};return Es(r,t),r}function hv(e){const t=Vs(e).map(r=>{const n=dt(r.x,r.y);return{...r,unitX:n.x,unitY:n.y}});return{kind:"points",layerId:e.id,geom:e.geom,position:e.position,projection:"polar",points:t,delaunay:null,delaunayAspectRatio:null}}function Es(e,t){e.delaunay&&e.delaunayAspectRatio===t||(e.delaunay=Pl.Delaunay.from(e.points,r=>r.x*t,r=>r.y),e.delaunayAspectRatio=t)}function Vs(e){const t=e.data;if(t.size()===0)return[];if(!t.hasVariable(l.POSITION_VARIABLES.x)||!t.hasVariable(l.POSITION_VARIABLES.y))return[];const r=t.getValues(l.POSITION_VARIABLES.x,{type:"numeric"}),n=t.getValues(l.POSITION_VARIABLES.y,{type:"numeric"}),a=[];let i=0;for(const s of t){const o=r[i],c=n[i];i+=1,!(!l.isDefined(o)||!l.isDefined(c))&&a.push({pointIndex:a.length,x:o,y:c,observation:s})}return a}function Rs(e){return{kind:"render-hit-test",layerId:e.id,geom:e.geom,position:e.position,projection:"cartesian",byKey:pv(e)}}function Cs(e,t){return{anchored:!1,layerId:e,pointIndex:t.pointIndex,observation:t.observation}}function pv(e){const t=e.identityKey,r=new Map;if(typeof t=="object"){let n=0;for(const a of e.data){const i=a[t.variable];l.isDefined(i)&&r.set(l.getStableKey(i),{pointIndex:n,observation:a}),n+=1}return r}if(t==="index"){let n=0;for(const a of e.data)r.set(String(n),{pointIndex:n,observation:a}),n+=1}return r}function oa(e,t,r){return t.type==="polar"?fv(e,t.bandAxis):gv(e,t.mainAxis,r)}function fv(e,t){switch(e.spatialKind){case"points":return hv(e);case"buckets":return Ls(e,"x","polar");case"rects":return t===null?uv(e):Ts(e,t,"polar");case"noop":return ws(e);case"render-hit-test":return Rs(e);default:{const r=e.spatialKind;throw new l.InternalError({message:`buildPolarLayerIndex: unhandled spatialKind ${String(r)}`})}}}function gv(e,t,r){switch(e.spatialKind){case"points":return mv(e,r);case"buckets":return Ls(e,t,"cartesian");case"rects":return Ts(e,t,"cartesian");case"noop":return ws(e);case"render-hit-test":return Rs(e);default:{const n=e.spatialKind;throw new l.InternalError({message:`buildCartesianLayerIndex: unhandled spatialKind ${String(n)}`})}}}function yv(e,t,r){if(e.columns.length===0)return null;const n=Is(e,we(e.mainAxis,t)),a=n?.rects??[];if(!n||!l.isNonEmptyArray(a))return null;const i=O(e.position)?vv(a,t,e.mainAxis):bv(a,t,r);return{hit:{anchored:!0,layerId:e.layerId,pointIndex:i.pointIndex,x:(i.xMin+i.xMax)/2,y:(i.yMin+i.yMax)/2,observation:i.observation},index:e,column:n,distance:ks(i,t,r)}}function vv(e,t,r){const n=vt(r,t);return ae(e,i=>Sv(i,r,n),{shortCircuitOnZero:!0})}function bv(e,t,r){return ae(e,a=>ks(a,t,r))}function ks(e,t,r){return Jr(ft(t.x,e.xMin,e.xMax),ft(t.y,e.yMin,e.yMax),r)}function Sv(e,t,r){return ft(r,t==="x"?e.yMin:e.xMin,t==="x"?e.yMax:e.xMax)}function xv(e,t,r){if(e.buckets.length===0)return null;const{main:n,cross:a}=Bl(e.mainAxis,t),i=As(e,n),s=i?.entries??[];if(!i||!l.isNonEmptyArray(s))return null;const o=Ds(s,a,e.mainAxis);return{hit:{anchored:!0,layerId:e.layerId,pointIndex:o.pointIndex,x:o.x,y:o.y,observation:o.observation},index:e,bucket:i,distance:Jr(o.x-t.x,o.y-t.y,r)}}function Ds(e,t,r){return ae(e,a=>Math.abs(vt(r,a)-t))}function Av(e,t,r){if(e.columns.length===0)return null;const{angle:n,radius:a}=Lt(t,r),i=e.mainAxis==="x",s=i?Iv(e.columns,n):Is(e,a),o=s?.rects??[];if(!s||!l.isNonEmptyArray(o))return null;const c=i?Tv(o,a):Lv(o,n);return{hit:{anchored:!0,layerId:e.layerId,pointIndex:c.pointIndex,x:(c.xMin+c.xMax)/2,y:(c.yMin+c.yMax)/2,observation:c.observation},index:e,column:s,distance:0}}function Iv(e,t){return l.isNonEmptyArray(e)?ae(e,r=>ut(t,r.mainMid)):null}function Tv(e,t){return ae(e,r=>ft(t,r.yMin,r.yMax),{shortCircuitOnZero:!0})}function Lv(e,t){return ae(e,r=>Ua(t,r.xMin,r.xMax)?0:Math.min(ut(t,r.xMin),ut(t,r.xMax)),{shortCircuitOnZero:!0})}function wv(e,t,r){if(e.buckets.length===0)return null;const{angle:n,radius:a}=Lt(t,r),i=Ev(e.buckets,n),s=i?.entries??[];if(!i||!l.isNonEmptyArray(s))return null;const o=Ds(s,a,e.mainAxis);return{hit:{anchored:!0,layerId:e.layerId,pointIndex:o.pointIndex,x:o.x,y:o.y,observation:o.observation},index:e,bucket:i,distance:0}}function Ev(e,t){return l.isNonEmptyArray(e)?ae(e,r=>ut(r.main,t)):null}function Vv(e,t,r){if(e.cells.length===0)return null;const{angle:n,radius:a}=Lt(t,r);for(const i of e.cells)if(!(a<i.yMin||a>i.yMax)&&Ua(n,i.xMin,i.xMax))return{hit:{anchored:!0,layerId:e.layerId,pointIndex:i.pointIndex,x:(i.xMin+i.xMax)/2,y:(i.yMin+i.yMax)/2,observation:i.observation},index:e};return null}function Rv(e,t,r){if(!l.isNonEmptyArray(e.points))return null;const{x:n,y:a}=Ar(t,r),i=ae(e.points,s=>la(s,n,a));return{hit:{anchored:!0,layerId:e.layerId,pointIndex:i.pointIndex,x:i.x,y:i.y,observation:i.observation},index:e,distance:Math.sqrt(la(i,n,a))}}function la(e,t,r){const n=e.unitX??dt(e.x,e.y).x,a=e.unitY??dt(e.x,e.y).y,i=n-t,s=a-r;return i*i+s*s}var Cv=.05;function kv({layers:e,cursor:t,aspectRatio:r,warmStarts:n,hitTesters:a}){const i={match:null,distance:Number.POSITIVE_INFINITY},s={match:null,distance:Number.POSITIVE_INFINITY};for(const o of e){if(o.kind==="render-hit-test"){const u=Mv(o,t,a);if(u)return{kind:"render-hit-test",match:u};continue}if(o.projection==="polar"){const u=Ov(o,t,r);if(u)return u;continue}const c=Pv({layer:o,cursor:t,aspectRatio:r,warmStarts:n});if(c){if(c.kind==="banded"){c.match.distance<i.distance&&(i.match=c,i.distance=c.match.distance);continue}c.match.distance<s.distance&&(s.match=c,s.distance=c.match.distance)}}return Dv({rect:i,continuous:s})}function Dv({rect:e,continuous:t}){return e.match&&t.match?t.distance<=e.distance+Cv?t.match:e.match:e.match??t.match}function Pv({layer:e,cursor:t,aspectRatio:r,warmStarts:n}){switch(e.kind){case"buckets":{const a=xv(e,t,r);return a?{kind:"buckets",match:a}:null}case"banded":{const a=yv(e,t,r);return a?{kind:"banded",match:a}:null}case"points":{const a=Xy(e,t,r,n.get(e.layerId)??null);return a?{kind:"points",match:a}:null}case"noop":return null}}function Ov(e,t,r){switch(e.kind){case"enclosure":{const n=Vv(e,t,r);return n?{kind:"enclosure",match:n}:null}case"points":{const n=Rv(e,t,r);return n?{kind:"points",match:n}:null}case"buckets":{const n=wv(e,t,r);return n?{kind:"buckets",match:n}:null}case"banded":{const n=Av(e,t,r);return n?{kind:"banded",match:n}:null}case"noop":case"render-hit-test":return null}}function Mv(e,t,r){const n=r.get(e.layerId);if(!n)return null;const a=n({x:t.x,y:1-t.y});if(!a)return null;const i=e.byKey.get(a.key);return i?{hit:Cs(e.layerId,i)}:null}var X={primary:null,group:[],related:new Map},_v=1,Nv=class{constructor({layers:e,coordSystem:t}){this.layerIndexes=[],this.layerRefs=[],this.aspectRatio=_v,this.warmStarts=new Map,this.cachedState=X,this.cachedKey=null,this.nonInteractiveLayerIds=new Set,this.hitTesters=new Map,this.cachedByKeyId=null,this.cachedByKeyState=X,this.layerIndexes=e.map(r=>oa(r,t,this.aspectRatio)),this.layerRefs=e.map(r=>ca(r,t)),this.nonInteractiveLayerIds=ua(e)}update({layers:e,coordSystem:t}){const r=new Map;for(let i=0;i<this.layerIndexes.length;i+=1){const s=this.layerIndexes[i],o=this.layerRefs[i];!s||!o||r.set(s.layerId,{index:s,ref:o})}const n=[],a=[];for(const i of e){const s=r.get(i.id),o=ca(i,t);if(s!==void 0&&Bv(s.ref,o)){n.push(s.index),a.push(s.ref);continue}this.warmStarts.delete(i.id),n.push(oa(i,t,this.aspectRatio)),a.push(o)}for(const i of this.warmStarts.keys())e.some(s=>s.id===i)||this.warmStarts.delete(i);this.layerIndexes=n,this.layerRefs=a,this.nonInteractiveLayerIds=ua(e),this.invalidateCache()}setViewport(e){this.aspectRatio=e.width/e.height;for(const t of this.layerIndexes)t.kind==="points"&&t.projection==="cartesian"&&Es(t,this.aspectRatio)}query(e){if(this.layerIndexes.length===0)return X;const t=this.nonInteractiveLayerIds.size===0?this.layerIndexes:this.layerIndexes.filter(o=>!this.nonInteractiveLayerIds.has(o.layerId)),r=kv({layers:t,aspectRatio:this.aspectRatio,warmStarts:this.warmStarts,hitTesters:this.hitTesters,cursor:e});if(!r)return this.invalidateCache(),X;const n=r.match.hit;this.warmStarts.set(n.layerId,n.pointIndex);const a=`${n.layerId}:${n.pointIndex}`;if(this.cachedKey===a)return this.cachedState;const{group:i,related:s}=Jy(r,t);return this.cachedKey=a,this.cachedState={primary:n,group:i,related:s},this.cachedState}registerHitTester(e,t){this.hitTesters.set(e,t)}unregisterHitTester(e){this.hitTesters.delete(e)}resolveHoverByKey(e,t){if(this.nonInteractiveLayerIds.has(e))return X;const r=this.layerIndexes.find(i=>i.layerId===e);if(!r||r.kind!=="render-hit-test")return X;const n=r.byKey.get(t);if(!n)return X;const a=`${e}:${t}`;return this.cachedByKeyId===a?this.cachedByKeyState:(this.cachedByKeyId=a,this.cachedByKeyState={primary:Cs(e,n),group:[],related:new Map},this.cachedByKeyState)}invalidateCache(){this.cachedKey=null,this.cachedState=X,this.cachedByKeyId=null,this.cachedByKeyState=X}};function ca(e,t){return{data:e.data,geom:e.geom,position:e.position,coord:t}}function ua(e){const t=new Set;for(const r of e)r.interactive||t.add(r.id);return t}function Bv(e,t){return e.data===t.data&&e.geom===t.geom&&e.position===t.position&&e.coord===t.coord}var Fv=Math.PI*2;function $v(e,t){const r=we(e.mainAxis,t);if(e.mainAxis==="y"){const a=oe(Q(r));return{x1:0,x2:"100%",y1:a,y2:a}}const n=oe(r);return{x1:n,x2:n,y1:0,y2:"100%"}}function Gv(e,t,r){const n=e.mainAxis==="y"?w(r.observation):V(r.observation);if(n===null)return null;const a=e.mainAxis==="y"?Os(r):Ps(r),i=(t.x?.kind==="position"?t.x:null)?.bandwidth??a;if(i===null||i<=0)return null;const s=i/2;return e.mainAxis==="y"?{x:0,y:oe(Q(n+s)),width:"100%",height:oe(i)}:{x:oe(n-s),y:0,width:oe(i),height:"100%"}}function Uv(e,t){if(e.bandAxis===null)return null;if(e.bandAxis==="x"){const a=K(t.observation),i=z(t.observation);return a===null||i===null?null:{startAngle:a,endAngle:i,innerRadius:e.innerRadius,outerRadius:1}}const r=N(t.observation),n=P(t.observation);return r===null||n===null?null:{startAngle:e.startAngle,endAngle:e.startAngle+Fv,innerRadius:r,outerRadius:n}}function Ps(e){const t=K(e.observation),r=z(e.observation);return t===null||r===null?null:r-t}function Os(e){const t=N(e.observation),r=P(e.observation);return t===null||r===null?null:r-t}var Dt=.5,Wv=.4,Hv=10,Kv=({layer:e,coordSystem:t,scales:r,options:n})=>e.data.size()===0?null:e.spatialKind==="rects"?t.type==="cartesian"?Yv(e,t,r,n):qv(e,t,n):e.spatialKind==="buckets"&&t.type==="cartesian"?jv(e,t,n):e.spatialKind==="points"?Xv(e,n):null,zv=e=>{if(e.spatialKind==="buckets"){let t=0;return e.data.groupBy(l.GROUP_VARIABLES.group).forEach(()=>{t+=1}),t}return e.data.size()},Yv=(e,t,r,n)=>({type:"grow",layerId:e.id,durationSeconds:Dt*n.durationScale,baseline:Zv(e,t,r),growAxis:t.mainAxis==="x"?"y":"x",delayByKey:n.stagger?Jv(e,t.mainAxis,n):{}}),qv=(e,t,r)=>{const n=t.bandAxis==="x"?"radius":"angle";return{type:"grow",layerId:e.id,durationSeconds:Dt*r.durationScale,growAxis:n,baseline:n==="radius"?t.innerRadius:t.startAngle,delayByKey:n==="radius"&&r.stagger?tb(e,t,r):{}}},Xv=(e,t)=>({type:"grow",layerId:e.id,durationSeconds:Dt*t.durationScale,growAxis:"size",baseline:0,delayByKey:t.stagger?Qv(e,t):{}}),jv=(e,t,r)=>({type:"wipe",layerId:e.id,durationSeconds:Dt*r.durationScale,axis:t.mainAxis}),Zv=(e,t,r)=>{const n=t.mainAxis==="x"?1:0,a=r[ge(e.yScaleType)];if(!a||a.kind!=="position")return n;const i=a.map(0);if(!Number.isFinite(i))return n;const s=Math.min(1,Math.max(0,i));return t.mainAxis==="x"?1-s:s},Jv=(e,t,r)=>{const n=kt(e.data,e.mapping,e.id),a=new Map;for(const i of e.data){const s=ys(t,i);if(!s)continue;const o=vs(t,s),c=n(i),u=a.get(o);u?u.keys.push(c):a.set(o,{position:t==="x"?s.x:s.y,keys:[c]})}return tn([...a.values()],r)},Qv=(e,t)=>{const r=kt(e.data,e.mapping,e.id),n=[];for(const a of e.data){const i=eb(a,t.staggerOrder);i!==null&&n.push({position:i,keys:[r(a)]})}return tn(n,t)},eb=(e,t)=>{if(t==="main-axis")return V(e);const r=Sr(e)??V(e);return r===null?null:t==="value-descending"?-r:r},tb=(e,t,r)=>{const n=kt(e.data,e.mapping,e.id),a=new Map;for(const i of e.data){const{startAngle:s,endAngle:o}=zr(i),{innerRadius:c,outerRadius:u}=Yr(i);if(s===null||o===null||c===null||u===null)continue;const d=xs(t.bandAxis,{startAngle:s,endAngle:o,innerRadius:c,outerRadius:u}),m=n(i),h=a.get(d);h?h.keys.push(m):a.set(d,{position:s,keys:[m]})}return tn([...a.values()],r)},tn=(e,t)=>{const r={};if(e.length===0)return r;const n=[...e].sort((o,c)=>o.position-c.position),a=Math.ceil(n.length/Hv),i=Math.ceil(n.length/a),s=Wv*t.durationScale/i;return n.forEach((o,c)=>{const u=Math.floor(c/a)*s;for(const d of o.keys)r[d]=u}),r},rb=/^(?:https?:|mailto:)/i,nb=e=>{if(typeof e!="string")return!1;const t=e.replace(/^[\x00-\x20]+/,"");return t.length===0?!1:rb.test(t)},ab=({locale:e,intlOptions:t})=>D(r=>Intl.DateTimeFormat(e,{day:"numeric",month:"long",year:"numeric",weekday:"long",...M,...t}).format(r)),ib=({locale:e,intlOptions:t})=>D(r=>{const n=r.getUTCSeconds()!==0;return Intl.DateTimeFormat(e,{day:"2-digit",month:"short",year:"numeric",weekday:"short",hour:"2-digit",minute:"2-digit",second:n?"2-digit":void 0,...M,...t}).format(r)}),gt=e=>{const{valueFormat:t}=e;switch(t.type){case"currency":return Bi(e);case"date":return ab(e);case"datetime":return ib(e);case"day_month":return Ui(e);case"decimal":return Fi(e);case"duration":return Or(e);case"integer":return $i(e);case"month":return Wi(e);case"month_year":return Nr(e);case"percentage":return Gi(e);case"quarter":return Br(e);case"text":return Pr(e);case"time":return zi(e);case"weekly_date_range":return Hi(e);case"weekly_date_range_with_year":return Ki(e);case"year":return Fr(e);case"lookup":return gt({...e,valueFormat:t.fallback});default:throw new l.InternalError({message:`Unhandled value format: ${t.type}`})}},sb=({layers:e,coordSystem:t,scales:r,guides:n,numberFormat:a,parsingLocale:i,hover:s,colorScheme:o,formattingLocale:c,comments:u,activeCalloutId:d})=>{const{primary:m}=s;if(m===null)return null;const h=c??i,p=ob(u,d);return{header:p===null?lb({layers:e,coordSystem:t,guides:n,primary:m,locale:h,numberFormat:a}):null,rows:cb({layers:e,scales:r,guides:n,hover:s,locale:h,numberFormat:a,colorScheme:o}),comment:p}};function ob(e,t){return e===void 0||t===null||t===void 0?null:e.find(r=>r.id===t)?.content??null}function lb(e){if(e.coordSystem.type!=="cartesian")return null;const t=jr(e.guides,"x");if(!t)return null;const r=e.layers.find(i=>i.id===e.primary.layerId);if(!r)return null;const n=l.extractVariableName(r.mapping.x);if(!l.isDefined(n))return null;const a=e.primary.observation[n];return l.isDefined(a)?gt({valueFormat:t.valueFormat,locale:e.locale,numberFormat:e.numberFormat})(a):null}function cb(e){const t=[],r=e.scales.color??null,n=Kr({colorScheme:e.colorScheme}),a=hb({guides:e.guides,locale:e.locale,numberFormat:e.numberFormat});for(const i of e.layers){const s=db(i,e.hover);if(s.length===0)continue;const o=s[0];if(i.tooltip.length>0&&o){t.push(...ub(i,o,{locale:e.locale,numberFormat:e.numberFormat}));continue}const c=wa(i.data,i.mapping),u=mb(s,i,r,c),d=qr({layer:i,numberFormat:e.numberFormat,locale:e.locale}),m=pb(e.guides,i),h=ke(i),p=i.mapping.color!==void 0,f=n.geomReaders(i);for(const g of u){const y=p?c(g.observation):null,v=f.get("color",g.observation),x=f.get("lineType",g.observation)??"solid",T=p&&y!==null?a(y):m,A=h(g.observation),_=A===null?"":d(A,g.observation);t.push({swatchColor:v,geom:i.geom,swatchLineType:x,label:T,value:_,isPrimary:g===e.hover.primary,key:`${g.layerId}:${g.pointIndex}`})}}return t}function ub(e,t,r){return e.tooltip.map(n=>{const a=e.mapping[n.aes],i=U(e.data,a)(t.observation),s=R({valueFormat:Aa(e,l.extractVariableName(a)),locale:r.locale,numberFormat:r.numberFormat});return{swatchColor:null,geom:e.geom,swatchLineType:"solid",label:n.key,value:i===null?"":s(i,t.observation),isPrimary:!1,key:`${t.layerId}:${t.pointIndex}:${n.aes}`}})}function db(e,t){const r=[];return t.primary!==null&&t.primary.layerId===e.id&&r.push(t.primary,...t.group),r.push(...t.related.get(e.id)??[]),r}function mb(e,t,r,n){if(r===null||t.mapping.color===void 0)return e;const a=new Map;return r.domain.forEach((i,s)=>{a.set(l.getStableKey(i),s)}),e.map((i,s)=>{const o=n(i.observation),c=o===null?null:l.getStableKey(o);return{hit:i,originalIndex:s,rank:c===null?Number.POSITIVE_INFINITY:a.get(c)??Number.POSITIVE_INFINITY}}).sort((i,s)=>i.rank===s.rank?i.originalIndex-s.originalIndex:i.rank-s.rank).map(i=>i.hit)}function hb({guides:e,locale:t,numberFormat:r}){const n=new Map(e.colorGroups.map(i=>[l.getStableKey(i.value),{label:i.label,format:gt({valueFormat:i.valueFormat,locale:t,numberFormat:r})}])),a=gt({valueFormat:{type:"text"},locale:t,numberFormat:r});return i=>{const s=n.get(l.getStableKey(i));return s===void 0?a(i):s.label??s.format(i)}}function pb(e,t){return Tr(l.extractVariableName(t.mapping.y),e.variableLabels)??""}function fb(e,t,r=0){const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:r}function gb(e,t,r=""){const n=e[t];return typeof n=="string"?n:r}var Pt={differenceArrow:"differenceArrows",shape:"shapes",arrow:"arrows",text:"textAnnotations",image:"images",sticker:"stickers",pinnedNumber:"pinnedNumbers",comment:"comments"},yb={differenceArrow(e){return{type:"annotation",kind:"differenceArrow",annotation:e}},shape(e){return{type:"annotation",kind:"shape",annotation:e}},arrow(e){return{type:"annotation",kind:"arrow",annotation:e}},text(e){return{type:"annotation",kind:"text",annotation:e}},image(e){return{type:"annotation",kind:"image",annotation:e}},sticker(e){return{type:"annotation",kind:"sticker",annotation:e}},pinnedNumber(e){return{type:"annotation",kind:"pinnedNumber",annotation:e}},comment(e){return{type:"annotation",kind:"comment",annotation:e}}},vb=Object.keys(Pt),bb=e=>Object.hasOwn(Pt,e),Ot=(e,t)=>{for(const r of vb){const n=Sb(e,r,t);if(n)return n}return null},Ye=(e,t)=>e[Pt[t]],rn=(e,t,r)=>({...e,[Pt[t]]:r}),Ms=(e,t)=>{const r=Ye(e,t.kind);return rn(e,t.kind,[...r.slice(0,t.index),...r.slice(t.index+1)])},Sb=(e,t,r)=>{const n=Ye(e,t),a=n.findIndex(s=>s.id===r),i=n[a];return i===void 0?null:{kind:t,index:a,annotation:i}},nn=["sticker","pinnedNumber","comment","image"],xb=e=>nn.includes(e),an=e=>{switch(e.kind){case"pinnedNumber":case"comment":return e.annotation.at;case"sticker":return e.annotation.at.anchorType==="observation"?Ib(e.annotation.at):null;default:return null}},_s=(e,t)=>e.layerId===t.layerId&&l.areDataValuesEqual(e.anchorValue,t.anchorValue)&&l.areDataValuesEqual(e.groupValue??null,t.groupValue??null),Ns=(e,t,r=Ab)=>{const n=r(t);for(const a of nn){const i=Ye(e,a),s=i.findIndex(c=>{const u=an({kind:a,annotation:c});if(u===null)return!1;const d=r(u);return _s(d,n)}),o=i[s];if(o!==void 0)return{kind:a,index:s,annotation:o}}return null},Ab=e=>({...e,anchorValue:da(e.anchorValue),...e.groupValue!==void 0&&{groupValue:da(e.groupValue)}}),da=e=>l.readISOInstant(e)??e,Ib=e=>({layerId:e.layerId,anchorValue:e.anchorValue,groupValue:e.groupValue,align:e.align}),Tb={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 Lb(e,t={}){return{type:"highlight",id:t.id,predicate:e,scope:t.scope,layerId:t.layerId}}var wb=(e,t)=>e.find(r=>r.scope===t.scope&&r.layerId===t.layerId&&sn(r.predicate,t.predicate))??null,sn=(e,t)=>"and"in e?"and"in t&&ma(e.and,t.and):"or"in e?"or"in t&&ma(e.or,t.or):"not"in e?"not"in t&&sn(e.not,t.not):Eb(t)&&e.variable===t.variable&&Vb(e,t),Eb=e=>"variable"in e,ma=(e,t)=>e.length===t.length&&e.every((r,n)=>{const a=t[n];return a!==void 0&&sn(r,a)}),Vb=(e,t)=>"eq"in e?"eq"in t&&l.areDataValuesEqual(e.eq,t.eq):"oneOf"in e?"oneOf"in t&&ha(e.oneOf,t.oneOf):"lt"in e?"lt"in t&&l.areDataValuesEqual(e.lt,t.lt):"lte"in e?"lte"in t&&l.areDataValuesEqual(e.lte,t.lte):"gt"in e?"gt"in t&&l.areDataValuesEqual(e.gt,t.gt):"gte"in e?"gte"in t&&l.areDataValuesEqual(e.gte,t.gte):"range"in t&&ha(e.range,t.range),ha=(e,t)=>e.length===t.length&&e.every((r,n)=>l.areDataValuesEqual(r,t[n]??null));function Bs(e){return{mapping:e.mapping,layers:e.layers,scales:e.scales.map(Rb),transforms:e.transforms,highlights:e.highlights,annotations:e.annotations,coords:e.coords,config:e.config}}function Rb(e){return e.scaleType==="palette"?Cb(e):e}function Cb(e){return{...e,palette:kb(e.palette),overrides:Db(e.overrides)}}function kb(e){return e.type==="custom"?{type:"custom",id:e.id}:e}function Db(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))t[Number(r)]={hex:n};return t}function S(e){return{id:e.id??C(),timestamp:e.timestamp??Date.now(),description:e.description,author:e.author??"unknown"}}function te(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,n)=>te(r,t[n]));if(l.isPlainObject(e)&&l.isPlainObject(t)){const r=Object.keys(e).filter(a=>e[a]!==void 0),n=Object.keys(t).filter(a=>t[a]!==void 0);return r.length===n.length&&r.every(a=>te(e[a],t[a]))}return!1}var on=class{constructor(e,t={}){this.type="remove-annotation",this.params=e,this.metadata=S({...t,description:"Remove annotation"})}get target(){return{kind:"annotation",id:this.params.id}}apply(e){const t=Ot(e.annotations,this.params.id);if(!t)return null;const{kind:r,index:n,annotation:a}=t;return{spec:I(e,{annotations:Ms(e.annotations,t)}),revert:new ln({kind:r,annotation:a,index:n},this.metadata)}}},Pb={type:"remove-annotation",deserialize:(e,t)=>new on(e,t)},ln=class Fs{constructor(t,r={}){this.type="add-annotation",this.params={kind:t.kind,annotation:{...t.annotation,id:t.annotation.id??C()},...t.index!==void 0&&{index:t.index}},this.metadata=S({...r,description:"Add annotation"})}get target(){return{kind:"annotation",id:this.params.annotation.id}}apply(t){const{kind:r,annotation:n,index:a}=this.params;if(!bb(r)||Ot(t.annotations,n.id))return null;const i=Mb(t.annotations,{kind:r,annotation:n}),s=i===null?t.annotations:Ms(t.annotations,i),o=Ye(s,r),c=a??o.length,u=Math.min(Math.max(c,0),o.length);return{spec:I(t,{annotations:rn(s,r,[...o.slice(0,u),n,...o.slice(u)])}),revert:i===null?new on({id:n.id},this.metadata):new Fs({kind:i.kind,annotation:i.annotation,index:i.index},this.metadata)}}},Ob={type:"add-annotation",deserialize:(e,t)=>new ln({kind:e.kind,annotation:e.annotation,index:e.index},t)},Mb=(e,t)=>{const r=an(t);return r===null?null:Ns(e,r)},$s=class Gs{constructor(t,r={}){this.type="update-annotation",this.params=t,this.metadata=S({...r,description:"Update annotation"})}get target(){return{kind:"annotation",id:this.params.id}}apply(t){const{kind:r,id:n,patch:a}=this.params,i=Ot(t.annotations,n);if(!i||i.kind!==r)return null;const s=Ye(t.annotations,r),o=s[i.index];if(o===void 0)return null;const c=o;if(!Fb(c,a))return null;const u=Nb(o,a),d=[...s.slice(0,i.index),u,...s.slice(i.index+1)];return{spec:I(t,{annotations:rn(t.annotations,r,d)}),revert:new Gs({kind:r,id:n,patch:Bb(c,a)},this.metadata)}}},_b={type:"update-annotation",deserialize:(e,t)=>new $s(e,t)},Nb=(e,t)=>{const r=new Set(Object.entries(t).filter(([,n])=>n===void 0).map(([n])=>n));return Object.fromEntries(Object.entries({...e,...t}).filter(([n])=>!r.has(n)))},Bb=(e,t)=>{const r={};for(const n of Object.keys(t))r[n]=e[n];return r},Fb=(e,t)=>Object.entries(t).some(([r,n])=>!Object.is(e[r],n)),Us=class Ws{constructor(t,r={}){this.type="set-appearance-background",this.target={kind:"appearance"},this.params=t,this.metadata=S({...r,description:`Set chart background to ${t.background.type}`})}apply(t){const r=t.config.appearance.background;if(te(r,this.params.background))return null;const n=I(t.config.appearance,{background:this.params.background});return{spec:I(t,{config:I(t.config,{appearance:n})}),revert:new Ws({background:r},this.metadata)}}},$b={type:"set-appearance-background",deserialize:(e,t)=>new Us(e,t)},Hs=class Ks{constructor(t,r={}){this.type="set-appearance-border",this.target={kind:"appearance"},this.params=t,this.metadata=S({...r,description:`Set chart border to ${t.border.type}`})}apply(t){const r=t.config.appearance.border;if(te(r,this.params.border))return null;const n=I(t.config.appearance,{border:this.params.border});return{spec:I(t,{config:I(t.config,{appearance:n})}),revert:new Ks({border:r},this.metadata)}}},Gb={type:"set-appearance-border",deserialize:(e,t)=>new Hs(e,t)},zs=class Ys{constructor(t,r={}){this.type="set-appearance-corner-radius",this.target={kind:"appearance"},this.params=t,this.metadata=S({...r,description:`Set chart corner radius to ${t.cornerRadius}`})}apply(t){const r=t.config.appearance.cornerRadius;return r===this.params.cornerRadius?null:{spec:E(t,{config:{appearance:{cornerRadius:this.params.cornerRadius}}}),revert:new Ys({cornerRadius:r},this.metadata)}}},Ub={type:"set-appearance-corner-radius",deserialize:(e,t)=>new zs(e,t)},qs=class Xs{constructor(t,r={}){this.type="set-appearance-text-scale",this.target={kind:"appearance"},this.params=t,this.metadata=S({...r,description:`Set text scale to ${t.textScale}`})}apply(t){const r=t.config.appearance.textScale;return r===this.params.textScale?null:{spec:E(t,{config:{appearance:{textScale:this.params.textScale}}}),revert:new Xs({textScale:r},this.metadata)}}},Wb={type:"set-appearance-text-scale",deserialize:(e,t)=>new qs(e,t)};function Hb(e,t){return e.config.axes[t]??{}}function Kb(e,t,r){if(t!=="ySecondary")return E(e,{config:{axes:{[t]:r}}});const n=e.config.axes.ySecondary,a=js(n,r);if(a===n)return e;const i={...e.config.axes,ySecondary:a};return a===void 0&&delete i.ySecondary,I(e,{config:I(e.config,{axes:i})})}function js(e,t){const r={};let n=!1;for(const a of new Set([...Object.keys(e??{}),...Object.keys(t)])){const i=e?.[a],s=a in t?zb(i,t[a]):i;s!==i&&(n=!0),s!==void 0&&(r[a]=s)}return n?Object.keys(r).length>0?r:void 0:e}function zb(e,t){return l.isPlainObject(t)?js(l.isPlainObject(e)?e:void 0,t):t}var Zs=class Js{constructor(t,r={}){this.type="set-axis-label",this.params=t,this.metadata=S({...r,description:`Set ${t.axis} axis label to ${qb(t.label)}`})}get target(){return{kind:"axis",axis:this.params.axis}}apply(t){const{axis:r,label:n}=this.params,a=Hb(t,r).label;if(a===n)return null;const i=Kb(t,r,{label:n});return i===t?null:{spec:i,revert:new Js(r==="ySecondary"?{axis:r,label:a}:{axis:r,label:a??null},this.metadata)}}},Yb={type:"set-axis-label",deserialize:(e,t)=>new Zs(e,t)};function qb(e){return e===void 0?"(inherited)":e??"(none)"}var Qs=class eo{constructor(t,r={}){this.type="set-axis-position",this.params=t,this.metadata=S({...r,description:`Set ${t.axis} axis position to ${t.position}`})}get target(){return{kind:"axis",axis:this.params.axis}}apply(t){const{axis:r,position:n}=this.params,a=t.config.axes[r].position;return a===n?null:{spec:E(t,{config:{axes:{[r]:{position:n}}}}),revert:new eo({axis:r,position:a},this.metadata)}}},Xb={type:"set-axis-position",deserialize:(e,t)=>new Qs(e,t)},to=class ro{constructor(t,r={}){this.type="set-axis-tick-mode",this.params=t,this.metadata=S({...r,description:`Set ${t.axis} axis tick mode to ${t.tickMode}`})}get target(){return{kind:"axis",axis:this.params.axis}}apply(t){const{axis:r,tickMode:n}=this.params,a=t.config.axes[r].ticks.mode;return a===n?null:{spec:E(t,{config:{axes:{[r]:{ticks:{mode:n}}}}}),revert:new ro({axis:r,tickMode:a},this.metadata)}}},jb={type:"set-axis-tick-mode",deserialize:(e,t)=>new to(e,t)},no=class ao{constructor(t,r={}){this.type="set-axis-ticks-visibility",this.params=t,this.metadata=S({...r,description:`Set ${t.axis} axis ticks visibility to ${t.isVisible}`})}get target(){return{kind:"axis",axis:this.params.axis}}apply(t){const{axis:r,isVisible:n}=this.params,a=t.config.axes[r].ticks.isVisible;return a===n?null:{spec:E(t,{config:{axes:{[r]:{ticks:{isVisible:n}}}}}),revert:new ao({axis:r,isVisible:a},this.metadata)}}},Zb={type:"set-axis-ticks-visibility",deserialize:(e,t)=>new no(e,t)},io=class so{constructor(t,r={}){this.type="set-axis-visibility",this.params=t,this.metadata=S({...r,description:`Set ${t.axis} axis visibility to ${t.isVisible}`})}get target(){return{kind:"axis",axis:this.params.axis}}apply(t){const{axis:r,isVisible:n}=this.params,a=t.config.axes[r].isVisible;return a===n?null:{spec:E(t,{config:{axes:{[r]:{isVisible:n}}}}),revert:new so({axis:r,isVisible:a},this.metadata)}}},Jb={type:"set-axis-visibility",deserialize:(e,t)=>new io(e,t)},oo=class lo{constructor(t,r={}){this.type="set-content-caption",this.target={kind:"content",part:"caption"},this.params=t,this.metadata=S({...r,description:"Set chart caption"})}apply(t){const r=t.config.content.caption;return r===this.params.caption?null:{spec:E(t,{config:{content:{caption:this.params.caption}}}),revert:new lo({caption:r},this.metadata)}}},Qb={type:"set-content-caption",deserialize:(e,t)=>new oo(e,t)},co=class uo{constructor(t,r={}){this.type="set-content-source",this.target={kind:"content",part:"source"},this.params=t,this.metadata=S({...r,description:`Set content source to ${t.source?.label??t.source?.url??"(none)"}`})}apply(t){const r=t.config.content.source;if(te(r,this.params.source))return null;const n=I(t.config.content,{source:this.params.source});return{spec:I(t,{config:I(t.config,{content:n})}),revert:new uo({source:r},this.metadata)}}},eS={type:"set-content-source",deserialize:(e,t)=>new co(e,t)},mo=class ho{constructor(t,r={}){this.type="set-content-subtitle",this.target={kind:"content",part:"subtitle"},this.params=t,this.metadata=S({...r,description:"Set chart subtitle"})}apply(t){const r=t.config.content.subtitle;return r===this.params.subtitle?null:{spec:E(t,{config:{content:{subtitle:this.params.subtitle}}}),revert:new ho({subtitle:r},this.metadata)}}},tS={type:"set-content-subtitle",deserialize:(e,t)=>new mo(e,t)},po=class fo{constructor(t,r={}){this.type="set-content-title",this.target={kind:"content",part:"title"},this.params=t,this.metadata=S({...r,description:"Set chart title"})}apply(t){const r=t.config.content.title;return r===this.params.title?null:{spec:E(t,{config:{content:{title:this.params.title}}}),revert:new fo({title:r},this.metadata)}}},rS={type:"set-content-title",deserialize:(e,t)=>new po(e,t)},go=class yo{constructor(t,r={}){this.type="set-grid-visibility",this.params=t,this.metadata=S({...r,description:`Set ${t.axis} axis grid visibility to ${t.isVisible??"(auto)"}`})}get target(){return{kind:"grid",axis:this.params.axis}}apply(t){const{axis:r,isVisible:n}=this.params,a=t.config.axes[r].grid.isVisible;return a===n?null:{spec:E(t,{config:{axes:{[r]:{grid:{isVisible:n}}}}}),revert:new yo({axis:r,isVisible:a},this.metadata)}}},nS={type:"set-grid-visibility",deserialize:(e,t)=>new go(e,t)},vo=class bo{constructor(t,r={}){this.type="set-headline-compare-with",this.target={kind:"headline"},this.params=t,this.metadata=S({...r,description:`Set headline compare with to ${t.compareWith}`})}apply(t){const r=t.config.headline.compareWith;return r===this.params.compareWith?null:{spec:E(t,{config:{headline:{compareWith:this.params.compareWith}}}),revert:new bo({compareWith:r},this.metadata)}}},aS={type:"set-headline-compare-with",deserialize:(e,t)=>new vo(e,t)},So=class xo{constructor(t,r={}){this.type="set-headline-position",this.target={kind:"headline"},this.params=t,this.metadata=S({...r,description:`Set headline position to ${t.position}`})}apply(t){const r=t.config.headline.position;return r===this.params.position?null:{spec:E(t,{config:{headline:{position:this.params.position}}}),revert:new xo({position:r},this.metadata)}}},iS={type:"set-headline-position",deserialize:(e,t)=>new So(e,t)},Ao=class Io{constructor(t,r={}){this.type="set-headline-show",this.target={kind:"headline"},this.params=t,this.metadata=S({...r,description:`Set headline show to ${t.show}`})}apply(t){const r=t.config.headline.show;return r===this.params.show?null:{spec:E(t,{config:{headline:{show:this.params.show}}}),revert:new Io({show:r},this.metadata)}}},sS={type:"set-headline-show",deserialize:(e,t)=>new Ao(e,t)},To=class Lo{constructor(t,r={}){this.type="set-headline-size",this.target={kind:"headline"},this.params=t,this.metadata=S({...r,description:`Set headline size to ${t.size}`})}apply(t){const r=t.config.headline.size;return r===this.params.size?null:{spec:E(t,{config:{headline:{size:this.params.size}}}),revert:new Lo({size:r},this.metadata)}}},oS={type:"set-headline-size",deserialize:(e,t)=>new To(e,t)},wo=class Eo{constructor(t,r={}){this.type="set-legend-position",this.target={kind:"legend"},this.params=t,this.metadata=S({...r,description:`Set legend position to ${t.position}`})}apply(t){const r=t.config.legend.position;return r===this.params.position?null:{spec:E(t,{config:{legend:{position:this.params.position}}}),revert:new Eo({position:r},this.metadata)}}},lS={type:"set-legend-position",deserialize:(e,t)=>new wo(e,t)},Vo=class Ro{constructor(t,r={}){this.type="set-number-format-abbreviation",this.target={kind:"numberFormat"},this.params=t,this.metadata=S({...r,description:`Set number format abbreviation to ${t.abbreviation}`})}apply(t){const r=t.config.numberFormat.abbreviation;return r===this.params.abbreviation?null:{spec:E(t,{config:{numberFormat:{abbreviation:this.params.abbreviation}}}),revert:new Ro({abbreviation:r},this.metadata)}}},cS={type:"set-number-format-abbreviation",deserialize:(e,t)=>new Vo(e,t)},Co=class ko{constructor(t,r={}){this.type="set-number-format-decimals",this.target={kind:"numberFormat"},this.params=t,this.metadata=S({...r,description:`Set number format decimals to ${t.decimals}`})}apply(t){const r=t.config.numberFormat.decimals;return r===this.params.decimals?null:{spec:E(t,{config:{numberFormat:{decimals:this.params.decimals}}}),revert:new ko({decimals:r},this.metadata)}}},uS={type:"set-number-format-decimals",deserialize:(e,t)=>new Co(e,t)},Do=class Po{constructor(t,r={}){this.type="toggle-content-visibility",this.params=t,this.metadata=S({...r,description:`Set ${t.slot} visibility to ${t.isVisible}`})}get target(){return{kind:"content",part:this.params.slot}}apply(t){const{slot:r,isVisible:n}=this.params,a=mS(r);if(!a)return null;const i=t.config.content[a];return i===n?null:{spec:E(t,{config:{content:{[a]:n}}}),revert:new Po({slot:r,isVisible:i},this.metadata)}}},dS={type:"toggle-content-visibility",deserialize:(e,t)=>new Do(e,t)},pa={title:"isTitleVisible",subtitle:"isSubtitleVisible",caption:"isCaptionVisible",source:"isSourceVisible"};function mS(e){return Object.hasOwn(pa,e)?pa[e]:void 0}var Oo=class Mo{constructor(t,r={}){this.type="set-coord-limits",this.target={kind:"coords"},this.params=t,this.metadata=S({...r,description:"Set coordinate limits"})}apply(t){const{xLimits:r,yLimits:n}=this.params,a=t.coords.params,i={xLimits:r!==void 0?r:a.xLimits,yLimits:n!==void 0?n:a.yLimits};if(te(i.xLimits,a.xLimits)&&te(i.yLimits,a.yLimits))return null;const s={};r!==void 0&&(s.xLimits=a.xLimits),n!==void 0&&(s.yLimits=a.yLimits);const o=new Mo(s,this.metadata);return{spec:I(t,{coords:pS(t.coords,i)}),revert:o}}},hS={type:"set-coord-limits",deserialize:(e,t)=>new Oo(e,t)};function pS(e,t){switch(e.coordType){case"cartesian":return{...e,params:{...e.params,...t}};case"flip":return{...e,params:{...e.params,...t}};case"polar":return{...e,params:{...e.params,...t}}}}var _o=class No{constructor(t,r={}){this.type="set-polar-inner-radius",this.target={kind:"coords"},this.params={innerRadius:gS(t.innerRadius)},this.metadata=S({...r,description:`Set polar inner radius to ${this.params.innerRadius}`})}apply(t){const r=t.coords;if(r.coordType!=="polar")return null;const n=r.params.innerRadius;return n===this.params.innerRadius?null:{spec:I(t,{coords:{...r,params:{...r.params,innerRadius:this.params.innerRadius}}}),revert:new No({innerRadius:n},this.metadata)}}},fS={type:"set-polar-inner-radius",deserialize:(e,t)=>new _o(e,t)},gS=e=>Math.min(Math.max(e,0),1),yS={type:"set-polar-start-angle",deserialize:(e,t)=>new Bo(e,t)},Bo=class Fo{constructor(t,r={}){this.type="set-polar-start-angle",this.target={kind:"coords"},this.params={startAngle:fa(t.startAngle)},this.metadata=S({...r,description:`Set polar start angle to ${this.params.startAngle}`})}apply(t){const r=t.coords;if(r.coordType!=="polar")return null;const n=r.params.startAngle;return fa(n)===this.params.startAngle?null:{spec:I(t,{coords:{...r,params:{...r.params,startAngle:this.params.startAngle}}}),revert:new Fo({startAngle:n},this.metadata)}}},Qt=360,fa=e=>(e%Qt+Qt)%Qt,cn=class{constructor(e,t={}){this.type="remove-highlight",this.params=e,this.metadata=S({...t,description:"Remove highlight"})}get target(){return{kind:"highlight",id:this.params.id}}apply(e){const t=e.highlights.find(i=>i.id===this.params.id);if(!t)return null;const r=e.highlights.indexOf(t),n=e.highlights.filter(i=>i!==t),a=new un({predicate:t.predicate,id:t.id,scope:t.scope,layerId:t.layerId,index:r},this.metadata);return{spec:I(e,{highlights:n}),revert:a}}},vS={type:"remove-highlight",deserialize:(e,t)=>new cn(e,t)},un=class{constructor(e,t={}){this.type="add-highlight",this.params={...e,id:e.id??C(),scope:e.scope??"data-point"},this.metadata=S({...t,description:"Add highlight"})}get target(){return{kind:"highlight",id:this.params.id}}apply(e){const{predicate:t,id:r,scope:n,layerId:a,index:i}=this.params;if(e.highlights.some(d=>d.id===r))return null;const s=new cn({id:r},this.metadata),o={type:"highlight",id:r,predicate:t,scope:n,...a!==void 0&&{layerId:a}},c=i??e.highlights.length,u=Math.min(Math.max(c,0),e.highlights.length);return{spec:I(e,{highlights:[...e.highlights.slice(0,u),o,...e.highlights.slice(u)]}),revert:s}}},bS={type:"add-highlight",deserialize:(e,t)=>new un(e,t)};function Pe(e,...t){return e?t.includes(e.geom):!1}function $(e,t){return e.find(r=>r.id===t)}function Oe(e,...t){return e.find(r=>t.some(n=>n===r.geom))}function $o(e,t){return{...e,params:{...e.params,...t}}}function Mt(e,t){return{...e,dataLabels:{...e.dataLabels,...t}}}function SS(e,t){return I(e,{layers:[...e.layers,t]})}function W(e,t,r){const n=e.layers.findIndex(a=>a.id===t);return n===-1?e:I(e,{layers:Ba(e.layers,n,r)})}function Go(e,t){const r=e.layers.findIndex(n=>n.id===t);return r===-1||e.layers.length<=1?e:I(e,{layers:e.layers.filter((n,a)=>a!==r)})}var dn=class{constructor(e,t={}){this.type="remove-layer",this.params=e,this.metadata=S({...t,description:"Remove layer"})}get target(){return{kind:"layer",layerId:this.params.layerId}}apply(e){const t=e.layers.findIndex(a=>a.id===this.params.layerId),r=e.layers[t];if(r===void 0)return null;const n=Go(e,this.params.layerId);return n===e?null:{spec:n,revert:new mn({layer:r,index:t},this.metadata)}}},xS={type:"remove-layer",deserialize:(e,t)=>new dn(e,t)},mn=class{constructor(e,t={}){this.type="add-layer",this.params={layer:{...e.layer,id:e.layer.id??C()},...e.index!==void 0&&{index:e.index}},this.metadata=S({...t,description:`Add ${this.params.layer.geom} layer`})}get target(){return{kind:"layer",layerId:this.params.layer.id}}apply(e){const{layer:t,index:r}=this.params;if(e.layers.some(i=>i.id===t.id))return null;const n=r??e.layers.length,a=Math.min(Math.max(n,0),e.layers.length);return{spec:I(e,{layers:[...e.layers.slice(0,a),t,...e.layers.slice(a)]}),revert:new dn({layerId:t.id},this.metadata)}}},AS={type:"add-layer",deserialize:(e,t)=>new mn(e,t)},Uo=class Wo{constructor(t,r={}){this.type="set-data-labels-format",this.params=t,this.metadata=S({...r,description:`Set data labels format to ${t.format}`})}get target(){return{kind:"layer",layerId:this.params.layerId}}apply(t){const r=this.params.layerId?$(t.layers,this.params.layerId):t.layers[0];if(!r)return null;const n=r.dataLabels.format;return n===this.params.format?null:{spec:W(t,r.id,Mt(r,{format:this.params.format})),revert:new Wo({layerId:r.id,format:n},this.metadata)}}},IS={type:"set-data-labels-format",deserialize:(e,t)=>new Uo(e,t)},Ho=class Ko{constructor(t,r={}){this.type="set-layer-geom",this.params=t,this.metadata=S({...r,description:`Set layer geom to ${t.geom}`})}get target(){return{kind:"layer",layerId:this.params.layerId}}apply(t){const r=this.params.layerId?$(t.layers,this.params.layerId):t.layers[0];if(!Pe(r,...wS))return null;const n=r.geom;if(n===this.params.geom)return null;const a=this.params.previousLayer??ES(t,r,this.params.geom);return{spec:W(t,r.id,a),revert:new Ko({layerId:r.id,geom:n,previousLayer:r},this.metadata)}}},TS={type:"set-layer-geom",deserialize:(e,t)=>new Ho(e,t)},LS=new We,wS=si.map(e=>e.type);function ES(e,t,r){const{showDataLabels:n,format:a,showStackTotals:i,showCategoryLabels:s,labelSource:o}=t.dataLabels,c=Dr(LS,e.mapping,e.coords.coordType,{type:"layer",id:t.id,geom:r,mapping:t.mapping,stat:t.stat,position:t.position,yScaleType:t.yScaleType,transforms:t.transforms,interactive:t.interactive,dataLabels:{showDataLabels:n,format:a,showStackTotals:i,showCategoryLabels:s}});return{...c,stat:t.stat,dataLabels:{...c.dataLabels,labelSource:o}}}var zo=class Yo{constructor(t,r={}){this.type="set-layer-position",this.params=t,this.metadata=S({...r,description:`Set layer position to ${t.position}`})}get target(){return{kind:"layer",layerId:this.params.layerId}}apply(t){const r=this.params.layerId?$(t.layers,this.params.layerId):Oe(t.layers,"bar","area");if(!r)return null;const n=r.position;return n===this.params.position?null:{spec:W(t,r.id,{...r,position:this.params.position}),revert:new Yo({layerId:r.id,position:n},this.metadata)}}},VS={type:"set-layer-position",deserialize:(e,t)=>new zo(e,t)},qo=class Xo{constructor(t,r={}){this.type="set-layer-stat";const n=bi(t.stat,"identity");this.params={...t.layerId!==void 0&&{layerId:t.layerId},stat:n},this.metadata=S({...r,description:`Set layer stat to ${n.type}`})}get target(){return{kind:"layer",layerId:this.params.layerId}}apply(t){const r=this.params.layerId?$(t.layers,this.params.layerId):t.layers[0];if(!r)return null;const n=r.stat;return CS(n,this.params.stat)?null:{spec:W(t,r.id,{...r,stat:this.params.stat}),revert:new Xo({layerId:r.id,stat:n},this.metadata)}}},RS={type:"set-layer-stat",deserialize:(e,t)=>new qo(e,t)},CS=(e,t)=>{if(e.type!==t.type)return!1;const r=e,n=t,a=new Set([...Object.keys(r),...Object.keys(n)]);for(const i of a)if(!Object.is(r[i],n[i]))return!1;return!0},jo=class Zo{constructor(t,r={}){this.type="set-layer-y-scale-type",this.params=t,this.metadata=S({...r,description:`Set layer to ${t.yScaleType} y axis`})}get target(){return{kind:"layer",layerId:this.params.layerId}}apply(t){const r=this.params.layerId?$(t.layers,this.params.layerId):t.layers[0];if(!r)return null;const n=r.yScaleType;return n===this.params.yScaleType?null:{spec:W(t,r.id,{...r,yScaleType:this.params.yScaleType}),revert:new Zo({layerId:r.id,yScaleType:n},this.metadata)}}},kS={type:"set-layer-y-scale-type",deserialize:(e,t)=>new jo(e,t)},Jo=class Qo{constructor(t,r={}){this.type="set-line-interpolation",this.params=t,this.metadata=S({...r,description:`Set line interpolation to ${t.interpolate}`})}get target(){return{kind:"layer",layerId:this.params.layerId}}apply(t){const r=this.params.layerId?$(t.layers,this.params.layerId):Oe(t.layers,"line","area");if(!Pe(r,"line","area"))return null;const n=r.params.interpolate;return n===this.params.interpolate?null:{spec:W(t,r.id,$o(r,{interpolate:this.params.interpolate})),revert:new Qo({layerId:r.id,interpolate:n},this.metadata)}}},DS={type:"set-line-interpolation",deserialize:(e,t)=>new Jo(e,t)},el=class tl{constructor(t,r={}){this.type="set-line-missing-values",this.params=t,this.metadata=S({...r,description:`Set missing values handling to ${t.missingValues}`})}get target(){return{kind:"layer",layerId:this.params.layerId}}apply(t){const r=this.params.layerId?$(t.layers,this.params.layerId):Oe(t.layers,"line","area");if(!Pe(r,"line","area"))return null;const n=r.params.missingValues;return n===this.params.missingValues?null:{spec:W(t,r.id,$o(r,{missingValues:this.params.missingValues})),revert:new tl({layerId:r.id,missingValues:n},this.metadata)}}},PS={type:"set-line-missing-values",deserialize:(e,t)=>new el(e,t)},rl=class nl{constructor(t,r={}){this.type="set-rule-label",this.params=t,this.metadata=S({...r,description:"Set reference line label"})}get target(){return{kind:"layer",layerId:this.params.layerId}}apply(t){const r=this.params.layerId?$(t.layers,this.params.layerId):Oe(t.layers,"rule");if(!Pe(r,"rule"))return null;const n=r.params.label,a=this.params.label??void 0;if(n===a)return null;const i=a===void 0?Object.fromEntries(Object.entries(r.params).filter(([s])=>s!=="label")):{...r.params,label:a};return{spec:W(t,r.id,{...r,params:i}),revert:new nl({layerId:r.id,label:n??null},this.metadata)}}},OS={type:"set-rule-label",deserialize:(e,t)=>new rl(e,t)},al=class il{constructor(t,r={}){this.type="set-rule-value",this.params=t,this.metadata=S({...r,description:`Set reference line to ${t.value}`})}get target(){return{kind:"layer",layerId:this.params.layerId}}apply(t){const r=this.params.layerId?$(t.layers,this.params.layerId):Oe(t.layers,"rule");if(!Pe(r,"rule"))return null;const n=typeof l.extractConstantValue(r.mapping.y)=="number"?"y":"x",a=l.extractConstantValue(r.mapping[n]);if(typeof a!="number"||a===this.params.value)return null;const i={...r.mapping,[n]:{value:this.params.value}};return{spec:W(t,r.id,{...r,mapping:i}),revert:new il({layerId:r.id,value:a},this.metadata)}}},MS={type:"set-rule-value",deserialize:(e,t)=>new al(e,t)},sl=class ol{constructor(t,r={}){this.type="toggle-category-labels",this.params=t,this.metadata=S({...r,description:`${t.showCategoryLabels?"Show":"Hide"} category labels`})}get target(){return{kind:"layer",layerId:this.params.layerId}}apply(t){const r=this.params.layerId?$(t.layers,this.params.layerId):t.layers[0];if(!r)return null;const n=r.dataLabels.showCategoryLabels;return n===this.params.showCategoryLabels?null:{spec:W(t,r.id,Mt(r,{showCategoryLabels:this.params.showCategoryLabels})),revert:new ol({layerId:r.id,showCategoryLabels:n},this.metadata)}}},_S={type:"toggle-category-labels",deserialize:(e,t)=>new sl(e,t)},ll=class cl{constructor(t,r={}){this.type="toggle-data-labels",this.params=t,this.metadata=S({...r,description:`${t.showDataLabels?"Show":"Hide"} data labels`})}get target(){return{kind:"layer",layerId:this.params.layerId}}apply(t){const r=this.params.layerId?$(t.layers,this.params.layerId):t.layers[0];if(!r)return null;const n=r.dataLabels.showDataLabels;return n===this.params.showDataLabels?null:{spec:W(t,r.id,Mt(r,{showDataLabels:this.params.showDataLabels})),revert:new cl({layerId:r.id,showDataLabels:n},this.metadata)}}},NS={type:"toggle-data-labels",deserialize:(e,t)=>new ll(e,t)},BS={type:"toggle-line-points",deserialize:(e,t)=>new ul(e,t)},ul=class gr{constructor(t,r={}){this.type="toggle-line-points",this.params=t,this.metadata=S({...r,description:`${t.showPoints?"Show":"Hide"} line points`})}get target(){return{kind:"layer",layerId:this.params.layerId}}apply(t){const r=this.params.layerId?$(t.layers,this.params.layerId):Oe(t.layers,"line");return Pe(r,"line")?this.params.showPoints?this.addPointLayer(t,r):this.removePointLayer(t,r):null}addPointLayer(t,r){return this.findAssociatedPointLayer(t,r)?null:{spec:SS(t,this.params.removedLayer??Dr(FS,t.mapping,t.coords.coordType,l.geom.point({aes:{...r.mapping},interactive:!1}))),revert:new gr({layerId:r.id,showPoints:!1},this.metadata)}}removePointLayer(t,r){const n=this.findAssociatedPointLayer(t,r);return n?{spec:Go(t,n.id),revert:new gr({layerId:r.id,showPoints:!0,removedLayer:n},this.metadata)}:null}findAssociatedPointLayer(t,r){return t.layers.find(n=>n.geom==="point"&&(0,rr.default)(n.mapping,r.mapping))}},FS=new We,dl=class ml{constructor(t,r={}){this.type="toggle-stack-totals",this.params=t,this.metadata=S({...r,description:`${t.showStackTotals?"Show":"Hide"} stack totals`})}get target(){return{kind:"layer",layerId:this.params.layerId}}apply(t){const r=this.params.layerId?$(t.layers,this.params.layerId):t.layers[0];if(!r)return null;const n=r.dataLabels.showStackTotals;return n===this.params.showStackTotals?null:{spec:W(t,r.id,Mt(r,{showStackTotals:this.params.showStackTotals})),revert:new ml({layerId:r.id,showStackTotals:n},this.metadata)}}},$S={type:"toggle-stack-totals",deserialize:(e,t)=>new dl(e,t)};function qe(e,t){return e.scales.find(r=>r.scaledAesthetic===t)}function Xe(e,t,r){const n=e.scales.findIndex(a=>a.scaledAesthetic===t);return n===-1?e:I(e,{scales:Ba(e.scales,n,r)})}function je(e){const t=e.replace(/([A-Z])/g," $1").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}var hl=class pl{constructor(t,r={}){this.type="set-scale-domain",this.params=t,this.metadata=S({...r,description:`Set ${je(t.scaledAesthetic)} scale domain`})}get target(){return{kind:"scale",aesthetic:this.params.scaledAesthetic}}apply(t){const r=qe(t,this.params.scaledAesthetic);if(!r||r.scaleType!=="continuous"&&r.scaleType!=="datetime")return null;const n={min:r.domainMin??null,max:r.domainMax??null},a=this.params.domainMin===void 0?n.min:this.params.domainMin,i=this.params.domainMax===void 0?n.max:this.params.domainMax;if(a===n.min&&i===n.max)return null;const s={...r,...this.params.domainMin!==void 0&&{domainMin:this.params.domainMin},...this.params.domainMax!==void 0&&{domainMax:this.params.domainMax}},o=Xe(t,this.params.scaledAesthetic,s),c={scaledAesthetic:this.params.scaledAesthetic};return this.params.domainMin!==void 0&&(c.domainMin=n.min),this.params.domainMax!==void 0&&(c.domainMax=n.max),{spec:o,revert:new pl(c,this.metadata)}}},GS={type:"set-scale-domain",deserialize:(e,t)=>new hl(e,t)},fl=class gl{constructor(t,r={}){this.type="set-scale-palette",this.params=t,this.metadata=S({...r,description:`Set ${je(t.scaledAesthetic)} palette`})}get target(){return{kind:"scale",aesthetic:this.params.scaledAesthetic}}apply(t){const r=qe(t,this.params.scaledAesthetic);return r?.scaleType!=="palette"||te(r.palette,this.params.palette)?null:{spec:Xe(t,this.params.scaledAesthetic,{...r,scaledAesthetic:this.params.scaledAesthetic,palette:this.params.palette}),revert:new gl({scaledAesthetic:this.params.scaledAesthetic,palette:r.palette},this.metadata)}}},US={type:"set-scale-palette",deserialize:(e,t)=>new fl(e,t)},yl=class vl{constructor(t,r={}){this.type="set-scale-reverse",this.params=t,this.metadata=S({...r,description:`Set ${je(t.scaledAesthetic)} scale reverse to ${t.reverse}`})}get target(){return{kind:"scale",aesthetic:this.params.scaledAesthetic}}apply(t){const r=qe(t,this.params.scaledAesthetic);if(!r||!HS(r))return null;const n=r.reverse;return n===this.params.reverse?null:{spec:Xe(t,this.params.scaledAesthetic,{...r,reverse:this.params.reverse}),revert:new vl({scaledAesthetic:this.params.scaledAesthetic,reverse:n},this.metadata)}}},WS={type:"set-scale-reverse",deserialize:(e,t)=>new yl(e,t)};function HS(e){return e.scaleType==="continuous"||e.scaleType==="datetime"||e.scaleType==="discrete"}var bl=class Sl{constructor(t,r={}){this.type="set-scale-transform",this.params=t,this.metadata=S({...r,description:`Set ${je(t.scaledAesthetic)} scale transform to ${t.transform}`})}get target(){return{kind:"scale",aesthetic:this.params.scaledAesthetic}}apply(t){const r=qe(t,this.params.scaledAesthetic);if(!r||r.scaleType!=="continuous")return null;const n=r.transform;return n===this.params.transform?null:{spec:Xe(t,this.params.scaledAesthetic,{...r,transform:this.params.transform}),revert:new Sl({scaledAesthetic:this.params.scaledAesthetic,transform:n},this.metadata)}}},KS={type:"set-scale-transform",deserialize:(e,t)=>new bl(e,t)},xl=class Al{constructor(t,r={}){this.type="set-scale-zero",this.params=t,this.metadata=S({...r,description:`Set ${je(t.scaledAesthetic)} scale zero to ${t.zero}`})}get target(){return{kind:"scale",aesthetic:this.params.scaledAesthetic}}apply(t){const r=qe(t,this.params.scaledAesthetic);if(!r||r.scaleType!=="continuous")return null;const n=r.zero;return n===this.params.zero?null:{spec:Xe(t,this.params.scaledAesthetic,{...r,zero:this.params.zero}),revert:new Al({scaledAesthetic:this.params.scaledAesthetic,zero:n},this.metadata)}}},zS={type:"set-scale-zero",deserialize:(e,t)=>new xl(e,t)},Il=class ot{constructor(t,r={}){this.type="set-style-rule",this.params={...t,id:t.id??C()},this.metadata=S({...r,description:t.rule===null?"Remove style rule":"Set style rule"})}get target(){return{kind:"styleRule",id:this.params.id}}apply(t){const{list:r,id:n,rule:a,index:i}=this.params,s=t.styles[r],o=s.findIndex(f=>f.id===n),c=o===-1?void 0:s[o];if(a===null){if(c===void 0)return null;const f=new ot({list:r,id:n,rule:c,index:o},this.metadata),g=s.filter(y=>y!==c);return{spec:er(t,r,g),revert:f}}const u={...a,id:n};if(c!==void 0){if(JSON.stringify(c)===JSON.stringify(u))return null;const f=new ot({list:r,id:n,rule:c,index:o},this.metadata),g=s.map(y=>y===c?u:y);return{spec:er(t,r,g),revert:f}}const d=i??s.length,m=Math.min(Math.max(d,0),s.length),h=[...s.slice(0,m),u,...s.slice(m)],p=new ot({list:r,id:n,rule:null},this.metadata);return{spec:er(t,r,h),revert:p}}},YS={type:"set-style-rule",deserialize:(e,t)=>new Il(e,t)},er=(e,t,r)=>I(e,{styles:{...e.styles,[t]:r}}),Tl=class{constructor(){this.descriptors=new Map}register(e){if(this.descriptors.has(e.type))throw new l.InternalError({message:`CommandRegistry: descriptor for type '${e.type}' is already registered`});this.descriptors.set(e.type,e)}serialize(e){return{type:e.type,params:e.params,metadata:e.metadata}}deserialize(e){return this.getDescriptor(e.type).deserialize(e.params,e.metadata)}getRegisteredTypes(){return[...this.descriptors.keys()]}getDescriptor(e){const t=this.descriptors.get(e);if(!t)throw new l.InternalError({message:`CommandRegistry: no descriptor registered for type '${e}'`});return t}},b=new Tl;b.register(AS);b.register(xS);b.register(IS);b.register(TS);b.register(VS);b.register(RS);b.register(kS);b.register(DS);b.register(PS);b.register(OS);b.register(MS);b.register(_S);b.register(NS);b.register(BS);b.register($S);b.register(GS);b.register(US);b.register(WS);b.register(KS);b.register(zS);b.register($b);b.register(Gb);b.register(Ub);b.register(Wb);b.register(Yb);b.register(jb);b.register(Xb);b.register(Zb);b.register(Jb);b.register(Qb);b.register(eS);b.register(tS);b.register(rS);b.register(nS);b.register(aS);b.register(iS);b.register(sS);b.register(oS);b.register(lS);b.register(cS);b.register(uS);b.register(dS);b.register(bS);b.register(vS);b.register(YS);b.register(Ob);b.register(Pb);b.register(_b);b.register(hS);b.register(fS);b.register(yS);var Ll=class{constructor(e={}){this.undoStack=[],this.redoStack=[],this.listeners=new Set,this.isEmitting=!1,this.cachedSnapshot=null,this.hasOpenRun=!1,this.maxHistorySize=e.maxHistorySize??100}apply(e,t,r,n={}){return this.withReentrancyGuard(()=>{const a=n.transient??!1,i=(u,d)=>r?d:u,s=e.apply(t);if(!s)return a||(this.hasOpenRun=!1),i(t,null);const o=r?.({spec:s.spec,command:e})??null,c=o?o.adopted:s.spec;return c?(this.push(e,c,s.revert,a),i(c,o?.value??null)):(a||(this.hasOpenRun=!1),i(t,o?.value??null))})}seal(){return this.withReentrancyGuard(()=>this.hasOpenRun?(this.hasOpenRun=!1,this.emit({type:"seal"}),!0):!1)}undo(e,t){return this.withReentrancyGuard(()=>{const r=this.undoStack[this.undoStack.length-1];if(!r)return null;const n=this.step(r,e,t);return n?n.adopted?(this.undoStack.pop(),this.redoStack.push({command:r.command,revert:n.revert}),this.hasOpenRun=!1,this.emit({type:"undo",command:r.command,spec:n.adopted}),t?n.value:{spec:n.adopted,command:r.command}):n.value:null})}redo(e,t){return this.withReentrancyGuard(()=>{const r=this.redoStack[this.redoStack.length-1];if(!r)return null;const n=this.step(r,e,t);return n?n.adopted?(this.redoStack.pop(),this.undoStack.push({command:r.command,revert:n.revert}),this.hasOpenRun=!1,this.emit({type:"redo",command:r.command,spec:n.adopted}),t?n.value:{spec:n.adopted,command:r.command}):n.value:null})}clear(){this.withReentrancyGuard(()=>{this.hasOpenRun=!1,!(this.undoStack.length===0&&this.redoStack.length===0)&&(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,undoStack:ga(this.undoStack),redoStack:ga(this.redoStack)}),this.cachedSnapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}step(e,t,r){const n=e.revert.apply(t);if(!n)return null;const a=r?.({spec:n.spec,command:e.command})??null;return{adopted:a?a.adopted:n.spec,revert:n.revert,value:a?.value??null}}push(e,t,r,n){const a=this.undoStack.length-1,i=this.undoStack[a],s=this.hasOpenRun&&i!==void 0&&XS(i.command,e);if(n&&s){this.undoStack[a]={command:e,revert:i.revert},this.cachedSnapshot=null;return}this.undoStack.push({command:e,revert:r}),this.undoStack.length>this.maxHistorySize&&this.undoStack.shift(),this.hasOpenRun=n,this.redoStack=[],this.emit({type:"apply",command:e,spec:t})}withReentrancyGuard(e){if(this.isEmitting)throw new l.InternalError({message:"CommandStack: cannot call apply/undo/redo/clear from within a listener"});this.isEmitting=!0;try{return e()}finally{this.isEmitting=!1}}emit(e){this.cachedSnapshot=null;for(const t of this.listeners)try{t(e)}catch(r){console.error("CommandStack listener error:",r)}}},qS=Object.freeze([]),XS=(e,t)=>{if(e.type!==t.type||e.target.kind!==t.target.kind)return!1;const r=e.target,n=t.target;for(const a of new Set([...Object.keys(r),...Object.keys(n)]))if(!Object.is(r[a],n[a]))return!1;return!0},ga=e=>e.length===0?qS:e.map(t=>t.command.metadata),jS=(e,t)=>{if(e===t)return!0;if(e===null||t===null)return!1;switch(e.kind){case"annotation":return t.kind==="annotation"&&e.id===t.id;case"highlight":return t.kind==="highlight"&&e.id===t.id;case"styleRule":return t.kind==="styleRule"&&e.id===t.id;case"content":return t.kind==="content"&&e.part===t.part;case"axis":return t.kind==="axis"&&e.axis===t.axis;case"grid":return t.kind==="grid"&&e.axis===t.axis;case"layer":return t.kind==="layer"&&e.layerId===t.layerId;case"observation":return t.kind==="observation"&&e.layerId===t.layerId&&e.index===t.index;case"mapping":return t.kind==="mapping"&&e.aesthetic===t.aesthetic;case"scale":return t.kind==="scale"&&e.aesthetic===t.aesthetic;case"legend":case"coords":case"appearance":case"headline":case"numberFormat":return e.kind===t.kind;default:throw new l.InternalError({message:`Unhandled edit target kind: ${e.kind}`})}},ZS=class{constructor(e){this.history=e,this.frame=null}open(e){this.frame=e}clear(){this.frame=null}close(){const e=this.history.seal(),t=this.frame;return this.frame=null,e?t:null}},JS=class{constructor(e){this.compiler=e,this.history=new Ll,this.current=null,this.last=null,this.hostInput=null,this.run=new ZS(this.history)}get compiled(){return this.current}compile(e){return this.last=e,this.hostInput=e.input,this.absorb(this.compiler.compile(e))}update(e){const t=this.last,r=!t||e.input!==this.hostInput&&e.input!==t.input,n=!t||e.data!==t.data,a=!t||e.customPalettes!==t.customPalettes;if(this.hostInput=e.input,!r&&!n&&!a)return null;let i=null;r?this.run.close():i=this.closeAndConvert();const s=this.last,o=s&&!r?s.input:e.input;this.last={input:o,data:e.data,customPalettes:e.customPalettes};const c=this.current,u=r||a||!c?this.absorb(this.compiler.compile({input:o,data:e.data,customPalettes:e.customPalettes})):this.absorb(this.compiler.recompile({spec:c.spec,data:e.data}));return r&&u.ok&&this.history.clear(),{result:u,inputChanged:r,...i&&{sealedInput:i.input}}}applyCommand(e,t={}){const r=t.transient??!1,n=[];if(!r){const c=this.sealNotification(!1);c&&n.push(c)}const{current:a,last:i,history:s}=this;if(!a||!i)return n;const o=s.apply(e,a.spec,({spec:c})=>{const u=this.commit(c,i,r,e);return{adopted:u.ok?u.compiled.spec:null,value:u}},t);return o&&n.push(this.renderedNotification(o,e,r)),n}seal(){const e=this.sealNotification(!0);return e?[e]:[]}undo(){return this.stepHistory((e,t)=>this.history.undo(e,t))}redo(){return this.stepHistory((e,t)=>this.history.redo(e,t))}stepHistory(e){const{current:t,last:r}=this;if(!t||!r)return[];const n=e(t.spec,({spec:a,command:i})=>{const s=this.commit(a,r);return{adopted:s.ok?s.compiled.spec:null,value:{result:s,command:i}}});return n?[this.renderedNotification(n.result,n.command,!1)]:[]}renderedNotification(e,t,r){return e.ok?r?{compiled:e.compiled}:{compiled:e.compiled,result:e,command:t,...e.input&&{input:e.input}}:{errors:e.errors}}sealNotification(e){const t=this.closeAndConvert();return t?{result:t.result,input:t.input,...e&&{command:t.command}}:null}closeAndConvert(){const e=this.run.close(),{current:t,last:r}=this;return!t||!r||!e?null:{input:this.recordCompiledInput(t.spec,r),result:e.result,command:e.command}}commit(e,t,r=!1,n=null){const a=this.compiler.recompile({spec:e});if(!a.ok)return{ok:!1,errors:a.errors};if(this.current=a.compiled,r&&n){const s={ok:!0,compiled:a.compiled,warnings:a.warnings};return this.run.open({result:s,command:n}),s}this.run.clear();const i=this.recordCompiledInput(a.compiled.spec,t);return{ok:!0,compiled:a.compiled,warnings:a.warnings,input:i}}recordCompiledInput(e,t){const r=Bs(e);return this.last={input:r,data:t.data,customPalettes:t.customPalettes},r}absorb(e){return e.ok&&(this.current=e.compiled),e}},QS=500,ex="normal",hn={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},tx=e=>{const t=e.style??"normal",r=e.weight??500,n=e.family.includes(",")?e.family:`'${e.family}'`;return`${t} ${r} ${e.size}px ${n}`},pn=e=>typeof e!="string"?e??500:hn[e],rx="\0",nx=class{constructor(e){this.inner=e,this.cache=new Map}measureText(e,t){const r=this.getCacheKey(e,t),n=this.cache.get(r);if(n)return n;const a=this.inner.measureText(e,t);return this.cache.set(r,a),a}getCacheKey(e,t){return[t.family,t.size,pn(t.weight),t.style??"normal",e].join(rx)}},ax={" ":.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};var ix=1.05,sx=.84,ox=.21,lx=class{measureText(e,t){let r=0;for(const i of e)r+=(ax[i]??.55)*t.size;pn(t.weight)>=hn.semiBold&&(r*=ix);const n=sx*t.size,a=ox*t.size;return{width:r,height:n+a,ascent:n,descent:a}}};exports.ANNOTATION_TOOLTIP_MARKER_GAP=hg;exports.AddAnnotationCommand=ln;exports.AddHighlightCommand=un;exports.AddLayerCommand=mn;exports.BORDER_PRESETS=l.BORDER_PRESETS;exports.BORDER_PRESET_GRADIENTS=Tb;exports.BORDER_RADIUS_PX=Zr;exports.BORDER_RADIUS_TOKENS=l.BORDER_RADIUS_TOKENS;exports.BUILTIN_STYLES=l.BUILTIN_STYLES;exports.COLOR_INTERPOLATION_SPACES=pm;exports.COMPILER_STAGE_KEYS=Nh;exports.CONSTANT_VARIABLES=l.CONSTANT_VARIABLES;exports.CachedTextMeasurer=nx;exports.CommandRegistry=Tl;exports.CommandStackManager=Ll;exports.Compiler=Pi;exports.DATA_LABEL_PADDING_X_PX=Dg;exports.DATA_LABEL_PADDING_Y_PX=Pg;exports.DEFAULT_BAR_BORDER_RADIUS_TOKEN=My;exports.DEFAULT_COLOR_PALETTE=l.DEFAULT_COLOR_PALETTE;exports.DEFAULT_DIMMED_ALPHA=l.DEFAULT_DIMMED_ALPHA;exports.DEFAULT_FONT_STYLE=ex;exports.DEFAULT_FONT_WEIGHT=QS;exports.DEFAULT_GEOM_COLOR=l.DEFAULT_GEOM_COLOR;exports.DEFAULT_HOVER_AFFORDANCE_COLOR=l.DEFAULT_HOVER_AFFORDANCE_COLOR;exports.DEFAULT_LOCALE=l.DEFAULT_LOCALE;exports.DIFFERENCE_ARROW_DEFAULTS=at;exports.DIVERGING_SCHEME_NAMES=gi;exports.Dataset=l.Dataset;exports.GROUP_VARIABLES=l.GROUP_VARIABLES;exports.Geom=re;exports.GraphCompilationSession=JS;exports.HEADLINE_SWATCH_GAP=Iy;exports.HEADLINE_SWATCH_SIZE=Ay;exports.HEADLINE_TREND_GAP=wy;exports.HEADLINE_TREND_ICON_SIZE=Ly;exports.HEADLINE_VALUE_LABEL_GAP=Ty;exports.HeuristicTextMeasurer=lx;exports.HoverEngine=Nv;exports.InternalError=l.InternalError;exports.LAYOUT_PADDING=Kh;exports.LINE_STYLE_TYPES=br;exports.LayoutCompiler=Wf;exports.MONO_BASES=l.MONO_BASES;exports.NAMED_WEIGHTS=hn;exports.NEON_BASES=l.NEON_BASES;exports.OBSERVATION_ATTACHMENT_KINDS=nn;exports.OUT_OF_VIEW_MARGIN_PX=pg;exports.POLAR_RIM_LABEL_GAP_PX=_c;exports.POSITION_VARIABLES=l.POSITION_VARIABLES;exports.RESTING_HOVER_STATE=X;exports.RemoveAnnotationCommand=on;exports.RemoveHighlightCommand=cn;exports.RemoveLayerCommand=dn;exports.SCHEME_ALIASES=yi;exports.SEQUENTIAL_SCHEME_NAMES=fm;exports.SIBLING_OVERLAP_THRESHOLD_PX=fg;exports.STACK_TOTAL_PADDING_X_PX=Og;exports.STACK_TOTAL_PADDING_Y_PX=Mg;exports.STACK_VARIABLES=l.STACK_VARIABLES;exports.STYLE_STATES=l.STYLE_STATES;exports.SetAppearanceBackgroundCommand=Us;exports.SetAppearanceBorderCommand=Hs;exports.SetAppearanceCornerRadiusCommand=zs;exports.SetAppearanceTextScaleCommand=qs;exports.SetAxisLabelCommand=Zs;exports.SetAxisPositionCommand=Qs;exports.SetAxisTickModeCommand=to;exports.SetAxisTicksVisibilityCommand=no;exports.SetAxisVisibilityCommand=io;exports.SetContentCaptionCommand=oo;exports.SetContentSourceCommand=co;exports.SetContentSubtitleCommand=mo;exports.SetContentTitleCommand=po;exports.SetCoordLimitsCommand=Oo;exports.SetDataLabelsFormatCommand=Uo;exports.SetGridVisibilityCommand=go;exports.SetHeadlineCompareWithCommand=vo;exports.SetHeadlinePositionCommand=So;exports.SetHeadlineShowCommand=Ao;exports.SetHeadlineSizeCommand=To;exports.SetLayerGeomCommand=Ho;exports.SetLayerPositionCommand=zo;exports.SetLayerStatCommand=qo;exports.SetLayerYScaleTypeCommand=jo;exports.SetLegendPositionCommand=wo;exports.SetLineInterpolationCommand=Jo;exports.SetLineMissingValuesCommand=el;exports.SetNumberFormatAbbreviationCommand=Vo;exports.SetNumberFormatDecimalsCommand=Co;exports.SetPolarInnerRadiusCommand=_o;exports.SetPolarStartAngleCommand=Bo;exports.SetRuleLabelCommand=rl;exports.SetRuleValueCommand=al;exports.SetScaleDomainCommand=hl;exports.SetScalePaletteCommand=fl;exports.SetScaleReverseCommand=yl;exports.SetScaleTransformCommand=bl;exports.SetScaleZeroCommand=xl;exports.SetStyleRuleCommand=Il;exports.SpecResolver=Ii;exports.Stat=De;exports.TAU=ue;exports.ToggleCategoryLabelsCommand=sl;exports.ToggleContentVisibilityCommand=Do;exports.ToggleDataLabelsCommand=ll;exports.ToggleLinePointsVisibilityCommand=ul;exports.ToggleStackTotalsCommand=dl;exports.UpdateAnnotationCommand=$s;exports.VISUAL_VARIABLES=l.VISUAL_VARIABLES;exports.alignUnitFractions=ba;exports.annotation=yb;exports.areAnchorsEqual=fs;exports.areEditMenuTriggersEqual=ey;exports.areEditTargetsEqual=jS;exports.areEndpointsComparable=Sa;exports.areObservationAnchorsEqual=_s;exports.arePointerRegionListsEqual=Yg;exports.buildAverageLineSymbols=cg;exports.buildCalloutHitRegions=mg;exports.buildColumnKey=vs;exports.buildDataLabelsContent=uf;exports.buildDiagnostic=Na;exports.buildEditMenuTriggerRegion=Jg;exports.buildFontString=tx;exports.buildLayerIntroPlan=Kv;exports.buildLayerYValueFormatter=qr;exports.buildObservationAnchor=bt;exports.buildObservationPredicate=$g;exports.buildPinnedNumberValueFormatter=uy;exports.buildPolarBarArcPath=Wy;exports.buildSliceGroupKey=xs;exports.buildTooltipContent=sb;exports.commandRegistry=b;exports.compileStylesheetForLayer=Th;exports.computeArrow=og;exports.computeDifferenceArrow=is;exports.computeDirectLabelsLayout=Fg;exports.computePanelBorderPaths=Lg;exports.computePanelBorderSizes=wg;exports.config=l.config;exports.convertSpecToInput=Bs;exports.coord=l.coord;exports.countLayerGeoms=zv;exports.createAlphaValueReader=Wl;exports.createAnchorResolver=Kf;exports.createAreaPathGenerators=Py;exports.createColorValueReader=wa;exports.createCompiler=Bh;exports.createDatasetFromKindPartitions=Tc;exports.createEmptyHighlight=ri;exports.createGraphyBuilder=Uh;exports.createGroupValueReader=Hl;exports.createHeadlineItemRows=Ey;exports.createLabelValueReader=Gl;exports.createLineFillAreaGenerator=$y;exports.createLinePathGenerator=Fy;exports.createObservationAnchorParser=Ra;exports.createRawValueReader=U;exports.createSegmentYReader=ke;exports.createSizeValueReader=Ul;exports.createSpec=Oi;exports.createStableKeyGenerator=kt;exports.createStrokeWidthValueReader=Kl;exports.createStyleResolver=Kr;exports.createValueFormatter=R;exports.createXValueReader=St;exports.createYValueReader=La;exports.cursorToPiePlane=Ar;exports.cursorToPolar=Lt;exports.describeMeasurementBasis=ar;exports.extractConstantValue=l.extractConstantValue;exports.extractPlainText=ms;exports.extractVariableName=l.extractVariableName;exports.findAnnotation=Ot;exports.findAxisGuide=jr;exports.findEquivalentHighlight=wb;exports.findHighlightsAtObservation=ry;exports.findLegendForAesthetic=Sy;exports.findObservationAttachment=Ns;exports.findPointerRegion=Kg;exports.formatDifferenceLabel=ns;exports.formatHeadline=dy;exports.formatLegends=vy;exports.formatRuleValue=xy;exports.geom=l.geom;exports.getAlpha=Ea;exports.getAngleExtent=zr;exports.getBarRectBounds=ys;exports.getBoundingRect=By;exports.getColor=At;exports.getCrossAxisCoordinate=vt;exports.getCurve=Ct;exports.getDashArray=Dy;exports.getDataLabelDimensions=_g;exports.getDifferenceArrowDimensions=as;exports.getDifferenceArrowLabelBox=Ng;exports.getGroup=G;exports.getHoverGuideLineProps=$v;exports.getHoverGuideRectProps=Gv;exports.getLineType=Va;exports.getMainAxisCoordinate=we;exports.getNumericWeight=pn;exports.getPolarHoverGuideArcProps=Uv;exports.getRadiusExtent=Yr;exports.getRuleDashPattern=zy;exports.getRuleLabelTextColor=Yy;exports.getScaledAesthetic=Ml;exports.getSize=Sr;exports.getStablePolarBarKeyGenerator=qy;exports.getStackRole=ii;exports.getStrokeWidth=sr;exports.getUnionExtent=Ky;exports.getX=V;exports.getXMax=z;exports.getXMin=K;exports.getY=w;exports.getYMax=P;exports.getYMin=N;exports.getYRaw=vr;exports.hasMultipleGroups=Vt;exports.highlight=Lb;exports.inferDifferenceArrowEndpoints=sy;exports.isBorderRadiusToken=l.isBorderRadiusToken;exports.isCartesian=Fl;exports.isCategoricalValueFormat=l.isCategoricalValueFormat;exports.isCompilerCachingEnabled=l.isCompilerCachingEnabled;exports.isCurrencyValueFormat=l.isCurrencyValueFormat;exports.isDateWithoutYearValueFormat=l.isDateWithoutYearValueFormat;exports.isDefined=l.isDefined;exports.isFullTurnSweep=Ga;exports.isLayerOf=Fh;exports.isLineStyleType=Ta;exports.isLookupValueFormat=l.isLookupValueFormat;exports.isNumericValueFormat=l.isNumericValueFormat;exports.isObservationAttachmentKind=xb;exports.isPointWithinEditMenuTrigger=Qg;exports.isPointWithinRegionShape=Xr;exports.isSafeUrl=nb;exports.isStackedPosition=O;exports.isTemporalValueFormat=l.isTemporalValueFormat;exports.mapping=l.mapping;exports.normalizeAngle=Ve;exports.orderPointerRegions=zg;exports.pipe=Mi;exports.placeCallouts=Sg;exports.polarToUnit=dt;exports.positionToAngle=Wa;exports.prefixInternalVariable=l.prefixInternalVariable;exports.prepareAreaObservations=Oy;exports.prepareLineObservations=Gy;exports.projectAnchorToPanel=us;exports.quantiseKey=H;exports.readAttachedObservation=an;exports.readAuthoredNumber=fb;exports.readAuthoredString=gb;exports.readXExtent=Ps;exports.readYExtent=Os;exports.resolveAnchorVariable=pe;exports.resolveArrowColor=Ma;exports.resolveBarBorderRadiusPx=gs;exports.resolveBarBorderTreatment=Ny;exports.resolveBarCornerRadiiPx=_y;exports.resolveColorRamp=Cr;exports.resolveDeferredAnchors=Zf;exports.resolveDefinition=Rr;exports.resolveHeadlinePlacement=Nf;exports.resolveObservationPoint=oy;exports.resolvePolarBarCornerRadiusUnit=Hy;exports.resolveSegmentYSource=xt;exports.resolveYScaleAesthetic=ge;exports.sampleColorScheme=Sm;exports.scale=l.scale;exports.setCompilerCachingEnabled=l.setCompilerCachingEnabled;exports.stat=l.stat;exports.stepDifferenceArrowEndpoint=ly;exports.style=l.style;exports.styles=l.styles;exports.toPanelCursor=ds;exports.toPercent=oe;exports.toViewBoxX=Yf;exports.toViewBoxY=Q;exports.token=l.token;exports.transform=l.transform;exports.truncateToWidth=Ni;exports.uniqueId=C;exports.unitToPolar=Ha;exports.updateSpec=E;