@tsplc/typegen 0.5.13 → 0.5.15

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/dist/index.js CHANGED
@@ -1,25 +1,54 @@
1
1
  // packages/typegen/src/index.ts
2
- import { ioScalarBits as ioScalarBits4 } from "@tsplc/iec";
2
+ import { ioScalarBits as ioScalarBits3 } from "@tsplc/iec";
3
3
 
4
4
  // packages/typegen/src/codegen/generate.ts
5
- import { readdir, readFile } from "node:fs/promises";
6
- import { basename, join } from "node:path";
7
- import { elementaryTypesByName } from "@tsplc/iec";
5
+ import {
6
+ elementaryType as elementaryType3,
7
+ elementaryTypesByName,
8
+ fitsNumber as fitsNumber2,
9
+ isIntegerValued as isIntegerValued2,
10
+ isWholeValue,
11
+ stringTypeText
12
+ } from "@tsplc/iec";
8
13
  import { identifierPattern as identifierPattern2 } from "@tsplc/iec/st";
9
14
 
15
+ // packages/typegen/src/files.ts
16
+ import { readdir, readFile } from "node:fs/promises";
17
+ import { join } from "node:path";
18
+ var isMissingFile = (error) => error instanceof Error && ("code" in error) && error.code === "ENOENT";
19
+ var readIfPresent = (path) => readFile(path, "utf8").catch((error) => {
20
+ if (isMissingFile(error)) {
21
+ return null;
22
+ }
23
+ throw error;
24
+ });
25
+ async function filesUnder(directory, extension, order) {
26
+ const pattern = new RegExp(`\\.${extension}$`, "i");
27
+ const entries = await readdir(directory, { withFileTypes: true });
28
+ const paths = await Promise.all(entries.sort((a, b) => order(a.name, b.name)).map(async (entry) => {
29
+ const path = join(directory, entry.name);
30
+ if (entry.isDirectory()) {
31
+ return filesUnder(path, extension, order);
32
+ }
33
+ return entry.isFile() && pattern.test(entry.name) ? [path] : [];
34
+ }));
35
+ return paths.flat();
36
+ }
37
+ var stFiles = (directory) => filesUnder(directory, "st", (a, b) => a < b ? -1 : 1);
38
+
10
39
  // packages/typegen/src/codegen/constants.ts
11
40
  import {
12
41
  elementaryType,
13
42
  elementaryTypes,
43
+ fitsNumber,
14
44
  integerRange,
15
45
  isIntegerValued
16
46
  } from "@tsplc/iec";
17
- var isNumberInteger = (name) => {
18
- const type = elementaryType(name);
19
- return isIntegerValued(type) && type.bits <= 32;
20
- };
47
+ import { identifierPart, identifierStart, integerLiteral } from "@tsplc/iec/st";
21
48
  var integerRanges = new Map(elementaryTypes.filter(isIntegerValued).map((type) => [type.name, integerRange(type)]));
22
- var integerToken = new RegExp(String.raw`(?:${[...integerRanges.keys()].join("|")})\s*#\s*[+-]?(?:(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*)|(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*|[A-Za-z_]\w*(?:\s*\.\s*[A-Za-z_]\w*)?|[()+\-*/]`, "g");
49
+ var identifier = `${identifierStart}${identifierPart}*`;
50
+ var startsWithIdentifier = new RegExp(`^${identifierStart}`);
51
+ var integerToken = new RegExp(String.raw`(?:${[...integerRanges.keys()].join("|")})\s*#\s*[+-]?(?:(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*)|(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*|${identifier}(?:\s*\.\s*${identifier})?|[()+\-*/]`, "g");
23
52
  function integerExpression(text, lookup) {
24
53
  const compact = text.replace(/\s+/g, "");
25
54
  const tokens = (text.match(integerToken) ?? []).map((token) => token.replace(/\s+/g, ""));
@@ -58,13 +87,13 @@ function integerExpression(text, lookup) {
58
87
  return value;
59
88
  }
60
89
  if (token && /^\d/.test(token)) {
61
- const [base, digits] = token.replace(/_/g, "").split("#");
62
- if (digits !== undefined && ![...digits].every((digit) => parseInt(digit, 16) < Number(base))) {
63
- throw new Error(`invalid base-${base} literal: ${token}`);
90
+ const literal = integerLiteral(token);
91
+ if (literal === undefined) {
92
+ throw new Error(`invalid integer literal: ${token}`);
64
93
  }
65
- return safe(digits === undefined ? Number(base) : parseInt(digits, Number(base)));
94
+ return safe(Number(literal));
66
95
  }
67
- if (token && /^[A-Za-z_]/.test(token)) {
96
+ if (token && startsWithIdentifier.test(token)) {
68
97
  return lookup(token);
69
98
  }
70
99
  throw new Error(`invalid integer expression: ${text}`);
@@ -91,11 +120,12 @@ function integerExpression(text, lookup) {
91
120
  return value;
92
121
  }
93
122
  const value = sum();
94
- if (position !== tokens.length || !Number.isSafeInteger(value)) {
95
- throw new Error(`invalid or unsafe integer expression: ${text}`);
123
+ if (position !== tokens.length) {
124
+ throw new Error(`invalid integer expression: ${text}`);
96
125
  }
97
126
  return value;
98
127
  }
128
+ var isIntegerConstant = (member) => member.type.kind === "named" && fitsNumber(elementaryType(member.type.name.toUpperCase()));
99
129
  function constantResolver(lists) {
100
130
  const values = new Map;
101
131
  const resolving = new Set;
@@ -119,7 +149,7 @@ function constantResolver(lists) {
119
149
  throw new Error(`cyclic constant ${name}`);
120
150
  }
121
151
  const { member, list } = definition;
122
- if (member.initial === undefined || member.type.kind !== "named" || !isNumberInteger(member.type.name.toUpperCase())) {
152
+ if (member.initial === undefined || !isIntegerConstant(member)) {
123
153
  throw new Error(`${list.source}: constant ${member.name} must have an integer type and initializer`);
124
154
  }
125
155
  resolving.add(definition.key);
@@ -132,72 +162,89 @@ function constantResolver(lists) {
132
162
  }
133
163
 
134
164
  // packages/typegen/src/codegen/parser.ts
165
+ import { readFile as readFile2 } from "node:fs/promises";
166
+ import { basename } from "node:path";
167
+ import { defaultStringLength } from "@tsplc/iec";
135
168
  import {
136
169
  blockCommentEnd,
137
170
  directAddressEnd,
171
+ identifierPart as identifierPart2,
138
172
  identifierPattern,
173
+ identifierStart as identifierStart2,
139
174
  lineCommentEnd,
140
- qualifiers
175
+ qualifiers,
176
+ stringEnd
141
177
  } from "@tsplc/iec/st";
178
+ var pragmaEnd = (text, offset) => {
179
+ const next = text.slice(offset).search(/[}'"]/);
180
+ if (next < 0) {
181
+ return null;
182
+ }
183
+ const at = offset + next;
184
+ if (text[at] === "}") {
185
+ return at + 1;
186
+ }
187
+ const end = stringEnd(text, at);
188
+ return end === null ? null : pragmaEnd(text, end);
189
+ };
190
+ var codeToken = new RegExp(String.raw`^(?:\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|${identifierStart2}${identifierPart2}*|:=|\.\.|[[\]():;,.+\-*/#])`, "i");
191
+ function tokenAt(source, start) {
192
+ const { text } = source;
193
+ const offset = start + text.slice(start).search(/\S|$/);
194
+ if (offset === text.length) {
195
+ return;
196
+ }
197
+ const rest = text.slice(offset);
198
+ if (rest.startsWith("(*")) {
199
+ const end = blockCommentEnd(text, offset);
200
+ if (end === null) {
201
+ throw new Error(`${source.name}: unterminated comment`);
202
+ }
203
+ const comment = text.slice(offset + 2, end - 2).trim();
204
+ return { text: comment, offset, end, kind: "comment" };
205
+ }
206
+ if (rest.startsWith("//")) {
207
+ const end = lineCommentEnd(text, offset);
208
+ const comment = text.slice(offset + 2, end).trim();
209
+ return { text: comment, offset, end, kind: "comment" };
210
+ }
211
+ const code = (kind, end) => ({
212
+ text: text.slice(offset, end),
213
+ offset,
214
+ end,
215
+ kind
216
+ });
217
+ const attributeEnd = rest.startsWith("{") ? pragmaEnd(text, offset + 1) : null;
218
+ if (attributeEnd !== null) {
219
+ return code("attribute", attributeEnd);
220
+ }
221
+ const addressEnd = directAddressEnd(text, offset);
222
+ if (addressEnd !== null) {
223
+ return code("code", addressEnd);
224
+ }
225
+ const literalEnd = rest.startsWith("'") || rest.startsWith('"') ? stringEnd(text, offset) : null;
226
+ if (literalEnd !== null) {
227
+ return code("code", literalEnd);
228
+ }
229
+ const word = codeToken.exec(rest);
230
+ if (!word) {
231
+ throw new Error(`${source.name}:${text.slice(0, offset).split(`
232
+ `).length}: unsupported token ${JSON.stringify(rest.slice(0, 24))}`);
233
+ }
234
+ return code("code", offset + word[0].length);
235
+ }
142
236
  function tokenize(source) {
143
237
  const tokens = [];
144
- let offset = 0;
145
- while (offset < source.text.length) {
146
- const rest = source.text.slice(offset);
147
- const whitespace = /^\s+/.exec(rest);
148
- if (whitespace) {
149
- offset += whitespace[0].length;
150
- continue;
151
- }
152
- if (rest.startsWith("(*")) {
153
- const end = blockCommentEnd(source.text, offset);
154
- if (end === null) {
155
- throw new Error(`${source.name}: unterminated comment`);
156
- }
157
- tokens.push({
158
- text: source.text.slice(offset + 2, end - 2).trim(),
159
- offset,
160
- kind: "comment"
161
- });
162
- offset = end;
163
- continue;
164
- }
165
- if (rest.startsWith("//")) {
166
- const end = lineCommentEnd(source.text, offset);
167
- tokens.push({
168
- text: source.text.slice(offset + 2, end).trim(),
169
- offset,
170
- kind: "comment"
171
- });
172
- offset = end;
173
- continue;
174
- }
175
- const attribute = /^\{(?:[^}'"]|'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*")*\}/.exec(rest);
176
- if (attribute) {
177
- tokens.push({ text: attribute[0], offset, kind: "attribute" });
178
- offset += attribute[0].length;
179
- continue;
180
- }
181
- const addressEnd = directAddressEnd(source.text, offset);
182
- if (addressEnd !== null) {
183
- tokens.push({
184
- text: source.text.slice(offset, addressEnd),
185
- offset,
186
- kind: "code"
187
- });
188
- offset = addressEnd;
189
- continue;
190
- }
191
- const code = /^(?:'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*"|\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|[A-Za-z_]\w*|:=|\.\.|[[\]():;,.+\-*/#])/i.exec(rest);
192
- if (!code) {
193
- throw new Error(`${source.name}:${source.text.slice(0, offset).split(`
194
- `).length}: unsupported token ${JSON.stringify(rest.slice(0, 24))}`);
195
- }
196
- tokens.push({ text: code[0], offset, kind: "code" });
197
- offset += code[0].length;
238
+ for (let token = tokenAt(source, 0);token; token = tokenAt(source, token.end)) {
239
+ tokens.push(token);
198
240
  }
199
241
  return tokens;
200
242
  }
243
+ var codeTokenAt = (source, offset) => {
244
+ const token = tokenAt(source, offset);
245
+ return token && token.kind !== "code" ? codeTokenAt(source, token.end) : token;
246
+ };
247
+ var firstCodeToken = (source) => codeTokenAt(source, 0)?.text;
201
248
 
202
249
  class Parser {
203
250
  source;
@@ -299,7 +346,11 @@ class Parser {
299
346
  if (upper === "STRING" || upper === "WSTRING") {
300
347
  const opening = this.peek();
301
348
  if (opening !== "(" && opening !== "[") {
302
- return { kind: "string", name: upper, length: "80" };
349
+ return {
350
+ kind: "string",
351
+ name: upper,
352
+ length: String(defaultStringLength)
353
+ };
303
354
  }
304
355
  this.take();
305
356
  const closing = opening === "(" ? ")" : "]";
@@ -438,126 +489,143 @@ function parseDeclarations(source) {
438
489
  function parseGlobals(source, name) {
439
490
  return new Parser(source).globals(name);
440
491
  }
492
+ var readSource = async (name) => ({
493
+ name,
494
+ text: await readFile2(name, "utf8")
495
+ });
496
+ async function parseSources(files) {
497
+ return {
498
+ types: (await Promise.all(files.types.map(readSource))).flatMap(parseDeclarations),
499
+ globals: (await Promise.all(files.globals.map(readSource))).map((source) => parseGlobals(source, basename(source.name).replace(/\.st$/i, "")))
500
+ };
501
+ }
502
+
503
+ // packages/typegen/src/codegen/resolution.ts
504
+ import { elementaryType as elementaryType2 } from "@tsplc/iec";
505
+ function resolveDeclarations({
506
+ types,
507
+ globals
508
+ }) {
509
+ const declarations = new Map(types.map((declaration) => [declaration.name.toUpperCase(), declaration]));
510
+ const constant = constantResolver(globals.filter((list) => list.constant));
511
+ const integer = (expression) => integerExpression(expression, (name) => constant(name, null));
512
+ const declaration = (name) => {
513
+ const found = declarations.get(name.toUpperCase());
514
+ if (!found) {
515
+ throw new Error(`unknown IEC type ${name}`);
516
+ }
517
+ return found;
518
+ };
519
+ const aliasTarget = (reference) => {
520
+ if (reference.kind !== "named" || elementaryType2(reference.name.toUpperCase())) {
521
+ return reference;
522
+ }
523
+ const named = declaration(reference.name);
524
+ return named.kind === "alias" ? aliasTarget(named.type) : reference;
525
+ };
526
+ const bounds = (array) => array.dimensions.map(({ lower, upper }) => {
527
+ const start = integer(lower);
528
+ const end = integer(upper);
529
+ if (end < start || !Number.isSafeInteger(end - start + 1)) {
530
+ throw new Error(`invalid array bounds ${lower}..${upper}`);
531
+ }
532
+ return { start, end };
533
+ });
534
+ const enumMembers = (enumeration) => {
535
+ const members = [];
536
+ for (const member of enumeration.members) {
537
+ const value = member.value === undefined ? (members.at(-1)?.value ?? -1) + 1 : integerExpression(member.value, (name) => members.find((item) => item.name.toUpperCase() === name.toUpperCase())?.value ?? constant(name, null));
538
+ members.push({ name: member.name, value });
539
+ }
540
+ return members;
541
+ };
542
+ return { constant, integer, declaration, aliasTarget, bounds, enumMembers };
543
+ }
441
544
 
442
545
  // packages/typegen/src/codegen/generate.ts
443
546
  var scalarType = (type) => {
444
- switch (type.family) {
445
- case "bool":
446
- return "boolean";
447
- case "integer":
448
- case "bits":
449
- return type.bits === 64 ? "bigint" : "number";
450
- case "real":
451
- return "number";
452
- case "duration":
453
- case "date":
454
- case "timeOfDay":
455
- case "dateTime":
456
- return type.bits === 32 ? "number" : undefined;
457
- case "char":
458
- case "string":
459
- return;
547
+ if (type.family === "bool") {
548
+ return "boolean";
460
549
  }
550
+ return isIntegerValued2(type) && !fitsNumber2(type) ? "bigint" : "number";
461
551
  };
462
- var scalars = Object.fromEntries([...elementaryTypesByName].flatMap(([name, type]) => {
463
- const typescript = scalarType(type);
464
- return typescript ? [[name, typescript]] : [];
465
- }));
466
- async function stFiles(directory) {
467
- const entries = await readdir(directory, { withFileTypes: true });
468
- const paths = await Promise.all(entries.sort((a, b) => {
469
- if (a.name === b.name) {
470
- return 0;
471
- }
472
- return a.name < b.name ? -1 : 1;
473
- }).map(async (entry) => {
474
- const file = join(directory, entry.name);
475
- if (entry.isDirectory()) {
476
- return stFiles(file);
477
- }
478
- return entry.isFile() && /\.st$/i.test(file) ? [file] : [];
479
- }));
480
- return paths.flat();
481
- }
552
+ var scalars = Object.fromEntries([...elementaryTypesByName].flatMap(([name, type]) => isWholeValue(type) ? [[name, scalarType(type)]] : []));
553
+ var sourceFiles = async (setting) => typeof setting === "string" ? stFiles(setting) : setting;
554
+ var contractNames = {
555
+ field: "PlcField",
556
+ globals: "PlcGlobals",
557
+ typeFields: "typeFields",
558
+ globalVariableLists: "globalVariableLists",
559
+ symbols: "symbols",
560
+ publication: "publication"
561
+ };
562
+ var fieldList = (index) => `_fields${index}`;
563
+ var isFieldList = (name) => /^_fields\d+$/.test(name);
564
+ var javascriptReserved = "break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval".split(" ");
482
565
  var quote = (value) => JSON.stringify(value);
483
566
  var documentation = (value) => value ? `/** ${value.replace(/\*\//g, "* /").replace(/\r?\n/g, `
484
567
  * `)} */
485
568
  ` : "";
486
- function unique(items) {
487
- const result = new Map;
488
- for (const item of items) {
489
- const key = item.name.toUpperCase();
490
- if (result.has(key)) {
491
- throw new Error(`${item.source}: duplicate declaration ${item.name} (also in ${result.get(key)?.source})`);
569
+ function assertUniqueNames(items) {
570
+ const seen = new Map;
571
+ for (const { name, source } of items) {
572
+ const key = name.toUpperCase();
573
+ const previous = seen.get(key);
574
+ if (previous !== undefined) {
575
+ throw new Error(`${source}: duplicate declaration ${name} (also in ${previous})`);
492
576
  }
493
- result.set(key, item);
577
+ seen.set(key, source);
494
578
  }
495
- return result;
496
579
  }
497
- var readSources = (files) => Promise.all(files.map(async (name) => ({ name, text: await readFile(name, "utf8") })));
498
580
  async function generateTypes(options) {
499
- const typeFiles = typeof options.types === "string" ? await stFiles(options.types) : options.types;
500
- const declarations = (await readSources(typeFiles)).flatMap((source) => parseDeclarations(source));
501
- const globalFiles = typeof options.globals === "string" ? await stFiles(options.globals) : options.globals ?? [];
581
+ const typeFiles = await sourceFiles(options.types);
582
+ const globalFiles = await sourceFiles(options.globals);
502
583
  if (!typeFiles.length && !globalFiles.length && (typeof options.types === "string" || typeof options.globals === "string")) {
503
584
  throw new Error(`no .st declarations found in ${typeof options.types === "string" ? options.types : "the selected source files"}`);
504
585
  }
505
- const globals = (await readSources(globalFiles)).map((source) => parseGlobals(source, basename(source.name).replace(/\.st$/i, "")));
506
- const publishedGlobalsOnly = options.publishedGlobalsOnly ?? false;
507
- const contract = emit(declarations, publishedGlobalsOnly ? published(globals, options.publication) : globals, { publishedGlobalsOnly, emitDeclarations: options.declarations ?? true });
508
- return options.publication ? `${contract}
509
- export const publication = ${JSON.stringify(options.publication, null, 2)} as const;
586
+ const { types: declarations, globals } = await parseSources({
587
+ types: typeFiles,
588
+ globals: globalFiles
589
+ });
590
+ const { publication } = options;
591
+ const contract = emit(declarations, publication ? published(globals, publication) : globals, {
592
+ publishedGlobalsOnly: publication !== null,
593
+ emitDeclarations: options.declarations
594
+ });
595
+ return publication ? `${contract}
596
+ export const ${contractNames.publication} = ${JSON.stringify(publication, null, 2)} as const;
510
597
  ` : contract;
511
598
  }
512
599
  function published(globals, publication) {
600
+ const selected = new Set([
601
+ ...publication.production,
602
+ ...publication.development
603
+ ]);
513
604
  return globals.map((list) => list.constant ? list : {
514
605
  ...list,
515
- members: list.members.filter((member) => publication ? [
516
- ...publication.production,
517
- ...publication.development
518
- ].includes(`${list.name}.${member.name}`) : member.symbol !== undefined)
606
+ members: list.members.filter((member) => selected.has(`${list.name}.${member.name}`))
519
607
  }).filter((list) => list.constant || list.members.length);
520
608
  }
521
609
  function emit(declarations, globals, {
522
610
  publishedGlobalsOnly,
523
611
  emitDeclarations
524
612
  }) {
525
- const types = unique(declarations);
526
- unique(globals);
613
+ assertUniqueNames(declarations);
614
+ assertUniqueNames(globals);
527
615
  const constants = globals.filter((list) => list.constant);
528
616
  const constantLists = publishedGlobalsOnly ? constants.map((list) => ({
529
617
  ...list,
530
- members: list.members.filter((member) => member.type.kind === "named" && isNumberInteger(member.type.name.toUpperCase()))
618
+ members: list.members.filter(isIntegerConstant)
531
619
  })).filter((list) => list.members.length) : constants;
532
620
  const variableLists = globals.filter((list) => !list.constant);
533
- const constant = constantResolver(constants);
534
- function bound(expression) {
535
- return integerExpression(expression, (name) => constant(name, null));
536
- }
537
- function dimensions(type) {
538
- return type.dimensions.map(({ lower, upper }) => {
539
- const start = bound(lower);
540
- const end = bound(upper);
541
- if (end < start || !Number.isSafeInteger(end - start + 1)) {
542
- throw new Error(`invalid array bounds ${lower}..${upper}`);
543
- }
544
- return { start, end };
545
- });
546
- }
547
- function declaration(name) {
548
- const found = types.get(name.toUpperCase());
549
- if (!found) {
550
- throw new Error(`unknown IEC type ${name}`);
551
- }
552
- return found;
553
- }
621
+ const { constant, integer, declaration, aliasTarget, bounds, enumMembers } = resolveDeclarations({ types: declarations, globals });
554
622
  function tsType(type) {
555
623
  if (type.kind === "array") {
556
- dimensions(type);
624
+ bounds(type);
557
625
  return type.dimensions.reduce((child) => `Array<${child}>`, tsType(type.element));
558
626
  }
559
627
  if (type.kind === "string") {
560
- const length = bound(type.length);
628
+ const length = integer(type.length);
561
629
  if (length < 1) {
562
630
  throw new Error(`invalid ${type.name} length ${length}`);
563
631
  }
@@ -566,25 +634,23 @@ function emit(declarations, globals, {
566
634
  return scalars[type.name.toUpperCase()] ?? declaration(type.name).name;
567
635
  }
568
636
  function resolved(type) {
569
- if (type.kind !== "named" || scalars[type.name.toUpperCase()]) {
570
- return type;
571
- }
572
- const definition = declaration(type.name);
573
- if (definition.kind === "alias") {
574
- return resolved(definition.type);
637
+ const target = aliasTarget(type);
638
+ if (target.kind !== "named" || scalars[target.name.toUpperCase()]) {
639
+ return target;
575
640
  }
576
- if (definition.kind === "enum") {
577
- return { kind: "named", name: definition.base };
578
- }
579
- return type;
641
+ const definition = declaration(target.name);
642
+ return definition.kind === "enum" ? { kind: "named", name: definition.base } : target;
580
643
  }
581
644
  function iecType(type) {
582
645
  const actual = resolved(type);
583
646
  if (actual.kind === "string") {
584
- return `${actual.name}(${bound(actual.length)})`;
647
+ return stringTypeText({
648
+ wide: actual.name === "WSTRING",
649
+ capacity: integer(actual.length)
650
+ });
585
651
  }
586
652
  if (actual.kind === "array") {
587
- return `ARRAY[${dimensions(actual).map(({ start, end }) => `${start}..${end}`).join(", ")}] OF ${iecType(actual.element)}`;
653
+ return `ARRAY[${bounds(actual).map(({ start, end }) => `${start}..${end}`).join(", ")}] OF ${iecType(actual.element)}`;
588
654
  }
589
655
  return scalars[actual.name.toUpperCase()] ? actual.name.toUpperCase() : declaration(actual.name).name;
590
656
  }
@@ -621,17 +687,19 @@ function emit(declarations, globals, {
621
687
  ordered.push(type);
622
688
  }
623
689
  declarations.forEach(visit);
624
- const reserved = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval PlcGlobals PlcField typeFields symbols globalVariableLists publication".split(" "));
690
+ const reserved = new Set([
691
+ ...javascriptReserved,
692
+ ...Object.values(contractNames)
693
+ ]);
625
694
  for (const name of [
626
695
  ...declarations.map((type) => type.name),
627
696
  ...constantLists.map((list) => list.name)
628
697
  ]) {
629
- if (!identifierPattern2.test(name) || reserved.has(name) || /^_fields\d+$/.test(name)) {
698
+ if (!identifierPattern2.test(name) || reserved.has(name) || isFieldList(name)) {
630
699
  throw new Error(`name cannot be exported to TypeScript: ${name}`);
631
700
  }
632
701
  reserved.add(name);
633
702
  }
634
- const indexes = new Map(ordered.map((type, index) => [type.name, index]));
635
703
  function complex(type) {
636
704
  const actual = resolved(type);
637
705
  if (actual.kind === "array") {
@@ -649,14 +717,14 @@ function emit(declarations, globals, {
649
717
  function fields(type, path, description, depth = 0) {
650
718
  const actual = resolved(type);
651
719
  if (actual.kind === "named" && complex(actual)) {
652
- const children = `_fields${indexes.get(declaration(actual.name).name)}`;
720
+ const children = fieldList(ordered.indexOf(declaration(actual.name)));
653
721
  if (path === '""') {
654
722
  return children;
655
723
  }
656
724
  return `${children}.map((member) => ({ ...member, field: ${path} + "." + member.field }))`;
657
725
  }
658
726
  if (actual.kind === "array" && (complex(actual.element) || keyed(type))) {
659
- const ranges = dimensions(actual);
727
+ const ranges = bounds(actual);
660
728
  const coordinates = ranges.map((range, index) => `String(i${depth}_${index} + (${range.start}))`);
661
729
  const arrayPath = `${path} + "[" + ${coordinates.join(' + "," + ')} + "]"`;
662
730
  return ranges.reduceRight((child, range, index) => `Array.from({ length: ${range.end - range.start + 1} }, (_, i${depth}_${index}) => ${child}).flat()`, fields(actual.element, `(${arrayPath})`, description, depth + 1));
@@ -667,10 +735,10 @@ function emit(declarations, globals, {
667
735
  const output = [
668
736
  `// Generated by @tsplc/typegen. Edit the PLC sources and regenerate.
669
737
  `,
670
- `export interface PlcField { field: string; type: string; description: string; }
738
+ `export interface ${contractNames.field} { field: string; type: string; description: string; }
671
739
  `
672
740
  ];
673
- for (const type of ordered) {
741
+ for (const [index, type] of ordered.entries()) {
674
742
  try {
675
743
  const doc = documentation(type.description);
676
744
  if (type.kind === "struct") {
@@ -679,7 +747,7 @@ ${type.members.map((member) => `${documentation(member.description)}${quote(memb
679
747
  `)}
680
748
  }
681
749
  `));
682
- output.push(`const _fields${indexes.get(type.name)}: PlcField[] = [
750
+ output.push(`const ${fieldList(index)}: ${contractNames.field}[] = [
683
751
  ${type.members.map((member) => `...${fields(member.type, quote(member.name), member.description)},`).join(`
684
752
  `)}
685
753
  ];
@@ -687,22 +755,17 @@ ${type.members.map((member) => `...${fields(member.type, quote(member.name), mem
687
755
  } else if (type.kind === "alias") {
688
756
  output.push(...declare(`${doc}export type ${type.name} = ${tsType(type.type)};
689
757
  `));
690
- output.push(`const _fields${indexes.get(type.name)}: PlcField[] = ${fields({ kind: "named", name: type.name }, '""', type.description)};
758
+ output.push(`const ${fieldList(index)}: ${contractNames.field}[] = ${fields({ kind: "named", name: type.name }, '""', type.description)};
691
759
  `);
692
760
  } else {
693
- if (!isNumberInteger(type.base)) {
761
+ if (!fitsNumber2(elementaryType3(type.base))) {
694
762
  throw new Error(`unsupported enum base ${type.base}`);
695
763
  }
696
- const entries = new Map;
697
- for (const member of type.members) {
698
- const previous = [...entries.values()].at(-1) ?? -1;
699
- const value = member.value === undefined ? previous + 1 : integerExpression(member.value, (name) => entries.get(name.toUpperCase()) ?? constant(name, null));
700
- entries.set(member.name.toUpperCase(), value);
701
- }
702
- output.push(...declare(`${doc}export const ${type.name} = { ${type.members.map((member) => `${quote(member.name)}: ${entries.get(member.name.toUpperCase())}`).join(", ")} } as const;
764
+ const members = enumMembers(type);
765
+ output.push(...declare(`${doc}export const ${type.name} = { ${members.map(({ name, value }) => `${quote(name)}: ${value}`).join(", ")} } as const;
703
766
  export type ${type.name} = (typeof ${type.name})[keyof typeof ${type.name}];
704
767
  `));
705
- output.push(`const _fields${indexes.get(type.name)}: PlcField[] = ${fields({ kind: "named", name: type.base }, '""', type.description)};
768
+ output.push(`const ${fieldList(index)}: ${contractNames.field}[] = ${fields({ kind: "named", name: type.base }, '""', type.description)};
706
769
  `);
707
770
  }
708
771
  } catch (error) {
@@ -713,9 +776,9 @@ export type ${type.name} = (typeof ${type.name})[keyof typeof ${type.name}];
713
776
  iecType(member.type),
714
777
  fields(member.type, '""', member.description)
715
778
  ]));
716
- output.push(`export const typeFields = {
779
+ output.push(`export const ${contractNames.typeFields} = {
717
780
  ${[
718
- ...ordered.map((type) => `${quote(type.name)}: _fields${indexes.get(type.name)},`),
781
+ ...ordered.map((type, index) => `${quote(type.name)}: ${fieldList(index)},`),
719
782
  ...[...inlineArrays].map(([type, members]) => `${quote(type)}: ${members},`)
720
783
  ].join(`
721
784
  `)}
@@ -728,7 +791,7 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
728
791
  } as const;
729
792
  `);
730
793
  }
731
- output.push(...declare(`export interface PlcGlobals {
794
+ output.push(...declare(`export interface ${contractNames.globals} {
732
795
  ${variableLists.map((list) => `${documentation(list.description)}${quote(list.name)}: {
733
796
  ${list.members.map((member) => `${documentation(member.description)}${quote(member.name)}: ${tsType(member.type)};`).join(`
734
797
  `)}
@@ -736,9 +799,9 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
736
799
  `)}
737
800
  }
738
801
  `));
739
- output.push(`export const globalVariableLists = ${JSON.stringify(Object.fromEntries(variableLists.map((list) => [list.name, list.description])), null, "\t")} as const;
802
+ output.push(`export const ${contractNames.globalVariableLists} = ${JSON.stringify(Object.fromEntries(variableLists.map((list) => [list.name, list.description])), null, "\t")} as const;
740
803
  `);
741
- output.push(`export const symbols = ${JSON.stringify(variableLists.flatMap((list) => list.members.map((member) => ({
804
+ output.push(`export const ${contractNames.symbols} = ${JSON.stringify(variableLists.flatMap((list) => list.members.map((member) => ({
742
805
  name: member.name,
743
806
  gvl: list.name,
744
807
  type: member.type.kind === "named" && !scalars[member.type.name.toUpperCase()] ? declaration(member.type.name).name : iecType(member.type),
@@ -749,9 +812,19 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
749
812
  `);
750
813
  }
751
814
  // packages/typegen/src/device-tree.ts
752
- import { readFile as readFile2 } from "node:fs/promises";
815
+ import { readFile as readFile3 } from "node:fs/promises";
753
816
  import { iecName } from "@tsplc/config/build";
754
817
 
818
+ // packages/typegen/src/hardware/catalog.ts
819
+ var deviceChannel = (catalog, binding) => catalog.devices.find((device) => device.id === binding.device)?.channels.find((channel) => channel.id === binding.channel);
820
+ function boundChannel(catalog, symbol, binding) {
821
+ const channel = deviceChannel(catalog, binding);
822
+ if (!channel?.address) {
823
+ throw new Error(`${symbol}: unknown or unaddressable channel ${binding.device}.${binding.channel}.`);
824
+ }
825
+ return { ...channel, address: channel.address };
826
+ }
827
+
755
828
  // packages/typegen/src/hardware/eds.ts
756
829
  var cipTypes = {
757
830
  193: "BOOL",
@@ -770,6 +843,23 @@ var cipTypes = {
770
843
  211: "DWORD",
771
844
  212: "LWORD"
772
845
  };
846
+ var connectionFields = {
847
+ transport: 0,
848
+ outputSize: 3,
849
+ outputFormat: 4,
850
+ inputSize: 6,
851
+ inputFormat: 7,
852
+ name: 12,
853
+ path: 14
854
+ };
855
+ var assemblyFields = {
856
+ name: 0,
857
+ path: 1,
858
+ size: 2,
859
+ descriptor: 3,
860
+ firstMember: 6
861
+ };
862
+ var isConnection = (key) => /^Connection\d+$/.test(key);
773
863
  function stripComments(text) {
774
864
  let clean = "";
775
865
  const offsets = [];
@@ -849,14 +939,15 @@ function edsSections(text) {
849
939
  if (!section) {
850
940
  throw new Error("EDS record outside a section.");
851
941
  }
942
+ const start = offsets[match.index];
943
+ const last = offsets[end - 1];
944
+ if (key === undefined || body === undefined || start === undefined || last === undefined) {
945
+ throw new Error("Malformed EDS record or section.");
946
+ }
852
947
  if (section.has(key)) {
853
948
  throw new Error(`Duplicate EDS record ${key}.`);
854
949
  }
855
- section.set(key, {
856
- fields: recordFields(body),
857
- start: offsets[match.index],
858
- end: offsets[end - 1] + 1
859
- });
950
+ section.set(key, { fields: recordFields(body), start, end: last + 1 });
860
951
  }
861
952
  if (clean.slice(end).trim()) {
862
953
  throw new Error("Unterminated EDS record.");
@@ -902,21 +993,29 @@ function logicalSegments(bytes) {
902
993
  ...logicalSegments(data.slice(length))
903
994
  ];
904
995
  }
905
- function logicalPath(path) {
906
- const bytes = path.trim() ? path.trim().split(/\s+/).map((token) => {
907
- if (!/^[0-9a-f]{2}$/i.test(token)) {
996
+ function pathBytes(path, params) {
997
+ return path.trim().split(/\s+/).filter(Boolean).flatMap((token) => {
998
+ if (/^[0-9a-f]{2}$/i.test(token)) {
999
+ return [parseInt(token, 16)];
1000
+ }
1001
+ const reference = /^\[(Param\d+)\]$/.exec(token)?.[1];
1002
+ const parameter = reference ? params.get(reference) : undefined;
1003
+ if (!parameter || parameter.default === undefined) {
908
1004
  throw new Error(`Unsupported EDS path token ${token}.`);
909
1005
  }
910
- return parseInt(token, 16);
911
- }) : [];
912
- const segments = logicalSegments(bytes);
1006
+ const value = parameter.default;
1007
+ return Array.from({ length: parameter.size }, (_, index) => Math.floor(value / 2 ** (index * 8)) % 256);
1008
+ });
1009
+ }
1010
+ function logicalPath(path, params) {
1011
+ const segments = logicalSegments(pathBytes(path, params));
913
1012
  return {
914
1013
  instance: segments.filter(({ type }) => type === 36).at(-1)?.value,
915
1014
  points: segments.filter(({ type }) => type === 44).map(({ value }) => value)
916
1015
  };
917
1016
  }
918
1017
  var optionalNumber = (value) => value?.trim() && Number.isFinite(Number(value)) ? Number(value) : undefined;
919
- function parseEds(text, file = "device.eds") {
1018
+ function parseEds(text, file) {
920
1019
  const records = readEdsRecords(text);
921
1020
  const device = records.Device;
922
1021
  if (!device?.ProdName?.[0]) {
@@ -935,6 +1034,7 @@ function parseEds(text, file = "device.eds") {
935
1034
  }));
936
1035
  const params = new Map(parameters.map((parameter) => [parameter.id, parameter]));
937
1036
  const instances = new Map;
1037
+ const recordless = new Map;
938
1038
  const size = (value) => {
939
1039
  if (!value) {
940
1040
  return;
@@ -953,18 +1053,24 @@ function parseEds(text, file = "device.eds") {
953
1053
  maximum: parameter.maximum
954
1054
  };
955
1055
  };
956
- const connections = Object.entries(records["Connection Manager"] ?? {}).filter(([id]) => /^Connection\d+$/.test(id)).map(([id, fields]) => {
957
- const path = fields[14] ?? "";
958
- const points = logicalPath(path).points;
959
- const assembly = (reference, point) => {
1056
+ const connections = Object.entries(records["Connection Manager"] ?? {}).filter(([id]) => isConnection(id)).map(([id, fields]) => {
1057
+ const path = fields[connectionFields.path] ?? "";
1058
+ const points = logicalPath(path, params).points;
1059
+ const outputSize = size(fields[connectionFields.outputSize]);
1060
+ const inputSize = size(fields[connectionFields.inputSize]);
1061
+ const assembly = (reference, point, payload) => {
960
1062
  if (!reference) {
961
- return;
1063
+ if (!payload || payload.value <= 0 || point === undefined) {
1064
+ return;
1065
+ }
1066
+ recordless.set(point, Math.max(recordless.get(point) ?? 0, payload.maximum ?? payload.value));
1067
+ return point;
962
1068
  }
963
1069
  const record = records.Assembly?.[reference];
964
1070
  if (!/^Assem\d+$/.test(reference) || !record) {
965
1071
  throw new Error(`${file}: unknown connection assembly ${reference}.`);
966
1072
  }
967
- const instance = point ?? logicalPath(record[1] ?? "").instance;
1073
+ const instance = point ?? logicalPath(record[assemblyFields.path] ?? "", params).instance;
968
1074
  if (instance === undefined) {
969
1075
  throw new Error(`${file}: no runtime instance for ${reference}.`);
970
1076
  }
@@ -977,19 +1083,19 @@ function parseEds(text, file = "device.eds") {
977
1083
  };
978
1084
  return {
979
1085
  id,
980
- name: fields[12] || id,
981
- owner: /^0x[\da-f]{8}$/i.test(fields[0] ?? "") && (Number(fields[0]) >>> 24 & 15) === 4,
1086
+ name: fields[connectionFields.name] || id,
1087
+ owner: /^0x[\da-f]{8}$/i.test(fields[connectionFields.transport] ?? "") && (Number(fields[connectionFields.transport]) >>> 24 & 15) === 4,
982
1088
  path,
983
- outputAssembly: assembly(fields[4], points.at(-2)),
984
- inputAssembly: assembly(fields[7], points.at(-1)),
985
- outputSize: size(fields[3]),
986
- inputSize: size(fields[6])
1089
+ outputAssembly: assembly(fields[connectionFields.outputFormat], points.at(-2), outputSize),
1090
+ inputAssembly: assembly(fields[connectionFields.inputFormat], points.at(-1), inputSize),
1091
+ outputSize,
1092
+ inputSize
987
1093
  };
988
1094
  });
989
1095
  const assemblies = Object.entries(records.Assembly ?? {}).filter(([id]) => /^Assem\d+$/.test(id)).map(([id, fields]) => {
990
1096
  const members = [];
991
1097
  let offsetBits = 0;
992
- for (let index = 6;index < fields.length; index += 2) {
1098
+ for (let index = assemblyFields.firstMember;index < fields.length; index += 2) {
993
1099
  if (!fields[index] && !fields[index + 1]) {
994
1100
  continue;
995
1101
  }
@@ -1012,13 +1118,31 @@ function parseEds(text, file = "device.eds") {
1012
1118
  });
1013
1119
  offsetBits += bits;
1014
1120
  }
1015
- const size = fields[2] ? integer(fields[2], `${id} size`, { minimum: 0 }) : Math.ceil(offsetBits / 8);
1121
+ const declared = fields[assemblyFields.size];
1122
+ const size = declared ? integer(declared, `${id} size`, { minimum: 0 }) : Math.ceil(offsetBits / 8);
1016
1123
  if (offsetBits > size * 8) {
1017
1124
  throw new Error(`${file}: ${id} members exceed its ${size} byte payload.`);
1018
1125
  }
1019
- const instance = logicalPath(fields[1] ?? "").instance ?? instances.get(id);
1020
- return { id, instance, name: fields[0] || id, size, members };
1126
+ const instance = logicalPath(fields[assemblyFields.path] ?? "", params).instance ?? instances.get(id);
1127
+ return {
1128
+ id,
1129
+ instance,
1130
+ name: fields[assemblyFields.name] || id,
1131
+ size,
1132
+ members
1133
+ };
1021
1134
  });
1135
+ for (const [instance, payloadSize] of recordless) {
1136
+ if (!assemblies.some((assembly) => assembly.instance === instance)) {
1137
+ assemblies.push({
1138
+ id: `Instance${instance}`,
1139
+ instance,
1140
+ name: `Assembly ${instance}`,
1141
+ size: payloadSize,
1142
+ members: []
1143
+ });
1144
+ }
1145
+ }
1022
1146
  return {
1023
1147
  file,
1024
1148
  name: device.ProdName[0],
@@ -1029,70 +1153,10 @@ function parseEds(text, file = "device.eds") {
1029
1153
  connections
1030
1154
  };
1031
1155
  }
1032
-
1033
- // packages/typegen/src/hardware/process-image.ts
1034
- import { ioArray, ioScalar, sizePrefix } from "@tsplc/iec";
1035
- function ioLayout(type) {
1036
- const array = ioArray(type.trim());
1037
- if (array) {
1038
- const element = ioLayout(array.element);
1039
- return element && element !== "BOOL" ? `${array.length}x${element}` : undefined;
1040
- }
1041
- const scalar = ioScalar(type);
1042
- if (scalar?.family === "integer" || scalar?.family === "bits") {
1043
- return `INT${scalar.bits}`;
1044
- }
1045
- return scalar?.name;
1046
- }
1047
- var addressSize = (bits) => bits === 64 ? undefined : sizePrefix(bits);
1048
- function directAddress(region, base, offsetBits, bits) {
1049
- const size = addressSize(bits);
1050
- if (!size) {
1051
- return;
1052
- }
1053
- const byte = base + Math.floor(offsetBits / 8);
1054
- if (bits === 1) {
1055
- return `%${region}X${byte}.${offsetBits % 8}`;
1056
- }
1057
- if ((base * 8 + offsetBits) % bits) {
1058
- return;
1059
- }
1060
- return `%${region}${size}${byte / (bits / 8)}`;
1061
- }
1062
- var byteOffset = (address) => Number(address.slice(3));
1063
- function regionPlacer(regions, { generatedTree }) {
1064
- const taken = regions.flatMap(({ region, size, address }) => address ? [
1065
- {
1066
- region,
1067
- start: byteOffset(address),
1068
- end: byteOffset(address) + size
1069
- }
1070
- ] : []);
1071
- const cursors = { I: 0, Q: 0 };
1072
- const aligned = (offset) => Math.ceil(offset / 4) * 4;
1073
- return ({ id, region, size, address }) => {
1074
- if (address) {
1075
- return address;
1076
- }
1077
- if (!generatedTree) {
1078
- throw new Error(`${id}: set the %${region}B address the template assigns to this assembly, or let codesys.deviceTree place it.`);
1079
- }
1080
- const clear = (start) => {
1081
- const overlap = taken.find((item) => item.region === region && item.start < start + size && start < item.end);
1082
- return overlap ? clear(aligned(overlap.end)) : start;
1083
- };
1084
- const start = clear(aligned(cursors[region]));
1085
- taken.push({ region, start, end: start + size });
1086
- cursors[region] = start + size;
1087
- return `%${region}B${start}`;
1088
- };
1089
- }
1090
-
1091
- // packages/typegen/src/device-tree.ts
1092
1156
  var quoted = (value) => `"${value.replaceAll('"', '""')}"`;
1093
1157
  function normalizeEds(text, selection) {
1094
1158
  const sections = edsSections(text);
1095
- const connections = [...sections.get("Connection Manager") ?? []].filter(([key]) => /^Connection\d+$/.test(key));
1159
+ const connections = [...sections.get("Connection Manager") ?? []].filter(([key]) => isConnection(key));
1096
1160
  const selected = connections.find(([key]) => key === selection.connection)?.[1];
1097
1161
  if (!selected) {
1098
1162
  throw new Error(`EDS has no ${selection.connection}.`);
@@ -1100,8 +1164,16 @@ function normalizeEds(text, selection) {
1100
1164
  const fields = [...selected.fields];
1101
1165
  const resized = new Map;
1102
1166
  for (const [sizeField, formatField, size] of [
1103
- [3, 4, selection.outputSize],
1104
- [6, 7, selection.inputSize]
1167
+ [
1168
+ connectionFields.outputSize,
1169
+ connectionFields.outputFormat,
1170
+ selection.outputSize
1171
+ ],
1172
+ [
1173
+ connectionFields.inputSize,
1174
+ connectionFields.inputFormat,
1175
+ selection.inputSize
1176
+ ]
1105
1177
  ]) {
1106
1178
  const assembly = fields[formatField];
1107
1179
  if (!assembly) {
@@ -1116,19 +1188,19 @@ function normalizeEds(text, selection) {
1116
1188
  const edits = connections.map(([, record]) => ({
1117
1189
  start: record.start,
1118
1190
  end: record.end,
1119
- text: record === selected ? `Connection1 = ${fields.map((value, index) => index >= 12 ? quoted(value) : value).join(",")};` : ""
1191
+ text: record === selected ? `Connection1 = ${fields.map((value, index) => index >= connectionFields.name ? quoted(value) : value).join(",")};` : ""
1120
1192
  }));
1121
1193
  for (const [key, record] of sections.get("Assembly") ?? []) {
1122
1194
  const size = resized.get(key);
1123
1195
  if (size === undefined) {
1124
1196
  continue;
1125
1197
  }
1126
- const [name = "", path = "", , descriptor = ""] = record.fields;
1198
+ const path = record.fields[assemblyFields.path] ?? "";
1127
1199
  const rawBytes = [
1128
- quoted(name),
1200
+ quoted(record.fields[assemblyFields.name] ?? ""),
1129
1201
  path && quoted(path),
1130
1202
  size,
1131
- descriptor,
1203
+ record.fields[assemblyFields.descriptor] ?? "",
1132
1204
  "",
1133
1205
  "",
1134
1206
  size * 8,
@@ -1146,6 +1218,77 @@ function normalizeEds(text, selection) {
1146
1218
  }
1147
1219
  return edits.sort((a, b) => b.start - a.start).reduce((result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end), text);
1148
1220
  }
1221
+
1222
+ // packages/typegen/src/hardware/process-image.ts
1223
+ import {
1224
+ elementaryTypes as elementaryTypes2,
1225
+ ioArray,
1226
+ ioScalar,
1227
+ isIntegerValued as isIntegerValued3,
1228
+ isWholeValue as isWholeValue2,
1229
+ sizePrefix,
1230
+ sizePrefixes
1231
+ } from "@tsplc/iec";
1232
+ var scalarLayout = (scalar) => isIntegerValued3(scalar) ? `INT${scalar.bits}` : scalar.name;
1233
+ var scalarLayoutBits = new Map(elementaryTypes2.filter(isWholeValue2).map((scalar) => [scalarLayout(scalar), scalar.bits]));
1234
+ function ioLayout(type) {
1235
+ const array = ioArray(type.trim());
1236
+ if (array) {
1237
+ const element = ioLayout(array.element);
1238
+ return element && element !== "BOOL" ? `${array.length}x${element}` : undefined;
1239
+ }
1240
+ const scalar = ioScalar(type);
1241
+ return scalar && scalarLayout(scalar);
1242
+ }
1243
+ var layoutBits = (layout) => scalarLayoutBits.get(layout.replace(/^\d+x/, ""));
1244
+ var addressSize = (bits) => bits === 64 ? undefined : sizePrefix(bits);
1245
+ function directAddress(region, base, offsetBits, bits) {
1246
+ const size = addressSize(bits);
1247
+ if (!size) {
1248
+ return;
1249
+ }
1250
+ const byte = base + Math.floor(offsetBits / 8);
1251
+ if (bits === 1) {
1252
+ return `%${region}X${byte}.${offsetBits % 8}`;
1253
+ }
1254
+ if ((base * 8 + offsetBits) % bits) {
1255
+ return;
1256
+ }
1257
+ return `%${region}${size}${byte / (bits / 8)}`;
1258
+ }
1259
+ function addressBits(address) {
1260
+ const [, region, size, index, bit] = /^%([IQ])([A-Z])(\d+)(?:\.([0-7]))?$/.exec(address) ?? [];
1261
+ const bits = size === undefined ? undefined : sizePrefixes.get(size)?.bits;
1262
+ if (region !== "I" && region !== "Q" || bits === undefined || addressSize(bits) !== size || bits === 1 !== (bit !== undefined)) {
1263
+ return;
1264
+ }
1265
+ const offsetBits = bits === 1 ? Number(index) * 8 + Number(bit) : Number(index) * bits;
1266
+ return { region, offsetBits, bits };
1267
+ }
1268
+ var regionOf = (direction) => direction === "input" ? "I" : "Q";
1269
+ function regionPlacer(regions, { generatedTree }) {
1270
+ const taken = regions.flatMap(({ region, size, offset }) => offset === undefined ? [] : [{ region, start: offset, end: offset + size }]);
1271
+ const cursors = { I: 0, Q: 0 };
1272
+ const aligned = (offset) => Math.ceil(offset / 4) * 4;
1273
+ return ({ id, region, size, offset }) => {
1274
+ if (offset !== undefined) {
1275
+ return offset;
1276
+ }
1277
+ if (!generatedTree) {
1278
+ throw new Error(`${id}: set the %${region}B address the template assigns to this assembly, or let codesys.deviceTree place it.`);
1279
+ }
1280
+ const clear = (start) => {
1281
+ const overlap = taken.find((item) => item.region === region && item.start < start + size && start < item.end);
1282
+ return overlap ? clear(aligned(overlap.end)) : start;
1283
+ };
1284
+ const start = clear(aligned(cursors[region]));
1285
+ taken.push({ region, start, end: start + size });
1286
+ cursors[region] = start + size;
1287
+ return start;
1288
+ };
1289
+ }
1290
+
1291
+ // packages/typegen/src/device-tree.ts
1149
1292
  async function deviceTree(config, catalog) {
1150
1293
  const settings = config.codesys?.deviceTree;
1151
1294
  if (!settings) {
@@ -1169,21 +1312,20 @@ async function deviceTree(config, catalog) {
1169
1312
  if (!("device" in binding) || binding.device !== device.id) {
1170
1313
  return [];
1171
1314
  }
1172
- const channel = device.channels.find((item) => item.id === binding.channel);
1315
+ const channel = boundChannel(catalog, key, binding);
1173
1316
  if (channel.assembly === undefined) {
1174
1317
  return [];
1175
1318
  }
1176
1319
  if (channel.bits === 1) {
1177
1320
  return [{ address: channel.address, text: key }];
1178
1321
  }
1179
- const area = channel.direction === "input" ? inputs : outputs;
1322
+ const location = addressBits(channel.address);
1323
+ const address = location && directAddress(location.region, 0, location.offsetBits, 8);
1324
+ if (!address) {
1325
+ throw new Error(`${key}: channel ${binding.device}.${binding.channel} does not start on a byte.`);
1326
+ }
1180
1327
  const bytes = channel.bits / 8;
1181
- return [
1182
- {
1183
- address: `${area.address.slice(0, 3)}${byteOffset(area.address) + channel.offsetBits / 8}`,
1184
- text: bytes > 1 ? `${key} (${bytes} bytes)` : key
1185
- }
1186
- ];
1328
+ return [{ address, text: bytes > 1 ? `${key} (${bytes} bytes)` : key }];
1187
1329
  });
1188
1330
  const network = config.devices[device.id]?.network;
1189
1331
  if (device.modbus && !network?.address) {
@@ -1191,7 +1333,7 @@ async function deviceTree(config, catalog) {
1191
1333
  }
1192
1334
  return {
1193
1335
  name: device.id,
1194
- eds: normalizeEds(await readFile2(device.descriptor, "utf8"), {
1336
+ eds: normalizeEds(await readFile3(device.descriptor, "utf8"), {
1195
1337
  connection: connection.id,
1196
1338
  inputSize: inputs?.size,
1197
1339
  outputSize: outputs?.size
@@ -1213,11 +1355,12 @@ async function deviceTree(config, catalog) {
1213
1355
  return { ethernet: settings.ethernet ?? {}, devices: [first, ...rest] };
1214
1356
  }
1215
1357
  // packages/typegen/src/hardware.ts
1216
- import { readdir as readdir2, readFile as readFile3 } from "node:fs/promises";
1358
+ import { readFile as readFile4 } from "node:fs/promises";
1217
1359
  import { resolve } from "node:path";
1360
+ import { tsplcConfigSchema } from "@tsplc/config/schema";
1218
1361
 
1219
1362
  // packages/typegen/src/hardware/channels.ts
1220
- import { ioScalarBits } from "@tsplc/iec";
1363
+ import { arrayTypeText, ioScalarBits } from "@tsplc/iec";
1221
1364
  function assemblyChannels({
1222
1365
  device,
1223
1366
  direction,
@@ -1227,7 +1370,7 @@ function assemblyChannels({
1227
1370
  payloadSize
1228
1371
  }) {
1229
1372
  const prefix = `${direction}s`;
1230
- const region = direction === "input" ? "I" : "Q";
1373
+ const region = regionOf(direction);
1231
1374
  const payloadBits = payloadSize * 8;
1232
1375
  const address = (offsetBits, bits) => directAddress(region, base, offsetBits, bits);
1233
1376
  const channels = [];
@@ -1305,7 +1448,11 @@ function assemblyChannels({
1305
1448
  const span = {
1306
1449
  ...channel,
1307
1450
  bits: length * scalarBits,
1308
- type: `ARRAY[0..${length - 1}] OF ${member.type}`,
1451
+ type: arrayTypeText({
1452
+ lower: 0,
1453
+ upper: length - 1,
1454
+ element: member.type
1455
+ }),
1309
1456
  address: address(member.offsetBits, scalarBits)
1310
1457
  };
1311
1458
  channels.push(span);
@@ -1333,21 +1480,35 @@ function placeModbusRegisters(device, registers, place) {
1333
1480
  if (!entries.length) {
1334
1481
  return [];
1335
1482
  }
1336
- const outputBase = byteOffset(place({ id: device, region: "Q", size: entries.length * registerBytes.Q }));
1337
- const inputBase = byteOffset(place({ id: device, region: "I", size: entries.length * registerBytes.I }));
1483
+ const outputBase = place({
1484
+ id: device,
1485
+ region: "Q",
1486
+ size: entries.length * registerBytes.Q
1487
+ });
1488
+ const inputBase = place({
1489
+ id: device,
1490
+ region: "I",
1491
+ size: entries.length * registerBytes.I
1492
+ });
1338
1493
  return entries.map(([name, offset], index) => {
1339
- const channel = (field, direction, offsetBits, bits, type, description) => ({
1340
- device,
1341
- id: `modbus.${name}.${field}`,
1342
- name: `${name} ${field}`,
1343
- direction,
1344
- offsetBits,
1345
- bits,
1346
- type,
1347
- address: directAddress(direction === "input" ? "I" : "Q", direction === "input" ? inputBase + index * registerBytes.I : outputBase + index * registerBytes.Q, offsetBits, bits),
1348
- unit: "",
1349
- description
1350
- });
1494
+ const channel = (field, direction, offsetBits, bits, type, description) => {
1495
+ const address = directAddress(regionOf(direction), direction === "input" ? inputBase + index * registerBytes.I : outputBase + index * registerBytes.Q, offsetBits, bits);
1496
+ if (!address) {
1497
+ throw new Error(`${device}: Modbus register ${name} ${field} has no direct address.`);
1498
+ }
1499
+ return {
1500
+ device,
1501
+ id: `modbus.${name}.${field}`,
1502
+ name: `${name} ${field}`,
1503
+ direction,
1504
+ offsetBits,
1505
+ bits,
1506
+ type,
1507
+ address,
1508
+ unit: "",
1509
+ description
1510
+ };
1511
+ };
1351
1512
  const value = channel("value", "output", 0, 16, "WORD", "Value to write");
1352
1513
  const write = channel("write", "output", 16, 1, "BOOL", "Writes the value when it rises");
1353
1514
  const status = channel("status", "input", 0, 8, "BYTE", "The last answer: 0 accepted, otherwise the exception code");
@@ -1386,6 +1547,14 @@ function selectConnection(id, settings, descriptor) {
1386
1547
  const choices = compatible.map((item) => `${item.id} "${item.name}" (in ${item.inputAssembly ?? "-"}, out ${item.outputAssembly ?? "-"})`).join(", ");
1387
1548
  throw new Error(`${id}: select connection; ${settings.file} offers ${choices}.`);
1388
1549
  }
1550
+ function configuredByte(id, direction, address) {
1551
+ const region = regionOf(direction);
1552
+ const location = addressBits(address);
1553
+ if (location?.region !== region || location.bits !== 8) {
1554
+ throw new Error(`${id}: ${direction} assembly needs a %${region}B address.`);
1555
+ }
1556
+ return location.offsetBits / 8;
1557
+ }
1389
1558
  function selectAssemblies(id, settings, descriptor, connection) {
1390
1559
  return ["input", "output"].flatMap((direction) => {
1391
1560
  const selection = direction === "input" ? settings.inputs : settings.outputs;
@@ -1400,10 +1569,8 @@ function selectAssemblies(id, settings, descriptor, connection) {
1400
1569
  if (!assembly) {
1401
1570
  throw new Error(`${id}: assembly ${instance} is not present in ${settings.file}.`);
1402
1571
  }
1403
- const region = direction === "input" ? "I" : "Q";
1404
- if (selection?.address && !selection.address.startsWith(`%${region}B`)) {
1405
- throw new Error(`${id}: ${direction} assembly needs a %${region}B address.`);
1406
- }
1572
+ const region = regionOf(direction);
1573
+ const offset = selection?.address === undefined ? undefined : configuredByte(id, direction, selection.address);
1407
1574
  const declaredSize = direction === "input" ? connection?.inputSize : connection?.outputSize;
1408
1575
  const payloadSize = selection?.size ?? declaredSize?.value ?? assembly.size;
1409
1576
  if (!Number.isSafeInteger(payloadSize) || payloadSize <= 0 || payloadSize > assembly.size || declaredSize?.minimum !== undefined && payloadSize < declaredSize.minimum || declaredSize?.maximum !== undefined && payloadSize > declaredSize.maximum || selection?.size !== undefined && declaredSize && !declaredSize.parameter && payloadSize !== declaredSize.value) {
@@ -1417,29 +1584,49 @@ function selectAssemblies(id, settings, descriptor, connection) {
1417
1584
  instance,
1418
1585
  assembly,
1419
1586
  size: payloadSize,
1420
- address: selection?.address
1587
+ offset
1421
1588
  }
1422
1589
  ];
1423
1590
  });
1424
1591
  }
1425
1592
 
1426
1593
  // packages/typegen/src/hardware.ts
1427
- import { ioScalarBits as ioScalarBits3 } from "@tsplc/iec";
1594
+ import { ioScalarBits as ioScalarBits2 } from "@tsplc/iec";
1428
1595
 
1429
1596
  // packages/typegen/src/hardware/mapping-types.ts
1430
- import { ioScalarBits as ioScalarBits2 } from "@tsplc/iec";
1597
+ import { relative, sep } from "node:path";
1598
+ import { sizePrefixes as sizePrefixes2 } from "@tsplc/iec";
1599
+ var region = '${"I" | "Q"}';
1600
+ var bitAddress = `\`%${region}X\${number}.\${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}\``;
1601
+ var byteSizes = [...sizePrefixes2].filter(([prefix, type]) => type.bits > 1 && addressSize(type.bits) === prefix).map(([prefix]) => JSON.stringify(prefix)).join(" | ");
1602
+ var addressBinding = (address) => `{ address: ${address}; type?: string }`;
1431
1603
  var directBinding = (layout) => {
1432
- const scalar = layout.replace(/^\d+x/, "");
1433
- const integer = /^INT(\d+)$/.exec(scalar);
1434
- const bits = integer ? Number(integer[1]) : ioScalarBits2(scalar);
1604
+ const bits = layoutBits(layout);
1435
1605
  const size = bits === undefined ? undefined : addressSize(bits);
1436
1606
  if (!size) {
1437
1607
  return;
1438
1608
  }
1439
- return size === "X" ? '{ address: `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }' : `{ address: \`%\${"I" | "Q"}${size}\${number}\`; type?: string }`;
1609
+ return addressBinding(size === "X" ? bitAddress : `\`%${region}${size}\${number}\``);
1610
+ };
1611
+ var portableCatalog = (catalog, root) => {
1612
+ const portable = (file) => relative(root, file).split(sep).join("/");
1613
+ return {
1614
+ descriptors: catalog.descriptors.map((descriptor) => ({
1615
+ ...descriptor,
1616
+ file: portable(descriptor.file)
1617
+ })),
1618
+ devices: catalog.devices.map((device) => ({
1619
+ ...device,
1620
+ descriptor: portable(device.descriptor)
1621
+ }))
1622
+ };
1440
1623
  };
1441
- function generateHardwareTypes(catalog, targets, publication, ioTypes = true) {
1442
- const selectors = publication?.map((selector) => JSON.stringify(selector)).join(" | ") ?? "string";
1624
+ function generateHardwareTypes(catalog, {
1625
+ root,
1626
+ targets,
1627
+ ioTypes
1628
+ }) {
1629
+ const selectors = targets?.publication.map((selector) => JSON.stringify(selector)).join(" | ") ?? "string";
1443
1630
  const publicationTypes = `// Generated by tsPLC. Run tsplc typegen after changing EDS files, device selections or PLC storage.
1444
1631
  export type PublicationSelector = ${selectors || "never"};
1445
1632
  export type PlcPublication = { readonly production: readonly PublicationSelector[]; readonly development: readonly PublicationSelector[] };
@@ -1452,11 +1639,11 @@ export type PlcPublication = { readonly production: readonly PublicationSelector
1452
1639
  binding: channel(device.id, item.id, item.direction === "input" && item.type === "BOOL" ? "; inverted?: boolean; shared?: boolean" : ""),
1453
1640
  layout: ioLayout(item.type)
1454
1641
  })));
1455
- const direct = '{ address: `%${"I" | "Q"}${"B" | "W" | "D"}${number}` | `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }';
1642
+ const direct = addressBinding(`\`%${region}\${${byteSizes}}\${number}\` | ${bitAddress}`);
1456
1643
  const anyBinding = [...channels.map((item) => item.binding), direct].join(`
1457
1644
  | `);
1458
- const mapping = targets ? [...new Set(targets.map((target) => target.layout))].sort().map((layout) => {
1459
- const keys = targets.filter((target) => target.layout === layout).map((target) => `\`${target.key}\``);
1645
+ const mapping = targets ? [...new Set(targets.io.map((target) => target.layout))].sort().map((layout) => {
1646
+ const keys = targets.io.filter((target) => target.layout === layout).map((target) => `\`${target.key}\``);
1460
1647
  const bindings = [
1461
1648
  ...channels.filter((item) => item.layout === layout).map((item) => item.binding),
1462
1649
  directBinding(layout)
@@ -1467,45 +1654,37 @@ export type PlcPublication = { readonly production: readonly PublicationSelector
1467
1654
  }).join(" & ") || "Readonly<Record<string, never>>" : "Readonly<Record<string, HardwareIoBinding>>";
1468
1655
  return `${publicationTypes}export type HardwareIoBinding = ${anyBinding};
1469
1656
  export type HardwareIoMapping = ${mapping};
1470
- export const hardware = ${JSON.stringify(catalog, null, 2)} as const;
1657
+ export const hardware = ${JSON.stringify(portableCatalog(catalog, root), null, 2)} as const;
1471
1658
  `;
1472
1659
  }
1473
1660
 
1474
1661
  // packages/typegen/src/hardware.ts
1475
- async function edsFiles(directory) {
1476
- const entries = await readdir2(directory, { withFileTypes: true }).catch((cause) => {
1477
- if (cause && typeof cause === "object" && "code" in cause && cause.code === "ENOENT") {
1478
- return [];
1479
- }
1480
- throw cause;
1481
- });
1482
- const files = [];
1483
- for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
1484
- const path = resolve(directory, entry.name);
1485
- if (entry.isDirectory()) {
1486
- files.push(...await edsFiles(path));
1487
- } else if (entry.isFile() && /\.eds$/i.test(entry.name)) {
1488
- files.push(path);
1489
- }
1662
+ var defaultEds = tsplcConfigSchema.shape.eds.parse(undefined);
1663
+ var edsFiles = (config, directory) => filesUnder(directory, "eds", (a, b) => a.localeCompare(b)).catch((error) => {
1664
+ if (config.eds === defaultEds && isMissingFile(error)) {
1665
+ return [];
1490
1666
  }
1491
- return files;
1492
- }
1667
+ throw error;
1668
+ });
1493
1669
  async function readDescriptors(config, root) {
1494
1670
  const files = new Set;
1495
1671
  for (const directory of [config.eds].flat()) {
1496
- for (const file of await edsFiles(resolve(root, directory))) {
1672
+ for (const file of await edsFiles(config, resolve(root, directory))) {
1497
1673
  files.add(file);
1498
1674
  }
1499
1675
  }
1500
1676
  for (const device of Object.values(config.devices)) {
1501
1677
  files.add(resolve(root, device.file));
1502
1678
  }
1503
- return Promise.all([...files].map(async (file) => parseEds(await readFile3(file, "utf8"), file)));
1679
+ return new Map(await Promise.all([...files].map(async (file) => [file, parseEds(await readFile4(file, "utf8"), file)])));
1504
1680
  }
1505
1681
  async function loadHardware(config, root) {
1506
1682
  const descriptors = await readDescriptors(config, root);
1507
1683
  const selected = Object.entries(config.devices).map(([id, settings]) => {
1508
- const descriptor = descriptors.find((d) => d.file === resolve(root, settings.file));
1684
+ const descriptor = descriptors.get(resolve(root, settings.file));
1685
+ if (!descriptor) {
1686
+ throw new Error(`${id}: ${settings.file} was not read.`);
1687
+ }
1509
1688
  const connection = selectConnection(id, settings, descriptor);
1510
1689
  const selections = selectAssemblies(id, settings, descriptor, connection);
1511
1690
  return { id, settings, descriptor, connection, selections };
@@ -1513,10 +1692,14 @@ async function loadHardware(config, root) {
1513
1692
  const place = regionPlacer(selected.flatMap((device) => device.selections), { generatedTree: config.codesys?.deviceTree !== undefined });
1514
1693
  const placed = selected.map((device) => ({
1515
1694
  ...device,
1516
- assemblies: device.selections.map((selection) => ({
1517
- ...selection,
1518
- address: place(selection)
1519
- }))
1695
+ assemblies: device.selections.map((selection) => {
1696
+ const offset = place(selection);
1697
+ const address = directAddress(selection.region, offset, 0, 8);
1698
+ if (!address) {
1699
+ throw new Error(`${device.id}: byte ${offset} has no direct address.`);
1700
+ }
1701
+ return { ...selection, offset, address };
1702
+ })
1520
1703
  }));
1521
1704
  const devices = placed.map(({ id, settings, descriptor, connection, assemblies }) => {
1522
1705
  const registers = placeModbusRegisters(id, settings.modbus?.registers ?? {}, place);
@@ -1538,12 +1721,12 @@ async function loadHardware(config, root) {
1538
1721
  })),
1539
1722
  channels: [
1540
1723
  ...registers.flatMap((register) => register.channels),
1541
- ...assemblies.flatMap(({ direction, instance, assembly, size, address }) => assemblyChannels({
1724
+ ...assemblies.flatMap(({ direction, instance, assembly, size, offset }) => assemblyChannels({
1542
1725
  device: id,
1543
1726
  direction,
1544
1727
  instance,
1545
1728
  members: assembly.members,
1546
- base: byteOffset(address),
1729
+ base: offset,
1547
1730
  payloadSize: size
1548
1731
  }))
1549
1732
  ],
@@ -1556,18 +1739,14 @@ async function loadHardware(config, root) {
1556
1739
  }
1557
1740
  };
1558
1741
  });
1559
- return { descriptors, devices };
1742
+ return { descriptors: [...descriptors.values()], devices };
1560
1743
  }
1561
1744
  function resolveIo(config, catalog) {
1562
1745
  return Object.fromEntries(Object.entries(config.io).map(([symbol, binding]) => {
1563
1746
  if ("address" in binding) {
1564
1747
  return [symbol, binding];
1565
1748
  }
1566
- const device = catalog.devices.find((d) => d.id === binding.device);
1567
- const channel = device?.channels.find((c) => c.id === binding.channel);
1568
- if (!channel?.address) {
1569
- throw new Error(`${symbol}: unknown or unaddressable channel ${binding.device}.${binding.channel}.`);
1570
- }
1749
+ const channel = boundChannel(catalog, symbol, binding);
1571
1750
  return [
1572
1751
  symbol,
1573
1752
  {
@@ -1580,73 +1759,92 @@ function resolveIo(config, catalog) {
1580
1759
  }));
1581
1760
  }
1582
1761
  // packages/typegen/src/project.ts
1583
- import { mkdir, readFile as readFile5, rename, writeFile } from "node:fs/promises";
1584
- import { dirname, resolve as resolve2 } from "node:path";
1762
+ import { resolve as resolve2 } from "node:path";
1585
1763
  import {
1586
1764
  ioSymbolsSchema,
1587
- loadTsplcConfig,
1588
1765
  publicationSchema,
1589
- typegenSchema
1766
+ typegenSettings
1590
1767
  } from "@tsplc/config";
1591
1768
  import {
1592
1769
  emittedFiles,
1593
1770
  emittedStDirectory,
1594
- projectSnapshotFile
1771
+ projectSnapshotFile,
1772
+ stRoot
1595
1773
  } from "@tsplc/config/project-files";
1596
- import { format } from "prettier";
1774
+ import { isWithin } from "@tsplc/iec/st";
1597
1775
 
1598
1776
  // packages/typegen/src/codegen/declarations.ts
1599
- import { readFile as readFile4 } from "node:fs/promises";
1600
- import { blockCommentEnd as blockCommentEnd2, lineCommentEnd as lineCommentEnd2 } from "@tsplc/iec/st";
1601
- var codeStart = (text, offset) => {
1602
- const start = offset + text.slice(offset).search(/\S|$/);
1603
- if (text.startsWith("(*", start)) {
1604
- const end = blockCommentEnd2(text, start);
1605
- return end === null ? start : codeStart(text, end);
1606
- }
1607
- if (text.startsWith("//", start)) {
1608
- return codeStart(text, lineCommentEnd2(text, start));
1609
- }
1610
- if (text.startsWith("{", start)) {
1611
- const end = text.indexOf("}", start);
1612
- return end < 0 ? start : codeStart(text, end + 1);
1613
- }
1614
- return start;
1615
- };
1777
+ import { readFile as readFile5 } from "node:fs/promises";
1616
1778
  var declarationFiles = async (files) => {
1617
1779
  const sorted = {
1618
1780
  types: [],
1619
1781
  globals: []
1620
1782
  };
1621
1783
  for (const file of files) {
1622
- const text = await readFile4(file, "utf8");
1623
- const code = text.slice(codeStart(text, 0));
1624
- if (/^TYPE\b/i.test(code)) {
1784
+ const keyword = firstCodeToken({
1785
+ name: file,
1786
+ text: await readFile5(file, "utf8")
1787
+ })?.toUpperCase();
1788
+ if (keyword === "TYPE") {
1625
1789
  sorted.types.push(file);
1626
- } else if (/^VAR_GLOBAL\b/i.test(code)) {
1790
+ } else if (keyword === "VAR_GLOBAL") {
1627
1791
  sorted.globals.push(file);
1628
1792
  }
1629
1793
  }
1630
1794
  return sorted;
1631
1795
  };
1632
1796
 
1633
- // packages/typegen/src/project.ts
1797
+ // packages/typegen/src/outputs.ts
1798
+ import { randomUUID } from "node:crypto";
1799
+ import { mkdir, rename, rm, writeFile } from "node:fs/promises";
1800
+ import { dirname } from "node:path";
1801
+ import { format } from "prettier";
1634
1802
  var formatTypeScript = (source) => format(source, { parser: "typescript" });
1635
- var readPublication = async (root) => publicationSchema.parse(JSON.parse(await readFile5(resolve2(root, emittedStDirectory, emittedFiles.publication), "utf8")));
1803
+ async function writeOutputs(outputs) {
1804
+ for (const { path, content } of outputs) {
1805
+ if (content === null) {
1806
+ await rm(path, { force: true });
1807
+ continue;
1808
+ }
1809
+ await mkdir(dirname(path), { recursive: true });
1810
+ const temporary = `${path}.${randomUUID()}.tmp`;
1811
+ try {
1812
+ await writeFile(temporary, content);
1813
+ await rename(temporary, path);
1814
+ } finally {
1815
+ await rm(temporary, { force: true });
1816
+ }
1817
+ }
1818
+ }
1819
+ async function checkOutputs(outputs) {
1820
+ for (const { path, content } of outputs) {
1821
+ const actual = await readIfPresent(path);
1822
+ const normalized = actual !== null && /\.ts$/i.test(path) ? await formatTypeScript(actual).catch(() => actual) : actual;
1823
+ if (normalized !== content) {
1824
+ throw new Error(`Generated file is missing or stale: ${path}`);
1825
+ }
1826
+ }
1827
+ }
1828
+
1829
+ // packages/typegen/src/project.ts
1830
+ var emittedPath = (root, file) => resolve2(root, emittedStDirectory, file);
1831
+ var missingEmission = (root) => new Error(`No emitted Structured Text in ${resolve2(root, emittedStDirectory)}: emit the program with tsplc build --emit-only, or check with tsplc typegen --check, which emits it first.`);
1832
+ var readPublication = async (root) => {
1833
+ const text = await readIfPresent(emittedPath(root, emittedFiles.publication));
1834
+ if (text === null) {
1835
+ throw missingEmission(root);
1836
+ }
1837
+ return publicationSchema.parse(JSON.parse(text));
1838
+ };
1636
1839
  var generatedFiles = {
1637
1840
  hardware: "hardware.ts",
1638
1841
  contract: "plc.ts",
1639
1842
  machines: "machines.ts"
1640
1843
  };
1641
1844
  async function readIoSymbols(root) {
1642
- const file = resolve2(root, emittedStDirectory, emittedFiles.ioSymbols);
1643
- const text = await readFile5(file, "utf8").catch((error) => {
1644
- if (error instanceof Error && "code" in error && error.code === "ENOENT") {
1645
- return "{}";
1646
- }
1647
- throw error;
1648
- });
1649
- const symbols = ioSymbolsSchema.safeParse(JSON.parse(text));
1845
+ const file = emittedPath(root, emittedFiles.ioSymbols);
1846
+ const text = await readIfPresent(file);
1847
+ const symbols = ioSymbolsSchema.safeParse(JSON.parse(text ?? "{}"));
1650
1848
  if (!symbols.success) {
1651
1849
  throw new Error(`Invalid IO symbols in ${file}`, { cause: symbols.error });
1652
1850
  }
@@ -1657,6 +1855,7 @@ async function contractSources(config, root, settings) {
1657
1855
  const types = directories(settings.types);
1658
1856
  const globals = directories(settings.globals);
1659
1857
  if (types.length || globals.length) {
1858
+ const filesIn = async (directories) => (await Promise.all(directories.map(stFiles))).flat();
1660
1859
  const sources = {
1661
1860
  types: await filesIn(types),
1662
1861
  globals: await filesIn(globals),
@@ -1667,56 +1866,32 @@ async function contractSources(config, root, settings) {
1667
1866
  }
1668
1867
  return sources;
1669
1868
  }
1670
- const source = config.compiler ? emittedStDirectory : config.build?.sourceDir;
1869
+ const source = stRoot(config);
1671
1870
  if (!source) {
1672
- if (config.typegen) {
1673
- throw new Error("Configure build.sourceDir or typegen.types/globals to generate PLC types.");
1674
- }
1675
- return;
1871
+ throw new Error("Configure build.sourceDir or typegen.types/globals to generate PLC types.");
1676
1872
  }
1677
1873
  const sourceRoot = resolve2(root, source);
1678
- const files = await stFiles(sourceRoot);
1874
+ const files = await stFiles(sourceRoot).catch((cause) => {
1875
+ if (!isMissingFile(cause)) {
1876
+ throw cause;
1877
+ }
1878
+ throw config.compiler ? missingEmission(root) : new Error(`build.sourceDir ${sourceRoot} doesn't exist.`);
1879
+ });
1679
1880
  if (!files.length) {
1680
1881
  throw new Error(`no .st declarations found in ${sourceRoot}`);
1681
1882
  }
1682
1883
  return { ...await declarationFiles(files), explicit: false };
1683
1884
  }
1684
- async function filesIn(directories) {
1685
- const files = [];
1686
- for (const directory of directories) {
1687
- files.push(...await stFiles(directory));
1688
- }
1689
- return files;
1690
- }
1691
1885
  function checkHmiTargets(controls, published) {
1692
1886
  for (const { target } of controls) {
1693
- if (!published.some((symbol) => target === symbol || target.startsWith(`${symbol}.`) || target.startsWith(`${symbol}[`))) {
1887
+ if (!published.some((symbol) => isWithin(symbol, target))) {
1694
1888
  throw new Error(`HMI control ${target} is not in the production publication.`);
1695
1889
  }
1696
1890
  }
1697
1891
  }
1698
- async function writeOutputs(outputs) {
1699
- for (const output of outputs) {
1700
- await mkdir(dirname(output.path), { recursive: true });
1701
- const temp = `${output.path}.${process.pid}.tmp`;
1702
- await writeFile(temp, output.content);
1703
- await rename(temp, output.path);
1704
- }
1705
- }
1706
- async function checkOutputs(outputs) {
1707
- for (const output of outputs) {
1708
- const actual = await readFile5(output.path, "utf8").catch(() => {
1709
- return;
1710
- });
1711
- const normalized = actual !== undefined && /\.ts$/i.test(output.path) ? await formatTypeScript(actual) : actual;
1712
- if (normalized !== output.content) {
1713
- throw new Error(`Generated file is missing or stale: ${output.path}`);
1714
- }
1715
- }
1716
- }
1717
- async function generateProject(file = "tsplc.config.ts", options = {}) {
1718
- const { config, root, configFile } = options.loaded ?? await loadTsplcConfig(file);
1719
- const settings = typegenSchema.parse(config.typegen ?? {});
1892
+ async function generateProject({ config, root, configFile }, options = {}) {
1893
+ const hardwareOnly = options.hardwareOnly || !config.compiler && !config.typegen;
1894
+ const settings = typegenSettings(config);
1720
1895
  const catalog = await loadHardware(config, root);
1721
1896
  const io = resolveIo(config, catalog);
1722
1897
  const project = {
@@ -1728,44 +1903,53 @@ async function generateProject(file = "tsplc.config.ts", options = {}) {
1728
1903
  const outputs = [
1729
1904
  {
1730
1905
  path: resolve2(root, settings.dir, generatedFiles.hardware),
1731
- content: await formatTypeScript(generateHardwareTypes(catalog, options.targets?.io, options.targets?.publication, settings.ioTypes))
1906
+ content: await formatTypeScript(generateHardwareTypes(catalog, {
1907
+ root,
1908
+ targets: options.targets ?? null,
1909
+ ioTypes: settings.ioTypes
1910
+ }))
1732
1911
  },
1733
- {
1734
- path: resolve2(root, projectSnapshotFile),
1735
- content: `${JSON.stringify(project, null, 2)}
1912
+ ...options.check ? [] : [
1913
+ {
1914
+ path: resolve2(root, projectSnapshotFile),
1915
+ content: `${JSON.stringify(project, null, 2)}
1736
1916
  `
1737
- }
1917
+ }
1918
+ ]
1738
1919
  ];
1739
- const sources = options.hardwareOnly ? undefined : await contractSources(config, root, settings);
1740
- if (sources) {
1741
- const inferred = !!config.compiler && !sources.explicit;
1742
- outputs.push({
1743
- path: resolve2(root, settings.dir, generatedFiles.contract),
1744
- content: await formatTypeScript(await generateTypes({
1745
- types: sources.types,
1746
- globals: sources.globals,
1747
- publishedGlobalsOnly: inferred,
1748
- declarations: settings.declarations,
1749
- publication: inferred ? await readPublication(root) : undefined
1750
- }))
1751
- });
1920
+ const sources = hardwareOnly ? null : await contractSources(config, root, settings);
1921
+ const inferred = sources !== null && !!config.compiler && !sources.explicit;
1922
+ const hmi = config.compiler && config.publish && !hardwareOnly ? config.hmi : undefined;
1923
+ const publication = inferred || hmi ? await readPublication(root) : null;
1924
+ const contract = sources && {
1925
+ path: resolve2(root, settings.dir, generatedFiles.contract),
1926
+ content: await formatTypeScript(await generateTypes({
1927
+ types: sources.types,
1928
+ globals: sources.globals,
1929
+ publication: inferred ? publication : null,
1930
+ declarations: settings.declarations
1931
+ }))
1932
+ };
1933
+ if (contract) {
1934
+ outputs.push(contract);
1752
1935
  }
1753
- if (config.hmi && config.publish && config.compiler && !options.hardwareOnly) {
1754
- checkHmiTargets(config.hmi.controls, (await readPublication(root)).production);
1936
+ if (hmi && publication) {
1937
+ checkHmiTargets(hmi.controls, publication.production);
1755
1938
  }
1756
- if (config.compiler && !options.hardwareOnly) {
1757
- const machine = await readFile5(resolve2(root, emittedStDirectory, emittedFiles.machines), "utf8").catch(() => {
1758
- return;
1939
+ if (config.compiler && !hardwareOnly) {
1940
+ const machines = await readIfPresent(emittedPath(root, emittedFiles.machines));
1941
+ outputs.push({
1942
+ path: resolve2(root, settings.dir, generatedFiles.machines),
1943
+ content: machines === null ? null : await formatTypeScript(machines)
1759
1944
  });
1760
- if (machine) {
1761
- outputs.push({
1762
- path: resolve2(root, settings.dir, generatedFiles.machines),
1763
- content: await formatTypeScript(machine)
1764
- });
1765
- }
1766
1945
  }
1767
1946
  await (options.check ? checkOutputs(outputs) : writeOutputs(outputs));
1768
- return { catalog, io, files: outputs.map((output) => output.path) };
1947
+ return {
1948
+ catalog,
1949
+ io,
1950
+ files: outputs.flatMap((output) => output.content === null ? [] : [output.path]),
1951
+ contract: contract?.path ?? null
1952
+ };
1769
1953
  }
1770
1954
  export {
1771
1955
  deviceTree,
@@ -1774,7 +1958,7 @@ export {
1774
1958
  generateTypes,
1775
1959
  generatedFiles,
1776
1960
  ioLayout,
1777
- ioScalarBits4 as ioScalarBits,
1961
+ ioScalarBits3 as ioScalarBits,
1778
1962
  loadHardware,
1779
1963
  normalizeEds,
1780
1964
  parseEds,
@@ -1782,5 +1966,5 @@ export {
1782
1966
  resolveIo
1783
1967
  };
1784
1968
 
1785
- //# debugId=2684A5DA71992D8C64756E2164756E21
1969
+ //# debugId=A913FE8EC54CA54864756E2164756E21
1786
1970
  //# sourceMappingURL=index.js.map