@nova-energy/openamx 0.16.0 → 0.19.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,4 +1,4 @@
1
- import { composeUnits, powerUnit, unitFromMetadata } from './measurement';
1
+ import { composeUnits, isAffineUnit, powerUnit, unitFromMetadata } from './measurement';
2
2
  export class ExternalUnitTextError extends Error {
3
3
  unknownUnit;
4
4
  constructor(message, unknownUnit) {
@@ -9,6 +9,7 @@ export class ExternalUnitTextError extends Error {
9
9
  }
10
10
  const unitless = Object.freeze({
11
11
  scale: 1,
12
+ offset: 0,
12
13
  vector: Object.freeze({}),
13
14
  factors: Object.freeze([]),
14
15
  text: '1'
@@ -32,10 +33,16 @@ export function parseExternalUnitText(text, registry) {
32
33
  const parseProduct = () => {
33
34
  let unit = parseFactor();
34
35
  while (true) {
35
- if (consume('*'))
36
- unit = validateUnit(composeUnits(unit, parseFactor()));
37
- else if (consume('/'))
38
- unit = validateUnit(composeUnits(unit, parseFactor(), true));
36
+ if (consume('*')) {
37
+ const right = parseFactor();
38
+ rejectAffineComposition(unit, right);
39
+ unit = validateUnit(composeUnits(unit, right));
40
+ }
41
+ else if (consume('/')) {
42
+ const right = parseFactor();
43
+ rejectAffineComposition(unit, right);
44
+ unit = validateUnit(composeUnits(unit, right, true));
45
+ }
39
46
  else
40
47
  return unit;
41
48
  }
@@ -63,6 +70,9 @@ export function parseExternalUnitText(text, registry) {
63
70
  unit = unitFromMetadata(metadata);
64
71
  }
65
72
  if (consume('^')) {
73
+ if (isAffineUnit(unit)) {
74
+ throw new ExternalUnitTextError('Affine units may not be used in external unit powers', false);
75
+ }
66
76
  skipWhitespace();
67
77
  const exponent = source.slice(offset).match(/^[+-]?\d+/);
68
78
  if (!exponent)
@@ -81,8 +91,13 @@ export function parseExternalUnitText(text, registry) {
81
91
  throw new ExternalUnitTextError(`Unexpected '${source[offset]}' in unit expression`, false);
82
92
  return Object.freeze({ ...parsed, text: source });
83
93
  }
94
+ function rejectAffineComposition(left, right) {
95
+ if (isAffineUnit(left) || isAffineUnit(right)) {
96
+ throw new ExternalUnitTextError('Affine units may not be used in external unit products or divisions', false);
97
+ }
98
+ }
84
99
  function validateUnit(unit) {
85
- if (!Number.isFinite(unit.scale) || unit.scale <= 0
100
+ if (!Number.isFinite(unit.scale) || unit.scale <= 0 || !Number.isFinite(unit.offset)
86
101
  || Object.values(unit.vector).some(exponent => !Number.isSafeInteger(exponent))
87
102
  || unit.factors.some(factor => !Number.isSafeInteger(factor.exponent))) {
88
103
  throw new ExternalUnitTextError('Unit expression exceeds supported scale or exponent limits', false);
@@ -3,7 +3,7 @@ import { inputError, throwInputErrors } from '../diagnostics/errors';
3
3
  import { Environment } from './environment';
4
4
  import { evaluateExpression } from './evaluateExpression';
5
5
  import { parseStrictCsvText, parseStrictJsonText } from './dataText';
6
- import { isMeasurement, measurement } from './measurement';
6
+ import { isMeasurement, measurement, measurementPhysicalValue } from './measurement';
7
7
  import { ExternalUnitTextError, parseExternalUnitText } from './externalUnits';
8
8
  import { fieldRegistry } from '../typechecker/declarationRegistry';
9
9
  function defaultsEnvironment(environment, registry) {
@@ -398,7 +398,12 @@ function convertMeasurement(value, unitText, expectedVector, unitPath, context,
398
398
  report(measurementDiagnostic('AMX4005', 'Measurement unit has an incompatible dimension', unitPath, context, declarationSource, fieldSource, formatVector(expectedVector, registry), formatVector(unit.vector, registry)));
399
399
  return null;
400
400
  }
401
- return measurement(value, unit);
401
+ const result = measurement(value, unit);
402
+ if (!Number.isFinite(measurementPhysicalValue(result))) {
403
+ report(measurementDiagnostic('AMX4005', 'Measurement physical value must be finite', unitPath, context, declarationSource, fieldSource, 'finite physical value', String(measurementPhysicalValue(result))));
404
+ return null;
405
+ }
406
+ return result;
402
407
  }
403
408
  function measurementDiagnostic(code, message, dataPath, context, declarationSource, fieldSource, expected, actual) {
404
409
  return inputError(code, message, {
@@ -20,11 +20,27 @@ export function unitFromMetadata(unit) {
20
20
  const factors = [{ identity: unit.identity, name: unit.name, exponent: 1 }];
21
21
  return Object.freeze({
22
22
  scale: unit.scale,
23
+ offset: unit.offset,
23
24
  vector: vectorRecord(unit.vector),
24
25
  factors: Object.freeze(factors),
25
26
  text: unit.name
26
27
  });
27
28
  }
29
+ export function physicalValue(value, unit) {
30
+ return value * unit.scale + unit.offset;
31
+ }
32
+ export function displayValue(physical, unit) {
33
+ return (physical - unit.offset) / unit.scale;
34
+ }
35
+ export function measurementPhysicalValue(value) {
36
+ return physicalValue(value.value, value.unit);
37
+ }
38
+ export function measurementDisplayValue(physical, unit) {
39
+ return displayValue(physical, unit);
40
+ }
41
+ export function isAffineUnit(unit) {
42
+ return unit.offset !== 0;
43
+ }
28
44
  function combineFactors(left, right, multiplier) {
29
45
  const factors = new Map();
30
46
  for (const factor of left.factors)
@@ -51,20 +67,28 @@ function combineVectorRecords(left, right, multiplier) {
51
67
  return vector;
52
68
  }
53
69
  export function composeUnits(left, right, divide = false) {
70
+ if (isAffineUnit(left) || isAffineUnit(right)) {
71
+ throw new Error('Affine measurement units cannot be composed');
72
+ }
54
73
  const multiplier = divide ? -1 : 1;
55
74
  const factors = combineFactors(left, right, multiplier);
56
75
  return Object.freeze({
57
76
  scale: divide ? left.scale / right.scale : left.scale * right.scale,
77
+ offset: 0,
58
78
  vector: Object.freeze(combineVectorRecords(left, right, multiplier)),
59
79
  factors: Object.freeze(factors),
60
80
  text: formatFactors(factors)
61
81
  });
62
82
  }
63
83
  export function powerUnit(unit, exponent) {
84
+ if (isAffineUnit(unit)) {
85
+ throw new Error('Affine measurement units may not be powered');
86
+ }
64
87
  const factors = unit.factors.map(factor => ({ ...factor, exponent: factor.exponent * exponent }))
65
88
  .filter(factor => factor.exponent !== 0);
66
89
  return Object.freeze({
67
90
  scale: Math.pow(unit.scale, exponent),
91
+ offset: unit.offset,
68
92
  vector: Object.freeze(Object.fromEntries(Object.entries(unit.vector)
69
93
  .map(([identity, power]) => [identity, power * exponent]).filter(([, power]) => power !== 0))),
70
94
  factors: Object.freeze(factors),
@@ -84,19 +108,22 @@ export function canonicalUnit(vector, registry) {
84
108
  }
85
109
  return Object.freeze({
86
110
  scale: 1,
111
+ offset: 0,
87
112
  vector: vectorRecord(vector),
88
113
  factors: Object.freeze(factors),
89
114
  text: formatFactors(factors)
90
115
  });
91
116
  }
92
117
  export function sqrtMeasurement(value, registry) {
118
+ if (isAffineUnit(value.unit))
119
+ throw new Error('Affine measurement sqrt is not supported');
93
120
  const vector = new Map();
94
121
  for (const [identity, exponent] of Object.entries(value.unit.vector)) {
95
122
  if (exponent % 2 !== 0)
96
123
  throw new Error('sqrt requires integral measurement dimension exponents');
97
124
  vector.set(identity, exponent / 2);
98
125
  }
99
- const physical = value.value * value.unit.scale;
126
+ const physical = measurementPhysicalValue(value);
100
127
  const physicalRoot = Math.sqrt(physical);
101
128
  if (!Number.isFinite(physicalRoot))
102
129
  return measurement(physicalRoot, canonicalUnit(vector, registry));
@@ -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) {
@@ -1,6 +1,6 @@
1
1
  import * as path from 'path';
2
2
  import { outputError } from '../diagnostics/errors';
3
- import { isMeasurement } from './measurement';
3
+ import { isMeasurement, measurementPhysicalValue } from './measurement';
4
4
  import { fieldRegistry } from '../typechecker/declarationRegistry';
5
5
  function typeName(type) {
6
6
  if (type.kind === 'named')
@@ -149,8 +149,9 @@ function jsonValue(value, type, output, recordTypes, registry) {
149
149
  return value.map(item => jsonValue(item, type.element, output, recordTypes, registry));
150
150
  }
151
151
  if (type.kind === 'measurement') {
152
- if (!isMeasurement(value) || !Number.isFinite(value.value))
152
+ if (!isMeasurement(value) || !Number.isFinite(value.value) || !Number.isFinite(measurementPhysicalValue(value))) {
153
153
  return invalidValue(output, 'expected a finite measurement value');
154
+ }
154
155
  if (!sameVector(value.unit.vector, type.vector))
155
156
  return invalidValue(output, 'measurement has an incompatible dimension');
156
157
  return { value: value.value, unit: value.unit.text };
@@ -198,8 +199,9 @@ function csvCell(value, type, output, registry) {
198
199
  return csvCell(value, type.element, output, registry);
199
200
  }
200
201
  if (type.kind === 'measurement') {
201
- if (!isMeasurement(value) || !Number.isFinite(value.value))
202
+ if (!isMeasurement(value) || !Number.isFinite(value.value) || !Number.isFinite(measurementPhysicalValue(value))) {
202
203
  return invalidValue(output, 'expected a finite measurement value');
204
+ }
203
205
  if (!sameVector(value.unit.vector, type.vector) || !value.unit.text)
204
206
  return invalidValue(output, 'measurement has an incompatible dimension or missing unit text');
205
207
  text = `${JSON.stringify(value.value)} ${value.unit.text}`;