@nova-energy/openamx 0.21.0 → 0.23.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.
@@ -0,0 +1,372 @@
1
+ import * as ts from 'typescript';
2
+ import { AmxError } from '../diagnostics/errors';
3
+ const bridgeReservedTypeNames = new Set(['Array']);
4
+ function declarationIdentifiers(statement) {
5
+ const identifiers = [];
6
+ const collectBindingName = (name) => {
7
+ if (ts.isIdentifier(name)) {
8
+ identifiers.push(name);
9
+ return;
10
+ }
11
+ for (const element of name.elements) {
12
+ if (ts.isOmittedExpression(element))
13
+ continue;
14
+ collectBindingName(element.name);
15
+ }
16
+ };
17
+ if (ts.isVariableStatement(statement)) {
18
+ for (const declaration of statement.declarationList.declarations)
19
+ collectBindingName(declaration.name);
20
+ }
21
+ else if (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)
22
+ || ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)
23
+ || ts.isEnumDeclaration(statement) || ts.isModuleDeclaration(statement)) {
24
+ if (statement.name && ts.isIdentifier(statement.name))
25
+ identifiers.push(statement.name);
26
+ }
27
+ return identifiers;
28
+ }
29
+ function typeReferenceText(reference, view, dateTimeName, seen = new Set(), readonlyArrays = false) {
30
+ if (reference.type === 'listType') {
31
+ const element = reference.element && typeReferenceText(reference.element, view, dateTimeName, seen, readonlyArrays);
32
+ return element ? readonlyArrays ? `ReadonlyArray<${element}>` : `${element}[]` : undefined;
33
+ }
34
+ if (reference.type === 'nullableType') {
35
+ const element = reference.element && typeReferenceText(reference.element, view, dateTimeName, seen, readonlyArrays);
36
+ return element ? `${element} | null` : undefined;
37
+ }
38
+ const name = reference.name;
39
+ if (!name)
40
+ return undefined;
41
+ if (name === 'Number')
42
+ return 'number';
43
+ if (name === 'String')
44
+ return 'string';
45
+ if (name === 'Boolean')
46
+ return 'boolean';
47
+ if (name === 'DateTime')
48
+ return dateTimeName;
49
+ if (view.enums.has(name))
50
+ return name;
51
+ const declaration = view.types.get(name);
52
+ if (!declaration || seen.has(name) || declaration.fields.some(field => field.optional))
53
+ return undefined;
54
+ const nextSeen = new Set(seen).add(name);
55
+ for (const field of declaration.fields) {
56
+ if (!typeReferenceText(field.annotation, view, dateTimeName, nextSeen, readonlyArrays))
57
+ return undefined;
58
+ }
59
+ return name;
60
+ }
61
+ function checkedTypeText(type, view, dateTimeName, seen = new Set(), readonlyArrays = false) {
62
+ switch (type.kind) {
63
+ case 'named': {
64
+ if (type.name === 'Number')
65
+ return 'number';
66
+ if (type.name === 'String')
67
+ return 'string';
68
+ if (type.name === 'Boolean')
69
+ return 'boolean';
70
+ if (type.name === 'DateTime')
71
+ return dateTimeName;
72
+ if (view.enums.has(type.name))
73
+ return type.name;
74
+ const declaration = view.types.get(type.name);
75
+ if (!declaration || seen.has(type.name) || declaration.fields.some(field => field.optional))
76
+ return undefined;
77
+ const nextSeen = new Set(seen).add(type.name);
78
+ for (const field of declaration.fields) {
79
+ if (!typeReferenceText(field.annotation, view, dateTimeName, nextSeen, readonlyArrays))
80
+ return undefined;
81
+ }
82
+ return type.name;
83
+ }
84
+ case 'list': {
85
+ const element = checkedTypeText(type.element, view, dateTimeName, seen, readonlyArrays);
86
+ return element ? readonlyArrays ? `ReadonlyArray<${element}>` : `${element}[]` : undefined;
87
+ }
88
+ case 'nullable': {
89
+ const element = checkedTypeText(type.element, view, dateTimeName, seen, readonlyArrays);
90
+ return element ? `${element} | null` : undefined;
91
+ }
92
+ case 'measurement':
93
+ case 'null': return undefined;
94
+ }
95
+ }
96
+ function outputReferenceSupported(reference, view, seen = new Set()) {
97
+ if (reference.type === 'listType' || reference.type === 'nullableType') {
98
+ return !!reference.element && outputReferenceSupported(reference.element, view, seen);
99
+ }
100
+ const name = reference.name;
101
+ if (!name || name === 'DateTime')
102
+ return false;
103
+ if (name === 'Number' || name === 'String' || name === 'Boolean' || view.enums.has(name))
104
+ return true;
105
+ const declaration = view.types.get(name);
106
+ if (!declaration || seen.has(name) || declaration.fields.some(field => field.optional))
107
+ return false;
108
+ const nextSeen = new Set(seen).add(name);
109
+ return declaration.fields.every(field => outputReferenceSupported(field.annotation, view, nextSeen));
110
+ }
111
+ function outputType(type, view, dateTimeName, seen = new Set()) {
112
+ if (ts.isParenthesizedTypeNode(type))
113
+ return outputType(type.type, view, dateTimeName, seen);
114
+ if (type.kind === ts.SyntaxKind.NumberKeyword)
115
+ return { kind: 'named', name: 'Number' };
116
+ if (type.kind === ts.SyntaxKind.StringKeyword)
117
+ return { kind: 'named', name: 'String' };
118
+ if (type.kind === ts.SyntaxKind.BooleanKeyword)
119
+ return { kind: 'named', name: 'Boolean' };
120
+ if (ts.isArrayTypeNode(type)) {
121
+ const element = outputType(type.elementType, view, dateTimeName, seen);
122
+ return element ? { kind: 'list', element } : undefined;
123
+ }
124
+ if (ts.isUnionTypeNode(type)) {
125
+ const nullTypes = type.types.filter(item => ts.isLiteralTypeNode(item) && item.literal.kind === ts.SyntaxKind.NullKeyword);
126
+ if (type.types.length !== 2 || nullTypes.length !== 1)
127
+ return undefined;
128
+ const base = type.types.find(item => item !== nullTypes[0]);
129
+ const element = base && outputType(base, view, dateTimeName, seen);
130
+ return element ? { kind: 'nullable', element } : undefined;
131
+ }
132
+ if (!ts.isTypeReferenceNode(type) || !ts.isIdentifier(type.typeName))
133
+ return undefined;
134
+ const name = type.typeName.text;
135
+ if (name === 'Array' && type.typeArguments?.length === 1) {
136
+ const element = outputType(type.typeArguments[0], view, dateTimeName, seen);
137
+ return element ? { kind: 'list', element } : undefined;
138
+ }
139
+ if (type.typeArguments?.length)
140
+ return undefined;
141
+ if (name === 'DateTime' || name === dateTimeName)
142
+ return undefined;
143
+ if (view.enums.has(name))
144
+ return { kind: 'named', name };
145
+ const declaration = view.types.get(name);
146
+ if (!declaration || !outputReferenceSupported({ type: 'namedType', name }, view, seen))
147
+ return undefined;
148
+ return { kind: 'named', name };
149
+ }
150
+ function sourceLocation(block, sourceFile, offset) {
151
+ const position = sourceFile.getLineAndCharacterOfPosition(Math.min(offset, sourceFile.text.length));
152
+ return {
153
+ line: block.contentSource.line + position.line,
154
+ column: position.line === 0 ? block.contentSource.column + position.character : position.character + 1
155
+ };
156
+ }
157
+ function makeIssue(block, sourceFile, offset, code, message, file) {
158
+ const source = sourceLocation(block, sourceFile, offset);
159
+ return {
160
+ offset,
161
+ diagnostic: { code, message, file, line: source.line, column: source.column }
162
+ };
163
+ }
164
+ function hasModifier(node, kind) {
165
+ return ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some(modifier => modifier.kind === kind) ?? false);
166
+ }
167
+ function compilerPrelude(view, rawSource) {
168
+ const identifiers = new Set();
169
+ const collectIdentifiers = (node) => {
170
+ if (ts.isIdentifier(node))
171
+ identifiers.add(node.text);
172
+ ts.forEachChild(node, collectIdentifiers);
173
+ };
174
+ collectIdentifiers(rawSource);
175
+ const privateName = (base) => {
176
+ let name = base;
177
+ while (identifiers.has(name) || view.isNameVisible(name))
178
+ name += '_';
179
+ identifiers.add(name);
180
+ return name;
181
+ };
182
+ const recordBrand = privateName('__openamx_record_brand');
183
+ const dateTimeBrand = privateName('__openamx_datetime_brand');
184
+ const dateTimeName = privateName('__OpenAmxDateTime');
185
+ const lines = [
186
+ `declare const ${recordBrand}: unique symbol;`,
187
+ `declare const ${dateTimeBrand}: unique symbol;`,
188
+ `type ${dateTimeName} = string & { readonly [${dateTimeBrand}]: true };`,
189
+ `type DateTime = ${dateTimeName};`
190
+ ];
191
+ for (const [name, declaration] of view.types) {
192
+ if (declaration.fields.some(field => field.optional))
193
+ continue;
194
+ const fields = declaration.fields.map(field => {
195
+ const fieldType = typeReferenceText(field.annotation, view, dateTimeName, new Set(), true);
196
+ return fieldType ? ` readonly ${JSON.stringify(field.name)}: ${fieldType};` : undefined;
197
+ });
198
+ if (fields.some(field => field === undefined))
199
+ continue;
200
+ lines.push(`interface ${name} {`);
201
+ lines.push(` readonly [${recordBrand}]: ${JSON.stringify(name)};`);
202
+ lines.push(...fields);
203
+ lines.push('}');
204
+ }
205
+ for (const [name, declaration] of view.enums) {
206
+ const values = declaration.resolvedValues ?? [];
207
+ if (values.length !== declaration.members.length)
208
+ continue;
209
+ lines.push(`declare enum ${name} {`);
210
+ declaration.members.forEach((member, index) => {
211
+ lines.push(` ${JSON.stringify(member.name)} = ${JSON.stringify(values[index])},`);
212
+ });
213
+ lines.push('}');
214
+ }
215
+ for (const [name, type] of view.bindings) {
216
+ const typeText = checkedTypeText(type, view, dateTimeName, new Set(), view.immutableNames.has(name));
217
+ if (!typeText)
218
+ continue;
219
+ lines.push(`declare ${view.immutableNames.has(name) ? 'const' : 'let'} ${name}: ${typeText};`);
220
+ }
221
+ return { text: lines.join('\n'), dateTimeName };
222
+ }
223
+ export function checkTypeScriptBlock(block, view, file) {
224
+ const rawSource = ts.createSourceFile('__openamx_raw.ts', block.content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
225
+ const prelude = compilerPrelude(view, rawSource);
226
+ const bodyFileName = ts.sys.resolvePath('__openamx_mixed_body.ts');
227
+ const preludeFileName = ts.sys.resolvePath('__openamx_mixed_prelude.d.ts');
228
+ const bodyText = `${block.content}\nexport {};`;
229
+ const options = {
230
+ noEmit: true,
231
+ strict: true,
232
+ target: ts.ScriptTarget.ES2022,
233
+ module: ts.ModuleKind.ESNext,
234
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
235
+ noResolve: true,
236
+ types: [],
237
+ skipLibCheck: true
238
+ };
239
+ const host = ts.createCompilerHost(options);
240
+ const virtualFiles = new Map([
241
+ [bodyFileName, ts.createSourceFile(bodyFileName, bodyText, options.target, true, ts.ScriptKind.TS)],
242
+ [preludeFileName, ts.createSourceFile(preludeFileName, prelude.text, options.target, true, ts.ScriptKind.TS)]
243
+ ]);
244
+ const normalize = (path) => ts.sys.resolvePath(path);
245
+ const originalGetSourceFile = host.getSourceFile.bind(host);
246
+ const originalFileExists = host.fileExists.bind(host);
247
+ const originalReadFile = host.readFile.bind(host);
248
+ host.getSourceFile = (path, languageVersionOrOptions, onError, shouldCreateNewSourceFile) => virtualFiles.get(normalize(path))
249
+ ?? originalGetSourceFile(path, languageVersionOrOptions, onError, shouldCreateNewSourceFile);
250
+ host.fileExists = path => virtualFiles.has(normalize(path)) || originalFileExists(path);
251
+ host.readFile = path => virtualFiles.get(normalize(path))?.text ?? originalReadFile(path);
252
+ const program = ts.createProgram([bodyFileName, preludeFileName], options, host);
253
+ const bodySource = program.getSourceFile(bodyFileName);
254
+ if (!bodySource)
255
+ throw new Error('TypeScript compiler did not load the virtual body');
256
+ const issues = [];
257
+ const report = (node, code, message) => {
258
+ issues.push(makeIssue(block, rawSource, node.getStart(rawSource), code, message, file));
259
+ };
260
+ const visitRestrictions = (node, functionDepth) => {
261
+ const nestedFunctionDepth = functionDepth + (ts.isFunctionLike(node) ? 1 : 0);
262
+ if (hasModifier(node, ts.SyntaxKind.AsyncKeyword)) {
263
+ report(node, 'AMX3023', 'Async functions are not supported in TypeScript blocks');
264
+ }
265
+ if (node.kind === ts.SyntaxKind.ImportDeclaration || node.kind === ts.SyntaxKind.ExportDeclaration
266
+ || node.kind === ts.SyntaxKind.ExportAssignment) {
267
+ report(node, 'AMX3023', 'TypeScript module declarations are not supported in TypeScript blocks');
268
+ }
269
+ if (ts.isImportEqualsDeclaration(node)) {
270
+ report(node, 'AMX3023', 'Import assignments are not supported in TypeScript blocks');
271
+ }
272
+ if (node.kind === ts.SyntaxKind.NamespaceExportDeclaration) {
273
+ report(node, 'AMX3023', 'Namespace exports are not supported in TypeScript blocks');
274
+ }
275
+ if (ts.isModuleDeclaration(node)
276
+ && (ts.isStringLiteral(node.name) || ts.isIdentifier(node.name) && node.name.text === 'global')) {
277
+ report(node, 'AMX3023', 'Ambient module declarations and global augmentations are not supported in TypeScript blocks');
278
+ }
279
+ if (ts.isImportTypeNode(node)) {
280
+ report(node, 'AMX3023', 'Import types are not supported in TypeScript blocks');
281
+ }
282
+ if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
283
+ report(node, 'AMX3023', 'Dynamic imports are not supported in TypeScript blocks');
284
+ }
285
+ if (ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword) {
286
+ report(node, 'AMX3023', 'import.meta is not supported in TypeScript blocks');
287
+ }
288
+ if (ts.isAwaitExpression(node) && functionDepth === 0) {
289
+ report(node, 'AMX3023', 'Top-level await is not supported in TypeScript blocks');
290
+ }
291
+ if (hasModifier(node, ts.SyntaxKind.ExportKeyword) || hasModifier(node, ts.SyntaxKind.DefaultKeyword)) {
292
+ report(node, 'AMX3023', 'Export declarations are not supported in TypeScript blocks');
293
+ }
294
+ ts.forEachChild(node, child => visitRestrictions(child, nestedFunctionDepth));
295
+ };
296
+ visitRestrictions(rawSource, 0);
297
+ for (const statement of rawSource.statements) {
298
+ for (const identifier of declarationIdentifiers(statement)) {
299
+ if (view.isNameVisible(identifier.text) || bridgeReservedTypeNames.has(identifier.text)) {
300
+ report(identifier, 'AMX3024', `TypeScript declaration '${identifier.text}' shadows a visible or bridge-reserved name`);
301
+ }
302
+ }
303
+ }
304
+ for (const diagnostic of [
305
+ ...program.getSyntacticDiagnostics(bodySource),
306
+ ...program.getSemanticDiagnostics(bodySource)
307
+ ]) {
308
+ if (diagnostic.start !== undefined && diagnostic.start > block.content.length)
309
+ continue;
310
+ const offset = diagnostic.start ?? 0;
311
+ const source = sourceLocation(block, rawSource, offset);
312
+ issues.push({
313
+ offset,
314
+ diagnostic: {
315
+ code: `TS${diagnostic.code}`,
316
+ message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'),
317
+ file,
318
+ line: source.line,
319
+ column: source.column
320
+ }
321
+ });
322
+ }
323
+ const outputs = [];
324
+ const outputNames = new Set();
325
+ for (const statement of rawSource.statements) {
326
+ if (!ts.isVariableStatement(statement))
327
+ continue;
328
+ const flags = statement.declarationList.flags;
329
+ const isConst = (flags & ts.NodeFlags.Const) !== 0;
330
+ const isLet = (flags & ts.NodeFlags.Let) !== 0;
331
+ if (!isConst && !isLet) {
332
+ for (const declaration of statement.declarationList.declarations) {
333
+ if (declaration.type)
334
+ report(declaration, 'AMX3023', 'Top-level var declarations cannot be exposed to AMX');
335
+ }
336
+ continue;
337
+ }
338
+ for (const declaration of statement.declarationList.declarations) {
339
+ if (!ts.isIdentifier(declaration.name)) {
340
+ if (declaration.type)
341
+ report(declaration.name, 'AMX3023', 'Destructured TypeScript outputs are not supported');
342
+ continue;
343
+ }
344
+ if (!declaration.type)
345
+ continue;
346
+ const name = declaration.name.text;
347
+ const offset = declaration.name.getStart(rawSource);
348
+ if (outputNames.has(name)) {
349
+ issues.push(makeIssue(block, rawSource, offset, 'AMX3024', `Repeated TypeScript output '${name}'`, file));
350
+ continue;
351
+ }
352
+ const mappedType = outputType(declaration.type, view, prelude.dateTimeName);
353
+ if (!mappedType) {
354
+ report(declaration.type, 'AMX3023', `TypeScript output '${name}' has an unsupported AMX type annotation`);
355
+ continue;
356
+ }
357
+ outputNames.add(name);
358
+ outputs.push({
359
+ name,
360
+ type: mappedType,
361
+ mutable: !isConst,
362
+ source: sourceLocation(block, rawSource, offset)
363
+ });
364
+ }
365
+ }
366
+ if (issues.length) {
367
+ issues.sort((left, right) => left.offset - right.offset);
368
+ const diagnostics = issues.map(issue => issue.diagnostic);
369
+ throw new AmxError(diagnostics[0], diagnostics);
370
+ }
371
+ return outputs;
372
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nova-energy/openamx",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "OpenAMX is an open-source, text-based, computable document format for engineering knowledge.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -12,6 +12,7 @@
12
12
  ],
13
13
  "dependencies": {
14
14
  "cac": "^6.7.14",
15
+ "complex.js": "2.4.3",
15
16
  "csv-parse": "^7.0.3",
16
17
  "docx": "^9.14.0",
17
18
  "echarts": "6.1.0",
@@ -19,10 +20,11 @@
19
20
  "pdfmake": "0.3.11",
20
21
  "sanitize-html": "2.17.0",
21
22
  "sharp": "^0.35.5",
23
+ "typescript": "^5.9.3",
22
24
  "yaml": "^2.9.1"
23
25
  },
24
26
  "engines": {
25
- "bun": ">=1.0.0"
27
+ "bun": ">=1.4.4"
26
28
  },
27
29
  "license": "SEE LICENSE IN LICENSE.md",
28
30
  "repository": {