@nova-energy/openamx 0.21.0 → 0.22.0

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/README.md CHANGED
@@ -21,8 +21,10 @@ not certified risk models or industry standards.
21
21
  results as JSON or CSV.
22
22
  - **Build visual explanations.** Create tables, charts, and formula-driven 2D
23
23
  diagrams alongside the narrative.
24
- - **Use the latest language additions.** V0.20 adds AMX-to-TypeScript graph
25
- transpilation for calculation and data workflows. V0.19 lets charts omit their data table
24
+ - **Use the latest language additions.** V0.22 adds synchronous TypeScript
25
+ blocks with source-ordered AMX interoperation and mixed-block TypeScript
26
+ graph emission. V0.20 adds AMX-to-TypeScript graph transpilation for
27
+ calculation and data workflows. V0.19 lets charts omit their data table
26
28
  with `showTable false` (the omitted default) and adds affine offset units for
27
29
  Celsius/Fahrenheit-style conversions. V0.18 adds diagram-local loops and
28
30
  conditionals, V0.16 adds statement-bodied functions, and V0.14 adds runtime
@@ -62,7 +64,7 @@ Release builds are unsigned, so your operating system may show a warning.
62
64
  ### CLI
63
65
 
64
66
  The CLI is published to npm as `@nova-energy/openamx` and runs on
65
- [Bun](https://bun.sh/) 1.0 or newer. Node.js and Deno are not supported.
67
+ [Bun](https://bun.sh/) 1.4.4 or newer. Node.js and Deno are not supported.
66
68
 
67
69
  1. Install Bun using the instructions at [bun.sh](https://bun.sh/).
68
70
  2. Install OpenAMX:
@@ -149,7 +151,8 @@ unified HTML/PDF/DOCX export workflow.
149
151
  the [battery-resistor circuit](examples/14_Battery_Resistor_Circuit.amx), and
150
152
  [function bodies](examples/15_Function_Bodies.amx) and
151
153
  [TypeScript graph transpilation](examples/16_TypeScript_Transpilation.amx)
152
- are standalone references.
154
+ and [TypeScript blocks](examples/17_TypeScript_Blocks.amx) are standalone
155
+ references.
153
156
  - V0.12 features: [records and enums](examples/04_Typed_Records_Enums_and_Modules.amx)
154
157
  and [expressions and decisions](examples/02_Expressions_and_Decisions.amx).
155
158
  - V0.13/V0.18 diagrams: [formula-driven diagrams](examples/08_Formula_Driven_Diagrams.amx)
@@ -167,6 +170,7 @@ Read the [V0.9 language specification](docs/language-spec-v0.9.md) and
167
170
  [V0.18 diagram generation specification](docs/language-spec-v0.18.md), and the
168
171
  additive [V0.19 rendering and affine-unit specification](docs/language-spec-v0.19.md)
169
172
  followed by the additive [V0.20 TypeScript transpilation specification](docs/language-spec-v0.20.md)
173
+ and [V0.22 TypeScript blocks specification](docs/language-spec-v0.22.md)
170
174
  for the current language contract. V0.19 omits chart data tables by default;
171
175
  authors that intentionally retain one use `showTable true` or another Boolean
172
176
  expression that resolves true. Browse the [examples](examples/) and
@@ -52,30 +52,43 @@ function parseDocumentBody(body, startLine) {
52
52
  continue;
53
53
  }
54
54
  const fence = opening[2];
55
- const isExecutable = fence[0] === '`' && opening[3].trim() === 'amx';
55
+ const infoString = opening[3].trim();
56
+ const isExecutable = fence[0] === '`' && infoString === 'amx';
57
+ const isTypeScript = fence[0] === '`' && infoString === 'ts';
56
58
  const closingIndex = findClosingFence(lines, index + 1, fence);
57
- if (!isExecutable) {
59
+ if (!isExecutable && !isTypeScript) {
58
60
  index = closingIndex === -1 ? lines.length : closingIndex + 1;
59
61
  continue;
60
62
  }
61
63
  const openerLocation = { line: startLine + index, column: opening[1].length + 1 };
62
64
  if (closingIndex === -1) {
63
- throw new Error(`Unclosed amx fence at ${openerLocation.line}:${openerLocation.column}`);
65
+ const language = isExecutable ? 'amx' : 'ts';
66
+ throw new Error(`Unclosed ${language} fence at ${openerLocation.line}:${openerLocation.column}`);
64
67
  }
65
68
  flushNarrative(line.start, index === 0 ? 0 : narrativeLineIndex(lines, narrativeStart));
66
69
  const contentStart = line.nextStart;
67
70
  const contentEnd = lines[closingIndex].start;
68
71
  const content = body.slice(contentStart, contentEnd);
69
- const statements = parseStatements(content, {
70
- line: startLine + index + 1,
71
- column: 1
72
- });
73
- nodes.push({
74
- type: 'executableCodeBlock',
75
- content,
76
- statements,
77
- source: openerLocation
78
- });
72
+ if (isExecutable) {
73
+ const statements = parseStatements(content, {
74
+ line: startLine + index + 1,
75
+ column: 1
76
+ });
77
+ nodes.push({
78
+ type: 'executableCodeBlock',
79
+ content,
80
+ statements,
81
+ source: openerLocation
82
+ });
83
+ }
84
+ else {
85
+ nodes.push({
86
+ type: 'typescriptCodeBlock',
87
+ content,
88
+ source: openerLocation,
89
+ contentSource: { line: startLine + index + 1, column: 1 }
90
+ });
91
+ }
79
92
  index = closingIndex + 1;
80
93
  narrativeStart = lines[closingIndex].nextStart;
81
94
  }
@@ -1,2 +1,2 @@
1
- const diagramBrowserRuntime = "(()=>{class M extends Error{code;file;line;column;declarationSource;fieldSource;diagnostics;constructor(e,n){super(e.message);this.name=\"AmxError\",this.code=e.code,this.file=e.file,this.line=e.line,this.column=e.column,this.declarationSource=e.declarationSource,this.fieldSource=e.fieldSource,this.diagnostics=n}}function _(e,n,t={}){return{code:e,message:n,...t}}function P(e){let n=e[0]??_(\"AMX4001\",\"Input validation failed\");throw new M(n,e)}function w(e,n,t,r,i){throw new M({code:e,message:n,file:r,line:t?.line,column:t?.column,declarationSource:i})}function S(e,n,t){throw new M({code:\"AMX1009\",message:e,file:t,line:n?.line,column:n?.column})}function fn(e,n,t){return{code:\"AMX1004\",message:`Undefined identifier '${e}'`,file:t,line:n?.line,column:n?.column}}function de(e,n,t){let r=fn(e,n,t);throw new M(r)}function fe(e,n){throw new M({code:\"AMX1005\",message:\"Range bounds must be finite integers\",file:n,line:e?.line,column:e?.column})}function Fe(e,n){throw new M({code:\"AMX1006\",message:\"For loops require a list or range value\",file:n,line:e?.line,column:e?.column})}function Ve(e,n){throw new M({code:\"AMX1007\",message:\"Return is only valid inside an expression-form for loop\",file:n,line:e?.line,column:e?.column})}function Xe(e,n){throw new M({code:\"AMXF4002\",message:\"Function finished without returning a valid expression\",file:n,line:e?.line,column:e?.column})}function k(e,n,t){throw new M({code:\"AMX1008\",message:e,file:t,line:n?.line,column:n?.column})}var ze=new WeakMap;function z(e,n){ze.set(e,n)}function L(e,n){return ze.get(e)??n}class j{store=new Map;recordTypes;enumDeclarations=new Map;enumValues=new Map;functions;bindingTypes=new Map;dimensionRegistry;viewDefinitions=new Map;viewEmissions=[];diagramEmissions=[];immutableValues=new WeakSet;currentDocumentNodeIndex=-1;currentStatementIndex=-1;validationMode=\"aggregate\";constructor(e=new Map,n=new Map,t){this.recordTypes=e,this.functions=n,this.dimensionRegistry=t}createCallFrame(e){let n=new j(this.recordTypes,this.functions,this.dimensionRegistry);n.validationMode=this.validationMode;for(let[t,r]of this.bindingTypes)n.bindingTypes.set(t,r);for(let[t,r]of this.enumDeclarations)n.enumDeclarations.set(t,r);for(let[t,r]of this.enumValues)n.enumValues.set(t,r);for(let[t,r]of Object.entries(e))if(n.set(t,r),this.isImmutable(r))n.markImmutable(r);return n}set(e,n){this.store.set(e,n)}markImmutable(e){let n=(t)=>{if(!t||typeof t!==\"object\"||this.immutableValues.has(t))return;if(this.immutableValues.add(t),Array.isArray(t))t.forEach(n);else Object.values(t).forEach(n)};n(e)}isImmutable(e){return!!e&&typeof e===\"object\"&&this.immutableValues.has(e)}update(e,n,t,r){if(!this.store.has(e))de(e,t,r);this.store.set(e,n)}delete(e){this.store.delete(e)}get(e,n,t){if(!this.store.has(e))de(e,n,t);return this.store.get(e)}has(e){return this.store.has(e)}toObject(){let e={};for(let[n,t]of this.store.entries())e[n]=t;return e}clear(){this.store.clear(),this.immutableValues=new WeakSet,this.viewDefinitions.clear(),this.viewEmissions.length=0,this.diagramEmissions.length=0}}function b(e){return!!e&&typeof e===\"object\"&&e.__amxMeasurement===!0&&typeof e.value===\"number\"&&!!e.unit}function je(e){return Object.freeze(Object.fromEntries(e))}function pe(e){let n=[...e].filter((i)=>i.exponent!==0).sort((i,o)=>i.identity<o.identity?-1:i.identity>o.identity?1:0),t=n.filter((i)=>i.exponent>0).map((i)=>`${i.name}${i.exponent===1?\"\":` ^ ${i.exponent}`}`),r=n.filter((i)=>i.exponent<0).map((i)=>`${i.name}${i.exponent===-1?\"\":` ^ ${-i.exponent}`}`);return`${t.length?t.join(\" * \"):\"1\"}${r.length?` / ${r.join(\" * \")}`:\"\"}`}function te(e){let n=[{identity:e.identity,name:e.name,exponent:1}];return Object.freeze({scale:e.scale,offset:e.offset,vector:je(e.vector),factors:Object.freeze(n),text:e.name})}function pn(e,n){return e*n.scale+n.offset}function gn(e,n){return(e-n.offset)/n.scale}function x(e){return pn(e.value,e.unit)}function Z(e,n){return gn(e,n)}function N(e){return e.offset!==0}function yn(e,n,t){let r=new Map;for(let i of e.factors)r.set(i.identity,{...i});for(let i of n.factors){let o=r.get(i.identity);r.set(i.identity,{identity:i.identity,name:i.name,exponent:(o?.exponent??0)+i.exponent*t})}return[...r.values()].filter((i)=>i.exponent!==0)}function bn(e,n,t){let r={...e.vector};for(let[i,o]of Object.entries(n.vector)){let a=(r[i]??0)+o*t;if(a)r[i]=a;else delete r[i]}return r}function Oe(e,n,t=!1){if(N(e)||N(n))throw Error(\"Affine measurement units cannot be composed\");let r=t?-1:1,i=yn(e,n,r);return Object.freeze({scale:t?e.scale/n.scale:e.scale*n.scale,offset:0,vector:Object.freeze(bn(e,n,r)),factors:Object.freeze(i),text:pe(i)})}function ge(e,n){if(N(e))throw Error(\"Affine measurement units may not be powered\");let t=e.factors.map((r)=>({...r,exponent:r.exponent*n})).filter((r)=>r.exponent!==0);return Object.freeze({scale:Math.pow(e.scale,n),offset:e.offset,vector:Object.freeze(Object.fromEntries(Object.entries(e.vector).map(([r,i])=>[r,i*n]).filter(([,r])=>r!==0))),factors:Object.freeze(t),text:pe(t)})}function D(e,n){return Object.freeze({__amxMeasurement:!0,value:e,unit:n})}function ne(e,n){let t=[];for(let[r,i]of[...e].sort(([o],[a])=>o<a?-1:o>a?1:0)){let o=n.baseUnits.get(r);if(!o)throw Error(`No visible canonical base unit for dimension identity ${r}`);t.push({identity:o.identity,name:o.name,exponent:i})}return Object.freeze({scale:1,offset:0,vector:je(e),factors:Object.freeze(t),text:pe(t)})}function Ce(e,n){if(N(e.unit))throw Error(\"Affine measurement sqrt is not supported\");let t=new Map;for(let[l,u]of Object.entries(e.unit.vector)){if(u%2!==0)throw Error(\"sqrt requires integral measurement dimension exponents\");t.set(l,u/2)}let r=x(e),i=Math.sqrt(r);if(!Number.isFinite(i))return D(i,ne(t,n));let o=Math.sqrt(e.unit.scale),a=[...n.units.values()].find((l)=>l.scale===o&&l.vector.size===t.size&&[...t].every(([u,c])=>l.vector.get(u)===c));if(a)return D(i/a.scale,te(a));let s=ne(t,n);return D(i,s)}function re(e,n,t,r){if(!Array.isArray(e)){let i=t?` at line ${t.line}`:\"\";throw new M({code:\"AMX2001\",message:`${n} expects a list${i}`,file:r,line:t?.line,column:t?.column})}return e}function I(e,n,t,r){if(typeof e===\"number\")return e;if(typeof e===\"boolean\")return e?1:0;if(typeof e===\"string\"){let o=Number(e);if(!Number.isNaN(o))return o}let i=t?` at line ${t.line}`:\"\";throw new M({code:\"AMX2002\",message:`${n} requires a numeric value${i}`,file:r,line:t?.line,column:t?.column})}function O(e,n,t,r,i){if(e.length!==n){let o=r?` at line ${r.line}`:\"\";throw new M({code:\"AMX2003\",message:`${t} expects ${n} argument(s), got ${e.length}${o}`,file:i,line:r?.line,column:r?.column})}}function hn(e,n,t,r,i){if(e.length<n){let o=r?` at line ${r.line}`:\"\";throw new M({code:\"AMX2003\",message:`${t} expects at least ${n} argument(s), got ${e.length}${o}`,file:i,line:r?.line,column:r?.column})}}var _e={sin:{evaluate:Math.sin,accepts:Number.isFinite},cos:{evaluate:Math.cos,accepts:Number.isFinite},tan:{evaluate:Math.tan,accepts:Number.isFinite},asin:{evaluate:Math.asin,accepts:(e)=>Number.isFinite(e)&&e>=-1&&e<=1},acos:{evaluate:Math.acos,accepts:(e)=>Number.isFinite(e)&&e>=-1&&e<=1},atan:{evaluate:Math.atan,accepts:Number.isFinite},sinh:{evaluate:Math.sinh,accepts:Number.isFinite},cosh:{evaluate:Math.cosh,accepts:Number.isFinite},tanh:{evaluate:Math.tanh,accepts:Number.isFinite},asinh:{evaluate:Math.asinh,accepts:Number.isFinite},acosh:{evaluate:Math.acosh,accepts:(e)=>Number.isFinite(e)&&e>=1},atanh:{evaluate:Math.atanh,accepts:(e)=>Number.isFinite(e)&&e>-1&&e<1},ln:{evaluate:Math.log,accepts:(e)=>Number.isFinite(e)&&e>0},log:{evaluate:Math.log10,accepts:(e)=>Number.isFinite(e)&&e>0},exp:{evaluate:Math.exp,accepts:Number.isFinite}};function Pe(e){return Object.hasOwn(_e,e)}function Ue(e,n,t,r){return new M({code:e,message:n,file:r,line:t?.line,column:t?.column})}function T(e,n,t,r){return new M({code:e,message:n,file:r,line:t?.line,column:t?.column})}function ye(e){if(e===null)return\"null\";if(b(e))return\"Measurement\";if(Array.isArray(e))return\"list\";if(typeof e===\"number\")return\"Number\";if(typeof e===\"string\")return\"String\";if(typeof e===\"boolean\")return\"Boolean\";return typeof e}function ie(e,n,t,r,i,o){if(n.length<t||n.length>r)throw T(\"AMX3004\",`Invalid arity for '${e}'`,i,o)}function qe(e,n,t,r){if(typeof n!==\"string\")throw T(\"AMX3002\",`${e} requires a String, got ${ye(n)}`,t,r);return n}function Be(e){return e>=9&&e<=13||e===32||e===133||e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288}function wn(e){let n=Array.from(e),t=0,r=n.length;while(t<r&&Be(n[t].codePointAt(0)))t++;while(r>t&&Be(n[r-1].codePointAt(0)))r--;return n.slice(t,r).join(\"\")}function xn(e,n,t){if(typeof e!==\"string\")throw T(\"AMXSL004\",\"Incorrect formatting pattern\",n,t);let r=/^([$€£])?(#,##0|0)(?:\\.(0{1,6}))?(%)?$/.exec(e);if(!r)throw T(\"AMXSL004\",\"Incorrect formatting pattern\",n,t);return{currency:r[1]??\"\",grouped:r[2]===\"#,##0\",precision:r[3]?.length??0,percent:r[4]===\"%\"}}function Mn(e,n,t){switch(e){case\"en-US\":return{decimal:\".\",group:\",\"};case\"de-DE\":return{decimal:\",\",group:\".\"};case\"fr-FR\":return{decimal:\",\",group:\" \"};default:throw T(\"AMXSL005\",\"Formatting locale is malformed or unsupported\",n,t)}}function En(e,n){let[t,r]=Math.abs(e).toString().toLowerCase().split(\"e\"),i=r===void 0?0:Number(r),[o,a=\"\"]=t.split(\".\"),s=`${o}${a}`.replace(/^0+(?=\\d)/,\"\"),l=BigInt(s||\"0\"),u=n+i-a.length;if(u>=0)return l*10n**BigInt(u);let c=10n**BigInt(-u),m=l/c,d=l%c;return m+(d*2n>=c?1n:0n)}function vn(e,n){return e.replace(/\\B(?=(\\d{3})+(?!\\d))/g,n)}function An(e,n,t){let r=n.percent?e*100:e,i=r<0,o=10n**BigInt(n.precision),a=En(r,n.precision),s=(a/o).toString(),l=n.precision?`${t.decimal}${(a%o).toString().padStart(n.precision,\"0\")}`:\"\",u=n.grouped?vn(s,t.group):s;return`${i?\"-\":\"\"}${n.currency}${u}${l}${n.percent?\"%\":\"\"}`}function J(e,n,t,r,i=[]){let o=(s)=>i[s]??t;if(e===\"len\"){ie(e,n,1,1,t,r);let s=n[0];if(typeof s===\"string\")return Array.from(s).length;if(Array.isArray(s))return s.length;throw T(\"AMX3002\",`len requires a String or list, got ${ye(s)}`,o(0),r)}if(e===\"trim\")return ie(e,n,1,1,t,r),wn(qe(e,n[0],o(0),r));if(e===\"left\"||e===\"right\"){ie(e,n,1,2,t,r);let s=Array.from(qe(e,n[0],o(0),r)),l=n.length===1?1:n[1];if(typeof l!==\"number\"||!Number.isFinite(l)||!Number.isInteger(l)||l<0)throw T(\"AMXSL003\",\"Invalid text slice count\",o(1),r);let u=Math.min(l,s.length);return e===\"left\"?s.slice(0,u).join(\"\"):s.slice(s.length-u).join(\"\")}if(e===\"format\"){ie(e,n,2,3,t,r);let s=n[0],l=o(0);if(typeof s!==\"number\"&&!b(s))throw T(\"AMX3002\",`format expects a Number or Measurement, got ${ye(s)}`,l,r);let u=b(s)?s.value:s;if(!Number.isFinite(u))throw T(\"AMXSL006\",\"Input is non-finite\",l,r);let c=xn(n[1],o(1),r),m=Mn(n.length===3?n[2]:\"en-US\",o(2),r);if(c.percent&&!Number.isFinite(u*100))throw T(\"AMXSL006\",\"Input is non-finite\",l,r);let d=An(u,c,m);return b(s)?`${d} ${s.unit.text}`:d}let a=_e[e];if(a){if(n.length!==1)throw new M({code:\"AMX3004\",message:`Invalid arity for '${e}'`,file:r,line:t?.line,column:t?.column});let s=n[0];if(typeof s!==\"number\"){let u=s===null?\"null\":Array.isArray(s)?\"list\":typeof s===\"object\"?\"Measurement\":typeof s===\"string\"?\"String\":typeof s===\"boolean\"?\"Boolean\":typeof s;throw new M({code:\"AMX3002\",message:`Expected Number or dimensionless Measurement, got ${u}`,file:r,line:t?.line,column:t?.column})}if(!a.accepts(s))throw Ue(\"AMXSL001\",\"Invalid input for mathematical function\",t,r);let l=a.evaluate(s);if(!Number.isFinite(l))throw Ue(\"AMXSL002\",\"Function evaluation results in infinite result\",t,r);return l}switch(e){case\"sum\":return O(n,1,\"sum\",t,r),re(n[0],\"sum\",t,r).reduce((u,c)=>u+I(c,\"sum element\",t,r),0);case\"min\":{O(n,1,\"min\",t,r);let l=re(n[0],\"min\",t,r);if(l.length===0){let u=t?` at line ${t.line}`:\"\";throw new M({code:\"AMX2004\",message:`min of empty list${u}`,file:r,line:t?.line,column:t?.column})}return l.reduce((u,c)=>Math.min(u,I(c,\"min element\",t,r)),Number.POSITIVE_INFINITY)}case\"max\":{O(n,1,\"max\",t,r);let l=re(n[0],\"max\",t,r);if(l.length===0){let u=t?` at line ${t.line}`:\"\";throw new M({code:\"AMX2004\",message:`max of empty list${u}`,file:r,line:t?.line,column:t?.column})}return l.reduce((u,c)=>Math.max(u,I(c,\"max element\",t,r)),Number.NEGATIVE_INFINITY)}case\"mean\":{O(n,1,\"mean\",t,r);let l=re(n[0],\"mean\",t,r);if(l.length===0){let c=t?` at line ${t.line}`:\"\";throw new M({code:\"AMX2004\",message:`mean of empty list${c}`,file:r,line:t?.line,column:t?.column})}return l.reduce((c,m)=>c+I(m,\"mean element\",t,r),0)/l.length}case\"round\":{hn(n,1,\"round\",t,r);let l=I(n[0],\"round value\",t,r),u=n.length>1?I(n[1],\"round digits\",t,r):0,c=Math.pow(10,Math.trunc(u));return Math.round(l*c)/c}case\"abs\":{O(n,1,\"abs\",t,r);let l=I(n[0],\"abs value\",t,r);return Math.abs(l)}case\"sqrt\":{O(n,1,\"sqrt\",t,r);let l=I(n[0],\"sqrt value\",t,r);if(l<0){let u=t?` at line ${t.line}`:\"\";throw new M({code:\"AMX2005\",message:`sqrt of negative value${u}`,file:r,line:t?.line,column:t?.column})}return Math.sqrt(l)}case\"pow\":{O(n,2,\"pow\",t,r);let l=I(n[0],\"pow base\",t,r),u=I(n[1],\"pow exponent\",t,r);return Math.pow(l,u)}default:let s=t?` at line ${t.line}`:\"\";throw new M({code:\"AMX2000\",message:`Unknown function '${e}'${s}`,file:r,line:t?.line,column:t?.column})}}function C(e,n,t,r,i,o){let a=[],s=(u,c,m,d,f)=>{let p=_(\"AMX4003\",u,{file:i,line:r?.line,column:r?.column,dataPath:d,expected:be(c),actual:we(m),fieldSource:f});if(a.push(p),t.validationMode===\"fail-fast\")P([p])},l=(u,c,m,d)=>{if(c.kind===\"null\"){if(u!==null)s(\"Expected null\",c,u,m,d);return}if(c.kind===\"nullable\"){if(u!==null)l(u,c.element,m,d);return}if(c.kind===\"list\"){if(!Array.isArray(u)){s(\"Expected a list value\",c,u,m,d);return}u.forEach((h,A)=>l(h,c.element,`${m}[${A}]`,d));return}if(c.kind===\"measurement\"){if(!b(u)){s(\"Expected a measurement value\",c,u,m,d);return}let h=u.unit.vector;if(Object.keys(h).length!==c.vector.size||[...c.vector].some(([A,F])=>h[A]!==F))s(\"Measurement dimension does not match the declared dimension\",c,u,m,d);if(!Number.isFinite(u.value)||!Number.isFinite(x(u)))s(\"Measurement value must be finite\",c,u,m,d);return}if(c.kind!==\"named\")return;if(c.name===\"Number\"){if(typeof u!==\"number\"||!Number.isFinite(u))s(\"Expected a finite Number value\",c,u,m,d);return}if(c.name===\"String\"||c.name===\"DateTime\"){if(typeof u!==\"string\")s(`Expected a ${c.name} value`,c,u,m,d);else if(c.name===\"DateTime\"&&!He(u))s(\"Invalid RFC 3339 DateTime value\",c,u,m,d);return}if(c.name===\"Boolean\"){if(typeof u!==\"boolean\")s(\"Expected a Boolean value\",c,u,m,d);return}let f=t.recordTypes.get(c.name);if(!f||typeof u!==\"object\"||u===null||Array.isArray(u)){s(`Expected a ${c.name} record`,c,u,m,d);return}let p=u,g=new Set(f.fields.map((h)=>h.name));for(let h of f.fields){let A=L(h,t.dimensionRegistry);if(!Object.prototype.hasOwnProperty.call(p,h.name))s(`Missing computed field '${h.name}'`,W(h.annotation,A),\"missing\",`${m}.${h.name}`,h.source);else l(p[h.name],W(h.annotation,A),`${m}.${h.name}`,h.source)}for(let h of Object.keys(p).filter((A)=>!g.has(A)).sort())s(`Unknown computed field '${h}'`,c,p[h],`${m}.${h}`,d)};if(l(e,n,o),a.length)P(a)}function Sn(e,n,t){if(!e.defaultExpression)return null;let r=n.dimensionRegistry;n.dimensionRegistry=L(e,r);try{return y(e.defaultExpression,n,t)}finally{n.dimensionRegistry=r}}function W(e,n){let t=n instanceof j?n.dimensionRegistry:n;if(e.type===\"namedType\"){let i=t?.dimensions.get(e.name);return i?{kind:\"measurement\",vector:i.vector}:{kind:\"named\",name:e.name}}let r=W(e.element,t);return e.type===\"listType\"?{kind:\"list\",element:r}:{kind:\"nullable\",element:r}}function be(e){if(e.kind===\"named\")return e.name;if(e.kind===\"measurement\")return\"measurement\";if(e.kind===\"null\")return\"null\";return e.kind===\"list\"?`${be(e.element)}[]`:`${be(e.element)}?`}function we(e){if(typeof e===\"number\"&&!Number.isFinite(e))return String(e);let n;try{n=JSON.stringify(e)??String(e)}catch{n=String(e)}return n.replace(/[\\x00-\\x1f\\x7f]/g,(t)=>`\\\\u${t.charCodeAt(0).toString(16).padStart(4,\"0\")}`).slice(0,160)}function H(e,n){return Object.keys(e.unit.vector).length===n.size&&[...n].every(([t,r])=>e.unit.vector[t]===r)}function He(e){let n=e.match(/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,9})?(Z|[+-]\\d{2}:\\d{2})$/);if(!n)return!1;let[,t,r,i,o,a,s,l]=n,u=new Date(0);return u.setUTCFullYear(+t,+r-1,+i),u.getUTCFullYear()===+t&&u.getUTCMonth()===+r-1&&u.getUTCDate()===+i&&+o<=23&&+a<=59&&+s<=59&&(l===\"Z\"||+l.slice(1,3)<=23&&+l.slice(4)<=59)}function oe(e,n,t,r,i=t.dimensionRegistry){if(n.type===\"nullableType\")return e===null||oe(e,n.element,t,r,i);if(n.type===\"listType\")return Array.isArray(e)&&e.every((u)=>oe(u,n.element,t,r,i));let o=n.name,a=i?.dimensions.get(o);if(a)return b(e)&&H(e,a.vector);if(o===\"Number\")return typeof e===\"number\";if(o===\"String\")return typeof e===\"string\";if(o===\"Boolean\")return typeof e===\"boolean\";if(o===\"DateTime\")return typeof e===\"string\"&&He(e);let s=t.enumDeclarations.get(o);if(s){if(typeof e!==\"number\"&&typeof e!==\"string\")return!1;if(!s.resolvedValues)throw Error(`Enum '${o}' has not been resolved`);return s.resolvedValues.includes(e)}let l=t.recordTypes.get(o);if(l){if(typeof e!==\"object\"||e===null||Array.isArray(e)||b(e))return!1;let u=e;return l.fields.every((c)=>{if(!Object.prototype.hasOwnProperty.call(u,c.name))return c.optional;return oe(u[c.name],c.annotation,t,r,L(c,i))})}return w(\"AMX3001\",`Unknown type '${o}'`,n.source,r)}function y(e,n,t){switch(e.type){case\"nullLiteral\":return null;case\"recordConstructor\":{let r=n.recordTypes.get(e.name);if(!r)throw Error(`Unknown record type '${e.name}'`);let i=new Map(e.fields.map((a)=>[a.name,y(a.expression,n,t)])),o={};for(let a of r.fields)o[a.name]=i.has(a.name)?i.get(a.name):a.defaultExpression?Sn(a,n,t):null;return C(o,{kind:\"named\",name:e.name},n,e.source,t,`record ${e.name}`),o}case\"fieldAccess\":{if(e.receiver.type===\"identifier\"){let r=n.enumValues.get(e.receiver.name);if(r)return r[e.field]}return y(e.receiver,n,t)[e.field]}case\"listAccess\":return $n(e,n,t);case\"numberLiteral\":return e.value;case\"stringLiteral\":return e.value;case\"stringInterpolation\":return e.parts.map((r)=>{if(typeof r===\"string\")return r;let i=y(r,n,t);if(i===null)return\"null\";if(typeof i===\"string\"||typeof i===\"number\")return String(i);if(typeof i===\"boolean\")return i?\"true\":\"false\";if(b(i))return`${String(i.value)} ${i.unit.text}`;return w(\"AMX3007\",\"Only String, Number, Boolean, measurement, and null values can be interpolated\",r.source,t)}).join(\"\");case\"booleanLiteral\":return e.value;case\"identifier\":if(e.name===\"PI\")return Math.PI;if(e.name===\"E\")return Math.E;return n.get(e.name,e.source,t);case\"measurementAttachment\":{let r=y(e.value,n,t),i=n.dimensionRegistry?.units.get(e.unit);if(!i)return w(\"AMX3008\",`Unknown or invisible unit '${e.unit}'`,e.unitSource??e.source,t);if(typeof r!==\"number\")return w(\"AMX3007\",\"Unit attachment requires a Number expression\",e.source,t);let o=D(r,te(i));if(!Number.isFinite(x(o)))S(\"Measurement physical value must be finite\",e.source,t);return o}case\"measurementConversion\":{let r=y(e.value,n,t),i=n.dimensionRegistry?.units.get(e.unit);if(!i)return w(\"AMX3008\",`Unknown or invisible unit '${e.unit}'`,e.unitSource??e.source,t);if(!b(r)||!H(r,i.vector))return w(\"AMX3007\",`Cannot convert value to unit '${e.unit}'`,e.source,t);let o=te(i),a=Z(x(r),o);if(!Number.isFinite(a))S(\"Converted measurement value must be finite\",e.source,t);return D(a,o)}case\"binaryExpression\":return Nn(e,n,t);case\"typeTestExpression\":return oe(y(e.value,n,t),e.target,n,t);case\"unaryExpression\":return kn(e,n,t);case\"conditionalExpression\":return In(e,n,t);case\"bracedIfExpression\":return Rn(e,n,t);case\"listLiteral\":return Ln(e,n,t);case\"functionCall\":return Vn(e,n,t);case\"rangeExpression\":return qn(e,n,t);case\"forExpression\":return _n(e,n,t);case\"matchExpression\":return Dn(e,n,t);default:throw Error(`Unsupported expression node type: ${e}`)}}function Dn(e,n,t){let r=y(e.expression,n,t);for(let i of e.cases)if(r===i.value.value)return y(i.expression,n,t);return y(e.defaultExpression,n,t)}function Nn(e,n,t){let r=y(e.left,n,t),i=y(e.right,n,t),o=e.operatorSource??e.source;switch(e.operator){case\"+\":case\"-\":{if(b(r)||b(i)){if(!b(r)||!b(i)||!H(r,new Map(Object.entries(i.unit.vector))))return w(\"AMX3007\",\"Addition and subtraction require compatible measurements\",o,t);if(e.operator===\"+\"&&(N(r.unit)||N(i.unit)))return w(\"AMX3007\",\"Direct addition of affine measurements is not supported\",o,t);let l=x(r),u=x(i),c=e.operator===\"+\"?l+u:l-u,m=e.operator===\"+\"?Z(c,r.unit):c/r.unit.scale;if(!Number.isFinite(m)||!Number.isFinite(c))S(\"Measurement arithmetic result must be finite\",o,t);return D(m,r.unit)}let a=E(r,e.left),s=E(i,e.right);return e.operator===\"+\"?a+s:a-s}case\"*\":case\"/\":{if(b(r)||b(i)){let l={scale:1,offset:0,vector:{},factors:[],text:\"1\"},u=b(r)?r:void 0,c=b(i)?i:void 0;if(u&&N(u.unit)||c&&N(c.unit))return w(\"AMX3007\",e.operator===\"*\"?\"Affine measurement multiplication is not supported\":\"Affine measurement division is not supported\",o,t);let m=u?u.value:E(r,e.left),d=c?c.value:E(i,e.right),f=u?.unit??l,p=c?.unit??l,g=u?x(u):m,h=c?x(c):d;if(e.operator===\"/\"&&h===0)S(\"Measurement division by zero\",o,t);let A=Oe(f,p,e.operator===\"/\"),F=e.operator===\"/\"?g/h:g*h;if(A.vector&&Object.keys(A.vector).length===0){if(!Number.isFinite(F))S(\"Measurement arithmetic result must be finite\",o,t);return F}let Y=e.operator===\"/\"?m/d:m*d;if(!Number.isFinite(A.scale)||A.scale<=0||!Number.isFinite(Y)||!Number.isFinite(F))S(\"Measurement arithmetic result must be finite\",o,t);return D(Y,A)}let a=E(r,e.left),s=E(i,e.right);return e.operator===\"*\"?a*s:a/s}case\"%\":{let a=E(r,e.left),s=E(i,e.right);return a%s}case\"^\":{if(b(r)){if(N(r.unit))return w(\"AMX3007\",\"Affine measurement powers are not supported\",o,t);let l=E(i,e.right);if(!Number.isSafeInteger(l))return w(\"AMX3007\",\"A dimensional power exponent must be an integer literal\",e.right.source,t);if(r.value===0&&l<0)S(\"Zero measurement cannot be raised to a negative power\",o,t);let u=ge(r.unit,l),c=Math.pow(r.value,l);if(!Number.isFinite(c)||!Number.isFinite(u.scale))S(\"Measurement power result must be finite\",o,t);let m=D(c,u);if(Object.keys(u.vector).length===0)return x(m);return m}let a=E(r,e.left),s=E(i,e.right);return Math.pow(a,s)}case\"==\":if(b(r)&&b(i))return H(r,new Map(Object.entries(i.unit.vector)))&&x(r)===x(i);return r===i;case\"!=\":if(b(r)&&b(i))return!H(r,new Map(Object.entries(i.unit.vector)))||x(r)!==x(i);return r!==i;case\">\":if(b(r)&&b(i))return x(r)>x(i);return E(r,e.left)>E(i,e.right);case\">=\":if(b(r)&&b(i))return x(r)>=x(i);return E(r,e.left)>=E(i,e.right);case\"<\":if(b(r)&&b(i))return x(r)<x(i);return E(r,e.left)<E(i,e.right);case\"<=\":if(b(r)&&b(i))return x(r)<=x(i);return E(r,e.left)<=E(i,e.right);case\"and\":return R(r)&&R(i);case\"or\":return R(r)||R(i);default:throw Error(`Unsupported binary operator: ${e.operator}`)}}function kn(e,n,t){let r=y(e.argument,n,t);if(e.operator===\"-\"){if(b(r))return D(-r.value,r.unit);return-E(r,e.argument)}if(e.operator===\"not\")return!R(r);throw Error(`Unsupported unary operator: ${e.operator}`)}function In(e,n,t){let r=y(e.test,n,t);return R(r)?y(e.consequent,n,t):y(e.alternate,n,t)}class xe{value;constructor(e){this.value=e}}class Me{value;constructor(e){this.value=e}}class Ee{value;constructor(e){this.value=e}}var Ge=new WeakMap,Ye=new WeakMap,ve=new WeakMap,ae=new WeakMap;function Ae(e,n,t){e.set(n,(e.get(n)??0)+1);try{return t()}finally{let r=e.get(n)-1;if(r)e.set(n,r);else e.delete(n)}}function Tn(e,n){let t=ae.get(n),r=t?.[t.length-1];if(!r||r.has(e))return;let i=n.has(e);r.set(e,{existed:i,value:i?n.get(e):void 0})}function Se(e,n,t){let r=ae.get(n)??[],i=new Map;r.push(i),ae.set(n,r);try{De(e,n,t)}finally{r.pop();for(let[o,a]of i)if(a.existed)n.set(o,a.value);else n.delete(o);if(!r.length)ae.delete(n)}}function Rn(e,n,t){let r=R(y(e.test,n,t))?e.consequent:e.alternate,i=r===e.consequent?e.consequentSource:e.alternateSource;try{Ae(Ge,n,()=>Se(r,n,t))}catch(o){if(o instanceof xe)return o.value;throw o}return w(\"AMX3021\",\"Every possible path in an if expression must return a value\",i??e.source,t)}function Ln(e,n,t){return e.elements.map((r)=>y(r,n,t))}function $n(e,n,t){let r=y(e.receiver,n,t),i=y(e.index,n,t);if(!Array.isArray(r))k(\"List access requires a list value\",e.source,t);if(typeof i!==\"number\"||!Number.isFinite(i)||!Number.isInteger(i)||i<1)k(`List index must be a positive integer; got ${we(i)}`,e.index.source??e.source,t);if(i>r.length)k(`List index ${i} is out of bounds for length ${r.length}; expected 1..${r.length}`,e.index.source??e.source,t);return r[i-1]}function se(e,n){if(e.type===\"binaryExpression\")return se(e.left,n)??e.operatorSource??e.source??n;if(e.type===\"unaryExpression\"){let t=se(e.argument,n);if(t)return{line:t.line,column:Math.max(1,t.column-(e.operator===\"not\"?3:1))}}if(e.type===\"measurementAttachment\"||e.type===\"measurementConversion\")return se(e.value,n)??e.source??n;return e.source??n}function Ze(e){return Array.isArray(e)?e.map(Ze):e}function Fn(e){return e.kind===\"list\"||e.kind===\"nullable\"&&e.element.kind===\"list\"}function Vn(e,n,t){let r=e.arguments.map((a)=>y(a,n,t)),i=n.functions.get(e.callee);if(i){let a=L(i,n.dimensionRegistry),s={};i.parameters.forEach((m,d)=>{let f=W(m.annotation,a);C(r[d],f,n,e.arguments[d]?.source??e.source,t,`function ${e.callee}.${m.name}`);let p=r[d];s[m.name]=Fn(f)&&p!==null?Ze(p):p});let l=n.createCallFrame(s);l.dimensionRegistry=a,i.parameters.forEach((m)=>{l.bindingTypes.set(m.name,W(m.annotation,a))});let u,c=i.body;if(c.kind===\"expression\")u=y(c.expression,l,t);else{let m=!1;try{Ae(ve,l,()=>De(c.statements,l,t))}catch(d){if(!(d instanceof Ee))throw d;m=!0,u=d.value}if(!m)Xe(c.closingSource,t)}return C(u,W(i.returnType,a),n,e.source,t,`function ${e.callee} return`),u}let o=r[0];if([\"sum\",\"mean\",\"min\",\"max\"].includes(e.callee)&&Array.isArray(o)&&(o.length>0&&b(o[0]))){let a=o,s=a[0];for(let m of a){if(!H(s,new Map(Object.entries(m.unit.vector))))return w(\"AMX3007\",`${e.callee} requires compatible measurement dimensions`,e.source,t);if(Array.isArray(o)&&o.length>0&&typeof o[0]===\"number\"&&[\"sum\",\"mean\",\"min\",\"max\"].includes(e.callee))return J(e.callee,r,e.source,t)}if(e.callee===\"min\"||e.callee===\"max\"){if(!a.length)return J(e.callee,r,e.source,t);return a.reduce((m,d)=>(e.callee===\"min\"?x(d)<x(m):x(d)>x(m))?d:m)}let l=a.reduce((m,d)=>m+x(d),0),u=e.callee===\"mean\"?l/a.length:l,c=Z(u,s.unit);if(!Number.isFinite(l)||!Number.isFinite(u)||!Number.isFinite(c))S(`${e.callee} result must be finite`,e.source,t);return D(c,s.unit)}if(e.callee===\"sum\"&&Array.isArray(o)&&o.length===0&&e.arguments[0]?.type===\"identifier\"){let a=n.bindingTypes.get(e.arguments[0].name);if(a?.kind===\"list\"&&a.element.kind===\"measurement\"&&n.dimensionRegistry)return D(0,ne(a.element.vector,n.dimensionRegistry))}if(b(r[0])){let a=r[0];if(Pe(e.callee)){if(Object.keys(a.unit.vector).length!==0)return w(\"AMX3007\",`'${e.callee}' requires a Number or dimensionless Measurement`,e.arguments[0]?.source??e.source,t);return J(e.callee,[x(a)],e.source,t)}switch(e.callee){case\"abs\":return D(Math.abs(a.value),a.unit);case\"round\":{let s=r.length>1?E(r[1],e.arguments[1]):0,l=Math.pow(10,Math.trunc(s)),u=Math.round(a.value*l)/l;if(!Number.isFinite(u))S(\"round result must be finite\",e.source,t);return D(u,a.unit)}case\"sqrt\":{if(N(a.unit))return w(\"AMX3007\",\"Affine measurement sqrt is not supported\",e.source,t);if(x(a)<0)S(\"sqrt of a negative measurement value\",e.source,t);if(!n.dimensionRegistry)throw Error(\"Measurement registry is unavailable during sqrt evaluation\");try{let l=Ce(a,n.dimensionRegistry);if(!Number.isFinite(l.value)||!Number.isFinite(l.unit.scale))S(\"sqrt result must be finite\",e.source,t);if(Object.keys(l.unit.vector).length===0)return x(l);return l}catch(l){if(l instanceof Error&&l.message.startsWith(\"sqrt requires\"))return w(\"AMX3007\",l.message,e.source,t);throw l}}case\"pow\":{if(N(a.unit))return w(\"AMX3007\",\"Affine measurement powers are not supported\",e.source,t);let s=E(r[1],e.arguments[1]);if(!Number.isSafeInteger(s))return w(\"AMX3007\",\"A dimensional pow exponent must be an integer literal\",e.arguments[1]?.source,t);if(a.value===0&&s<0)S(\"Zero measurement cannot be raised to a negative power\",e.source,t);let l=ge(a.unit,s),u=Math.pow(a.value,s);if(!Number.isFinite(u)||!Number.isFinite(l.scale))S(\"pow result must be finite\",e.source,t);let c=D(u,l);if(!Object.keys(l.vector).length)return x(c);return c}}}return J(e.callee,r,e.source,t,e.arguments.map((a)=>se(a,e.source)))}function E(e,n){if(typeof e===\"number\")return e;if(typeof e===\"boolean\")return e?1:0;if(typeof e===\"string\"){let i=Number(e);if(!Number.isNaN(i))return i}let t=n?.source,r=t?` at line ${t.line}`:\"\";throw Error(`Cannot convert value to number${r}`)}function R(e){if(typeof e===\"boolean\")return e;if(typeof e===\"number\")return e!==0;if(typeof e===\"string\")return e.length>0;if(Array.isArray(e))return e.length>0;if(e&&typeof e===\"object\")return!0;return!1}function De(e,n,t){let r=n.currentStatementIndex;try{for(let i=0;i<e.length;i++)n.currentStatementIndex=i,Ke(e[i],n,t)}finally{n.currentStatementIndex=r}}function G(e){if(b(e))return`${e.value} ${e.unit.text}`;if(Array.isArray(e))return Object.freeze(e.map(G));if(e&&typeof e===\"object\"){let n={};for(let[t,r]of Object.entries(e))n[t]=G(r);return Object.freeze(n)}return e}function Xn(e,n,t,r){let i=n.viewDefinitions.get(e);if(!i)return w(\"AMX3001\",`Unknown visualization '${e}'`,r,t);let o=n.get(i.binding,i.bindingSource,t);if(!Array.isArray(o)){let d=_(\"AMX4003\",`Visualization '${e}' requires a list value`,{file:t,line:i.bindingSource?.line,column:i.bindingSource?.column,dataPath:`visualization ${e}`,expected:\"list\",actual:Array.isArray(o)?\"list\":typeof o});P([d])}let a,s,l,u=!1,c;if(i.type===\"chartDeclaration\"){let d=i.options.find((g)=>g.type===\"chartShowTableOption\");if(d?.type===\"chartShowTableOption\"){let g=y(d.expression,n,t);if(typeof g!==\"boolean\")w(\"AMX3002\",`Expected Boolean, got ${typeof g}`,d.expression.source,t);u=g}let f=i.options.find((g)=>g.type===\"chartFieldOption\"&&g.role===\"labels\");if(f?.type===\"chartFieldOption\"){let g=n.get(f.field,f.fieldSource,t);if(!Array.isArray(g)||!g.every((h)=>typeof h===\"string\")){let h=_(\"AMX4003\",`Chart '${e}' labels must be a String[] value`,{file:t,line:f.source?.line,column:f.source?.column,dataPath:`visualization ${e}.labels`,expected:\"String[]\",actual:Array.isArray(g)?\"invalid list value\":typeof g});P([h])}if(g.length!==o.length){let h=_(\"AMX4003\",`Chart '${e}' has ${o.length} values but ${g.length} labels`,{file:t,line:f.source?.line,column:f.source?.column,dataPath:`visualization ${e}.labels`,expected:`${o.length} labels`,actual:`${g.length} labels`});P([h])}a=G(g)}let p=zn(o,i,e,t);c=p.data,s=p.headings,l=p.measurementDescriptors}else c=G(o);let m={name:e,data:c,documentNodeIndex:n.currentDocumentNodeIndex,statementIndex:n.currentStatementIndex,source:r};return i.type===\"tableDeclaration\"?Object.freeze({kind:\"table\",...m,declaration:i}):Object.freeze({kind:\"chart\",...m,declaration:i,showTable:u,...a?{labels:a}:{},...s?{headings:s}:{},...l?.length?{measurementDescriptors:l}:{}})}function zn(e,n,t,r){let i=n.kind===\"scatter\",o=i?n.options.filter((c)=>c.type===\"chartFieldOption\"&&(c.role===\"x\"||c.role===\"y\")).map((c)=>({role:c.role,field:c.field,label:c.role,source:c.source})):n.options.filter((c)=>c.type===\"chartSeriesOption\").map((c)=>({role:\"series\",field:c.field,label:c.label,source:c.source})),a=o.map((c)=>{let m=c.field,d=e.map((g)=>g!==null&&typeof g===\"object\"&&!Array.isArray(g)&&!b(g)?g[m??\"\"]:m===void 0?g:void 0),f=d.find((g)=>g!==null&&g!==void 0),p=b(f)?f:void 0;for(let g of d){if(g===null||g===void 0)continue;if(p){if(!b(g)||!Je(g,p))w(\"AMX3007\",`Chart '${t}' contains incompatible measurement dimensions`,c.source,r,n.source)}else if(b(g))w(\"AMX3007\",`Chart '${t}' mixes measurements with non-measurement values`,c.source,r,n.source)}return p}),s=i?[\"x\",\"y\"].map((c,m)=>a[m]?`${c} (${a[m].unit.text})`:c).concat(\"group\"):[\"label\",...o.flatMap((c,m)=>c.role===\"series\"?[a[m]?`${c.label} (${a[m].unit.text})`:c.label]:[])],l=o.flatMap((c,m)=>{let d=a[m]?.unit;if(!d)return[];return[Object.freeze({role:c.role,...c.field===void 0?{}:{field:c.field},label:c.label,unit:Object.freeze({text:d.text,scale:d.scale,vector:Object.freeze({...d.vector}),factors:Object.freeze(d.factors.map((f)=>Object.freeze({...f})))})})]}),u=e.map((c)=>{if(c!==null&&typeof c===\"object\"&&!Array.isArray(c)&&!b(c)){let m={};for(let[d,f]of Object.entries(c)){let p=o.findIndex((g)=>g.field===d);m[d]=p<0?G(f):We(f,a[p],t,o[p]?.source,n,r)}return Object.freeze(m)}return We(c,a[0],t,o[0]?.source,n,r)});return{data:Object.freeze(u),headings:Object.freeze(s),measurementDescriptors:Object.freeze(l)}}function We(e,n,t,r,i,o){if(e===null||e===void 0)return null;if(!n)return G(e);if(!b(e)||!Je(e,n))w(\"AMX3007\",`Chart '${t}' contains an incompatible measurement value`,r,o,i.source);let a=Z(x(e),n.unit);if(!Number.isFinite(a))w(\"AMX3007\",`Chart '${t}' measurement cannot be normalized to its first display unit`,r,o,i.source);return a}function Je(e,n){let t=Object.entries(e.unit.vector);return t.length===Object.keys(n.unit.vector).length&&t.every(([r,i])=>n.unit.vector[r]===i)}function Ke(e,n,t){switch(e.type){case\"importDeclaration\":case\"exportNamesDeclaration\":return;case\"dimensionDeclaration\":case\"unitDeclaration\":return;case\"inputDeclaration\":return;case\"tableDeclaration\":case\"chartDeclaration\":n.viewDefinitions.set(e.name,e);return;case\"diagramDeclaration\":n.diagramEmissions.push({model:en(e,n,t,n.currentDocumentNodeIndex,n.currentStatementIndex)});return;case\"showStatement\":n.viewEmissions.push(Xn(e.name,n,t,e.source));return;case\"typeDeclaration\":n.recordTypes.set(e.name,e);return;case\"enumDeclaration\":{let r=e.resolvedValues??e.members.map((o,a)=>{if(!o.value)return a+1;if(o.value.type===\"numberLiteral\"||o.value.type===\"stringLiteral\")return o.value.value;return w(\"AMX3020\",\"Only constant values can be assigned to enum members\",o.valueSource??o.value.source,t)}),i={};e.members.forEach((o,a)=>{i[o.name]=r[a]}),n.enumDeclarations.set(e.name,e),n.enumValues.set(e.name,i);return}case\"functionDeclaration\":n.functions.set(e.name,e);return;case\"variableDeclaration\":{Tn(e.name,n);let r=y(e.expression,n,t),i=n.bindingTypes.get(e.name);if(i)C(r,i,n,e.source,t,e.name);n.set(e.name,r)}return;case\"assignmentStatement\":{let r=y(e.expression,n,t),i=n.bindingTypes.get(e.name);if(i)C(r,i,n,e.source,t,e.name);n.update(e.name,r,e.source,t);return}case\"compoundAssignmentStatement\":{let r=y({type:\"binaryExpression\",operator:\"+\",left:{type:\"identifier\",name:e.name,source:e.source},right:e.expression,source:e.source},n,t),i=n.bindingTypes.get(e.name);if(i)C(r,i,n,e.source,t,e.name);n.update(e.name,r,e.source,t);return}case\"addStatement\":Cn(e,n,t);return;case\"removeStatement\":Un(e,n,t);return;case\"forStatement\":Bn(e,n,t);return;case\"bracedIfStatement\":jn(e,n,t);return;case\"returnStatement\":if(Ge.has(n))throw new xe(y(e.expression,n,t));if(Ye.has(n))throw new Me(y(e.expression,n,t));if(ve.has(n))throw new Ee(y(e.expression,n,t));Ve(e.source,t)}}function jn(e,n,t){let r=R(y(e.test,n,t))?e.consequent:e.alternate;if(r)Se(r,n,t)}function Qe(e,n,t,r){let i=n.get(e,t,r);if(!Array.isArray(i))k(`Mutation target '${e}' is not a list`,t,r);if(n.isImmutable(i))k(`Cannot mutate immutable imported list '${e}'`,t,r);return i}function On(e,n){let t=n.bindingTypes.get(e);return t?.kind===\"list\"?t.element:void 0}function he(e,n,t,r){if(typeof e!==\"number\"||!Number.isFinite(e)||!Number.isInteger(e)||e<1)k(`${n} must be a positive integer; got ${we(e)}`,t,r);return e}function Cn(e,n,t){let r=Qe(e.name,n,e.source,t),i=y(e.value,n,t),o=On(e.name,n);if(o)C(i,o,n,e.value.source??e.source,t,`${e.name} element`);let a=e.index?he(y(e.index,n,t),\"Insertion position\",e.index.source??e.source,t):r.length+1;if(a>r.length+1)k(`Insertion position ${a} is out of bounds for length ${r.length}; expected 1..${r.length+1}`,e.index?.source??e.source,t);r.splice(a-1,0,i)}function Un(e,n,t){let r=Qe(e.name,n,e.source,t),i=he(y(e.count,n,t),\"Removal count\",e.count.source??e.source,t);if(r.length===0)k(\"Cannot remove from an empty list\",e.source,t);if(!e.index){r.pop();return}let o=he(y(e.index,n,t),\"Removal position\",e.index.source??e.source,t);if(o>r.length)k(`Removal position ${o} is out of bounds for length ${r.length}; expected 1..${r.length}`,e.index.source??e.source,t);if(i>r.length-o+1)k(`Removal interval ${o}..${o+i-1} exceeds list length ${r.length}`,e.count.source??e.source,t);r.splice(o-1,i)}function qn(e,n,t){let r=y(e.start,n,t),i=y(e.end,n,t);if(typeof r!==\"number\"||!Number.isFinite(r)||!Number.isInteger(r)||typeof i!==\"number\"||!Number.isFinite(i)||!Number.isInteger(i))fe(e.source,t);let o=[],a=r<=i?1:-1;for(let s=r;a>0?s<=i:s>=i;s+=a)if(o.push(s),s+a===s&&s!==i)fe(e.source,t);return o}function Bn(e,n,t){let r=ce(e.iterable,n,t);K(e.variable,r,n,()=>{if(ve.has(n))Se(e.body,n,t);else De(e.body,n,t)})}function _n(e,n,t){let r=ce(e.iterable,n,t),i=[];return Ae(Ye,n,()=>K(e.variable,r,n,()=>{for(let o of e.body)if(o.type===\"returnStatement\")i.push(y(o.expression,n,t));else try{Ke(o,n,t)}catch(a){if(a instanceof Me)i.push(a.value);else throw a}})),i}function ce(e,n,t){let r=y(e,n,t);if(!Array.isArray(r))Fe(e.source,t);return r.slice()}function K(e,n,t,r){let i=t.has(e),o=i?t.get(e):void 0;try{for(let a of n)t.set(e,a),r()}finally{if(i)t.set(e,o);else t.delete(e)}}var ke=new WeakMap,Ie=new WeakMap;function nn(e){return e.some((n)=>n.type!==\"diagramElement\")}function Pn(e){if(nn(e.declaration.content))throw Error(\"Version 1 control-bearing diagram models are missing expanded instances.\")}function V(e){if(!Array.isArray(e)||typeof e[0]!==\"string\")throw Error(\"Invalid serialized diagram value.\");switch(e[0]){case\"undefined\":if(e.length!==1)throw Error(\"Invalid serialized undefined diagram value.\");return;case\"null\":if(e.length!==1)throw Error(\"Invalid serialized null diagram value.\");return null;case\"boolean\":if(e.length!==2||typeof e[1]!==\"boolean\")throw Error(\"Invalid serialized boolean diagram value.\");return e[1];case\"number\":if(e.length!==2)throw Error(\"Invalid serialized number diagram value.\");if(e[1]===\"nan\")return NaN;if(e[1]===\"positive-infinity\")return 1/0;if(e[1]===\"negative-infinity\")return-1/0;if(typeof e[1]!==\"number\")throw Error(\"Invalid serialized number diagram value.\");return e[1];case\"string\":if(e.length!==2||typeof e[1]!==\"string\")throw Error(\"Invalid serialized string diagram value.\");return e[1];case\"array\":if(e.length!==2||!Array.isArray(e[1]))throw Error(\"Invalid serialized array diagram value.\");return e[1].map(V);case\"object\":{if(e.length!==2||!Array.isArray(e[1]))throw Error(\"Invalid serialized object diagram value.\");let n=e[1].map((t)=>{if(!Array.isArray(t)||t.length!==2||typeof t[0]!==\"string\")throw Error(\"Invalid serialized object entry in diagram value.\");return[t[0],V(t[1])]});return Object.fromEntries(n)}case\"map\":if(e.length!==2||!Array.isArray(e[1]))throw Error(\"Invalid serialized map diagram value.\");return new Map(e[1].map((n)=>{if(!Array.isArray(n)||n.length!==2)throw Error(\"Invalid serialized map entry in diagram value.\");return[V(n[0]),V(n[1])]}));case\"set\":if(e.length!==2||!Array.isArray(e[1]))throw Error(\"Invalid serialized set diagram value.\");return new Set(e[1].map(V));default:throw Error(\"Unknown serialized diagram value type.\")}}function Q(e,n){if(!(e instanceof Map))throw Error(`Invalid serialized diagram context map '${n}'.`);for(let t of e.keys())if(typeof t!==\"string\")throw Error(`Invalid key in serialized diagram context map '${n}'.`);return e}function Ne(e,n=new Set){if(e===void 0||e===null||typeof e===\"boolean\"||typeof e===\"number\"||typeof e===\"string\")return;if(!e||typeof e!==\"object\")throw Error(\"Unsupported serialized diagram instance binding value.\");if(n.has(e))throw Error(\"Serialized diagram instance binding contains a cyclic value.\");n.add(e);try{if(Array.isArray(e)){e.forEach((r)=>Ne(r,n));return}let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw Error(\"Unsupported serialized diagram instance binding value.\");Object.values(e).forEach((r)=>Ne(r,n))}finally{n.delete(e)}}function Wn(e,n){if(!Array.isArray(n))throw Error(\"Invalid serialized diagram instance source path.\");let t=e,r=0,i=!1,o=[];while(r<n.length){let a=n[r++];if(!a||typeof a!==\"object\"||Array.isArray(a)||a.type!==\"content\"||!Number.isSafeInteger(a.index)||a.index<0)throw Error(\"Invalid serialized diagram instance source path.\");let s=t[a.index];if(!s)throw Error(\"Serialized diagram instance source path does not resolve.\");if(s.type===\"diagramElement\"){if(r!==n.length)throw Error(\"Serialized diagram instance source path continues past a primitive.\");return{element:s,bindingNames:o,controlOriginating:i}}if(i=!0,s.type===\"diagramForBlock\"){o.push(s.variable),t=s.content;continue}let l=n[r++];if(!l||typeof l!==\"object\"||Array.isArray(l)||l.type!==\"branch\"||l.branch!==\"consequent\"&&l.branch!==\"alternate\")throw Error(\"Invalid serialized diagram instance branch path.\");if(t=l.branch===\"consequent\"?s.consequent:s.alternate??[],l.branch===\"alternate\"&&!s.alternate)throw Error(\"Serialized diagram instance source path does not resolve.\")}throw Error(\"Serialized diagram instance source path does not resolve to a primitive.\")}function Hn(e,n){if(!Array.isArray(n))throw Error(\"Invalid serialized diagram instance list.\");let t=0,r=n.map((i,o)=>{if(!i||typeof i!==\"object\"||Array.isArray(i)||!(\"identity\"in i)||!(\"bindings\"in i)||!Number.isSafeInteger(i.identity)||i.identity!==o||!Array.isArray(i.bindings))throw Error(\"Invalid serialized diagram instance descriptor.\");let a=i,s=a.bindings,l=Wn(e,a.sourcePath);if(l.controlOriginating&&++t>on)throw Error(\"Serialized diagram instance list exceeds the generated element limit.\");if(s.length!==l.bindingNames.length)throw Error(\"Serialized diagram instance has incomplete loop bindings.\");let u=s.map((c,m)=>{if(!c||typeof c!==\"object\"||Array.isArray(c)||!(\"name\"in c)||!(\"value\"in c))throw Error(\"Invalid serialized diagram instance loop binding.\");let d=c;if(d.name!==l.bindingNames[m]||typeof d.name!==\"string\")throw Error(\"Invalid serialized diagram instance loop binding.\");let f=V(d.value);return Ne(f),Object.freeze({name:d.name,value:f})});return Object.freeze({identity:a.identity,element:l.element,bindings:Object.freeze(u)})});return Object.freeze(r)}function tn(e){let n=JSON.parse(e);if(!n||typeof n!==\"object\"||Array.isArray(n)||!(\"version\"in n)||n.version!==1&&n.version!==2||!(\"model\"in n)||!(\"context\"in n))throw Error(\"Invalid serialized diagram model envelope.\");let t=n,r=t.version;if(r===2){if(!Array.isArray(t.instances))throw Error(\"Invalid serialized diagram instance list.\");if(!Number.isSafeInteger(t.instanceCount)||t.instanceCount!==t.instances.length)throw Error(\"Serialized diagram instance count does not match its payload.\")}let i=V(t.model),o=V(t.context);if(!i||typeof i!==\"object\"||Array.isArray(i)||!o||typeof o!==\"object\"||Array.isArray(o))throw Error(\"Invalid serialized diagram model or evaluation context.\");let a=ue(i);if(!a.declaration||!Array.isArray(a.declaration.content))throw Error(\"Invalid serialized diagram declaration.\");let s=r===1?(Pn(a),an(a.declaration.content)):Hn(a.declaration.content,t.instances),l=o;if(!l.values||typeof l.values!==\"object\"||Array.isArray(l.values)||!Array.isArray(l.immutableValues)||!l.declarationRegistries||!Array.isArray(l.declarationRegistries.records)||!Array.isArray(l.declarationRegistries.functions)||l.validationMode!==\"aggregate\"&&l.validationMode!==\"fail-fast\")throw Error(\"Invalid serialized diagram evaluation context.\");let u=Q(l.recordTypes,\"recordTypes\"),c=Q(l.functions,\"functions\"),m=new j(u,c,l.dimensionRegistry);m.validationMode=l.validationMode;for(let[d,f]of Object.entries(l.values))if(m.set(d,f),l.immutableValues.includes(d))m.markImmutable(f);for(let[d,f]of Q(l.enumDeclarations,\"enumDeclarations\"))m.enumDeclarations.set(d,f);for(let[d,f]of Q(l.enumValues,\"enumValues\"))m.enumValues.set(d,f);for(let[d,f]of Q(l.bindingTypes,\"bindingTypes\"))m.bindingTypes.set(d,f);for(let d of l.declarationRegistries.records){let f=u.get(d.name);if(!f||!Array.isArray(d.fields))throw Error(\"Invalid serialized record declaration registry.\");if(d.declaration)z(f,d.declaration);let p=f.declaredFields??f.fields;if(p.length!==d.fields.length)throw Error(\"Serialized record field registry does not match its declaration.\");d.fields.forEach((g,h)=>{if(g)z(p[h],g)})}for(let d of l.declarationRegistries.functions){let f=c.get(d.name);if(!f)throw Error(\"Invalid serialized function declaration registry.\");if(d.declaration)z(f,d.declaration)}return ke.set(a,m),Ie.set(a,s),a}function v(e,n=new Map){if(!e||typeof e!==\"object\")return e;let t=n.get(e);if(t)return t;if(Array.isArray(e)){let i=[];n.set(e,i);for(let o of e)i.push(v(o,n));return i}if(e instanceof Map){let i=new Map;n.set(e,i);for(let[o,a]of e)i.set(v(o,n),v(a,n));return i}if(e instanceof Set){let i=new Set;n.set(e,i);for(let o of e)i.add(v(o,n));return i}let r={};n.set(e,r);for(let[i,o]of Object.entries(e))r[i]=v(o,n);return r}function ue(e,n=new Set){if(!e||typeof e!==\"object\"||n.has(e))return e;if(n.add(e),Array.isArray(e))e.forEach((t)=>ue(t,n));else if(!(e instanceof Map)&&!(e instanceof Set))Object.values(e).forEach((t)=>ue(t,n));return Object.freeze(e)}function rn(e){let n=v(e.recordTypes),t=v(e.functions),r=e.dimensionRegistry?v(e.dimensionRegistry):void 0,i=new j(n,t,r);i.validationMode=e.validationMode;for(let[o,a]of e.recordTypes){let s=n.get(o),l=L(a,e.dimensionRegistry);if(l)z(s,v(l));let u=a.declaredFields??a.fields,c=s.declaredFields??s.fields;for(let m=0;m<u.length;m++){let d=L(u[m],e.dimensionRegistry);if(d&&c[m])z(c[m],v(d))}}for(let[o,a]of e.functions){let s=L(a,e.dimensionRegistry);if(s)z(t.get(o),v(s))}for(let[o,a]of e.enumDeclarations)i.enumDeclarations.set(o,v(a));for(let[o,a]of e.enumValues)i.enumValues.set(o,v(a));for(let[o,a]of e.bindingTypes)i.bindingTypes.set(o,v(a));for(let[o,a]of Object.entries(e.toObject())){let s=v(a);if(i.set(o,s),e.isImmutable(a))i.markImmutable(s)}return i}var on=64;function an(e){if(nn(e))throw Error(\"Control-bearing diagram models are missing their expanded per-instance bindings.\");return Object.freeze(e.map((n,t)=>{if(n.type!==\"diagramElement\")throw Error(\"Unexpected diagram control in static content.\");return Object.freeze({identity:t,element:n,bindings:Object.freeze([])})}))}function Gn(e,n,t){let r=[],i=[],o=0,a=(s,l)=>{for(let u of s){if(u.type===\"diagramElement\"){if(l){if(o>=on)w(\"AMXD6004\",\"Number of elements in this diagram exceed the maximum (64)\",u.source??u.nameSource,t);o++}r.push(Object.freeze({identity:r.length,element:u,bindings:Object.freeze(i.map((m)=>Object.freeze({name:m.name,value:v(m.value)})))}));continue}if(u.type===\"diagramForBlock\"){let m=ce(u.iterable,n,t);K(u.variable,m,n,()=>{i.push({name:u.variable,value:n.get(u.variable)});try{a(u.content,!0)}finally{i.pop()}});continue}let c=R(y(u.test,n,t))?u.consequent:u.alternate;if(c)a(c,!0)}};return a(e,!1),Object.freeze(r)}function sn(e,n,t,r=0){if(r>=e.length)return t();let i,o=e[r];return K(o.name,[o.value],n,()=>{i=sn(e,n,t,r+1)}),i}function U(e,n){let t=e.properties.find((r)=>r.name===n);if(!t)throw Error(`Type checker accepted missing diagram property '${n}'`);return t}function Yn(e,n,t,r,i,o){let a=U(e,n),s=y(a.expression,t,r);if(typeof s!==\"number\"||!Number.isFinite(s)){if(s===1/0&&o===i.to)w(\"AMXD010\",\"Infinity value calculated for time upper bound\",a.valueSource??a.source,r);if(s===1/0&&o>i.from&&o<i.to)w(\"AMXD011\",\"Expression produces an infinite result\",a.valueSource??a.source,r);w(\"AMXD008\",\"Invalid primitive geometry\",a.valueSource??a.source,r)}return s}function cn(e,n,t,r,i,o){if(typeof t!==\"number\"||!Number.isFinite(t)||t<n.from||t>n.to)w(\"AMXD004\",\"Invalid time bounds\",e.times[0]?.source??e.source,o);let a=rn(i);a.set(n.variable,t);let s=(u)=>{let c=(f)=>Yn(u,f,a,o,n,t),m=(f)=>{let p=U(u,f).expression;if(p.type!==\"stringLiteral\")throw Error(\"Type checker accepted a non-literal diagram style\");return p.value},d=()=>{let f=U(u,\"lineWidth\").expression;if(f.type!==\"numberLiteral\")throw Error(\"Type checker accepted a non-literal line width\");return f.value};try{switch(u.primitive){case\"line\":{let f=u.properties.find((g)=>g.name===\"arrow\")?.expression,p=f?.type===\"stringLiteral\"?f.value:\"none\";return Object.freeze({primitive:\"line\",name:u.name,source:u.source,x1:c(\"x1\"),y1:c(\"y1\"),x2:c(\"x2\"),y2:c(\"y2\"),stroke:m(\"stroke\"),lineWidth:d(),arrow:p})}case\"rectangle\":{let f=c(\"width\"),p=c(\"height\");if(f<=0)w(\"AMXD008\",\"Invalid primitive geometry\",U(u,\"width\").valueSource,o);if(p<=0)w(\"AMXD008\",\"Invalid primitive geometry\",U(u,\"height\").valueSource,o);let g=u.properties.some((h)=>h.name===\"fill\")?m(\"fill\"):void 0;return Object.freeze({primitive:\"rectangle\",name:u.name,source:u.source,x:c(\"x\"),y:c(\"y\"),width:f,height:p,stroke:m(\"stroke\"),...g===void 0?{}:{fill:g},lineWidth:d()})}case\"circle\":{let f=c(\"r\");if(f<=0)w(\"AMXD008\",\"Invalid primitive geometry\",U(u,\"r\").valueSource,o);let p=u.properties.some((g)=>g.name===\"fill\")?m(\"fill\"):void 0;return Object.freeze({primitive:\"circle\",name:u.name,source:u.source,cx:c(\"cx\"),cy:c(\"cy\"),r:f,stroke:m(\"stroke\"),...p===void 0?{}:{fill:p},lineWidth:d()})}case\"text\":{let f=U(u,\"value\"),p=y(f.expression,a,o);if(typeof p!==\"string\")w(\"AMX3002\",\"Expected String, got non-String value\",f.valueSource,o);return Object.freeze({primitive:\"text\",name:u.name,source:u.source,x:c(\"x\"),y:c(\"y\"),value:p,fill:m(\"fill\")})}default:throw Error(`Type checker accepted unsupported diagram primitive '${u.primitive}'`)}}catch(f){if(f instanceof M&&t!==n.from&&f.code!==\"AMXD008\"&&f.code!==\"AMXD010\"&&f.code!==\"AMXD011\")throw new M({code:\"AMXD009\",message:`Frame evaluation leads to invalid results. The underlying error is: ${f.message}`,file:f.file??o,line:f.line??u.source?.line,column:f.column??u.source?.column});throw f}},l=r.map((u)=>sn(u.bindings,a,()=>s(u.element)));return Object.freeze({time:t,elements:Object.freeze(l)})}function ee(e,n,t,r,i,o){let a=y(e,n,t);if(typeof a!==\"number\"||!Number.isFinite(a)||(r===\"AMXD003\"||r===\"AMXD014\"||r===\"AMXD005\")&&a<=0)w(r,i,o,t);return a}function en(e,n,t,r,i){let o=ue(v(e)),a=rn(n),s=(Le)=>{let $e=o.properties.find((dn)=>dn.name===Le);if(!$e)throw Error(`Type checker accepted missing diagram property '${Le}'`);return $e},l=s(\"width\"),u=s(\"height\"),c=ee(l.expression,a,t,\"AMXD003\",\"Canvas width is invalid\",l.valueSource),m=ee(u.expression,a,t,\"AMXD014\",\"Canvas height is invalid\",u.valueSource),d=s(\"title\").expression,f=s(\"description\").expression;if(d.type!==\"stringLiteral\"||f.type!==\"stringLiteral\")throw Error(\"Type checker accepted a non-literal diagram title or description\");let p=o.times[0],g=ee(p.from,a,t,\"AMXD004\",\"Invalid time bounds\",p.fromSource??p.source),h=ee(p.to,a,t,\"AMXD004\",\"Invalid time bounds\",p.toSource??p.source);if(g>=h)w(\"AMXD004\",\"Invalid time bounds\",p.source??o.source,t);let A=ee(p.duration,a,t,\"AMXD005\",\"Invalid playback duration value\",p.durationSource??p.source),F=Object.freeze({variable:p.name,from:g,to:h,duration:A}),Y=Gn(o.content,a,t),mn=cn(o,F,g,Y,a,t),me=Object.freeze({name:o.name,title:d.value,description:f.value,canvas:Object.freeze({width:c,height:m,coordinates:\"bottom-left-y-up\"}),timeline:F,declaration:o,initialFrame:mn,source:o.source,file:t,documentNodeIndex:r,statementIndex:i});return ke.set(me,a),Ie.set(me,Y),me}function un(e,n,t=e.file){let r=ke.get(e);if(!r)throw Error(\"Diagram model has no captured AMX evaluation context\");let i=Ie.get(e)??an(e.declaration.content);return cn(e.declaration,e.timeline,n,i,r,t)}var Zn=\"http://www.w3.org/2000/svg\",Te=new Set;function X(e,n={}){let t=document.createElementNS(Zn,e);for(let[r,i]of Object.entries(n))t.setAttribute(r,String(i));return t}function Jn(e,n,t){e.setAttribute(\"x\",String(n)),e.setAttribute(\"y\",String(t)),e.setAttribute(\"transform\",`translate(0 ${2*t}) scale(1 -1)`)}function Kn(e,n){let{model:t,canvas:r}=e,i=X(\"defs\"),o=X(\"marker\",{id:`${r.dataset.diagramId}-arrowhead`,markerWidth:6,markerHeight:6,refX:10,refY:5,orient:\"auto-start-reverse\",markerUnits:\"strokeWidth\",viewBox:\"0 0 10 10\"});o.append(X(\"path\",{d:\"M 0 0 L 10 5 L 0 10 z\",fill:\"context-stroke\"})),i.append(o);let a=X(\"g\",{transform:`translate(0 ${t.canvas.height}) scale(1 -1)`});for(let s of n.elements)if(s.primitive===\"line\"){let l=X(\"line\",{x1:s.x1,y1:s.y1,x2:s.x2,y2:s.y2,stroke:s.stroke,\"stroke-width\":s.lineWidth,\"stroke-linecap\":\"round\"});if(l.setAttribute(\"data-diagram-element\",s.name),s.arrow===\"start\"||s.arrow===\"both\")l.setAttribute(\"marker-start\",`url(#${r.dataset.diagramId}-arrowhead)`);if(s.arrow===\"end\"||s.arrow===\"both\")l.setAttribute(\"marker-end\",`url(#${r.dataset.diagramId}-arrowhead)`);a.append(l)}else if(s.primitive===\"rectangle\"){let l=X(\"rect\",{x:s.x,y:s.y,width:s.width,height:s.height,stroke:s.stroke,fill:s.fill??\"none\",\"stroke-width\":s.lineWidth});l.setAttribute(\"data-diagram-element\",s.name),a.append(l)}else if(s.primitive===\"circle\"){let l=X(\"circle\",{cx:s.cx,cy:s.cy,r:s.r,stroke:s.stroke,fill:s.fill??\"none\",\"stroke-width\":s.lineWidth});l.setAttribute(\"data-diagram-element\",s.name),a.append(l)}else{let l=X(\"text\",{fill:s.fill,\"font-family\":\"sans-serif\",\"font-size\":12});Jn(l,s.x,s.y),l.setAttribute(\"data-diagram-element\",s.name),l.textContent=s.value,a.append(l)}r.replaceChildren(i,a),r.removeAttribute(\"aria-hidden\")}function Re(e){window.dispatchEvent(new CustomEvent(\"openamx-diagram-frame\",{detail:e}))}async function Qn(e){if(e.dataset.encoding!==\"gzip-base64\")throw Error(\"Unsupported diagram data encoding.\");let n=atob(e.textContent??\"\"),t=new Uint8Array(n.length);for(let i=0;i<n.length;i++)t[i]=n.charCodeAt(i);let r=new Blob([t]).stream().pipeThrough(new DecompressionStream(\"gzip\"));return tn(await new Response(r).text())}function le(e){let n=e.model.title,t=e.time.toFixed(3).toString();e.playButton.textContent=e.running?\"Pause\":\"Play\",e.playButton.setAttribute(\"aria-label\",`${e.running?\"Pause\":\"Play\"} ${n}`),e.scrubber.value=String(e.time),e.scrubber.setAttribute(\"aria-valuetext\",t),e.timeOutput.value=t,e.timeOutput.textContent=t}function q(e){if(e.running=!1,e.animationFrame!==void 0)cancelAnimationFrame(e.animationFrame);e.animationFrame=void 0,le(e)}function B(e,n){e.time=n,le(e);try{let t=un(e.model,n);if(Kn(e,t),e.alert.hidden=!0,e.alert.textContent=\"\",e.failed)e.failed=!1,Re({version:1,type:\"diagram-recovered\",diagramId:e.canvas.dataset.diagramId});return!0}catch(t){q(e),e.canvas.replaceChildren(),e.canvas.setAttribute(\"aria-hidden\",\"true\"),e.failed=!0;let r=t instanceof M?{code:t.code,message:t.message,file:t.file??e.model.file,line:t.line??e.model.source?.line,column:t.column??e.model.source?.column}:{code:\"DIAGRAM_RUNTIME\",message:\"The diagram frame could not be evaluated.\",file:e.model.file,line:e.model.source?.line,column:e.model.source?.column},i=r.file?`${r.file}${r.line?`:${r.line}${r.column?`:${r.column}`:\"\"}`:\"\"}`:r.line?`${r.line}${r.column?`:${r.column}`:\"\"}`:\"\";return e.alert.textContent=`${r.code}: ${r.message}${i?` (${i})`:\"\"}`,e.alert.hidden=!1,Re({version:1,type:\"diagram-error\",diagramId:e.canvas.dataset.diagramId,...r}),!1}}function et(e){if(e.running||e.failed)return;if(e.time>=e.model.timeline.to){if(!e.canvas.closest(\"[data-openamx-diagram]\")?.querySelector(\"[data-diagram-loop]\")?.checked)return;B(e,e.model.timeline.from)}e.running=!0,e.startedAt=performance.now()-(e.time-e.model.timeline.from)/(e.model.timeline.to-e.model.timeline.from)*e.model.timeline.duration*1000,le(e),e.animationFrame=requestAnimationFrame((n)=>ln(e,n))}function ln(e,n){if(!e.running||!document.contains(e.canvas)){q(e);return}let t=e.model.timeline.duration,r=(n-e.startedAt)/1000/t;if(r>=1){if(!(e.canvas.closest(\"[data-openamx-diagram]\")?.querySelector(\"[data-diagram-loop]\")?.checked??!1)){B(e,e.model.timeline.to),q(e);return}if(!B(e,e.model.timeline.from))return;e.startedAt=n}else{let i=e.model.timeline.from,o=e.model.timeline.to,a=r<=0?i:i*(1-r)+o*r;if(!B(e,a))return}e.animationFrame=requestAnimationFrame((i)=>ln(e,i))}async function nt(e){let n=e.querySelector(\"[data-diagram-model]\"),t=e.querySelector(\"[data-diagram-canvas]\"),r=e.querySelector(\"[data-diagram-play]\"),i=e.querySelector(\"[data-diagram-reset]\"),o=e.querySelector(\"[data-diagram-scrubber]\"),a=e.querySelector(\"[data-diagram-loop]\"),s=e.querySelector(\"[data-diagram-time]\"),l=e.querySelector(\"[data-diagram-error]\");if(!n||!t||!r||!i||!o||!a||!s||!l)throw Error(\"Diagram HTML is missing required runtime elements.\");let u=await Qn(n);t.dataset.diagramId=e.dataset.diagramId;let c={model:u,canvas:t,playButton:r,scrubber:o,timeOutput:s,alert:l,running:!1,failed:!1,time:u.timeline.from,startedAt:0};Te.add(c),le(c),r.addEventListener(\"click\",()=>{if(c.running)q(c);else et(c)}),i.addEventListener(\"click\",()=>{q(c),B(c,u.timeline.from)}),o.addEventListener(\"input\",()=>{let m=Number(o.value);q(c),B(c,m)}),B(c,u.timeline.from)}async function tt(){for(let e of Array.from(document.querySelectorAll(\"[data-openamx-diagram]\")))try{await nt(e)}catch(n){let t=e.querySelector(\"[data-diagram-error]\");if(!t)throw n;t.textContent=`DIAGRAM_RUNTIME: ${n instanceof Error?n.message:\"The diagram could not be initialized.\"}`,t.hidden=!1,Re({version:1,type:\"diagram-error\",diagramId:e.dataset.diagramId??\"\",code:\"DIAGRAM_RUNTIME\",message:t.textContent})}}document.addEventListener(\"DOMContentLoaded\",()=>{tt()},{once:!0});window.addEventListener(\"pagehide\",()=>{for(let e of Te)q(e);Te.clear()},{once:!0});})();\n";
1
+ const diagramBrowserRuntime = "(()=>{class M extends Error{code;file;line;column;declarationSource;fieldSource;diagnostics;constructor(e,n){super(e.message);this.name=\"AmxError\",this.code=e.code,this.file=e.file,this.line=e.line,this.column=e.column,this.declarationSource=e.declarationSource,this.fieldSource=e.fieldSource,this.diagnostics=n}}function J(e,n,t={}){return{code:e,message:n,...t}}function Q(e){let n=e[0]??J(\"AMX4001\",\"Input validation failed\");throw new M(n,e)}function w(e,n,t,r,i){throw new M({code:e,message:n,file:r,line:t?.line,column:t?.column,declarationSource:i})}function N(e,n,t){throw new M({code:\"AMX1009\",message:e,file:t,line:n?.line,column:n?.column})}function fn(e,n,t){return{code:\"AMX1004\",message:`Undefined identifier '${e}'`,file:t,line:n?.line,column:n?.column}}function be(e,n,t){let r=fn(e,n,t);throw new M(r)}function he(e,n){throw new M({code:\"AMX1005\",message:\"Range bounds must be finite integers\",file:n,line:e?.line,column:e?.column})}function Xe(e,n){throw new M({code:\"AMX1006\",message:\"For loops require a list or range value\",file:n,line:e?.line,column:e?.column})}function ze(e,n){throw new M({code:\"AMX1007\",message:\"Return is only valid inside an expression-form for loop\",file:n,line:e?.line,column:e?.column})}function Oe(e,n){throw new M({code:\"AMXF4002\",message:\"Function finished without returning a valid expression\",file:n,line:e?.line,column:e?.column})}function V(e,n,t){throw new M({code:\"AMX1008\",message:e,file:t,line:n?.line,column:n?.column})}var Ce=new WeakMap;function P(e,n){Ce.set(e,n)}function C(e,n){return Ce.get(e)??n}class W{store=new Map;recordTypes;enumDeclarations=new Map;enumValues=new Map;functions;bindingTypes=new Map;dimensionRegistry;viewDefinitions=new Map;viewEmissions=[];diagramEmissions=[];immutableValues=new WeakSet;currentDocumentNodeIndex=-1;currentStatementIndex=-1;validationMode=\"aggregate\";constructor(e=new Map,n=new Map,t){this.recordTypes=e,this.functions=n,this.dimensionRegistry=t}createCallFrame(e){let n=new W(this.recordTypes,this.functions,this.dimensionRegistry);n.validationMode=this.validationMode;for(let[t,r]of this.bindingTypes)n.bindingTypes.set(t,r);for(let[t,r]of this.enumDeclarations)n.enumDeclarations.set(t,r);for(let[t,r]of this.enumValues)n.enumValues.set(t,r);for(let[t,r]of Object.entries(e))if(n.set(t,r),this.isImmutable(r))n.markImmutable(r);return n}set(e,n){this.store.set(e,n)}markImmutable(e){let n=(t)=>{if(!t||typeof t!==\"object\"||this.immutableValues.has(t))return;if(this.immutableValues.add(t),Array.isArray(t))t.forEach(n);else Object.values(t).forEach(n)};n(e)}isImmutable(e){return!!e&&typeof e===\"object\"&&this.immutableValues.has(e)}update(e,n,t,r){if(!this.store.has(e))be(e,t,r);this.store.set(e,n)}delete(e){this.store.delete(e)}get(e,n,t){if(!this.store.has(e))be(e,n,t);return this.store.get(e)}has(e){return this.store.has(e)}toObject(){let e={};for(let[n,t]of this.store.entries())e[n]=t;return e}clear(){this.store.clear(),this.immutableValues=new WeakSet,this.viewDefinitions.clear(),this.viewEmissions.length=0,this.diagramEmissions.length=0}}function b(e){return!!e&&typeof e===\"object\"&&e.__amxMeasurement===!0&&typeof e.value===\"number\"&&!!e.unit}function Ue(e){return Object.freeze(Object.fromEntries(e))}function we(e){let n=[...e].filter((i)=>i.exponent!==0).sort((i,o)=>i.identity<o.identity?-1:i.identity>o.identity?1:0),t=n.filter((i)=>i.exponent>0).map((i)=>`${i.name}${i.exponent===1?\"\":` ^ ${i.exponent}`}`),r=n.filter((i)=>i.exponent<0).map((i)=>`${i.name}${i.exponent===-1?\"\":` ^ ${-i.exponent}`}`);return`${t.length?t.join(\" * \"):\"1\"}${r.length?` / ${r.join(\" * \")}`:\"\"}`}function ce(e){let n=[{identity:e.identity,name:e.name,exponent:1}];return Object.freeze({scale:e.scale,offset:e.offset,vector:Ue(e.vector),factors:Object.freeze(n),text:e.name})}function gn(e,n){return e*n.scale+n.offset}function yn(e,n){return(e-n.offset)/n.scale}function x(e){return gn(e.value,e.unit)}function te(e,n){return yn(e,n)}function T(e){return e.offset!==0}function bn(e,n,t){let r=new Map;for(let i of e.factors)r.set(i.identity,{...i});for(let i of n.factors){let o=r.get(i.identity);r.set(i.identity,{identity:i.identity,name:i.name,exponent:(o?.exponent??0)+i.exponent*t})}return[...r.values()].filter((i)=>i.exponent!==0)}function hn(e,n,t){let r={...e.vector};for(let[i,o]of Object.entries(n.vector)){let a=(r[i]??0)+o*t;if(a)r[i]=a;else delete r[i]}return r}function qe(e,n,t=!1){if(T(e)||T(n))throw Error(\"Affine measurement units cannot be composed\");let r=t?-1:1,i=bn(e,n,r);return Object.freeze({scale:t?e.scale/n.scale:e.scale*n.scale,offset:0,vector:Object.freeze(hn(e,n,r)),factors:Object.freeze(i),text:we(i)})}function xe(e,n){if(T(e))throw Error(\"Affine measurement units may not be powered\");let t=e.factors.map((r)=>({...r,exponent:r.exponent*n})).filter((r)=>r.exponent!==0);return Object.freeze({scale:Math.pow(e.scale,n),offset:e.offset,vector:Object.freeze(Object.fromEntries(Object.entries(e.vector).map(([r,i])=>[r,i*n]).filter(([,r])=>r!==0))),factors:Object.freeze(t),text:we(t)})}function k(e,n){return Object.freeze({__amxMeasurement:!0,value:e,unit:n})}function se(e,n){let t=[];for(let[r,i]of[...e].sort(([o],[a])=>o<a?-1:o>a?1:0)){let o=n.baseUnits.get(r);if(!o)throw Error(`No visible canonical base unit for dimension identity ${r}`);t.push({identity:o.identity,name:o.name,exponent:i})}return Object.freeze({scale:1,offset:0,vector:Ue(e),factors:Object.freeze(t),text:we(t)})}function Be(e,n){if(T(e.unit))throw Error(\"Affine measurement sqrt is not supported\");let t=new Map;for(let[s,l]of Object.entries(e.unit.vector)){if(l%2!==0)throw Error(\"sqrt requires integral measurement dimension exponents\");t.set(s,l/2)}let r=x(e),i=Math.sqrt(r);if(!Number.isFinite(i))return k(i,se(t,n));let o=Math.sqrt(e.unit.scale),a=[...n.units.values()].find((s)=>s.scale===o&&s.vector.size===t.size&&[...t].every(([l,c])=>s.vector.get(l)===c));if(a)return k(i/a.scale,ce(a));let u=se(t,n);return k(i,u)}function ue(e,n,t,r){if(!Array.isArray(e)){let i=t?` at line ${t.line}`:\"\";throw new M({code:\"AMX2001\",message:`${n} expects a list${i}`,file:r,line:t?.line,column:t?.column})}return e}function X(e,n,t,r){if(typeof e===\"number\")return e;if(typeof e===\"boolean\")return e?1:0;if(typeof e===\"string\"){let o=Number(e);if(!Number.isNaN(o))return o}let i=t?` at line ${t.line}`:\"\";throw new M({code:\"AMX2002\",message:`${n} requires a numeric value${i}`,file:r,line:t?.line,column:t?.column})}function H(e,n,t,r,i){if(e.length!==n){let o=r?` at line ${r.line}`:\"\";throw new M({code:\"AMX2003\",message:`${t} expects ${n} argument(s), got ${e.length}${o}`,file:i,line:r?.line,column:r?.column})}}function wn(e,n,t,r,i){if(e.length<n){let o=r?` at line ${r.line}`:\"\";throw new M({code:\"AMX2003\",message:`${t} expects at least ${n} argument(s), got ${e.length}${o}`,file:i,line:r?.line,column:r?.column})}}var He={sin:{evaluate:Math.sin,accepts:Number.isFinite},cos:{evaluate:Math.cos,accepts:Number.isFinite},tan:{evaluate:Math.tan,accepts:Number.isFinite},asin:{evaluate:Math.asin,accepts:(e)=>Number.isFinite(e)&&e>=-1&&e<=1},acos:{evaluate:Math.acos,accepts:(e)=>Number.isFinite(e)&&e>=-1&&e<=1},atan:{evaluate:Math.atan,accepts:Number.isFinite},sinh:{evaluate:Math.sinh,accepts:Number.isFinite},cosh:{evaluate:Math.cosh,accepts:Number.isFinite},tanh:{evaluate:Math.tanh,accepts:Number.isFinite},asinh:{evaluate:Math.asinh,accepts:Number.isFinite},acosh:{evaluate:Math.acosh,accepts:(e)=>Number.isFinite(e)&&e>=1},atanh:{evaluate:Math.atanh,accepts:(e)=>Number.isFinite(e)&&e>-1&&e<1},ln:{evaluate:Math.log,accepts:(e)=>Number.isFinite(e)&&e>0},log:{evaluate:Math.log10,accepts:(e)=>Number.isFinite(e)&&e>0},exp:{evaluate:Math.exp,accepts:Number.isFinite}};function Ge(e){return Object.hasOwn(He,e)}function _e(e,n,t,r){return new M({code:e,message:n,file:r,line:t?.line,column:t?.column})}function z(e,n,t,r){return new M({code:e,message:n,file:r,line:t?.line,column:t?.column})}function Me(e){if(e===null)return\"null\";if(b(e))return\"Measurement\";if(Array.isArray(e))return\"list\";if(typeof e===\"number\")return\"Number\";if(typeof e===\"string\")return\"String\";if(typeof e===\"boolean\")return\"Boolean\";return typeof e}function le(e,n,t,r,i,o){if(n.length<t||n.length>r)throw z(\"AMX3004\",`Invalid arity for '${e}'`,i,o)}function Pe(e,n,t,r){if(typeof n!==\"string\")throw z(\"AMX3002\",`${e} requires a String, got ${Me(n)}`,t,r);return n}function We(e){return e>=9&&e<=13||e===32||e===133||e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288}function xn(e){let n=Array.from(e),t=0,r=n.length;while(t<r&&We(n[t].codePointAt(0)))t++;while(r>t&&We(n[r-1].codePointAt(0)))r--;return n.slice(t,r).join(\"\")}function Mn(e,n,t){if(typeof e!==\"string\")throw z(\"AMXSL004\",\"Incorrect formatting pattern\",n,t);let r=/^([$€£])?(#,##0|0)(?:\\.(0{1,6}))?(%)?$/.exec(e);if(!r)throw z(\"AMXSL004\",\"Incorrect formatting pattern\",n,t);return{currency:r[1]??\"\",grouped:r[2]===\"#,##0\",precision:r[3]?.length??0,percent:r[4]===\"%\"}}function En(e,n,t){switch(e){case\"en-US\":return{decimal:\".\",group:\",\"};case\"de-DE\":return{decimal:\",\",group:\".\"};case\"fr-FR\":return{decimal:\",\",group:\" \"};default:throw z(\"AMXSL005\",\"Formatting locale is malformed or unsupported\",n,t)}}function vn(e,n){let[t,r]=Math.abs(e).toString().toLowerCase().split(\"e\"),i=r===void 0?0:Number(r),[o,a=\"\"]=t.split(\".\"),u=`${o}${a}`.replace(/^0+(?=\\d)/,\"\"),s=BigInt(u||\"0\"),l=n+i-a.length;if(l>=0)return s*10n**BigInt(l);let c=10n**BigInt(-l),m=s/c,d=s%c;return m+(d*2n>=c?1n:0n)}function An(e,n){return e.replace(/\\B(?=(\\d{3})+(?!\\d))/g,n)}function Dn(e,n,t){let r=n.percent?e*100:e,i=r<0,o=10n**BigInt(n.precision),a=vn(r,n.precision),u=(a/o).toString(),s=n.precision?`${t.decimal}${(a%o).toString().padStart(n.precision,\"0\")}`:\"\",l=n.grouped?An(u,t.group):u;return`${i?\"-\":\"\"}${n.currency}${l}${s}${n.percent?\"%\":\"\"}`}function re(e,n,t,r,i=[]){let o=(u)=>i[u]??t;if(e===\"len\"){le(e,n,1,1,t,r);let u=n[0];if(typeof u===\"string\")return Array.from(u).length;if(Array.isArray(u))return u.length;throw z(\"AMX3002\",`len requires a String or list, got ${Me(u)}`,o(0),r)}if(e===\"trim\")return le(e,n,1,1,t,r),xn(Pe(e,n[0],o(0),r));if(e===\"left\"||e===\"right\"){le(e,n,1,2,t,r);let u=Array.from(Pe(e,n[0],o(0),r)),s=n.length===1?1:n[1];if(typeof s!==\"number\"||!Number.isFinite(s)||!Number.isInteger(s)||s<0)throw z(\"AMXSL003\",\"Invalid text slice count\",o(1),r);let l=Math.min(s,u.length);return e===\"left\"?u.slice(0,l).join(\"\"):u.slice(u.length-l).join(\"\")}if(e===\"format\"){le(e,n,2,3,t,r);let u=n[0],s=o(0);if(typeof u!==\"number\"&&!b(u))throw z(\"AMX3002\",`format expects a Number or Measurement, got ${Me(u)}`,s,r);let l=b(u)?u.value:u;if(!Number.isFinite(l))throw z(\"AMXSL006\",\"Input is non-finite\",s,r);let c=Mn(n[1],o(1),r),m=En(n.length===3?n[2]:\"en-US\",o(2),r);if(c.percent&&!Number.isFinite(l*100))throw z(\"AMXSL006\",\"Input is non-finite\",s,r);let d=Dn(l,c,m);return b(u)?`${d} ${u.unit.text}`:d}let a=He[e];if(a){if(n.length!==1)throw new M({code:\"AMX3004\",message:`Invalid arity for '${e}'`,file:r,line:t?.line,column:t?.column});let u=n[0];if(typeof u!==\"number\"){let l=u===null?\"null\":Array.isArray(u)?\"list\":typeof u===\"object\"?\"Measurement\":typeof u===\"string\"?\"String\":typeof u===\"boolean\"?\"Boolean\":typeof u;throw new M({code:\"AMX3002\",message:`Expected Number or dimensionless Measurement, got ${l}`,file:r,line:t?.line,column:t?.column})}if(!a.accepts(u))throw _e(\"AMXSL001\",\"Invalid input for mathematical function\",t,r);let s=a.evaluate(u);if(!Number.isFinite(s))throw _e(\"AMXSL002\",\"Function evaluation results in infinite result\",t,r);return s}switch(e){case\"sum\":return H(n,1,\"sum\",t,r),ue(n[0],\"sum\",t,r).reduce((l,c)=>l+X(c,\"sum element\",t,r),0);case\"min\":{H(n,1,\"min\",t,r);let s=ue(n[0],\"min\",t,r);if(s.length===0){let l=t?` at line ${t.line}`:\"\";throw new M({code:\"AMX2004\",message:`min of empty list${l}`,file:r,line:t?.line,column:t?.column})}return s.reduce((l,c)=>Math.min(l,X(c,\"min element\",t,r)),Number.POSITIVE_INFINITY)}case\"max\":{H(n,1,\"max\",t,r);let s=ue(n[0],\"max\",t,r);if(s.length===0){let l=t?` at line ${t.line}`:\"\";throw new M({code:\"AMX2004\",message:`max of empty list${l}`,file:r,line:t?.line,column:t?.column})}return s.reduce((l,c)=>Math.max(l,X(c,\"max element\",t,r)),Number.NEGATIVE_INFINITY)}case\"mean\":{H(n,1,\"mean\",t,r);let s=ue(n[0],\"mean\",t,r);if(s.length===0){let c=t?` at line ${t.line}`:\"\";throw new M({code:\"AMX2004\",message:`mean of empty list${c}`,file:r,line:t?.line,column:t?.column})}return s.reduce((c,m)=>c+X(m,\"mean element\",t,r),0)/s.length}case\"round\":{wn(n,1,\"round\",t,r);let s=X(n[0],\"round value\",t,r),l=n.length>1?X(n[1],\"round digits\",t,r):0,c=Math.pow(10,Math.trunc(l));return Math.round(s*c)/c}case\"abs\":{H(n,1,\"abs\",t,r);let s=X(n[0],\"abs value\",t,r);return Math.abs(s)}case\"sqrt\":{H(n,1,\"sqrt\",t,r);let s=X(n[0],\"sqrt value\",t,r);if(s<0){let l=t?` at line ${t.line}`:\"\";throw new M({code:\"AMX2005\",message:`sqrt of negative value${l}`,file:r,line:t?.line,column:t?.column})}return Math.sqrt(s)}case\"pow\":{H(n,2,\"pow\",t,r);let s=X(n[0],\"pow base\",t,r),l=X(n[1],\"pow exponent\",t,r);return Math.pow(s,l)}default:let u=t?` at line ${t.line}`:\"\";throw new M({code:\"AMX2000\",message:`Unknown function '${e}'${u}`,file:r,line:t?.line,column:t?.column})}}function G(e,n,t,r,i,o){let a=[],u=new WeakSet,s=(c,m,d,p,g)=>{let f=J(\"AMX4003\",c,{file:i,line:r?.line,column:r?.column,dataPath:p,expected:Ee(m),actual:Ae(d),fieldSource:g});if(a.push(f),t.validationMode===\"fail-fast\")Q([f])},l=(c,m,d,p)=>{if(m.kind===\"null\"){if(c!==null)s(\"Expected null\",m,c,d,p);return}if(m.kind===\"nullable\"){if(c!==null)l(c,m.element,d,p);return}if(m.kind===\"list\"){let I;try{I=Array.isArray(c)}catch{s(\"Expected a list value\",m,c,d,p);return}if(!I){s(\"Expected a list value\",m,c,d,p);return}let h=c,D;try{D=Object.getPrototypeOf(h)}catch{s(\"Expected a plain list value\",m,c,d,p);return}if(D!==Array.prototype){s(\"Expected a plain list value\",m,c,d,p);return}if(u.has(h)){s(\"Cyclic values are not supported\",m,c,d,p);return}u.add(h);try{for(let R=0;R<h.length;R++){let F;try{F=Object.getOwnPropertyDescriptor(h,String(R))}catch{s(\"Expected a plain list value\",m,c,`${d}[${R}]`,p);continue}if(!F||!(\"value\"in F)||F.enumerable!==!0){s(\"Expected a dense data list\",m.element,F?\"accessor\":\"missing\",`${d}[${R}]`,p);continue}l(F.value,m.element,`${d}[${R}]`,p)}let S;try{S=Reflect.ownKeys(h)}catch{s(\"Expected a plain list value\",m,c,d,p);return}for(let R of S){if(R===\"length\")continue;let F=typeof R===\"string\"?Number(R):Number.NaN;if(!Number.isSafeInteger(F)||F<0||F>=h.length||String(F)!==R)s(\"Unsupported list property\",m,c,`${d}.${String(R)}`,p)}}finally{u.delete(h)}return}if(m.kind===\"measurement\"){if(!b(c)){s(\"Expected a measurement value\",m,c,d,p);return}let I=c.unit.vector;if(Object.keys(I).length!==m.vector.size||[...m.vector].some(([h,D])=>I[h]!==D))s(\"Measurement dimension does not match the declared dimension\",m,c,d,p);if(!Number.isFinite(c.value)||!Number.isFinite(x(c)))s(\"Measurement value must be finite\",m,c,d,p);return}if(m.kind!==\"named\")return;if(m.name===\"Number\"){if(typeof c!==\"number\"||!Number.isFinite(c))s(\"Expected a finite Number value\",m,c,d,p);return}if(m.name===\"String\"||m.name===\"DateTime\"){if(typeof c!==\"string\")s(`Expected a ${m.name} value`,m,c,d,p);else if(m.name===\"DateTime\"&&!Ye(c))s(\"Invalid RFC 3339 DateTime value\",m,c,d,p);return}if(m.name===\"Boolean\"){if(typeof c!==\"boolean\")s(\"Expected a Boolean value\",m,c,d,p);return}let g=t.enumDeclarations.get(m.name);if(g){let I=g.resolvedValues??[];if(typeof c!==\"number\"&&typeof c!==\"string\"||!I.includes(c))s(`Expected a member value of enum '${m.name}'`,m,c,d,p);return}let f=t.recordTypes.get(m.name),v;try{v=Array.isArray(c)}catch{s(`Expected a plain ${m.name} record`,m,c,d,p);return}if(!f||typeof c!==\"object\"||c===null||v){s(`Expected a ${m.name} record`,m,c,d,p);return}let L;try{L=Object.getPrototypeOf(c)}catch{s(`Expected a plain ${m.name} record`,m,c,d,p);return}if(L!==Object.prototype&&L!==null){s(`Expected a plain ${m.name} record`,m,c,d,p);return}if(u.has(c)){s(\"Cyclic values are not supported\",m,c,d,p);return}u.add(c);let j=c,_=new Set(f.fields.map((I)=>I.name));try{let I;try{I=Reflect.ownKeys(j)}catch{s(`Expected a plain ${m.name} record`,m,c,d,p);return}for(let h of f.fields){let D=C(h,t.dimensionRegistry),S;try{S=Object.getOwnPropertyDescriptor(j,h.name)}catch{s(`Expected a plain data field '${h.name}'`,U(h.annotation,D),\"accessor\",`${d}.${h.name}`,h.source);continue}if(!S)s(`Missing computed field '${h.name}'`,U(h.annotation,D),\"missing\",`${d}.${h.name}`,h.source);else if(!(\"value\"in S)||S.enumerable!==!0)s(`Expected a plain data field '${h.name}'`,U(h.annotation,D),\"accessor\",`${d}.${h.name}`,h.source);else l(S.value,U(h.annotation,D),`${d}.${h.name}`,h.source)}for(let h of I)if(typeof h!==\"string\"||!_.has(h)){let D=\"unsupported property\";try{let S=Object.getOwnPropertyDescriptor(j,h);if(S&&\"value\"in S)D=S.value}catch{D=\"unavailable property\"}s(`Unknown computed field '${String(h)}'`,m,D,`${d}.${String(h)}`,p)}}finally{u.delete(c)}};if(l(e,n,o),a.length)Q(a)}function Sn(e,n,t){if(!e.defaultExpression)return null;let r=n.dimensionRegistry;n.dimensionRegistry=C(e,r);try{return y(e.defaultExpression,n,t)}finally{n.dimensionRegistry=r}}function U(e,n){let t=n instanceof W?n.dimensionRegistry:n;if(e.type===\"namedType\"){let i=t?.dimensions.get(e.name);return i?{kind:\"measurement\",vector:i.vector}:{kind:\"named\",name:e.name}}let r=U(e.element,t);return e.type===\"listType\"?{kind:\"list\",element:r}:{kind:\"nullable\",element:r}}function Ee(e){if(e.kind===\"named\")return e.name;if(e.kind===\"measurement\")return\"measurement\";if(e.kind===\"null\")return\"null\";return e.kind===\"list\"?`${Ee(e.element)}[]`:`${Ee(e.element)}?`}function Ae(e){if(typeof e===\"number\"&&!Number.isFinite(e))return String(e);let n;try{n=JSON.stringify(e)??String(e)}catch{n=String(e)}return n.replace(/[\\x00-\\x1f\\x7f]/g,(t)=>`\\\\u${t.charCodeAt(0).toString(16).padStart(4,\"0\")}`).slice(0,160)}function ee(e,n){return Object.keys(e.unit.vector).length===n.size&&[...n].every(([t,r])=>e.unit.vector[t]===r)}function Ye(e){let n=e.match(/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,9})?(Z|[+-]\\d{2}:\\d{2})$/);if(!n)return!1;let[,t,r,i,o,a,u,s]=n,l=new Date(0);return l.setUTCFullYear(+t,+r-1,+i),l.getUTCFullYear()===+t&&l.getUTCMonth()===+r-1&&l.getUTCDate()===+i&&+o<=23&&+a<=59&&+u<=59&&(s===\"Z\"||+s.slice(1,3)<=23&&+s.slice(4)<=59)}function me(e,n,t,r,i=t.dimensionRegistry){if(n.type===\"nullableType\")return e===null||me(e,n.element,t,r,i);if(n.type===\"listType\")return Array.isArray(e)&&e.every((l)=>me(l,n.element,t,r,i));let o=n.name,a=i?.dimensions.get(o);if(a)return b(e)&&ee(e,a.vector);if(o===\"Number\")return typeof e===\"number\";if(o===\"String\")return typeof e===\"string\";if(o===\"Boolean\")return typeof e===\"boolean\";if(o===\"DateTime\")return typeof e===\"string\"&&Ye(e);let u=t.enumDeclarations.get(o);if(u){if(typeof e!==\"number\"&&typeof e!==\"string\")return!1;if(!u.resolvedValues)throw Error(`Enum '${o}' has not been resolved`);return u.resolvedValues.includes(e)}let s=t.recordTypes.get(o);if(s){if(typeof e!==\"object\"||e===null||Array.isArray(e)||b(e))return!1;let l=e;return s.fields.every((c)=>{if(!Object.prototype.hasOwnProperty.call(l,c.name))return c.optional;return me(l[c.name],c.annotation,t,r,C(c,i))})}return w(\"AMX3001\",`Unknown type '${o}'`,n.source,r)}function y(e,n,t){switch(e.type){case\"nullLiteral\":return null;case\"recordConstructor\":{let r=n.recordTypes.get(e.name);if(!r)throw Error(`Unknown record type '${e.name}'`);let i=new Map(e.fields.map((a)=>[a.name,y(a.expression,n,t)])),o={};for(let a of r.fields)o[a.name]=i.has(a.name)?i.get(a.name):a.defaultExpression?Sn(a,n,t):null;return G(o,{kind:\"named\",name:e.name},n,e.source,t,`record ${e.name}`),o}case\"fieldAccess\":{if(e.receiver.type===\"identifier\"){let r=n.enumValues.get(e.receiver.name);if(r)return r[e.field]}return y(e.receiver,n,t)[e.field]}case\"listAccess\":return Fn(e,n,t);case\"numberLiteral\":return e.value;case\"stringLiteral\":return e.value;case\"stringInterpolation\":return e.parts.map((r)=>{if(typeof r===\"string\")return r;let i=y(r,n,t);if(i===null)return\"null\";if(typeof i===\"string\"||typeof i===\"number\")return String(i);if(typeof i===\"boolean\")return i?\"true\":\"false\";if(b(i))return`${String(i.value)} ${i.unit.text}`;return w(\"AMX3007\",\"Only String, Number, Boolean, measurement, and null values can be interpolated\",r.source,t)}).join(\"\");case\"booleanLiteral\":return e.value;case\"identifier\":if(e.name===\"PI\")return Math.PI;if(e.name===\"E\")return Math.E;return n.get(e.name,e.source,t);case\"measurementAttachment\":{let r=y(e.value,n,t),i=n.dimensionRegistry?.units.get(e.unit);if(!i)return w(\"AMX3008\",`Unknown or invisible unit '${e.unit}'`,e.unitSource??e.source,t);if(typeof r!==\"number\")return w(\"AMX3007\",\"Unit attachment requires a Number expression\",e.source,t);let o=k(r,ce(i));if(!Number.isFinite(x(o)))N(\"Measurement physical value must be finite\",e.source,t);return o}case\"measurementConversion\":{let r=y(e.value,n,t),i=n.dimensionRegistry?.units.get(e.unit);if(!i)return w(\"AMX3008\",`Unknown or invisible unit '${e.unit}'`,e.unitSource??e.source,t);if(!b(r)||!ee(r,i.vector))return w(\"AMX3007\",`Cannot convert value to unit '${e.unit}'`,e.source,t);let o=ce(i),a=te(x(r),o);if(!Number.isFinite(a))N(\"Converted measurement value must be finite\",e.source,t);return k(a,o)}case\"binaryExpression\":return kn(e,n,t);case\"typeTestExpression\":return me(y(e.value,n,t),e.target,n,t);case\"unaryExpression\":return $n(e,n,t);case\"conditionalExpression\":return In(e,n,t);case\"bracedIfExpression\":return Tn(e,n,t);case\"listLiteral\":return Ln(e,n,t);case\"functionCall\":return jn(e,n,t);case\"rangeExpression\":return Bn(e,n,t);case\"forExpression\":return Pn(e,n,t);case\"matchExpression\":return Nn(e,n,t);default:throw Error(`Unsupported expression node type: ${e}`)}}function Nn(e,n,t){let r=y(e.expression,n,t);for(let i of e.cases)if(r===i.value.value)return y(i.expression,n,t);return y(e.defaultExpression,n,t)}function kn(e,n,t){let r=y(e.left,n,t),i=y(e.right,n,t),o=e.operatorSource??e.source;switch(e.operator){case\"+\":case\"-\":{if(b(r)||b(i)){if(!b(r)||!b(i)||!ee(r,new Map(Object.entries(i.unit.vector))))return w(\"AMX3007\",\"Addition and subtraction require compatible measurements\",o,t);if(e.operator===\"+\"&&(T(r.unit)||T(i.unit)))return w(\"AMX3007\",\"Direct addition of affine measurements is not supported\",o,t);let s=x(r),l=x(i),c=e.operator===\"+\"?s+l:s-l,m=e.operator===\"+\"?te(c,r.unit):c/r.unit.scale;if(!Number.isFinite(m)||!Number.isFinite(c))N(\"Measurement arithmetic result must be finite\",o,t);return k(m,r.unit)}let a=E(r,e.left),u=E(i,e.right);return e.operator===\"+\"?a+u:a-u}case\"*\":case\"/\":{if(b(r)||b(i)){let s={scale:1,offset:0,vector:{},factors:[],text:\"1\"},l=b(r)?r:void 0,c=b(i)?i:void 0;if(l&&T(l.unit)||c&&T(c.unit))return w(\"AMX3007\",e.operator===\"*\"?\"Affine measurement multiplication is not supported\":\"Affine measurement division is not supported\",o,t);let m=l?l.value:E(r,e.left),d=c?c.value:E(i,e.right),p=l?.unit??s,g=c?.unit??s,f=l?x(l):m,v=c?x(c):d;if(e.operator===\"/\"&&v===0)N(\"Measurement division by zero\",o,t);let L=qe(p,g,e.operator===\"/\"),j=e.operator===\"/\"?f/v:f*v;if(L.vector&&Object.keys(L.vector).length===0){if(!Number.isFinite(j))N(\"Measurement arithmetic result must be finite\",o,t);return j}let _=e.operator===\"/\"?m/d:m*d;if(!Number.isFinite(L.scale)||L.scale<=0||!Number.isFinite(_)||!Number.isFinite(j))N(\"Measurement arithmetic result must be finite\",o,t);return k(_,L)}let a=E(r,e.left),u=E(i,e.right);return e.operator===\"*\"?a*u:a/u}case\"%\":{let a=E(r,e.left),u=E(i,e.right);return a%u}case\"^\":{if(b(r)){if(T(r.unit))return w(\"AMX3007\",\"Affine measurement powers are not supported\",o,t);let s=E(i,e.right);if(!Number.isSafeInteger(s))return w(\"AMX3007\",\"A dimensional power exponent must be an integer literal\",e.right.source,t);if(r.value===0&&s<0)N(\"Zero measurement cannot be raised to a negative power\",o,t);let l=xe(r.unit,s),c=Math.pow(r.value,s);if(!Number.isFinite(c)||!Number.isFinite(l.scale))N(\"Measurement power result must be finite\",o,t);let m=k(c,l);if(Object.keys(l.vector).length===0)return x(m);return m}let a=E(r,e.left),u=E(i,e.right);return Math.pow(a,u)}case\"==\":if(b(r)&&b(i))return ee(r,new Map(Object.entries(i.unit.vector)))&&x(r)===x(i);return r===i;case\"!=\":if(b(r)&&b(i))return!ee(r,new Map(Object.entries(i.unit.vector)))||x(r)!==x(i);return r!==i;case\">\":if(b(r)&&b(i))return x(r)>x(i);return E(r,e.left)>E(i,e.right);case\">=\":if(b(r)&&b(i))return x(r)>=x(i);return E(r,e.left)>=E(i,e.right);case\"<\":if(b(r)&&b(i))return x(r)<x(i);return E(r,e.left)<E(i,e.right);case\"<=\":if(b(r)&&b(i))return x(r)<=x(i);return E(r,e.left)<=E(i,e.right);case\"and\":return O(r)&&O(i);case\"or\":return O(r)||O(i);default:throw Error(`Unsupported binary operator: ${e.operator}`)}}function $n(e,n,t){let r=y(e.argument,n,t);if(e.operator===\"-\"){if(b(r))return k(-r.value,r.unit);return-E(r,e.argument)}if(e.operator===\"not\")return!O(r);throw Error(`Unsupported unary operator: ${e.operator}`)}function In(e,n,t){let r=y(e.test,n,t);return O(r)?y(e.consequent,n,t):y(e.alternate,n,t)}class De{value;constructor(e){this.value=e}}class Se{value;constructor(e){this.value=e}}class Ne{value;constructor(e){this.value=e}}var Ze=new WeakMap,Je=new WeakMap,ke=new WeakMap,de=new WeakMap;function $e(e,n,t){e.set(n,(e.get(n)??0)+1);try{return t()}finally{let r=e.get(n)-1;if(r)e.set(n,r);else e.delete(n)}}function Rn(e,n){let t=de.get(n),r=t?.[t.length-1];if(!r||r.has(e))return;let i=n.has(e);r.set(e,{existed:i,value:i?n.get(e):void 0})}function Ie(e,n,t){let r=de.get(n)??[],i=new Map;r.push(i),de.set(n,r);try{Re(e,n,t)}finally{r.pop();for(let[o,a]of i)if(a.existed)n.set(o,a.value);else n.delete(o);if(!r.length)de.delete(n)}}function Tn(e,n,t){let r=O(y(e.test,n,t))?e.consequent:e.alternate,i=r===e.consequent?e.consequentSource:e.alternateSource;try{$e(Ze,n,()=>Ie(r,n,t))}catch(o){if(o instanceof De)return o.value;throw o}return w(\"AMX3021\",\"Every possible path in an if expression must return a value\",i??e.source,t)}function Ln(e,n,t){return e.elements.map((r)=>y(r,n,t))}function Fn(e,n,t){let r=y(e.receiver,n,t),i=y(e.index,n,t);if(!Array.isArray(r))V(\"List access requires a list value\",e.source,t);if(typeof i!==\"number\"||!Number.isFinite(i)||!Number.isInteger(i)||i<1)V(`List index must be a positive integer; got ${Ae(i)}`,e.index.source??e.source,t);if(i>r.length)V(`List index ${i} is out of bounds for length ${r.length}; expected 1..${r.length}`,e.index.source??e.source,t);return r[i-1]}function pe(e,n){if(e.type===\"binaryExpression\")return pe(e.left,n)??e.operatorSource??e.source??n;if(e.type===\"unaryExpression\"){let t=pe(e.argument,n);if(t)return{line:t.line,column:Math.max(1,t.column-(e.operator===\"not\"?3:1))}}if(e.type===\"measurementAttachment\"||e.type===\"measurementConversion\")return pe(e.value,n)??e.source??n;return e.source??n}function Qe(e){return Array.isArray(e)?e.map(Qe):e}function Vn(e){return e.kind===\"list\"||e.kind===\"nullable\"&&e.element.kind===\"list\"}function jn(e,n,t){let r=e.arguments.map((a)=>y(a,n,t)),i=n.functions.get(e.callee);if(i){let a=C(i,n.dimensionRegistry),u={};i.parameters.forEach((m,d)=>{let p=U(m.annotation,a);G(r[d],p,n,e.arguments[d]?.source??e.source,t,`function ${e.callee}.${m.name}`);let g=r[d];u[m.name]=Vn(p)&&g!==null?Qe(g):g});let s=n.createCallFrame(u);s.dimensionRegistry=a,i.parameters.forEach((m)=>{s.bindingTypes.set(m.name,U(m.annotation,a))});let l,c=i.body;if(c.kind===\"expression\")l=y(c.expression,s,t);else{let m=!1;try{$e(ke,s,()=>Re(c.statements,s,t))}catch(d){if(!(d instanceof Ne))throw d;m=!0,l=d.value}if(!m)Oe(c.closingSource,t)}return G(l,U(i.returnType,a),n,e.source,t,`function ${e.callee} return`),l}let o=r[0];if([\"sum\",\"mean\",\"min\",\"max\"].includes(e.callee)&&Array.isArray(o)&&(o.length>0&&b(o[0]))){let a=o,u=a[0];for(let m of a){if(!ee(u,new Map(Object.entries(m.unit.vector))))return w(\"AMX3007\",`${e.callee} requires compatible measurement dimensions`,e.source,t);if(Array.isArray(o)&&o.length>0&&typeof o[0]===\"number\"&&[\"sum\",\"mean\",\"min\",\"max\"].includes(e.callee))return re(e.callee,r,e.source,t)}if(e.callee===\"min\"||e.callee===\"max\"){if(!a.length)return re(e.callee,r,e.source,t);return a.reduce((m,d)=>(e.callee===\"min\"?x(d)<x(m):x(d)>x(m))?d:m)}let s=a.reduce((m,d)=>m+x(d),0),l=e.callee===\"mean\"?s/a.length:s,c=te(l,u.unit);if(!Number.isFinite(s)||!Number.isFinite(l)||!Number.isFinite(c))N(`${e.callee} result must be finite`,e.source,t);return k(c,u.unit)}if(e.callee===\"sum\"&&Array.isArray(o)&&o.length===0&&e.arguments[0]?.type===\"identifier\"){let a=n.bindingTypes.get(e.arguments[0].name);if(a?.kind===\"list\"&&a.element.kind===\"measurement\"&&n.dimensionRegistry)return k(0,se(a.element.vector,n.dimensionRegistry))}if(b(r[0])){let a=r[0];if(Ge(e.callee)){if(Object.keys(a.unit.vector).length!==0)return w(\"AMX3007\",`'${e.callee}' requires a Number or dimensionless Measurement`,e.arguments[0]?.source??e.source,t);return re(e.callee,[x(a)],e.source,t)}switch(e.callee){case\"abs\":return k(Math.abs(a.value),a.unit);case\"round\":{let u=r.length>1?E(r[1],e.arguments[1]):0,s=Math.pow(10,Math.trunc(u)),l=Math.round(a.value*s)/s;if(!Number.isFinite(l))N(\"round result must be finite\",e.source,t);return k(l,a.unit)}case\"sqrt\":{if(T(a.unit))return w(\"AMX3007\",\"Affine measurement sqrt is not supported\",e.source,t);if(x(a)<0)N(\"sqrt of a negative measurement value\",e.source,t);if(!n.dimensionRegistry)throw Error(\"Measurement registry is unavailable during sqrt evaluation\");try{let s=Be(a,n.dimensionRegistry);if(!Number.isFinite(s.value)||!Number.isFinite(s.unit.scale))N(\"sqrt result must be finite\",e.source,t);if(Object.keys(s.unit.vector).length===0)return x(s);return s}catch(s){if(s instanceof Error&&s.message.startsWith(\"sqrt requires\"))return w(\"AMX3007\",s.message,e.source,t);throw s}}case\"pow\":{if(T(a.unit))return w(\"AMX3007\",\"Affine measurement powers are not supported\",e.source,t);let u=E(r[1],e.arguments[1]);if(!Number.isSafeInteger(u))return w(\"AMX3007\",\"A dimensional pow exponent must be an integer literal\",e.arguments[1]?.source,t);if(a.value===0&&u<0)N(\"Zero measurement cannot be raised to a negative power\",e.source,t);let s=xe(a.unit,u),l=Math.pow(a.value,u);if(!Number.isFinite(l)||!Number.isFinite(s.scale))N(\"pow result must be finite\",e.source,t);let c=k(l,s);if(!Object.keys(s.vector).length)return x(c);return c}}}return re(e.callee,r,e.source,t,e.arguments.map((a)=>pe(a,e.source)))}function E(e,n){if(typeof e===\"number\")return e;if(typeof e===\"boolean\")return e?1:0;if(typeof e===\"string\"){let i=Number(e);if(!Number.isNaN(i))return i}let t=n?.source,r=t?` at line ${t.line}`:\"\";throw Error(`Cannot convert value to number${r}`)}function O(e){if(typeof e===\"boolean\")return e;if(typeof e===\"number\")return e!==0;if(typeof e===\"string\")return e.length>0;if(Array.isArray(e))return e.length>0;if(e&&typeof e===\"object\")return!0;return!1}function Re(e,n,t){let r=n.currentStatementIndex;try{for(let i=0;i<e.length;i++)n.currentStatementIndex=i,nn(e[i],n,t)}finally{n.currentStatementIndex=r}}function ne(e){if(b(e))return`${e.value} ${e.unit.text}`;if(Array.isArray(e))return Object.freeze(e.map(ne));if(e&&typeof e===\"object\"){let n={};for(let[t,r]of Object.entries(e))n[t]=ne(r);return Object.freeze(n)}return e}function Xn(e,n,t,r){let i=n.viewDefinitions.get(e);if(!i)return w(\"AMX3001\",`Unknown visualization '${e}'`,r,t);let o=n.get(i.binding,i.bindingSource,t);if(!Array.isArray(o)){let d=J(\"AMX4003\",`Visualization '${e}' requires a list value`,{file:t,line:i.bindingSource?.line,column:i.bindingSource?.column,dataPath:`visualization ${e}`,expected:\"list\",actual:Array.isArray(o)?\"list\":typeof o});Q([d])}let a,u,s,l=!1,c;if(i.type===\"chartDeclaration\"){let d=i.options.find((f)=>f.type===\"chartShowTableOption\");if(d?.type===\"chartShowTableOption\"){let f=y(d.expression,n,t);if(typeof f!==\"boolean\")w(\"AMX3002\",`Expected Boolean, got ${typeof f}`,d.expression.source,t);l=f}let p=i.options.find((f)=>f.type===\"chartFieldOption\"&&f.role===\"labels\");if(p?.type===\"chartFieldOption\"){let f=n.get(p.field,p.fieldSource,t);if(!Array.isArray(f)||!f.every((v)=>typeof v===\"string\")){let v=J(\"AMX4003\",`Chart '${e}' labels must be a String[] value`,{file:t,line:p.source?.line,column:p.source?.column,dataPath:`visualization ${e}.labels`,expected:\"String[]\",actual:Array.isArray(f)?\"invalid list value\":typeof f});Q([v])}if(f.length!==o.length){let v=J(\"AMX4003\",`Chart '${e}' has ${o.length} values but ${f.length} labels`,{file:t,line:p.source?.line,column:p.source?.column,dataPath:`visualization ${e}.labels`,expected:`${o.length} labels`,actual:`${f.length} labels`});Q([v])}a=ne(f)}let g=zn(o,i,e,t);c=g.data,u=g.headings,s=g.measurementDescriptors}else c=ne(o);let m={name:e,data:c,documentNodeIndex:n.currentDocumentNodeIndex,statementIndex:n.currentStatementIndex,source:r};return i.type===\"tableDeclaration\"?Object.freeze({kind:\"table\",...m,declaration:i}):Object.freeze({kind:\"chart\",...m,declaration:i,showTable:l,...a?{labels:a}:{},...u?{headings:u}:{},...s?.length?{measurementDescriptors:s}:{}})}function zn(e,n,t,r){let i=n.kind===\"scatter\",o=i?n.options.filter((c)=>c.type===\"chartFieldOption\"&&(c.role===\"x\"||c.role===\"y\")).map((c)=>({role:c.role,field:c.field,label:c.role,source:c.source})):n.options.filter((c)=>c.type===\"chartSeriesOption\").map((c)=>({role:\"series\",field:c.field,label:c.label,source:c.source})),a=o.map((c)=>{let m=c.field,d=e.map((f)=>f!==null&&typeof f===\"object\"&&!Array.isArray(f)&&!b(f)?f[m??\"\"]:m===void 0?f:void 0),p=d.find((f)=>f!==null&&f!==void 0),g=b(p)?p:void 0;for(let f of d){if(f===null||f===void 0)continue;if(g){if(!b(f)||!en(f,g))w(\"AMX3007\",`Chart '${t}' contains incompatible measurement dimensions`,c.source,r,n.source)}else if(b(f))w(\"AMX3007\",`Chart '${t}' mixes measurements with non-measurement values`,c.source,r,n.source)}return g}),u=i?[\"x\",\"y\"].map((c,m)=>a[m]?`${c} (${a[m].unit.text})`:c).concat(\"group\"):[\"label\",...o.flatMap((c,m)=>c.role===\"series\"?[a[m]?`${c.label} (${a[m].unit.text})`:c.label]:[])],s=o.flatMap((c,m)=>{let d=a[m]?.unit;if(!d)return[];return[Object.freeze({role:c.role,...c.field===void 0?{}:{field:c.field},label:c.label,unit:Object.freeze({text:d.text,scale:d.scale,vector:Object.freeze({...d.vector}),factors:Object.freeze(d.factors.map((p)=>Object.freeze({...p})))})})]}),l=e.map((c)=>{if(c!==null&&typeof c===\"object\"&&!Array.isArray(c)&&!b(c)){let m={};for(let[d,p]of Object.entries(c)){let g=o.findIndex((f)=>f.field===d);m[d]=g<0?ne(p):Ke(p,a[g],t,o[g]?.source,n,r)}return Object.freeze(m)}return Ke(c,a[0],t,o[0]?.source,n,r)});return{data:Object.freeze(l),headings:Object.freeze(u),measurementDescriptors:Object.freeze(s)}}function Ke(e,n,t,r,i,o){if(e===null||e===void 0)return null;if(!n)return ne(e);if(!b(e)||!en(e,n))w(\"AMX3007\",`Chart '${t}' contains an incompatible measurement value`,r,o,i.source);let a=te(x(e),n.unit);if(!Number.isFinite(a))w(\"AMX3007\",`Chart '${t}' measurement cannot be normalized to its first display unit`,r,o,i.source);return a}function en(e,n){let t=Object.entries(e.unit.vector);return t.length===Object.keys(n.unit.vector).length&&t.every(([r,i])=>n.unit.vector[r]===i)}function nn(e,n,t){switch(e.type){case\"importDeclaration\":case\"exportNamesDeclaration\":return;case\"dimensionDeclaration\":case\"unitDeclaration\":return;case\"inputDeclaration\":return;case\"tableDeclaration\":case\"chartDeclaration\":n.viewDefinitions.set(e.name,e);return;case\"diagramDeclaration\":n.diagramEmissions.push({model:rn(e,n,t,n.currentDocumentNodeIndex,n.currentStatementIndex)});return;case\"showStatement\":n.viewEmissions.push(Xn(e.name,n,t,e.source));return;case\"typeDeclaration\":n.recordTypes.set(e.name,e);return;case\"enumDeclaration\":{let r=e.resolvedValues??e.members.map((o,a)=>{if(!o.value)return a+1;if(o.value.type===\"numberLiteral\"||o.value.type===\"stringLiteral\")return o.value.value;return w(\"AMX3020\",\"Only constant values can be assigned to enum members\",o.valueSource??o.value.source,t)}),i={};e.members.forEach((o,a)=>{i[o.name]=r[a]}),n.enumDeclarations.set(e.name,e),n.enumValues.set(e.name,i);return}case\"functionDeclaration\":n.functions.set(e.name,e);return;case\"variableDeclaration\":{Rn(e.name,n);let r=y(e.expression,n,t),i=n.bindingTypes.get(e.name);if(i)G(r,i,n,e.source,t,e.name);n.set(e.name,r)}return;case\"assignmentStatement\":{let r=y(e.expression,n,t),i=n.bindingTypes.get(e.name);if(i)G(r,i,n,e.source,t,e.name);n.update(e.name,r,e.source,t);return}case\"compoundAssignmentStatement\":{let r=y({type:\"binaryExpression\",operator:\"+\",left:{type:\"identifier\",name:e.name,source:e.source},right:e.expression,source:e.source},n,t),i=n.bindingTypes.get(e.name);if(i)G(r,i,n,e.source,t,e.name);n.update(e.name,r,e.source,t);return}case\"addStatement\":Un(e,n,t);return;case\"removeStatement\":qn(e,n,t);return;case\"forStatement\":_n(e,n,t);return;case\"bracedIfStatement\":On(e,n,t);return;case\"returnStatement\":if(Ze.has(n))throw new De(y(e.expression,n,t));if(Je.has(n))throw new Se(y(e.expression,n,t));if(ke.has(n))throw new Ne(y(e.expression,n,t));ze(e.source,t)}}function On(e,n,t){let r=O(y(e.test,n,t))?e.consequent:e.alternate;if(r)Ie(r,n,t)}function tn(e,n,t,r){let i=n.get(e,t,r);if(!Array.isArray(i))V(`Mutation target '${e}' is not a list`,t,r);if(n.isImmutable(i))V(`Cannot mutate immutable imported list '${e}'`,t,r);return i}function Cn(e,n){let t=n.bindingTypes.get(e);return t?.kind===\"list\"?t.element:void 0}function ve(e,n,t,r){if(typeof e!==\"number\"||!Number.isFinite(e)||!Number.isInteger(e)||e<1)V(`${n} must be a positive integer; got ${Ae(e)}`,t,r);return e}function Un(e,n,t){let r=tn(e.name,n,e.source,t),i=y(e.value,n,t),o=Cn(e.name,n);if(o)G(i,o,n,e.value.source??e.source,t,`${e.name} element`);let a=e.index?ve(y(e.index,n,t),\"Insertion position\",e.index.source??e.source,t):r.length+1;if(a>r.length+1)V(`Insertion position ${a} is out of bounds for length ${r.length}; expected 1..${r.length+1}`,e.index?.source??e.source,t);r.splice(a-1,0,i)}function qn(e,n,t){let r=tn(e.name,n,e.source,t),i=ve(y(e.count,n,t),\"Removal count\",e.count.source??e.source,t);if(r.length===0)V(\"Cannot remove from an empty list\",e.source,t);if(!e.index){r.pop();return}let o=ve(y(e.index,n,t),\"Removal position\",e.index.source??e.source,t);if(o>r.length)V(`Removal position ${o} is out of bounds for length ${r.length}; expected 1..${r.length}`,e.index.source??e.source,t);if(i>r.length-o+1)V(`Removal interval ${o}..${o+i-1} exceeds list length ${r.length}`,e.count.source??e.source,t);r.splice(o-1,i)}function Bn(e,n,t){let r=y(e.start,n,t),i=y(e.end,n,t);if(typeof r!==\"number\"||!Number.isFinite(r)||!Number.isInteger(r)||typeof i!==\"number\"||!Number.isFinite(i)||!Number.isInteger(i))he(e.source,t);let o=[],a=r<=i?1:-1;for(let u=r;a>0?u<=i:u>=i;u+=a)if(o.push(u),u+a===u&&u!==i)he(e.source,t);return o}function _n(e,n,t){let r=fe(e.iterable,n,t);ie(e.variable,r,n,()=>{if(ke.has(n))Ie(e.body,n,t);else Re(e.body,n,t)})}function Pn(e,n,t){let r=fe(e.iterable,n,t),i=[];return $e(Je,n,()=>ie(e.variable,r,n,()=>{for(let o of e.body)if(o.type===\"returnStatement\")i.push(y(o.expression,n,t));else try{nn(o,n,t)}catch(a){if(a instanceof Se)i.push(a.value);else throw a}})),i}function fe(e,n,t){let r=y(e,n,t);if(!Array.isArray(r))Xe(e.source,t);return r.slice()}function ie(e,n,t,r){let i=t.has(e),o=i?t.get(e):void 0;try{for(let a of n)t.set(e,a),r()}finally{if(i)t.set(e,o);else t.delete(e)}}var Le=new WeakMap,Fe=new WeakMap;function on(e){return e.some((n)=>n.type!==\"diagramElement\")}function Wn(e){if(on(e.declaration.content))throw Error(\"Version 1 control-bearing diagram models are missing expanded instances.\")}function q(e){if(!Array.isArray(e)||typeof e[0]!==\"string\")throw Error(\"Invalid serialized diagram value.\");switch(e[0]){case\"undefined\":if(e.length!==1)throw Error(\"Invalid serialized undefined diagram value.\");return;case\"null\":if(e.length!==1)throw Error(\"Invalid serialized null diagram value.\");return null;case\"boolean\":if(e.length!==2||typeof e[1]!==\"boolean\")throw Error(\"Invalid serialized boolean diagram value.\");return e[1];case\"number\":if(e.length!==2)throw Error(\"Invalid serialized number diagram value.\");if(e[1]===\"nan\")return NaN;if(e[1]===\"positive-infinity\")return 1/0;if(e[1]===\"negative-infinity\")return-1/0;if(typeof e[1]!==\"number\")throw Error(\"Invalid serialized number diagram value.\");return e[1];case\"string\":if(e.length!==2||typeof e[1]!==\"string\")throw Error(\"Invalid serialized string diagram value.\");return e[1];case\"array\":if(e.length!==2||!Array.isArray(e[1]))throw Error(\"Invalid serialized array diagram value.\");return e[1].map(q);case\"object\":{if(e.length!==2||!Array.isArray(e[1]))throw Error(\"Invalid serialized object diagram value.\");let n=e[1].map((t)=>{if(!Array.isArray(t)||t.length!==2||typeof t[0]!==\"string\")throw Error(\"Invalid serialized object entry in diagram value.\");return[t[0],q(t[1])]});return Object.fromEntries(n)}case\"map\":if(e.length!==2||!Array.isArray(e[1]))throw Error(\"Invalid serialized map diagram value.\");return new Map(e[1].map((n)=>{if(!Array.isArray(n)||n.length!==2)throw Error(\"Invalid serialized map entry in diagram value.\");return[q(n[0]),q(n[1])]}));case\"set\":if(e.length!==2||!Array.isArray(e[1]))throw Error(\"Invalid serialized set diagram value.\");return new Set(e[1].map(q));default:throw Error(\"Unknown serialized diagram value type.\")}}function oe(e,n){if(!(e instanceof Map))throw Error(`Invalid serialized diagram context map '${n}'.`);for(let t of e.keys())if(typeof t!==\"string\")throw Error(`Invalid key in serialized diagram context map '${n}'.`);return e}function Te(e,n=new Set){if(e===void 0||e===null||typeof e===\"boolean\"||typeof e===\"number\"||typeof e===\"string\")return;if(!e||typeof e!==\"object\")throw Error(\"Unsupported serialized diagram instance binding value.\");if(n.has(e))throw Error(\"Serialized diagram instance binding contains a cyclic value.\");n.add(e);try{if(Array.isArray(e)){e.forEach((r)=>Te(r,n));return}let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw Error(\"Unsupported serialized diagram instance binding value.\");Object.values(e).forEach((r)=>Te(r,n))}finally{n.delete(e)}}function Hn(e,n){if(!Array.isArray(n))throw Error(\"Invalid serialized diagram instance source path.\");let t=e,r=0,i=!1,o=[];while(r<n.length){let a=n[r++];if(!a||typeof a!==\"object\"||Array.isArray(a)||a.type!==\"content\"||!Number.isSafeInteger(a.index)||a.index<0)throw Error(\"Invalid serialized diagram instance source path.\");let u=t[a.index];if(!u)throw Error(\"Serialized diagram instance source path does not resolve.\");if(u.type===\"diagramElement\"){if(r!==n.length)throw Error(\"Serialized diagram instance source path continues past a primitive.\");return{element:u,bindingNames:o,controlOriginating:i}}if(i=!0,u.type===\"diagramForBlock\"){o.push(u.variable),t=u.content;continue}let s=n[r++];if(!s||typeof s!==\"object\"||Array.isArray(s)||s.type!==\"branch\"||s.branch!==\"consequent\"&&s.branch!==\"alternate\")throw Error(\"Invalid serialized diagram instance branch path.\");if(t=s.branch===\"consequent\"?u.consequent:u.alternate??[],s.branch===\"alternate\"&&!u.alternate)throw Error(\"Serialized diagram instance source path does not resolve.\")}throw Error(\"Serialized diagram instance source path does not resolve to a primitive.\")}function Gn(e,n){if(!Array.isArray(n))throw Error(\"Invalid serialized diagram instance list.\");let t=0,r=n.map((i,o)=>{if(!i||typeof i!==\"object\"||Array.isArray(i)||!(\"identity\"in i)||!(\"bindings\"in i)||!Number.isSafeInteger(i.identity)||i.identity!==o||!Array.isArray(i.bindings))throw Error(\"Invalid serialized diagram instance descriptor.\");let a=i,u=a.bindings,s=Hn(e,a.sourcePath);if(s.controlOriginating&&++t>cn)throw Error(\"Serialized diagram instance list exceeds the generated element limit.\");if(u.length!==s.bindingNames.length)throw Error(\"Serialized diagram instance has incomplete loop bindings.\");let l=u.map((c,m)=>{if(!c||typeof c!==\"object\"||Array.isArray(c)||!(\"name\"in c)||!(\"value\"in c))throw Error(\"Invalid serialized diagram instance loop binding.\");let d=c;if(d.name!==s.bindingNames[m]||typeof d.name!==\"string\")throw Error(\"Invalid serialized diagram instance loop binding.\");let p=q(d.value);return Te(p),Object.freeze({name:d.name,value:p})});return Object.freeze({identity:a.identity,element:s.element,bindings:Object.freeze(l)})});return Object.freeze(r)}function an(e){let n=JSON.parse(e);if(!n||typeof n!==\"object\"||Array.isArray(n)||!(\"version\"in n)||n.version!==1&&n.version!==2||!(\"model\"in n)||!(\"context\"in n))throw Error(\"Invalid serialized diagram model envelope.\");let t=n,r=t.version;if(r===2){if(!Array.isArray(t.instances))throw Error(\"Invalid serialized diagram instance list.\");if(!Number.isSafeInteger(t.instanceCount)||t.instanceCount!==t.instances.length)throw Error(\"Serialized diagram instance count does not match its payload.\")}let i=q(t.model),o=q(t.context);if(!i||typeof i!==\"object\"||Array.isArray(i)||!o||typeof o!==\"object\"||Array.isArray(o))throw Error(\"Invalid serialized diagram model or evaluation context.\");let a=ge(i);if(!a.declaration||!Array.isArray(a.declaration.content))throw Error(\"Invalid serialized diagram declaration.\");let u=r===1?(Wn(a),un(a.declaration.content)):Gn(a.declaration.content,t.instances),s=o;if(!s.values||typeof s.values!==\"object\"||Array.isArray(s.values)||!Array.isArray(s.immutableValues)||!s.declarationRegistries||!Array.isArray(s.declarationRegistries.records)||!Array.isArray(s.declarationRegistries.functions)||s.validationMode!==\"aggregate\"&&s.validationMode!==\"fail-fast\")throw Error(\"Invalid serialized diagram evaluation context.\");let l=oe(s.recordTypes,\"recordTypes\"),c=oe(s.functions,\"functions\"),m=new W(l,c,s.dimensionRegistry);m.validationMode=s.validationMode;for(let[d,p]of Object.entries(s.values))if(m.set(d,p),s.immutableValues.includes(d))m.markImmutable(p);for(let[d,p]of oe(s.enumDeclarations,\"enumDeclarations\"))m.enumDeclarations.set(d,p);for(let[d,p]of oe(s.enumValues,\"enumValues\"))m.enumValues.set(d,p);for(let[d,p]of oe(s.bindingTypes,\"bindingTypes\"))m.bindingTypes.set(d,p);for(let d of s.declarationRegistries.records){let p=l.get(d.name);if(!p||!Array.isArray(d.fields))throw Error(\"Invalid serialized record declaration registry.\");if(d.declaration)P(p,d.declaration);let g=p.declaredFields??p.fields;if(g.length!==d.fields.length)throw Error(\"Serialized record field registry does not match its declaration.\");d.fields.forEach((f,v)=>{if(f)P(g[v],f)})}for(let d of s.declarationRegistries.functions){let p=c.get(d.name);if(!p)throw Error(\"Invalid serialized function declaration registry.\");if(d.declaration)P(p,d.declaration)}return Le.set(a,m),Fe.set(a,u),a}function A(e,n=new Map){if(!e||typeof e!==\"object\")return e;let t=n.get(e);if(t)return t;if(Array.isArray(e)){let i=[];n.set(e,i);for(let o of e)i.push(A(o,n));return i}if(e instanceof Map){let i=new Map;n.set(e,i);for(let[o,a]of e)i.set(A(o,n),A(a,n));return i}if(e instanceof Set){let i=new Set;n.set(e,i);for(let o of e)i.add(A(o,n));return i}let r={};n.set(e,r);for(let[i,o]of Object.entries(e))r[i]=A(o,n);return r}function ge(e,n=new Set){if(!e||typeof e!==\"object\"||n.has(e))return e;if(n.add(e),Array.isArray(e))e.forEach((t)=>ge(t,n));else if(!(e instanceof Map)&&!(e instanceof Set))Object.values(e).forEach((t)=>ge(t,n));return Object.freeze(e)}function sn(e){let n=A(e.recordTypes),t=A(e.functions),r=e.dimensionRegistry?A(e.dimensionRegistry):void 0,i=new W(n,t,r);i.validationMode=e.validationMode;for(let[o,a]of e.recordTypes){let u=n.get(o),s=C(a,e.dimensionRegistry);if(s)P(u,A(s));let l=a.declaredFields??a.fields,c=u.declaredFields??u.fields;for(let m=0;m<l.length;m++){let d=C(l[m],e.dimensionRegistry);if(d&&c[m])P(c[m],A(d))}}for(let[o,a]of e.functions){let u=C(a,e.dimensionRegistry);if(u)P(t.get(o),A(u))}for(let[o,a]of e.enumDeclarations)i.enumDeclarations.set(o,A(a));for(let[o,a]of e.enumValues)i.enumValues.set(o,A(a));for(let[o,a]of e.bindingTypes)i.bindingTypes.set(o,A(a));for(let[o,a]of Object.entries(e.toObject())){let u=A(a);if(i.set(o,u),e.isImmutable(a))i.markImmutable(u)}return i}var cn=64;function un(e){if(on(e))throw Error(\"Control-bearing diagram models are missing their expanded per-instance bindings.\");return Object.freeze(e.map((n,t)=>{if(n.type!==\"diagramElement\")throw Error(\"Unexpected diagram control in static content.\");return Object.freeze({identity:t,element:n,bindings:Object.freeze([])})}))}function Kn(e,n,t){let r=[],i=[],o=0,a=(u,s)=>{for(let l of u){if(l.type===\"diagramElement\"){if(s){if(o>=cn)w(\"AMXD6004\",\"Number of elements in this diagram exceed the maximum (64)\",l.source??l.nameSource,t);o++}r.push(Object.freeze({identity:r.length,element:l,bindings:Object.freeze(i.map((m)=>Object.freeze({name:m.name,value:A(m.value)})))}));continue}if(l.type===\"diagramForBlock\"){let m=fe(l.iterable,n,t);ie(l.variable,m,n,()=>{i.push({name:l.variable,value:n.get(l.variable)});try{a(l.content,!0)}finally{i.pop()}});continue}let c=O(y(l.test,n,t))?l.consequent:l.alternate;if(c)a(c,!0)}};return a(e,!1),Object.freeze(r)}function ln(e,n,t,r=0){if(r>=e.length)return t();let i,o=e[r];return ie(o.name,[o.value],n,()=>{i=ln(e,n,t,r+1)}),i}function K(e,n){let t=e.properties.find((r)=>r.name===n);if(!t)throw Error(`Type checker accepted missing diagram property '${n}'`);return t}function Yn(e,n,t,r,i,o){let a=K(e,n),u=y(a.expression,t,r);if(typeof u!==\"number\"||!Number.isFinite(u)){if(u===1/0&&o===i.to)w(\"AMXD010\",\"Infinity value calculated for time upper bound\",a.valueSource??a.source,r);if(u===1/0&&o>i.from&&o<i.to)w(\"AMXD011\",\"Expression produces an infinite result\",a.valueSource??a.source,r);w(\"AMXD008\",\"Invalid primitive geometry\",a.valueSource??a.source,r)}return u}function mn(e,n,t,r,i,o){if(typeof t!==\"number\"||!Number.isFinite(t)||t<n.from||t>n.to)w(\"AMXD004\",\"Invalid time bounds\",e.times[0]?.source??e.source,o);let a=sn(i);a.set(n.variable,t);let u=(l)=>{let c=(p)=>Yn(l,p,a,o,n,t),m=(p)=>{let g=K(l,p).expression;if(g.type!==\"stringLiteral\")throw Error(\"Type checker accepted a non-literal diagram style\");return g.value},d=()=>{let p=K(l,\"lineWidth\").expression;if(p.type!==\"numberLiteral\")throw Error(\"Type checker accepted a non-literal line width\");return p.value};try{switch(l.primitive){case\"line\":{let p=l.properties.find((f)=>f.name===\"arrow\")?.expression,g=p?.type===\"stringLiteral\"?p.value:\"none\";return Object.freeze({primitive:\"line\",name:l.name,source:l.source,x1:c(\"x1\"),y1:c(\"y1\"),x2:c(\"x2\"),y2:c(\"y2\"),stroke:m(\"stroke\"),lineWidth:d(),arrow:g})}case\"rectangle\":{let p=c(\"width\"),g=c(\"height\");if(p<=0)w(\"AMXD008\",\"Invalid primitive geometry\",K(l,\"width\").valueSource,o);if(g<=0)w(\"AMXD008\",\"Invalid primitive geometry\",K(l,\"height\").valueSource,o);let f=l.properties.some((v)=>v.name===\"fill\")?m(\"fill\"):void 0;return Object.freeze({primitive:\"rectangle\",name:l.name,source:l.source,x:c(\"x\"),y:c(\"y\"),width:p,height:g,stroke:m(\"stroke\"),...f===void 0?{}:{fill:f},lineWidth:d()})}case\"circle\":{let p=c(\"r\");if(p<=0)w(\"AMXD008\",\"Invalid primitive geometry\",K(l,\"r\").valueSource,o);let g=l.properties.some((f)=>f.name===\"fill\")?m(\"fill\"):void 0;return Object.freeze({primitive:\"circle\",name:l.name,source:l.source,cx:c(\"cx\"),cy:c(\"cy\"),r:p,stroke:m(\"stroke\"),...g===void 0?{}:{fill:g},lineWidth:d()})}case\"text\":{let p=K(l,\"value\"),g=y(p.expression,a,o);if(typeof g!==\"string\")w(\"AMX3002\",\"Expected String, got non-String value\",p.valueSource,o);return Object.freeze({primitive:\"text\",name:l.name,source:l.source,x:c(\"x\"),y:c(\"y\"),value:g,fill:m(\"fill\")})}default:throw Error(`Type checker accepted unsupported diagram primitive '${l.primitive}'`)}}catch(p){if(p instanceof M&&t!==n.from&&p.code!==\"AMXD008\"&&p.code!==\"AMXD010\"&&p.code!==\"AMXD011\")throw new M({code:\"AMXD009\",message:`Frame evaluation leads to invalid results. The underlying error is: ${p.message}`,file:p.file??o,line:p.line??l.source?.line,column:p.column??l.source?.column});throw p}},s=r.map((l)=>ln(l.bindings,a,()=>u(l.element)));return Object.freeze({time:t,elements:Object.freeze(s)})}function ae(e,n,t,r,i,o){let a=y(e,n,t);if(typeof a!==\"number\"||!Number.isFinite(a)||(r===\"AMXD003\"||r===\"AMXD014\"||r===\"AMXD005\")&&a<=0)w(r,i,o,t);return a}function rn(e,n,t,r,i){let o=ge(A(e)),a=sn(n),u=(D)=>{let S=o.properties.find((R)=>R.name===D);if(!S)throw Error(`Type checker accepted missing diagram property '${D}'`);return S},s=u(\"width\"),l=u(\"height\"),c=ae(s.expression,a,t,\"AMXD003\",\"Canvas width is invalid\",s.valueSource),m=ae(l.expression,a,t,\"AMXD014\",\"Canvas height is invalid\",l.valueSource),d=u(\"title\").expression,p=u(\"description\").expression;if(d.type!==\"stringLiteral\"||p.type!==\"stringLiteral\")throw Error(\"Type checker accepted a non-literal diagram title or description\");let g=o.times[0],f=ae(g.from,a,t,\"AMXD004\",\"Invalid time bounds\",g.fromSource??g.source),v=ae(g.to,a,t,\"AMXD004\",\"Invalid time bounds\",g.toSource??g.source);if(f>=v)w(\"AMXD004\",\"Invalid time bounds\",g.source??o.source,t);let L=ae(g.duration,a,t,\"AMXD005\",\"Invalid playback duration value\",g.durationSource??g.source),j=Object.freeze({variable:g.name,from:f,to:v,duration:L}),_=Kn(o.content,a,t),I=mn(o,j,f,_,a,t),h=Object.freeze({name:o.name,title:d.value,description:p.value,canvas:Object.freeze({width:c,height:m,coordinates:\"bottom-left-y-up\"}),timeline:j,declaration:o,initialFrame:I,source:o.source,file:t,documentNodeIndex:r,statementIndex:i});return Le.set(h,a),Fe.set(h,_),h}function dn(e,n,t=e.file){let r=Le.get(e);if(!r)throw Error(\"Diagram model has no captured AMX evaluation context\");let i=Fe.get(e)??un(e.declaration.content);return mn(e.declaration,e.timeline,n,i,r,t)}var Zn=\"http://www.w3.org/2000/svg\",Ve=new Set;function B(e,n={}){let t=document.createElementNS(Zn,e);for(let[r,i]of Object.entries(n))t.setAttribute(r,String(i));return t}function Jn(e,n,t){e.setAttribute(\"x\",String(n)),e.setAttribute(\"y\",String(t)),e.setAttribute(\"transform\",`translate(0 ${2*t}) scale(1 -1)`)}function Qn(e,n){let{model:t,canvas:r}=e,i=B(\"defs\"),o=B(\"marker\",{id:`${r.dataset.diagramId}-arrowhead`,markerWidth:6,markerHeight:6,refX:10,refY:5,orient:\"auto-start-reverse\",markerUnits:\"strokeWidth\",viewBox:\"0 0 10 10\"});o.append(B(\"path\",{d:\"M 0 0 L 10 5 L 0 10 z\",fill:\"context-stroke\"})),i.append(o);let a=B(\"g\",{transform:`translate(0 ${t.canvas.height}) scale(1 -1)`});for(let u of n.elements)if(u.primitive===\"line\"){let s=B(\"line\",{x1:u.x1,y1:u.y1,x2:u.x2,y2:u.y2,stroke:u.stroke,\"stroke-width\":u.lineWidth,\"stroke-linecap\":\"round\"});if(s.setAttribute(\"data-diagram-element\",u.name),u.arrow===\"start\"||u.arrow===\"both\")s.setAttribute(\"marker-start\",`url(#${r.dataset.diagramId}-arrowhead)`);if(u.arrow===\"end\"||u.arrow===\"both\")s.setAttribute(\"marker-end\",`url(#${r.dataset.diagramId}-arrowhead)`);a.append(s)}else if(u.primitive===\"rectangle\"){let s=B(\"rect\",{x:u.x,y:u.y,width:u.width,height:u.height,stroke:u.stroke,fill:u.fill??\"none\",\"stroke-width\":u.lineWidth});s.setAttribute(\"data-diagram-element\",u.name),a.append(s)}else if(u.primitive===\"circle\"){let s=B(\"circle\",{cx:u.cx,cy:u.cy,r:u.r,stroke:u.stroke,fill:u.fill??\"none\",\"stroke-width\":u.lineWidth});s.setAttribute(\"data-diagram-element\",u.name),a.append(s)}else{let s=B(\"text\",{fill:u.fill,\"font-family\":\"sans-serif\",\"font-size\":12});Jn(s,u.x,u.y),s.setAttribute(\"data-diagram-element\",u.name),s.textContent=u.value,a.append(s)}r.replaceChildren(i,a),r.removeAttribute(\"aria-hidden\")}function je(e){window.dispatchEvent(new CustomEvent(\"openamx-diagram-frame\",{detail:e}))}async function et(e){if(e.dataset.encoding!==\"gzip-base64\")throw Error(\"Unsupported diagram data encoding.\");let n=atob(e.textContent??\"\"),t=new Uint8Array(n.length);for(let i=0;i<n.length;i++)t[i]=n.charCodeAt(i);let r=new Blob([t]).stream().pipeThrough(new DecompressionStream(\"gzip\"));return an(await new Response(r).text())}function ye(e){let n=e.model.title,t=e.time.toFixed(3).toString();e.playButton.textContent=e.running?\"Pause\":\"Play\",e.playButton.setAttribute(\"aria-label\",`${e.running?\"Pause\":\"Play\"} ${n}`),e.scrubber.value=String(e.time),e.scrubber.setAttribute(\"aria-valuetext\",t),e.timeOutput.value=t,e.timeOutput.textContent=t}function Y(e){if(e.running=!1,e.animationFrame!==void 0)cancelAnimationFrame(e.animationFrame);e.animationFrame=void 0,ye(e)}function Z(e,n){e.time=n,ye(e);try{let t=dn(e.model,n);if(Qn(e,t),e.alert.hidden=!0,e.alert.textContent=\"\",e.failed)e.failed=!1,je({version:1,type:\"diagram-recovered\",diagramId:e.canvas.dataset.diagramId});return!0}catch(t){Y(e),e.canvas.replaceChildren(),e.canvas.setAttribute(\"aria-hidden\",\"true\"),e.failed=!0;let r=t instanceof M?{code:t.code,message:t.message,file:t.file??e.model.file,line:t.line??e.model.source?.line,column:t.column??e.model.source?.column}:{code:\"DIAGRAM_RUNTIME\",message:\"The diagram frame could not be evaluated.\",file:e.model.file,line:e.model.source?.line,column:e.model.source?.column},i=r.file?`${r.file}${r.line?`:${r.line}${r.column?`:${r.column}`:\"\"}`:\"\"}`:r.line?`${r.line}${r.column?`:${r.column}`:\"\"}`:\"\";return e.alert.textContent=`${r.code}: ${r.message}${i?` (${i})`:\"\"}`,e.alert.hidden=!1,je({version:1,type:\"diagram-error\",diagramId:e.canvas.dataset.diagramId,...r}),!1}}function nt(e){if(e.running||e.failed)return;if(e.time>=e.model.timeline.to){if(!e.canvas.closest(\"[data-openamx-diagram]\")?.querySelector(\"[data-diagram-loop]\")?.checked)return;Z(e,e.model.timeline.from)}e.running=!0,e.startedAt=performance.now()-(e.time-e.model.timeline.from)/(e.model.timeline.to-e.model.timeline.from)*e.model.timeline.duration*1000,ye(e),e.animationFrame=requestAnimationFrame((n)=>pn(e,n))}function pn(e,n){if(!e.running||!document.contains(e.canvas)){Y(e);return}let t=e.model.timeline.duration,r=(n-e.startedAt)/1000/t;if(r>=1){if(!(e.canvas.closest(\"[data-openamx-diagram]\")?.querySelector(\"[data-diagram-loop]\")?.checked??!1)){Z(e,e.model.timeline.to),Y(e);return}if(!Z(e,e.model.timeline.from))return;e.startedAt=n}else{let i=e.model.timeline.from,o=e.model.timeline.to,a=r<=0?i:i*(1-r)+o*r;if(!Z(e,a))return}e.animationFrame=requestAnimationFrame((i)=>pn(e,i))}async function tt(e){let n=e.querySelector(\"[data-diagram-model]\"),t=e.querySelector(\"[data-diagram-canvas]\"),r=e.querySelector(\"[data-diagram-play]\"),i=e.querySelector(\"[data-diagram-reset]\"),o=e.querySelector(\"[data-diagram-scrubber]\"),a=e.querySelector(\"[data-diagram-loop]\"),u=e.querySelector(\"[data-diagram-time]\"),s=e.querySelector(\"[data-diagram-error]\");if(!n||!t||!r||!i||!o||!a||!u||!s)throw Error(\"Diagram HTML is missing required runtime elements.\");let l=await et(n);t.dataset.diagramId=e.dataset.diagramId;let c={model:l,canvas:t,playButton:r,scrubber:o,timeOutput:u,alert:s,running:!1,failed:!1,time:l.timeline.from,startedAt:0};Ve.add(c),ye(c),r.addEventListener(\"click\",()=>{if(c.running)Y(c);else nt(c)}),i.addEventListener(\"click\",()=>{Y(c),Z(c,l.timeline.from)}),o.addEventListener(\"input\",()=>{let m=Number(o.value);Y(c),Z(c,m)}),Z(c,l.timeline.from)}async function rt(){for(let e of Array.from(document.querySelectorAll(\"[data-openamx-diagram]\")))try{await tt(e)}catch(n){let t=e.querySelector(\"[data-diagram-error]\");if(!t)throw n;t.textContent=`DIAGRAM_RUNTIME: ${n instanceof Error?n.message:\"The diagram could not be initialized.\"}`,t.hidden=!1,je({version:1,type:\"diagram-error\",diagramId:e.dataset.diagramId??\"\",code:\"DIAGRAM_RUNTIME\",message:t.textContent})}}document.addEventListener(\"DOMContentLoaded\",()=>{rt()},{once:!0});window.addEventListener(\"pagehide\",()=>{for(let e of Ve)Y(e);Ve.clear()},{once:!0});})();\n";
2
2
  export default diagramBrowserRuntime;
@@ -1,6 +1,6 @@
1
1
  import { Environment } from './environment';
2
- import { evaluateStatements } from './evaluateExpression';
3
- import { checkDocument } from '../typechecker/checkDocument';
2
+ import { checkDocumentWithRuntimePlan } from '../typechecker/checkDocument';
3
+ import { evaluateDocumentNodes, prepareTypeScriptBlocks } from './typescriptBridge';
4
4
  /**
5
5
  * Evaluate an OpenAmxDocument in source order.
6
6
  * - Only executable code-block statements are processed.
@@ -13,20 +13,15 @@ export function evaluateDocument(doc, file) {
13
13
  }
14
14
  /** Evaluate executable blocks once and return their shared final environment. */
15
15
  export function evaluateDocumentEnvironment(doc, file) {
16
- const checked = checkDocument(doc, file);
16
+ const checked = checkDocumentWithRuntimePlan(doc, file);
17
+ const prepared = prepareTypeScriptBlocks(checked.typescriptBlocks, file);
17
18
  const env = new Environment(new Map(), new Map(), {
18
- dimensions: checked.dimensions,
19
- units: checked.units,
20
- baseUnits: checked.baseUnits
19
+ dimensions: checked.result.dimensions,
20
+ units: checked.result.units,
21
+ baseUnits: checked.result.baseUnits
21
22
  });
22
- for (const [name, type] of checked.bindingTypes)
23
+ for (const [name, type] of checked.result.bindingTypes)
23
24
  env.bindingTypes.set(name, type);
24
- for (let nodeIndex = 0; nodeIndex < doc.nodes.length; nodeIndex++) {
25
- const node = doc.nodes[nodeIndex];
26
- if (node.type === 'executableCodeBlock') {
27
- env.currentDocumentNodeIndex = nodeIndex;
28
- evaluateStatements(node.statements, env, file);
29
- }
30
- }
25
+ evaluateDocumentNodes(doc, env, file, checked.typescriptBlocks, prepared);
31
26
  return env;
32
27
  }