@nova-energy/openamx 0.21.0 → 0.22.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,7 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { AmxError, moduleError } from '../diagnostics/errors';
3
3
  import { parseDocumentText } from '../parser/parseDocument';
4
- import { checkDocument } from '../typechecker/checkDocument';
4
+ import { checkDocumentWithRuntimePlan } from '../typechecker/checkDocument';
5
5
  import { normalizeParserLineSeparators } from './source';
6
6
  function statementsOf(document) {
7
7
  const statements = [];
@@ -147,7 +147,7 @@ export function prepareGraph(entryModuleId, modules) {
147
147
  }
148
148
  }
149
149
  const imported = importedContext(record.input, record.statements, dependencies);
150
- const check = checkDocument(record.document, record.input.sourcePath, {
150
+ const checked = checkDocumentWithRuntimePlan(record.document, record.input.sourcePath, {
151
151
  ...imported,
152
152
  baseUnits: sharedBaseUnits,
153
153
  moduleIdentity: record.input.outputPath,
@@ -159,7 +159,8 @@ export function prepareGraph(entryModuleId, modules) {
159
159
  statements: record.statements,
160
160
  imports: dependencies,
161
161
  importSpecifiers: specifiers,
162
- check
162
+ check: checked.result,
163
+ typescriptBlocks: checked.typescriptBlocks
163
164
  };
164
165
  prepared.set(moduleId, module);
165
166
  states.set(moduleId, 'visited');
@@ -1,6 +1,7 @@
1
1
  import { moduleError, staticError } from '../diagnostics/errors';
2
2
  import { physicalValue } from '../runtime/measurement';
3
3
  import { fieldRegistry, setDeclaringRegistry } from './declarationRegistry';
4
+ import { checkTypeScriptBlock } from './typescriptAnalysis';
4
5
  const named = (name) => ({ kind: 'named', name });
5
6
  const list = (element) => ({ kind: 'list', element });
6
7
  const nullable = (element) => ({ kind: 'nullable', element });
@@ -307,9 +308,16 @@ function literalListLength(expression) {
307
308
  return Number.isSafeInteger(length) ? length : undefined;
308
309
  }
309
310
  export function checkDocument(doc, file, context) {
311
+ return checkDocumentInternal(doc, file, context).result;
312
+ }
313
+ export function checkDocumentWithRuntimePlan(doc, file, context) {
314
+ return checkDocumentInternal(doc, file, context);
315
+ }
316
+ function checkDocumentInternal(doc, file, context) {
310
317
  const types = new Map(context?.types ?? []);
311
318
  const enums = new Map(context?.enums ?? []);
312
319
  let bindings = new Map(context?.bindings ?? []);
320
+ const bindingSources = new Map();
313
321
  const functions = new Map(context?.functions ?? []);
314
322
  const dimensions = new Map(context?.dimensions ?? []);
315
323
  const units = new Map(context?.units ?? []);
@@ -318,6 +326,9 @@ export function checkDocument(doc, file, context) {
318
326
  const moduleIdentity = context?.moduleIdentity ?? file ?? '<memory>';
319
327
  const immutableNames = new Set([...(context?.bindings?.keys() ?? []), ...(context?.functions?.keys() ?? []), ...(context?.types?.keys() ?? []), ...(context?.enums?.keys() ?? []), ...(context?.dimensions?.keys() ?? []), ...(context?.units?.keys() ?? [])]);
320
328
  const inputNames = new Set();
329
+ const typescriptOutputNames = new Set();
330
+ const typescriptConstNames = new Set();
331
+ const typescriptRuntimePlans = new Map();
321
332
  const exportedTypes = new Map();
322
333
  const exportedEnums = new Map();
323
334
  const exportedFunctions = new Map();
@@ -1713,6 +1724,8 @@ export function checkDocument(doc, file, context) {
1713
1724
  fail('AMX3005', `Input '${statement.name}' collides with another declaration`, statement.source);
1714
1725
  }
1715
1726
  bindings.set(statement.name, resolve(statement.annotation));
1727
+ if (statement.source)
1728
+ bindingSources.set(statement.name, statement.source);
1716
1729
  immutableNames.add(statement.name);
1717
1730
  inputNames.add(statement.name);
1718
1731
  return;
@@ -1874,6 +1887,8 @@ export function checkDocument(doc, file, context) {
1874
1887
  return;
1875
1888
  }
1876
1889
  case 'variableDeclaration': {
1890
+ if (typescriptOutputNames.has(statement.name))
1891
+ fail('AMX3005', `Binding '${statement.name}' collides with a prior TypeScript output`, statement.source);
1877
1892
  if (types.has(statement.name) || enums.has(statement.name) || functions.has(statement.name) || views.has(statement.name) || dimensions.has(statement.name) || units.has(statement.name))
1878
1893
  fail('AMX3005', `Binding '${statement.name}' conflicts with another declaration`, statement.source);
1879
1894
  if (inputNames.has(statement.name))
@@ -1888,12 +1903,16 @@ export function checkDocument(doc, file, context) {
1888
1903
  requireType(actual, target, statement.expression.source ?? statement.source);
1889
1904
  const finalType = target ?? actual;
1890
1905
  bindings.set(statement.name, finalType);
1906
+ if (statement.source)
1907
+ bindingSources.set(statement.name, statement.source);
1891
1908
  if (statement.exported)
1892
1909
  exportedBindings.set(statement.name, finalType);
1893
1910
  return;
1894
1911
  }
1895
1912
  case 'assignmentStatement':
1896
1913
  case 'compoundAssignmentStatement': {
1914
+ if (typescriptConstNames.has(statement.name))
1915
+ fail('AMX3005', `Cannot assign to immutable TypeScript const '${statement.name}'`, statement.source);
1897
1916
  if (views.has(statement.name))
1898
1917
  fail('AMX3005', `Cannot assign to immutable visualization '${statement.name}'`, statement.source);
1899
1918
  if (inputNames.has(statement.name))
@@ -2015,7 +2034,49 @@ export function checkDocument(doc, file, context) {
2015
2034
  let sawInput = false;
2016
2035
  let sawOtherItem = false;
2017
2036
  checkInheritanceCycles();
2018
- for (const node of doc.nodes) {
2037
+ for (let nodeIndex = 0; nodeIndex < doc.nodes.length; nodeIndex++) {
2038
+ const node = doc.nodes[nodeIndex];
2039
+ if (node.type === 'typescriptCodeBlock') {
2040
+ const visibleBindings = [...bindings].map(([name, type]) => ({
2041
+ name,
2042
+ type,
2043
+ mutable: !immutableNames.has(name),
2044
+ origin: inputNames.has(name) ? 'input'
2045
+ : typescriptConstNames.has(name) ? 'typescript-const'
2046
+ : typescriptOutputNames.has(name) ? 'typescript-let'
2047
+ : context?.bindings?.has(name) ? 'import' : 'amx',
2048
+ source: bindingSources.get(name)
2049
+ }));
2050
+ const visibleTypes = new Map(types);
2051
+ const visibleEnums = new Map(enums);
2052
+ const outputs = checkTypeScriptBlock(node, {
2053
+ bindings,
2054
+ immutableNames,
2055
+ types,
2056
+ enums,
2057
+ isNameVisible: hasName
2058
+ }, file);
2059
+ for (const output of outputs) {
2060
+ if (hasName(output.name))
2061
+ fail('AMX3005', `TypeScript output '${output.name}' collides with a visible declaration`, output.source);
2062
+ bindings.set(output.name, output.type);
2063
+ bindingSources.set(output.name, output.source);
2064
+ typescriptOutputNames.add(output.name);
2065
+ if (!output.mutable) {
2066
+ immutableNames.add(output.name);
2067
+ typescriptConstNames.add(output.name);
2068
+ }
2069
+ }
2070
+ typescriptRuntimePlans.set(nodeIndex, {
2071
+ nodeIndex,
2072
+ node,
2073
+ visibleBindings,
2074
+ visibleTypes,
2075
+ visibleEnums,
2076
+ outputs
2077
+ });
2078
+ continue;
2079
+ }
2019
2080
  if (node.type !== 'executableCodeBlock')
2020
2081
  continue;
2021
2082
  for (const statement of node.statements) {
@@ -2036,7 +2097,7 @@ export function checkDocument(doc, file, context) {
2036
2097
  checkStatement(statement);
2037
2098
  }
2038
2099
  }
2039
- return {
2100
+ const result = {
2040
2101
  exportedTypes,
2041
2102
  exportedEnums,
2042
2103
  exportedFunctions,
@@ -2048,4 +2109,5 @@ export function checkDocument(doc, file, context) {
2048
2109
  units,
2049
2110
  baseUnits: new Map(baseUnits)
2050
2111
  };
2112
+ return { result, typescriptBlocks: typescriptRuntimePlans };
2051
2113
  }
@@ -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, file) {
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.22.0",
4
4
  "description": "OpenAMX is an open-source, text-based, computable document format for engineering knowledge.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -19,10 +19,11 @@
19
19
  "pdfmake": "0.3.11",
20
20
  "sanitize-html": "2.17.0",
21
21
  "sharp": "^0.35.5",
22
+ "typescript": "^5.9.3",
22
23
  "yaml": "^2.9.1"
23
24
  },
24
25
  "engines": {
25
- "bun": ">=1.0.0"
26
+ "bun": ">=1.4.4"
26
27
  },
27
28
  "license": "SEE LICENSE IN LICENSE.md",
28
29
  "repository": {