@nova-energy/openamx 0.16.0 → 0.18.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.
@@ -1,8 +1,17 @@
1
1
  import { AmxError, staticError } from '../diagnostics/errors';
2
2
  import { fieldRegistry, setDeclaringRegistry } from '../typechecker/declarationRegistry';
3
- import { evaluateExpression } from './evaluateExpression';
3
+ import { evaluateExpression, evaluateLoopIterable, toBoolean, withLoopBinding } from './evaluateExpression';
4
4
  import { Environment } from './environment';
5
5
  const capturedContexts = new WeakMap();
6
+ const expandedElementsByModel = new WeakMap();
7
+ function hasDiagramControls(content) {
8
+ return content.some(node => node.type !== 'diagramElement');
9
+ }
10
+ function assertLegacyDiagramSerializationSupported(model) {
11
+ if (hasDiagramControls(model.declaration.content)) {
12
+ throw new Error('Version 1 control-bearing diagram models are missing expanded instances.');
13
+ }
14
+ }
6
15
  function serializeValue(value, ancestors = new Set()) {
7
16
  if (value === undefined)
8
17
  return ['undefined'];
@@ -107,10 +116,168 @@ function mapValue(value, field) {
107
116
  throw new Error(`Invalid key in serialized diagram context map '${field}'.`);
108
117
  return value;
109
118
  }
119
+ function serializeBindingValue(value, ancestors = new Set()) {
120
+ if (value === undefined || value === null || typeof value === 'boolean'
121
+ || typeof value === 'number' || typeof value === 'string')
122
+ return serializeValue(value);
123
+ if (!value || typeof value !== 'object')
124
+ throw new Error('Unsupported diagram instance binding value.');
125
+ if (ancestors.has(value))
126
+ throw new Error('Diagram instance binding contains a cyclic value.');
127
+ ancestors.add(value);
128
+ try {
129
+ if (Array.isArray(value))
130
+ return ['array', value.map(item => serializeBindingValue(item, ancestors))];
131
+ const prototype = Object.getPrototypeOf(value);
132
+ if (prototype !== Object.prototype && prototype !== null || Object.getOwnPropertySymbols(value).length > 0) {
133
+ throw new Error('Unsupported diagram instance binding value.');
134
+ }
135
+ return ['object', Object.entries(value).map(([key, item]) => [key, serializeBindingValue(item, ancestors)])];
136
+ }
137
+ finally {
138
+ ancestors.delete(value);
139
+ }
140
+ }
141
+ function assertDiagramBindingValue(value, ancestors = new Set()) {
142
+ if (value === undefined || value === null || typeof value === 'boolean'
143
+ || typeof value === 'number' || typeof value === 'string')
144
+ return;
145
+ if (!value || typeof value !== 'object')
146
+ throw new Error('Unsupported serialized diagram instance binding value.');
147
+ if (ancestors.has(value))
148
+ throw new Error('Serialized diagram instance binding contains a cyclic value.');
149
+ ancestors.add(value);
150
+ try {
151
+ if (Array.isArray(value)) {
152
+ value.forEach(item => assertDiagramBindingValue(item, ancestors));
153
+ return;
154
+ }
155
+ const prototype = Object.getPrototypeOf(value);
156
+ if (prototype !== Object.prototype && prototype !== null) {
157
+ throw new Error('Unsupported serialized diagram instance binding value.');
158
+ }
159
+ Object.values(value).forEach(item => assertDiagramBindingValue(item, ancestors));
160
+ }
161
+ finally {
162
+ ancestors.delete(value);
163
+ }
164
+ }
165
+ function collectDiagramElementPaths(content, paths = new Map(), prefix = []) {
166
+ content.forEach((node, index) => {
167
+ const path = [...prefix, { type: 'content', index }];
168
+ if (node.type === 'diagramElement') {
169
+ if (paths.has(node))
170
+ throw new Error('A diagram primitive appears at multiple AST paths.');
171
+ paths.set(node, path);
172
+ }
173
+ else if (node.type === 'diagramForBlock') {
174
+ collectDiagramElementPaths(node.content, paths, path);
175
+ }
176
+ else {
177
+ collectDiagramElementPaths(node.consequent, paths, [...path, { type: 'branch', branch: 'consequent' }]);
178
+ if (node.alternate) {
179
+ collectDiagramElementPaths(node.alternate, paths, [...path, { type: 'branch', branch: 'alternate' }]);
180
+ }
181
+ }
182
+ });
183
+ return paths;
184
+ }
185
+ function resolveDiagramElementPath(content, sourcePath) {
186
+ if (!Array.isArray(sourcePath))
187
+ throw new Error('Invalid serialized diagram instance source path.');
188
+ let currentContent = content;
189
+ let pathIndex = 0;
190
+ let controlOriginating = false;
191
+ const bindingNames = [];
192
+ while (pathIndex < sourcePath.length) {
193
+ const segment = sourcePath[pathIndex++];
194
+ if (!segment || typeof segment !== 'object' || Array.isArray(segment)
195
+ || segment.type !== 'content' || !Number.isSafeInteger(segment.index) || segment.index < 0) {
196
+ throw new Error('Invalid serialized diagram instance source path.');
197
+ }
198
+ const node = currentContent[segment.index];
199
+ if (!node)
200
+ throw new Error('Serialized diagram instance source path does not resolve.');
201
+ if (node.type === 'diagramElement') {
202
+ if (pathIndex !== sourcePath.length)
203
+ throw new Error('Serialized diagram instance source path continues past a primitive.');
204
+ return { element: node, bindingNames, controlOriginating };
205
+ }
206
+ controlOriginating = true;
207
+ if (node.type === 'diagramForBlock') {
208
+ bindingNames.push(node.variable);
209
+ currentContent = node.content;
210
+ continue;
211
+ }
212
+ const branch = sourcePath[pathIndex++];
213
+ if (!branch || typeof branch !== 'object' || Array.isArray(branch)
214
+ || branch.type !== 'branch' || (branch.branch !== 'consequent' && branch.branch !== 'alternate')) {
215
+ throw new Error('Invalid serialized diagram instance branch path.');
216
+ }
217
+ currentContent = branch.branch === 'consequent' ? node.consequent : node.alternate ?? [];
218
+ if (branch.branch === 'alternate' && !node.alternate) {
219
+ throw new Error('Serialized diagram instance source path does not resolve.');
220
+ }
221
+ }
222
+ throw new Error('Serialized diagram instance source path does not resolve to a primitive.');
223
+ }
224
+ function serializeDiagramInstances(model, instances) {
225
+ const paths = collectDiagramElementPaths(model.declaration.content);
226
+ return instances.map(instance => {
227
+ const sourcePath = paths.get(instance.element);
228
+ if (!sourcePath)
229
+ throw new Error('Diagram instance source is absent from its declaration.');
230
+ return {
231
+ identity: instance.identity,
232
+ sourcePath,
233
+ bindings: instance.bindings.map(binding => ({
234
+ name: binding.name,
235
+ value: serializeBindingValue(binding.value)
236
+ }))
237
+ };
238
+ });
239
+ }
240
+ function deserializeDiagramInstances(content, value) {
241
+ if (!Array.isArray(value))
242
+ throw new Error('Invalid serialized diagram instance list.');
243
+ let controlCount = 0;
244
+ const instances = value.map((raw, index) => {
245
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)
246
+ || !('identity' in raw) || !('bindings' in raw)
247
+ || !Number.isSafeInteger(raw.identity) || raw.identity !== index || !Array.isArray(raw.bindings)) {
248
+ throw new Error('Invalid serialized diagram instance descriptor.');
249
+ }
250
+ const descriptor = raw;
251
+ const rawBindings = descriptor.bindings;
252
+ const resolved = resolveDiagramElementPath(content, descriptor.sourcePath);
253
+ if (resolved.controlOriginating && ++controlCount > generatedElementLimit) {
254
+ throw new Error('Serialized diagram instance list exceeds the generated element limit.');
255
+ }
256
+ if (rawBindings.length !== resolved.bindingNames.length) {
257
+ throw new Error('Serialized diagram instance has incomplete loop bindings.');
258
+ }
259
+ const bindings = rawBindings.map((binding, bindingIndex) => {
260
+ if (!binding || typeof binding !== 'object' || Array.isArray(binding)
261
+ || !('name' in binding) || !('value' in binding)) {
262
+ throw new Error('Invalid serialized diagram instance loop binding.');
263
+ }
264
+ const entry = binding;
265
+ if (entry.name !== resolved.bindingNames[bindingIndex] || typeof entry.name !== 'string') {
266
+ throw new Error('Invalid serialized diagram instance loop binding.');
267
+ }
268
+ const bindingValue = deserializeValue(entry.value);
269
+ assertDiagramBindingValue(bindingValue);
270
+ return Object.freeze({ name: entry.name, value: bindingValue });
271
+ });
272
+ return Object.freeze({ identity: descriptor.identity, element: resolved.element, bindings: Object.freeze(bindings) });
273
+ });
274
+ return Object.freeze(instances);
275
+ }
110
276
  export function serializeDiagramSceneModel(model) {
111
277
  const env = capturedContexts.get(model);
112
278
  if (!env)
113
279
  throw new Error('Diagram model has no captured AMX evaluation context');
280
+ const instances = expandedElementsByModel.get(model) ?? directDiagramElements(model.declaration.content);
114
281
  const context = {
115
282
  values: env.toObject(),
116
283
  immutableValues: Object.entries(env.toObject()).filter(([, value]) => env.isImmutable(value)).map(([name]) => name),
@@ -135,26 +302,43 @@ export function serializeDiagramSceneModel(model) {
135
302
  }
136
303
  };
137
304
  const payload = {
138
- version: 1,
305
+ version: 2,
139
306
  model: serializeValue(model),
140
- context: serializeValue(context)
307
+ context: serializeValue(context),
308
+ instances: serializeDiagramInstances(model, instances),
309
+ instanceCount: instances.length
141
310
  };
142
311
  return JSON.stringify(payload);
143
312
  }
144
313
  export function deserializeDiagramSceneModel(serialized) {
145
314
  const payload = JSON.parse(serialized);
146
315
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)
147
- || !('version' in payload) || payload.version !== 1
316
+ || !('version' in payload) || (payload.version !== 1 && payload.version !== 2)
148
317
  || !('model' in payload) || !('context' in payload)) {
149
318
  throw new Error('Invalid serialized diagram model envelope.');
150
319
  }
151
- const modelValue = deserializeValue(payload.model);
152
- const contextValue = deserializeValue(payload.context);
320
+ const envelope = payload;
321
+ const version = envelope.version;
322
+ if (version === 2) {
323
+ if (!Array.isArray(envelope.instances))
324
+ throw new Error('Invalid serialized diagram instance list.');
325
+ if (!Number.isSafeInteger(envelope.instanceCount) || envelope.instanceCount !== envelope.instances.length) {
326
+ throw new Error('Serialized diagram instance count does not match its payload.');
327
+ }
328
+ }
329
+ const modelValue = deserializeValue(envelope.model);
330
+ const contextValue = deserializeValue(envelope.context);
153
331
  if (!modelValue || typeof modelValue !== 'object' || Array.isArray(modelValue)
154
332
  || !contextValue || typeof contextValue !== 'object' || Array.isArray(contextValue)) {
155
333
  throw new Error('Invalid serialized diagram model or evaluation context.');
156
334
  }
157
335
  const model = freezeData(modelValue);
336
+ if (!model.declaration || !Array.isArray(model.declaration.content)) {
337
+ throw new Error('Invalid serialized diagram declaration.');
338
+ }
339
+ const instances = version === 1
340
+ ? (assertLegacyDiagramSerializationSupported(model), directDiagramElements(model.declaration.content))
341
+ : deserializeDiagramInstances(model.declaration.content, envelope.instances);
158
342
  const context = contextValue;
159
343
  if (!context.values || typeof context.values !== 'object' || Array.isArray(context.values)
160
344
  || !Array.isArray(context.immutableValues) || !context.declarationRegistries
@@ -202,6 +386,7 @@ export function deserializeDiagramSceneModel(serialized) {
202
386
  setDeclaringRegistry(declaration, item.declaration);
203
387
  }
204
388
  capturedContexts.set(model, env);
389
+ expandedElementsByModel.set(model, instances);
205
390
  return model;
206
391
  }
207
392
  function cloneData(value, seen = new Map()) {
@@ -287,6 +472,73 @@ function cloneEnvironment(source) {
287
472
  }
288
473
  return copy;
289
474
  }
475
+ const generatedElementLimit = 64;
476
+ function directDiagramElements(content) {
477
+ if (hasDiagramControls(content)) {
478
+ throw new Error('Control-bearing diagram models are missing their expanded per-instance bindings.');
479
+ }
480
+ return Object.freeze(content.map((node, identity) => {
481
+ if (node.type !== 'diagramElement')
482
+ throw new Error('Unexpected diagram control in static content.');
483
+ return Object.freeze({ identity, element: node, bindings: Object.freeze([]) });
484
+ }));
485
+ }
486
+ function expandDiagramContent(content, env, file) {
487
+ const instances = [];
488
+ const bindings = [];
489
+ let generatedCount = 0;
490
+ const visit = (nodes, controlOriginating) => {
491
+ for (const node of nodes) {
492
+ if (node.type === 'diagramElement') {
493
+ if (controlOriginating) {
494
+ if (generatedCount >= generatedElementLimit) {
495
+ staticError('AMXD6004', 'Number of elements in this diagram exceed the maximum (64)', node.source ?? node.nameSource, file);
496
+ }
497
+ generatedCount++;
498
+ }
499
+ instances.push(Object.freeze({
500
+ identity: instances.length,
501
+ element: node,
502
+ bindings: Object.freeze(bindings.map(binding => Object.freeze({
503
+ name: binding.name,
504
+ value: cloneData(binding.value)
505
+ })))
506
+ }));
507
+ continue;
508
+ }
509
+ if (node.type === 'diagramForBlock') {
510
+ const values = evaluateLoopIterable(node.iterable, env, file);
511
+ withLoopBinding(node.variable, values, env, () => {
512
+ bindings.push({ name: node.variable, value: env.get(node.variable) });
513
+ try {
514
+ visit(node.content, true);
515
+ }
516
+ finally {
517
+ bindings.pop();
518
+ }
519
+ });
520
+ continue;
521
+ }
522
+ const branch = toBoolean(evaluateExpression(node.test, env, file))
523
+ ? node.consequent
524
+ : node.alternate;
525
+ if (branch)
526
+ visit(branch, true);
527
+ }
528
+ };
529
+ visit(content, false);
530
+ return Object.freeze(instances);
531
+ }
532
+ function withInstanceBindings(bindings, env, run, index = 0) {
533
+ if (index >= bindings.length)
534
+ return run();
535
+ let result;
536
+ const binding = bindings[index];
537
+ withLoopBinding(binding.name, [binding.value], env, () => {
538
+ result = withInstanceBindings(bindings, env, run, index + 1);
539
+ });
540
+ return result;
541
+ }
290
542
  function property(element, name) {
291
543
  const found = element.properties.find(item => item.name === name);
292
544
  if (!found)
@@ -307,13 +559,13 @@ function requiredNumber(element, name, env, file, timeline, time) {
307
559
  }
308
560
  return value;
309
561
  }
310
- function evaluateFrame(declaration, timeline, time, sourceEnvironment, file) {
562
+ function evaluateFrame(declaration, timeline, time, instances, sourceEnvironment, file) {
311
563
  if (typeof time !== 'number' || !Number.isFinite(time) || time < timeline.from || time > timeline.to) {
312
564
  staticError('AMXD004', 'Invalid time bounds', declaration.times[0]?.source ?? declaration.source, file);
313
565
  }
314
566
  const env = cloneEnvironment(sourceEnvironment);
315
567
  env.set(timeline.variable, time);
316
- const elements = declaration.elements.map((element) => {
568
+ const evaluateElement = (element) => {
317
569
  const readNumber = (name) => requiredNumber(element, name, env, file, timeline, time);
318
570
  const readStyle = (name) => {
319
571
  const value = property(element, name).expression;
@@ -394,7 +646,8 @@ function evaluateFrame(declaration, timeline, time, sourceEnvironment, file) {
394
646
  }
395
647
  throw error;
396
648
  }
397
- });
649
+ };
650
+ const elements = instances.map((instance) => withInstanceBindings(instance.bindings, env, () => evaluateElement(instance.element)));
398
651
  return Object.freeze({ time, elements: Object.freeze(elements) });
399
652
  }
400
653
  function evaluateDocumentNumber(expression, env, file, code, message, source) {
@@ -430,7 +683,8 @@ export function createDiagramModel(sourceDeclaration, sourceEnvironment, file, d
430
683
  staticError('AMXD004', 'Invalid time bounds', time.source ?? declaration.source, file);
431
684
  const duration = evaluateDocumentNumber(time.duration, env, file, 'AMXD005', 'Invalid playback duration value', time.durationSource ?? time.source);
432
685
  const timeline = Object.freeze({ variable: time.name, from, to, duration });
433
- const initialFrame = evaluateFrame(declaration, timeline, from, env, file);
686
+ const instances = expandDiagramContent(declaration.content, env, file);
687
+ const initialFrame = evaluateFrame(declaration, timeline, from, instances, env, file);
434
688
  const model = Object.freeze({
435
689
  name: declaration.name,
436
690
  title: titleExpression.value,
@@ -445,11 +699,13 @@ export function createDiagramModel(sourceDeclaration, sourceEnvironment, file, d
445
699
  statementIndex
446
700
  });
447
701
  capturedContexts.set(model, env);
702
+ expandedElementsByModel.set(model, instances);
448
703
  return model;
449
704
  }
450
705
  export function evaluateDiagramFrame(model, time, file = model.file) {
451
706
  const env = capturedContexts.get(model);
452
707
  if (!env)
453
708
  throw new Error('Diagram model has no captured AMX evaluation context');
454
- return evaluateFrame(model.declaration, model.timeline, time, env, file);
709
+ const instances = expandedElementsByModel.get(model) ?? directDiagramElements(model.declaration.content);
710
+ return evaluateFrame(model.declaration, model.timeline, time, instances, env, file);
455
711
  }
@@ -720,7 +720,7 @@ function toNumber(v, nodeForError) {
720
720
  const locInfo = loc ? ` at line ${loc.line}` : '';
721
721
  throw new Error(`Cannot convert value to number${locInfo}`);
722
722
  }
723
- function toBoolean(v) {
723
+ export function toBoolean(v) {
724
724
  if (typeof v === 'boolean')
725
725
  return v;
726
726
  if (typeof v === 'number')
@@ -1109,13 +1109,13 @@ function evalForExpression(node, env, file) {
1109
1109
  }));
1110
1110
  return results;
1111
1111
  }
1112
- function evaluateLoopIterable(node, env, file) {
1112
+ export function evaluateLoopIterable(node, env, file) {
1113
1113
  const value = evaluateExpression(node, env, file);
1114
1114
  if (!Array.isArray(value))
1115
1115
  throwInvalidLoopIterable(node.source, file);
1116
1116
  return value.slice();
1117
1117
  }
1118
- function withLoopBinding(name, values, env, runIteration) {
1118
+ export function withLoopBinding(name, values, env, runIteration) {
1119
1119
  const existed = env.has(name);
1120
1120
  const previous = existed ? env.get(name) : undefined;
1121
1121
  try {
@@ -36,6 +36,19 @@ function reportDiagramDeclarations(doc) {
36
36
  }
37
37
  return declarations;
38
38
  }
39
+ function* authoredDiagramElements(content) {
40
+ for (const node of content) {
41
+ if (node.type === 'diagramElement')
42
+ yield node;
43
+ else if (node.type === 'diagramForBlock')
44
+ yield* authoredDiagramElements(node.content);
45
+ else {
46
+ yield* authoredDiagramElements(node.consequent);
47
+ if (node.alternate)
48
+ yield* authoredDiagramElements(node.alternate);
49
+ }
50
+ }
51
+ }
39
52
  function validateReportDiagramCaps(records) {
40
53
  let diagramCount = 0;
41
54
  let elementCount = 0;
@@ -45,7 +58,7 @@ function validateReportDiagramCaps(records) {
45
58
  if (diagramCount > 16) {
46
59
  staticError('AMXD012', 'A single report can have up to 16 diagrams maximum.', declaration.source, record.canonicalPath);
47
60
  }
48
- for (const element of declaration.elements) {
61
+ for (const element of authoredDiagramElements(declaration.content)) {
49
62
  elementCount++;
50
63
  if (elementCount > 512) {
51
64
  staticError('AMXD013', 'A single report can have up to 512 elements maximum.', element.source, record.canonicalPath);
@@ -77,6 +90,10 @@ function realpathOrFail(absolutePath, code, message, sourceFile) {
77
90
  moduleError(code, message, undefined, sourceFile);
78
91
  }
79
92
  }
93
+ function isWithinDirectory(root, candidate) {
94
+ const relative = path.relative(root, candidate);
95
+ return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
96
+ }
80
97
  /**
81
98
  * Resolve, check, and evaluate the complete module graph reachable from `entryPath`,
82
99
  * returning the entry module's document and final evaluated environment.
@@ -84,7 +101,23 @@ function realpathOrFail(absolutePath, code, message, sourceFile) {
84
101
  export async function loadEntryModule(entryPath, options = {}) {
85
102
  const absoluteEntry = path.resolve(entryPath);
86
103
  const realEntry = realpathOrFail(absoluteEntry, 'AMX5001', `Entry module '${entryPath}' could not be read`, entryPath);
87
- const entryRoot = path.dirname(realEntry);
104
+ const importRoot = options.importRoot === undefined
105
+ ? path.dirname(realEntry)
106
+ : realpathOrFail(path.resolve(options.importRoot), 'AMX5001', `Import root '${options.importRoot}' could not be read`, entryPath);
107
+ let importRootStats;
108
+ try {
109
+ importRootStats = fs.statSync(importRoot);
110
+ }
111
+ catch {
112
+ moduleError('AMX5001', `Import root '${options.importRoot ?? importRoot}' could not be read`, undefined, entryPath);
113
+ }
114
+ if (!importRootStats.isDirectory()) {
115
+ moduleError('AMX5001', 'Import root must be a directory', undefined, entryPath);
116
+ }
117
+ if (realEntry !== importRoot && !isWithinDirectory(importRoot, realEntry)) {
118
+ moduleError('AMX5001', `Entry module '${entryPath}' resolves outside the import root directory tree`, undefined, entryPath);
119
+ }
120
+ const rootDescription = options.importRoot === undefined ? 'entry directory tree' : 'import root directory tree';
88
121
  if (options.sourceOverlay) {
89
122
  if (options.sourceOverlay.size > 100) {
90
123
  moduleError('AMX5001', 'Source overlay exceeds the 100-module limit', undefined, entryPath);
@@ -94,9 +127,8 @@ export async function loadEntryModule(entryPath, options = {}) {
94
127
  moduleError('AMX5001', 'Source overlay paths must be canonical absolute paths', undefined, entryPath);
95
128
  }
96
129
  const canonicalOverlayPath = realpathOrFail(overlayPath, 'AMX5001', 'Source overlay module could not be read', entryPath);
97
- const relativeToRoot = path.relative(entryRoot, canonicalOverlayPath);
98
- if (canonicalOverlayPath !== overlayPath || relativeToRoot === '' || relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)) {
99
- moduleError('AMX5001', 'Source overlay paths must be canonical and contained by the entry directory tree', undefined, entryPath);
130
+ if (canonicalOverlayPath !== overlayPath || !isWithinDirectory(importRoot, canonicalOverlayPath)) {
131
+ moduleError('AMX5001', `Source overlay paths must be canonical and contained by the ${rootDescription}`, undefined, entryPath);
100
132
  }
101
133
  }
102
134
  }
@@ -110,7 +142,7 @@ export async function loadEntryModule(entryPath, options = {}) {
110
142
  return existing;
111
143
  const cycleIndex = visiting.indexOf(canonicalPath);
112
144
  if (cycleIndex !== -1) {
113
- const cycle = [...visiting.slice(cycleIndex), canonicalPath].map(p => path.relative(entryRoot, p) || path.basename(p));
145
+ const cycle = [...visiting.slice(cycleIndex), canonicalPath].map(p => path.relative(importRoot, p) || path.basename(p));
114
146
  moduleError('AMX5003', `Import cycle detected: ${cycle.join(' -> ')}`, viaImportSource?.pathSource, viaImportSource?.file);
115
147
  }
116
148
  visiting.push(canonicalPath);
@@ -174,9 +206,8 @@ export async function loadEntryModule(entryPath, options = {}) {
174
206
  const importerDir = path.dirname(canonicalPath);
175
207
  const targetAbsolute = path.resolve(importerDir, importNode.path);
176
208
  const targetReal = realpathOrFail(targetAbsolute, 'AMX5001', `Module '${importNode.path}' could not be found`, canonicalPath);
177
- const relativeToRoot = path.relative(entryRoot, targetReal);
178
- if (relativeToRoot === '' || relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)) {
179
- moduleError('AMX5001', `Module '${importNode.path}' resolves outside the entry directory tree`, importNode.pathSource, canonicalPath);
209
+ if (!isWithinDirectory(importRoot, targetReal)) {
210
+ moduleError('AMX5001', `Module '${importNode.path}' resolves outside the ${rootDescription}`, importNode.pathSource, canonicalPath);
180
211
  }
181
212
  const dependency = await visit(targetReal, { pathSource: importNode.pathSource, file: canonicalPath });
182
213
  for (const importedName of importNode.names) {
@@ -137,6 +137,74 @@ function expressionReferencesIdentifier(expression, name) {
137
137
  default: return false;
138
138
  }
139
139
  }
140
+ function identifierSource(expression, name) {
141
+ if (expression.type === 'identifier')
142
+ return expression.name === name ? expression.source : undefined;
143
+ switch (expression.type) {
144
+ case 'binaryExpression': return identifierSource(expression.left, name) ?? identifierSource(expression.right, name);
145
+ case 'typeTestExpression':
146
+ case 'measurementAttachment':
147
+ case 'measurementConversion':
148
+ return identifierSource(expression.value, name);
149
+ case 'unaryExpression': return identifierSource(expression.argument, name);
150
+ case 'conditionalExpression': return identifierSource(expression.test, name)
151
+ ?? identifierSource(expression.consequent, name) ?? identifierSource(expression.alternate, name);
152
+ case 'bracedIfExpression': return identifierSource(expression.test, name)
153
+ ?? bodyIdentifierSource(expression.consequent, name) ?? bodyIdentifierSource(expression.alternate, name);
154
+ case 'stringInterpolation':
155
+ return expression.parts.find((part) => typeof part !== 'string')
156
+ ? expression.parts.reduce((source, part) => source ?? (typeof part === 'string' ? undefined : identifierSource(part, name)), undefined)
157
+ : undefined;
158
+ case 'matchExpression': return identifierSource(expression.expression, name)
159
+ ?? expression.cases.reduce((source, item) => source ?? identifierSource(item.expression, name), undefined)
160
+ ?? identifierSource(expression.defaultExpression, name);
161
+ case 'rangeExpression': return identifierSource(expression.start, name) ?? identifierSource(expression.end, name);
162
+ case 'functionCall': return expression.arguments.reduce((source, argument) => source ?? identifierSource(argument, name), undefined);
163
+ case 'listLiteral': return expression.elements.reduce((source, item) => source ?? identifierSource(item, name), undefined);
164
+ case 'forExpression': return identifierSource(expression.iterable, name) ?? bodyIdentifierSource(expression.body, name);
165
+ case 'recordConstructor': return expression.fields.reduce((source, field) => source ?? identifierSource(field.expression, name), undefined);
166
+ case 'fieldAccess': return identifierSource(expression.receiver, name);
167
+ case 'listAccess': return identifierSource(expression.receiver, name) ?? identifierSource(expression.index, name);
168
+ default: return undefined;
169
+ }
170
+ }
171
+ function bodyIdentifierSource(statements, name) {
172
+ for (const statement of statements) {
173
+ let source;
174
+ switch (statement.type) {
175
+ case 'variableDeclaration':
176
+ source = identifierSource(statement.expression, name);
177
+ break;
178
+ case 'assignmentStatement':
179
+ case 'compoundAssignmentStatement':
180
+ source = identifierSource(statement.expression, name);
181
+ break;
182
+ case 'returnStatement':
183
+ source = identifierSource(statement.expression, name);
184
+ break;
185
+ case 'forStatement':
186
+ source = identifierSource(statement.iterable, name) ?? bodyIdentifierSource(statement.body, name);
187
+ break;
188
+ case 'bracedIfStatement':
189
+ source = identifierSource(statement.test, name)
190
+ ?? bodyIdentifierSource(statement.consequent, name)
191
+ ?? (statement.alternate ? bodyIdentifierSource(statement.alternate, name) : undefined);
192
+ break;
193
+ case 'addStatement':
194
+ source = identifierSource(statement.value, name)
195
+ ?? (statement.index ? identifierSource(statement.index, name) : undefined);
196
+ break;
197
+ case 'removeStatement':
198
+ source = identifierSource(statement.count, name)
199
+ ?? (statement.index ? identifierSource(statement.index, name) : undefined);
200
+ break;
201
+ default: source = undefined;
202
+ }
203
+ if (source)
204
+ return source;
205
+ }
206
+ return undefined;
207
+ }
140
208
  function bodyReferencesIdentifier(statements, name) {
141
209
  return statements.some(statement => {
142
210
  switch (statement.type) {
@@ -1405,7 +1473,44 @@ export function checkDocument(doc, file, context) {
1405
1473
  localBindings.set(time.name, named('Number'));
1406
1474
  bindings = localBindings;
1407
1475
  try {
1408
- for (const element of diagram.elements) {
1476
+ function checkDiagramContent(content) {
1477
+ for (const node of content) {
1478
+ if (node.type === 'diagramElement') {
1479
+ checkDiagramElement(node);
1480
+ continue;
1481
+ }
1482
+ if (node.type === 'diagramForBlock') {
1483
+ if (node.variable === time.name) {
1484
+ fail('AMXD6001', `Variable [${time.name}] is already used to control the diagrams timeline. Use a different variable name.`, node.variableSource ?? node.source);
1485
+ }
1486
+ if (expressionReferencesIdentifier(node.iterable, time.name)) {
1487
+ fail('AMXD6001', `Variable [${time.name}] is already used to control the diagrams timeline. Use a different variable name.`, identifierSource(node.iterable, time.name) ?? node.iterableSource ?? node.source);
1488
+ }
1489
+ const iterable = infer(node.iterable);
1490
+ if (iterable.kind !== 'list') {
1491
+ fail(iterable.kind === 'measurement' ? 'AMX3007' : 'AMX3003', 'For loop needs a list or range', node.iterableSource ?? node.source);
1492
+ }
1493
+ const outerBindings = bindings;
1494
+ bindings = new Map(outerBindings);
1495
+ bindings.set(node.variable, iterable.element);
1496
+ try {
1497
+ checkDiagramContent(node.content);
1498
+ }
1499
+ finally {
1500
+ bindings = outerBindings;
1501
+ }
1502
+ continue;
1503
+ }
1504
+ if (expressionReferencesIdentifier(node.test, time.name)) {
1505
+ fail('AMXD6001', `Variable [${time.name}] is already used to control the diagrams timeline. Use a different variable name.`, identifierSource(node.test, time.name) ?? node.testSource ?? node.source);
1506
+ }
1507
+ requireType(infer(node.test), named('Boolean'), node.testSource ?? node.source);
1508
+ checkDiagramContent(node.consequent);
1509
+ if (node.alternate)
1510
+ checkDiagramContent(node.alternate);
1511
+ }
1512
+ }
1513
+ function checkDiagramElement(element) {
1409
1514
  diagramElementCount++;
1410
1515
  if (diagramElementCount > 512) {
1411
1516
  fail('AMXD013', 'A single report can have up to 512 elements maximum.', element.source);
@@ -1465,6 +1570,7 @@ export function checkDocument(doc, file, context) {
1465
1570
  }
1466
1571
  }
1467
1572
  }
1573
+ checkDiagramContent(diagram.content);
1468
1574
  }
1469
1575
  finally {
1470
1576
  bindings = outerBindings;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nova-energy/openamx",
3
- "version": "0.16.0",
3
+ "version": "0.18.0",
4
4
  "description": "OpenAMX is an open-source, text-based, computable document format for engineering knowledge.",
5
5
  "type": "module",
6
6
  "bin": {