@nova-energy/openamx 0.0.0-stage → 0.10.1
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 +513 -2
- package/dist/ast/types.js +2 -0
- package/dist/cli.js +186 -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/renderHtml.js +383 -0
- package/dist/renderer/reportDocx.js +163 -0
- package/dist/renderer/reportPdf.js +202 -0
- package/dist/renderer/reportPreparation.js +208 -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,303 @@
|
|
|
1
|
+
import * as path from 'path';
|
|
2
|
+
import { outputError } from '../diagnostics/errors';
|
|
3
|
+
import { isMeasurement } from './measurement';
|
|
4
|
+
import { fieldRegistry } from '../typechecker/declarationRegistry';
|
|
5
|
+
function typeName(type) {
|
|
6
|
+
if (type.kind === 'named')
|
|
7
|
+
return type.name;
|
|
8
|
+
if (type.kind === 'measurement')
|
|
9
|
+
return 'measurement';
|
|
10
|
+
if (type.kind === 'null')
|
|
11
|
+
return 'null';
|
|
12
|
+
return type.kind === 'list' ? `${typeName(type.element)}[]` : `${typeName(type.element)}?`;
|
|
13
|
+
}
|
|
14
|
+
function isPrimitive(type) {
|
|
15
|
+
return type.kind === 'named' && ['Number', 'String', 'Boolean', 'DateTime'].includes(type.name);
|
|
16
|
+
}
|
|
17
|
+
function isCsvScalar(type) {
|
|
18
|
+
return type.kind === 'measurement' || isPrimitive(type) || (type.kind === 'nullable' && isCsvScalar(type.element));
|
|
19
|
+
}
|
|
20
|
+
function supportsJson(type, recordTypes, registry, visiting = new Set()) {
|
|
21
|
+
if (type.kind === 'nullable' || type.kind === 'list')
|
|
22
|
+
return supportsJson(type.element, recordTypes, registry, visiting);
|
|
23
|
+
if (type.kind === 'measurement')
|
|
24
|
+
return true;
|
|
25
|
+
if (type.kind !== 'named')
|
|
26
|
+
return false;
|
|
27
|
+
if (isPrimitive(type))
|
|
28
|
+
return true;
|
|
29
|
+
const declaration = recordTypes.get(type.name);
|
|
30
|
+
if (!declaration || visiting.has(type.name))
|
|
31
|
+
return false;
|
|
32
|
+
const next = new Set(visiting).add(type.name);
|
|
33
|
+
return declaration.fields.every(field => supportsJson(checkedType(field.annotation, fieldRegistry(declaration, registry)), recordTypes, fieldRegistry(declaration, registry), next));
|
|
34
|
+
}
|
|
35
|
+
function supportsCsv(type, recordTypes, registry) {
|
|
36
|
+
if (type.kind !== 'list' || type.element.kind !== 'named')
|
|
37
|
+
return false;
|
|
38
|
+
const declaration = recordTypes.get(type.element.name);
|
|
39
|
+
return !!declaration && declaration.fields.every(field => isCsvScalar(checkedType(field.annotation, fieldRegistry(declaration, registry))));
|
|
40
|
+
}
|
|
41
|
+
export function describeOutputSchemas(exportedBindings, recordTypes, registry) {
|
|
42
|
+
return [...exportedBindings].flatMap(([name, type]) => {
|
|
43
|
+
const formats = [];
|
|
44
|
+
if (supportsJson(type, recordTypes, registry))
|
|
45
|
+
formats.push('json');
|
|
46
|
+
if (supportsCsv(type, recordTypes, registry))
|
|
47
|
+
formats.push('csv');
|
|
48
|
+
const measurements = registry ? measurementExpectations(type, recordTypes, registry) ?? [] : [];
|
|
49
|
+
return formats.length ? [{ name, type: typeName(type), formats, ...(measurements.length ? { measurements } : {}) }] : [];
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
function assertJsonShape(type, recordTypes, outputName, registry) {
|
|
53
|
+
if (type.kind === 'nullable' || type.kind === 'list') {
|
|
54
|
+
assertJsonShape(type.element, recordTypes, outputName, registry);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (type.kind === 'measurement')
|
|
58
|
+
return;
|
|
59
|
+
if (type.kind !== 'named')
|
|
60
|
+
outputError('AMX6001', `Output '${outputName}' has no declared serializable type`);
|
|
61
|
+
if (isPrimitive(type))
|
|
62
|
+
return;
|
|
63
|
+
const declaration = recordTypes.get(type.name);
|
|
64
|
+
if (!declaration)
|
|
65
|
+
outputError('AMX6001', `Output '${outputName}' uses unknown record type '${type.name}'`);
|
|
66
|
+
const recordRegistry = fieldRegistry(declaration, registry);
|
|
67
|
+
for (const field of declaration.fields)
|
|
68
|
+
assertJsonShape(checkedType(field.annotation, recordRegistry), recordTypes, outputName, recordRegistry);
|
|
69
|
+
}
|
|
70
|
+
function checkedType(reference, registry) {
|
|
71
|
+
if (reference.type === 'namedType') {
|
|
72
|
+
const dimension = registry?.dimensions.get(reference.name);
|
|
73
|
+
return dimension ? { kind: 'measurement', vector: dimension.vector } : { kind: 'named', name: reference.name };
|
|
74
|
+
}
|
|
75
|
+
const element = checkedType(reference.element, registry);
|
|
76
|
+
return reference.type === 'listType' ? { kind: 'list', element } : { kind: 'nullable', element };
|
|
77
|
+
}
|
|
78
|
+
function assertCsvShape(type, recordTypes, outputName, registry) {
|
|
79
|
+
if (type.kind !== 'list' || type.element.kind !== 'named') {
|
|
80
|
+
outputError('AMX6001', `CSV output '${outputName}' must be a list of one declared record type`);
|
|
81
|
+
}
|
|
82
|
+
const declaration = recordTypes.get(type.element.name);
|
|
83
|
+
if (!declaration)
|
|
84
|
+
outputError('AMX6001', `CSV output '${outputName}' uses unknown record type '${type.element.name}'`);
|
|
85
|
+
const recordRegistry = fieldRegistry(declaration, registry);
|
|
86
|
+
const unsupported = declaration.fields.find(field => !isCsvScalar(checkedType(field.annotation, recordRegistry)));
|
|
87
|
+
if (unsupported) {
|
|
88
|
+
outputError('AMX6001', `CSV output '${outputName}' field '${unsupported.name}' must be a scalar or nullable scalar, not ${typeName(checkedType(unsupported.annotation, recordRegistry))}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
export function prepareOutputs(mappings, exportedBindings, recordTypes, reservedDestination, registry) {
|
|
92
|
+
const outputs = [];
|
|
93
|
+
const names = new Set();
|
|
94
|
+
const destinations = new Set();
|
|
95
|
+
const reserved = reservedDestination ? path.resolve(reservedDestination) : undefined;
|
|
96
|
+
for (const mapping of mappings ?? []) {
|
|
97
|
+
const separator = mapping.indexOf('=');
|
|
98
|
+
if (separator < 0)
|
|
99
|
+
outputError('AMX6001', `Invalid --output mapping '${mapping}'; expected name=path`);
|
|
100
|
+
const name = mapping.slice(0, separator);
|
|
101
|
+
const destination = mapping.slice(separator + 1);
|
|
102
|
+
if (!name || !destination)
|
|
103
|
+
outputError('AMX6001', `Invalid --output mapping '${mapping}'; name and path must be non-empty`);
|
|
104
|
+
if (names.has(name))
|
|
105
|
+
outputError('AMX6001', `Duplicate output name '${name}'`);
|
|
106
|
+
names.add(name);
|
|
107
|
+
const type = exportedBindings.get(name);
|
|
108
|
+
if (!type)
|
|
109
|
+
outputError('AMX6001', `Output '${name}' is not an explicitly exported entry-module let value`);
|
|
110
|
+
const absolutePath = path.resolve(destination);
|
|
111
|
+
if (destinations.has(absolutePath))
|
|
112
|
+
outputError('AMX6001', `Duplicate output destination '${absolutePath}'`);
|
|
113
|
+
if (absolutePath === reserved)
|
|
114
|
+
outputError('AMX6001', `Output '${name}' conflicts with the render HTML destination '${absolutePath}'`);
|
|
115
|
+
destinations.add(absolutePath);
|
|
116
|
+
const extension = path.extname(destination);
|
|
117
|
+
if (extension !== '.json' && extension !== '.csv') {
|
|
118
|
+
outputError('AMX6001', `Output '${name}' must use the exact lowercase .json or .csv extension`);
|
|
119
|
+
}
|
|
120
|
+
const format = extension.slice(1);
|
|
121
|
+
if (format === 'json')
|
|
122
|
+
assertJsonShape(type, recordTypes, name, registry);
|
|
123
|
+
else
|
|
124
|
+
assertCsvShape(type, recordTypes, name, registry);
|
|
125
|
+
outputs.push({ name, path: absolutePath, format, type });
|
|
126
|
+
}
|
|
127
|
+
return outputs;
|
|
128
|
+
}
|
|
129
|
+
function invalidValue(output, detail) {
|
|
130
|
+
outputError('AMX6002', `Cannot serialize output '${output.name}': ${detail}`);
|
|
131
|
+
}
|
|
132
|
+
function jsonValue(value, type, output, recordTypes, registry) {
|
|
133
|
+
if (type.kind === 'nullable') {
|
|
134
|
+
if (value === null)
|
|
135
|
+
return null;
|
|
136
|
+
return jsonValue(value, type.element, output, recordTypes, registry);
|
|
137
|
+
}
|
|
138
|
+
if (type.kind === 'null') {
|
|
139
|
+
if (value === null)
|
|
140
|
+
return null;
|
|
141
|
+
return invalidValue(output, 'expected null');
|
|
142
|
+
}
|
|
143
|
+
if (type.kind === 'list') {
|
|
144
|
+
if (!Array.isArray(value))
|
|
145
|
+
return invalidValue(output, `expected ${typeName(type)}`);
|
|
146
|
+
return value.map(item => jsonValue(item, type.element, output, recordTypes, registry));
|
|
147
|
+
}
|
|
148
|
+
if (type.kind === 'measurement') {
|
|
149
|
+
if (!isMeasurement(value) || !Number.isFinite(value.value))
|
|
150
|
+
return invalidValue(output, 'expected a finite measurement value');
|
|
151
|
+
if (!sameVector(value.unit.vector, type.vector))
|
|
152
|
+
return invalidValue(output, 'measurement has an incompatible dimension');
|
|
153
|
+
return { value: value.value, unit: value.unit.text };
|
|
154
|
+
}
|
|
155
|
+
if (type.kind !== 'named')
|
|
156
|
+
return invalidValue(output, `unsupported type ${typeName(type)}`);
|
|
157
|
+
if (type.name === 'Number') {
|
|
158
|
+
if (typeof value !== 'number' || !Number.isFinite(value))
|
|
159
|
+
return invalidValue(output, `expected a finite Number, got ${String(value)}`);
|
|
160
|
+
return value;
|
|
161
|
+
}
|
|
162
|
+
if (type.name === 'String' || type.name === 'DateTime') {
|
|
163
|
+
if (typeof value !== 'string')
|
|
164
|
+
return invalidValue(output, `expected ${type.name}`);
|
|
165
|
+
return value;
|
|
166
|
+
}
|
|
167
|
+
if (type.name === 'Boolean') {
|
|
168
|
+
if (typeof value !== 'boolean')
|
|
169
|
+
return invalidValue(output, 'expected Boolean');
|
|
170
|
+
return value;
|
|
171
|
+
}
|
|
172
|
+
const declaration = recordTypes.get(type.name);
|
|
173
|
+
if (!declaration || typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
174
|
+
return invalidValue(output, `expected record ${type.name}`);
|
|
175
|
+
}
|
|
176
|
+
const record = value;
|
|
177
|
+
const knownFields = new Set(declaration.fields.map(field => field.name));
|
|
178
|
+
const extras = Object.keys(record).filter(key => !knownFields.has(key)).sort();
|
|
179
|
+
if (extras.length)
|
|
180
|
+
return invalidValue(output, `record ${type.name} has undeclared field '${extras[0]}'`);
|
|
181
|
+
const ordered = {};
|
|
182
|
+
for (const field of declaration.fields) {
|
|
183
|
+
if (!Object.prototype.hasOwnProperty.call(record, field.name))
|
|
184
|
+
return invalidValue(output, `record ${type.name} is missing field '${field.name}'`);
|
|
185
|
+
ordered[field.name] = jsonValue(record[field.name], checkedType(field.annotation, fieldRegistry(declaration, registry)), output, recordTypes, fieldRegistry(declaration, registry));
|
|
186
|
+
}
|
|
187
|
+
return ordered;
|
|
188
|
+
}
|
|
189
|
+
function csvCell(value, type, output, registry) {
|
|
190
|
+
let text;
|
|
191
|
+
if (type.kind === 'nullable') {
|
|
192
|
+
if (value === null)
|
|
193
|
+
return '';
|
|
194
|
+
return csvCell(value, type.element, output, registry);
|
|
195
|
+
}
|
|
196
|
+
if (type.kind === 'measurement') {
|
|
197
|
+
if (!isMeasurement(value) || !Number.isFinite(value.value))
|
|
198
|
+
return invalidValue(output, 'expected a finite measurement value');
|
|
199
|
+
if (!sameVector(value.unit.vector, type.vector) || !value.unit.text)
|
|
200
|
+
return invalidValue(output, 'measurement has an incompatible dimension or missing unit text');
|
|
201
|
+
text = `${JSON.stringify(value.value)} ${value.unit.text}`;
|
|
202
|
+
const quote = /[",\r\n]/.test(text) || /^\s|\s$/.test(text);
|
|
203
|
+
return quote ? `"${text.replace(/"/g, '""')}"` : text;
|
|
204
|
+
}
|
|
205
|
+
if (type.kind !== 'named')
|
|
206
|
+
return invalidValue(output, `unsupported CSV cell type ${typeName(type)}`);
|
|
207
|
+
if (type.name === 'Number') {
|
|
208
|
+
if (typeof value !== 'number' || !Number.isFinite(value))
|
|
209
|
+
return invalidValue(output, `expected a finite Number, got ${String(value)}`);
|
|
210
|
+
text = JSON.stringify(value);
|
|
211
|
+
}
|
|
212
|
+
else if (type.name === 'Boolean') {
|
|
213
|
+
if (typeof value !== 'boolean')
|
|
214
|
+
return invalidValue(output, 'expected Boolean');
|
|
215
|
+
text = value ? 'true' : 'false';
|
|
216
|
+
}
|
|
217
|
+
else if (type.name === 'String' || type.name === 'DateTime') {
|
|
218
|
+
if (typeof value !== 'string')
|
|
219
|
+
return invalidValue(output, `expected ${type.name}`);
|
|
220
|
+
text = value;
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
return invalidValue(output, `unsupported CSV cell type ${typeName(type)}`);
|
|
224
|
+
}
|
|
225
|
+
const quote = text === '' || /[",\r\n]/.test(text) || /^\s|\s$/.test(text);
|
|
226
|
+
return quote ? `"${text.replace(/"/g, '""')}"` : text;
|
|
227
|
+
}
|
|
228
|
+
function csvContents(value, type, output, recordTypes, registry) {
|
|
229
|
+
if (type.kind !== 'list' || type.element.kind !== 'named')
|
|
230
|
+
return invalidValue(output, 'expected a declared record list');
|
|
231
|
+
const declaration = recordTypes.get(type.element.name);
|
|
232
|
+
if (!declaration || !Array.isArray(value))
|
|
233
|
+
return invalidValue(output, `expected ${typeName(type)}`);
|
|
234
|
+
const fields = declaration.fields;
|
|
235
|
+
const rows = [fields.map(field => csvCell(field.name, { kind: 'named', name: 'String' }, output, registry)).join(',')];
|
|
236
|
+
const knownFields = new Set(fields.map(field => field.name));
|
|
237
|
+
for (const [index, item] of value.entries()) {
|
|
238
|
+
if (typeof item !== 'object' || item === null || Array.isArray(item))
|
|
239
|
+
return invalidValue(output, `record ${index} is not an object`);
|
|
240
|
+
const record = item;
|
|
241
|
+
const extras = Object.keys(record).filter(key => !knownFields.has(key)).sort();
|
|
242
|
+
if (extras.length)
|
|
243
|
+
return invalidValue(output, `record ${index} has undeclared field '${extras[0]}'`);
|
|
244
|
+
rows.push(fields.map(field => {
|
|
245
|
+
if (!Object.prototype.hasOwnProperty.call(record, field.name))
|
|
246
|
+
return invalidValue(output, `record ${index} is missing field '${field.name}'`);
|
|
247
|
+
return csvCell(record[field.name], checkedType(field.annotation, fieldRegistry(declaration, registry)), output, registry);
|
|
248
|
+
}).join(','));
|
|
249
|
+
}
|
|
250
|
+
return `${rows.join('\n')}\n`;
|
|
251
|
+
}
|
|
252
|
+
export function serializeOutputs(outputs, env) {
|
|
253
|
+
return outputs.map(output => {
|
|
254
|
+
const value = env.get(output.name);
|
|
255
|
+
const contents = output.format === 'json'
|
|
256
|
+
? `${JSON.stringify(jsonValue(value, output.type, output, env.recordTypes, env.dimensionRegistry), null, 2)}\n`
|
|
257
|
+
: csvContents(value, output.type, output, env.recordTypes, env.dimensionRegistry);
|
|
258
|
+
return { path: output.path, contents };
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
function measurementExpectations(type, recordTypes, registry, path = '$', seen = new Set()) {
|
|
262
|
+
if (type.kind === 'nullable' || type.kind === 'list')
|
|
263
|
+
return measurementExpectations(type.element, recordTypes, registry, path, seen);
|
|
264
|
+
if (type.kind === 'measurement') {
|
|
265
|
+
return [{
|
|
266
|
+
path,
|
|
267
|
+
dimension: formatDimensionVector(type.vector, registry),
|
|
268
|
+
visibleUnits: [...registry.units.values()].filter(unit => sameVector(unit.vector, type.vector)).map(unit => unit.name).sort()
|
|
269
|
+
}];
|
|
270
|
+
}
|
|
271
|
+
if (type.kind !== 'named' || isPrimitive(type) || seen.has(type.name))
|
|
272
|
+
return [];
|
|
273
|
+
const declaration = recordTypes.get(type.name);
|
|
274
|
+
if (!declaration)
|
|
275
|
+
return [];
|
|
276
|
+
const next = new Set(seen).add(type.name);
|
|
277
|
+
const recordRegistry = fieldRegistry(declaration, registry) ?? registry;
|
|
278
|
+
return declaration.fields.flatMap(field => measurementExpectations(checkedType(field.annotation, recordRegistry), recordTypes, recordRegistry, `${path}.${field.name}`, next) ?? []);
|
|
279
|
+
}
|
|
280
|
+
function formatDimensionVector(vector, registry) {
|
|
281
|
+
return [...vector].sort(([left], [right]) => left.localeCompare(right)).map(([identity, exponent]) => {
|
|
282
|
+
const base = [...registry.dimensions.values()].find(dimension => dimension.baseIdentity === identity);
|
|
283
|
+
if (!base)
|
|
284
|
+
throw new Error('Output schema references an unavailable base dimension');
|
|
285
|
+
return `${base.declarationName}${exponent === 1 ? '' : `^${exponent}`}`;
|
|
286
|
+
}).join(' * ') || 'dimensionless';
|
|
287
|
+
}
|
|
288
|
+
function sameVector(left, right) {
|
|
289
|
+
const entries = left instanceof Map ? [...left] : Object.entries(left);
|
|
290
|
+
const rightMap = new Map(right instanceof Map ? right : Object.entries(right));
|
|
291
|
+
return entries.length === rightMap.size && entries.every(([identity, exponent]) => rightMap.get(identity) === exponent);
|
|
292
|
+
}
|
|
293
|
+
export async function writeOutputs(outputs) {
|
|
294
|
+
for (const output of outputs) {
|
|
295
|
+
try {
|
|
296
|
+
await Bun.write(output.path, output.contents);
|
|
297
|
+
}
|
|
298
|
+
catch (error) {
|
|
299
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
300
|
+
outputError('AMX6002', `Failed to write output '${output.path}': ${detail}`);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
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 preparePdfDestination(destination, entryPath, inputMappings) {
|
|
5
|
+
if (!destination)
|
|
6
|
+
outputError('AMX6001', 'PDF export requires --out <path>');
|
|
7
|
+
if (path.extname(destination) !== '.pdf')
|
|
8
|
+
outputError('AMX6001', 'PDF destination must use the exact lowercase .pdf 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', `PDF 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', `PDF destination '${canonicalDestination}' conflicts with an input or entry module`);
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
const existing = await lstat(canonicalDestination);
|
|
26
|
+
if (existing.isSymbolicLink())
|
|
27
|
+
outputError('AMX6001', `PDF destination '${canonicalDestination}' must not be a symlink`);
|
|
28
|
+
if (!existing.isFile())
|
|
29
|
+
outputError('AMX6001', `PDF destination '${canonicalDestination}' is not a regular file`);
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (error.code !== 'ENOENT') {
|
|
33
|
+
outputError('AMX6001', `Cannot inspect PDF destination '${canonicalDestination}'`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return { path: canonicalDestination, parent: canonicalParent };
|
|
37
|
+
}
|
|
38
|
+
export async function writePdfAtomically(destination, bytes, beforeCommit) {
|
|
39
|
+
const temporary = path.join(destination.parent, `.${path.basename(destination.path)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);
|
|
40
|
+
let handle;
|
|
41
|
+
try {
|
|
42
|
+
handle = await open(temporary, 'wx');
|
|
43
|
+
await handle.write(bytes);
|
|
44
|
+
await handle.sync();
|
|
45
|
+
await handle.close();
|
|
46
|
+
handle = undefined;
|
|
47
|
+
beforeCommit?.();
|
|
48
|
+
await rename(temporary, destination.path);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (handle)
|
|
52
|
+
await handle.close().catch(() => undefined);
|
|
53
|
+
await unlink(temporary).catch(() => undefined);
|
|
54
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
55
|
+
outputError('AMX6002', `Failed to write PDF '${destination.path}': ${detail}`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { AmxError } from '../diagnostics/errors';
|
|
2
|
+
/**
|
|
3
|
+
* Standard library for OpenAMX v0.1.
|
|
4
|
+
*
|
|
5
|
+
* Functions:
|
|
6
|
+
* sum(values) - numeric sum of list elements
|
|
7
|
+
* min(values) - minimum numeric value in list
|
|
8
|
+
* max(values) - maximum numeric value in list
|
|
9
|
+
* mean(values) - arithmetic mean of list elements
|
|
10
|
+
* round(value, digits?) - round to optional decimal places
|
|
11
|
+
* abs(value) - absolute value
|
|
12
|
+
* sqrt(value) - square root
|
|
13
|
+
* pow(value, exponent) - power
|
|
14
|
+
*
|
|
15
|
+
* Errors are surfaced via AmxError with clear messages (no new AMX codes beyond 1004 unless needed).
|
|
16
|
+
*/
|
|
17
|
+
function ensureList(arg, callee, source, file) {
|
|
18
|
+
if (!Array.isArray(arg)) {
|
|
19
|
+
const loc = source ? ` at line ${source.line}` : '';
|
|
20
|
+
throw new AmxError({
|
|
21
|
+
code: 'AMX2001',
|
|
22
|
+
message: `${callee} expects a list${loc}`,
|
|
23
|
+
file,
|
|
24
|
+
line: source?.line,
|
|
25
|
+
column: source?.column
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
return arg;
|
|
29
|
+
}
|
|
30
|
+
function ensureNumber(v, context, source, file) {
|
|
31
|
+
if (typeof v === 'number')
|
|
32
|
+
return v;
|
|
33
|
+
if (typeof v === 'boolean')
|
|
34
|
+
return v ? 1 : 0;
|
|
35
|
+
if (typeof v === 'string') {
|
|
36
|
+
const n = Number(v);
|
|
37
|
+
if (!Number.isNaN(n))
|
|
38
|
+
return n;
|
|
39
|
+
}
|
|
40
|
+
const loc = source ? ` at line ${source.line}` : '';
|
|
41
|
+
throw new AmxError({
|
|
42
|
+
code: 'AMX2002',
|
|
43
|
+
message: `${context} requires a numeric value${loc}`,
|
|
44
|
+
file,
|
|
45
|
+
line: source?.line,
|
|
46
|
+
column: source?.column
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
function ensureArgCount(args, expected, callee, source, file) {
|
|
50
|
+
if (args.length !== expected) {
|
|
51
|
+
const loc = source ? ` at line ${source.line}` : '';
|
|
52
|
+
throw new AmxError({
|
|
53
|
+
code: 'AMX2003',
|
|
54
|
+
message: `${callee} expects ${expected} argument(s), got ${args.length}${loc}`,
|
|
55
|
+
file,
|
|
56
|
+
line: source?.line,
|
|
57
|
+
column: source?.column
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function ensureMinArgCount(args, min, callee, source, file) {
|
|
62
|
+
if (args.length < min) {
|
|
63
|
+
const loc = source ? ` at line ${source.line}` : '';
|
|
64
|
+
throw new AmxError({
|
|
65
|
+
code: 'AMX2003',
|
|
66
|
+
message: `${callee} expects at least ${min} argument(s), got ${args.length}${loc}`,
|
|
67
|
+
file,
|
|
68
|
+
line: source?.line,
|
|
69
|
+
column: source?.column
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export function evaluateStandardLibraryCall(callee, args, source, file) {
|
|
74
|
+
switch (callee) {
|
|
75
|
+
case 'sum': {
|
|
76
|
+
ensureArgCount(args, 1, 'sum', source, file);
|
|
77
|
+
const list = ensureList(args[0], 'sum', source, file);
|
|
78
|
+
return list.reduce((acc, v) => acc + ensureNumber(v, 'sum element', source, file), 0);
|
|
79
|
+
}
|
|
80
|
+
case 'min': {
|
|
81
|
+
ensureArgCount(args, 1, 'min', source, file);
|
|
82
|
+
const list = ensureList(args[0], 'min', source, file);
|
|
83
|
+
if (list.length === 0) {
|
|
84
|
+
const loc = source ? ` at line ${source.line}` : '';
|
|
85
|
+
throw new AmxError({ code: 'AMX2004', message: `min of empty list${loc}`, file, line: source?.line, column: source?.column });
|
|
86
|
+
}
|
|
87
|
+
return list.reduce((acc, v) => Math.min(acc, ensureNumber(v, 'min element', source, file)), Number.POSITIVE_INFINITY);
|
|
88
|
+
}
|
|
89
|
+
case 'max': {
|
|
90
|
+
ensureArgCount(args, 1, 'max', source, file);
|
|
91
|
+
const list = ensureList(args[0], 'max', source, file);
|
|
92
|
+
if (list.length === 0) {
|
|
93
|
+
const loc = source ? ` at line ${source.line}` : '';
|
|
94
|
+
throw new AmxError({ code: 'AMX2004', message: `max of empty list${loc}`, file, line: source?.line, column: source?.column });
|
|
95
|
+
}
|
|
96
|
+
return list.reduce((acc, v) => Math.max(acc, ensureNumber(v, 'max element', source, file)), Number.NEGATIVE_INFINITY);
|
|
97
|
+
}
|
|
98
|
+
case 'mean': {
|
|
99
|
+
ensureArgCount(args, 1, 'mean', source, file);
|
|
100
|
+
const list = ensureList(args[0], 'mean', source, file);
|
|
101
|
+
if (list.length === 0) {
|
|
102
|
+
const loc = source ? ` at line ${source.line}` : '';
|
|
103
|
+
throw new AmxError({ code: 'AMX2004', message: `mean of empty list${loc}`, file, line: source?.line, column: source?.column });
|
|
104
|
+
}
|
|
105
|
+
const sum = list.reduce((acc, v) => acc + ensureNumber(v, 'mean element', source, file), 0);
|
|
106
|
+
return sum / list.length;
|
|
107
|
+
}
|
|
108
|
+
case 'round': {
|
|
109
|
+
ensureMinArgCount(args, 1, 'round', source, file);
|
|
110
|
+
const value = ensureNumber(args[0], 'round value', source, file);
|
|
111
|
+
const digits = args.length > 1 ? ensureNumber(args[1], 'round digits', source, file) : 0;
|
|
112
|
+
const factor = Math.pow(10, Math.trunc(digits));
|
|
113
|
+
return Math.round(value * factor) / factor;
|
|
114
|
+
}
|
|
115
|
+
case 'abs': {
|
|
116
|
+
ensureArgCount(args, 1, 'abs', source, file);
|
|
117
|
+
const value = ensureNumber(args[0], 'abs value', source, file);
|
|
118
|
+
return Math.abs(value);
|
|
119
|
+
}
|
|
120
|
+
case 'sqrt': {
|
|
121
|
+
ensureArgCount(args, 1, 'sqrt', source, file);
|
|
122
|
+
const value = ensureNumber(args[0], 'sqrt value', source, file);
|
|
123
|
+
if (value < 0) {
|
|
124
|
+
const loc = source ? ` at line ${source.line}` : '';
|
|
125
|
+
throw new AmxError({ code: 'AMX2005', message: `sqrt of negative value${loc}`, file, line: source?.line, column: source?.column });
|
|
126
|
+
}
|
|
127
|
+
return Math.sqrt(value);
|
|
128
|
+
}
|
|
129
|
+
case 'pow': {
|
|
130
|
+
ensureArgCount(args, 2, 'pow', source, file);
|
|
131
|
+
const value = ensureNumber(args[0], 'pow base', source, file);
|
|
132
|
+
const exponent = ensureNumber(args[1], 'pow exponent', source, file);
|
|
133
|
+
return Math.pow(value, exponent);
|
|
134
|
+
}
|
|
135
|
+
default:
|
|
136
|
+
const loc = source ? ` at line ${source.line}` : '';
|
|
137
|
+
throw new AmxError({
|
|
138
|
+
code: 'AMX2000',
|
|
139
|
+
message: `Unknown function '${callee}'${loc}`,
|
|
140
|
+
file,
|
|
141
|
+
line: source?.line,
|
|
142
|
+
column: source?.column
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
}
|