@nova-energy/openamx 0.0.0-stage → 0.11.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/COMMERCIAL-LICENSE.md +74 -0
- package/LICENSE.md +660 -0
- package/README.md +537 -3
- package/dist/ast/types.js +2 -0
- package/dist/cli.js +197 -0
- package/dist/diagnostics/errors.js +94 -0
- package/dist/editor/completion.js +313 -0
- package/dist/editor/highlighting.js +224 -0
- package/dist/editor/moduleAnalysis.js +206 -0
- package/dist/editor/refactoring.js +46 -0
- package/dist/editor/sourceRanges.js +50 -0
- package/dist/editor/symbols.js +203 -0
- package/dist/formatter/formatAmx.js +79 -0
- package/dist/index.js +10 -0
- package/dist/parser/parseDocument.js +114 -0
- package/dist/parser/parseExpression.js +768 -0
- package/dist/parser/parseFor.js +53 -0
- package/dist/parser/parseFrontMatter.js +65 -0
- package/dist/parser/parseStatements.js +667 -0
- package/dist/parser/stringScanner.js +71 -0
- package/dist/renderer/chartModel.js +476 -0
- package/dist/renderer/narrativeModel.js +561 -0
- package/dist/renderer/renderHtml.js +521 -0
- package/dist/renderer/reportDocx.js +725 -0
- package/dist/renderer/reportPaths.js +31 -0
- package/dist/renderer/reportPdf.js +314 -0
- package/dist/renderer/reportPreparation.js +196 -0
- package/dist/runtime/csvTextSerialization.js +8 -0
- package/dist/runtime/dataText.js +191 -0
- package/dist/runtime/docxDestination.js +55 -0
- package/dist/runtime/environment.js +105 -0
- package/dist/runtime/evaluateDocument.js +32 -0
- package/dist/runtime/evaluateExpression.js +888 -0
- package/dist/runtime/externalUnits.js +91 -0
- package/dist/runtime/inputData.js +508 -0
- package/dist/runtime/measurement.js +110 -0
- package/dist/runtime/moduleLoader.js +279 -0
- package/dist/runtime/outputData.js +303 -0
- package/dist/runtime/pdfDestination.js +57 -0
- package/dist/runtime/standardLibrary.js +145 -0
- package/dist/typechecker/checkDocument.js +1282 -0
- package/dist/typechecker/declarationRegistry.js +7 -0
- package/dist/typechecker/dimensionTypes.js +1 -0
- package/package.json +33 -4
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { parse as parseCsv } from 'csv-parse/sync';
|
|
2
|
+
class StrictJsonParser {
|
|
3
|
+
text;
|
|
4
|
+
offset = 0;
|
|
5
|
+
constructor(text) {
|
|
6
|
+
this.text = text;
|
|
7
|
+
}
|
|
8
|
+
parse() {
|
|
9
|
+
this.skipWhitespace();
|
|
10
|
+
const value = this.parseValue('');
|
|
11
|
+
this.skipWhitespace();
|
|
12
|
+
if (this.offset !== this.text.length)
|
|
13
|
+
this.fail('Unexpected content after JSON value');
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
parseValue(dataPath) {
|
|
17
|
+
this.skipWhitespace();
|
|
18
|
+
const character = this.text[this.offset];
|
|
19
|
+
if (character === '{')
|
|
20
|
+
return this.parseObject(dataPath);
|
|
21
|
+
if (character === '[')
|
|
22
|
+
return this.parseArray(dataPath);
|
|
23
|
+
if (character === '"')
|
|
24
|
+
return this.parseString();
|
|
25
|
+
if (character === 't')
|
|
26
|
+
return this.parseLiteral('true', true);
|
|
27
|
+
if (character === 'f')
|
|
28
|
+
return this.parseLiteral('false', false);
|
|
29
|
+
if (character === 'n')
|
|
30
|
+
return this.parseLiteral('null', null);
|
|
31
|
+
if (character === '-' || (character >= '0' && character <= '9'))
|
|
32
|
+
return this.parseNumber();
|
|
33
|
+
this.fail('Expected a JSON value', dataPath);
|
|
34
|
+
}
|
|
35
|
+
parseObject(dataPath) {
|
|
36
|
+
this.offset++;
|
|
37
|
+
this.skipWhitespace();
|
|
38
|
+
const result = {};
|
|
39
|
+
const keys = new Set();
|
|
40
|
+
if (this.consume('}'))
|
|
41
|
+
return result;
|
|
42
|
+
while (true) {
|
|
43
|
+
this.skipWhitespace();
|
|
44
|
+
if (this.text[this.offset] !== '"')
|
|
45
|
+
this.fail('Expected a quoted object key', dataPath);
|
|
46
|
+
const keyOffset = this.offset;
|
|
47
|
+
const key = this.parseString();
|
|
48
|
+
const propertyPath = `${dataPath}/${key.replace(/~/g, '~0').replace(/\//g, '~1')}`;
|
|
49
|
+
if (keys.has(key))
|
|
50
|
+
throw { message: `Duplicate JSON object key '${key}'`, offset: keyOffset, duplicate: true, dataPath: propertyPath };
|
|
51
|
+
keys.add(key);
|
|
52
|
+
this.skipWhitespace();
|
|
53
|
+
if (!this.consume(':'))
|
|
54
|
+
this.fail("Expected ':' after object key", propertyPath);
|
|
55
|
+
Object.defineProperty(result, key, {
|
|
56
|
+
value: this.parseValue(propertyPath), enumerable: true, configurable: true, writable: true
|
|
57
|
+
});
|
|
58
|
+
this.skipWhitespace();
|
|
59
|
+
if (this.consume('}'))
|
|
60
|
+
return result;
|
|
61
|
+
if (!this.consume(','))
|
|
62
|
+
this.fail("Expected ',' or '}' in object", dataPath);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
parseArray(dataPath) {
|
|
66
|
+
this.offset++;
|
|
67
|
+
this.skipWhitespace();
|
|
68
|
+
const result = [];
|
|
69
|
+
if (this.consume(']'))
|
|
70
|
+
return result;
|
|
71
|
+
while (true) {
|
|
72
|
+
result.push(this.parseValue(`${dataPath}/${result.length}`));
|
|
73
|
+
this.skipWhitespace();
|
|
74
|
+
if (this.consume(']'))
|
|
75
|
+
return result;
|
|
76
|
+
if (!this.consume(','))
|
|
77
|
+
this.fail("Expected ',' or ']' in array", dataPath);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
parseString() {
|
|
81
|
+
const start = this.offset++;
|
|
82
|
+
while (this.offset < this.text.length) {
|
|
83
|
+
const code = this.text.charCodeAt(this.offset++);
|
|
84
|
+
if (code === 0x22) {
|
|
85
|
+
try {
|
|
86
|
+
return JSON.parse(this.text.slice(start, this.offset));
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
this.fail('Invalid JSON string');
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (code < 0x20)
|
|
93
|
+
this.fail('Unescaped control character in JSON string');
|
|
94
|
+
if (code === 0x5c) {
|
|
95
|
+
const escape = this.text[this.offset++];
|
|
96
|
+
if (escape === 'u') {
|
|
97
|
+
const hex = this.text.slice(this.offset, this.offset + 4);
|
|
98
|
+
if (!/^[0-9A-Fa-f]{4}$/.test(hex))
|
|
99
|
+
this.fail('Invalid Unicode escape');
|
|
100
|
+
this.offset += 4;
|
|
101
|
+
}
|
|
102
|
+
else if (!['"', '\\', '/', 'b', 'f', 'n', 'r', 't'].includes(escape)) {
|
|
103
|
+
this.fail('Invalid JSON escape');
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
this.fail('Unterminated JSON string');
|
|
108
|
+
}
|
|
109
|
+
parseNumber() {
|
|
110
|
+
const match = this.text.slice(this.offset).match(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/);
|
|
111
|
+
if (!match)
|
|
112
|
+
this.fail('Invalid JSON number');
|
|
113
|
+
this.offset += match[0].length;
|
|
114
|
+
return Number(match[0]);
|
|
115
|
+
}
|
|
116
|
+
parseLiteral(literal, value) {
|
|
117
|
+
if (!this.text.startsWith(literal, this.offset))
|
|
118
|
+
this.fail(`Invalid JSON token '${this.text[this.offset] ?? ''}'`);
|
|
119
|
+
this.offset += literal.length;
|
|
120
|
+
return value;
|
|
121
|
+
}
|
|
122
|
+
skipWhitespace() {
|
|
123
|
+
while (/[\t\n\r ]/.test(this.text[this.offset] ?? '\0'))
|
|
124
|
+
this.offset++;
|
|
125
|
+
}
|
|
126
|
+
consume(character) {
|
|
127
|
+
if (this.text[this.offset] !== character)
|
|
128
|
+
return false;
|
|
129
|
+
this.offset++;
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
fail(message, dataPath) {
|
|
133
|
+
throw { message, offset: this.offset, dataPath };
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function safeText(value) {
|
|
137
|
+
return value.replace(/[\x00-\x1f\x7f]/g, character => `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`).slice(0, 160);
|
|
138
|
+
}
|
|
139
|
+
function lineAt(text, offset) {
|
|
140
|
+
return text.slice(0, offset).split('\n').length;
|
|
141
|
+
}
|
|
142
|
+
function hasBareCarriageReturn(text) {
|
|
143
|
+
let quoted = false;
|
|
144
|
+
for (let index = 0; index < text.length; index++) {
|
|
145
|
+
if (text[index] === '"') {
|
|
146
|
+
if (quoted && text[index + 1] === '"')
|
|
147
|
+
index++;
|
|
148
|
+
else
|
|
149
|
+
quoted = !quoted;
|
|
150
|
+
}
|
|
151
|
+
else if (text[index] === '\r' && !quoted && text[index + 1] !== '\n') {
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
export function parseStrictJsonText(text) {
|
|
158
|
+
try {
|
|
159
|
+
return { value: new StrictJsonParser(text).parse() };
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
const issue = error;
|
|
163
|
+
return { issue: {
|
|
164
|
+
message: typeof issue.message === 'string' ? issue.message : 'Malformed JSON',
|
|
165
|
+
offset: Number.isSafeInteger(issue.offset) ? issue.offset : 0,
|
|
166
|
+
duplicate: issue.duplicate,
|
|
167
|
+
dataPath: issue.dataPath
|
|
168
|
+
} };
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
export function parseStrictCsvText(text) {
|
|
172
|
+
if (hasBareCarriageReturn(text)) {
|
|
173
|
+
const offset = text.indexOf('\r');
|
|
174
|
+
return { issue: { message: 'Bare CR record separators are not valid CSV', offset, line: lineAt(text, offset) } };
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
const rows = parseCsv(text, {
|
|
178
|
+
bom: true,
|
|
179
|
+
columns: false,
|
|
180
|
+
skip_empty_lines: false,
|
|
181
|
+
relax_column_count: true,
|
|
182
|
+
record_delimiter: ['\r\n', '\n'],
|
|
183
|
+
cast: (value, field) => ({ value, quoted: field.quoting })
|
|
184
|
+
});
|
|
185
|
+
return { value: rows };
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
const csvError = error;
|
|
189
|
+
return { issue: { message: `Malformed CSV: ${safeText(csvError.message ?? 'parse error')}`, line: csvError.lines } };
|
|
190
|
+
}
|
|
191
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { lstat, open, realpath, rename, unlink } from 'node:fs/promises';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { outputError } from '../diagnostics/errors';
|
|
4
|
+
export async function prepareDocxDestination(destination, entryPath, inputMappings) {
|
|
5
|
+
if (!destination)
|
|
6
|
+
outputError('AMX6001', 'DOCX export requires --out <path>');
|
|
7
|
+
if (path.extname(destination) !== '.docx')
|
|
8
|
+
outputError('AMX6001', 'DOCX destination must use the exact lowercase .docx extension');
|
|
9
|
+
const absolute = path.resolve(destination);
|
|
10
|
+
const parent = path.dirname(absolute);
|
|
11
|
+
let canonicalParent;
|
|
12
|
+
try {
|
|
13
|
+
canonicalParent = await realpath(parent);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
outputError('AMX6001', `DOCX destination parent '${parent}' does not exist`);
|
|
17
|
+
}
|
|
18
|
+
const canonicalDestination = path.join(canonicalParent, path.basename(absolute));
|
|
19
|
+
const conflicts = [path.resolve(entryPath), ...(inputMappings ?? []).map(mapping => mapping.slice(mapping.indexOf('=') + 1))]
|
|
20
|
+
.map(candidate => path.resolve(candidate));
|
|
21
|
+
if (conflicts.includes(canonicalDestination))
|
|
22
|
+
outputError('AMX6001', `DOCX destination '${canonicalDestination}' conflicts with an input or entry module`);
|
|
23
|
+
try {
|
|
24
|
+
const existing = await lstat(canonicalDestination);
|
|
25
|
+
if (existing.isSymbolicLink())
|
|
26
|
+
outputError('AMX6001', `DOCX destination '${canonicalDestination}' must not be a symlink`);
|
|
27
|
+
if (!existing.isFile())
|
|
28
|
+
outputError('AMX6001', `DOCX destination '${canonicalDestination}' is not a regular file`);
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
if (error.code !== 'ENOENT')
|
|
32
|
+
outputError('AMX6001', `Cannot inspect DOCX destination '${canonicalDestination}'`);
|
|
33
|
+
}
|
|
34
|
+
return { path: canonicalDestination, parent: canonicalParent };
|
|
35
|
+
}
|
|
36
|
+
export async function writeDocxAtomically(destination, bytes, beforeCommit) {
|
|
37
|
+
const temporary = path.join(destination.parent, `.${path.basename(destination.path)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);
|
|
38
|
+
let handle;
|
|
39
|
+
try {
|
|
40
|
+
handle = await open(temporary, 'wx');
|
|
41
|
+
await handle.write(bytes);
|
|
42
|
+
await handle.sync();
|
|
43
|
+
await handle.close();
|
|
44
|
+
handle = undefined;
|
|
45
|
+
beforeCommit?.();
|
|
46
|
+
await rename(temporary, destination.path);
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
if (handle)
|
|
50
|
+
await handle.close().catch(() => undefined);
|
|
51
|
+
await unlink(temporary).catch(() => undefined);
|
|
52
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
53
|
+
outputError('AMX6002', `Failed to write DOCX '${destination.path}': ${detail}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { throwUndefinedIdentifier } from '../diagnostics/errors';
|
|
2
|
+
/**
|
|
3
|
+
* Runtime environment for variable storage during evaluation.
|
|
4
|
+
* Variables are stored in declaration order (source order).
|
|
5
|
+
* get() throws AMX1004 for undefined identifiers.
|
|
6
|
+
*/
|
|
7
|
+
export class Environment {
|
|
8
|
+
store = new Map();
|
|
9
|
+
recordTypes;
|
|
10
|
+
functions;
|
|
11
|
+
bindingTypes = new Map();
|
|
12
|
+
dimensionRegistry;
|
|
13
|
+
viewDefinitions = new Map();
|
|
14
|
+
viewEmissions = [];
|
|
15
|
+
immutableValues = new WeakSet();
|
|
16
|
+
currentDocumentNodeIndex = -1;
|
|
17
|
+
currentStatementIndex = -1;
|
|
18
|
+
validationMode = 'aggregate';
|
|
19
|
+
constructor(recordTypes = new Map(), functions = new Map(), dimensionRegistry) {
|
|
20
|
+
this.recordTypes = recordTypes;
|
|
21
|
+
this.functions = functions;
|
|
22
|
+
this.dimensionRegistry = dimensionRegistry;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Create an isolated call frame sharing this module's record types and functions
|
|
26
|
+
* but containing only the supplied parameter bindings. Used to evaluate pure
|
|
27
|
+
* function bodies without exposing document/module state.
|
|
28
|
+
*/
|
|
29
|
+
createCallFrame(parameters) {
|
|
30
|
+
const frame = new Environment(this.recordTypes, this.functions, this.dimensionRegistry);
|
|
31
|
+
frame.validationMode = this.validationMode;
|
|
32
|
+
for (const [name, type] of this.bindingTypes)
|
|
33
|
+
frame.bindingTypes.set(name, type);
|
|
34
|
+
for (const [name, value] of Object.entries(parameters)) {
|
|
35
|
+
frame.set(name, value);
|
|
36
|
+
if (this.isImmutable(value))
|
|
37
|
+
frame.markImmutable(value);
|
|
38
|
+
}
|
|
39
|
+
return frame;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Set or overwrite a variable value.
|
|
43
|
+
*/
|
|
44
|
+
set(name, value) {
|
|
45
|
+
this.store.set(name, value);
|
|
46
|
+
}
|
|
47
|
+
markImmutable(value) {
|
|
48
|
+
const visit = (item) => {
|
|
49
|
+
if (!item || typeof item !== 'object' || this.immutableValues.has(item))
|
|
50
|
+
return;
|
|
51
|
+
this.immutableValues.add(item);
|
|
52
|
+
if (Array.isArray(item))
|
|
53
|
+
item.forEach(visit);
|
|
54
|
+
else
|
|
55
|
+
Object.values(item).forEach(visit);
|
|
56
|
+
};
|
|
57
|
+
visit(value);
|
|
58
|
+
}
|
|
59
|
+
isImmutable(value) {
|
|
60
|
+
return !!value && typeof value === 'object' && this.immutableValues.has(value);
|
|
61
|
+
}
|
|
62
|
+
update(name, value, source, file) {
|
|
63
|
+
if (!this.store.has(name)) {
|
|
64
|
+
throwUndefinedIdentifier(name, source, file);
|
|
65
|
+
}
|
|
66
|
+
this.store.set(name, value);
|
|
67
|
+
}
|
|
68
|
+
delete(name) {
|
|
69
|
+
this.store.delete(name);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Get a variable value. Throws AMX1004 if not defined.
|
|
73
|
+
*/
|
|
74
|
+
get(name, source, file) {
|
|
75
|
+
if (!this.store.has(name)) {
|
|
76
|
+
throwUndefinedIdentifier(name, source, file);
|
|
77
|
+
}
|
|
78
|
+
return this.store.get(name);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Check existence (used internally by evaluator for forward-ref detection).
|
|
82
|
+
*/
|
|
83
|
+
has(name) {
|
|
84
|
+
return this.store.has(name);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Return a plain object snapshot of current bindings (for evaluateDocument result).
|
|
88
|
+
*/
|
|
89
|
+
toObject() {
|
|
90
|
+
const obj = {};
|
|
91
|
+
for (const [k, v] of this.store.entries()) {
|
|
92
|
+
obj[k] = v;
|
|
93
|
+
}
|
|
94
|
+
return obj;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Clear all bindings (useful for tests).
|
|
98
|
+
*/
|
|
99
|
+
clear() {
|
|
100
|
+
this.store.clear();
|
|
101
|
+
this.immutableValues = new WeakSet();
|
|
102
|
+
this.viewDefinitions.clear();
|
|
103
|
+
this.viewEmissions.length = 0;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Environment } from './environment';
|
|
2
|
+
import { evaluateStatements } from './evaluateExpression';
|
|
3
|
+
import { checkDocument } from '../typechecker/checkDocument';
|
|
4
|
+
/**
|
|
5
|
+
* Evaluate an OpenAmxDocument in source order.
|
|
6
|
+
* - Only executable code-block statements are processed.
|
|
7
|
+
* - All blocks share one environment and execute in document order.
|
|
8
|
+
* - Narrative nodes and legacy top-level declarations are ignored.
|
|
9
|
+
* Returns a plain object map of final variable bindings.
|
|
10
|
+
*/
|
|
11
|
+
export function evaluateDocument(doc, file) {
|
|
12
|
+
return evaluateDocumentEnvironment(doc, file).toObject();
|
|
13
|
+
}
|
|
14
|
+
/** Evaluate executable blocks once and return their shared final environment. */
|
|
15
|
+
export function evaluateDocumentEnvironment(doc, file) {
|
|
16
|
+
const checked = checkDocument(doc, file);
|
|
17
|
+
const env = new Environment(new Map(), new Map(), {
|
|
18
|
+
dimensions: checked.dimensions,
|
|
19
|
+
units: checked.units,
|
|
20
|
+
baseUnits: checked.baseUnits
|
|
21
|
+
});
|
|
22
|
+
for (const [name, type] of checked.bindingTypes)
|
|
23
|
+
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
|
+
}
|
|
31
|
+
return env;
|
|
32
|
+
}
|