@tsplc/typegen 0.2.21 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,4 +4,4 @@ Part of [tsPLC](https://github.com/rip-technologies/tsplc).
4
4
 
5
5
  Generates TypeScript contracts for host clients from Structured Text declarations, and parses EtherNet/IP EDS files into typed hardware IO channels. In a tsPLC project, `tsplc typegen` writes `generated/hardware.ts`, whose `HardwareIoMapping` type checks every `io` key and channel in `tsplc.config.ts`.
6
6
 
7
- See the [documentation](https://github.com/rip-technologies/tsplc/tree/main/docs). MIT licensed.
7
+ See the [documentation](https://github.com/rip-technologies/tsplc/tree/master/docs). MIT licensed.
package/dist/cli.js CHANGED
@@ -5,20 +5,11 @@ import { mkdir as mkdir2, readFile as readFile4, rename as rename2, rm, writeFil
5
5
  import { dirname as dirname2, resolve as resolve3 } from "node:path";
6
6
  import { parseArgs } from "node:util";
7
7
 
8
- // packages/typegen/src/project.ts
9
- import { mkdir, readFile as readFile3, rename, writeFile } from "node:fs/promises";
10
- import { dirname, resolve as resolve2 } from "node:path";
11
- import { format } from "prettier";
12
- import {
13
- loadTsplcConfig,
14
- publicationSchema,
15
- typegenSchema
16
- } from "@tsplc/config";
17
- import { blockCommentEnd as blockCommentEnd2, lineCommentEnd as lineCommentEnd2 } from "@tsplc/iec/st";
18
-
19
8
  // packages/typegen/src/codegen/generate.ts
20
9
  import { readdir, readFile } from "node:fs/promises";
21
10
  import { basename, join } from "node:path";
11
+ import { elementaryTypesByName } from "@tsplc/iec";
12
+ import { identifierPattern as identifierPattern2 } from "@tsplc/iec/st";
22
13
 
23
14
  // packages/typegen/src/codegen/constants.ts
24
15
  import {
@@ -144,10 +135,6 @@ function constantResolver(lists) {
144
135
  return constant;
145
136
  }
146
137
 
147
- // packages/typegen/src/codegen/generate.ts
148
- import { elementaryTypesByName } from "@tsplc/iec";
149
- import { identifierPattern as identifierPattern2 } from "@tsplc/iec/st";
150
-
151
138
  // packages/typegen/src/codegen/parser.ts
152
139
  import {
153
140
  blockCommentEnd,
@@ -411,6 +398,23 @@ class Parser {
411
398
  }
412
399
  globals(name) {
413
400
  const description = this.documentation();
401
+ const sections = [];
402
+ do {
403
+ sections.push(this.globalSection());
404
+ } while (this.peek());
405
+ const constant = sections.every((section) => section.constant);
406
+ if (!constant && sections.some((section) => section.constant)) {
407
+ this.error("a list mixes CONSTANT and writable VAR_GLOBAL sections");
408
+ }
409
+ return {
410
+ name,
411
+ description,
412
+ source: this.source.name,
413
+ constant,
414
+ members: sections.flatMap((section) => section.members)
415
+ };
416
+ }
417
+ globalSection() {
414
418
  this.expect("VAR_GLOBAL");
415
419
  const written = new Set;
416
420
  while (qualifiers.has(this.peek())) {
@@ -422,16 +426,7 @@ class Parser {
422
426
  }
423
427
  const members = this.members("END_VAR");
424
428
  this.accept(";");
425
- if (this.peek()) {
426
- this.error("only one VAR_GLOBAL block per file is supported");
427
- }
428
- return {
429
- name,
430
- description,
431
- source: this.source.name,
432
- constant: written.has("CONSTANT"),
433
- members
434
- };
429
+ return { constant: written.has("CONSTANT"), members };
435
430
  }
436
431
  }
437
432
  function parseDeclarations(source) {
@@ -595,7 +590,8 @@ function emit(declarations, globals, {
595
590
  const visited = new Set;
596
591
  function visitReference(type) {
597
592
  if (type.kind === "array") {
598
- return visitReference(type.element);
593
+ visitReference(type.element);
594
+ return;
599
595
  }
600
596
  if (type.kind === "named" && !scalars[type.name.toUpperCase()]) {
601
597
  visit(declaration(type.name));
@@ -610,7 +606,9 @@ function emit(declarations, globals, {
610
606
  }
611
607
  visiting.add(type.name);
612
608
  if (type.kind === "struct") {
613
- type.members.forEach((member) => visitReference(member.type));
609
+ type.members.forEach((member) => {
610
+ visitReference(member.type);
611
+ });
614
612
  }
615
613
  if (type.kind === "alias") {
616
614
  visitReference(type.type);
@@ -741,10 +739,197 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
741
739
  `);
742
740
  }
743
741
 
742
+ // packages/typegen/src/project.ts
743
+ import { mkdir, readFile as readFile3, rename, writeFile } from "node:fs/promises";
744
+ import { dirname, resolve as resolve2 } from "node:path";
745
+ import {
746
+ ioSymbolsSchema,
747
+ loadTsplcConfig,
748
+ publicationSchema,
749
+ typegenSchema
750
+ } from "@tsplc/config";
751
+ import {
752
+ emittedFiles,
753
+ emittedStDirectory,
754
+ projectSnapshotFile
755
+ } from "@tsplc/config/project-files";
756
+ import { blockCommentEnd as blockCommentEnd2, lineCommentEnd as lineCommentEnd2 } from "@tsplc/iec/st";
757
+ import { format } from "prettier";
758
+
744
759
  // packages/typegen/src/hardware.ts
745
760
  import { readdir as readdir2, readFile as readFile2 } from "node:fs/promises";
746
761
  import { resolve } from "node:path";
747
762
 
763
+ // packages/typegen/src/hardware/channels.ts
764
+ import { ioScalarBits } from "@tsplc/iec";
765
+
766
+ // packages/typegen/src/hardware/process-image.ts
767
+ import { ioArray, ioScalar, sizePrefix } from "@tsplc/iec";
768
+ function ioLayout(type) {
769
+ const array = ioArray(type.trim());
770
+ if (array) {
771
+ const element = ioLayout(array.element);
772
+ return element && element !== "BOOL" ? `${array.length}x${element}` : undefined;
773
+ }
774
+ const scalar = ioScalar(type);
775
+ if (scalar?.family === "integer" || scalar?.family === "bits") {
776
+ return `INT${scalar.bits}`;
777
+ }
778
+ return scalar?.name;
779
+ }
780
+ var addressSize = (bits) => bits === 64 ? undefined : sizePrefix(bits);
781
+ function directAddress(region, base, offsetBits, bits) {
782
+ const size = addressSize(bits);
783
+ if (!size) {
784
+ return;
785
+ }
786
+ const byte = base + Math.floor(offsetBits / 8);
787
+ if (bits === 1) {
788
+ return `%${region}X${byte}.${offsetBits % 8}`;
789
+ }
790
+ if ((base * 8 + offsetBits) % bits) {
791
+ return;
792
+ }
793
+ return `%${region}${size}${byte / (bits / 8)}`;
794
+ }
795
+ var byteOffset = (address) => Number(address.slice(3));
796
+ function regionPlacer(regions, { generatedTree }) {
797
+ const taken = regions.flatMap(({ region, size, address }) => address ? [
798
+ {
799
+ region,
800
+ start: byteOffset(address),
801
+ end: byteOffset(address) + size
802
+ }
803
+ ] : []);
804
+ const cursors = { I: 0, Q: 0 };
805
+ const aligned = (offset) => Math.ceil(offset / 4) * 4;
806
+ return ({ id, region, size, address }) => {
807
+ if (address) {
808
+ return address;
809
+ }
810
+ if (!generatedTree) {
811
+ throw new Error(`${id}: set the %${region}B address the template assigns to this assembly, or let codesys.deviceTree place it.`);
812
+ }
813
+ const clear = (start) => {
814
+ const overlap = taken.find((item) => item.region === region && item.start < start + size && start < item.end);
815
+ return overlap ? clear(aligned(overlap.end)) : start;
816
+ };
817
+ const start = clear(aligned(cursors[region]));
818
+ taken.push({ region, start, end: start + size });
819
+ cursors[region] = start + size;
820
+ return `%${region}B${start}`;
821
+ };
822
+ }
823
+
824
+ // packages/typegen/src/hardware/channels.ts
825
+ function assemblyChannels({
826
+ device,
827
+ direction,
828
+ instance,
829
+ members,
830
+ base,
831
+ payloadSize
832
+ }) {
833
+ const prefix = `${direction}s`;
834
+ const region = direction === "input" ? "I" : "Q";
835
+ const payloadBits = payloadSize * 8;
836
+ const address = (offsetBits, bits) => directAddress(region, base, offsetBits, bits);
837
+ const channels = [];
838
+ for (let i = 0;i < payloadSize; i++) {
839
+ const key = `${prefix}.Byte${i}`;
840
+ channels.push({
841
+ device,
842
+ id: key,
843
+ name: `Byte ${i}`,
844
+ direction,
845
+ assembly: instance,
846
+ offsetBits: i * 8,
847
+ bits: 8,
848
+ type: "BYTE",
849
+ address: address(i * 8, 8),
850
+ unit: "",
851
+ description: "Assembly payload byte"
852
+ });
853
+ for (let bit = 0;bit < 8; bit++) {
854
+ channels.push({
855
+ device,
856
+ id: `${key}.Bit${bit}`,
857
+ parent: key,
858
+ name: `Bit ${bit}`,
859
+ direction,
860
+ assembly: instance,
861
+ offsetBits: i * 8 + bit,
862
+ bits: 1,
863
+ type: "BOOL",
864
+ address: address(i * 8 + bit, 1),
865
+ unit: "",
866
+ description: "Assembly payload bit"
867
+ });
868
+ }
869
+ }
870
+ const named = members.filter((member) => member.parameter).map((member) => ({ member, name: member.name.replace(/[^\w]/g, "_") }));
871
+ const seen = new Set;
872
+ const repeated = new Set;
873
+ for (const { name } of named) {
874
+ if (seen.has(name)) {
875
+ repeated.add(name);
876
+ }
877
+ seen.add(name);
878
+ }
879
+ const counts = new Map;
880
+ for (const { member, name } of named) {
881
+ if (member.offsetBits >= payloadBits) {
882
+ continue;
883
+ }
884
+ const count = counts.get(name) ?? 0;
885
+ counts.set(name, count + 1);
886
+ const key = `${prefix}.${name}${repeated.has(name) ? `[${count}]` : ""}`;
887
+ const scalarBits = ioScalarBits(member.type);
888
+ const channel = {
889
+ device,
890
+ id: key,
891
+ name: member.name,
892
+ direction,
893
+ assembly: instance,
894
+ offsetBits: member.offsetBits,
895
+ bits: member.bits,
896
+ type: member.type,
897
+ address: scalarBits === member.bits ? address(member.offsetBits, member.bits) : undefined,
898
+ unit: member.unit,
899
+ description: member.description
900
+ };
901
+ const spansScalars = scalarBits !== undefined && scalarBits >= 8 && member.bits > scalarBits && member.bits % scalarBits === 0 && member.offsetBits % scalarBits === 0;
902
+ if (!spansScalars) {
903
+ if (member.offsetBits + member.bits <= payloadBits) {
904
+ channels.push(channel);
905
+ }
906
+ continue;
907
+ }
908
+ const length = Math.floor(Math.min(member.bits, payloadBits - member.offsetBits) / scalarBits);
909
+ const span = {
910
+ ...channel,
911
+ bits: length * scalarBits,
912
+ type: `ARRAY[0..${length - 1}] OF ${member.type}`,
913
+ address: address(member.offsetBits, scalarBits)
914
+ };
915
+ channels.push(span);
916
+ for (let index = 0;index < length; index++) {
917
+ const offset = member.offsetBits + index * scalarBits;
918
+ channels.push({
919
+ ...span,
920
+ id: `${key}[${index}]`,
921
+ parent: key,
922
+ name: `${member.name}[${index}]`,
923
+ type: member.type,
924
+ bits: scalarBits,
925
+ offsetBits: offset,
926
+ address: address(offset, scalarBits)
927
+ });
928
+ }
929
+ }
930
+ return channels;
931
+ }
932
+
748
933
  // packages/typegen/src/hardware/eds.ts
749
934
  var cipTypes = {
750
935
  193: "BOOL",
@@ -1023,176 +1208,6 @@ function parseEds(text, file = "device.eds") {
1023
1208
  };
1024
1209
  }
1025
1210
 
1026
- // packages/typegen/src/hardware/channels.ts
1027
- import { ioScalarBits } from "@tsplc/iec";
1028
-
1029
- // packages/typegen/src/hardware/process-image.ts
1030
- import { ioArray, ioScalar, sizePrefix } from "@tsplc/iec";
1031
- function ioLayout(type) {
1032
- const array = ioArray(type.trim());
1033
- if (array) {
1034
- const element = ioLayout(array.element);
1035
- return element && element !== "BOOL" ? `${array.length}x${element}` : undefined;
1036
- }
1037
- const scalar = ioScalar(type);
1038
- if (scalar?.family === "integer" || scalar?.family === "bits") {
1039
- return `INT${scalar.bits}`;
1040
- }
1041
- return scalar?.name;
1042
- }
1043
- var addressSize = (bits) => bits === 64 ? undefined : sizePrefix(bits);
1044
- function directAddress(region, base, offsetBits, bits) {
1045
- const size = addressSize(bits);
1046
- if (!size) {
1047
- return;
1048
- }
1049
- const byte = base + Math.floor(offsetBits / 8);
1050
- if (bits === 1) {
1051
- return `%${region}X${byte}.${offsetBits % 8}`;
1052
- }
1053
- if ((base * 8 + offsetBits) % bits) {
1054
- return;
1055
- }
1056
- return `%${region}${size}${byte / (bits / 8)}`;
1057
- }
1058
- var byteOffset = (address) => Number(address.slice(3));
1059
- function regionPlacer(regions, { generatedTree }) {
1060
- const taken = regions.flatMap(({ region, size, address }) => address ? [
1061
- {
1062
- region,
1063
- start: byteOffset(address),
1064
- end: byteOffset(address) + size
1065
- }
1066
- ] : []);
1067
- const cursors = { I: 0, Q: 0 };
1068
- const aligned = (offset) => Math.ceil(offset / 4) * 4;
1069
- return ({ id, region, size, address }) => {
1070
- if (address) {
1071
- return address;
1072
- }
1073
- if (!generatedTree) {
1074
- throw new Error(`${id}: set the %${region}B address the template assigns to this assembly, or let codesys.deviceTree place it.`);
1075
- }
1076
- const clear = (start) => {
1077
- const overlap = taken.find((item) => item.region === region && item.start < start + size && start < item.end);
1078
- return overlap ? clear(aligned(overlap.end)) : start;
1079
- };
1080
- const start = clear(aligned(cursors[region]));
1081
- taken.push({ region, start, end: start + size });
1082
- cursors[region] = start + size;
1083
- return `%${region}B${start}`;
1084
- };
1085
- }
1086
-
1087
- // packages/typegen/src/hardware/channels.ts
1088
- function assemblyChannels({
1089
- device,
1090
- direction,
1091
- instance,
1092
- members,
1093
- base,
1094
- payloadSize
1095
- }) {
1096
- const prefix = `${direction}s`;
1097
- const region = direction === "input" ? "I" : "Q";
1098
- const payloadBits = payloadSize * 8;
1099
- const address = (offsetBits, bits) => directAddress(region, base, offsetBits, bits);
1100
- const channels = [];
1101
- for (let i = 0;i < payloadSize; i++) {
1102
- const key = `${prefix}.Byte${i}`;
1103
- channels.push({
1104
- device,
1105
- id: key,
1106
- name: `Byte ${i}`,
1107
- direction,
1108
- assembly: instance,
1109
- offsetBits: i * 8,
1110
- bits: 8,
1111
- type: "BYTE",
1112
- address: address(i * 8, 8),
1113
- unit: "",
1114
- description: "Assembly payload byte"
1115
- });
1116
- for (let bit = 0;bit < 8; bit++) {
1117
- channels.push({
1118
- device,
1119
- id: `${key}.Bit${bit}`,
1120
- parent: key,
1121
- name: `Bit ${bit}`,
1122
- direction,
1123
- assembly: instance,
1124
- offsetBits: i * 8 + bit,
1125
- bits: 1,
1126
- type: "BOOL",
1127
- address: address(i * 8 + bit, 1),
1128
- unit: "",
1129
- description: "Assembly payload bit"
1130
- });
1131
- }
1132
- }
1133
- const named = members.filter((member) => member.parameter).map((member) => ({ member, name: member.name.replace(/[^\w]/g, "_") }));
1134
- const seen = new Set;
1135
- const repeated = new Set;
1136
- for (const { name } of named) {
1137
- if (seen.has(name)) {
1138
- repeated.add(name);
1139
- }
1140
- seen.add(name);
1141
- }
1142
- const counts = new Map;
1143
- for (const { member, name } of named) {
1144
- if (member.offsetBits >= payloadBits) {
1145
- continue;
1146
- }
1147
- const count = counts.get(name) ?? 0;
1148
- counts.set(name, count + 1);
1149
- const key = `${prefix}.${name}${repeated.has(name) ? `[${count}]` : ""}`;
1150
- const scalarBits = ioScalarBits(member.type);
1151
- const channel = {
1152
- device,
1153
- id: key,
1154
- name: member.name,
1155
- direction,
1156
- assembly: instance,
1157
- offsetBits: member.offsetBits,
1158
- bits: member.bits,
1159
- type: member.type,
1160
- address: scalarBits === member.bits ? address(member.offsetBits, member.bits) : undefined,
1161
- unit: member.unit,
1162
- description: member.description
1163
- };
1164
- const spansScalars = scalarBits !== undefined && scalarBits >= 8 && member.bits > scalarBits && member.bits % scalarBits === 0 && member.offsetBits % scalarBits === 0;
1165
- if (!spansScalars) {
1166
- if (member.offsetBits + member.bits <= payloadBits) {
1167
- channels.push(channel);
1168
- }
1169
- continue;
1170
- }
1171
- const length = Math.floor(Math.min(member.bits, payloadBits - member.offsetBits) / scalarBits);
1172
- const span = {
1173
- ...channel,
1174
- bits: length * scalarBits,
1175
- type: `ARRAY[0..${length - 1}] OF ${member.type}`,
1176
- address: address(member.offsetBits, scalarBits)
1177
- };
1178
- channels.push(span);
1179
- for (let index = 0;index < length; index++) {
1180
- const offset = member.offsetBits + index * scalarBits;
1181
- channels.push({
1182
- ...span,
1183
- id: `${key}[${index}]`,
1184
- parent: key,
1185
- name: `${member.name}[${index}]`,
1186
- type: member.type,
1187
- bits: scalarBits,
1188
- offsetBits: offset,
1189
- address: address(offset, scalarBits)
1190
- });
1191
- }
1192
- }
1193
- return channels;
1194
- }
1195
-
1196
1211
  // packages/typegen/src/hardware/modbus.ts
1197
1212
  var registerBytes = { Q: 4, I: 8 };
1198
1213
  function placeModbusRegisters(device, registers, place) {
@@ -1448,9 +1463,27 @@ function resolveIo(config, catalog) {
1448
1463
  }
1449
1464
 
1450
1465
  // packages/typegen/src/project.ts
1451
- var emittedSt = ".tsplc/artifacts/st";
1452
1466
  var formatTypeScript = (source) => format(source, { parser: "typescript" });
1453
- var readPublication = async (root) => publicationSchema.parse(JSON.parse(await readFile3(resolve2(root, emittedSt, "publication.json"), "utf8")));
1467
+ var readPublication = async (root) => publicationSchema.parse(JSON.parse(await readFile3(resolve2(root, emittedStDirectory, emittedFiles.publication), "utf8")));
1468
+ var generatedFiles = {
1469
+ hardware: "hardware.ts",
1470
+ contract: "plc.ts",
1471
+ machines: "machines.ts"
1472
+ };
1473
+ async function readIoSymbols(root) {
1474
+ const file = resolve2(root, emittedStDirectory, emittedFiles.ioSymbols);
1475
+ const text = await readFile3(file, "utf8").catch((error) => {
1476
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
1477
+ return "{}";
1478
+ }
1479
+ throw error;
1480
+ });
1481
+ const symbols = ioSymbolsSchema.safeParse(JSON.parse(text));
1482
+ if (!symbols.success) {
1483
+ throw new Error(`Invalid IO symbols in ${file}`, { cause: symbols.error });
1484
+ }
1485
+ return symbols.data;
1486
+ }
1454
1487
  async function contractSources(config, root, settings) {
1455
1488
  const directories = (setting) => setting ? [setting].flat().map((path) => resolve2(root, path)) : [];
1456
1489
  const types = directories(settings.types);
@@ -1466,7 +1499,7 @@ async function contractSources(config, root, settings) {
1466
1499
  }
1467
1500
  return sources;
1468
1501
  }
1469
- const source = config.compiler ? emittedSt : config.build?.sourceDir;
1502
+ const source = config.compiler ? emittedStDirectory : config.build?.sourceDir;
1470
1503
  if (!source) {
1471
1504
  if (config.typegen) {
1472
1505
  throw new Error("Configure build.sourceDir or typegen.types/globals to generate PLC types.");
@@ -1547,16 +1580,16 @@ async function generateProject(file = "tsplc.config.ts", options = {}) {
1547
1580
  version: 1,
1548
1581
  configFile,
1549
1582
  config,
1550
- symbols: config.compiler ? JSON.parse(await readFile3(resolve2(root, emittedSt, "io-symbols.json"), "utf8").catch(() => "{}")) : Object.fromEntries(Object.keys(io).filter((symbol) => symbol.includes(".")).map((symbol) => [symbol, symbol]))
1583
+ symbols: config.compiler ? await readIoSymbols(root) : Object.fromEntries(Object.keys(io).filter((symbol) => symbol.includes(".")).map((symbol) => [symbol, symbol]))
1551
1584
  };
1552
1585
  const outputs = [
1553
1586
  {
1554
- path: resolve2(root, settings.dir, "hardware.ts"),
1587
+ path: resolve2(root, settings.dir, generatedFiles.hardware),
1555
1588
  content: await formatTypeScript(generateHardwareTypes(catalog, options.targets?.io, options.targets?.publication, settings.ioTypes))
1556
1589
  },
1557
1590
  {
1558
- path: resolve2(root, ".tsplc/project.json"),
1559
- content: JSON.stringify(project, null, 2) + `
1591
+ path: resolve2(root, projectSnapshotFile),
1592
+ content: `${JSON.stringify(project, null, 2)}
1560
1593
  `
1561
1594
  }
1562
1595
  ];
@@ -1564,7 +1597,7 @@ async function generateProject(file = "tsplc.config.ts", options = {}) {
1564
1597
  if (sources) {
1565
1598
  const inferred = !!config.compiler && !sources.explicit;
1566
1599
  outputs.push({
1567
- path: resolve2(root, settings.dir, "plc.ts"),
1600
+ path: resolve2(root, settings.dir, generatedFiles.contract),
1568
1601
  content: await formatTypeScript(await generateTypes({
1569
1602
  types: sources.types,
1570
1603
  globals: sources.globals,
@@ -1578,12 +1611,12 @@ async function generateProject(file = "tsplc.config.ts", options = {}) {
1578
1611
  checkHmiTargets(config.hmi.controls, (await readPublication(root)).production);
1579
1612
  }
1580
1613
  if (config.compiler && !options.hardwareOnly) {
1581
- const machine = await readFile3(resolve2(root, emittedSt, "machines.ts"), "utf8").catch(() => {
1614
+ const machine = await readFile3(resolve2(root, emittedStDirectory, emittedFiles.machines), "utf8").catch(() => {
1582
1615
  return;
1583
1616
  });
1584
1617
  if (machine) {
1585
1618
  outputs.push({
1586
- path: resolve2(root, settings.dir, "machines.ts"),
1619
+ path: resolve2(root, settings.dir, generatedFiles.machines),
1587
1620
  content: await formatTypeScript(machine)
1588
1621
  });
1589
1622
  }
@@ -1657,5 +1690,5 @@ main().catch((error) => {
1657
1690
  process.exitCode = 1;
1658
1691
  });
1659
1692
 
1660
- //# debugId=6E079C222AB7798D64756E2164756E21
1693
+ //# debugId=91D99125E052C89064756E2164756E21
1661
1694
  //# sourceMappingURL=cli.js.map