@graphysdk/viz-engine 0.0.1-plugins.1 → 0.0.1-plugins.10

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,20 +1,21 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("./geom.utils-DbZj1kY1.cjs"),A=require("date-fns"),le=require("lodash-es"),Ve=require("d3-time"),To=require("date-fns/differenceInDays"),q=require("d3-scale"),_r=require("lodash-es/merge"),J=require("d3-regression"),wo=require("humanize-duration"),Io=require("d3-delaunay");typeof window<"u"&&(window.__GRAPHY_SDK__??={},window.__GRAPHY_SDK__.vizEngine="0.0.1-plugins.1");function Oe(e,t){return Nr(e,t)}function St(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 Nr(e,t){let n=!1;const r={...e};for(const[a,o]of Object.entries(t)){const s=e[a];if(u.isPlainObject(o)&&u.isPlainObject(s)){const i=Nr(s,o);i!==s&&(r[a]=i,n=!0)}else o!==void 0&&o!==s&&(r[a]=o,n=!0)}return n?r:e}const ne=process.env.NODE_ENV!=="production";function lt(e){return{pipe:t=>{const n=t(e);return lt({...e,...n})},result:()=>e}}let ut=!0;const Vo=e=>{ut=e},Lo=()=>ut,Eo=()=>{let e=null;const t={hits:0,misses:0};return Object.assign((r,a)=>{if(!ut)return ne&&(t.misses+=1),a();if(e&&Or(e.args,r))return ne&&(t.hits+=1),e.out;ne&&(t.misses+=1);const o=a();return e={args:r,out:o},o},{stats:t,reset:()=>{e=null}})},Fr=()=>{const e=new WeakMap,t={hits:0,misses:0};return Object.assign((r,a,o)=>{if(!ut)return ne&&(t.misses+=1),o();const s=e.get(r);if(s){for(const c of s)if(Or(c.args,a))return ne&&(t.hits+=1),c.out}ne&&(t.misses+=1);const i=o();return s?s.push({args:a,out:i}):e.set(r,[{args:a,out:i}]),i},{stats:t})},Mo=(...e)=>e.reduce((t,n)=>({hits:t.hits+n.hits,misses:t.misses+n.misses}),{hits:0,misses:0}),Or=(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 j{constructor(){this.memo=Fr(),this.singletonKey={}}get stats(){return this.memo.stats}compile(t){return this.memo(this.key(t),this.dependencies(t),()=>this.run(t))}key(t){return this.singletonKey}}const be=e=>e[u.GROUP_VARIABLES.group],Do=e=>{const{coordinate:t,coordSystem:n}=e;return"observation"in t?Ro(e):n.type!=="cartesian"?null:"unit"in t?{x:t.unit.x,y:t.unit.y,mode:"unit"}:Co(t.data,e)},Ro=({coordinate:e,layers:t,coordSystem:n,geomCompiler:r})=>{if(!("observation"in e))return null;const a=e.observation;for(const o of t){if(a.layerId!==void 0&&o.id!==a.layerId)continue;const s=u.extractVariableName(o.mapping.x);if(s!==null)for(const i of o.data){if(i[s]!==a.anchorValue||be(i)!==a.groupValue)continue;const c=r.resolveAnchorPosition(o.geom,i,n);if(c!==null)return{x:c.x,y:1-c.y,mode:"observation",observation:i}}}return null},Co=(e,{coordSystem:t,scales:n})=>{const r=Bn(n,"x"),a=Bn(n,"y");if(r===null||a===null)return null;const o=r.map(e.x),s=a.map(e.y);if(!Number.isFinite(o)||!Number.isFinite(s))return null;const i=t.type==="cartesian"&&t.mainAxis==="y";return{x:i?s:o,y:1-(i?o:s),mode:"data"}},Bn=(e,t)=>{const n=e[t];return n!==void 0&&n.kind==="position"?n:null},C=e=>e instanceof Date&&A.isValid(e),ko=e=>C(e)||e===null,Pe=e=>typeof e=="string",w=e=>typeof e=="number"&&!Number.isNaN(e)&&Number.isFinite(e);function Wt(e){return e[u.VISUAL_VARIABLES.color]}function _o(e){return e[u.VISUAL_VARIABLES.alpha]}function Pr(e){return e[u.VISUAL_VARIABLES.size]}function No(e){return e[u.VISUAL_VARIABLES.strokeWidth]}function Br(e){return e[u.VISUAL_VARIABLES.lineType]??"solid"}const Bt=(e,t,n,r)=>{for(const a of t){if(e.layerId!==void 0&&a.id!==e.layerId)continue;const o=u.extractVariableName(a.mapping.x);if(o===null)continue;const s=u.extractVariableName(a.mapping.y);for(const i of a.data){if(i[o]!==e.anchorValue||be(i)!==e.groupValue)continue;const c=r.resolveAnchorPosition(a.geom,i,n);if(c===null)continue;const l=s!==null?i[s]??null:null;if(w(l))return{...c,measurementValue:l,color:Wt(i)}}}return null};class Fo extends j{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:Po(t,n),shapes:t.annotations.shapes,freeformArrows:t.annotations.freeformArrows,textAnnotations:t.annotations.textAnnotations,stickers:xt(t.annotations.stickers,t.layers,t.coordSystem,n),pinnedNumbers:xt(t.annotations.pinnedNumbers,t.layers,t.coordSystem,n),comments:xt(t.annotations.comments,t.layers,t.coordSystem,n),custom:Oo(t,n)}}}const Oo=({annotations:e,layers:t,coordSystem:n,scales:r},a)=>{const o=[];for(const s of e.custom){const i=[];let c=!1;for(const l of s.coordinates){const d=Do({coordinate:l,layers:t,coordSystem:n,scales:r,geomCompiler:a});if(d===null){c=!0;break}i.push(d)}c||o.push({id:s.id,type:s.type,params:s.params,zOrder:s.zOrder,targets:i})}return o},xt=(e,t,n,r)=>{const a=[];for(const o of e){const s=Bt(o.anchor,t,n,r);s!==null&&a.push({...o,anchor:s})}return a},Po=({annotations:e,layers:t,coordSystem:n},r)=>{if(n.type!=="cartesian")return[];const a=[];for(const o of e.differenceArrows){if(Bo(o.start,o.end))continue;const s=Bt(o.start,t,n,r),i=Bt(o.end,t,n,r);s===null||i===null||a.push({id:o.id,start:s,end:i,color:Go(o,s,i),size:o.size,label:o.label,labelCrossPosition:o.labelCrossPosition})}return a},Bo=(e,t)=>e.layerId===t.layerId&&e.anchorValue===t.anchorValue&&e.groupValue===t.groupValue,Go=(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 Uo(e,t){const n=Ko(t);return{...e,background:$o(e.background,n),border:Yo(e.border,n)}}function $o(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 Yo(e,t){if(e.type==="tinted"||e.type==="gradient"){const n=e.color??t;if(!n)throw new Error(`could not resolve color for ${e.type} background`);return{...e,color:n}}return e}function Ko(e){const t=e.color,n=t?.domain[0];if(!n)return;const r=t.map(n);if(typeof r=="string")return r}class Ho extends j{dependencies(t){return[t.scales,t.config]}run(t){const{scales:n,config:r}=t;return{...r,appearance:Uo(r.appearance,n)}}}class Wo extends j{dependencies(t){return[t.data,t.mapping]}run(t){let n=t.data,r=t.mapping;r.x===""&&(n=n.addConstantVariable(u.CONSTANT_VARIABLES.x,"categorical",""),r={...r,x:u.CONSTANT_VARIABLES.x});for(const a of Object.keys(r)){const o=u.extractConstantValue(r[a]);if(o===void 0)continue;const s=u.prefixInternalVariable(`const_${a}`);n=n.addConstantVariable(s,zo(o),o),r={...r,[a]:s}}return{data:n,mapping:r}}}const zo=e=>typeof e=="number"?"numeric":e instanceof Date?"temporal":"categorical";class Se{constructor(){this.perLayerMemo=Fr(),this.listMemo=Eo()}get stats(){return Mo(this.perLayerMemo.stats,this.listMemo.stats)}compile(t){const n=this.dependencies(t),r=t.layers.map(a=>this.perLayerMemo(a,n,()=>this.compileLayer(a,t)));return this.listMemo(r,()=>r)}}class Xo extends j{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 qo extends Se{constructor(t){super(),this.registry=t}dependencies(t){return[t.coordSpec]}compileLayer(t,n){const r=this.registry.get(n.coordSpec.coordType),[a]=r.transform({coordSpec:n.coordSpec,layers:[t]});if(!a)throw new Error(`CoordCompiler: strategy '${n.coordSpec.coordType}' did not return a transformed layer`);return a}}class jo{constructor(t){this.setupStage=new Xo(t),this.transformStage=new qo(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 xe{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 Qo{constructor(){this.coordType="cartesian"}setup(t){if(t.coordSpec.coordType!=="cartesian")throw new Error(`Invalid coordinate type: ${t.coordSpec.coordType}`);return{coordSystem:{type:"cartesian",mainAxis:"x",axisMapping:{x:{position:"bottom",geometry:"linear"},y:{position:"right",geometry:"linear"}}},scales:t.scales}}transform(t){return t.layers}}class Zo{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:Jo(t.scales,t.layers)}}transform(t){return t.layers.map(n=>{const r=this.geomRegistry.get(n.geom),a=u.derivePositionColumnPairs(r.positionChannels);return ts(n,a)})}}const Gn=u.prefixInternalVariable("flipSwap"),Jo=(e,t)=>es(t)?e.map(n=>n.scaledAesthetic!=="x"||n.scaleType!=="continuous"&&n.scaleType!=="datetime"&&n.scaleType!=="discrete"?n:{...n,reverse:!n.reverse}):e,es=e=>{for(const t of e){const n=u.extractVariableName(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},ts=(e,t)=>{let n=e.data;for(const[r,a]of t){const o=n.hasVariable(r),s=n.hasVariable(a);o&&s?n=n.renameVariable(r,Gn).renameVariable(a,r).renameVariable(Gn,a):o?n=n.renameVariable(r,a):s&&(n=n.renameVariable(a,r))}return{...e,data:n}};class ns{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},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=rs(n),a=as(n);return t.layers.map(o=>{const s=this.geomRegistry.get(o.geom),i=u.derivePositionColumnPairs(s.positionChannels),c=n.theta==="y"?ss(o,i):o;return{...os(c,i,r,a),spatialMap:{kind:"arcs"}}})}}function rs(e){const t=e.startAngle*(Math.PI/180);return n=>n*2*Math.PI+t}function as(e){const{innerRadius:t}=e;return n=>t+n*(1-t)}function os(e,t,n,r){let a=e.data;for(const[o,s]of t)a=Un(a,o,n),a=Un(a,s,r);return{...e,data:a}}function Un(e,t,n){if(!e.hasVariable(t))return e;const a=e.getValues(t,{type:"numeric"}).map(o=>o===null?null:n(o));return e.addVariable(t,"numeric",a)}function ss(e,t){let n=e.data;for(const[r,a]of t){const o=n.hasVariable(r),s=n.hasVariable(a);if(!o&&!s)continue;const i=o?n.getValues(r):null,c=s?n.getValues(a):null;i&&(n=n.addVariable(a,"numeric",i)),c&&(n=n.addVariable(r,"numeric",c))}return{...e,data:n}}class is extends xe{constructor(t){super("coord"),this.register("cartesian",new Qo),this.register("flip",new Zo(t)),this.register("polar",new ns(t))}}class Gr{constructor(){this.currentYear=new Date().getUTCFullYear(),this.previousDate=null,this.previousYear=null}incrementYearIfNeeded(t){this.previousYear===null?this.previousYear=t.getUTCFullYear():this.previousDate!==null&&A.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 Ur=e=>{const t=Object.entries(e);return!t.length||!t.some(([,n])=>!Be(n))},Be=e=>typeof e=="string"&&e.trim()===""||e===void 0||e===null||e==="-",dt="en-GB",cs=e=>e.type==="lookup",ls=e=>e.type==="text",Ge=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",$r=e=>e.type==="decimal"||e.type==="integer"||e.type==="percentage"||e.type==="duration"||e.type==="currency",Yr=e=>e.type==="currency",Kr=e=>e.type==="month"||e.type==="day_month"||e.type==="weekly_date_range",Hr=e=>{if(cs(e))return Hr(e.fallback);if(Ge(e))return"temporal";if($r(e))return"numeric";if(ls(e))return"categorical";const t=e;throw new Error(`No data type found for value format: ${t.type}`)},Ce={k:1e3,m:1e6,b:1e9,t:1e12},zt=["k","m","b","t"],us=new RegExp(`^-?(\\d{1,3}(,\\d{3})*|\\d+)\\.?\\d*(${zt.join("|")})?$`,"i"),ds=/^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?%?$/,oe=e=>e===null||e instanceof Date||Array.isArray(e)||typeof e=="boolean"?!1:typeof e=="string"?us.test(e)&&!Number.isNaN(Number(e.replace(new RegExp(`[,${zt.join("")}]`,"gi"),""))):!Number.isNaN(Number(e)),Wr=e=>oe(e)?!0:typeof e=="string"?ds.test(e):!1,ms=/^\d{4}-\d{2}-\d{2}(T|\s)\d{1,2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|\+00:00)?$/,ps=/^\s*(19\d{2}|2[01]\d{2})\s*$/,fs=[[/\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"]],hs={"en-US":"MDY","en-GB":"DMY","pt-PT":"DMY",ar:"DMY"},zr=["/","-","."," "],$n=[["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"]],Yn=[["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"]],Kn=[["yyyy","M","d"],["yyyy","M","dd"],["yyyy","MM","d"],["yyyy","MM","dd"],["yyyy","MMMM","d"],["yyyy","MMMM","dd"],["yyyy","MMMM","do"]],Xr=[["d","MMMM"],["dd","MMMM"],["do","MMMM"],["MMMM","d"],["MMMM","dd"],["MMMM","do"]],ys=[{dateFormat:"MMMM d, yyyy",type:"date"},{dateFormat:"MMMM dd, yyyy",type:"date"},{dateFormat:"MMMM do, yyyy",type:"date"},{dateFormat:"yyyy-MM",type:"month_year"}],qr=1900,jr=2199,gs=3,bs=6,Ss=5,xs=1,vs=28,As=/\s*[–—]\s*|\s-\s/,Ts=e=>typeof e=="number"?Number.isNaN(e)?!1:e>=qr&&e<=jr:typeof e=="string"?ps.test(e):!1,Qr=(e,t)=>{const n=ke(e);return oe(n)?Vs(n):typeof n=="string"?!!Zr(n)||Xt(n)&&A.isValid(new Date(n)):A.isValid(n)},ke=e=>{if(typeof e!="string")return e;let t=e;for(const[n,r]of fs)t=t.replace(n,r);return t},Zr=(e,t=dt)=>{const n=ke(e);return Xt(n)?{type:"datetime"}:Jr(t).find(r=>!Ge(r)||r.type==="month"&&n.length<gs?!1:r.dateFormat&&A.isValid(A.parse(n,r.dateFormat,new Date)))},Xt=e=>ms.test(e.trim()),ws=(e,t=dt)=>{const[n,r]=e.split(As);if(!n||!r)return;const a=ke(n).trim(),o=ke(r).trim();return Is(t).find(s=>{if(!Ge(s)||!s.dateFormat)return!1;const i=A.parse(a,s.dateFormat,new Date),c=A.parse(o,s.dateFormat,new Date);if(!A.isValid(i)||!A.isValid(c))return!1;const l=new Gr,d=l.incrementYearIfNeeded(i),m=l.incrementYearIfNeeded(c),f=A.differenceInDays(m,d);return A.isWithinInterval(new Date(d.getFullYear(),xs,vs),{start:d,end:m})&&f===Ss?!0:f===bs})},Jr=e=>{const t={date:ea(e),year:[["yyyy"]],day_month:Xr,month_year:[["MMMM","yyyy"],["yyyy","MMMM"]],month:[["MMMM"]],quarter:[["QQQ","yyyy"],["yyyy","QQQ"]]};return[...ys,...Object.entries(t).flatMap(([n,r])=>r.flatMap(a=>zr.map(o=>({dateFormat:a.join(o),type:n}))))]},ea=e=>hs[e]==="MDY"?[...Yn,...$n,...Kn]:[...$n,...Yn,...Kn],Is=e=>{const t={weekly_date_range:Xr,weekly_date_range_with_year:ea(e)};return Object.entries(t).flatMap(([n,r])=>r.flatMap(a=>zr.map(o=>({dateFormat:a.join(o),type:n}))))},Vs=e=>{const t=Number(e);if(!le.isInteger(t))return!1;const n=new Date(t),r=new Date(t*1e3),a=o=>A.isValid(o)&&o.getFullYear()>=qr&&o.getFullYear()<=jr;return a(n)||a(r)},ta={$:"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"},na=e=>{if(typeof e=="string"){const t=ra(e);return t.length?oe(t):!1}return oe(e)},Ls=e=>{const t=aa(e),n=t?ta[t]:void 0;if(!n)throw new Error("Could not get currency ISO");return n},ra=e=>{const t=aa(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 oe(n)?n.split(",").join(""):""},aa=e=>Object.keys(ta).sort((n,r)=>r.length-n.length).find(n=>e.includes(n)),Es=(e,t)=>{const n=typeof e=="string"?e.trim():e;if(oe(n))return{type:"decimal"};const r=typeof n=="string"&&Zr(n,t);if(r)return r;const a=typeof n=="string"&&ws(n,t);return a||(Qr(e)?{type:"date"}:Wr(e)?{type:"percentage"}:na(e)&&typeof e=="string"?{type:"currency",iso:Ls(e)}:{type:"text"})},Ms=/\s*[–—]\s*|\s-\s/,Ds=(e,t,n)=>{if(Be(e))return null;switch(t.type){case"decimal":case"integer":case"duration":return oa(e);case"percentage":return Rs(e);case"currency":return Cs(e);case"datetime":case"date":case"year":case"month_year":case"month":case"day_month":case"quarter":case"time":return qt(e,t.dateFormat,n);case"weekly_date_range":case"weekly_date_range_with_year":return ks(e,t.dateFormat,n);case"text":return _s(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}`)}}},qt=(e,t,n)=>{if(e instanceof Date)return A.isValid(e)?e:null;const r=ke(String(e).trim());if(r.length===0)return null;const a=new Date;if(t){const s=A.parse(r,t,a);return A.isValid(s)?vt(s):null}for(const s of Jr(n)){if(!Ge(s)||!s.dateFormat)continue;const i=A.parse(r,s.dateFormat,a);if(A.isValid(i))return vt(i)}const o=new Date(r);return Qr(o)?Xt(r)?o:vt(o):null},oa=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;let t=e.trim();if(!oe(t))return null;let n=1;for(const r of zt)if(new RegExp(`${r}$`,"i").test(t)){n=Ce[r],t=t.slice(0,-1);break}return Number(t.split(",").join(""))*n},Rs=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;const t=e.trim();if(!Wr(t))return null;const n=Number(t.replace(/%/g,"").replace(/,/g,""))/100;return Number.isNaN(n)?null:n},Cs=e=>{if(typeof e=="number")return Number.isNaN(e)?null:e;if(typeof e!="string")return null;const t=e.trim();return na(t)?oa(ra(t)):null},ks=(e,t,n)=>{const r=String(e).trim().split(Ms),[a,o]=[r[0]?.trim(),r[1]?.trim()];return!a||!o?null:qt(a,t,n)},_s=e=>String(e).trim(),vt=e=>new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())),Ns={type:"year",dateFormat:"yyyy"};class Fs extends j{dependencies(t){return[t]}run(t){const n=t._metadata?.parsingLocale??dt,r={},a=Bs(t),o=Os(t);for(const[s,i]of t.columns.entries()){if(i._metadata?.isHidden)continue;const c=a.get(i.key);if(Be(c))continue;const l=s===o?Ns:Es(c,n),d=Hr(l);r[i.key]=Ps(i.key,t.rows,l,d,n)}return new u.Dataset(r)}}const Os=e=>{const t=Gs(e.rows,5);return e.columns.findIndex(n=>{const r=t.map(a=>a[n.key]).filter(a=>!Be(a));return r.length>=2&&r.every(Ts)})},Ps=(e,t,n,r,a)=>{const o=new Gr,s=t.reduce((i,c)=>{if(Ur(c))return i;const l=Ds(c[e],n,a);return Kr(n)&&C(l)?i.push(o.incrementYearIfNeeded(l)):i.push(l),i},[]);return{type:r,values:s,valueFormat:n}},Bs=e=>{const t=new Map,n=new Set(e.columns.map(r=>r.key));for(const r of e.rows){for(const a of n){const o=r[a];Be(o)||(t.set(a,o),n.delete(a))}if(n.size===0)break}return t},Gs=(e,t)=>{const n=[];for(const r of e)if(Ur(r)||n.push(r),n.length===t)return n;return n};class Us{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 $s extends u.Geom{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=u.sortByXIfContinuous(t,n),t.hasVariable(u.POSITION_VARIABLES.yMin)||(t=t.addConstantVariable(u.POSITION_VARIABLES.yMin,"numeric",0)),!t.hasVariable(u.POSITION_VARIABLES.yMax)){const r=u.extractVariableName(n.y);u.isDefined(r)&&t.hasVariable(r)&&(t=t.addVariable(u.POSITION_VARIABLES.yMax,"numeric",t.getValues(r,{type:"numeric"})))}return{data:t,mapping:{}}}}const sa=.7,Ys=.1;function ve(e){return e[u.POSITION_VARIABLES.x]}function z(e){return e[u.POSITION_VARIABLES.y]}function _e(e){return e[u.POSITION_VARIABLES.xMin]}function ye(e){return e[u.POSITION_VARIABLES.xMax]}function se(e){return e[u.POSITION_VARIABLES.yMin]}function $(e){return e[u.POSITION_VARIABLES.yMax]}function ia(e){return e[u.POSITION_VARIABLES.yRaw]}class Ks extends u.Geom{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=u.sortByXIfContinuous(t,n),t.hasVariable(u.POSITION_VARIABLES.yMin)||(t=t.addConstantVariable(u.POSITION_VARIABLES.yMin,"numeric",0)),!t.hasVariable(u.POSITION_VARIABLES.yMax)){const a=u.extractVariableName(n.y);u.isDefined(a)&&t.hasVariable(a)&&(t=t.addVariable(u.POSITION_VARIABLES.yMax,"numeric",t.getValues(a,{type:"numeric"})))}const r=sa/2;return t=t.addConstantVariable(u.POSITION_VARIABLES.xMin,"numeric",-r).addConstantVariable(u.POSITION_VARIABLES.xMax,"numeric",r),{data:t,mapping:{}}}resolveAnchorPosition(t,n){if(n.type==="polar"){const s=_e(t),i=ye(t),c=se(t),l=$(t);if(s===null||i===null||c===null||l===null)return null;const d=(s+i)/2,m=(c+l)/2;return{x:.5+.5*m*Math.sin(d),y:.5-.5*m*Math.cos(d),geom:"polar-bar"}}if(n.mainAxis==="x"){const s=_e(t),i=ye(t),c=$(t)??z(t);return s===null||i===null||c===null?null:{x:(s+i)/2,y:c,geom:"bar"}}const r=se(t),a=$(t),o=ye(t)??ve(t);return r===null||a===null||o===null?null:{x:o,y:(r+a)/2,geom:"bar"}}}class Hs extends u.Geom{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:u.sortByXIfContinuous(t.data,t.mapping),mapping:{}}}resolveAnchorPosition(t,n){if(n.type==="polar")return null;const r=ve(t),a=z(t);return r===null||a===null?null:{x:r,y:a,geom:"line"}}}class Ws extends u.Geom{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 zs extends u.Geom{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=Hn(n.y,t);if(r!==null)return{data:new u.Dataset({[u.RULE_VARIABLES.y]:{type:"numeric",values:[r.value],valueFormat:r.sourceFormat}}),mapping:{y:u.RULE_VARIABLES.y,x:void 0}};const a=Hn(n.x,t);return a!==null?{data:new u.Dataset({[u.RULE_VARIABLES.x]:{type:"numeric",values:[a.value],valueFormat:a.sourceFormat}}),mapping:{x:u.RULE_VARIABLES.x,y:void 0}}:{data:new u.Dataset,mapping:{x:void 0,y:void 0}}}validateMapping({layerId:t,mapping:n,computedVariables:r}){const a=r.has("x")||w(u.extractConstantValue(n.x)),o=r.has("y")||w(u.extractConstantValue(n.y));return a&&o?[{code:"INVALID_RULE_MAPPING",message:`Layer '${t}': rule geom requires exactly one of 'x' or 'y', both were provided`,layerId:t}]:!a&&!o?[{code:"INVALID_RULE_MAPPING",message:`Layer '${t}': rule geom requires a numeric value on 'x' or 'y'`,layerId:t}]:[]}}const Hn=(e,t)=>{const n=u.extractConstantValue(e);if(w(n))return{value:n,sourceFormat:void 0};const r=u.extractVariableName(e);if(r===null||!u.isStatVariable(r)||!t.hasVariable(r))return null;const[a]=t.getValues(r);return w(a)?{value:a,sourceFormat:t.getValueFormat(r)}:null};class Xs extends xe{constructor(t){super("geom"),this.register("bar",new Ks),this.register("point",new Ws),this.register("line",new Hs),this.register("area",new $s),this.register("rule",new zs);for(const n of t?.geoms??[])this.register(n.type,n)}}const jt=(e,t)=>{if(u.isDefined(t.group)){const a=u.extractVariableName(t.group);if(a!==null)return[a]}const n=new Set([u.extractVariableName(t.x),u.extractVariableName(t.y)].filter(u.isDefined)),r=new Set;for(const a in t){if(a==="x"||a==="y")continue;const o=u.extractVariableName(t[a]);u.isDefined(o)&&(n.has(o)||e.getType(o)==="categorical"&&r.add(o))}return[...r]};class qs{compute({data:t,mapping:n}){const r=jt(t,n);if(r.length===0)return{data:t.addConstantVariable(u.GROUP_VARIABLES.group,"categorical",null)};const a=t.size(),o=r.map(i=>t.getValues(i)),s=new Array(a);for(let i=0;i<a;i++)s[i]=u.getStableKey(o.map(c=>c[i]));return{data:t.addVariable(u.GROUP_VARIABLES.group,"categorical",s)}}}const ca=new Set(["x","y","ySecondary"]),mt=new Set(["color","size","alpha","strokeWidth","lineType"]),pt=e=>ca.has(e),js=e=>mt.has(e),Qs=e=>pt(e)||js(e);function Ue(e){return e==="secondary"?"ySecondary":"y"}function Y(e){return e==="ySecondary"?"y":e}const Zs=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},Js=(e,t,n)=>{const r=ie(t,"color");return r===null?{}:(e?.columns??[]).some(s=>s.key===r)?{}:n};function ie(e,t){const n=Y(t);for(const r of la(t,e)){const a=u.extractVariableName(r.mapping[n]);if(u.isDefined(a))return a}return null}const Qt=(e,t)=>e===null?null:t[e]??e,ei=(e,t)=>e===null?null:t[String(e)]??null,ce=({layers:e,scaleType:t,variableName:n})=>{if(n===null)return At(t);for(const r of e){if(!r.data.hasVariable(n))continue;const a=r.data.getValueFormat(n),o=a.type==="lookup"?a.fallback:a;return ni(o,t)?o:At(t)}return At(t)},ti=(e,t)=>t!=="y"&&t!=="ySecondary"?!1:la(t,e).some(n=>n.position==="fill");function la(e,t){return e==="ySecondary"?t.filter(n=>n.yScaleType==="secondary"):e==="y"?t.filter(n=>n.yScaleType==="primary"):t}const At=e=>{switch(e){case"continuous":return{type:"decimal"};case"datetime":return{type:"date"};case"discrete":case"palette":case"identity":return{type:"text"}}},ni=(e,t)=>{switch(t){case"continuous":return $r(e);case"datetime":return Ge(e);case"discrete":case"palette":case"identity":return!0}},ri=[{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}],Wn={year:0,quarter:1,month:2,week:3,day:4,hour:5},de=40,ai=(e,t,n)=>{const r=n.unit==="quarter"?n.step*3:n.step;return ci(n.unit).range(e,new Date(t.valueOf()+1),r)},oi=({unit:e,step:t,start:n,stop:r})=>{const a=To.differenceInDays(r,n);switch(e){case"hour":return 24*a/t>de;case"day":return a/t>de;case"week":return a/(7*t)>de;case"month":return a/(30*t)>de;case"quarter":return a/(90*t)>de;case"year":return a/(365*t)>de}},si=(e,t)=>{const n=!Kr(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"}}},ii=(e,t)=>{const n=li(t);return n===null?!1:Wn[e]>Wn[n]},ci=e=>{switch(e){case"hour":return Ve.utcHour;case"day":return Ve.utcDay;case"week":return Ve.utcMonday;case"month":case"quarter":return Ve.utcMonth;case"year":return Ve.utcYear}},li=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}},ua={left:"right",right:"left",top:"bottom",bottom:"top"},ui={x:!0,y:!0,ySecondary:!1},di=20,zn=new Set(["top","bottom"]),mi={type:"percentage"};function pi(e,t){const{scales:n,config:r,layers:a,coordSystem:o,variableLabels:s,geomCompiler:i}=e;if(o.type==="polar")return[];const c=hi(a,o.type,r,i),l=new Set(t.map(f=>f.position)),d=gi(da(r.axes.y.position,o.axisMapping.y.position),l),m=[];for(const f of ca){const p=n[f];if(!u.isDefined(p)||p.kind!=="position")continue;const h=fi({scaleAestheticKey:f,scale:p,config:r,layers:a,axisMapping:o.axisMapping,resolvedYPosition:d,gridOverrides:c,variableLabels:s});m.push(h)}return m}function fi(e){const{scaleAestheticKey:t,scale:n,config:r,layers:a,axisMapping:o,resolvedYPosition:s,gridOverrides:i,variableLabels:c}=e,l=Y(t),{axisConfig:d,position:m}=yi(t,r,o,s),f=ie(a,t),p=ti(a,t)?mi:ce({layers:a,scaleType:n.spec.scaleType,variableName:f}),h=Qt(f,c);return{scaleAestheticKey:t,aesthetic:l,position:m,label:d.label??h,isVisible:d.isVisible,tickCandidates:Si(n,p),valueFormat:p,tickMode:d.ticks.mode,ticksVisible:d.ticks.isVisible,gridVisible:bi(d,i,t),scaleType:n.spec.scaleType,bandwidth:n.bandwidth??void 0}}function hi(e,t,n,r){const a=e.flatMap(c=>{const l=r.getGridPolicies(c.geom)[t];return l?[l]:[]}),o=a.some(c=>c.hideGridX),s=a.some(c=>c.hideGridY),i=a.some(c=>c.hideBorder);return{x:{gridVisible:Xn(o,n.axes.x.grid.isVisible)},y:{gridVisible:Xn(s,n.axes.y.grid.isVisible)},borderVisible:i?!1:void 0}}function Xn(e,t){if(e&&t===null)return!1}function yi(e,t,n,r){switch(e){case"x":return{axisConfig:t.axes[e],position:da(t.axes[e].position,n[e].position)};case"y":return{axisConfig:t.axes[e],position:r};case"ySecondary":{const a=ua[r],o=le.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:o,position:o.position}}}}function da(e,t){return zn.has(e)===zn.has(t)?e:t}function gi(e,t){return t.has(e)?ua[e]:e}function bi(e,t,n){const{gridVisible:r}=n==="x"?t.x:t.y;return r??e.grid.isVisible??ui[n]}const Si=(e,t)=>{if(e.spec.scaleType==="continuous"){const r=new Set,a=[];for(let o=1;o<=di;o++){const s=e.generateTicks({count:o}),i=u.getStableKey(s);r.has(i)||(r.add(i),a.push({ticks:s.map(c=>ot(e,c))}))}return a}return e.spec.scaleType==="datetime"?xi(e,t):[{ticks:e.generateTicks().map(r=>ot(e,r))}]},xi=(e,t)=>{const[n,r]=e.domain;if(!C(n)||!C(r))return[{ticks:e.generateTicks().map(c=>ot(e,c))}];const a=new Set,o=[],s=(i,c)=>{if(i.length===0)return;const l=u.getStableKey(i);a.has(l)||(a.add(l),o.push({ticks:i.map(d=>ot(e,d)),valueFormat:c}))};for(const i of ri)oi({...i,start:n,stop:r})||ii(i.unit,t)||s(e.generateTicks({interval:i}),si(i,t));return s(e.generateTicks({atInputs:!0})),o.sort((i,c)=>i.ticks.length-c.ticks.length),o},ot=(e,t)=>({value:t,position:e.map(t)});function Ne(e,t){return t.type==="polar"&&e==="square"?"slice":e}function ma({scale:e,aesthetics:t,layers:n,coordSystem:r}){const a=vi({layers:n,coordSystem:r,aesthetics:t}),o=pa({layers:n,aesthetics:t});return e.domain.map(s=>({value:s,swatchShape:a(s),owner:o(s)}))}function vi({layers:e,coordSystem:t,aesthetics:n}){const r=pa({layers:e,aesthetics:n}),a=e.find(s=>n.some(i=>u.isDefined(s.mapping[i]))),o=a?Ne(a.swatchShape,t):"square";return s=>{const i=r(s);return i?Ne(i.layer.swatchShape,t):o}}function pa({layers:e,aesthetics:t,layerFilter:n}){const r=new Map;for(const[a,o]of e.entries()){if(n&&!n(o))continue;const s=t.find(c=>u.isDefined(o.mapping[c]));if(s===void 0)continue;const i=u.extractVariableName(o.mapping[s]);if(!(i===null||!o.data.hasVariable(i)))for(const c of o.data.getValues(i,{distinct:!0})){const l=u.getStableKey(c);r.has(l)||r.set(l,{layer:o,layerIndex:a})}}return a=>r.get(u.getStableKey(a))}const Zt=e=>{if(e.kind==="identity")return!1;const t=e.spec.scaleType;return t!=="continuous"&&t!=="datetime"};function Ai({scales:e,layers:t,coordSystem:n,valueLabels:r}){const a=e.color;if(a===void 0||!Zt(a))return[];if(!t.some(d=>u.isDefined(d.mapping.color)))return[];const o=ie(t,"color");if(fa({colorVariableName:o,xVariableName:ie(t,"x"),mapsColorAcrossMultipleLayers:wi(t)>1,isMergedWithAnotherAesthetic:Ti(e,t,o)}))return[];const i=a.spec.scaleType,c=t.findIndex(d=>u.isDefined(d.mapping.color));return ma({scale:a,aesthetics:["color"],layers:t,coordSystem:n}).map(({value:d,swatchShape:m,owner:f})=>{const p=f?.layerIndex??c,h=t[p],y=h?u.extractVariableName(h.mapping.color):null;return{value:d,color:String(a.map(d)),shape:m,layerIndex:p,valueFormat:ce({layers:h?[h]:t,scaleType:i,variableName:y}),label:ei(d,r)}})}const fa=({colorVariableName:e,xVariableName:t,mapsColorAcrossMultipleLayers:n,isMergedWithAnotherAesthetic:r})=>r?!1:e===null||u.isInternalVariable(e)?!n:t!==null&&e===t;function Ti(e,t,n){if(n===null)return!1;for(const r of mt){if(r==="color")continue;const a=e[r];if(!(a===void 0||!Zt(a))&&ie(t,r)===n)return!0}return!1}const wi=e=>e.filter(t=>u.isDefined(t.mapping.color)).length;function Ii(e,t,n,r){const a=t.findIndex(o=>r.supportsPerGroupHeadline(o.geom));if(a===-1)return[];if(e.length<2){const o=u.extractVariableName(t[a]?.mapping.y);return[{value:null,swatch:null,layerIndex:a,groupLabelFormat:{type:"text"},label:Qt(o,n)}]}return e.map(o=>({value:o.value,swatch:{color:o.color,shape:o.shape},layerIndex:o.layerIndex,groupLabelFormat:o.valueFormat,label:o.label}))}function qn(e,t,n){if(n===null||t===null)return[...e];const r=u.getStableKey(n);return e.filter((a,o)=>u.getStableKey(t[o]??null)===r)}const Vi=(e,t)=>{switch(t){case"total":{const{sum:n,count:r}=jn(e);return r===0?null:n}case"average":{const{sum:n,count:r}=jn(e);return r===0?null:n/r}case"current":return e.at(-1)??null}},Li=(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}},jn=e=>e.reduce((t,n)=>n===null?t:{sum:t.sum+n,count:t.count+1},{sum:0,count:0});function Ei(e){const{config:t,coordSystem:n}=e,r=t.headline.show;return r==="none"||r==="conversion"?null:n.type==="polar"?Mi(e,r):Di(e,r)}function Mi(e,t){if(t!=="total")return null;const{scales:n,layers:r}=e,a=r.find(c=>c.summary.grandTotal!==void 0);if(a===void 0)return null;const o=a.summary.grandTotal;if(o===void 0)return null;const s=u.extractVariableName(a.mapping.y);if(s===null)return null;const i=ce({layers:[a],scaleType:n.y?.spec.scaleType??"continuous",variableName:s});return{kind:"grandTotal",value:o,valueFormat:i}}function Di(e,t){const{config:n,scales:r,layers:a,variableLabels:o,colorGroups:s,geomCompiler:i}=e;if(!a.some(d=>i.supportsPerGroupHeadline(d.geom)))return null;const c=Ii(s,a,o,i);if(c.length===0)return null;const l=c.map(d=>Ri({group:d,show:t,compareWith:n.headline.compareWith,layers:a,scales:r})).filter(d=>d!==null);return l.length===0?null:{kind:"perGroup",items:l}}function Ri({group:e,show:t,compareWith:n,layers:r,scales:a}){const o=r[e.layerIndex];if(o===void 0)return null;const s=u.extractVariableName(o.mapping.y);if(s===null||t==="total"&&o.position==="fill")return null;const i=u.extractVariableName(o.mapping.x),c=u.extractVariableName(o.mapping.color),l=o.yScaleType==="secondary"?a.ySecondary:a.y,d=ce({layers:[o],scaleType:l?.spec.scaleType??"continuous",variableName:s}),m=_i(o.data,i),f=ce({layers:[o],scaleType:m?"datetime":a.x?.spec.scaleType??"discrete",variableName:i}),p=Ni(o.data,i),h=p.getValues(s,{type:"numeric"}),y=i!==null?p.getValues(i):[],g=c!==null?p.getValues(c):null,S=qn(h,g,e.value),b=qn(y,g,e.value);return{value:e.value,swatch:e.swatch,aggregate:Vi(S,t),valueFormat:d,groupLabelFormat:e.groupLabelFormat,mainValueFormat:f,label:e.label,observationLabel:Ci(t,m,b),comparison:ki(t,n,m,b,S)}}function Ci(e,t,n){if(e==="current"){const o=n.at(-1);return o===void 0?null:{kind:"point",value:o}}if(!t)return null;const r=n.at(0),a=n.at(-1);return r===void 0||a===void 0?null:{kind:"range",from:r,to:a}}function ki(e,t,n,r,a){if(e!=="current"||!n)return null;const o=t==="none"?"first":t,s=r.map((i,c)=>({main:i,cross:a[c]??null}));return Li(s,o)}function _i(e,t){return t!==null&&e.hasVariable(t)&&e.getType(t)==="temporal"}function Ni(e,t){return t===null||!["numeric","temporal"].includes(e.getType(t))?e:e.orderBy(t)}const ha=["point","line","area","bar","rule"],ya=new Set(ha);function ga(e){return ya.has(e)}function F(e){return e==="stack"||e==="fill"}const Fi=3;function Oi({scales:e,config:t,layers:n,coordSystem:r,variableLabels:a,colorGroups:o,geomCompiler:s}){if(t.legend.position==="none")return[];const i=new Map(o.map(g=>[u.getStableKey(g.value),g])),c=Gi({scales:e,layers:n,geomCompiler:s}),l=Hi(c),d=ie(n,"x"),m=l.map(g=>{if(Yi(g,d,n))return null;const S=zi({group:g,variableLabels:a,layers:n,coordSystem:r,colorGroupsByValue:i});return S.items.length===0?null:{group:g,built:S}}).filter(u.isDefined);if(m.length===0)return[];const f=Pi(m);if(t.legend.position==="auto"&&Zi(f,n,r))return[];const p=Ji(t.legend.position,f,n,r),h=tc(t.legend.display,p,n,r,s),y=h==="direct"?ac(n):null;return m.map(({built:g})=>Bi(g,p,h,y))}function Pi(e){return e.reduce((t,{group:n,built:r})=>{const a=n.some(o=>o.guideType!=="discrete");return t+(a?1:r.items.length)},0)}function Bi(e,t,n,r){return n!=="direct"||r===null?{...e,position:t,display:n}:{...e,position:t,display:n,items:e.items.map(a=>({...a,normalizedY:r.get(String(a.value))??null}))}}function Gi(e){const{scales:t,layers:n,geomCompiler:r}=e,a=Ui(n,r),o=[];for(const s of mt){if(!a.has(s))continue;const i=t[s];if(i===void 0||i.kind==="identity"||!$i(s,n))continue;const c=ie(n,s),l=rc(s,i);o.push({scaleAestheticKey:s,scale:i,variableName:c,guideType:l})}return o}function Ui(e,t){const n=new Set;for(const r of e)for(const a of t.getVisualAesthetics(r.geom))n.add(a);return n}function $i(e,t){const n=Y(e);return t.some(r=>u.isDefined(r.mapping[n]))}function Yi(e,t,n){const[r]=e;return r.scaleAestheticKey!=="color"?!1:fa({colorVariableName:r.variableName,xVariableName:t,mapsColorAcrossMultipleLayers:Ki(r.scaleAestheticKey,n),isMergedWithAnotherAesthetic:e.length>1})}function Ki(e,t){const n=Y(e);return t.filter(r=>u.isDefined(r.mapping[n])).length>1}function Hi(e){const t=new Map;for(const n of e){const r=nc(n),a=t.get(r);a?a.push(n):t.set(r,[n])}return[...t.values()]}function Wi(e,t,n){if(t==="lineType"){e.lineType=n;return}if(t==="color"){e.color=String(n);return}e[t]=n}function zi({group:e,variableLabels:t,layers:n,coordSystem:r,colorGroupsByValue:a}){const o=e[0],s=e.map(d=>Y(d.scaleAestheticKey)),i=ma({scale:o.scale,aesthetics:s,layers:n,coordSystem:r}),c=Qt(o.variableName,t),l=ce({layers:n,scaleType:o.scale.spec.scaleType,variableName:o.variableName});return{aesthetics:e.map(d=>d.scaleAestheticKey),title:c,items:i.map(d=>Xi(d,e,s,l,a))}}function Xi(e,t,n,r,a){const o={};for(const i of t)Wi(o,i.scaleAestheticKey,i.scale.map(e.value));const s=ji(e,t,n,r,a);return{value:e.value,label:qi(t,e,a),visual:o,normalizedY:null,swatchShape:e.swatchShape,valueFormat:s}}function qi(e,t,n){return e[0].scaleAestheticKey!=="color"?null:n.get(u.getStableKey(t.value))?.label??null}function ji(e,t,n,r,a){if(t[0].scaleAestheticKey==="color")return a.get(u.getStableKey(e.value))?.valueFormat??r;const o=e.owner?.layer,s=Qi(o,n);return o===void 0||s===null?r:ce({layers:[o],scaleType:t[0].scale.spec.scaleType,variableName:s})}function Qi(e,t){if(e===void 0)return null;for(const n of t){const r=e.mapping[n];if(r===void 0)continue;const a=u.extractVariableName(r);if(a!==null)return a}return null}function Zi(e,t,n){if(e>1)return!1;const r=n.type==="polar";return Ze(t,["line","area","bar"])||r}function Ji(e,t,n,r){if(e!=="auto")return e;if(r.type==="polar")return"top";const a=Ze(n,["line","area"]),o=Ze(n,["bar"]),s=Ze(n,["bar"],c=>F(c.position)),i=t>=Fi;return a&&o?"top":a?i?"right":"top":s?ba(r)?"top":i?"right":"top":"top"}function ec(e,t){if(e.length!==1)return!1;const n=e[0];return n?t.getDirectLabelPositions(n.geom).includes(n.position):!1}function tc(e,t,n,r,a){if(!(t==="right"&&!ba(r)))return"pill";switch(e){case"pill":return"pill";case"direct":return"direct";case"auto":return ec(n,a)?"direct":"pill"}}function ba(e){return e.type==="cartesian"&&e.mainAxis==="y"}function Ze(e,t,n){return e.some(r=>t.includes(r.geom)&&(n?.(r)??!0))}function nc(e){const t=e.scale.domain.map(u.getStableKey);return JSON.stringify([e.variableName,e.guideType,...t])}function rc(e,t){return Zt(t)?"discrete":`continuous:${e}`}function ac(e){const t=e[0];if(!t)return new Map;const n=new Map;return t.data.groupBy(u.GROUP_VARIABLES.group).forEach(r=>{const a=r.findLast(l=>u.isDefined($(l))||u.isDefined(z(l)));if(!a)return;const o=be(a);if(!u.isDefined(o))return;const s=se(a),i=$(a)??z(a);if(!u.isDefined(i))return;const c=u.isDefined(s)?(s+i)/2:i;n.set(String(o),c)}),n}class oc extends j{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=Zs(t.originalData),r=Ai({scales:t.scales,layers:t.layers,coordSystem:t.coordSystem,valueLabels:Js(t.originalData,t.layers,n)}),a={scales:t.scales,config:t.config,layers:t.layers,coordSystem:t.coordSystem,variableLabels:n,colorGroups:r,geomCompiler:this.geomCompiler},o=Ei(a),s=sc(o,Oi(a));return{axes:pi(a,s),legends:s,headline:o,panel:{border:{isVisible:t.config.panel.border.isVisible}},colorGroups:r}}}const sc=(e,t)=>e?.kind!=="perGroup"||t.some(r=>r.display==="direct")?t:[],ft=e=>e[u.IDENTITY_VARIABLES.key],ic=e=>u.getStableKey([be(e)]),Jt=(e,t)=>{const n=t!==null?e[t]??null:null;return u.getStableKey([n])},O=(e,t)=>{const n=u.extractConstantValue(t);if(n!==void 0)return()=>n;const r=u.extractVariableName(t);return u.isDefined(r)?a=>{const o=a[r];if(o===void 0)return null;switch(e.getType(r)){case"numeric":return w(o)?o:null;case"categorical":return Pe(o)?o:null;case"temporal":return C(o)?o:null;default:return null}}:()=>null},en=(e,t)=>O(e,t.x),Sa=(e,t)=>O(e,t.y),cc=(e,t)=>O(e,t.label),xa=(e,t)=>O(e,t.color),lc=(e,t)=>O(e,t.size),uc=(e,t)=>O(e,t.alpha),dc=(e,t)=>O(e,t.group),mc=(e,t)=>O(e,t.strokeWidth),Qn={variable:u.POSITION_VARIABLES.yRaw};function $e(e,t){return F(e)?Qn:t.y??Qn}function tn(e){return O(e.data,$e(e.position,e.mapping))}const pc=["lt","lte","gt","gte","range"];function Je(e,t){if("and"in e){const n=e.and.map(r=>Je(r,t));return r=>{for(const a of n)if(!a(r))return!1;return!0}}if("or"in e){const n=e.or.map(r=>Je(r,t));return r=>{for(const a of n)if(a(r))return!0;return!1}}if("not"in e){const n=Je(e.not,t);return r=>!n(r)}return fc(e,t)}function et(e,t){if("and"in e){for(const r of e.and)et(r,t);return}if("or"in e){for(const r of e.or)et(r,t);return}if("not"in e){et(e.not,t);return}const n=hc(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 Zn=()=>!1;function fc(e,t){if(!t.hasVariable(e.variable))return Zn;const n=t.getType(e.variable);if("eq"in e){const r=X(e.eq,n,t.parsingLocale);return a=>Jn(t.readValue(a,e.variable),r)}if("oneOf"in e){const r=e.oneOf.map(a=>X(a,n,t.parsingLocale));return a=>{const o=t.readValue(a,e.variable);for(const s of r)if(Jn(o,s))return!0;return!1}}if("lt"in e){const r=X(e.lt,n,t.parsingLocale);return a=>me(t.readValue(a,e.variable),r)==="less"}if("lte"in e){const r=X(e.lte,n,t.parsingLocale);return a=>{const o=me(t.readValue(a,e.variable),r);return o==="less"||o==="equal"}}if("gt"in e){const r=X(e.gt,n,t.parsingLocale);return a=>me(t.readValue(a,e.variable),r)==="greater"}if("gte"in e){const r=X(e.gte,n,t.parsingLocale);return a=>{const o=me(t.readValue(a,e.variable),r);return o==="greater"||o==="equal"}}if("range"in e){const[r,a]=e.range,o=X(r,n,t.parsingLocale),s=X(a,n,t.parsingLocale);return i=>{const c=t.readValue(i,e.variable),l=me(c,o),d=me(c,s);return l==="incomparable"||d==="incomparable"?!1:(l==="greater"||l==="equal")&&(d==="less"||d==="equal")}}return Zn}function hc(e){for(const t of pc)if(t in e)return t;return null}function me(e,t){if(e===null||t===null)return"incomparable";if(C(e)&&C(t)){const n=e.getTime(),r=t.getTime();return n<r?"less":n>r?"greater":"equal"}return w(e)&&w(t)?e<t?"less":e>t?"greater":"equal":"incomparable"}function Jn(e,t){return e===t?!0:C(e)&&C(t)?e.getTime()===t.getTime():!1}function X(e,t,n){return t!=="temporal"||!Pe(e)?e:qt(e,void 0,n)}function va(e){return e===null?null:{strategy:e,composition:Aa()}}function Aa(){return{isDimmed:!1,matchedLayer:null,overlayCandidates:[]}}class yc extends Se{dependencies(t){return[t.highlights,t.config.parsingLocale]}compileLayer(t,n){const r=t.highlight;if(r===null)return t;const a=n.highlights.filter(({layerId:s})=>s===void 0||s===t.id);if(a.length===0)return t;const o=gc({layer:t,highlights:a,parsingLocale:n.config.parsingLocale,strategy:r.strategy});return{...t,highlight:{...r,composition:o}}}}function gc({layer:e,highlights:t,parsingLocale:n,strategy:r}){for(const v of t)et(v.predicate,e.data);const a=u.extractVariableName(e.mapping.x),o=bc(e,n),s=t.map(v=>({predicate:Je(v.predicate,o),scope:v.scope})),i=s.some(({scope:v})=>v==="series"),c=s.some(({scope:v})=>v==="x-value"),l=r==="overlay-anchor",d=e.data.size(),m=i?new Array(d):null,f=c?new Array(d):null,p=l?new Array(d):null,h=new Uint8Array(d),y=new Set,g=new Set;let S=!1,b=0;for(const v of e.data){let K,Z;m!==null&&(K=ic(v),m[b]=K),f!==null&&(Z=Jt(v,a),f[b]=Z),p!==null&&(p[b]=v);for(const{predicate:Ke,scope:He}of s)if(Ke(v))switch(He){case"series":K!==void 0&&y.add(K);break;case"x-value":Z!==void 0&&g.add(Z);break;case"data-point":h[b]=1,S=!0;break}b++}if(y.size===0&&g.size===0&&!S)return Aa();const x=new Uint8Array(d),T=[];let L=0;for(let v=0;v<d;v++){const K=m?.[v],Z=f?.[v],Ke=K!==void 0&&y.has(K),He=Z!==void 0&&g.has(Z),On=h[v]===1;if(r==="observation-rerender")(Ke||On||He)&&(x[v]=1,L++);else if(Ke)x[v]=1,L++;else if(On||He){const Pn=p?.[v];Pn!==void 0&&T.push({observation:Pn,observationIndex:v})}}const P=L>0?{...e,data:e.data.filterByMask(x)}:null;return{isDimmed:(r==="observation-rerender"||y.size>0)&&P!==null,matchedLayer:P,overlayCandidates:T}}function bc(e,t){const n=u.extractVariableName(e.mapping.y),r=tn(e);return{hasVariable:a=>e.data.hasVariable(a),getType:a=>e.data.getType(a),readValue:(a,o)=>n!==null&&o===n?r(a):a[o]??null,parsingLocale:t}}const Sc=["x","y","color","size","alpha","strokeWidth","lineType","label"],Ta=(e,t,n,r=[])=>{const a=[];for(const o of Sc){const s=Ac(o,t,n);s===null||!e.hasVariable(s.valueVariable)||!e.hasVariable(s.formatVariable)||a.push({aesthetic:o,variable:s.valueVariable,valueFormat:e.getValueFormat(s.formatVariable)})}return{encodings:a,detailRows:vc(e,r)}},xc=e=>t=>({key:ft(t),encodings:e.encodings.map(({aesthetic:n,variable:r,valueFormat:a})=>({aesthetic:n,value:t[r]??null,valueFormat:a}))});function vc(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 Ac(e,t,n){if(e==="y"){const a=u.extractVariableName($e(n,t));return a===null?null:{valueVariable:a,formatVariable:u.extractVariableName(t.y)??a}}const r=u.extractVariableName(t[e]);return r===null?null:{valueVariable:r,formatVariable:r}}const Tc=Object.values(u.POSITION_VARIABLES);function er(e){const t=new u.Dataset({});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:Ta(t,{},e.position),spatialMap:{kind:"noop"},swatchShape:"square",failed:!0}}function wc(e,t){let n;try{n=t()}catch{return er(e)}return Ic(n)?n:er(e)}function Ic(e){for(const t of Tc)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 Vc=e=>e.kind==="index"?(t,n)=>String(n):t=>u.getStableKey(e.variables.map(n=>t[n])),Lc=(e,t)=>{if(e==="index")return{kind:"index"};const n=u.extractVariableName(t.x);return{kind:"fields",variables:n===null?[u.GROUP_VARIABLES.group]:[n,u.GROUP_VARIABLES.group]}},Ec=(e,t,n)=>{const r=Vc(Lc(t,n));return e.deriveVariable(u.IDENTITY_VARIABLES.key,"categorical",r)};class Mc extends Se{constructor(t,n,r,a,o){super(),this.transformCompiler=t,this.statCompiler=n,this.groupCompiler=r,this.geomCompiler=a,this.positionAdjusterCompiler=o}dependencies(t){return[t.data,t.mapping,tr(t)]}compileLayer(t,n){return wc(t,()=>{const r=this.transformCompiler.compile({data:n.data,transforms:t.transforms}),a={...n.mapping,...t.mapping};return this.runLayerPipeline(t,r,a,tr(n))})}runLayerPipeline(t,n,r,a){const o=lt({data:n,mapping:r}).pipe(({data:c,mapping:l})=>{const d=this.statCompiler.compute(t.stat,{data:c,mapping:l,xScaleIsDiscrete:a});return{data:d.data,mapping:{...l,...d.mapping}}}).pipe(({data:c,mapping:l})=>({data:this.groupCompiler.compute({data:c,mapping:l}).data,mapping:l})).pipe(({data:c,mapping:l})=>{const d=this.geomCompiler.compile(t.geom,{data:c,mapping:l,params:t.params});return{data:d.data,mapping:{...l,...d.mapping},tooltipRows:d.tooltipRows??[]}}).pipe(({data:c,mapping:l})=>{const d=this.geomCompiler.getPositionChannels(t.geom),m=this.positionAdjusterCompiler.adjust(t.position,d,{data:c,mapping:l});return{data:m.data,mapping:{...l,...m.mapping}}}).pipe(({data:c,mapping:l})=>({data:Ec(c,this.geomCompiler.getIdentityKeyStrategy(t.geom),l),mapping:l})).result(),{tooltipRows:s,...i}=o;return{...i,id:t.id,geom:t.geom,position:t.position,yScaleType:t.yScaleType,params:t.params,interactive:t.interactive,dataLabels:t.dataLabels,summary:{},highlight:va(this.geomCompiler.getHighlightStrategy(t.geom)),semanticMap:Ta(i.data,i.mapping,t.position,s),spatialMap:{kind:this.geomCompiler.getSpatialKind(t.geom)},swatchShape:this.geomCompiler.getSwatchShape(t.geom),failed:!1}}}function tr(e){return e.scales.some(t=>t.scaledAesthetic==="x"&&t.scaleType==="discrete")}class wa extends Error{constructor(t){const n=t.map(r=>`- ${r.message}`).join(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("date-fns"),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.10");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
2
  `);super(`Spec validation failed:
3
- ${n}`),this.issues=t,this.name="SpecValidationError"}}class Dc{constructor(t,n){this.transformCompiler=t,this.validator=n}check(t){const n=[];for(const r of t.layers){const a=this.transformCompiler.compile({data:t.data,transforms:r.transforms}),o={...t.mapping,...r.mapping};n.push(...this.validator.validate({layerId:r.id,geom:r.geom,stat:r.stat,effectiveMapping:o,data:a,coordType:t.coords.coordType}))}if(n.length>0)throw new wa(n)}}class Rc{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:a}){const o=[],{requiredAesthetics:s}=this.geomRegistry.get(n),{computedVariables:i}=this.statRegistry.get(r.type);for(const c of s)i.has(c)||u.isDefined(u.readAesthetic(a,c))||o.push({code:"MISSING_AESTHETIC",message:`Layer '${t}': geom '${n}' requires aesthetic '${c}'`,layerId:t,aesthetic:c});return o}validateVariableExistence({layerId:t,stat:n,effectiveMapping:r,data:a}){const o=[],{computedVariables:s}=this.statRegistry.get(n.type);for(const[i,c]of Object.entries(r)){if(s.has(i))continue;const l=u.extractVariableName(c);l!==null&&(a.hasVariable(l)||o.push({code:"UNKNOWN_VARIABLE",message:`Layer '${t}': aesthetic '${i}' references variable '${l}' which does not exist in the dataset`,layerId:t,aesthetic:i}))}return o}validateGeomMapping({layerId:t,geom:n,stat:r,effectiveMapping:a}){const o=this.geomRegistry.get(n);if(o.validateMapping===void 0)return[];const{computedVariables:s}=this.statRegistry.get(r.type);return o.validateMapping({layerId:t,mapping:a,computedVariables:s})}validateCoordSupport({layerId:t,geom:n,coordType:r}){const{supportedCoordTypes:a}=this.geomRegistry.get(n);return a.includes(r)?[]:[{code:"UNSUPPORTED_COORD",message:`Layer '${t}': geom '${n}' is not supported under '${r}' coords`,layerId:t}]}}const nr=u.prefixInternalVariable("__ungrouped__"),Cc=(e,t)=>t===null?!0:e.some(n=>n.axis===t.axis&&n.role===t.role&&n.valueKind===t.valueKind),Ia=(e,t,n="y")=>{const r=n==="y"?"x":"y",a=u.extractVariableName(t[n]),o=u.extractVariableName(t[r]);if(!a||!o)return null;const s=e.getValues(u.GROUP_VARIABLES.group,{type:"categorical",distinct:!0,skipNulls:!0}),i=s.length===0,c=i?[nr]:s,l=e.getValues(o),d=e.getValues(a,{type:"numeric"}),m=e.getValues(u.GROUP_VARIABLES.group,{type:"categorical"}),f=e.size(),p=new Map;for(let h=0;h<f;h++){const y=l[h]??null,g=m[h],S=i?nr:g;if(!u.isDefined(S))continue;let b=p.get(y);b||(b=new Map,p.set(y,b)),b.set(S,h)}return{values:d,observationIndexByPartitionAndGroup:p,uniqueGroupKeys:c,observationCount:f}};class kc{constructor(t){this.registry=t}adjust(t,n,r){const a=this.registry.get(t),o=a.getConsumedChannel(r.axis??"y");return Cc(n,o)?a.adjust(r):{data:r.data,mapping:{}}}}class ht{getConsumedChannel(t){return null}}class _c extends ht{constructor(){super(...arguments),this.type="dodge"}getConsumedChannel(t){return{axis:"x",role:"point",valueKind:"value"}}adjust({data:t,mapping:n}){if(!u.extractVariableName(n.x))return{data:t,mapping:{}};const a=t.getValues(u.GROUP_VARIABLES.group,{type:"categorical",distinct:!0,skipNulls:!0});if(a.length===0)return{data:t,mapping:{}};const o=t.size(),s=t.getValues(u.GROUP_VARIABLES.group,{type:"categorical"}),i=sa/2,c=a.length>1?Ys:0,l=q.scaleBand().domain(a.map(String)).range([-i,i]).paddingInner(c).paddingOuter(0),d=l.bandwidth(),m=new Array(o).fill(null),f=new Array(o).fill(null);for(let h=0;h<o;h++){const y=s[h];if(!u.isDefined(y))continue;const g=l(String(y));u.isDefined(g)&&(m[h]=g,f[h]=g+d)}return{data:t.addVariable(u.POSITION_VARIABLES.xMin,"numeric",m).addVariable(u.POSITION_VARIABLES.xMax,"numeric",f),mapping:{}}}}class Nc extends ht{constructor(){super(...arguments),this.type="fill"}getConsumedChannel(t){return{axis:t,role:"point",valueKind:"value"}}adjust({data:t,mapping:n,axis:r="y"}){const a=Ia(t,n,r);if(a===null)return{data:t,mapping:{}};const{values:o,observationIndexByPartitionAndGroup:s,uniqueGroupKeys:i,observationCount:c}=a,l=[...o],d=new Array(c).fill(0);for(const[,f]of s){let p=0,h=0;for(const S of i){const b=f.get(S);if(b===void 0)continue;const x=o[b];x!=null&&(x>=0?p+=x:h-=x)}let y=0,g=0;for(const S of i){const b=f.get(S);if(b===void 0)continue;const x=o[b];if(x===void 0)continue;if(x===null){d[b]=null,l[b]=null;continue}const T=x>=0?p:h;if(T===0){d[b]=0,l[b]=0;continue}const L=x/T;x>=0?(d[b]=y,l[b]=y+=L):(l[b]=g,d[b]=g+=L)}}let m=t.addVariable(u.variableFor(r,"lower"),"numeric",d).addVariable(u.variableFor(r,"upper"),"numeric",l);return r==="y"&&(m=m.addVariable(u.POSITION_VARIABLES.yRaw,"numeric",o)),{data:m,mapping:{}}}}class Fc extends ht{constructor(){super(...arguments),this.type="identity"}adjust({data:t}){return{data:t,mapping:{}}}}class Oc extends ht{constructor(){super(...arguments),this.type="stack"}getConsumedChannel(t){return{axis:t,role:"point",valueKind:"value"}}adjust({data:t,mapping:n,axis:r="y"}){const a=Ia(t,n,r);if(a===null)return{data:t,mapping:{}};const{values:o,observationIndexByPartitionAndGroup:s,uniqueGroupKeys:i,observationCount:c}=a,l=[...o],d=new Array(c).fill(0);for(const[,p]of s){let h=0,y=0;for(const g of i){const S=p.get(g);if(S===void 0)continue;const b=o[S];if(b!==void 0){if(b===null){d[S]=null,l[S]=null;continue}b>=0?(d[S]=h,l[S]=h+=b):(l[S]=y,d[S]=y+=b)}}}let m=t.addVariable(u.variableFor(r,"lower"),"numeric",d).addVariable(u.variableFor(r,"upper"),"numeric",l);r==="y"&&(m=m.addVariable(u.POSITION_VARIABLES.yRaw,"numeric",o));const f=u.extractVariableName(n[r]);return f!==null&&(m=m.addVariable(f,"numeric",l)),{data:m,mapping:{}}}}class Pc extends xe{constructor(){super("position"),this.register("identity",new Fc),this.register("stack",new Oc),this.register("fill",new Nc),this.register("dodge",new _c)}}function Bc(e){let t=e.data;for(const n of e.channels)n.role==="point"&&(t=Gc(n.axis,t,e));for(const n of $c(e.channels))t=Yc(n,t,e);for(const n of e.channels)n.role==="scalar"&&(t=Uc(n,t,e));return t}function nn(e,t){return e==="x"?"x":Ue(t)}function Gc(e,t,n){const r=u.extractVariableName(n.mapping[e]),a=n.getPositionScale(nn(e,n.yScaleType));if(!r||!a)return t;const s=t.getValues(r).map(i=>u.isDefined(i)?a.map(i):null);return t.addVariable(u.variableFor(e,"point"),"numeric",s)}function Uc(e,t,n){const r=n.getPositionScale(nn(e.axis,n.yScaleType)),o=(e.aes?u.extractVariableName(u.readAesthetic(n.mapping,e.aes)):null)??u.variableFor(e.axis,e.name);if(!r||!t.hasVariable(o))return t;const i=t.getValues(o,{type:"numeric"}).map(c=>u.isDefined(c)?r.map(c):null);return t.addVariable(u.variableFor(e.axis,e.name),"numeric",i)}function $c(e){const t=new Map;for(const n of e){if(n.role==="point"||n.role==="scalar")continue;const r=`${n.axis}:${n.valueKind}`,a=t.get(r)??{axis:n.axis,valueKind:n.valueKind,hasLower:!1,hasUpper:!1};n.role==="lower"&&(a.hasLower=!0),n.role==="upper"&&(a.hasUpper=!0),t.set(r,a)}return[...t.values()].filter(n=>n.hasLower&&n.hasUpper).map(({axis:n,valueKind:r})=>({axis:n,valueKind:r}))}function Yc(e,t,n){const r=n.getPositionScale(nn(e.axis,n.yScaleType));if(!r)return t;const a=u.variableFor(e.axis,"lower"),o=u.variableFor(e.axis,"upper");return!t.hasVariable(a)||!t.hasVariable(o)?t:e.valueKind==="value"?Kc(t,r,a,o):Hc(e.axis,t,r,a,o)}function Kc(e,t,n,r){const a=e.getValues(n,{type:"numeric"}),o=e.getValues(r,{type:"numeric"}),s=e.size(),i=new Array(s),c=new Array(s);for(let l=0;l<s;l++){const d=a[l],m=o[l];u.isDefined(d)&&u.isDefined(m)?(i[l]=t.map(d),c[l]=t.map(m)):(i[l]=null,c[l]=null)}return e.addVariable(n,"numeric",i).addVariable(r,"numeric",c)}function Hc(e,t,n,r,a){const o=u.variableFor(e,"point");if(!n.bandwidth||!t.hasVariable(o))return t;const s=n.bandwidth,i=t.getValues(o,{type:"numeric"}),c=t.getValues(r,{type:"numeric"}),l=t.getValues(a,{type:"numeric"}),d=t.size(),m=new Array(d),f=new Array(d);for(let p=0;p<d;p++){const h=i[p],y=c[p],g=l[p];u.isDefined(h)&&u.isDefined(y)&&u.isDefined(g)?(m[p]=h+y*s,f[p]=h+g*s):(m[p]=null,f[p]=null)}return t.addVariable(r,"numeric",m).addVariable(a,"numeric",f)}function Wc(e,t){const n=e[t];return n?.kind==="position"?n:null}class zc extends Se{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),a=Bc({channels:r.positionChannels,data:t.data,mapping:t.mapping,yScaleType:t.yScaleType,getPositionScale:o=>Wc(n.scales,o)});return{...t,data:a}}}class Xc extends j{constructor(t){super(),this.registry=t}dependencies(t){return[t.layers,t.scales]}run(t){this.validateScaleTypeCompatibility(t);const n=new Map;for(const o of t.scales)n.set(o.scaledAesthetic,o);const r=this.collectValues(t.layers,n),a={};for(const[o,s]of n){const i=r.get(o)??[],c=this.registry.get(s.scaleType);a[o]=c.compile(s,i)}return a}validateScaleTypeCompatibility(t){const n=[];for(const r of t.scales){const{compatibleDataTypes:a}=this.registry.get(r.scaleType),o=Y(r.scaledAesthetic),s=t.layers.find(l=>u.isDefined(l.mapping[o]));if(!s)continue;const i=u.extractVariableName(s.mapping[o]);if(!u.isDefined(i)||!s.data.hasVariable(i))continue;const c=s.data.getType(i);if(a.includes(c)||n.push({code:"INCOMPATIBLE_TYPE",message:`Scale '${r.scaledAesthetic}' (${r.scaleType}) is incompatible with variable '${i}' (${c})`,aesthetic:o}),r.scaledAesthetic==="lineType"&&c!=="categorical"){const l=c==="temporal"?"Bucket the variable into categorical periods (e.g. quarter, year) first.":"Bin the variable into categorical buckets first.";n.push({code:"INCOMPATIBLE_TYPE",message:`Scale 'lineType' is discrete-only and cannot be mapped to ${c} variable '${i}'. ${l}`,aesthetic:o})}}if(n.length>0)throw new wa(n)}collectValues(t,n){const r=new Map;for(const a of t)for(const[o,s]of Object.entries(a.mapping)){const i=o,c=i==="y"?Ue(a.yScaleType):i;if(!Qs(c)||!n.has(c))continue;const l=this.resolveVariables(i,s,a.data);this.collectFromVariables(a.data,l,c,r)}return r}resolveVariables(t,n,r){if(t==="y"&&this.hasPositionAdjustedY(r))return[u.POSITION_VARIABLES.yMin,u.POSITION_VARIABLES.yMax];const a=u.extractVariableName(n);return!a||!r.hasVariable(a)?[]:[a]}hasPositionAdjustedY(t){return t.hasVariable(u.POSITION_VARIABLES.yMin)&&t.hasVariable(u.POSITION_VARIABLES.yMax)}collectFromVariables(t,n,r,a){if(n.length===0)return;let o=[];for(const i of n)o=o.concat(t.getValues(i));const s=a.get(r);a.set(r,s?s.concat(o):o)}}class Ye{createPositionScale(t,n){return{kind:"position",aesthetic:Y(t.scaledAesthetic),spec:t,...n}}createVisualScale(t,n){return{kind:"visual",aesthetic:Y(t.scaledAesthetic),spec:t,...n}}}class qc extends Ye{constructor(){super(...arguments),this.compatibleDataTypes=["numeric"]}compile(t,n){if(t.scaleType!=="continuous")throw new Error("ContinuousScale.compile received non-continuous spec");const r=pt(t.scaledAesthetic),a=this.computeDataDomain(n,t);return r?this.buildPositionScale(a,t):this.buildVisualScale(a,t)}computeDataDomain(t,n){let r=1/0,a=-1/0;for(const o of t)typeof o=="number"&&(o<r&&(r=o),o>a&&(a=o));return r===1/0?[0,0]:(n.zero&&(r>0&&(r=0),a<0&&(a=0)),[r,a])}createD3Scale(t,n,r){let a=[r.domainMin??t[0],r.domainMax??t[1]];const o=r.transform==="log"&&jc(a),s=o?q.scaleLog():r.transform==="sqrt"?q.scaleSqrt():q.scaleLinear();return r.nice&&!o&&(a=s.copy().domain(a).nice().domain()),s.domain([r.domainMin??a[0],r.domainMax??a[1]]).range(n).clamp(r.clamp)}buildPositionScale(t,n){const r=n.reverse?[1,0]:[0,1],a=this.createD3Scale(t,r,n);return this.createPositionScale(n,{map:a,domain:a.domain(),bandwidth:null,generateTicks:o=>o&&"count"in o?a.ticks(o.count):a.ticks()})}buildVisualScale(t,n){const r=n.range??[0,1],a=n.reverse?[r[1],r[0]]:r,o=this.createD3Scale(t,a,n);return this.createVisualScale(n,{map:o,domain:o.domain(),generateTicks:s=>s&&"count"in s?o.ticks(s.count):o.ticks()})}}const jc=e=>{const[t,n]=e;return t>0&&n>0||t<0&&n<0};class Qc extends Ye{constructor(){super(...arguments),this.compatibleDataTypes=["temporal"]}compile(t,n){if(t.scaleType!=="datetime")throw new Error("DatetimeScale.compile received non-datetime spec");const r=pt(t.scaledAesthetic),a=this.computeDataDomain(n);if(!r)throw new Error("Datetime scale is not supported for non-position aesthetics");return this.buildScale(a,t,this.collectInputDates(n))}collectInputDates(t){const n=new Set,r=[];for(const a of t){if(!(a instanceof Date))continue;const o=a.getTime();n.has(o)||(n.add(o),r.push(a))}return r.sort((a,o)=>a.getTime()-o.getTime()),r}computeDataDomain(t){let n=1/0,r=-1/0;for(const a of t){if(!(a instanceof Date))continue;const o=a.getTime();o<n&&(n=o),o>r&&(r=o)}return n===1/0?[]:[new Date(n),new Date(r)]}createD3Scale(t,n,r){const a=Zc(t)?t:[],o=q.scaleUtc().domain(a).range(n).clamp(r.clamp);if(r.nice&&o.nice(),u.isDefined(r.domainMin)||u.isDefined(r.domainMax)){const[s,i]=o.domain();s!==void 0&&i!==void 0&&o.domain([r.domainMin??s,r.domainMax??i])}return o}buildScale(t,n,r){const a=n.reverse?[1,0]:[0,1],o=this.createD3Scale(t,a,n),[s,i]=o.domain(),c=s&&i?r.filter(l=>l>=s&&l<=i):[];return this.createPositionScale(n,{map:o,domain:o.domain(),bandwidth:null,generateTicks:l=>l&&"atInputs"in l?c:l&&"interval"in l?s&&i?ai(s,i,l.interval):[]:o.ticks(l?.count)})}}const Zc=e=>e.length===2&&C(e[0])&&C(e[1]),pe={transform:"linear",reverse:!1,nice:!0,zero:!1,domainMin:null,domainMax:null},rr={size:[4,20],alpha:[.1,1],strokeWidth:[1,4]},We={domainMin:null,domainMax:null,nice:!1,reverse:!1},De={range:null,domain:null,padding:.1,reverse:!1},Jc={palette:{type:"default"}};class el extends Ye{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=pt(t.scaledAesthetic),a=this.computeDataDomain(n,t);return r?this.buildPositionScale(a,t):this.buildVisualScale(a,t)}computeDataDomain(t,n){if(n.domain!==null&&n.domain.length>0)return[...n.domain];const r=new Set,a=[];for(const o of t)r.has(o)||(r.add(o),a.push(o));return a}buildPositionScale(t,n){const r=t.map(String),a=n.padding??De.padding,o=n.reverse?[1,0]:[0,1],s=q.scaleBand().domain(r).range(o).paddingInner(a).paddingOuter(a/2),i=s.bandwidth()/2;return this.createPositionScale(n,{map:c=>(s(String(c))??0)+i,domain:t,bandwidth:s.bandwidth(),generateTicks:()=>[...t]})}buildVisualScale(t,n){const r=t.map(String),a=n.range&&n.range.length>0?q.scaleOrdinal().domain(r).range(n.range).unknown(n.range[0]):null;return this.createVisualScale(n,{map:o=>{const s=String(o);return a?a(s):s},domain:t,generateTicks:()=>t})}}class tl extends Ye{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:Y(t.scaledAesthetic),spec:t,map:n=>n,domain:[],generateTicks:()=>[]}}}const Va=["grey","red","orange","yellow","green","cyan","blue","purple","pink"],La=["cyan","pink","purple","red","orange","yellow","green","blue"],rn=["#B399FE","#FC7E91","#33B6E0","#FFC849","#25CDA5","#FA9B65","#D93C95","#845FD8","#3F8EEB","#58C8D8","#F35074","#6EA0DA"],B={red:"#E83562",orange:"#F38650",yellow:"#FBBC30",green:"#31FCB4",cyan:"#40F8FF",blue:"#279EFF",purple:"#B399FD",dark_purple:"#6D48D2",plum:"#C82184",pink:"#FC8497"},nl=[B.purple,B.pink,B.yellow,B.blue,B.red,B.cyan,B.orange,B.plum,B.green,B.dark_purple],N={green:"#B2DDC9",cyan:"#A2D5E2",blue:"#AAC4FF",purple:"#B2A4FF",plum:"#DCA8C7",pink:"#FFCCD3",red:"#FFADAD",orange:"#FFDEB4",yellow:"#FDF7C3"},rl=[N.green,N.purple,N.red,N.cyan,N.pink,N.blue,N.orange,N.plum,N.yellow],Gt={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"},al=[Gt.grey200,N.green,N.red,Gt.grey200],ar={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]}},k={cyan:"#22D3EE",pink:"#F377EF",purple:"#6528F7",red:"#FB2576",orange:"#FF9300",yellow:"#FBFF00",green:"#06FF00",blue:"#0079FF"},ze=[k.cyan,k.pink,k.purple,k.red,k.orange,k.yellow,k.green,k.blue],ol=[k.cyan,k.green,k.red,k.cyan],Xe={start:"#84D1FC",positive:"#84FC89",negative:"#FC8497",total:"#84D1FC"},sl=[Xe.start,Xe.positive,Xe.negative,Xe.total];function il(e,t="light",n){return((n!==void 0?ar[t][n]:void 0)??ar[t].default).map(a=>Gt[`${e}${a}`])}function cl(e){const t=ze.indexOf(k[e]);return t<=0?ze:[...ze.slice(t),...ze.slice(0,t)]}function ll(e,t){switch(e.type){case"default":return rn;case"graphy":return e.variant==="waterfall"?sl:nl;case"pastel":return e.variant==="waterfall"?al:rl;case"neon":return e.variant==="waterfall"?ol:cl(e.base);case"mono":return il(e.base,e.variant??"light",t);case"custom":return e.colors}}function ul(e,t){if(!e)return Jc.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 dl extends Ye{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),a=ll(t.palette,r.length),o=a.length>0?a:[...rn],s=q.scaleOrdinal().domain(r.map(String)).range(o).unknown(o[0]);return this.createVisualScale(t,{map:i=>s(String(i)),domain:r,generateTicks:()=>r})}computeDomain(t){const n=new Set,r=[];for(const a of t)n.has(a)||(n.add(a),r.push(a));return r}}class ml extends xe{constructor(){super("scale"),this.register("continuous",new qc),this.register("discrete",new el),this.register("datetime",new Qc),this.register("identity",new tl),this.register("palette",new dl)}}const Ea=e=>!("layers"in e),I={point:pl,line:fl,area:hl,bar:yl,rule:gl};function pl(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 fl(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 hl(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 yl(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 gl(e={}){return{type:"layer",geom:"rule",mapping:e.aes,stat:e.stat,params:e.params,position:e.position,yScaleType:e.yScaleType,transforms:e.transforms,interactive:e.interactive,dataLabels:e.dataLabels}}const an={identity:Sl,count:xl,smooth:bl,mean:vl};function bl(e){return{type:"smooth",method:e.method,order:e.order,bandwidth:e.bandwidth}}function Sl(){return{type:"identity"}}function xl(){return{type:"count"}}function vl(){return{type:"mean"}}const re={reshape:Al,filter:Tl,sort:wl,aggregate:Il,constant:Vl};function Al(e={}){return{type:"transform",transformType:"reshape",options:e}}function Tl(e){return{type:"transform",transformType:"filter",options:e}}function wl(e){return{type:"transform",transformType:"sort",options:e}}function Il(e){return{type:"transform",transformType:"aggregate",options:e}}function Vl(e){return{type:"transform",transformType:"constant",options:e}}const or="#%_ENCODED_%#",Ma=e=>{if(!e.startsWith(or))return e;try{const{value:t}=JSON.parse(e.slice(or.length));return typeof t=="string"?t:e}catch{return e}},Ll=({annotations:e,dataset:t,mapping:n})=>{const r=[],a=[],o=[],s=[],i=[],c=[],l=[],d=u.extractVariableName(n.x);for(const m of e??[])switch(m.type){case"difference-arrow":{const f=El(m,d,t);f!==null&&r.push(f);break}case"shape":{a.push(Ml(m));break}case"arrow":{o.push(kl(m));break}case"highlight":break;case"text":{s.push(Dl(m));break}case"sticker":{const f=Rl(m,d,t);f!==null&&i.push(f);break}case"tooltip":{const f=Cl(m,d,t);if(f===null)break;f.kind==="pinnedNumber"?c.push(f.value):l.push(f.value);break}default:{const f=m;throw new Error(`Unsupported annotation type: ${f.type}`)}}return{differenceArrows:r,shapes:a,freeformArrows:o,textAnnotations:s,stickers:i,pinnedNumbers:c,comments:l}},El=(e,t,n)=>{const r=st({dataset:n,input:e.start,anchorVariable:t}),a=st({dataset:n,input:e.end,anchorVariable:t});return r===null||a===null?null:{id:e.id,start:r,end:a,label:e.show,color:e.color??null,size:e.size,labelCrossPosition:e.labelPosition}},Ml=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}),Dl=e=>({id:e.id,content:e.content,x:e.x,y:e.y,width:e.width,backgroundColor:e.backgroundColor??null,backgroundColorStyle:e.backgroundColorStyle}),Rl=(e,t,n)=>{const r=st({dataset:n,input:e,anchorVariable:t});return r===null?null:{id:e.id,anchor:r,sticker:e.sticker}},Cl=(e,t,n)=>{const r=st({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}}},kl=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}),st=({dataset:e,input:t,anchorVariable:n})=>{if(!u.isDefined(t)||!u.isDefined(t.columnKey))return null;const r=_l(t,n,e);return r===null?null:{anchorValue:r,groupValue:Ma(t.columnKey)}},_l=(e,t,n)=>e.rowValue!==void 0?e.rowValue:t===null||!u.isDefined(e.rowIndex)||!n.hasVariable(t)?null:n.getValues(t)[e.rowIndex]??null,Da=["lilac","neon_pink","blackberry","sun","iceland","sunset","ultraviolet","purple","ice_cream","mint","cool","fresh"];function Ra(e){return{type:"config",config:e}}const Nl="#E5E5E5",Fl={x:"top",y:"left"},Ol=new Set(["pie","donut"]);function Pl(e){return Ra({legend:Yl(e.legend),axes:Hl(e.axes),headline:Wl(e),numberFormat:zl(e.appearance),content:Xl(e.content),appearance:Bl(e.appearance,e.themeOverrides)}).config}function Bl(e,t){const n=$l(e?.border),r=e?.hasRoundedCorners===!1?0:void 0,a=Gl(e,t),o={};return e?.textScale!==void 0&&(o.textScale=e.textScale),n!==void 0&&(o.border=n),r!==void 0&&(o.cornerRadius=r),a!==void 0&&(o.background=a),e?.highlightStyle!==void 0&&(o.highlightStyle=e.highlightStyle==="grey"?"desaturate":"dim"),Object.keys(o).length>0?o:void 0}function Gl(e,t){if(e?.backgroundModifier==="tint")return{type:"tinted"};const n=t?.graphBackground;if(typeof n=="string")return{type:"solid",color:n}}const Ul=e=>Da.includes(e);function $l(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:Nl,width:t};if(e.style==="preset")return e.color===void 0||!Ul(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 Yl(e){if(e)return{position:e.position}}function sr(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:Fl[e]}:void 0,...t?.tickDisplayMode?{labels:{mode:t.tickDisplayMode}}:void 0,...n!==void 0?{grid:{isVisible:n}}:void 0}}function Kl(e){return{...e.label!==void 0?{label:e.label}:void 0}}function Hl(e){if(e)return{x:sr("x",e.x,e.showGridLines),y:sr("y",e.y,e.showGridLines),...e.y2?{ySecondary:Kl(e.y2)}:void 0}}function Wl(e){const{headlineNumbers:t,options:n,type:r}=e,a=r!==void 0&&Ol.has(r)?n?.pieTotalPosition:void 0;if(t===void 0&&a===void 0)return;const o={};return t?.show!==void 0&&(o.show=t.show),t?.compareWith!==void 0&&(o.compareWith=t.compareWith),t?.size!==void 0&&(o.size=t.size),a!==void 0&&(o.show="total",o.position=a==="center"?"center":"above"),o}function zl(e){if(e?.numberFormat)return{decimals:e.numberFormat.decimalPlaces,abbreviation:e.numberFormat.abbreviation}}function Xl(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=ql(e.source);return n!==void 0&&(t.source=n),e.isSourceHidden!==void 0&&(t.isSourceVisible=!e.isSourceHidden),t}function ql(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 R={cartesian:(e={})=>({type:"coord",coordType:"cartesian",params:e}),flip:(e={})=>({type:"coord",coordType:"flip",params:e}),polar:(e={})=>({type:"coord",coordType:"polar",params:e})},jl={showDataLabels:!1,format:"absolute",showStackTotals:!1,showCategoryLabels:!1,labelSource:{variable:u.POSITION_VARIABLES.yRaw}},tt={stat:{type:"identity"},position:"identity",params:{size:8}},Tt={stat:{type:"identity"},position:"identity",params:{lineWidth:"auto",interpolate:"linear",missingValues:"gap"}},wt={stat:{type:"identity"},position:"stack",params:{lineWidth:"auto",interpolate:"linear",missingValues:"zero"}},It={stat:{type:"identity"},position:"dodge",params:{}},Le={stat:{type:"identity"},position:"identity",interactive:!1,params:{strokeWidth:1,lineType:"dashed",labelPosition:"start"}},Ae="primary";function Ql(e,t){const n={...jl};return e==="bar"&&t==="polar"&&(n.format="percentage"),n}function E(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 nt(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 G(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"discrete",range:t.range,domain:t.domain??null,padding:t.padding,reverse:t.reverse}}function Re(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"identity"}}function rt(e,t){return{type:"scale",scaledAesthetic:e,scaleType:"inferred",options:t}}function Ca(e,t={}){return{type:"scale",scaledAesthetic:e,scaleType:"palette",palette:t.palette}}const ae={x:Object.assign(e=>rt("x",e),{continuous:e=>E("x",e),discrete:e=>G("x",e),datetime:e=>nt("x",e),log:e=>E("x",{...e,transform:"log"}),sqrt:e=>E("x",{...e,transform:"sqrt"})}),y:Object.assign(e=>rt("y",e),{continuous:e=>E("y",e),discrete:e=>G("y",e),datetime:e=>nt("y",e),log:e=>E("y",{...e,transform:"log"}),sqrt:e=>E("y",{...e,transform:"sqrt"})}),ySecondary:Object.assign(e=>rt("ySecondary",e),{continuous:e=>E("ySecondary",e),discrete:e=>G("ySecondary",e),datetime:e=>nt("ySecondary",e),log:e=>E("ySecondary",{...e,transform:"log"}),sqrt:e=>E("ySecondary",{...e,transform:"sqrt"})}),color:{continuous:e=>E("color",e),discrete:e=>G("color",e),palette:e=>Ca("color",e)},size:{continuous:e=>E("size",e),discrete:e=>G("size",e),identity:e=>Re("size",e)},alpha:{continuous:e=>E("alpha",e),discrete:e=>G("alpha",e),identity:e=>Re("alpha",e)},strokeWidth:{continuous:e=>E("strokeWidth",e),discrete:e=>G("strokeWidth",e),identity:e=>Re("strokeWidth",e)},lineType:{discrete:e=>G("lineType",e),identity:e=>Re("lineType",e)}},_="key",W="value",ir=u.prefixInternalVariable("lineSeriesLabel"),cr=u.prefixInternalVariable("barSeriesLabel"),it=u.prefixInternalVariable("constantY"),Zl=(e,t,n,r)=>ou[t](e,n,r),on=e=>{const{numeric:t,categorical:n,temporal:r}=e.groupVariableNamesByType();return u.isDefined(r[0])?r[0]:u.isDefined(n[0])?n[0]:u.isDefined(t[0])?t[0]:""},sn=e=>{const t=on(e),{numeric:n}=e.groupVariableNamesByType(),r=n.filter(o=>o!==t);return r.length<=1?{dataset:e,mapping:{x:t,y:r[0]??""},seriesVariables:r}:{dataset:e.reshapeFromWideToLong({keep:[t],keyName:_,valueName:W}),mapping:{x:t,y:W,color:_},seriesVariables:r}},cn=e=>{const t=e.appearance?.seriesStyles;if(!t||e.seriesVariables.length===0)return{mapping:{},scales:[]};if(!e.seriesVariables.some(a=>u.isDefined(t[a]?.lineStyle)))return{mapping:{},scales:[]};if(e.seriesVariables.length===1){const a=e.seriesVariables[0];if(!a)return{mapping:{},scales:[]};const o=t[a]?.lineStyle;return o?{mapping:{lineType:{value:o}},scales:[]}:{mapping:{},scales:[]}}const r=e.seriesVariables.map(a=>t[a]?.lineStyle??"solid");return{mapping:{lineType:_},scales:[ae.lineType.discrete({domain:e.seriesVariables,range:r})]}},Jl=e=>{const{categorical:t,temporal:n,numeric:r}=e.groupVariableNamesByType(),a=r[0];if(!u.isDefined(a))throw new Error("No first numeric variable found");const o=r.slice(1);return o.length===0?{dataset:e.addConstantVariable(it,"categorical",""),mapping:{x:a,y:it,label:t[0]}}:o.length===1?{dataset:e,mapping:{x:a,y:o[0]??"",label:t[0]}}:{dataset:e.reshapeFromWideToLong({keep:[a,...t,...n],keyName:_,valueName:W}),mapping:{x:a,y:W,label:t[0],color:_}}},eu=e=>{const{categorical:t,temporal:n,numeric:r}=e.groupVariableNamesByType();let a,o;if(u.isDefined(t[0])&&u.isDefined(r[0]))a=t[0],o=r[0];else if(u.isDefined(n[0])&&u.isDefined(r[0]))a=n[0],o=r[0];else if(u.isDefined(r[0])&&u.isDefined(r[1]))a=r[0],o=r[1];else throw new Error("No label or value variable found");return{x:"",y:o,color:a}},ka=(e,t,n)=>{const{dataset:r,mapping:a,seriesVariables:o}=sn(e.dataset),s=cn({appearance:n,seriesVariables:o}),i=[I.line({params:{lineWidth:t?.lineThickness,interpolate:t?.isSmoothLine?"catmull-rom":"linear",missingValues:t?.missingValues}})];return t?.showPoints&&i.push(I.point({params:{size:_a(t.pointSize)},interactive:!1})),{dataset:r,layers:i,coords:R.cartesian(),mapping:{...a,...s.mapping},scales:s.scales,seriesVariables:o}},tu=(e,t,n)=>{const{dataset:r,mapping:a,seriesVariables:o}=sn(e.dataset),s=cn({appearance:n,seriesVariables:o}),i=[I.area({position:"stack",params:{lineWidth:t?.lineThickness,interpolate:t?.isSmoothLine?"catmull-rom":"linear",missingValues:t?.missingValues}})];return t?.showPoints&&i.push(I.point({params:{size:_a(t.pointSize)},position:"stack",interactive:!1})),{dataset:r,layers:i,coords:R.cartesian(),mapping:{...a,...s.mapping},scales:s.scales,seriesVariables:o}},ee=(e,t,n,r,a)=>{const{dataset:o,mapping:s,seriesVariables:i}=sn(e.dataset),c=[];if(r?.sortBars){const l=u.extractVariableName(s.y);l!==null&&l!==""&&c.push(re.sort({variableName:l,direction:"desc"}))}if(!a?.useSingleColorForBars){const l=on(e.dataset),{numeric:d}=e.dataset.groupVariableNamesByType();d.filter(f=>f!==l).length===1&&e.dataset.getType(l)==="categorical"&&(s.color=l)}return{dataset:o,layers:[I.bar({position:t})],coords:n,mapping:s,scales:[],transforms:c,seriesVariables:i}},lr=(e,t)=>({dataset:e.dataset,layers:[I.bar({position:"fill"})],coords:R.polar({theta:"y",innerRadius:t==="donut"?.55:0}),mapping:eu(e.dataset),scales:[],seriesVariables:[]}),nu=e=>{const{dataset:t,mapping:n}=Jl(e.dataset);return{dataset:t,layers:[I.point()],coords:R.cartesian(),mapping:n,scales:[],seriesVariables:[]}},ru=e=>{const{numeric:t,categorical:n}=e.dataset.groupVariableNamesByType(),r=t[0];if(!u.isDefined(r))throw new Error("No first numeric variable found");const o=u.isDefined(t[1])?e.dataset:e.dataset.addConstantVariable(it,"categorical",""),s={x:r,y:t[1]??it,size:t[2],label:n[0]},i=[];return u.isDefined(s.size)&&i.push(ae.size.continuous()),{dataset:o,layers:[I.point()],coords:R.cartesian(),mapping:s,scales:i,seriesVariables:[]}},Vt=(e,t,n)=>{const r=n?.seriesStyles?.[e]?.lineStyle;return I.line({transforms:[re.constant({variableName:ir,type:"categorical",value:e})],aes:{y:e,color:ir,...r?{lineType:{value:r}}:{}},...t?{yScaleType:"secondary"}:void 0})},au=(e,t,n)=>{const{numeric:r,categorical:a,temporal:o}=e.dataset.groupVariableNamesByType(),s=on(e.dataset),i=[...a,...o],c=r.filter(g=>g!==s),l=t?.comboType??"grouped-bars",d=l==="lines";if(c.length===1)return d?ka(e,t,n):ee(e,"dodge",R.cartesian(),t,n);const m=e.axes?.hasDualYAxis===!0,f=d?[]:c.slice(0,-1),p=d?c:c.slice(-1),h=[],y=[];if(f.length>0){const g=l==="stacked-bars"?"stack":"dodge",S=f.length===1?f[0]:null;u.isDefined(S)?h.push(I.bar({transforms:[re.constant({variableName:cr,type:"categorical",value:S})],aes:{y:S,color:cr},position:g})):h.push(I.bar({transforms:[re.reshape({keep:i,reshape:f,keyName:_,valueName:W})],aes:{y:W,color:_},position:g}))}if(d&&p.length>=2){const g=m?p.slice(0,-1):p,S=g.length===1?g[0]:null;if(u.isDefined(S))h.push(Vt(S,!1,n));else{const b=cn({appearance:n,seriesVariables:g});h.push(I.line({transforms:[re.reshape({keep:i,reshape:g,keyName:_,valueName:W})],aes:{y:W,color:_,...b.mapping}})),y.push(...b.scales)}if(m){const b=p[p.length-1];u.isDefined(b)&&h.push(Vt(b,!0,n))}}else for(const g of p)h.push(Vt(g,m,n));return{dataset:e.dataset,layers:h,coords:R.cartesian(),mapping:{x:s},scales:y,seriesVariables:c}},_a=(e="auto")=>e==="auto"?tt.params.size:e,Ee=e=>()=>{throw new Error(`Unsupported graph type: ${e}`)},ou={line:(e,t,n)=>ka(e,t,n),areaStacked:(e,t,n)=>tu(e,t,n),bar:(e,t,n)=>ee(e,"dodge",R.flip(),t,n),barStacked:(e,t,n)=>ee(e,"stack",R.flip(),t,n),barStackedFill:(e,t,n)=>ee(e,"fill",R.flip(),t,n),column:(e,t,n)=>ee(e,"dodge",R.cartesian(),t,n),columnStacked:(e,t,n)=>ee(e,"stack",R.cartesian(),t,n),columnStackedFill:(e,t,n)=>ee(e,"fill",R.cartesian(),t,n),pie:e=>lr(e,"pie"),donut:e=>lr(e,"donut"),scatter:e=>nu(e),bubble:e=>ru(e),combo:(e,t,n)=>au(e,t,n),funnel:Ee("funnel"),heatmap:Ee("heatmap"),waterfall:Ee("waterfall"),mekko:Ee("mekko"),table:Ee("table")},Na=["key",u.prefixInternalVariable("lineSeriesLabel"),u.prefixInternalVariable("barSeriesLabel")];function su(e){const t=e.annotations??[],n=iu(e.mapping),r=uu(e.convertedDataset,e.layers),a=[];for(const o of t){if(o.type!=="highlight")continue;const s=cu({annotation:o,rowIdentityVariable:n,dataset:e.dataset,compiledVariableNames:r});s!==null&&a.push({type:"highlight",id:o.id,predicate:s,scope:o.highlight})}return a}function iu(e){const t=u.extractVariableName(e.x);return t!==null&&t!==""?t:u.extractVariableName(e.color)}function cu({annotation:e,rowIdentityVariable:t,dataset:n,compiledVariableNames:r}){switch(e.highlight){case"x-value":return ur(e,t,n);case"series":return dr(e,r);case"data-point":{const a=ur(e,t,n),o=dr(e,r);return a===null&&o===null?null:a===null?o:o===null?a:{and:[a,o]}}}}function ur(e,t,n){if(t===null)return null;const r=du(e,t,n);return r===null?null:{variable:t,eq:r}}function dr(e,t){if(!lu(t))return null;const n=e.columnKey;return u.isDefined(n)?{or:Na.map(r=>({variable:r,eq:n}))}:null}function lu(e){return Na.some(t=>e.includes(t))}function uu(e,t){const n=[...e.getVariableNames()];for(const r of t)for(const a of r.transforms??[])a.transformType==="reshape"?n.push(a.options.keyName??_):a.transformType==="constant"&&n.push(a.options.variableName);return n}function du(e,t,n){return e.rowValue!==void 0?e.rowValue:!u.isDefined(e.rowIndex)||!n.getVariableNames().includes(t)?null:n.getValues(t)[e.rowIndex]??null}function mu(e,t,n){const{theme:r,customPalettes:a}=n;if(a&&e&&a[e])return{type:"custom",id:e};if(e?.startsWith("preset:pastel"))return{type:"pastel",variant:Lt(t)};if(e?.startsWith("preset:graphy"))return{type:"graphy",variant:Lt(t)};const i="preset:mono:";if(e?.startsWith(i)){const l=e.slice(i.length);if(pu(l))return{type:"mono",base:l,variant:r}}const c="preset:neon:";if(e?.startsWith(c)){const l=e.slice(c.length);if(fu(l))return{type:"neon",base:l,variant:Lt(t)}}return{type:"default"}}function Lt(e){if(e==="waterfall")return"waterfall"}function pu(e){return Va.includes(e)}function fu(e){return La.includes(e)}function hu(e,t,n,r={}){const a=[];a.push(mr("x",t?.x)),a.push(mr("y",t?.y));const o=mu(n?.paletteId,e,r);return a.push(ae.color.palette({palette:o})),a}function mr(e,t){return t?.scaleType==="logarithmic"||t?.min!==void 0||t?.max!==void 0?t.scaleType==="logarithmic"?ae[e].log({domainMin:t.min??void 0,domainMax:t.max??void 0}):ae[e]({domainMin:t.min??void 0,domainMax:t.max??void 0}):ae[e]()}const yu=new Set(["column","columnStacked","columnStackedFill","bar","barStacked","barStackedFill","line","areaStacked","scatter","bubble","funnel","combo"]),gu=new Set(["column","columnStacked","columnStackedFill","bar","barStacked","barStackedFill","line","areaStacked","combo"]);function bu(e,t,n){const r=t.type??"column",a={dataset:e,axes:t.axes},o=Zl(a,r,t.options??void 0,t.appearance??void 0);return{data:o.dataset,mapping:o.mapping,layers:Su(r,t,o.layers,o.coords,o.mapping,o.seriesVariables),scales:[...hu(r,t.axes,t.appearance,n),...o.scales],transforms:o.transforms??[],highlights:su({annotations:t.annotations,dataset:e,mapping:o.mapping,convertedDataset:o.dataset,layers:o.layers}),annotations:Ll({annotations:t.annotations,dataset:e,mapping:o.mapping}),coords:o.coords,config:Pl(t)}}function Su(e,t,n,r,a,o){const s=wu(t.dataLabels),i=s===void 0?n:n.filter(l=>l.interactive!==!1).map(l=>({...l,dataLabels:{...s,...l.dataLabels}})),c=t.axes?.hasDualYAxis??!1;return[...i,...xu({type:e,trendline:t.referenceLines?.trendline,coords:r}),...vu({type:e,hasDualYAxis:c,goalLine:t.referenceLines?.goalLine,coords:r}),...Tu({type:e,hasDualYAxis:c,averageLine:t.referenceLines?.averageLine,coords:r,mapping:a,seriesVariables:o})]}function xu({type:e,trendline:t,coords:n}){return t===void 0?[]:yu.has(e)?n.coordType==="polar"?[]:[I.line({aes:{lineType:{value:"dashed"}},stat:an.smooth({method:t}),interactive:!1})]:[]}function vu({type:e,hasDualYAxis:t,goalLine:n,coords:r}){if(!Au(n))return[];if(r.coordType==="polar")return[];const a=r.coordType==="flip"?"end":"start";return[I.rule({aes:{y:{value:n.target}},params:{labelPosition:a,label:n.label??"Goal"},yScaleType:e==="combo"&&t?"secondary":"primary",interactive:!1})]}function Au(e){return e!==void 0&&Number.isFinite(e.target)}function Tu({type:e,hasDualYAxis:t,averageLine:n,coords:r,mapping:a,seriesVariables:o}){if(n===void 0)return[];if(!gu.has(e))return[];if(r.coordType==="polar")return[];const s=Ma(n.columnKey);if(!o.includes(s))return[];const i=a.color===_,c=i?W:s,l=i?[re.filter({variableName:_,operator:"eq",value:s})]:[];return[I.rule({aes:{y:c,color:void 0,group:void 0,lineType:void 0},stat:an.mean(),transforms:l,params:{label:"Average",labelPosition:r.coordType==="flip"?"end":"start"},yScaleType:e==="combo"&&t?"secondary":"primary",interactive:!1})]}function wu(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 Et={color:null,size:"small",labelCrossPosition:.5},fe={kind:"rectangle",zOrder:"foreground",fillColor:"transparent",fillOpacity:1,strokeWidth:1,strokeColor:null},pr={backgroundColor:null,backgroundColorStyle:"opaque"},he={color:null,thickness:"medium",startArrowheadStyle:"none",endArrowheadStyle:"line-arrow",lineStyle:"solid",hasStickerStyle:!1},Iu=(e,t)=>({differenceArrows:(e?.differenceArrows??[]).map(n=>Mu(n,t)),shapes:(e?.shapes??[]).map(ku),freeformArrows:(e?.freeformArrows??[]).map(_u),textAnnotations:(e?.textAnnotations??[]).map(Eu),stickers:(e?.stickers??[]).map(n=>Du(n,t)),pinnedNumbers:(e?.pinnedNumbers??[]).map(n=>Ru(n,t)),comments:(e?.comments??[]).map(n=>Cu(n,t)),custom:(e?.custom??[]).map(n=>Vu(n,t))}),Vu=(e,t)=>({id:e.id??crypto.randomUUID(),type:e.type,coordinates:e.coordinates.map(n=>Lu(n,t)),params:e.params??{},zOrder:e.zOrder??null}),Lu=(e,t)=>"observation"in e?{observation:ge(e.observation,t)}:e,Eu=e=>({id:e.id??crypto.randomUUID(),content:e.content,x:e.x,y:e.y,width:e.width,backgroundColor:e.backgroundColor??pr.backgroundColor,backgroundColorStyle:e.backgroundColorStyle??pr.backgroundColorStyle}),Mu=(e,t)=>({id:e.id??crypto.randomUUID(),start:ge(e.start,t),end:ge(e.end,t),label:e.label,color:e.color??Et.color,size:e.size??Et.size,labelCrossPosition:e.labelCrossPosition??Et.labelCrossPosition}),ge=(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}},Du=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:ge(e.anchor,t),sticker:e.sticker}),Ru=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:ge(e.anchor,t)}),Cu=(e,t)=>({id:e.id??crypto.randomUUID(),anchor:ge(e.anchor,t),content:e.content}),ku=e=>({id:e.id??crypto.randomUUID(),kind:e.kind??fe.kind,zOrder:e.zOrder??fe.zOrder,x:e.x,y:e.y,width:e.width,height:e.height,fillColor:e.fillColor??fe.fillColor,fillOpacity:e.fillOpacity??fe.fillOpacity,strokeWidth:e.strokeWidth??fe.strokeWidth,strokeColor:e.strokeColor??fe.strokeColor}),_u=e=>({id:e.id??crypto.randomUUID(),start:e.start,end:e.end,color:e.color??he.color,thickness:e.thickness??he.thickness,startArrowheadStyle:e.startArrowheadStyle??he.startArrowheadStyle,endArrowheadStyle:e.endArrowheadStyle??he.endArrowheadStyle,lineStyle:e.lineStyle??he.lineStyle,hasStickerStyle:e.hasStickerStyle??he.hasStickerStyle}),Nu={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 Fu(e){return le.merge({},Nu,e)}const Ou={xLimits:null,yLimits:null},Mt={theta:"x",startAngle:0,innerRadius:0};function Pu(e){const t=e??{type:"coord",coordType:"cartesian"},n=_r({},Ou,t.params??{});switch(t.coordType){case"cartesian":case"flip":return{...t,params:n};case"polar":return{...t,params:{...n,theta:t.params?.theta??Mt.theta,startAngle:t.params?.startAngle??Mt.startAngle,innerRadius:t.params?.innerRadius??Mt.innerRadius}}}}function Bu(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 Gu="linear",Uu=3,$u=.3;function Te(e,t){const n=e??t,r=typeof n=="string"?n:n.type;if(r==="smooth"){const a=typeof n=="string"?void 0:n;return{type:"smooth",method:a?.method??Gu,order:a?.order??Uu,bandwidth:a?.bandwidth??$u}}return{type:r}}function Yu(e,t,n){if(!Wu(n))return zu(e,t,n);switch(n.geom){case"point":return Xu(e,t,n);case"line":return qu(e,t,n);case"area":return ju(e,t,n);case"bar":return Qu(e,t,n);case"rule":return Zu(e,t,n)}}function Ku(e,t,n){const r=n.map(a=>Yu(e,t,a));return Ju(r)}const Hu=(e,t,n)=>n.label!==void 0?n.label:ed(e,t,n),Wu=e=>ga(e.geom);function zu(e,t,n){const r=n.position??"identity";return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Te(n.stat,"identity"),position:r,yScaleType:n.yScaleType??Ae,params:n.params??{},transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:we(e,n,r,t)}}const we=(e,t,n,r)=>{const a={...e,...t.mapping},o=Hu(t.geom,n,a);return{...Ql(t.geom,r),...t.dataLabels,labelSource:o}};function Xu(e,t,n){const r=n.position??tt.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Te(n.stat,tt.stat.type),position:r,yScaleType:n.yScaleType??Ae,params:le.merge({},tt.params,n.params),transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:we(e,n,r,t)}}function qu(e,t,n){const r=n.position??Tt.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Te(n.stat,Tt.stat.type),position:r,yScaleType:n.yScaleType??Ae,params:le.merge({},Tt.params,n.params),transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:we(e,n,r,t)}}function ju(e,t,n){const r=le.merge({},wt.params,n.params);r.missingValues==="gap"&&(r.missingValues="zero");const a=n.position??wt.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Te(n.stat,wt.stat.type),position:a,yScaleType:n.yScaleType??Ae,params:r,transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:we(e,n,a,t)}}function Qu(e,t,n){const r=n.position??It.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Te(n.stat,It.stat.type),position:r,yScaleType:n.yScaleType??Ae,params:{...It.params,...n.params},transforms:n.transforms??[],interactive:n.interactive??!0,dataLabels:we(e,n,r,t)}}function Zu(e,t,n){const r=n.position??Le.position;return{id:n.id??crypto.randomUUID(),type:n.type,geom:n.geom,mapping:n.mapping??{},stat:Te(n.stat,Le.stat.type),position:n.position??Le.position,yScaleType:n.yScaleType??Ae,params:le.merge({},Le.params,n.params),transforms:n.transforms??[],interactive:n.interactive??Le.interactive,dataLabels:we(e,n,r,t)}}const Ju=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=u.extractConstantValue(n.mapping.y);if(!w(r))return n;const a=Math.min(1,Math.max(0,r));return{...n,mapping:{...n.mapping,y:{value:a}}}})},ed=(e,t,n)=>{if(e==="point"){const r=u.extractVariableName(n.size);if(r!==null)return{variable:r}}return $e(t,n)};function td(e,...t){return e?t.includes(e.geom):!1}function nd(e,t){return e.find(n=>n.id===t)}function Fa(e,...t){return e.find(n=>t.includes(n.geom))}function rd(e,t,n){const r=e.layers.findIndex(o=>o.id===t);if(r===-1)return e;const a=e.layers.map((o,s)=>s===r?n:o);return{...e,layers:a}}const Oa={x:"position",y:"position",ySecondary:"position",color:"color-range",size:"continuous-range",alpha:"continuous-range",strokeWidth:"continuous-range",lineType:"discrete-only"},ad={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 Pa(e,t,n,r,a){switch(e.scaleType){case"inferred":{const o=id(e,t,n,r);return Pa(o,t,n,r,a)}case"continuous":{const o=Oa[e.scaledAesthetic],s=o==="continuous-range"&&e.scaledAesthetic in rr?rr[e.scaledAesthetic]:null,i=e.scaledAesthetic==="size"&&o==="continuous-range"?"sqrt":pe.transform;return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,transform:e.transform??i,reverse:e.reverse??pe.reverse,nice:e.nice??pe.nice,zero:e.zero??pe.zero,clamp:e.clamp??o!=="position",domainMin:e.domainMin??pe.domainMin,domainMax:e.domainMax??pe.domainMax,range:e.range??s??null}}case"datetime":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,domainMin:e.domainMin??We.domainMin,domainMax:e.domainMax??We.domainMax,nice:e.nice??We.nice,reverse:e.reverse??We.reverse,clamp:e.clamp??!1};case"discrete":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,range:e.range??De.range,domain:e.domain??De.domain,padding:e.padding??De.padding,reverse:e.reverse??De.reverse};case"palette":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType,palette:ul(e.palette,a)};case"identity":return{type:e.type,scaledAesthetic:e.scaledAesthetic,scaleType:e.scaleType};default:{const o=e;throw new Error(`Unknown scale type: ${o.scaleType}`)}}}function od(e,t,n,r,a,o){const s=ld(t,n),i=ud(s),c=new Map;for(const d of i)c.set(d.scaledAesthetic,d);const l=[...c.values()].map(d=>Pa(d,e,n,r,o));return a.coordType==="polar"?sd(l):l}const sd=e=>e.map(t=>t.scaleType==="discrete"?{...t,padding:0}:t);function id(e,t,n,r){const a=Y(e.scaledAesthetic),o=e.scaledAesthetic==="ySecondary"?cd(n,r):r[a],s=Fa(n,"bar");if(e.scaledAesthetic==="x"&&s)return G(e.scaledAesthetic,e.options);if(s&&e.scaledAesthetic===(s.yScaleType==="secondary"?"ySecondary":"y")){const m=e.options,f=s.position==="fill";return E(e.scaledAesthetic,{...m,zero:!0,...f&&{nice:!1}})}const i=u.extractVariableName(o);if(!u.isDefined(i)||!t.hasVariable(i))return E(e.scaledAesthetic,e.options);const c=t.getType(i),l=Oa[e.scaledAesthetic];switch(ad[c][l]){case"discrete":return G(e.scaledAesthetic,e.options);case"datetime":return nt(e.scaledAesthetic,e.options);case"continuous":return E(e.scaledAesthetic,e.options);case"identity":default:return Re(e.scaledAesthetic)}}function cd(e,t){const n=e.find(r=>r.yScaleType==="secondary");return n?n.mapping.y??t.y:t.y}function ld(e,t){return!t.some(a=>a.yScaleType==="secondary")||e.some(a=>a.scaledAesthetic==="ySecondary")?e:[...e,rt("ySecondary")]}function ud(e){return e.some(n=>n.scaledAesthetic==="color")?e:[...e,Ca("color")]}function fr(e,t){const n=Pu(e.coords),r=Ku(e.mapping,n.coordType,e.layers),a=od(e.data,e.scales,r,e.mapping,n,t),o=Fu(e.config),s=Bu(e.highlights,r),i=Iu(e.annotations,r);return{data:e.data,mapping:e.mapping,layers:r,scales:a,transforms:e.transforms,highlights:s,annotations:i,coords:n,config:o}}class Ba{compile({input:t,dataset:n,ctx:r}){const a=r.customPalettes??{};return Ea(t)?fr(bu(n,t,r),a):fr({...t,data:n},a)}}class dd{constructor(t){this.registry=t}compute(t,n){return this.registry.get(t.type).compute({data:n.data,mapping:n.mapping,spec:t,xScaleIsDiscrete:n.xScaleIsDiscrete})}}class yt{compute(t){return t.data.size()===0?{data:t.data,mapping:{}}:this.computeStat(t)}}class md extends yt{constructor(){super(...arguments),this.type="count",this.computedVariables=new Set(["y"])}computeStat({data:t,mapping:n}){const r=u.extractVariableName(n.x);if(!u.isDefined(r))throw new Error("'x' variable is required for 'count' stat");if(u.extractVariableName(n.y)!==null)throw new Error("Cannot map 'y' variable together with 'count' stat");const o=[...new Set([r,...jt(t,n)])];return{data:t.groupBy(...o).rollup({[u.STAT_VARIABLES.count]:{variableName:r,aggregation:"count"}}),mapping:{y:u.STAT_VARIABLES.count}}}}class pd extends yt{constructor(){super(...arguments),this.type="identity",this.computedVariables=new Set}computeStat({data:t}){return{data:t,mapping:{}}}}class fd extends yt{constructor(){super(...arguments),this.type="mean",this.computedVariables=new Set(["y"])}computeStat({data:t,mapping:n}){const r=u.extractVariableName(n.y);if(!u.isDefined(r))throw new Error("'y' variable is required for 'mean' stat");return{data:t.rollup({[u.STAT_VARIABLES.mean]:{variableName:r,aggregation:"mean"}}),mapping:{y:u.STAT_VARIABLES.mean}}}}const hd=2,Ga=1440*60*1e3;class yd extends yt{constructor(){super(...arguments),this.type="smooth",this.computedVariables=new Set}computeStat({data:t,mapping:n,spec:r,xScaleIsDiscrete:a}){if(r.type!=="smooth")throw new Error(`SmoothStat received a spec of type '${r.type}'`);const o=u.extractVariableName(n.x),s=u.extractVariableName(n.y);if(!u.isDefined(o))throw new Error("'x' variable is required for 'smooth' stat");if(!u.isDefined(s))throw new Error("'y' variable is required for 'smooth' stat");const i=t.getType(o),c=t.getType(s);if(c!=="numeric")throw new Error(`'smooth' stat requires a numeric 'y' (got '${c}' for variable '${s}')`);const l=jt(t,n),d=Td(o,i,s,l,t);return l.length===0?hr({data:t,xVariable:o,xType:i,yVariable:s,spec:r,output:d,groupObservation:{},xScaleIsDiscrete:a}):t.groupBy(...l).forEach(m=>{const f=wd(m,l);hr({data:m,xVariable:o,xType:i,yVariable:s,spec:r,output:d,groupObservation:f,xScaleIsDiscrete:a})}),{data:d.build(),mapping:{}}}}const hr=({data:e,xVariable:t,xType:n,yVariable:r,spec:a,output:o,groupObservation:s,xScaleIsDiscrete:i})=>{const{observations:c,temporalOrigin:l}=gd({data:e,xVariable:t,yVariable:r,xType:n});c.length<hd||(i?Ad({observations:c,spec:a,output:o,groupObservation:s}):xd({observations:c,xType:n,temporalOrigin:l,spec:a,output:o,groupObservation:s}))},gd=({data:e,xVariable:t,yVariable:n,xType:r})=>{const a=e.getValues(t),o=e.getValues(n,{type:"numeric"}),s=r==="temporal"?bd(a):null,i=[],c=new Map;for(let l=0;l<a.length;l++){const d=a[l],m=o[l];if(!u.isDefined(d)||!u.isDefined(m)||!Number.isFinite(m))continue;const f=Sd({xValue:d,xType:r,categoryRank:c,temporalOrigin:s});f!==null&&i.push({x:f,y:m,originalX:d})}return{observations:i,temporalOrigin:s}},bd=e=>{let t=null;for(const n of e){if(!C(n))continue;const r=n.getTime();(t===null||r<t)&&(t=r)}return t},Sd=({xValue:e,xType:t,categoryRank:n,temporalOrigin:r})=>{switch(t){case"numeric":return!w(e)||!Number.isFinite(e)?null:e;case"temporal":{if(!C(e))return null;const a=e.getTime();return r===null?a:(a-r)/Ga+1}case"categorical":{if(!Pe(e))return null;const a=n.get(e);if(a!==void 0)return a;const o=n.size+1;return n.set(e,o),o}default:{const a=t;throw new Error(`Unexpected xType: ${a}`)}}},xd=({observations:e,xType:t,temporalOrigin:n,spec:r,output:a,groupObservation:o})=>{const s=Ua(r,e);for(const[i,c]of s){if(!Number.isFinite(i)||!Number.isFinite(c))continue;const l=t==="temporal"?vd(i,n):i;a.push({x:l,y:c,groupObservation:o})}},vd=(e,t)=>t===null?new Date(e):new Date((e-1)*Ga+t),Ad=({observations:e,spec:t,output:n,groupObservation:r})=>{const a=new Map;for(const i of e)a.has(i.x)||a.set(i.x,i.originalX);const o=[...a.keys()].sort((i,c)=>i-c);if(t.method==="loess"){const i=Ua(t,e),c=new Map;for(const[l,d]of i)Number.isFinite(d)&&(c.has(l)||c.set(l,d));for(const l of o){const d=c.get(l),m=a.get(l);d===void 0||m===void 0||n.push({x:m,y:d,groupObservation:r})}return}const s=$a(t,e);for(const i of o){const c=a.get(i),l=s.predict(i);c===void 0||!Number.isFinite(l)||n.push({x:c,y:l,groupObservation:r})}},Ua=(e,t)=>e.method==="loess"?J.regressionLoess().x(r=>r.x).y(r=>r.y).bandwidth(e.bandwidth)(t):$a(e,t),$a=(e,t)=>{const n=a=>a.x,r=a=>a.y;switch(e.method){case"linear":return J.regressionLinear().x(n).y(r)(t);case"exponential":return J.regressionExp().x(n).y(r)(t);case"logarithmic":return J.regressionLog().x(n).y(r)(t);case"quadratic":return J.regressionQuad().x(n).y(r)(t);case"power":return J.regressionPow().x(n).y(r)(t);case"polynomial":return J.regressionPoly().x(n).y(r).order(e.order)(t);case"loess":throw new Error("'loess' does not expose a 'predict' function")}},Td=(e,t,n,r,a)=>{const o=[],s=[],i=Object.fromEntries(r.map(c=>[c,[]]));return{push:({x:c,y:l,groupObservation:d})=>{o.push(c),s.push(l);for(const m of r)i[m]?.push(d[m]??null)},build:()=>{const c={[e]:{type:t,values:o,valueFormat:a.getValueFormat(e)},[n]:{type:"numeric",values:s,valueFormat:a.getValueFormat(n)}};for(const l of r)c[l]={type:a.getType(l),values:i[l]??[],valueFormat:a.getValueFormat(l)};return new u.Dataset(c)}}},wd=(e,t)=>{const n={};for(const r of t){const a=e.getValues(r);n[r]=a[0]??null}return n};class Id extends xe{constructor(){super("stat"),this.register("identity",new pd),this.register("count",new md),this.register("smooth",new yd),this.register("mean",new fd)}}const Vd=({layer:e})=>{if(e.position==="stack")return;const t=u.extractVariableName(e.mapping.y);if(t===null)return;let n=0,r=0;for(const a of e.data){const o=a[t];w(o)&&(n+=o,r+=Math.abs(o))}return{grandTotal:n,absoluteGrandTotal:r}},Ld=({layer:e})=>{if(e.position!=="stack")return;const t=u.extractVariableName(e.mapping.x);if(t===null||!e.data.hasVariable(u.POSITION_VARIABLES.yMin)||!e.data.hasVariable(u.POSITION_VARIABLES.yMax))return;const n=new Map;for(const a of e.data){const o=a[t],s=se(a),i=$(a),c=_e(a),l=ye(a),d=ia(a);if(!u.isDefined(o)||!u.isDefined(s)||!u.isDefined(i)||!u.isDefined(c)||!u.isDefined(l)||!u.isDefined(d))continue;const m=d>=0;if(Math.abs(d)===0)continue;const p=Jt(a,t),h={yMin:s,yMax:i},y=n.get(p);if(y===void 0){n.set(p,{total:d,topPositive:m?h:null,bottomNegative:m?null:h,anchorXMin:c,anchorXMax:l});continue}y.total+=d,m?(y.topPositive===null||i>y.topPositive.yMax)&&(y.topPositive=h):(y.bottomNegative===null||s<y.bottomNegative.yMin)&&(y.bottomNegative=h)}const r=[];for(const[a,o]of n){const s=o.topPositive??o.bottomNegative;s!==null&&r.push({xKey:a,total:o.total,anchor:{xMin:o.anchorXMin,xMax:o.anchorXMax,yMin:s.yMin,yMax:s.yMax,direction:o.topPositive!==null?"positive":"negative"}})}return r};class Ed extends Se{constructor(t){super(),this.geomCompiler=t}dependencies(){return[]}compileLayer(t){const n={};if(this.geomCompiler.emitsStackTotals(t.geom)){const r=Ld({layer:t});r!==void 0&&(n.stackTotals=r)}if(this.geomCompiler.emitsGrandTotal(t.geom)){const r=Vd({layer:t});r!==void 0&&(n.grandTotal=r.grandTotal,n.absoluteGrandTotal=r.absoluteGrandTotal)}return{...t,summary:n}}}class Md extends j{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 Dd{constructor(){this.transformType="aggregate"}apply(t,n){const{options:r}=n,a={};for(const o of r.operations)a[o.as]={variableName:o.variableName,aggregation:o.op};return t.groupBy(...r.groupby).rollup(a)}}class Rd{constructor(){this.transformType="constant"}apply(t,n){const{options:r}=n;return t.addConstantVariable(r.variableName,r.type,r.value)}}class Cd{constructor(){this.transformType="filter"}apply(t,n){const{options:r}=n;return t.filter(r.variableName,r.operator,r.value)}}class kd{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 _d{constructor(){this.transformType="sort"}apply(t,n){const{options:r}=n;return t.orderBy(r.variableName,r.direction??"asc")}}class Nd extends xe{constructor(){super("transform"),this.register("aggregate",new Dd),this.register("constant",new Rd),this.register("filter",new Cd),this.register("reshape",new kd),this.register("sort",new _d)}}const yr={color:"categorical",size:"numeric",alpha:"numeric",strokeWidth:"numeric",lineType:"categorical"};class Fd extends Se{constructor(t){super(),this.geomCompiler=t}dependencies(t){return[...mt].map(n=>t.scales[n])}compileLayer(t,n){const r=this.geomCompiler.getVisualAesthetics(t.geom),a=Od(t.data,t.mapping,r,n.scales);return{...t,data:a}}}function Od(e,t,n,r){let a=e;for(const o of n){const s=u.VISUAL_VARIABLES[o],i=u.extractConstantValue(t[o]);if(i!==void 0){a=a.deriveVariable(s,yr[o],()=>i);continue}const c=u.extractVariableName(t[o]),l=r[o];if(!l||l.kind!=="visual")continue;const d=Pd(o,c,l);d&&(a=a.deriveVariable(s,yr[o],d))}return a}const Pd=(e,t,n)=>{if(!t){if(e!=="color"||n.spec.scaleType!=="palette")return null;const r=n.map(null);return()=>r}return r=>u.isDefined(r[t])?n.map(r[t]):null},Bd=["data","transform","constantMapping","layer","coordSetup","scale","positionMapper","visualMapper","coordTransform","summarise","guide","highlights","config","annotations"];class Ya{constructor(t,n,r,a,o,s,i,c,l,d,m,f,p,h,y){this.dataCompiler=t,this.specCompiler=n,this.transformCompiler=r,this.constantMappingCompiler=a,this.layerValidationCheck=o,this.layerCompiler=s,this.scaleCompiler=i,this.coordCompiler=c,this.positionMapperCompiler=l,this.visualMapperCompiler=d,this.guideCompiler=m,this.summariseCompiler=f,this.highlightsCompiler=p,this.configCompiler=h,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:St(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(!ne)return t();const n=this.getCacheStats(),r=performance.now(),a=t(),o=performance.now()-r,s={};for(const{name:i,getStats:c}of this.stages){const l=c();s[i]={hits:l.hits-n[i].hits,misses:l.misses-n[i].misses}}return this.lastCompile={stages:s,durationMs:o},a}runPipeline({spec:t}){return lt({spec:t}).pipe(({spec:r})=>({spec:St(r,{data:this.transformCompiler.compile({data:r.data,transforms:r.transforms})})})).pipe(({spec:r})=>{const a=this.constantMappingCompiler.compile({data:r.data,mapping:r.mapping});return{spec:St(r,{data:a.data,mapping:a.mapping})}}).pipe(({spec:r})=>{const a={data:r.data,layers:r.layers,mapping:r.mapping,coords:r.coords,scales:r.scales};return this.layerValidationCheck.check({...a,coords:r.coords}),{layers:this.layerCompiler.compile(a)}}).pipe(({spec:r,layers:a})=>this.coordCompiler.setup({coordSpec:r.coords,scales:r.scales,layers:a})).pipe(({layers:r,scales:a})=>({scales:this.scaleCompiler.compile({layers:r,scales:a})})).pipe(({spec:r,scales:a})=>({config:this.configCompiler.compile({config:r.config,scales:a})})).pipe(({layers:r,scales:a})=>({layers:this.positionMapperCompiler.compile({layers:r,scales:a})})).pipe(({layers:r,scales:a})=>({layers:this.visualMapperCompiler.compile({layers:r,scales:a})})).pipe(({spec:r,layers:a})=>({layers:this.coordCompiler.transform({coordSpec:r.coords,layers:a})})).pipe(({layers:r})=>({layers:this.summariseCompiler.compile({layers:r})})).pipe(({spec:r,scales:a,layers:o,coordSystem:s})=>({guides:this.guideCompiler.compile({scales:a,config:r.config,layers:o,coordSystem:s,originalData:this.lastData})})).pipe(({spec:r,layers:a})=>({layers:this.highlightsCompiler.compile({layers:a,highlights:r.highlights,config:r.config})})).pipe(({spec:r,layers:a,coordSystem:o,scales:s})=>({annotations:this.annotationsCompiler.compile({annotations:r.annotations,layers:a,coordSystem:o,scales:s})})).result()}}const Gd=e=>{const t=new Xs({geoms:e?.geoms}),n=new Us(t),r=new Id,a=new ml,o=new Md(new Nd);return new Ya(new Fs,new Ba,o,new Wo,new Dc(o,new Rc(t,r)),new Mc(o,new dd(r),new qs,n,new kc(new Pc)),new Xc(a),new jo(new is(t)),new zc(t),new Fd(n),new oc(n),new Ed(n),new yc,new Ho,new Fo(n))};function Ud(e,t){return e.geom===t}const ln="–",Ka="n/a",D={timeZone:"UTC"},M=e=>t=>{if(!C(t))return ln;try{return e(t)}catch{return Ka}},Q=e=>t=>w(t)?e(t):ln,un=e=>t=>Pe(t)?t:ln,$d=2,Yd=3,Kd=2,Hd=0,Wd=1,zd=2,Xd=wo.humanizer({language:"en",spacer:"",delimiter:" ",languages:{en:{y:()=>"y",mo:()=>"mo",w:()=>"w",d:()=>"d",h:()=>"h",m:()=>"m",s:()=>"s",ms:()=>"ms"}}}),Ha=({valueFormat:e,locale:t,numberFormat:n,intlOptions:r})=>Q(a=>{const o=typeof n.decimals=="number"?n.decimals:$d,s=fn(a,o),{base:i,suffix:c}=pn(a,n.abbreviation),l={...s,...Yr(e)?{style:"currency",currencyDisplay:"narrowSymbol",currency:e.iso}:{},...r};return`${Intl.NumberFormat(t,l).format(i)}${c}`}),dn=({locale:e,numberFormat:t,intlOptions:n})=>Q(r=>{const{base:a,suffix:o}=pn(r,t.abbreviation),i={...fn(a,t.decimals),...n};return`${Intl.NumberFormat(e,i).format(a)}${o}`}),mn=e=>Q(t=>Xd(t)),Wa=({locale:e,intlOptions:t})=>Q(n=>Intl.NumberFormat(e,{maximumFractionDigits:0,...t}).format(n)),za=({locale:e,numberFormat:t,intlOptions:n})=>Q(r=>{const a=fn(r,t.decimals);return Intl.NumberFormat(e,{...a,...n,style:"percent"}).format(r)}),pn=(e,t="none")=>{switch(t){case"none":return{base:e,suffix:""};case"auto":{const n=qd(e);return pn(e,n)}default:return{base:e/Ce[t],suffix:t}}},fn=(e,t)=>{if(typeof t=="number")return{minimumFractionDigits:t,maximumFractionDigits:t};const n=Math.ceil(Math.log10(Math.abs(e))),r=n>=Yd?Hd:n===Kd?Wd:zd;return{minimumFractionDigits:t==="auto"?0:r,maximumFractionDigits:r}},qd=e=>{const t=Math.abs(e);return t>=Ce.b?"b":t>=Ce.m?"m":t>=Ce.k?"k":"none"},jd=({locale:e,intlOptions:t})=>M(n=>Intl.DateTimeFormat(e,{dateStyle:"medium",...D,...t}).format(n)),Qd=({locale:e,intlOptions:t})=>M(n=>{const r=Intl.DateTimeFormat(e,{dateStyle:"medium",timeStyle:"medium",...D,...t}).formatToParts(n);return Zd(r.map(Jd))}),Xa=({locale:e,intlOptions:t})=>M(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"long",...D,...t}).format(n)),qa=({locale:e,intlOptions:t})=>M(n=>Intl.DateTimeFormat(e,{month:"long",...D,...t}).format(n)),hn=({locale:e,intlOptions:t})=>M(n=>Intl.DateTimeFormat(e,{month:"short",year:"numeric",...D,...t}).format(n)),yn=e=>M(t=>`Q${Math.floor(t.getUTCMonth()/3)+1} ${t.getUTCFullYear()}`),ja=({locale:e,intlOptions:t})=>M(n=>{const r=A.addDays(n,6);return Intl.DateTimeFormat(e,{day:"numeric",month:"long",...D,...t,year:void 0}).formatRange(n,r)}),Qa=({locale:e,intlOptions:t})=>M(n=>{const r=A.addDays(n,6);return Intl.DateTimeFormat(e,{dateStyle:"medium",...D,...t}).formatRange(n,r)}),gn=({locale:e,intlOptions:t})=>M(n=>Intl.DateTimeFormat(e,{year:"numeric",...D,...t}).format(n)),Za=({locale:e,intlOptions:t})=>M(n=>Intl.DateTimeFormat(e,{timeStyle:"short",...D,...t}).format(n)),Zd=e=>e.map(t=>t.value).join(""),Jd=e=>e.type!=="literal"||e.value!==", "?e:{type:"literal",value:" • "},em=1,tm=4,nm=1,gr=1e3,rm=({valueFormat:e,locale:t,tickValues:n,intlOptions:r})=>Q(a=>{const s={...Sn(a,n),notation:"compact",...Yr(e)?{style:"currency",currencyDisplay:"narrowSymbol",currency:e.iso}:{},...r};return bn(a,t,s)}),am=({locale:e,tickValues:t,intlOptions:n})=>Q(r=>{const o={...Sn(r,t),notation:"compact",...n};return bn(r,e,o)}),om=({locale:e,tickValues:t,intlOptions:n})=>Q(r=>{const o={...Sn(r,t),notation:"compact",...n,style:"percent"};return bn(r,e,o)}),bn=(e,t,n)=>Intl.NumberFormat(t,n).formatToParts(e).map(a=>a.type==="compact"?a.value.toLowerCase():a.value).join(""),Ja=e=>Math.abs(e)>gr?Ja(e/gr):Number.isInteger(e),sm=e=>{if(e.length<2)return!1;const[t,n]=e;return typeof t!="number"||typeof n!="number"?!1:Math.abs(n-t)<em},Sn=(e,t)=>Ja(e)?{minimumFractionDigits:0,maximumFractionDigits:0}:sm(t)?{minimumFractionDigits:0,maximumFractionDigits:tm}:{minimumFractionDigits:0,maximumFractionDigits:nm},im=({locale:e,intlOptions:t})=>M(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"short",...D,...t}).format(n)),cm=({locale:e,intlOptions:t})=>M(n=>Intl.DateTimeFormat(e,{month:"short",...D,...t}).format(n)),lm=({locale:e,intlOptions:t})=>M(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"short",...D,...t}).format(n)),um=({locale:e,intlOptions:t})=>M(n=>Intl.DateTimeFormat(e,{timeStyle:"short",...D,...t}).format(n)),xn=e=>{const{valueFormat:t}=e;switch(t.type){case"currency":return rm(e);case"date":case"datetime":return im(e);case"day_month":case"weekly_date_range":case"weekly_date_range_with_year":return lm(e);case"decimal":case"integer":return am(e);case"duration":return mn();case"month":return cm(e);case"month_year":return hn(e);case"percentage":return om(e);case"quarter":return yn();case"text":return un();case"time":return um(e);case"year":return gn(e);case"lookup":return xn({...e,valueFormat:t.fallback});default:{const n=t;throw new Error(`Unhandled value format: ${n.type}`)}}},dm=40,mm=60,br=8,pm=50,fm=1/3,hm=1/4,Dt="…",ym=(e,t,n)=>{if(t<=0||e.length===0)return"";if(n(e)<=t)return e;if(n(Dt)>t)return"";let r=0,a=e.length-1,o=0;for(;r<=a;){const s=r+a>>>1,i=e.slice(0,s)+Dt;n(i)<=t?(o=s,r=s+1):a=s-1}return e.slice(0,o)+Dt},gm=e=>e.formattedAxis.position==="top"||e.formattedAxis.position==="bottom"?bm(e):Sm(e),bm=({formattedAxis:e,bandwidthPx:t,panelRect:n,measureLabel:r})=>{const{widths:a,maxWidth:o,maxHeight:s}=eo(e.ticks,r),i=t-br;if(o<=i)return{...e,labelRotation:0,labelMaxWidthPx:null};if(t>=pm){const l=$t(i);return{...e,ticks:Ut(e.ticks,a,l,r),labelRotation:0,labelMaxWidthPx:l}}if(s+br>t)return{...e,ticks:[],labelRotation:0,labelMaxWidthPx:null};const c=$t(n.height*fm);return{...e,ticks:Ut(e.ticks,a,c,r),labelRotation:-90,labelMaxWidthPx:c}},Sm=({formattedAxis:e,bandwidthPx:t,panelRect:n,measureLabel:r})=>{const{widths:a,maxWidth:o,maxHeight:s}=eo(e.ticks,r);if(s>t)return{...e,ticks:[],labelRotation:0,labelMaxWidthPx:null};const i=$t(n.width*hm);return o<=i?{...e,labelRotation:0,labelMaxWidthPx:null}:{...e,ticks:Ut(e.ticks,a,i,r),labelRotation:0,labelMaxWidthPx:i}},eo=(e,t)=>{const n=[];let r=0,a=0;for(const o of e){const{width:s,height:i}=t(o.formattedLabel);n.push(s),s>r&&(r=s),i>a&&(a=i)}return{widths:n,maxWidth:r,maxHeight:a}},Ut=(e,t,n,r)=>{const a=o=>r(o).width;return e.map((o,s)=>(t[s]??0)<=n?o:{...o,formattedLabel:ym(o.formattedLabel,n,a)})},$t=e=>Math.max(0,Math.floor(e)),xm=(e,t,n,r)=>{if(e.length===0)return!0;const a=t==="top"||t==="bottom",o=a?mm:dm;let s=n-(e.length-1)*o;for(const i of e){const{width:c,height:l}=r(i);if(s-=a?c:l,s<0)return!1}return!0},vm=({axis:e,availableSpacePx:t,measureLabel:n,resolveFormatter:r})=>{const{tickCandidates:a,position:o}=e;if(a.length===0)return[];const s=new Map,i=m=>{const f=s.get(m);if(f)return f;const p=a[m],h=p?Am(p.ticks,r(p)):[];return s.set(m,h),h};let c=0,l=a.length-1,d=-1;for(;c<=l;){const m=c+l>>>1,p=i(m).map(h=>h.formattedLabel);xm(p,o,t,n)?(d=m,c=m+1):l=m-1}return d>=0?i(d):i(0)},Am=(e,t)=>e.map(n=>({...n,formattedLabel:t(n.value)})),Rt=6,Ct=6,kt=15,_t=5,Nt=15,vn=(e,t)=>{switch(e){case"small":return{arrowStartGap:Rt,arrowEndGap:Ct,offsetFromHigherObservation:kt,arrowheadSize:_t,curveRadius:Nt,strokeWidth:2,labelLineHeight:12*t,labelPaddingX:6,labelPaddingY:3,labelStrokeWidth:1,labelFontWeight:500};case"medium":return{arrowStartGap:Rt*1.5,arrowEndGap:Ct*1.5,offsetFromHigherObservation:kt*1.25,arrowheadSize:_t*1.5,curveRadius:Nt*1.25,strokeWidth:3,labelLineHeight:16*t,labelPaddingX:8,labelPaddingY:4,labelStrokeWidth:1.5,labelFontWeight:500};case"large":return{arrowStartGap:Rt*2,arrowEndGap:Ct*2,offsetFromHigherObservation:kt*1.75,arrowheadSize:_t*2.5,curveRadius:Nt*1.5,strokeWidth:5,labelLineHeight:20*t,labelPaddingX:10,labelPaddingY:5,labelStrokeWidth:2,labelFontWeight:600}}},Tm=e=>{const t=V({...e,valueFormat:e.valueFormat.fallback}),n={};for(const[a,o]of Object.entries(e.valueFormat.cases))n[a]=V({...e,valueFormat:o});const r=e.valueFormat.byVariable;return(a,o)=>{if(o===void 0||o[r]===void 0)return t(a);const s=u.getStableKey(o[r]),i=n[s];return i!==void 0?i(a,o):t(a)}},V=e=>{switch(e.valueFormat.type){case"currency":return Ha(e);case"date":return jd(e);case"datetime":return Qd(e);case"day_month":return Xa(e);case"decimal":return dn(e);case"duration":return mn();case"integer":return Wa(e);case"month":return qa(e);case"month_year":return hn(e);case"percentage":return za(e);case"quarter":return yn();case"text":return un();case"weekly_date_range":return ja(e);case"weekly_date_range_with_year":return Qa(e);case"year":return gn(e);case"time":return Za(e);case"lookup":return Tm({...e,valueFormat:e.valueFormat});default:{const t=e.valueFormat;throw new Error(`Unhandled value format: ${t.type}`)}}},Ft={abbreviation:"none",decimals:"auto"},to=({locale:e,kind:t,startValue:n,endValue:r})=>{if(n===null||r===null)return Ka;switch(t){case"absolute-difference":return dn({locale:e,numberFormat:Ft,intlOptions:{signDisplay:"always"}})(r-n);case"relative-difference":{const a=r-n;if(a===0)return"0%";const o=a/n;return o===Number.POSITIVE_INFINITY?"∞":o===Number.NEGATIVE_INFINITY?"-∞":V({valueFormat:{type:"percentage"},locale:e,numberFormat:Ft,intlOptions:{signDisplay:"always"}})(o)}case"proportion":{if(r-n===0)return"=";const a=r/n;return a===Number.POSITIVE_INFINITY?"∞":a===Number.NEGATIVE_INFINITY?"-∞":`${V({valueFormat:{type:"decimal"},locale:e,numberFormat:Ft,intlOptions:{maximumFractionDigits:1}})(a)}x`}}},wm=e=>{const t=e.padding??0,n=Sr(e.rows,t),r=Sr(e.cols,t);return{rows:n.tracks,cols:r.tracks,placements:Em(e.placements,n.nameToIndex,r.nameToIndex),width:e.containerSize.width,height:e.containerSize.height}},Im=e=>{const t=xr(e.rows,e.height),n=xr(e.cols,e.width),r=vr(t),a=vr(n),o=new Map;for(const s of e.placements){const i=s.rowSpan??1,c=s.colSpan??1,l=a[s.col]??0,d=r[s.row]??0,m=Ar(n,s.col,c),f=Ar(t,s.row,i);o.set(s.name,{x:l,y:d,width:Math.max(0,m),height:Math.max(0,f)})}return o},Sr=(e,t)=>{const n=[],r=new Map;t>0&&n.push({type:"fixed",pixels:t});for(let a=0;a<e.length;a++){const o=e[a];if(!o)continue;r.set(o.name,n.length),n.push(Vm(o));const s=Lm(e,a);if(no(o)&&s){const i=o.gaps?.after??0,c=s.gaps?.before??0,l=Math.max(i,c);l>0&&n.push({type:"fixed",pixels:l})}}return t>0&&n.push({type:"fixed",pixels:t}),{tracks:n,nameToIndex:r}},Vm=e=>typeof e.size=="number"?{type:"fixed",pixels:e.size}:{type:"flex",weight:e.size.flex},no=e=>typeof e.size=="number"?e.size>0:e.size.flex>0,Lm=(e,t)=>{for(let n=t+1;n<e.length;n++){const r=e[n];if(r&&no(r))return r}},Em=(e,t,n)=>{const r=[];for(const a of e){const o=t.get(a.row),s=n.get(a.col);if(o===void 0||s===void 0)continue;const i=a.rowEnd!==void 0?t.get(a.rowEnd):o,c=a.colEnd!==void 0?n.get(a.colEnd):s;i===void 0||c===void 0||r.push({name:a.name,row:o,col:s,rowSpan:Math.max(1,i-o+1),colSpan:Math.max(1,c-s+1)})}return r},xr=(e,t)=>{let n=0,r=0;for(const o of e)o.type==="fixed"?n+=o.pixels:r+=o.weight;const a=Math.max(0,t-n);return e.map(o=>o.type==="fixed"?o.pixels:r===0?0:o.weight/r*a)},vr=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},Ar=(e,t,n)=>{let r=0;const a=Math.min(t+n,e.length);for(let o=t;o<a;o++)r+=e[o]??0;return r},ro=24,H={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}},qe={leftLegend:{after:10,before:0},leftAxis:{after:4,before:0},panel:{after:4,before:0},rightAxis:{after:10,before:0}},An={top:0,right:0,bottom:0,left:0},Mm=(e,t,n,r=An)=>{const o=n.axes.top>0||n.axesLabels.top>0?n.axesLabels.top:Math.max(n.axesLabels.top,n.axesLabels.left,n.axesLabels.right);return wm({rows:[{name:"header",size:t.headerSize.height,gaps:H.header},{name:"topLegend",size:n.legends.top,gaps:H.topLegend},{name:"headline",size:n.headline,gaps:H.headline},{name:"topAxisLabel",size:o,gaps:H.topAxisLabel},{name:"topAxis",size:n.axes.top,gaps:H.topAxis},{name:"topAnnotation",size:r.top},{name:"panel",size:{flex:1},gaps:H.panel},{name:"bottomAxis",size:n.axes.bottom,gaps:H.bottomAxis},{name:"bottomAxisLabel",size:n.axesLabels.bottom,gaps:H.bottomAxisLabel},{name:"bottomLegend",size:n.legends.bottom,gaps:H.bottomLegend},{name:"footer",size:t.footerSize.height}],cols:[{name:"leftLegend",size:n.legends.left,gaps:qe.leftLegend},{name:"leftAxis",size:n.axes.left,gaps:qe.leftAxis},{name:"panel",size:{flex:1},gaps:qe.panel},{name:"rightAnnotation",size:r.right},{name:"rightAxis",size:n.axes.right,gaps:qe.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"},...Dm(n.axes),...Rm(n.axesLabels,n.axes),...Cm(n.legends)],containerSize:e,padding:ro})},Dm=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},Rm=(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},Cm=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},km=({annotations:e,mainAxis:t,panelRect:n,textScale:r,locale:a,measureLabel:o,currentOverflow:s})=>{if(e.differenceArrows.length===0)return An;const i=t==="y",c=n.height+s.top,l=n.width+s.right;let d=0,m=0;for(const f of e.differenceArrows){const{start:p,end:h,size:y,label:g}=f;if(!Tr(p.x,p.y)||!Tr(h.x,h.y))continue;const S=vn(y,r),b=S.offsetFromHigherObservation+S.arrowheadSize+S.arrowEndGap,x=to({locale:a,kind:g,startValue:p.measurementValue,endValue:h.measurementValue}),T=o(x,y);if(i){const L=Math.max(p.x,h.x),P=b+T.width/2+S.labelPaddingX;m=Math.max(m,wr(P,L,l))}else{const L=Math.max(p.y,h.y),P=b+S.labelLineHeight/2+S.labelPaddingY;d=Math.max(d,wr(P,L,c))}}return{top:Math.ceil(d),right:Math.ceil(m),bottom:0,left:0}},Tr=(e,t)=>e>=0&&e<=1&&t>=0&&t<=1,wr=(e,t,n)=>{if(t<=0)return 0;const r=(e-(1-t)*n)/t;return Math.max(0,r)},_m=["top","right","bottom","left"],Ot=(e,t)=>{const n={};for(const r of _m){const a=e.get(`${r}${t}`);a&&(n[r]=a)}return n},Yt=["large","medium","small"],Nm=({size:e,availableWidth:t,measureStripWidth:n})=>{if(e!=="auto")return e;for(const r of Yt)if(n(r)<=t)return r;return"small"},Fm=({size:e,availableWidth:t,measureStripWidth:n})=>{const r=e==="auto"?0:Yt.indexOf(e);for(const a of Yt.slice(r))if(n(a)<=t)return a;return null},Om=({itemWidths:e,gap:t,availableWidth:n})=>{let r=0,a=0;for(const o of e){const s=a===0?o:r+t+o;if(s>n)break;r=s,a+=1}return a},Pm=({headline:e,containerSize:t,measurer:n})=>{if(ao(e))return 0;const r=oo(e,t.width,n);return n.measureHeadline(e.formatted,r).height},Bm=({headline:e,layout:t,containerSize:n,measurer:r,itemGap:a})=>{if(ao(e)){const i=Gm(t.panel,e.innerRadius),c=Fm({size:e.size,availableWidth:i.width,measureStripWidth:so(e,r)});return c===null?null:{rect:i,resolvedSize:c,visibleItemCount:1}}const o=oo(e,n.width,r);if(e.formatted.kind!=="perGroup")return{rect:t.headline,resolvedSize:o,visibleItemCount:1};const s=Om({itemWidths:r.measureHeadlineItemWidths(e.formatted,o),gap:a,availableWidth:t.headline.width});return s===0?null:{rect:t.headline,resolvedSize:o,visibleItemCount:s}},ao=e=>e.formatted.kind==="grandTotal"&&e.position==="center"&&e.innerRadius>0,Gm=(e,t)=>{const n=Math.min(e.width,e.height)/2,r=t*n*Math.SQRT2,a=e.x+e.width/2,o=e.y+e.height/2;return{x:a-r/2,y:o-r/2,width:r,height:r}},oo=(e,t,n)=>Nm({size:e.size,availableWidth:t,measureStripWidth:so(e,n)}),so=(e,t)=>n=>t.measureHeadline(e.formatted,n).width,Me={x:0,y:0,width:0,height:0},Um="0000";class $m{constructor(t){this.measurer=t}compile(t){return lt({axes:t.axes,numberFormat:t.numberFormat,formattedLegends:t.formattedLegends,containerSize:t.containerSize,externalMeasurements:t.externalMeasurements,annotationOverflow:An,headline:t.headline,locale:t.formattingLocale??t.parsingLocale}).pipe(({axes:n,numberFormat:r,locale:a})=>({axisBundles:n.map(o=>({axis:o,resolveFormatter:Ym(o,a,r),formatted:this.seedAxis(o)}))})).pipe(({axisBundles:n,formattedLegends:r,containerSize:a,externalMeasurements:o,annotationOverflow:s,headline:i})=>({layout:this.resolveLayout({axes:n.map(c=>c.formatted),formattedLegends:r,containerSize:a,externalMeasurements:o,annotationOverflow:s,headline:i})})).pipe(({axisBundles:n,layout:r})=>({axisBundles:n.map(a=>Ir(a.axis.position)?{...a,formatted:this.finalizeAxis(a.axis,a.resolveFormatter,r.panel)}:a)})).pipe(({axisBundles:n,formattedLegends:r,containerSize:a,externalMeasurements:o,annotationOverflow:s,headline:i})=>({layout:this.resolveLayout({axes:n.map(c=>c.formatted),formattedLegends:r,containerSize:a,externalMeasurements:o,annotationOverflow:s,headline:i})})).pipe(({axisBundles:n,layout:r})=>({formattedAxes:n.map(a=>Ir(a.axis.position)?a.formatted:this.finalizeAxis(a.axis,a.resolveFormatter,r.panel))})).pipe(({formattedAxes:n,formattedLegends:r,containerSize:a,externalMeasurements:o,annotationOverflow:s,headline:i})=>({layout:this.resolveLayout({axes:n,formattedLegends:r,containerSize:a,externalMeasurements:o,annotationOverflow:s,headline:i})})).pipe(({formattedAxes:n,formattedLegends:r,containerSize:a,externalMeasurements:o,layout:s,annotationOverflow:i,headline:c,locale:l})=>{const d=this.measureAnnotationOverflow(t,s.panel,l,i);return d===i?{formattedAxes:n,layout:s}:{formattedAxes:n,layout:this.resolveLayout({axes:n,formattedLegends:r,containerSize:a,externalMeasurements:o,annotationOverflow:d,headline:c})}}).result()}measureAnnotationOverflow(t,n,r,a){if(!t.annotations||t.annotations.differenceArrows.length===0||t.coordSystem?.type!=="cartesian")return a;const o=km({annotations:t.annotations,mainAxis:t.coordSystem.mainAxis,panelRect:n,textScale:t.textScale??1,locale:r,measureLabel:this.measurer.measureDifferenceArrowLabel,currentOverflow:a});return o.top===a.top&&o.right===a.right?a:o}seedAxis(t){const{tickCandidates:n,...r}=t;return{...r,ticks:[{value:0,position:0,formattedLabel:Um}],labelRotation:0,labelMaxWidthPx:null}}finalizeAxis(t,n,r){const o=t.position==="top"||t.position==="bottom"?r.width:r.height,s=vm({axis:t,availableSpacePx:o,measureLabel:this.measurer.measureTickLabel,resolveFormatter:n}),{tickCandidates:i,...c}=t,l={...c,ticks:s,labelRotation:0,labelMaxWidthPx:null};if(t.scaleType==="discrete"&&t.bandwidth!==void 0){const d=t.bandwidth*o;return gm({formattedAxis:l,bandwidthPx:d,panelRect:r,measureLabel:this.measurer.measureTickLabel})}return l}resolveLayout({axes:t,formattedLegends:n,containerSize:r,externalMeasurements:a,annotationOverflow:o,headline:s}){const i=this.measureGuides(t,n,s,r),c=Mm(r,a,i,o),l=Im(c);return{header:l.get("header")??Me,headline:l.get("headline")??Me,footer:l.get("footer")??Me,plot:l.get("plot")??Me,panel:l.get("panel")??Me,axes:Ot(l,"Axis"),axisLabels:Ot(l,"AxisLabel"),legends:Ot(l,"Legend")}}measureGuides(t,n,r,a){const o={top:0,right:0,bottom:0,left:0},s={top:0,right:0,bottom:0,left:0};for(const c of t)c.isVisible&&(o[c.position]=this.measurer.measureAxis(c),c.label!==null&&(s[c.position]=this.measurer.measureAxisLabel(c)));const i={top:0,right:0,bottom:0,left:0};for(const c of n)i[c.position]=this.measurer.measureLegend(c);return{axes:o,axesLabels:s,legends:i,headline:this.measureHeadlineBand(r,a)}}measureHeadlineBand(t,n){return t===void 0?0:Pm({headline:t,containerSize:n,measurer:this.measurer})}}const Ir=e=>e==="left"||e==="right",Ym=(e,t,n)=>{const r=e.tickCandidates.flatMap(o=>o.ticks.map(s=>s.value)),a=new WeakMap;return o=>{const s=a.get(o);if(s)return s;const i=xn({valueFormat:o.valueFormat??e.valueFormat,locale:t,numberFormat:n,tickValues:r});return a.set(o,i),i}};function Km(e,t,n,r){const a=new Map;if(!n||n.kind!=="visual"||n.domain.length<=1)return a;const o=new Map(t.map(s=>[s.id,s.swatchShape]));for(const s of e){if(s.geom!=="rule"||s.stat.type!=="mean")continue;const i=s.transforms.find(y=>y.transformType==="filter"&&y.options.operator==="eq"),c=u.extractVariableName(s.mapping.y);let l,d,m;if(i?.transformType==="filter"&&typeof i.options.value=="string")l="color",d=i.options.variableName,m=i.options.value;else if(c!==null)l="y",d=c,m=c;else continue;const f=Hm(e,l,d);if(f===null)continue;const p=o.get(f.id);if(p===void 0)continue;const h=n.map(m);Pe(h)&&a.set(s.id,{shape:Ne(p,r),color:h})}return a}function Hm(e,t,n){let r=null;for(const a of e)if(a.geom!=="rule"&&(r===null&&(r=a),u.extractVariableName(a.mapping[t])===n))return a;return r}function Fe(e,t){return e==="x"?t.x:t.y}function gt(e,t){return e==="x"?t.y:t.x}function Wm(e,t){return{main:Fe(e,t),cross:gt(e,t)}}function zm(e){return e.type==="cartesian"}const Tn=12,Xm=4,qm=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=ve(n),a=$(n)??z(n);if(r===null||a===null||r<0||r>1||a<0||a>1)continue;const o=e.formatLabel(n);if(o==="")continue;const{width:s,height:i}=e.measureDataLabel("dataLabel",o),c=r*e.panelRect.width,l=(1-a)*e.panelRect.height-Tn-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:c,y:l,text:o,width:s,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},jm={place:qm,getPercentageValueStrategy:e=>e.position==="fill"?"fill":F(e.position)?"stack":"none"},Pt=4,je=6,Qm=e=>{const t=[],n=F(e.layer.position),r=e.coordSystem.mainAxis==="y";if(e.layer.dataLabels.showDataLabels){const{entries:a,shouldRotate:o}=Jm({layer:e.layer,mainAxis:e.coordSystem.mainAxis,panelRect:e.panelRect,measureDataLabel:e.measureDataLabel,formatLabel:e.formatLabel,isFlipped:r,getObservationKey:e.getObservationKey});for(const s of a){const i=rp({mainAxis:e.coordSystem.mainAxis,isStacked:n,isNegativeBar:s.isNegative,shouldRotate:o,bounds:s.bounds,labelWidth:s.labelWidth,labelHeight:s.labelHeight,panelWidth:e.panelRect.width,panelHeight:e.panelRect.height});i!==null&&t.push({layerId:e.layer.id,key:s.key,x:i.x,y:i.y,text:s.text,width:s.labelWidth,height:s.labelHeight,isRotated:i.isRotated,target:"observation",position:i.position})}}if(e.layer.dataLabels.showStackTotals){const a=ip({layer:e.layer,mainAxis:e.coordSystem.mainAxis,panelRect:e.panelRect,measureDataLabel:e.measureDataLabel,formatAbsolute:e.formatAbsolute});for(const o of a)t.push(o)}return t},Zm={place:Qm,getPercentageValueStrategy:e=>e.position==="fill"?"fill":F(e.position)?"stack":"absoluteGrandTotal"},Jm=({layer:e,mainAxis:t,panelRect:n,measureDataLabel:r,formatLabel:a,isFlipped:o,getObservationKey:s})=>{const i=[];let c=!1;const l=u.extractVariableName(e.mapping.y);for(const d of e.data){const m=ep(t,d);if(m===null)continue;const f=a(d);if(f==="")continue;const{width:p,height:h}=r("dataLabel",f),y=io(m,n);p>y.width&&(c=!0);const g=l===null?null:d[l],S=w(g)&&g<0;i.push({key:s(d),isNegative:S,text:f,labelWidth:p,labelHeight:h,bounds:y})}return{entries:i,shouldRotate:!o&&c}},io=(e,t)=>({x:e.x*t.width,y:e.y*t.height,width:e.width*t.width,height:e.height*t.height}),co=(e,t,n,r,a)=>{if(e==="x"){let i=1-a,c=a-r;return c<0&&(i+=c,c=-c),{x:t,y:i,width:n-t,height:c}}let o=t,s=n-t;return s<0&&(o+=s,s=-s),{x:o,y:1-a,width:s,height:a-r}},ep=(e,t)=>{const n=_e(t),r=ye(t),a=se(t),o=$(t)??z(t);return n===null||r===null||a===null||o===null?null:co(e,n,r,a,o)},tp=(e,t)=>{const{xMin:n,xMax:r,yMin:a,yMax:o}=t.anchor;return co(e,n,r,a,o)},np=(e,t)=>e==="x"?t?"bottom":"top":t?"left":"right",lo=(e,t,n)=>n?{width:t,height:e}:{width:e,height:t},rp=e=>e.isStacked?ap({bounds:e.bounds,labelWidth:e.labelWidth,labelHeight:e.labelHeight,isRotated:e.shouldRotate}):sp({edge:np(e.mainAxis,e.isNegativeBar),bounds:e.bounds,labelWidth:e.labelWidth,labelHeight:e.labelHeight,isRotated:e.shouldRotate,panelWidth:e.panelWidth,panelHeight:e.panelHeight}),ap=({bounds:e,labelWidth:t,labelHeight:n,isRotated:r})=>{const a=lo(t,n,r);return a.width>e.width||a.height>e.height?null:{x:e.x+e.width/2,y:e.y+e.height/2,isRotated:r,position:"inside"}},op=(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}}},sp=({edge:e,bounds:t,labelWidth:n,labelHeight:r,isRotated:a,panelWidth:o,panelHeight:s})=>{const i=e==="top"||e==="bottom",c=t.x+t.width/2,l=t.y+t.height/2,d=lo(n,r,a),m=i?d.height:d.width,f=i?d.width:d.height,p=i?t.height:t.width,h=i?t.width:t.height,y=m/2,{edgeCoord:g,outwardSign:S,panelExtent:b}=op(e,t,o,s);if(m+Pt<p){if(f>h)return null;if(a)return{x:c,y:l,isRotated:!0,position:"inside"};const T=g-S*(y+Pt);return{...i?{x:c,y:T}:{x:T,y:l},isRotated:!1,position:"inside"}}const x=g+S*(y+Pt);return x-y<0||x+y>b?null:{...i?{x:c,y:x}:{x,y:l},isRotated:a,position:"outside"}},ip=({layer:e,mainAxis:t,panelRect:n,measureDataLabel:r,formatAbsolute:a})=>{const o=[],s=e.summary.stackTotals;if(s===void 0||s.length===0)return o;const i=t==="y";for(const c of s){const l=io(tp(t,c),n),d=a(c.total),{width:m,height:f}=r("stackTotal",d),p=c.anchor.direction==="positive";let h,y;i?(h=p?l.x+l.width+je+m/2:l.x-je-m/2,y=l.y+l.height/2):(h=l.x+l.width/2,y=p?l.y-je-f/2:l.y+l.height+je+f/2),o.push({layerId:e.id,key:`${e.id}:stack:${c.xKey}`,x:h,y,text:d,width:m,height:f,isRotated:!1,target:"aggregate",position:"outside"})}return o},cp=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=ve(n),a=z(n);if(r===null||a===null||r<0||r>1||a<0||a>1)continue;const o=e.formatLabel(n);if(o==="")continue;const{width:s,height:i}=e.measureDataLabel("dataLabel",o),c=r*e.panelRect.width,l=(1-a)*e.panelRect.height-Tn-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:c,y:l,text:o,width:s,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},lp={place:cp,getPercentageValueStrategy:()=>"none"},up=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;for(const n of e.layer.data){const r=ve(n),a=z(n);if(r===null||a===null||r<0||r>1||a<0||a>1)continue;const o=e.formatLabel(n);if(o==="")continue;const{width:s,height:i}=e.measureDataLabel("dataLabel",o),c=(Pr(n)??e.layer.params.size)/2,l=r*e.panelRect.width,d=(1-a)*e.panelRect.height-c-Tn-i/2;t.push({layerId:e.layer.id,key:e.getObservationKey(n),x:l,y:d,text:o,width:s,height:i,isRotated:!1,target:"observation",position:"outside"})}return t},dp={place:up,getPercentageValueStrategy:()=>"none"};function uo(e){return{startAngle:e[u.POSITION_VARIABLES.xMin],endAngle:e[u.POSITION_VARIABLES.xMax]}}function mo(e){return{innerRadius:e[u.POSITION_VARIABLES.yMin],outerRadius:e[u.POSITION_VARIABLES.yMax]??e[u.POSITION_VARIABLES.y]}}const mp=" · ",pp=e=>typeof e=="string"?e:e instanceof Date?e.toISOString():String(e),fp=(e,t)=>{const n=u.extractVariableName(t.x);return n!==null&&n!==u.CONSTANT_VARIABLES.x?en(e,t):a=>be(a)},hp=e=>{const t=[];if(!e.layer.dataLabels.showDataLabels)return t;const n=e.layer.dataLabels.showCategoryLabels?fp(e.layer.data,e.layer.mapping):null,r=e.panelRect.width/2,a=e.panelRect.height/2,o=Math.min(e.panelRect.width,e.panelRect.height)/2;for(const s of e.layer.data){const{startAngle:i,endAngle:c}=uo(s),{outerRadius:l}=mo(s);if(i===null||c===null||l===null)continue;const d=e.formatLabel(s);if(d==="")continue;const m=n===null?null:n(s),f=m===null?d:`${pp(m)}${mp}${d}`,{width:p,height:h}=e.measureDataLabel("dataLabel",f),y=(i+c)/2,g=Math.abs(Math.sin(y))*(p/2)+Math.abs(Math.cos(y))*(h/2),S=l*o+Xm+g,b=r+Math.sin(y)*S,x=a-Math.cos(y)*S,T=p/2,L=h/2;b-T<0||b+T>e.panelRect.width||x-L<0||x+L>e.panelRect.height||t.push({layerId:e.layer.id,key:e.getObservationKey(s),x:b,y:x,text:f,width:p,height:h,isRotated:!1,target:"observation",position:"outside"})}return t},yp={place:hp,getPercentageValueStrategy:()=>"absoluteGrandTotal"},gp={type:"decimal"};function po({layer:e,numberFormat:t,locale:n}){const r=u.extractVariableName(e.mapping.y),a=r!==null&&e.data.hasVariable(r)?e.data.getValueFormat(r):gp;return V({valueFormat:a,locale:n,numberFormat:t})}const bp=({layer:e,coordSystem:t,axes:n,numberFormat:r,panelRect:a,measureDataLabel:o,formattingLocale:s,percentageValueStrategy:i})=>{const c=po({layer:e,numberFormat:r,locale:s});return{layer:e,coordSystem:t,panelRect:a,measureDataLabel:o,formatLabel:Tp({layer:e,numberFormat:r,axes:n,locale:s,absoluteFormatter:c,percentageValueStrategy:i}),formatAbsolute:c,getObservationKey:Sp(e)}},Sp=e=>t=>`${e.id}:${ft(t)}`,xp=(e,t)=>{switch(t){case"stack":return vp(e);case"fill":return Ap(e);case"absoluteGrandTotal":return()=>e.summary.absoluteGrandTotal??null;case"none":return()=>null}},vp=e=>{const t=u.extractVariableName(e.mapping.x);let n=null,r=!1;return a=>{const o=e.summary.stackTotals;if(o===void 0||o.length===0||t===null)return null;if(!r){n=new Map;for(const c of o)n.set(c.xKey,c);r=!0}const s=a[t];if(s==null)return null;const i=n?.get(Jt(a,t));return i===void 0?null:i.total}},Ap=e=>{const t=tn(e);return n=>{const r=se(n),a=$(n);if(!w(r)||!w(a))return null;const o=Math.abs(a-r);if(o===0)return null;const s=t(n);return w(s)?s/o:null}},Tp=({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:a,percentageValueStrategy:o})=>{const s=O(e.data,e.dataLabels.labelSource),i=xp(e,o),c=wp({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:a}),l=V({valueFormat:{type:"percentage"},locale:r,numberFormat:t}),d=e.dataLabels.format==="percentage"&&fo(e);return m=>{const f=s(m);if(f===null)return"";if(!d||!w(f))return c(f,m);const p=i(m);return p===null||p===0?c(f,m):l(f/p)}},wp=({layer:e,numberFormat:t,axes:n,locale:r,absoluteFormatter:a})=>{const o=e.dataLabels.labelSource,s=u.extractVariableName(o);if(s!==null){if(fo(e))return a;const i=Ip(e,n,t,r,s);if(i!==null)return i}return V({valueFormat:Vp(e.data,o),locale:r,numberFormat:t})},fo=e=>{const t=u.extractVariableName(e.dataLabels.labelSource);return t===null?!1:t===u.extractVariableName($e(e.position,e.mapping))},Ip=(e,t,n,r,a)=>{const o=u.extractVariableName(e.mapping.x);if(o===null||o!==a)return null;const s=t.find(i=>i.scaleAestheticKey==="x");return s===void 0?null:V({valueFormat:s.valueFormat,locale:r,numberFormat:n})},Vp=(e,t)=>{const n=u.extractConstantValue(t);if(n!==void 0)return typeof n=="number"?{type:"decimal"}:ko(n)?{type:"date"}:{type:"text"};const r=u.extractVariableName(t);return r===null||!e.hasVariable(r)?{type:"text"}:e.getValueFormat(r)},Lp={bar:{cartesian:Zm,polar:yp},line:{cartesian:lp},point:{cartesian:dp},area:{cartesian:jm}},Ep=({layers:e,coordSystem:t,axes:n,numberFormat:r,parsingLocale:a,panelRect:o,measureDataLabel:s,formattingLocale:i})=>{const c=[],l=i??a,d=t.type;for(const m of e){if(!m.dataLabels.showDataLabels&&!m.dataLabels.showStackTotals)continue;const f=Lp[m.geom]?.[d];if(f===void 0)continue;const p=bp({layer:m,coordSystem:t,axes:n,numberFormat:r,panelRect:o,measureDataLabel:s,formattingLocale:l,percentageValueStrategy:f.getPercentageValueStrategy(m)}),h=f.place(p);for(const y of h)c.push(y)}return{labels:c}},Mp=(e,t,n,r)=>{const a=r.offsetFromHigherObservation+r.arrowheadSize+r.arrowEndGap;return e?Math.max(t.x,n.x)+a:Math.min(t.y,n.y)-a},Dp=(e,t,n,{arrowStartGap:r,arrowEndGap:a,curveRadius:o})=>{const s={x:e.x,y:e.y-r},i={x:e.x,y:n},c={x:t.x,y:n},l={x:t.x,y:t.y-a},d=t.x>e.x?1:-1;return`
4
- M ${s.x} ${s.y}
5
- L ${i.x} ${i.y+o}
6
- Q ${i.x} ${i.y} ${i.x+d*o} ${i.y}
7
- L ${c.x-d*o} ${c.y}
8
- Q ${c.x} ${c.y} ${c.x} ${c.y+o}
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(),spec:t}}}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}
9
10
  L ${l.x} ${l.y}
10
- `},Rp=(e,t,n,{arrowStartGap:r,arrowEndGap:a,curveRadius:o})=>{const s={x:e.x+r,y:e.y},i={x:n,y:e.y},c={x:n,y:t.y},l={x:t.x+a,y:t.y},d=t.y>e.y?1:-1;return`
11
- M ${s.x} ${s.y}
12
- L ${i.x-o} ${i.y}
13
- Q ${i.x} ${i.y} ${i.x} ${i.y+d*o}
14
- L ${c.x} ${c.y-d*o}
15
- Q ${c.x} ${c.y} ${c.x-o} ${c.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}
16
17
  L ${l.x} ${l.y}
17
- `},Cp=(e,t,{arrowEndGap:n,arrowheadSize:r})=>e?`
18
+ `},sh=(e,t,{arrowEndGap:n,arrowheadSize:r})=>e?`
18
19
  M ${t.x+n+r} ${t.y-r}
19
20
  L ${t.x+n} ${t.y}
20
21
  L ${t.x+n+r} ${t.y+r}
@@ -22,4 +23,17 @@ ${n}`),this.issues=t,this.name="SpecValidationError"}}class Dc{constructor(t,n){
22
23
  M ${t.x-r} ${t.y-n-r}
23
24
  L ${t.x} ${t.y-n}
24
25
  L ${t.x+r} ${t.y-n-r}
25
- `,kp=(e,t,n,r,a,o=.5)=>{if(e){const i=Math.min(t.y,n.y);return{x:r,y:i+o*a}}return{x:Math.min(t.x,n.x)+o*a,y:r}},_p=(e,t,n)=>Math.abs(e?t.y-n.y:t.x-n.x),Np=({arrow:e,mainAxis:t,panelWidth:n,panelHeight:r,textScale:a,locale:o})=>{const s=t==="y",i={x:e.start.x*n,y:(1-e.start.y)*r},c={x:e.end.x*n,y:(1-e.end.y)*r},l=vn(e.size,a),d=Mp(s,i,c,l),m=(s?Rp:Dp)(i,c,d,l),f=Cp(s,c,l),p=_p(s,i,c),h=kp(s,i,c,d,p,e.labelCrossPosition),y=to({locale:o,kind:e.label,startValue:e.start.measurementValue,endValue:e.end.measurementValue});return{id:e.id,linePath:m,arrowheadPath:f,labelPosition:h,labelText:y,color:e.color,strokeWidth:l.strokeWidth,labelLineHeight:l.labelLineHeight,labelPaddingX:l.labelPaddingX,labelPaddingY:l.labelPaddingY,labelStrokeWidth:l.labelStrokeWidth,labelFontWeight:l.labelFontWeight}},Fp=100,Op=({items:e,containerHeight:t,labelHeight:n})=>{const r=e.map(l=>{const d=(1-l.normalizedY)*t;return{anchorY:d,y:d,payload:l.payload}}).sort((l,d)=>l.y-d.y),a=n/2;let o=!1,s=!0,i=0;for(;s;){s=!1,i++;for(let l=0;l<r.length-1;l++){const d=r[l],m=r[l+1];if(!d||!m)continue;const f=d.y+a,p=m.y-a;if(f>p){s=!0,o=!0;const y=(f-p)/2+1;d.y-=y,m.y+=y,d.y<0&&(d.y=0),m.y>t&&(m.y=t)}}if(i>Fp)break}return{placements:r.filter(l=>l.y>=0&&l.y<=t).map(l=>({y:l.y,anchorY:l.anchorY,payload:l.payload})),hasOverlap:o}},Pp=({headline:e,show:t,numberFormat:n,parsingLocale:r,formattingLocale:a})=>{if(e===null)return null;const o=a??r;return e.kind==="grandTotal"?Bp(e,o,n):Gp(e,t,o,n)},Bp=(e,t,n)=>({kind:"grandTotal",value:V({valueFormat:e.valueFormat,locale:t,numberFormat:n})(e.value)}),Gp=(e,t,n,r)=>{const a=V({valueFormat:{type:"percentage"},locale:n,numberFormat:r}),o=Kp(t,e.items.length>1);return{kind:"perGroup",items:e.items.map(i=>{const c=V({valueFormat:i.valueFormat,locale:n,numberFormat:r}),l=V({valueFormat:i.groupLabelFormat,locale:n,numberFormat:r}),d=xn({valueFormat:i.mainValueFormat,locale:n,numberFormat:r,tickValues:[]}),m=i.label??l(i.value);return{swatch:i.swatch,label:`${o}${m}`,value:i.aggregate===null?null:c(i.aggregate),observationLabel:Yp(i.observationLabel,d),comparison:Up(i.comparison,d,a)}})}},Up=(e,t,n)=>e===null?null:{direction:$p(e.variation),percentage:n(Math.abs(e.variation)),reference:`from ${t(e.against)}`},$p=e=>e>0?"up":e<0?"down":"flat",Yp=(e,t)=>e===null?null:e.kind==="point"?t(e.value):`${t(e.from)} – ${t(e.to)}`,Kp=(e,t)=>{switch(e){case"total":return"Total ";case"average":return t?"Avg. ":"Average ";default:return""}},Hp=({legends:e,numberFormat:t,parsingLocale:n,formattingLocale:r})=>{const a=r??n;return e.map(o=>Wp(o,a,t))},Wp=(e,t,n)=>({...e,items:e.items.map(r=>{const a=V({valueFormat:r.valueFormat,locale:t,numberFormat:n});return{...r,formattedLabel:r.label??a(r.value)}})});function bt(e,t){return e.axes.find(n=>n.scaleAestheticKey===t)??null}function zp(e,t){return e.legends.find(n=>n.aesthetics.includes(t))??null}const Xp=({guides:e,numberFormat:t,layer:n,locale:r})=>{const a=n.data.getFirst();if(!a)return null;const o=n.mapping.y!==void 0,i=(o?Sa:en)(n.data,n.mapping)(a);if(i===null)return null;const c=o?Ue(n.yScaleType):"x",l=bt(e,c)?.valueFormat??{type:"decimal"};return V({valueFormat:l,locale:r,numberFormat:t})(i)},qp=800,Vr=400,jp={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}}},Qp=e=>Math.max(1,(e-Vr)/(qp-Vr)+1),Zp=(e,t)=>{const n=Qp(t),r=jp[e];return{strokeWidth:Math.min(r.strokeWidth.targetValue,r.strokeWidth.minValue*n),arrowheadLength:Math.min(r.arrowheadLength.targetValue,r.arrowheadLength.minValue*n)}},Qe=Math.PI/4,Kt=1.5,Jp=({startX:e,startY:t,endX:n,endY:r})=>`M ${e} ${t} L ${n} ${r}`,Lr=(e,t,n)=>{if(n<=0)return"";const{startX:r,startY:a,endX:o,endY:s}=t,i=e==="start"?r:o,c=e==="start"?a:s,l=e==="start"?Math.atan2(a-s,r-o):Math.atan2(s-a,o-r),d=i-n*Math.cos(l-Qe),m=c-n*Math.sin(l-Qe),f=i-n*Math.cos(l+Qe),p=c-n*Math.sin(l+Qe);return`M ${i} ${c} L ${d} ${m} M ${i} ${c} L ${f} ${p}`},ef=(e,t)=>e==="solid"?null:`${t*Kt} ${t*Kt*2}`,tf=(e,t)=>t?e*Kt:0,nf=64,rf=({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:a,arrowheadLength:o}=Zp(e.thickness,t),s=Math.hypot(r.endX-r.startX,r.endY-r.startY),i=af(o,s),c=e.startArrowheadStyle==="line-arrow",l=e.endArrowheadStyle==="line-arrow",m=c||l?i*Math.sin(Math.PI/4):0;return{id:e.id,linePath:Jp(r),startArrowheadPath:c?Lr("start",r,i):"",endArrowheadPath:l?Lr("end",r,i):"",color:e.color,strokeWidth:a,dashArray:ef(e.lineStyle,a),hasStickerStyle:e.hasStickerStyle,startX:r.startX,startY:r.startY,endX:r.endX,endY:r.endY,dashOffset:tf(a,c),arrowheadExtent:m}},af=(e,t)=>Math.min(e,t*e/nf);function ho(e,t){return wn(e.buckets,t,n=>n.main)}function of(e,t){return wn(e.bands,t,n=>n.bandCenter)}function sf(e,t){return wn(e.columns,t,n=>n.mainMid)}function wn(e,t,n){if(e.length===0)return null;let r=0,a=e.length;for(;r<a;){const i=r+a>>>1,c=e[i];c&&n(c)<t?r=i+1:a=i}const o=e[r-1],s=e[r];return o?s&&Math.abs(n(s)-t)<Math.abs(n(o)-t)?s:o:s??null}function In(e,t,n){return Math.hypot(e*n,t)}function cf(e,t,n,r){if(e.points.length===0)return null;const a=e.delaunay;if(!a)return null;const o=a.find(t.x*n,t.y,r??void 0),s=e.points[o];return s?{hit:{layerId:e.layerId,pointIndex:s.pointIndex,x:s.x,y:s.y,observation:s.observation},index:e,distance:In(s.x-t.x,s.y-t.y,n)}:null}function lf(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 Er(e,t){return{group:uf(e),related:ff(e,t)}}function uf(e){switch(e.kind){case"buckets":{const t=e.match.index;return F(t.position)?df(t,e.match):[]}case"rects":{const t=e.match.index;return F(t.position)?mf(t,e.match):pf(t,e.match)}case"points":case"arcs":case"render-hit-test":return[]}}function df(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 mf(e,t){const n=[];for(const r of t.column.rects)r.pointIndex!==t.hit.pointIndex&&n.push(Vn(e,r));return n}function pf(e,t){const n=e.bands.find(a=>a.columns.includes(t.column));if(!n)return[];const r=[];for(const a of n.columns)for(const o of a.rects)o.pointIndex!==t.hit.pointIndex&&r.push(Vn(e,o));return r}function ff(e,t){const n=new Map;if(e.kind==="arcs")return n;for(const r of t){if(r.layerId!==e.match.index.layerId){yf(n,r,e.match.hit);continue}e.kind==="buckets"&&(F(r.position)||r.kind==="buckets"&&hf(n,r,e.match))}return n}function hf(e,t,n){for(const r of n.bucket.entries){if(r.pointIndex===n.hit.pointIndex)continue;at(e,t.layerId).push({layerId:t.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation})}}function yf(e,t,n){switch(t.kind){case"buckets":{const r=ho(t,Fe(t.mainAxis,n));if(!r)return;const a=at(e,t.layerId);for(const o of r.entries)a.push({layerId:t.layerId,pointIndex:o.pointIndex,x:o.x,y:o.y,observation:o.observation});return}case"rects":{const r=of(t,Fe(t.mainAxis,n));if(!r)return;const a=at(e,t.layerId);for(const o of r.columns)for(const s of o.rects)a.push(Vn(t,s));return}case"points":{const r=lf(t,n);if(!r)return;at(e,t.layerId).push({layerId:t.layerId,pointIndex:r.pointIndex,x:r.x,y:r.y,observation:r.observation});return}case"arcs":return;case"noop":return;case"render-hit-test":return}}function at(e,t){let n=e.get(t);return n||(n=[],e.set(t,n)),n}function Vn(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 gf(e){const t=bf(e);return{kind:"arcs",layerId:e.id,position:e.position,arcs:t}}function bf(e){const t=e.data;if(t.size()===0)return[];const n=[u.POSITION_VARIABLES.xMin,u.POSITION_VARIABLES.xMax,u.POSITION_VARIABLES.yMin,u.POSITION_VARIABLES.yMax];for(const l of n)if(!t.hasVariable(l))return[];const r=t.getValues(u.POSITION_VARIABLES.xMin,{type:"numeric"}),a=t.getValues(u.POSITION_VARIABLES.xMax,{type:"numeric"}),o=t.getValues(u.POSITION_VARIABLES.yMin,{type:"numeric"}),s=t.getValues(u.POSITION_VARIABLES.yMax,{type:"numeric"}),i=[];let c=0;for(const l of t){const d=r[c],m=a[c],f=o[c],p=s[c];if(!u.isDefined(d)||!u.isDefined(m)||!u.isDefined(f)||!u.isDefined(p)){c++;continue}i.push({pointIndex:c,startAngle:d,endAngle:m,innerRadius:f,outerRadius:p,observation:l}),c++}return i}const Sf=1e-9;function xf(e,t){const n=vf(e,t);n.sort((a,o)=>a.main-o.main);const r=[];for(const a of n){const o=r[r.length-1];o&&Math.abs(o.main-a.main)<=Sf?o.entries.push(a.entry):r.push({main:a.main,entries:[a.entry]})}return{kind:"buckets",layerId:e.id,position:e.position,mainAxis:t,buckets:r}}function vf(e,t){const n=e.data;if(n.size()===0)return[];const a=n.hasVariable(u.POSITION_VARIABLES.x),o=n.hasVariable(u.POSITION_VARIABLES.y);if(!a||!o)return[];const s=n.getValues(u.POSITION_VARIABLES.x,{type:"numeric"}),i=n.getValues(u.POSITION_VARIABLES.y,{type:"numeric"}),c=t==="y",l=c?u.POSITION_VARIABLES.xMin:u.POSITION_VARIABLES.yMin,d=c?u.POSITION_VARIABLES.xMax:u.POSITION_VARIABLES.yMax,m=F(e.position),f=m?n.getValues(l,{type:"numeric"}):null,p=m?n.getValues(d,{type:"numeric"}):null,h=n.hasVariable(u.GROUP_VARIABLES.group)?n.getValues(u.GROUP_VARIABLES.group,{type:"categorical"}):null,y=[];let g=0;for(const S of n){const b=s[g],x=i[g];if(!u.isDefined(b)||!u.isDefined(x)){g+=1;continue}const T=h?.[g]??null,L=c?x:b;if(m){const P=f?.[g],Ie=p?.[g];if(!u.isDefined(P)||!u.isDefined(Ie)){g+=1;continue}const v=c?Ie:b,K=c?x:Ie;y.push({main:L,entry:{isStacked:m,pointIndex:g,x:v,y:K,stackMin:P,stackMax:Ie,groupKey:T,observation:S}})}else y.push({main:L,entry:{isStacked:m,pointIndex:g,x:b,y:x,groupKey:T,observation:S}});g+=1}return y}function Af(e){return{kind:"noop",layerId:e.id,position:e.position}}function Tf(e,t){const n={kind:"points",layerId:e.id,position:e.position,points:wf(e),delaunay:null,delaunayAspectRatio:null};return yo(n,t),n}function yo(e,t){e.delaunay&&e.delaunayAspectRatio===t||(e.delaunay=Io.Delaunay.from(e.points,n=>n.x*t,n=>n.y),e.delaunayAspectRatio=t)}function wf(e){const t=e.data;if(t.size()===0)return[];if(!t.hasVariable(u.POSITION_VARIABLES.x)||!t.hasVariable(u.POSITION_VARIABLES.y))return[];const n=t.getValues(u.POSITION_VARIABLES.x,{type:"numeric"}),r=t.getValues(u.POSITION_VARIABLES.y,{type:"numeric"}),a=[];let o=0;for(const s of t){const i=n[o],c=r[o];o+=1,!(!u.isDefined(i)||!u.isDefined(c))&&a.push({pointIndex:a.length,x:i,y:c,observation:s})}return a}const If=1e6;function Vf(e,t){const n=Lf(e,t);n.sort((i,c)=>i.mainMid-c.mainMid);const r=new Map,a=new Map;for(const i of n){const c=Mr(i.mainMid);let l=r.get(c);if(!l){l={mainMid:i.mainMid,columnKey:c,rects:[]},r.set(c,l);const d=Mr(i.bandCenter);let m=a.get(d);m||(m={bandCenter:i.bandCenter,bandKey:d,columns:[]},a.set(d,m)),m.columns.push(l)}l.rects.push(i.entry)}const o=[...r.values()].sort((i,c)=>i.mainMid-c.mainMid),s=[...a.values()].sort((i,c)=>i.bandCenter-c.bandCenter);for(const i of s)i.columns.sort((c,l)=>c.mainMid-l.mainMid);return{kind:"rects",layerId:e.id,position:e.position,mainAxis:t,columns:o,bands:s}}function Mr(e){return String(Math.round(e*If))}function Lf(e,t){const n=e.data;if(n.size()===0)return[];if(!(n.hasVariable(u.POSITION_VARIABLES.xMin)&&n.hasVariable(u.POSITION_VARIABLES.xMax)&&n.hasVariable(u.POSITION_VARIABLES.yMin)&&n.hasVariable(u.POSITION_VARIABLES.yMax)))return[];const a=n.getValues(u.POSITION_VARIABLES.xMin,{type:"numeric"}),o=n.getValues(u.POSITION_VARIABLES.xMax,{type:"numeric"}),s=n.getValues(u.POSITION_VARIABLES.yMin,{type:"numeric"}),i=n.getValues(u.POSITION_VARIABLES.yMax,{type:"numeric"}),c=t==="y",l=c?u.POSITION_VARIABLES.y:u.POSITION_VARIABLES.x,d=n.hasVariable(l)?n.getValues(l,{type:"numeric"}):null,m=n.hasVariable(u.GROUP_VARIABLES.group)?n.getValues(u.GROUP_VARIABLES.group,{type:"categorical"}):null,f=[];let p=0;for(const h of n){const y=a[p],g=o[p],S=s[p],b=i[p];if(!u.isDefined(y)||!u.isDefined(g)||!u.isDefined(S)||!u.isDefined(b)){p++;continue}const x=c?(S+b)/2:(y+g)/2,T=d?.[p]??x;f.push({mainMid:x,bandCenter:T,entry:{pointIndex:p,xMin:y,xMax:g,yMin:S,yMax:b,segmentKey:m?.[p]??null,observation:h}}),p++}return f}function Ef(e){const t=new Map;let n=0;for(const r of e.data)t.set(ft(r),{pointIndex:n,observation:r}),n++;return{kind:"render-hit-test",layerId:e.id,position:e.position,byKey:t}}function Dr(e,t,n){switch(e.spatialMap.kind){case"points":return Tf(e,n);case"buckets":return xf(e,Rr(t));case"rects":return Vf(e,Rr(t));case"arcs":return gf(e);case"noop":return Af(e);case"render-hit-test":return Ef(e);default:{const r=e.spatialMap.kind;throw new Error(`buildLayerIndex: unhandled spatial-map kind ${String(r)}`)}}}function Rr(e){if(e.type!=="cartesian")throw new Error("buildLayerIndex: a bucket or rect hit-test requires a cartesian coord system");return e.mainAxis}const U=Math.PI*2,Mf=1e-9;function Df(e,t,n){if(e.arcs.length===0)return null;const{angle:r,radius:a}=Rf(t,n);for(const o of e.arcs)if(!(a<o.innerRadius||a>o.outerRadius)&&Cf(r,o))return{hit:{layerId:e.layerId,pointIndex:o.pointIndex,x:(o.startAngle+o.endAngle)/2,y:(o.innerRadius+o.outerRadius)/2,observation:o.observation},index:e};return null}function Rf(e,t){const n=e.x-.5,r=e.y-.5,a=t>=1?n*2*t:n*2,o=t>=1?r*2:r*2/t,s=Math.hypot(a,o);return{angle:(Math.atan2(a,o)%U+U)%U,radius:s}}function Cf(e,t){const n=t.endAngle-t.startAngle;if(Math.abs(n)>=U-Mf)return!0;const r=(n%U+U)%U;return((e-t.startAngle)%U+U)%U<=r}function kf(e,t,n){const r=n.get(e.layerId);if(!r)return null;const a=r({x:t.x,y:1-t.y});if(!a)return null;const o=e.byKey.get(a.key);return o?{hit:{layerId:e.layerId,pointIndex:o.pointIndex,x:t.x,y:t.y,observation:o.observation},index:e}:null}function _f(e,t,n){if(e.buckets.length===0)return null;const{main:r,cross:a}=Wm(e.mainAxis,t),o=ho(e,r),s=o?.entries??[];if(!o||!u.isNonEmptyArray(s))return null;const i=Pf(s,a,e.mainAxis);return{hit:{layerId:e.layerId,pointIndex:i.pointIndex,x:i.x,y:i.y,observation:i.observation},index:e,bucket:o,distance:In(i.x-t.x,i.y-t.y,n)}}function Nf(e,t,n){if(e.columns.length===0)return null;const r=Fe(e.mainAxis,t),a=sf(e,r),o=a?.rects??[];if(!a||!u.isNonEmptyArray(o))return null;const s=F(e.position)?Ff(o,t,e.mainAxis):Of(o,t,n);return{hit:{layerId:e.layerId,pointIndex:s.pointIndex,x:(s.xMin+s.xMax)/2,y:(s.yMin+s.yMax)/2,observation:s.observation},index:e,column:a,distance:go(s,t,n)}}function Ff(e,t,n){const r=gt(n,t);return Ln(e,o=>Bf(o,n,r),{shortCircuitOnZero:!0})}function Of(e,t,n){return Ln(e,a=>go(a,t,n))}function Pf(e,t,n){return Ln(e,a=>Math.abs(gt(n,a)-t))}function Ln(e,t,{shortCircuitOnZero:n=!1}={}){let r=e[0],a=t(r);if(n&&a===0)return r;for(let o=1;o<e.length;o+=1){const s=e[o];if(s===void 0)continue;const i=t(s);if(n&&i===0)return s;i<a&&(r=s,a=i)}return r}function go(e,t,n){const r=Ht(t.x,e.xMin,e.xMax),a=Ht(t.y,e.yMin,e.yMax);return In(r,a,n)}function Bf(e,t,n){const r=t==="x"?e.yMin:e.xMin,a=t==="x"?e.yMax:e.xMax;return Ht(n,r,a)}function Ht(e,t,n){return e<t?t-e:e>n?e-n:0}const Gf=new Map,Uf=.05;function $f({layers:e,cursor:t,aspectRatio:n,warmStarts:r,hitTesters:a=Gf}){const o={match:null,distance:Number.POSITIVE_INFINITY},s={match:null,distance:Number.POSITIVE_INFINITY};let i=null;for(const c of e){if(c.kind==="arcs"){const d=Df(c,t,n);return d?{kind:"arcs",match:d}:null}if(c.kind==="render-hit-test"){const d=kf(c,t,a);d&&(i={kind:"render-hit-test",match:d});continue}const l=Kf({layer:c,cursor:t,aspectRatio:n,warmStarts:r});if(l){if(l.kind==="rects"){l.match.distance<o.distance&&(o.match=l,o.distance=l.match.distance);continue}l.match.distance<s.distance&&(s.match=l,s.distance=l.match.distance)}}return i||Yf({rect:o,continuous:s})}function Yf({rect:e,continuous:t}){return e.match&&t.match?t.distance<=e.distance+Uf?t.match:e.match:e.match??t.match}function Kf({layer:e,cursor:t,aspectRatio:n,warmStarts:r}){switch(e.kind){case"buckets":{const a=_f(e,t,n);return a?{kind:"buckets",match:a}:null}case"rects":{const a=Nf(e,t,n);return a?{kind:"rects",match:a}:null}case"points":{const a=r.get(e.layerId)??null,o=cf(e,t,n,a);return o?{kind:"points",match:o}:null}case"noop":return null}}const te={primary:null,group:[],related:new Map},Hf=1;class Wf{constructor({layers:t,coordSystem:n}){this.layerIndexes=[],this.layerRefs=[],this.aspectRatio=Hf,this.warmStarts=new Map,this.cachedState=te,this.cachedKey=null,this.nonInteractiveLayerIds=new Set,this.hitTesters=new Map,this.layerIndexes=t.map(r=>Dr(r,n,this.aspectRatio)),this.layerRefs=t.map(r=>Cr(r,n)),this.nonInteractiveLayerIds=kr(t)}update({layers:t,coordSystem:n}){const r=new Map;for(let s=0;s<this.layerIndexes.length;s+=1){const i=this.layerIndexes[s],c=this.layerRefs[s];!i||!c||r.set(i.layerId,{index:i,ref:c})}const a=[],o=[];for(const s of t){const i=r.get(s.id),c=Cr(s,n);if(i!==void 0&&zf(i.ref,c)){a.push(i.index),o.push(i.ref);continue}this.warmStarts.delete(s.id),a.push(Dr(s,n,this.aspectRatio)),o.push(c)}for(const s of this.warmStarts.keys())t.some(i=>i.id===s)||this.warmStarts.delete(s);this.layerIndexes=a,this.layerRefs=o,this.nonInteractiveLayerIds=kr(t),this.invalidateCache()}setViewport(t){this.aspectRatio=t.width/t.height;for(const n of this.layerIndexes)n.kind==="points"&&yo(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 te;const a=r.byKey.get(n);if(!a)return te;const o={layerId:t,pointIndex:a.pointIndex,x:0,y:0,observation:a.observation},s={kind:"render-hit-test",match:{hit:o,index:r}},{group:i,related:c}=Er(s,this.layerIndexes);return{primary:o,group:i,related:c}}query(t){if(this.layerIndexes.length===0)return te;const n=this.nonInteractiveLayerIds.size===0?this.layerIndexes:this.layerIndexes.filter(c=>!this.nonInteractiveLayerIds.has(c.layerId)),r=$f({layers:n,aspectRatio:this.aspectRatio,warmStarts:this.warmStarts,hitTesters:this.hitTesters,cursor:t});if(!r)return this.invalidateCache(),te;const a=r.match.hit;this.warmStarts.set(a.layerId,a.pointIndex);const o=`${a.layerId}:${a.pointIndex}`;if(this.cachedKey===o)return this.cachedState;const{group:s,related:i}=Er(r,n);return this.cachedKey=o,this.cachedState={primary:a,group:s,related:i},this.cachedState}invalidateCache(){this.cachedKey=null,this.cachedState=te}}function Cr(e,t){return{data:e.data,geom:e.geom,position:e.position,coord:t}}function kr(e){const t=new Set;for(const n of e)n.interactive||t.add(n.id);return t}function zf(e,t){return e.data===t.data&&e.geom===t.geom&&e.position===t.position&&e.coord===t.coord}const Xf=({locale:e,intlOptions:t})=>M(n=>Intl.DateTimeFormat(e,{day:"numeric",month:"long",year:"numeric",weekday:"long",...D,...t}).format(n)),qf=({locale:e,intlOptions:t})=>M(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,...D,...t}).format(n)}),ct=e=>{const{valueFormat:t}=e;switch(t.type){case"currency":return Ha(e);case"date":return Xf(e);case"datetime":return qf(e);case"day_month":return Xa(e);case"decimal":return dn(e);case"duration":return mn();case"integer":return Wa(e);case"month":return qa(e);case"month_year":return hn(e);case"percentage":return za(e);case"quarter":return yn();case"text":return un();case"time":return Za(e);case"weekly_date_range":return ja(e);case"weekly_date_range_with_year":return Qa(e);case"year":return gn(e);case"lookup":return ct({...e,valueFormat:t.fallback});default:{const n=t;throw new Error(`Unhandled value format: ${n.type}`)}}},jf={type:"decimal"},Qf=({layers:e,coordSystem:t,scales:n,guides:r,numberFormat:a,parsingLocale:o,hover:s,formattingLocale:i})=>{const{primary:c}=s;if(c===null)return null;const l=i??o;return{header:Zf({layers:e,coordSystem:t,guides:r,primary:c,locale:l,numberFormat:a}),rows:Jf({layers:e,coordSystem:t,scales:n,guides:r,hover:s,locale:l,numberFormat:a})}};function Zf(e){if(e.coordSystem.type!=="cartesian")return null;const t=bt(e.guides,"x");if(!t)return null;const n=e.layers.find(s=>s.id===e.primary.layerId);if(!n)return null;const r=n.semanticMap.encodings.find(s=>s.aesthetic==="x");if(!r)return null;const a=e.primary.observation[r.variable];return u.isDefined(a)?ct({valueFormat:t.valueFormat,locale:e.locale,numberFormat:e.numberFormat})(a):null}function Jf(e){const t=[],n=e.scales.color??null,r=rh({guides:e.guides,locale:e.locale,numberFormat:e.numberFormat});for(const a of e.layers){const o=th(a,e.hover);if(o.length===0)continue;if(a.semanticMap.detailRows.length>0){const{primary:p}=e.hover;p!==null&&p.layerId===a.id&&t.push(...eh({layer:a,observation:p.observation,coordSystem:e.coordSystem,locale:e.locale,numberFormat:e.numberFormat}));continue}const s=xa(a.data,a.mapping),i=nh(o,a,n,s),c=xc(a.semanticMap),l=V({valueFormat:oh(a),locale:e.locale,numberFormat:e.numberFormat}),d=ah(e.guides,a),m=a.mapping.color!==void 0,f=Ne(a.swatchShape,e.coordSystem);for(const p of i){const h=m?s(p.observation):null,y=Wt(p.observation)??null,g=Br(p.observation),S=m&&h!==null?r(h):d,b=sh(c,p),x=b===null?"":l(b,p.observation);t.push({swatchColor:y,swatchShape:f,swatchLineType:g,label:S,value:x,isPrimary:p===e.hover.primary,key:`${p.layerId}:${p.pointIndex}`})}}return t}function eh(e){const t=Ne(e.layer.swatchShape,e.coordSystem);return e.layer.semanticMap.detailRows.map((n,r)=>{const a=V({valueFormat:n.valueFormat,locale:e.locale,numberFormat:e.numberFormat}),o=e.observation[n.variable]??null;return{swatchColor:null,swatchShape:t,swatchLineType:"solid",label:n.label,value:o===null?"":a(o,e.observation),isPrimary:!1,key:`${e.layer.id}:detail:${r}`}})}function th(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 nh(e,t,n,r){if(n===null||t.mapping.color===void 0)return e;const a=new Map;return n.domain.forEach((o,s)=>{a.set(u.getStableKey(o),s)}),e.map((o,s)=>{const i=r(o.observation),c=i===null?null:u.getStableKey(i),l=c===null?Number.POSITIVE_INFINITY:a.get(c)??Number.POSITIVE_INFINITY;return{hit:o,originalIndex:s,rank:l}}).sort((o,s)=>o.rank===s.rank?o.originalIndex-s.originalIndex:o.rank-s.rank).map(o=>o.hit)}function rh({guides:e,locale:t,numberFormat:n}){const r=new Map(e.colorGroups.map(o=>[u.getStableKey(o.value),{label:o.label,format:ct({valueFormat:o.valueFormat,locale:t,numberFormat:n})}])),a=ct({valueFormat:{type:"text"},locale:t,numberFormat:n});return o=>{const s=r.get(u.getStableKey(o));return s===void 0?a(o):s.label??s.format(o)}}function ah(e,t){const n=Ue(t.yScaleType);return bt(e,n)?.label??""}function oh(e){return e.semanticMap.encodings.find(n=>n.aesthetic==="y")?.valueFormat??jf}function sh(e,t){return e(t.observation).encodings.find(r=>r.aesthetic==="y")?.value??null}const ih={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 bo(...e){let t={},n;const[r,...a]=e;u.isDefined(r)&&!lh(r)?(t=r,n=a):n=e;const o={mapping:t,layers:[],scales:[],transforms:[],highlights:[],config:{}};return n.reduce((s,i)=>So(s,i),o)}function ch(e,...t){return t.reduce((n,r)=>So(n,r),e)}function lh(e){return typeof e=="object"&&e!==null&&"type"in e}function So(e,t){switch(t.type){case"scale":return{...e,scales:[...e.scales,t]};case"coord":return{...e,coords:t};case"config":return{...e,config:_r({},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{...e,annotations:{...e.annotations,custom:[...e.annotations?.custom??[],t.annotation]}};default:{const n=t;throw new Error(`Unknown spec item type: ${n.type}`)}}}function uh(e){const t={};for(const r of e.geoms??[]){const a=r;t[a.type]=(o={})=>({type:"layer",geom:a.type,mapping:o.aes,stat:o.stat,params:{...a.defaultParams,...o.params},position:o.position,yScaleType:o.yScaleType,transforms:o.transforms,interactive:o.interactive,dataLabels:o.dataLabels})}const n={};for(const r of e.annotations??[]){const a=r;n[a.type]=o=>(dh(a,o.coordinates),{type:"annotation",annotation:{id:o.id,type:a.type,coordinates:o.coordinates,params:{...a.defaultParams,...o.params},zOrder:o.zOrder}})}return{geom:{...I,...t},annotation:n,createSpec:bo}}function dh(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 mh(e,t={}){return{type:"highlight",id:t.id,predicate:e,scope:t.scope,layerIndex:t.layerIndex}}function ph(e){return{mapping:e.mapping,layers:e.layers,scales:e.scales.map(hh),transforms:e.transforms,highlights:e.highlights.map(t=>fh(t,e.layers)),coords:e.coords,config:e.config}}function fh(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 hh(e){return e.scaleType==="palette"?yh(e):e}function yh(e){return{...e,palette:gh(e.palette)}}function gh(e){return e.type==="custom"?{type:"custom",id:e.id}:e}class bh{constructor(t={}){this.undoStack=[],this.redoStack=[],this.listeners=new Set,this.isEmitting=!1,this.cachedSnapshot=null,this.maxHistorySize=t.maxHistorySize??100}apply(t,n){return this.withReentrancyGuard(()=>{const r=t.apply(n);return r?(this.undoStack.push({command:t,revert:r.revert}),this.redoStack=[],this.undoStack.length>this.maxHistorySize&&this.undoStack.shift(),this.emit({type:"apply",command:t,spec:r.spec}),r.spec):n})}undo(t){return this.withReentrancyGuard(()=>{const n=this.undoStack.pop();if(!n)return null;const r=n.revert.apply(t);return r?(this.redoStack.push({command:n.command,revert:r.revert}),this.emit({type:"undo",command:n.command,spec:r.spec}),{spec:r.spec,command:n.command}):(this.undoStack.push(n),null)})}redo(t){return this.withReentrancyGuard(()=>{const n=this.redoStack.pop();if(!n)return null;const r=n.revert.apply(t);return r?(this.undoStack.push({command:n.command,revert:r.revert}),this.emit({type:"redo",command:n.command,spec:r.spec}),{spec:r.spec,command:n.command}):(this.redoStack.push(n),null)})}clear(){this.withReentrancyGuard(()=>{this.undoStack=[],this.redoStack=[],this.emit({type:"clear"})})}getSnapshot(){return this.cachedSnapshot||(this.cachedSnapshot={canUndo:this.undoStack.length>0,canRedo:this.redoStack.length>0,undoDescription:this.undoStack[this.undoStack.length-1]?.command.metadata.description??null,redoDescription:this.redoStack[this.redoStack.length-1]?.command.metadata.description??null}),this.cachedSnapshot}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}withReentrancyGuard(t){if(this.isEmitting)throw new Error("CommandStack: cannot call apply/undo/redo/clear from within a listener");this.isEmitting=!0;try{return t()}finally{this.isEmitting=!1}}emit(t){this.cachedSnapshot=null;for(const n of this.listeners)try{n(t)}catch(r){console.error("CommandStack listener error:",r)}}}function ue(e){return{id:e.id??crypto.randomUUID(),timestamp:e.timestamp??Date.now(),description:e.description,author:e.author??"unknown"}}class En{constructor(t,n={}){this.type="set-axis-position",this.params=t,this.metadata=ue({...n,description:`Set ${t.axis} axis position to ${t.position}`})}apply(t){const{axis:n,position:r}=this.params,a=Oe(t,{config:{axes:{[n]:{position:r}}}}),o=n==="x"?{axis:"x",position:t.config.axes.x.position}:{axis:"y",position:t.config.axes.y.position},s=new En(o,this.metadata);return{spec:a,revert:s}}}class Mn{constructor(t,n={}){this.type="set-content-caption",this.params=t,this.metadata=ue({...n,description:"Set chart caption"})}apply(t){const n=t.config.content.caption;if(n===this.params.caption)return null;const r=Oe(t,{config:{content:{caption:this.params.caption}}}),a=new Mn({caption:n},this.metadata);return{spec:r,revert:a}}}class Dn{constructor(t,n={}){this.type="set-content-subtitle",this.params=t,this.metadata=ue({...n,description:"Set chart subtitle"})}apply(t){const n=t.config.content.subtitle;if(n===this.params.subtitle)return null;const r=Oe(t,{config:{content:{subtitle:this.params.subtitle}}}),a=new Dn({subtitle:n},this.metadata);return{spec:r,revert:a}}}class Rn{constructor(t,n={}){this.type="set-content-title",this.params=t,this.metadata=ue({...n,description:"Set chart title"})}apply(t){const n=t.config.content.title;if(n===this.params.title)return null;const r=Oe(t,{config:{content:{title:this.params.title}}}),a=new Rn({title:n},this.metadata);return{spec:r,revert:a}}}class Cn{constructor(t,n={}){this.type="set-headline-show",this.params=t,this.metadata=ue({...n,description:`Set headline show to ${t.show}`})}apply(t){const n=t.config.headline.show,r=Oe(t,{config:{headline:{show:this.params.show}}}),a=new Cn({show:n},this.metadata);return{spec:r,revert:a}}}class kn{constructor(t,n={}){this.type="set-line-width",this.params=t,this.metadata=ue({...n,description:`Set line width to ${t.lineWidth}`})}apply(t){const n=this.params.layerId?nd(t.layers,this.params.layerId):Fa(t.layers,"line","area");if(!td(n,"line","area"))return null;const r=n.params.lineWidth,a=rd(t,n.id,{...n,params:{...n.params,lineWidth:this.params.lineWidth}}),o=new kn({layerId:n.id,lineWidth:r},this.metadata);return{spec:a,revert:o}}}function Sh(e,t){return e.scales.find(n=>n.scaledAesthetic===t)}function xh(e,t,n){const r=e.scales.map(a=>a.scaledAesthetic===t?n:a);return{...e,scales:r}}function vh(e){const t=e.replace(/([A-Z])/g," $1").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}class _n{constructor(t,n={}){this.type="set-scale-domain",this.params=t,this.metadata=ue({...n,description:`Set ${vh(t.scaledAesthetic)} scale domain`})}apply(t){const n=Sh(t,this.params.scaledAesthetic);if(!n||n.scaleType!=="continuous"&&n.scaleType!=="datetime")return null;const r={min:n.domainMin??null,max:n.domainMax??null},a={...n,...this.params.domainMin!==void 0&&{domainMin:this.params.domainMin},...this.params.domainMax!==void 0&&{domainMax:this.params.domainMax}},o=xh(t,this.params.scaledAesthetic,a),s={scaledAesthetic:this.params.scaledAesthetic};this.params.domainMin!==void 0&&(s.domainMin=r.min),this.params.domainMax!==void 0&&(s.domainMax=r.max);const i=new _n(s,this.metadata);return{spec:o,revert:i}}}const Nn=500,Fn="normal",xo={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},Ah=e=>{const t=e.style??Fn,n=e.weight??Nn,r=e.family.includes(",")?e.family:`'${e.family}'`;return`${t} ${n} ${e.size}px ${r}`},Th=e=>typeof e=="string"?e:vo(e),vo=e=>e.text!==void 0?e.text:e.content?e.content.map(vo).join(""):"",Ao=e=>typeof e!="string"?e??Nn:xo[e],wh="\0";class Ih{constructor(t){this.inner=t,this.cache=new Map}measureText(t,n){const r=this.getCacheKey(t,n),a=this.cache.get(r);if(a)return a;const o=this.inner.measureText(t,n);return this.cache.set(r,o),o}getCacheKey(t,n){return[n.family,n.size,Ao(n.weight),n.style??Fn,t].join(wh)}}const Vh={" ":.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},Lh=.55,Eh=1.05,Mh=.84,Dh=.21;class Rh{measureText(t,n){let r=0;for(const i of t)r+=(Vh[i]??Lh)*n.size;Ao(n.weight)>=xo.semiBold&&(r*=Eh);const o=Mh*n.size,s=Dh*n.size;return{width:r,height:o+s,ascent:o,descent:s}}}exports.Dataset=u.Dataset;exports.GROUP_VARIABLES=u.GROUP_VARIABLES;exports.POSITION_VARIABLES=u.POSITION_VARIABLES;exports.VISUAL_VARIABLES=u.VISUAL_VARIABLES;exports.isDefined=u.isDefined;exports.mapping=u.mapping;exports.prefixInternalVariable=u.prefixInternalVariable;exports.BORDER_PRESETS=Da;exports.BORDER_PRESET_GRADIENTS=ih;exports.BUILTIN_GEOM_NAMES=ya;exports.COMPILER_STAGE_KEYS=Bd;exports.CachedTextMeasurer=Ih;exports.CommandStackManager=bh;exports.Compiler=Ya;exports.DEFAULT_COLOR_PALETTE=rn;exports.DEFAULT_FONT_STYLE=Fn;exports.DEFAULT_FONT_WEIGHT=Nn;exports.DEFAULT_LOCALE=dt;exports.GEOM_NAMES=ha;exports.HeuristicTextMeasurer=Rh;exports.HoverEngine=Wf;exports.LAYOUT_PADDING=ro;exports.LayoutCompiler=$m;exports.MONO_BASES=Va;exports.NEON_BASES=La;exports.RESTING_HOVER_STATE=te;exports.SetAxisPositionCommand=En;exports.SetContentCaptionCommand=Mn;exports.SetContentSubtitleCommand=Dn;exports.SetContentTitleCommand=Rn;exports.SetHeadlineShowCommand=Cn;exports.SetLineWidthCommand=kn;exports.SetScaleDomainCommand=_n;exports.SpecResolver=Ba;exports.buildAverageLineSymbols=Km;exports.buildDataLabelsContent=Ep;exports.buildFontString=Ah;exports.buildLayerYValueFormatter=po;exports.buildTooltipContent=Qf;exports.computeDifferenceArrow=Np;exports.computeDirectLabelsLayout=Op;exports.computeFreeformArrow=rf;exports.config=Ra;exports.convertSpecToInput=ph;exports.coord=R;exports.createAlphaValueReader=uc;exports.createColorValueReader=xa;exports.createCompiler=Gd;exports.createEmptyHighlight=va;exports.createGraphyBuilder=uh;exports.createGroupValueReader=dc;exports.createLabelValueReader=cc;exports.createRawValueReader=O;exports.createSegmentYReader=tn;exports.createSizeValueReader=lc;exports.createSpec=bo;exports.createStrokeWidthValueReader=mc;exports.createValueFormatter=V;exports.createXValueReader=en;exports.createYValueReader=Sa;exports.extractPlainText=Th;exports.findAxisGuide=bt;exports.findLegendForAesthetic=zp;exports.formatHeadline=Pp;exports.formatLegends=Hp;exports.formatRuleValue=Xp;exports.geom=I;exports.getAlpha=_o;exports.getAngleExtent=uo;exports.getColor=Wt;exports.getCrossAxisCoordinate=gt;exports.getDifferenceArrowDimensions=vn;exports.getGroup=be;exports.getIdentityKey=ft;exports.getLineType=Br;exports.getMainAxisCoordinate=Fe;exports.getRadiusExtent=mo;exports.getSize=Pr;exports.getStrokeWidth=No;exports.getX=ve;exports.getXMax=ye;exports.getXMin=_e;exports.getY=z;exports.getYMax=$;exports.getYMin=se;exports.getYRaw=ia;exports.highlight=mh;exports.isBuiltinGeomName=ga;exports.isCartesian=zm;exports.isCompilerCachingEnabled=Lo;exports.isGraphConfig=Ea;exports.isLayerOf=Ud;exports.isStackedPosition=F;exports.pipe=ch;exports.resolveHeadlinePlacement=Bm;exports.resolveSegmentYSource=$e;exports.resolveYScaleAesthetic=Ue;exports.scale=ae;exports.setCompilerCachingEnabled=Vo;exports.stat=an;exports.transform=re;
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;