@tsplc/build 0.2.17 → 0.2.19

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.
Files changed (51) hide show
  1. package/dist/cli.js +628 -352
  2. package/dist/cli.js.map +30 -28
  3. package/dist/index.js +548 -387
  4. package/dist/index.js.map +27 -25
  5. package/dist/libraries.js +68 -27
  6. package/dist/libraries.js.map +3 -3
  7. package/docker/Dockerfile +2 -0
  8. package/docker/Dockerfile.dockerignore +4 -1
  9. package/docker/Dockerfile.source +3 -0
  10. package/docker/config.ts +10 -5
  11. package/docker/runner.ts +140 -127
  12. package/package.json +54 -53
  13. package/python/build.py +183 -124
  14. package/python/codesys_online.py +44 -45
  15. package/python/hardware.py +9 -9
  16. package/python/test_build.py +3 -3
  17. package/python/test_codesys_online.py +18 -12
  18. package/python/test_installer_packages.py +1 -0
  19. package/python/worker.py +11 -7
  20. package/src/artifacts.ts +82 -60
  21. package/src/build.ts +71 -62
  22. package/src/cli.ts +109 -100
  23. package/src/controller-online.ts +400 -425
  24. package/src/controller-protocol.ts +140 -0
  25. package/src/controller-session.ts +466 -397
  26. package/src/device-tree.ts +19 -15
  27. package/src/diagnostics.ts +59 -49
  28. package/src/docker-build.ts +217 -156
  29. package/src/docker-context.ts +49 -27
  30. package/src/docker-run.ts +137 -111
  31. package/src/engineering-settings.ts +42 -0
  32. package/src/host/codesys-command.ts +35 -34
  33. package/src/host/codesys-host.ts +157 -129
  34. package/src/host/codesys-worker.ts +318 -301
  35. package/src/host/windows-path.ts +63 -59
  36. package/src/import-request.ts +24 -0
  37. package/src/index.ts +37 -31
  38. package/src/io.ts +152 -116
  39. package/src/libraries.ts +214 -146
  40. package/src/package-path.ts +3 -1
  41. package/src/run.ts +132 -108
  42. package/src/runtime-status.ts +25 -19
  43. package/src/sources.ts +264 -225
  44. package/src/st/declarations.ts +181 -193
  45. package/src/st/lexer.ts +102 -118
  46. package/src/st/parse.ts +193 -171
  47. package/src/st/reader.ts +47 -42
  48. package/src/__tests__/fixtures/xml/fb-simple.xml +0 -40
  49. package/src/__tests__/fixtures/xml/fb-state-machine.xml +0 -86
  50. package/src/__tests__/fixtures/xml/prg-cyclic.xml +0 -44
  51. package/src/config.ts +0 -12
package/dist/cli.js CHANGED
@@ -3,27 +3,24 @@
3
3
 
4
4
  // packages/build/src/cli.ts
5
5
  import { parseArgs } from "util";
6
- import { deviceTree } from "@tsplc/typegen";
7
- import { loadHardware, resolveIo } from "@tsplc/typegen/hardware";
8
- import { controllerFor, loadTsplcConfig, rawBuildConfig } from "@tsplc/config";
6
+ import { loadHardware as loadHardware2, resolveIo as resolveIo2 } from "@tsplc/typegen/hardware";
7
+ import { controllerFor as controllerFor2, loadTsplcConfig, rawBuildConfig as rawBuildConfig2 } from "@tsplc/config";
8
+ import { z as z12 } from "zod";
9
9
 
10
10
  // packages/build/src/artifacts.ts
11
- import { copyFile, cp, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
11
+ import {
12
+ copyFile,
13
+ cp,
14
+ readFile,
15
+ rename,
16
+ rm,
17
+ stat,
18
+ writeFile
19
+ } from "node:fs/promises";
12
20
  import { resolve } from "node:path";
21
+ import { identifierPattern } from "@tsplc/iec/st";
13
22
  import { z } from "zod";
14
-
15
- // packages/build/src/config.ts
16
- import {
17
- configSchema,
18
- controllerSchema,
19
- cyclicTasksSchema,
20
- dockerImage,
21
- defineBuildConfig,
22
- resolveConfig,
23
- loadConfig
24
- } from "@tsplc/config/build";
25
-
26
- // packages/build/src/artifacts.ts
23
+ import { cyclicTasksSchema } from "@tsplc/config/build";
27
24
  var buildFiles = {
28
25
  project: "Application.project",
29
26
  output: "runtime/Application.app",
@@ -34,7 +31,7 @@ var buildFiles = {
34
31
  };
35
32
  var receiptSchema = z.object({
36
33
  mode: z.literal("build"),
37
- application: z.string().regex(/^[A-Za-z_][A-Za-z_0-9]*$/),
34
+ application: z.string().regex(identifierPattern),
38
35
  tasks: cyclicTasksSchema.optional()
39
36
  });
40
37
  var readBuild = async (directory) => {
@@ -44,7 +41,11 @@ var readBuild = async (directory) => {
44
41
  cause: receipt.error
45
42
  });
46
43
  }
47
- for (const file of [buildFiles.project, buildFiles.output, buildFiles.checksum]) {
44
+ for (const file of [
45
+ buildFiles.project,
46
+ buildFiles.output,
47
+ buildFiles.checksum
48
+ ]) {
48
49
  const artifact = await stat(resolve(directory, file));
49
50
  if (!artifact.isFile() || artifact.size === 0) {
50
51
  throw new Error(`CODESYS produced an empty artifact: ${file}`);
@@ -59,13 +60,16 @@ var readBuild = async (directory) => {
59
60
  };
60
61
  };
61
62
 
63
+ // packages/build/src/build.ts
64
+ import { dockerImage as dockerImage2 } from "@tsplc/config/build";
65
+
62
66
  // packages/build/src/docker-build.ts
63
- import { execFile } from "node:child_process";
64
67
  import { randomUUID } from "node:crypto";
65
68
  import { cp as cp4, mkdir as mkdir3, mkdtemp as mkdtemp2, readFile as readFile3, rm as rm3 } from "node:fs/promises";
66
69
  import { tmpdir as tmpdir2 } from "node:os";
67
70
  import { resolve as resolve5 } from "node:path";
68
- import { promisify } from "node:util";
71
+ import { z as z3 } from "zod";
72
+ import { dockerImage } from "@tsplc/config/build";
69
73
 
70
74
  // packages/build/src/docker-context.ts
71
75
  import { cp as cp2, mkdir, mkdtemp, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
@@ -79,23 +83,39 @@ import { fileURLToPath } from "node:url";
79
83
  var packageDirectory = resolve2(fileURLToPath(new URL("..", import.meta.url)));
80
84
 
81
85
  // packages/build/src/docker-context.ts
86
+ var containerPackages = [
87
+ {
88
+ entry: "@tsplc/config/build",
89
+ directory: "shared-config",
90
+ files: ["src", "templates", "package.json"]
91
+ },
92
+ {
93
+ entry: "@tsplc/iec",
94
+ directory: "shared-iec",
95
+ files: ["src", "package.json"]
96
+ }
97
+ ];
82
98
  async function prepareDockerContext() {
83
99
  const context = await mkdtemp(resolve3(tmpdir(), "tsplc-docker-"));
84
100
  try {
85
- for (const directory of ["src", "python", "docker", "runtime"])
101
+ for (const directory of ["src", "python", "docker", "runtime"]) {
86
102
  await cp2(resolve3(packageDirectory, directory), resolve3(context, directory), {
87
103
  recursive: true
88
104
  });
89
- const configRoot = resolve3(dirname(createRequire(import.meta.url).resolve("@tsplc/config/build")), "..");
90
- await mkdir(resolve3(context, "shared-config"));
91
- await cp2(resolve3(configRoot, "src"), resolve3(context, "shared-config/src"), {
92
- recursive: true
93
- });
94
- await cp2(resolve3(configRoot, "templates"), resolve3(context, "shared-config/templates"), {
95
- recursive: true
96
- });
97
- await cp2(resolve3(configRoot, "package.json"), resolve3(context, "shared-config/package.json"));
98
- await writeFile2(resolve3(context, "package.json"), JSON.stringify({ type: "module", dependencies: { zod: "4.3.6", jiti: "2.7.0" } }));
105
+ }
106
+ for (const { entry, directory, files } of containerPackages) {
107
+ const root = resolve3(dirname(createRequire(import.meta.url).resolve(entry)), "..");
108
+ await mkdir(resolve3(context, directory));
109
+ for (const file of files) {
110
+ await cp2(resolve3(root, file), resolve3(context, directory, file), {
111
+ recursive: true
112
+ });
113
+ }
114
+ }
115
+ await writeFile2(resolve3(context, "package.json"), JSON.stringify({
116
+ type: "module",
117
+ dependencies: { zod: "4.3.6", jiti: "2.7.0" }
118
+ }));
99
119
  return context;
100
120
  } catch (cause) {
101
121
  await rm2(context, { recursive: true, force: true });
@@ -141,13 +161,20 @@ var buildFailureSchema = z2.strictObject({
141
161
  });
142
162
 
143
163
  // packages/build/src/docker-run.ts
144
- import { spawn } from "node:child_process";
164
+ import { execFile, spawn } from "node:child_process";
145
165
  import { createHash } from "node:crypto";
146
166
  import { copyFile as copyFile2, cp as cp3, mkdir as mkdir2, readFile as readFile2, writeFile as writeFile3 } from "node:fs/promises";
147
167
  import { basename, posix, relative, resolve as resolve4, sep } from "node:path";
168
+ import { promisify } from "node:util";
169
+ var execute = promisify(execFile);
170
+ var captureDocker = (args, timeout) => execute("docker", args, { timeout, maxBuffer: 8 * 1024 * 1024 });
148
171
  var runDocker = (args, failure) => new Promise((accept, reject) => {
149
172
  const child = spawn("docker", args, {
150
- stdio: ["inherit", process.env["TSPLC_LOG_STDERR"] === "1" ? 2 : "inherit", "inherit"]
173
+ stdio: [
174
+ "inherit",
175
+ process.env["TSPLC_LOG_STDERR"] === "1" ? 2 : "inherit",
176
+ "inherit"
177
+ ]
151
178
  });
152
179
  const interrupt = () => child.kill("SIGINT");
153
180
  const terminate = () => child.kill("SIGTERM");
@@ -174,13 +201,15 @@ var runDocker = (args, failure) => new Promise((accept, reject) => {
174
201
  });
175
202
  var bindMount = (source, target, readonly = false) => `type=bind,"source=${source.replaceAll('"', '""')}",target=${target}${readonly ? ",readonly" : ""}`;
176
203
  async function mountLibraries(libraries, directory, root = "/input") {
177
- if (!libraries?.length)
204
+ if (!libraries?.length) {
178
205
  return;
206
+ }
179
207
  await mkdir2(resolve4(directory, "libraries"), { recursive: true });
180
208
  return Promise.all(libraries.map(async (library) => {
181
209
  const data = await readFile2(library.path);
182
- if (createHash("sha256").update(data).digest("hex") !== library.sha256)
210
+ if (createHash("sha256").update(data).digest("hex") !== library.sha256) {
183
211
  throw new Error(`Library changed after installation: ${library.title}`);
212
+ }
184
213
  const filename = `${library.sha256}-${basename(library.path)}`;
185
214
  await writeFile3(resolve4(directory, "libraries", filename), data);
186
215
  return { ...library, path: `${root}/libraries/${filename}` };
@@ -218,7 +247,6 @@ var prepareContainerRun = async (config, requestDirectory, options) => {
218
247
  };
219
248
 
220
249
  // packages/build/src/docker-build.ts
221
- var execute = promisify(execFile);
222
250
  var runtimeImage = "tsplc-control-linux-sl:4.22.0.0";
223
251
  var buildInDocker = async (config, image) => {
224
252
  const requestDirectory = await mkdtemp2(resolve5(tmpdir2(), "codesys-docker-"));
@@ -230,7 +258,10 @@ var buildInDocker = async (config, image) => {
230
258
  const args = [
231
259
  "run",
232
260
  "--rm",
233
- ...await prepareContainerRun(config, requestDirectory, { network: "none", sources: true }),
261
+ ...await prepareContainerRun(config, requestDirectory, {
262
+ network: "none",
263
+ sources: true
264
+ }),
234
265
  image,
235
266
  "--request",
236
267
  "/input/config.json",
@@ -243,21 +274,25 @@ var buildInDocker = async (config, image) => {
243
274
  } catch (cause) {
244
275
  const message = cause instanceof Error ? cause.message : String(cause);
245
276
  const failure = await readFile3(failurePath, "utf8").then((text) => buildFailureSchema.parse(JSON.parse(text))).catch((error) => {
246
- if (error instanceof Error && "code" in error && error.code === "ENOENT")
277
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
247
278
  return;
279
+ }
248
280
  throw new AggregateError([cause, error], `${message}. Invalid CODESYS failure metadata (${failurePath})`, { cause: error });
249
281
  });
250
- if (!failure)
282
+ if (!failure) {
251
283
  throw cause;
252
- if (failure.operationId !== operationId)
284
+ }
285
+ if (failure.operationId !== operationId) {
253
286
  throw new Error(`${message}. CODESYS failure metadata belongs to a different Docker build`, {
254
287
  cause
255
288
  });
289
+ }
256
290
  if (cause instanceof Error) {
257
291
  cause.message = `${message}
258
292
  ${failure.message}`;
259
- if (failure.diagnostics.length)
293
+ if (failure.diagnostics.length) {
260
294
  cause.cause = new CodesysCompilerError(failure.message, failure.diagnostics);
295
+ }
261
296
  }
262
297
  throw cause;
263
298
  }
@@ -281,10 +316,9 @@ import {
281
316
  } from "node:fs/promises";
282
317
  import { resolve as resolve6 } from "node:path";
283
318
  import { setTimeout as delay } from "node:timers/promises";
284
- import { z as z4 } from "zod";
319
+ import { z as z5 } from "zod";
285
320
 
286
321
  // packages/build/src/host/codesys-command.ts
287
- import { commandArgumentSchema } from "@tsplc/config/build";
288
322
  var codesysCommand = [
289
323
  "@echo off",
290
324
  "setlocal DisableDelayedExpansion",
@@ -299,28 +333,31 @@ var codesysCommand = [
299
333
  // packages/build/src/host/codesys-host.ts
300
334
  import { execFile as execFile3, spawn as spawn2 } from "node:child_process";
301
335
  import { promisify as promisify3 } from "node:util";
302
- import { z as z3 } from "zod";
336
+ import { z as z4 } from "zod";
303
337
 
304
338
  // packages/build/src/host/windows-path.ts
305
339
  import { execFile as execFile2 } from "node:child_process";
306
340
  import { promisify as promisify2 } from "node:util";
307
- import { codesysTimeouts } from "@tsplc/config/build";
341
+ import {
342
+ codesysTimeouts,
343
+ commandArgumentSchema
344
+ } from "@tsplc/config/build";
308
345
  var execute2 = promisify2(execFile2);
309
346
 
310
347
  // packages/build/src/host/codesys-host.ts
311
348
  var execute3 = promisify3(execFile3);
312
- var exitSchema = z3.object({
313
- pid: z3.int().positive(),
314
- code: z3.int().nullable(),
315
- signal: z3.string().nullable()
349
+ var exitSchema = z4.object({
350
+ pid: z4.int().positive(),
351
+ code: z4.int().nullable(),
352
+ signal: z4.string().nullable()
316
353
  });
317
354
 
318
355
  // packages/build/src/host/codesys-worker.ts
319
356
  var pythonDirectory = resolve6(packageDirectory, "python");
320
- var sessionSchema = z4.object({
321
- directory: z4.string(),
322
- fingerprint: z4.string(),
323
- pid: z4.int().positive()
357
+ var sessionSchema = z5.object({
358
+ directory: z5.string(),
359
+ fingerprint: z5.string(),
360
+ pid: z5.int().positive()
324
361
  });
325
362
  var hasCode = (error, code) => error instanceof Error && ("code" in error) && error.code === code;
326
363
  var isProcessAlive = (pid) => {
@@ -370,10 +407,24 @@ var withWorkerLock = async (config, run) => {
370
407
  }
371
408
  };
372
409
 
410
+ // packages/build/src/sources.ts
411
+ import { identifierPattern as identifierPattern3 } from "@tsplc/iec/st";
412
+
373
413
  // packages/build/src/st/parse.ts
374
414
  import { basename as basename2 } from "node:path";
415
+ import {
416
+ globalSections,
417
+ identifierPattern as identifierPattern2,
418
+ qualifiers,
419
+ variableSections as variableSections2
420
+ } from "@tsplc/iec/st";
375
421
 
376
422
  // packages/build/src/st/declarations.ts
423
+ import {
424
+ conditionalDirective,
425
+ modifiers,
426
+ variableSections
427
+ } from "@tsplc/iec/st";
377
428
  var objectKinds = {
378
429
  PROGRAM: "program",
379
430
  FUNCTION_BLOCK: "function_block",
@@ -383,29 +434,6 @@ var objectKinds = {
383
434
  INTERFACE: "interface",
384
435
  PROPERTY: "property"
385
436
  };
386
- var modifiers = new Set([
387
- "PUBLIC",
388
- "PRIVATE",
389
- "PROTECTED",
390
- "INTERNAL",
391
- "FINAL",
392
- "ABSTRACT",
393
- "OVERRIDE"
394
- ]);
395
- var globalSections = new Set(["VAR_GLOBAL", "VAR_CONFIG"]);
396
- var variableSections = new Set([
397
- ...globalSections,
398
- "VAR",
399
- "VAR_INPUT",
400
- "VAR_OUTPUT",
401
- "VAR_IN_OUT",
402
- "VAR_TEMP",
403
- "VAR_STAT",
404
- "VAR_INST",
405
- "VAR_EXTERNAL",
406
- "VAR_ACCESS",
407
- "VAR_GENERIC"
408
- ]);
409
437
  var closingObjects = new Set(Object.keys(objectKinds).map((kind) => `END_${kind}`));
410
438
  var declarationKeywords = new Set([
411
439
  ...Object.keys(objectKinds),
@@ -423,12 +451,7 @@ var declarationKeywords = new Set([
423
451
  "CONFIGURATION",
424
452
  "END_CONFIGURATION"
425
453
  ]);
426
- var conditionalDirective = (token) => {
427
- if (token?.kind === "pragma") {
428
- return /^\{\s*(IF|ELSIF|ELSE|END_IF)\b/i.exec(token.value)?.[1]?.toUpperCase();
429
- }
430
- };
431
- var isDeclarationPragma = (token) => token?.kind === "pragma" && !conditionalDirective(token);
454
+ var isDeclarationPragma = (token) => token?.kind === "pragma" && !conditionalDirective(token.value);
432
455
  var readDeclarationPragmas = (reader) => {
433
456
  while (isDeclarationPragma(reader.peek())) {
434
457
  reader.take();
@@ -522,7 +545,7 @@ var readVariableSection = (reader) => {
522
545
  if (variableSections.has(token.value) || closingObjects.has(token.value)) {
523
546
  reader.fail("Missing END_VAR", token);
524
547
  }
525
- const directive = conditionalDirective(token);
548
+ const directive = token.kind === "pragma" && conditionalDirective(token.value);
526
549
  if (!directive) {
527
550
  continue;
528
551
  }
@@ -574,6 +597,8 @@ var readDeclarationSections = (reader) => {
574
597
  };
575
598
 
576
599
  // packages/build/src/st/lexer.ts
600
+ import { blockCommentEnd, lineCommentEnd, stringEnd } from "@tsplc/iec/st";
601
+
577
602
  class StSyntaxError extends Error {
578
603
  constructor(source, offset, filename, message) {
579
604
  const lines = source.slice(0, offset).split(/\r\n|\r|\n/);
@@ -588,16 +613,7 @@ var tokenize = (source, filename = "<source>") => {
588
613
  throw new StSyntaxError(source, start, filename, message);
589
614
  };
590
615
  const quoted = () => {
591
- const start = offset;
592
- const quote = source[offset++];
593
- while (offset < source.length) {
594
- if (source[offset] === "$") {
595
- offset += 2;
596
- } else if (source[offset++] === quote) {
597
- return;
598
- }
599
- }
600
- fail(start, "Unterminated string");
616
+ offset = stringEnd(source, offset) ?? fail(offset, "Unterminated string");
601
617
  };
602
618
  while (offset < source.length) {
603
619
  const start = offset;
@@ -607,28 +623,11 @@ var tokenize = (source, filename = "<source>") => {
607
623
  continue;
608
624
  }
609
625
  if (source.startsWith("//", offset)) {
610
- while (offset < source.length && !/[\r\n]/.test(source[offset] ?? "")) {
611
- offset++;
612
- }
626
+ offset = lineCommentEnd(source, start);
613
627
  continue;
614
628
  }
615
629
  if (source.startsWith("(*", offset)) {
616
- offset += 2;
617
- let depth = 1;
618
- while (offset < source.length && depth > 0) {
619
- if (source.startsWith("(*", offset)) {
620
- depth++;
621
- offset += 2;
622
- } else if (source.startsWith("*)", offset)) {
623
- depth--;
624
- offset += 2;
625
- } else {
626
- offset++;
627
- }
628
- }
629
- if (depth) {
630
- fail(start, "Unterminated block comment");
631
- }
630
+ offset = blockCommentEnd(source, start) ?? fail(start, "Unterminated block comment");
632
631
  continue;
633
632
  }
634
633
  if (character === "'" || character === '"') {
@@ -778,14 +777,14 @@ var parseGlobals = (reader, options) => {
778
777
  const start = reader.index;
779
778
  readVariableSection(reader);
780
779
  for (const token of reader.tokens.slice(start + 1, reader.index)) {
781
- if (token.kind !== "word" || !["CONSTANT", "RETAIN", "PERSISTENT", "NON_RETAIN"].includes(token.value)) {
780
+ if (token.kind !== "word" || !qualifiers.has(token.value)) {
782
781
  break;
783
782
  }
784
783
  persistent ||= token.value === "PERSISTENT";
785
784
  }
786
785
  }
787
786
  const name = options.name ?? basename2(reader.filename, ".st");
788
- if (!/^[A-Za-z_][A-Za-z_0-9]*$/.test(name)) {
787
+ if (!identifierPattern2.test(name)) {
789
788
  reader.fail("Global list requires an IEC filename or an explicit name", header);
790
789
  }
791
790
  return {
@@ -800,7 +799,7 @@ var validateImplementation = (reader, tokens) => {
800
799
  if (token.kind !== "word") {
801
800
  continue;
802
801
  }
803
- if (variableSections.has(token.value) || token.value === "END_VAR") {
802
+ if (variableSections2.has(token.value) || token.value === "END_VAR") {
804
803
  reader.fail("Variable declaration outside the declaration section; conditional declaration envelopes are not supported", token);
805
804
  }
806
805
  if (declarationKeywords.has(token.value)) {
@@ -869,61 +868,59 @@ var parseSource = (source, options = {}) => {
869
868
  };
870
869
 
871
870
  // packages/build/src/io.ts
872
- var arrayType = /^ARRAY\s*\[\s*(-?\d+)\s*\.\.\s*(-?\d+)\s*\]\s*OF\s+(\w+)$/;
873
- var layout = (type) => {
874
- const array = arrayType.exec(type);
875
- return array ? { element: array[3], length: Number(array[2]) - Number(array[1]) + 1 } : { element: type, length: 1 };
876
- };
877
- var widths = {
878
- BOOL: "X",
879
- BYTE: "B",
880
- SINT: "B",
881
- USINT: "B",
882
- WORD: "W",
883
- INT: "W",
884
- UINT: "W",
885
- DWORD: "D",
886
- DINT: "D",
887
- UDINT: "D",
888
- REAL: "D"
871
+ import { ioArray, ioScalarBits, sizePrefix } from "@tsplc/iec";
872
+ import { qualifiers as qualifiers2, variableSections as variableSections3 } from "@tsplc/iec/st";
873
+ var span = (type) => ioArray(type) ?? { element: type, length: 1 };
874
+ var addressSize = (type) => {
875
+ const bits = ioScalarBits(type);
876
+ return bits === undefined || bits === 64 ? undefined : sizePrefix(bits);
889
877
  };
890
878
  function bindStructuredTextIo(objects, bindings) {
891
879
  const declarations = [];
892
880
  const visit = (object) => {
893
881
  const tokens = tokenize(object.declaration, object.source);
894
- let section = false, start = 0;
895
- for (let i = 0;i < tokens.length; i++) {
896
- const token = tokens[i];
897
- if (variableSections.has(token.value)) {
882
+ let section = false;
883
+ let start = 0;
884
+ for (const [index, token] of tokens.entries()) {
885
+ if (variableSections3.has(token.value)) {
898
886
  section = true;
899
- start = i + 1;
887
+ start = index + 1;
900
888
  continue;
901
889
  }
902
890
  if (token.value === "END_VAR") {
903
891
  section = false;
904
892
  continue;
905
893
  }
906
- if (!section || token.value !== ";")
894
+ if (!section || token.value !== ";") {
907
895
  continue;
908
- const part = tokens.slice(start, i).filter((t) => t.kind !== "pragma");
909
- start = i + 1;
910
- const colonIndex = part.findIndex((t) => t.value === ":");
911
- if (colonIndex < 1)
896
+ }
897
+ const part = tokens.slice(start, index).filter((t) => t.kind !== "pragma");
898
+ start = index + 1;
899
+ const colon = part.find((t) => t.value === ":");
900
+ if (!colon) {
912
901
  continue;
913
- const names = part.slice(0, colonIndex).filter((t) => t.kind === "word" && !["CONSTANT", "RETAIN", "PERSISTENT", "AT"].includes(t.value));
914
- const at = part.findIndex((t) => t.value === "AT");
915
- const variables = at < 0 ? names : names.filter((t) => t.start < part[at].start);
902
+ }
903
+ const colonIndex = part.indexOf(colon);
904
+ if (colonIndex < 1) {
905
+ continue;
906
+ }
907
+ const names = part.slice(0, colonIndex).filter((t) => t.kind === "word" && !qualifiers2.has(t.value) && t.value !== "AT");
908
+ const at = part.find((t) => t.value === "AT");
909
+ const variables = at ? names.filter((t) => t.start < at.start) : names;
916
910
  const initializer = part.findIndex((t, index) => index > colonIndex && t.value === ":=");
917
911
  const typeTokens = part.slice(colonIndex + 1, initializer < 0 ? undefined : initializer);
918
- const type = typeTokens.length ? object.declaration.slice(typeTokens[0].start, typeTokens.at(-1).end).replace(/\s+/g, " ").toUpperCase() : "";
919
- for (const name of variables)
912
+ const [first] = typeTokens;
913
+ const last = typeTokens.at(-1);
914
+ const type = first && last ? object.declaration.slice(first.start, last.end).replace(/\s+/g, " ").toUpperCase() : "";
915
+ for (const name of variables) {
920
916
  declarations.push({
921
917
  object,
922
918
  name: name.value,
923
919
  names: variables,
924
- colon: part[colonIndex],
920
+ colon,
925
921
  type
926
922
  });
923
+ }
927
924
  }
928
925
  object.children.forEach(visit);
929
926
  };
@@ -931,99 +928,125 @@ function bindStructuredTextIo(objects, bindings) {
931
928
  const edits = new Map;
932
929
  for (const [symbol, binding] of Object.entries(bindings)) {
933
930
  const parts = symbol.toUpperCase().split(".");
934
- if (parts.length > 2)
931
+ if (parts.length > 2) {
935
932
  throw new Error(`${symbol}: direct IO maps a scalar declaration, not a nested field.`);
933
+ }
936
934
  const matches = declarations.filter((d) => d.name === parts.at(-1) && (parts.length === 1 || d.object.name.toUpperCase() === parts[0]));
937
- if (matches.length !== 1)
935
+ const [declaration, ...others] = matches;
936
+ if (!declaration || others.length) {
938
937
  throw new Error(`${symbol}: expected one ST variable declaration, found ${matches.length}. Use Object.Variable to disambiguate.`);
939
- const declaration = matches[0];
940
- if (declaration.names.length !== 1)
938
+ }
939
+ const [variable, ...siblings] = declaration.names;
940
+ if (!variable || siblings.length) {
941
941
  throw new Error(`${symbol}: declare mapped IO variables separately.`);
942
- const declared = layout(declaration.type);
943
- if (!widths[declared.element] || declared.length > 1 && declared.element === "BOOL" || binding.address[2] !== widths[declared.element])
942
+ }
943
+ const declared = span(declaration.type);
944
+ const size = addressSize(declared.element);
945
+ if (!size || declared.length > 1 && declared.element === "BOOL" || binding.address[2] !== size) {
944
946
  throw new Error(`${symbol}: ${declaration.type} is incompatible with ${binding.address}.`);
945
- const expected = binding.type && layout(binding.type.replace(/\s+/g, " ").toUpperCase());
946
- if (expected && (expected.element !== declared.element || expected.length !== declared.length))
947
+ }
948
+ const expected = binding.type && span(binding.type.replace(/\s+/g, " ").toUpperCase());
949
+ if (expected && (expected.element !== declared.element || expected.length !== declared.length)) {
947
950
  throw new Error(`${symbol}: expected ${binding.type}, found ${declaration.type}.`);
951
+ }
948
952
  const list = edits.get(declaration.object) ?? [];
949
- const start = declaration.names[0].end;
950
- if (list.some((e) => e.start === start))
953
+ const start = variable.end;
954
+ if (list.some((e) => e.start === start)) {
951
955
  throw new Error(`${symbol}: the variable has more than one IO binding.`);
952
- list.push({ start, end: declaration.colon.start, text: ` AT ${binding.address} ` });
956
+ }
957
+ list.push({
958
+ start,
959
+ end: declaration.colon.start,
960
+ text: ` AT ${binding.address} `
961
+ });
953
962
  edits.set(declaration.object, list);
954
963
  }
955
- for (const [object, list] of edits)
956
- for (const edit of list.sort((a, b) => b.start - a.start))
964
+ for (const [object, list] of edits) {
965
+ for (const edit of list.sort((a, b) => b.start - a.start)) {
957
966
  object.declaration = object.declaration.slice(0, edit.start) + edit.text + object.declaration.slice(edit.end);
967
+ }
968
+ }
958
969
  }
959
970
 
960
971
  // packages/build/src/build.ts
961
972
  var buildProject = async (config) => {
962
- if (!config.docker)
973
+ if (!config.docker) {
963
974
  throw new Error("Builds require a Docker builder image.");
964
- return buildInDocker(config, dockerImage);
975
+ }
976
+ return buildInDocker(config, dockerImage2);
965
977
  };
966
978
 
967
- // packages/build/src/config.ts
968
- import {
969
- configSchema as configSchema2,
970
- controllerSchema as controllerSchema2,
971
- cyclicTasksSchema as cyclicTasksSchema2,
972
- dockerImage as dockerImage2,
973
- defineBuildConfig as defineBuildConfig2,
974
- resolveConfig as resolveConfig2,
975
- loadConfig as loadConfig2
976
- } from "@tsplc/config/build";
979
+ // packages/build/src/cli.ts
980
+ import { resolveConfig as resolveConfig2 } from "@tsplc/config/build";
977
981
 
978
982
  // packages/build/src/controller-online.ts
979
- import { execFile as execFile4 } from "node:child_process";
980
983
  import { existsSync } from "node:fs";
981
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
984
+ import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
982
985
  import { mkdir as mkdir5, mkdtemp as mkdtemp3, readFile as readFile5, rm as rm5 } from "node:fs/promises";
983
986
  import { tmpdir as tmpdir3 } from "node:os";
984
987
  import { posix as posix2, resolve as resolve7 } from "node:path";
985
- import { promisify as promisify4 } from "node:util";
986
- import { z as z5 } from "zod";
987
- var execute4 = promisify4(execFile4);
988
- var imageIdSchema = z5.string().regex(/^sha256:[a-f0-9]{64}$/);
989
- var endpointSchema = z5.strictObject({
990
- host: z5.string().nonempty(),
991
- port: z5.number().int().min(1).max(65535)
988
+ import { z as z7 } from "zod";
989
+ import { dockerImage as dockerImage3 } from "@tsplc/config/build";
990
+
991
+ // packages/build/src/controller-protocol.ts
992
+ import { createHash as createHash2 } from "node:crypto";
993
+ import { z as z6 } from "zod";
994
+ import {
995
+ controllerSchema,
996
+ sha256Digest,
997
+ tcpPort
998
+ } from "@tsplc/config/build";
999
+ var imageIdSchema = z6.string().regex(/^sha256:[a-f0-9]{64}$/);
1000
+ var endpointSchema = z6.strictObject({
1001
+ host: z6.string().nonempty(),
1002
+ port: tcpPort
992
1003
  });
993
- var controllerResultSchema = z5.strictObject({
994
- schemaVersion: z5.literal(1),
995
- operationId: z5.uuid(),
996
- operation: z5.enum(["download", "online-change", "inspect"]),
1004
+ var controllerResultSchema = z6.strictObject({
1005
+ schemaVersion: z6.literal(1),
1006
+ operationId: z6.uuid(),
1007
+ operation: z6.enum(["download", "online-change", "inspect"]),
997
1008
  imageId: imageIdSchema,
998
- templateHash: z5.string().regex(/^[a-f0-9]{64}$/),
999
- target: z5.strictObject({
1000
- network: z5.string().nonempty(),
1009
+ templateHash: sha256Digest,
1010
+ target: z6.strictObject({
1011
+ network: z6.string().nonempty(),
1001
1012
  gateway: endpointSchema,
1002
1013
  device: endpointSchema,
1003
1014
  controller: controllerSchema.optional(),
1004
- deviceTree: z5.string().regex(/^[a-f0-9]{64}$/).optional()
1015
+ deviceTree: sha256Digest.optional()
1005
1016
  }),
1006
- generation: z5.string().nonempty(),
1007
- application: z5.string().nonempty(),
1008
- applicationGuid: z5.string().nonempty(),
1009
- controllerIds: z5.strictObject({
1010
- codeId: z5.string().nonempty(),
1011
- dataId: z5.string().nonempty()
1017
+ generation: z6.string().nonempty(),
1018
+ application: z6.string().nonempty(),
1019
+ applicationGuid: z6.string().nonempty(),
1020
+ controllerIds: z6.strictObject({
1021
+ codeId: z6.string().nonempty(),
1022
+ dataId: z6.string().nonempty()
1012
1023
  }),
1013
- state: z5.string().nonempty(),
1014
- values: z5.record(z5.string(), z5.string())
1024
+ state: z6.string().nonempty(),
1025
+ values: z6.record(z6.string(), z6.string())
1015
1026
  });
1016
- var controllerCredentialsSchema = z5.strictObject({
1017
- username: z5.string().nonempty(),
1018
- password: z5.string().nonempty()
1027
+ var controllerCredentialsSchema = z6.strictObject({
1028
+ username: z6.string().nonempty(),
1029
+ password: z6.string().nonempty()
1019
1030
  });
1020
- var warmOperationSchema = z5.strictObject({
1021
- operation: z5.enum(["download", "online-change"]),
1022
- operationId: z5.uuid(),
1023
- request: z5.string().nonempty(),
1024
- initializeUser: z5.boolean(),
1031
+ var warmOperationSchema = z6.strictObject({
1032
+ operation: z6.enum(["download", "online-change"]),
1033
+ operationId: z6.uuid(),
1034
+ request: z6.string().nonempty(),
1035
+ initializeUser: z6.boolean(),
1025
1036
  credentials: controllerCredentialsSchema.optional()
1026
1037
  });
1038
+ var tracebackFailure = (traceback) => {
1039
+ const text = traceback.trim();
1040
+ const lastFrame = text.lastIndexOf(`
1041
+ File `);
1042
+ if (lastFrame === -1) {
1043
+ return text;
1044
+ }
1045
+ const [, ...rest] = text.slice(lastFrame + 1).split(`
1046
+ `);
1047
+ return ((rest[0]?.startsWith(" ")) ? rest.slice(1) : rest).join(`
1048
+ `);
1049
+ };
1027
1050
  var controllerTarget = (config, online) => ({
1028
1051
  network: online.network,
1029
1052
  gateway: online.gateway,
@@ -1033,8 +1056,39 @@ var controllerTarget = (config, online) => ({
1033
1056
  deviceTree: createHash2("sha256").update(JSON.stringify(config.deviceTree)).digest("hex")
1034
1057
  }
1035
1058
  });
1059
+ var sameBaseline = (state, expected) => state.imageId === expected.imageId && state.templateHash === expected.templateHash && JSON.stringify(state.target) === JSON.stringify(expected.target);
1060
+ var loginCommandSchema = z6.discriminatedUnion("command", [
1061
+ z6.strictObject({ command: z6.literal("state") }),
1062
+ z6.strictObject({
1063
+ command: z6.literal("read"),
1064
+ expressions: z6.array(z6.string().nonempty()).nonempty()
1065
+ }),
1066
+ z6.strictObject({
1067
+ command: z6.enum(["write", "force"]),
1068
+ values: z6.record(z6.string().nonempty(), z6.string().nonempty())
1069
+ }),
1070
+ z6.strictObject({
1071
+ command: z6.literal("unforce"),
1072
+ expressions: z6.array(z6.string().nonempty()),
1073
+ restore: z6.boolean()
1074
+ }),
1075
+ z6.strictObject({ command: z6.enum(["start", "stop"]) }),
1076
+ z6.strictObject({
1077
+ command: z6.literal("reset"),
1078
+ kind: z6.enum(["Warm", "Cold"])
1079
+ })
1080
+ ]);
1081
+ var loginResultSchema = z6.union([
1082
+ z6.strictObject({ values: z6.record(z6.string(), z6.string()) }),
1083
+ z6.strictObject({ state: z6.string(), forced: z6.array(z6.string()) })
1084
+ ]);
1085
+
1086
+ // packages/build/src/controller-online.ts
1036
1087
  var credentialEnvironment = (config) => {
1037
- const names = config.online?.credentials ? [config.online.credentials.usernameEnv, config.online.credentials.passwordEnv] : [];
1088
+ const names = config.online?.credentials ? [
1089
+ config.online.credentials.usernameEnv,
1090
+ config.online.credentials.passwordEnv
1091
+ ] : [];
1038
1092
  for (const name of names) {
1039
1093
  if (process.env[name] === undefined) {
1040
1094
  throw new Error(`Controller credential environment variable ${name} is not set`);
@@ -1046,17 +1100,17 @@ var controllerConnection = async (config) => {
1046
1100
  if (!config.docker || !config.online) {
1047
1101
  throw new Error("Docker image and online gateway/device configuration are required for controller operations");
1048
1102
  }
1049
- const { stdout } = await execute4("docker", ["image", "inspect", "--format", "{{.Id}}", dockerImage], { timeout: config.timeouts.hostCommand }).catch((cause) => {
1050
- throw new Error(`Cannot inspect Docker builder image ${dockerImage}. Install and start Docker, then run tsplc-build configure if the image is missing`, { cause });
1103
+ const { stdout } = await captureDocker(["image", "inspect", "--format", "{{.Id}}", dockerImage3], config.timeouts.hostCommand).catch((cause) => {
1104
+ throw new Error(`Cannot inspect Docker builder image ${dockerImage3}. Install and start Docker, then run tsplc-build configure if the image is missing`, { cause });
1051
1105
  });
1052
1106
  return {
1053
1107
  imageId: imageIdSchema.parse(stdout.trim()),
1054
- templateHash: createHash2("sha256").update(await readFile5(config.template)).digest("hex"),
1108
+ templateHash: createHash3("sha256").update(await readFile5(config.template)).digest("hex"),
1055
1109
  target: controllerTarget(config, config.online)
1056
1110
  };
1057
1111
  };
1058
1112
  var checkReceipt = (result, expected, diagnostics) => {
1059
- if (result.operationId !== expected.operationId || result.operation !== expected.operation || result.imageId !== expected.imageId || result.templateHash !== expected.templateHash || JSON.stringify(result.target) !== JSON.stringify(expected.target)) {
1113
+ if (result.operationId !== expected.operationId || result.operation !== expected.operation || !sameBaseline(result, expected)) {
1060
1114
  throw new Error(`Controller receipt does not match this operation's image, template or target. Inspect ${diagnostics} for diagnostics`);
1061
1115
  }
1062
1116
  return result;
@@ -1090,11 +1144,13 @@ var controllerOperation = async (config, operation, options) => {
1090
1144
  ...options.initializeUser ? ["--initialize-user"] : [],
1091
1145
  ...options.read ? ["--read", JSON.stringify(options.read)] : []
1092
1146
  ], (status) => `Docker controller operation failed (${status}). Inspect ${diagnostics} for diagnostics`).catch(async (cause) => {
1093
- if (!existsSync(failure))
1147
+ if (!existsSync(failure)) {
1094
1148
  throw cause;
1095
- const reason = (await readFile5(failure, "utf8")).trim().split(`
1096
- `).at(-1);
1097
- throw new Error(`${reason}. Inspect ${diagnostics} for diagnostics`, { cause });
1149
+ }
1150
+ const reason = tracebackFailure(await readFile5(failure, "utf8"));
1151
+ throw new Error(`${reason}. Inspect ${diagnostics} for diagnostics`, {
1152
+ cause
1153
+ });
1098
1154
  });
1099
1155
  const result = await readFile5(resolve7(diagnostics, "result.json"), "utf8").then((content) => controllerResultSchema.parse(JSON.parse(content))).catch((cause) => {
1100
1156
  throw new Error(`Docker did not produce a valid controller receipt. Inspect ${diagnostics} for diagnostics`, { cause });
@@ -1106,42 +1162,19 @@ var controllerOperation = async (config, operation, options) => {
1106
1162
  };
1107
1163
  var updateController = (config, operation, options = {}) => controllerOperation(config, operation, options);
1108
1164
  var inspectController = (config, read) => controllerOperation(config, "inspect", { read });
1109
- var loginCommandSchema = z5.discriminatedUnion("command", [
1110
- z5.strictObject({ command: z5.literal("state") }),
1111
- z5.strictObject({
1112
- command: z5.literal("read"),
1113
- expressions: z5.array(z5.string().nonempty()).nonempty()
1114
- }),
1115
- z5.strictObject({
1116
- command: z5.enum(["write", "force"]),
1117
- values: z5.record(z5.string().nonempty(), z5.string().nonempty())
1118
- }),
1119
- z5.strictObject({
1120
- command: z5.literal("unforce"),
1121
- expressions: z5.array(z5.string().nonempty()),
1122
- restore: z5.boolean()
1123
- }),
1124
- z5.strictObject({ command: z5.enum(["start", "stop"]) }),
1125
- z5.strictObject({ command: z5.literal("reset"), kind: z5.enum(["Warm", "Cold"]) })
1126
- ]);
1127
- var loginResultSchema = z5.union([
1128
- z5.strictObject({ values: z5.record(z5.string(), z5.string()) }),
1129
- z5.strictObject({ state: z5.string(), forced: z5.array(z5.string()) })
1130
- ]);
1131
- var loginReplySchema = z5.discriminatedUnion("ok", [
1132
- z5.strictObject({ ok: z5.literal(true), result: z5.unknown() }),
1133
- z5.strictObject({ ok: z5.literal(false), error: z5.string() })
1165
+ var loginReplySchema = z7.discriminatedUnion("ok", [
1166
+ z7.strictObject({ ok: z7.literal(true), result: z7.unknown() }),
1167
+ z7.strictObject({ ok: z7.literal(false), error: z7.string() })
1134
1168
  ]);
1135
1169
 
1136
1170
  // packages/build/src/docker-build.ts
1137
- import { execFile as execFile5 } from "node:child_process";
1138
1171
  import { cp as cp5, mkdir as mkdir6, mkdtemp as mkdtemp4, readFile as readFile6, rm as rm6 } from "node:fs/promises";
1139
1172
  import { tmpdir as tmpdir4 } from "node:os";
1140
1173
  import { resolve as resolve8 } from "node:path";
1141
- import { promisify as promisify5 } from "node:util";
1142
- var execute5 = promisify5(execFile5);
1174
+ import { z as z8 } from "zod";
1175
+ import { dockerImage as dockerImage4 } from "@tsplc/config/build";
1143
1176
  var publishedImage = async (image) => {
1144
- const { version } = JSON.parse(await readFile6(resolve8(packageDirectory, "package.json"), "utf8"));
1177
+ const { version } = z8.object({ version: z8.string() }).parse(JSON.parse(await readFile6(resolve8(packageDirectory, "package.json"), "utf8")));
1145
1178
  return `ghcr.io/livingforjesus/${image.split(":")[0]}:${version}`;
1146
1179
  };
1147
1180
  var pullPublished = async (image) => {
@@ -1157,8 +1190,8 @@ var pullPublished = async (image) => {
1157
1190
  return true;
1158
1191
  };
1159
1192
  var configureDocker = async () => {
1160
- const image = dockerImage;
1161
- const { stdout } = await execute5("docker", ["info", "--format", "{{.OSType}}/{{.Architecture}}"], { timeout: 30000 }).catch((cause) => {
1193
+ const image = dockerImage4;
1194
+ const { stdout } = await captureDocker(["info", "--format", "{{.OSType}}/{{.Architecture}}"], 30000).catch((cause) => {
1162
1195
  throw new Error("Cannot connect to Docker. Install and start Docker Desktop or Docker Engine", {
1163
1196
  cause
1164
1197
  });
@@ -1168,8 +1201,9 @@ var configureDocker = async () => {
1168
1201
  if (!arm && architecture !== "linux/x86_64" && architecture !== "linux/amd64") {
1169
1202
  throw new Error("The builder requires a Linux Docker server on ARM64 or AMD64");
1170
1203
  }
1171
- if (await pullPublished(image))
1204
+ if (await pullPublished(image)) {
1172
1205
  return image;
1206
+ }
1173
1207
  const context = await mkdtemp4(resolve8(tmpdir4(), "codesys-installer-"));
1174
1208
  let buildContext;
1175
1209
  try {
@@ -1214,61 +1248,111 @@ var runtimeImage2 = "tsplc-control-linux-sl:4.22.0.0";
1214
1248
  var configureRuntime = async () => {
1215
1249
  const context = resolve8(packageDirectory, "docker/control-linux-sl");
1216
1250
  console.log(`Preparing the local PLC runtime (${runtimeImage2}).`);
1217
- await runDocker(["build", "--platform", "linux/amd64", "--progress", "plain", "-t", runtimeImage2, context], (status) => `Runtime image build failed (${status}). Review the image-build output`);
1251
+ await runDocker([
1252
+ "build",
1253
+ "--platform",
1254
+ "linux/amd64",
1255
+ "--progress",
1256
+ "plain",
1257
+ "-t",
1258
+ runtimeImage2,
1259
+ context
1260
+ ], (status) => `Runtime image build failed (${status}). Review the image-build output`);
1218
1261
  return runtimeImage2;
1219
1262
  };
1220
1263
 
1264
+ // packages/build/src/engineering-settings.ts
1265
+ import {
1266
+ controllerFor,
1267
+ rawBuildConfig,
1268
+ simulationConfig
1269
+ } from "@tsplc/config";
1270
+ import { deviceTree } from "@tsplc/typegen";
1271
+ import { loadHardware, resolveIo } from "@tsplc/typegen/hardware";
1272
+ import { resolveConfig } from "@tsplc/config/build";
1273
+
1221
1274
  // packages/build/src/libraries.ts
1222
- import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
1275
+ import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
1223
1276
  import { mkdir as mkdir7, readFile as readFile7, rename as rename3, writeFile as writeFile5 } from "node:fs/promises";
1224
1277
  import { basename as basename3, relative as relative2, resolve as resolve9 } from "node:path";
1278
+ import { sha256Digest as sha256Digest2 } from "@tsplc/config/build";
1279
+ import { z as z9 } from "zod";
1225
1280
  var libraryRegistry = "https://store-archive.codesys.com/CODESYSLibs";
1226
1281
  var libraryFile = /\.(?:compiled-library(?:-v\d+)?|library)$/i;
1227
- var hash = (data) => createHash3("sha256").update(data).digest("hex");
1282
+ var installedLibrarySchema = z9.object({
1283
+ title: z9.string(),
1284
+ company: z9.string().optional(),
1285
+ version: z9.string().optional(),
1286
+ namespace: z9.string().optional(),
1287
+ path: z9.string(),
1288
+ sha256: sha256Digest2,
1289
+ url: z9.string().optional()
1290
+ });
1291
+ var libraryLockSchema = z9.object({
1292
+ version: z9.literal(1),
1293
+ dependencies: z9.record(z9.string(), installedLibrarySchema)
1294
+ });
1295
+ var readLock = async (file) => {
1296
+ const text = await readFile7(file, "utf8").catch((cause) => {
1297
+ if (cause && typeof cause === "object" && "code" in cause && cause.code === "ENOENT") {
1298
+ return;
1299
+ }
1300
+ throw cause;
1301
+ });
1302
+ if (text === undefined) {
1303
+ return { version: 1, dependencies: {} };
1304
+ }
1305
+ const lock = libraryLockSchema.safeParse(JSON.parse(text));
1306
+ if (!lock.success) {
1307
+ throw new Error("Invalid tsplc.lock.json.", { cause: lock.error });
1308
+ }
1309
+ return lock.data;
1310
+ };
1311
+ var hash = (data) => createHash4("sha256").update(data).digest("hex");
1228
1312
  var component = (name) => {
1229
- if (!name.trim() || /[/\\\0\r\n]/.test(name) || name === "." || name === "..")
1313
+ if (!name.trim() || /[/\\\0\r\n]/.test(name) || name === "." || name === "..") {
1230
1314
  throw new Error(`Invalid library registry component: ${name}.`);
1315
+ }
1231
1316
  return encodeURIComponent(name);
1232
1317
  };
1233
1318
  async function response(url, fetcher) {
1234
1319
  const result = await fetcher(url, { signal: AbortSignal.timeout(30000) });
1235
- if (!result.ok)
1320
+ if (!result.ok) {
1236
1321
  throw new Error(`Library registry ${result.status}: ${url}`);
1322
+ }
1237
1323
  return result;
1238
1324
  }
1239
1325
  async function libraryIndex(path = ["System"], fetcher = fetch) {
1240
1326
  const url = `${libraryRegistry}/${path.map(component).join("/")}/index`;
1241
1327
  const result = await response(url, fetcher);
1242
1328
  const text = await result.text();
1243
- if (text.length > 4000000 || /<html/i.test(text))
1329
+ if (text.length > 4000000 || /<html/i.test(text)) {
1244
1330
  throw new Error(`Invalid library registry index: ${url}`);
1331
+ }
1245
1332
  return text.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
1246
1333
  }
1247
1334
  async function validateLibrary(title, version, company = "System", fetcher = fetch) {
1248
- if (!(await libraryIndex([company], fetcher)).includes(title))
1335
+ if (!(await libraryIndex([company], fetcher)).includes(title)) {
1249
1336
  throw new Error(`Unknown CODESYS library ${company}/${title}. Names are case sensitive.`);
1337
+ }
1250
1338
  const versions = await libraryIndex([company, title], fetcher);
1251
- if (!versions.includes(version))
1339
+ if (!versions.includes(version)) {
1252
1340
  throw new Error(`Unknown version ${version} for ${title}. Available: ${versions.join(", ")}`);
1341
+ }
1253
1342
  const filenames = (await libraryIndex([company, title, version], fetcher)).filter((name) => libraryFile.test(name));
1254
- if (filenames.length !== 1)
1343
+ const [filename, ...others] = filenames;
1344
+ if (filename === undefined || others.length) {
1255
1345
  throw new Error(`Expected one library payload for ${title} ${version}, received ${filenames.length}.`);
1346
+ }
1256
1347
  return {
1257
- filename: filenames[0],
1258
- url: `${libraryRegistry}/${[company, title, version, filenames[0]].map(component).join("/")}`
1348
+ filename,
1349
+ url: `${libraryRegistry}/${[company, title, version, filename].map(component).join("/")}`
1259
1350
  };
1260
1351
  }
1261
1352
  async function installLibraries(dependencies, root, options = {}) {
1262
- const file = resolve9(root, "tsplc.lock.json"), store = resolve9(root, ".tsplc/libraries");
1263
- let previous = { version: 1, dependencies: {} };
1264
- try {
1265
- previous = JSON.parse(await readFile7(file, "utf8"));
1266
- } catch (cause) {
1267
- if (!(cause && typeof cause === "object" && ("code" in cause) && cause.code === "ENOENT"))
1268
- throw cause;
1269
- }
1270
- if (previous.version !== 1 || !previous.dependencies || typeof previous.dependencies !== "object")
1271
- throw new Error("Invalid tsplc.lock.json.");
1353
+ const file = resolve9(root, "tsplc.lock.json");
1354
+ const store = resolve9(root, ".tsplc/libraries");
1355
+ const previous = await readLock(file);
1272
1356
  const installed = {};
1273
1357
  const fetcher = options.fetcher ?? fetch;
1274
1358
  await mkdir7(store, { recursive: true });
@@ -1285,14 +1369,17 @@ async function installLibraries(dependencies, root, options = {}) {
1285
1369
  continue;
1286
1370
  }
1287
1371
  } catch {}
1288
- if (options.frozen)
1372
+ if (options.frozen) {
1289
1373
  throw new Error(`Locked library ${title} is missing or changed.`);
1290
- } else if (options.frozen)
1374
+ }
1375
+ } else if (options.frozen) {
1291
1376
  throw new Error(`Dependency ${title} differs from tsplc.lock.json.`);
1377
+ }
1292
1378
  if ("path" in settings) {
1293
1379
  const path = resolve9(root, settings.path);
1294
- if (!libraryFile.test(path))
1380
+ if (!libraryFile.test(path)) {
1295
1381
  throw new Error(`${title}: expected a .library or .compiled-library file.`);
1382
+ }
1296
1383
  installed[title] = {
1297
1384
  title,
1298
1385
  path,
@@ -1304,12 +1391,15 @@ async function installLibraries(dependencies, root, options = {}) {
1304
1391
  const payload = await validateLibrary(title, settings.version, company, fetcher);
1305
1392
  const result = await response(payload.url, fetcher);
1306
1393
  const data = new Uint8Array(await result.arrayBuffer());
1307
- if (!data.length || data.length > 256 * 1024 * 1024)
1394
+ if (!data.length || data.length > 256 * 1024 * 1024) {
1308
1395
  throw new Error(`${title}: invalid library payload size.`);
1396
+ }
1309
1397
  const sha256 = hash(data);
1310
- if (same && prior.sha256 !== sha256)
1398
+ if (same && prior.sha256 !== sha256) {
1311
1399
  throw new Error(`Registry payload changed for locked library ${title} ${settings.version}.`);
1312
- const path = resolve9(store, `${sha256}-${basename3(payload.filename)}`), temp = `${path}.${randomUUID3()}.tmp`;
1400
+ }
1401
+ const path = resolve9(store, `${sha256}-${basename3(payload.filename)}`);
1402
+ const temp = `${path}.${randomUUID3()}.tmp`;
1313
1403
  await writeFile5(temp, data, { flag: "wx" });
1314
1404
  await rename3(temp, path);
1315
1405
  installed[title] = {
@@ -1323,13 +1413,17 @@ async function installLibraries(dependencies, root, options = {}) {
1323
1413
  };
1324
1414
  }
1325
1415
  }
1326
- if (options.frozen && Object.keys(previous.dependencies).some((name) => !Object.hasOwn(dependencies, name)))
1416
+ if (options.frozen && Object.keys(previous.dependencies).some((name) => !Object.hasOwn(dependencies, name))) {
1327
1417
  throw new Error("Removed dependencies differ from tsplc.lock.json.");
1418
+ }
1328
1419
  if (!options.frozen) {
1329
1420
  const temp = `${file}.${randomUUID3()}.tmp`;
1330
1421
  const portable = Object.fromEntries(Object.entries(installed).map(([title, library]) => [
1331
1422
  title,
1332
- { ...library, path: relative2(root, library.path).replaceAll("\\", "/") }
1423
+ {
1424
+ ...library,
1425
+ path: relative2(root, library.path).replaceAll("\\", "/")
1426
+ }
1333
1427
  ]));
1334
1428
  await writeFile5(temp, JSON.stringify({ version: 1, dependencies: portable }, null, 2) + `
1335
1429
  `);
@@ -1338,14 +1432,190 @@ async function installLibraries(dependencies, root, options = {}) {
1338
1432
  return Object.values(installed);
1339
1433
  }
1340
1434
 
1435
+ // packages/build/src/engineering-settings.ts
1436
+ var rawEngineeringSettings = async ({ config, configFile, root }, options) => {
1437
+ const hardwareConfig = options.simulate ? simulationConfig(config) : config;
1438
+ const build = rawBuildConfig(config);
1439
+ const libraries = await installLibraries(config.dependencies, root, {
1440
+ frozen: options.frozenLockfile
1441
+ });
1442
+ const hardware = await loadHardware(hardwareConfig, root);
1443
+ return resolveConfig({
1444
+ ...build,
1445
+ libraries,
1446
+ io: resolveIo(hardwareConfig, hardware),
1447
+ deviceTree: await deviceTree(hardwareConfig, hardware),
1448
+ controller: controllerFor(config, options.command)
1449
+ }, configFile);
1450
+ };
1451
+
1452
+ // packages/build/src/libraries.ts
1453
+ import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
1454
+ import { mkdir as mkdir8, readFile as readFile8, rename as rename4, writeFile as writeFile6 } from "node:fs/promises";
1455
+ import { basename as basename4, relative as relative3, resolve as resolve10 } from "node:path";
1456
+ import { sha256Digest as sha256Digest3 } from "@tsplc/config/build";
1457
+ import { z as z10 } from "zod";
1458
+ var libraryRegistry2 = "https://store-archive.codesys.com/CODESYSLibs";
1459
+ var libraryFile2 = /\.(?:compiled-library(?:-v\d+)?|library)$/i;
1460
+ var installedLibrarySchema2 = z10.object({
1461
+ title: z10.string(),
1462
+ company: z10.string().optional(),
1463
+ version: z10.string().optional(),
1464
+ namespace: z10.string().optional(),
1465
+ path: z10.string(),
1466
+ sha256: sha256Digest3,
1467
+ url: z10.string().optional()
1468
+ });
1469
+ var libraryLockSchema2 = z10.object({
1470
+ version: z10.literal(1),
1471
+ dependencies: z10.record(z10.string(), installedLibrarySchema2)
1472
+ });
1473
+ var readLock2 = async (file) => {
1474
+ const text = await readFile8(file, "utf8").catch((cause) => {
1475
+ if (cause && typeof cause === "object" && "code" in cause && cause.code === "ENOENT") {
1476
+ return;
1477
+ }
1478
+ throw cause;
1479
+ });
1480
+ if (text === undefined) {
1481
+ return { version: 1, dependencies: {} };
1482
+ }
1483
+ const lock = libraryLockSchema2.safeParse(JSON.parse(text));
1484
+ if (!lock.success) {
1485
+ throw new Error("Invalid tsplc.lock.json.", { cause: lock.error });
1486
+ }
1487
+ return lock.data;
1488
+ };
1489
+ var hash2 = (data) => createHash5("sha256").update(data).digest("hex");
1490
+ var component2 = (name) => {
1491
+ if (!name.trim() || /[/\\\0\r\n]/.test(name) || name === "." || name === "..") {
1492
+ throw new Error(`Invalid library registry component: ${name}.`);
1493
+ }
1494
+ return encodeURIComponent(name);
1495
+ };
1496
+ async function response2(url, fetcher) {
1497
+ const result = await fetcher(url, { signal: AbortSignal.timeout(30000) });
1498
+ if (!result.ok) {
1499
+ throw new Error(`Library registry ${result.status}: ${url}`);
1500
+ }
1501
+ return result;
1502
+ }
1503
+ async function libraryIndex2(path = ["System"], fetcher = fetch) {
1504
+ const url = `${libraryRegistry2}/${path.map(component2).join("/")}/index`;
1505
+ const result = await response2(url, fetcher);
1506
+ const text = await result.text();
1507
+ if (text.length > 4000000 || /<html/i.test(text)) {
1508
+ throw new Error(`Invalid library registry index: ${url}`);
1509
+ }
1510
+ return text.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
1511
+ }
1512
+ async function validateLibrary2(title, version, company = "System", fetcher = fetch) {
1513
+ if (!(await libraryIndex2([company], fetcher)).includes(title)) {
1514
+ throw new Error(`Unknown CODESYS library ${company}/${title}. Names are case sensitive.`);
1515
+ }
1516
+ const versions = await libraryIndex2([company, title], fetcher);
1517
+ if (!versions.includes(version)) {
1518
+ throw new Error(`Unknown version ${version} for ${title}. Available: ${versions.join(", ")}`);
1519
+ }
1520
+ const filenames = (await libraryIndex2([company, title, version], fetcher)).filter((name) => libraryFile2.test(name));
1521
+ const [filename, ...others] = filenames;
1522
+ if (filename === undefined || others.length) {
1523
+ throw new Error(`Expected one library payload for ${title} ${version}, received ${filenames.length}.`);
1524
+ }
1525
+ return {
1526
+ filename,
1527
+ url: `${libraryRegistry2}/${[company, title, version, filename].map(component2).join("/")}`
1528
+ };
1529
+ }
1530
+ async function installLibraries2(dependencies, root, options = {}) {
1531
+ const file = resolve10(root, "tsplc.lock.json");
1532
+ const store = resolve10(root, ".tsplc/libraries");
1533
+ const previous = await readLock2(file);
1534
+ const installed = {};
1535
+ const fetcher = options.fetcher ?? fetch;
1536
+ await mkdir8(store, { recursive: true });
1537
+ for (const [title, dependency] of Object.entries(dependencies)) {
1538
+ component2(title);
1539
+ const settings = typeof dependency === "string" ? { version: dependency } : dependency;
1540
+ const locked = previous.dependencies[title];
1541
+ const prior = locked ? { ...locked, path: resolve10(root, locked.path) } : undefined;
1542
+ const same = prior !== undefined && prior.namespace === settings.namespace && ("path" in settings ? prior.url === undefined && prior.path === resolve10(root, settings.path) : prior.version === settings.version && prior.company === (settings.company ?? "System"));
1543
+ if (same) {
1544
+ try {
1545
+ if (hash2(await readFile8(prior.path)) === prior.sha256) {
1546
+ installed[title] = prior;
1547
+ continue;
1548
+ }
1549
+ } catch {}
1550
+ if (options.frozen) {
1551
+ throw new Error(`Locked library ${title} is missing or changed.`);
1552
+ }
1553
+ } else if (options.frozen) {
1554
+ throw new Error(`Dependency ${title} differs from tsplc.lock.json.`);
1555
+ }
1556
+ if ("path" in settings) {
1557
+ const path = resolve10(root, settings.path);
1558
+ if (!libraryFile2.test(path)) {
1559
+ throw new Error(`${title}: expected a .library or .compiled-library file.`);
1560
+ }
1561
+ installed[title] = {
1562
+ title,
1563
+ path,
1564
+ sha256: hash2(await readFile8(path)),
1565
+ ...settings.namespace ? { namespace: settings.namespace } : {}
1566
+ };
1567
+ } else {
1568
+ const company = settings.company ?? "System";
1569
+ const payload = await validateLibrary2(title, settings.version, company, fetcher);
1570
+ const result = await response2(payload.url, fetcher);
1571
+ const data = new Uint8Array(await result.arrayBuffer());
1572
+ if (!data.length || data.length > 256 * 1024 * 1024) {
1573
+ throw new Error(`${title}: invalid library payload size.`);
1574
+ }
1575
+ const sha256 = hash2(data);
1576
+ if (same && prior.sha256 !== sha256) {
1577
+ throw new Error(`Registry payload changed for locked library ${title} ${settings.version}.`);
1578
+ }
1579
+ const path = resolve10(store, `${sha256}-${basename4(payload.filename)}`);
1580
+ const temp = `${path}.${randomUUID4()}.tmp`;
1581
+ await writeFile6(temp, data, { flag: "wx" });
1582
+ await rename4(temp, path);
1583
+ installed[title] = {
1584
+ title,
1585
+ company,
1586
+ version: settings.version,
1587
+ path,
1588
+ sha256,
1589
+ url: payload.url,
1590
+ ...settings.namespace ? { namespace: settings.namespace } : {}
1591
+ };
1592
+ }
1593
+ }
1594
+ if (options.frozen && Object.keys(previous.dependencies).some((name) => !Object.hasOwn(dependencies, name))) {
1595
+ throw new Error("Removed dependencies differ from tsplc.lock.json.");
1596
+ }
1597
+ if (!options.frozen) {
1598
+ const temp = `${file}.${randomUUID4()}.tmp`;
1599
+ const portable = Object.fromEntries(Object.entries(installed).map(([title, library]) => [
1600
+ title,
1601
+ {
1602
+ ...library,
1603
+ path: relative3(root, library.path).replaceAll("\\", "/")
1604
+ }
1605
+ ]));
1606
+ await writeFile6(temp, JSON.stringify({ version: 1, dependencies: portable }, null, 2) + `
1607
+ `);
1608
+ await rename4(temp, file);
1609
+ }
1610
+ return Object.values(installed);
1611
+ }
1612
+
1341
1613
  // packages/build/src/run.ts
1342
- import { execFile as execFile6 } from "node:child_process";
1343
- import { mkdtemp as mkdtemp5, readFile as readFile8, rm as rm7, writeFile as writeFile6 } from "node:fs/promises";
1614
+ import { mkdtemp as mkdtemp5, readFile as readFile9, rm as rm7, writeFile as writeFile7 } from "node:fs/promises";
1344
1615
  import { tmpdir as tmpdir5 } from "node:os";
1345
- import { basename as basename4, dirname as dirname2, join } from "node:path";
1616
+ import { basename as basename5, dirname as dirname2, join } from "node:path";
1346
1617
  import { setTimeout as delay2 } from "node:timers/promises";
1347
- import { promisify as promisify6 } from "node:util";
1348
- import { z as z6 } from "zod";
1618
+ import { z as z11 } from "zod";
1349
1619
 
1350
1620
  // packages/build/src/runtime-status.ts
1351
1621
  var getApplicationStatus = (log, application, startedAt) => {
@@ -1363,10 +1633,9 @@ var getApplicationStatus = (log, application, startedAt) => {
1363
1633
  };
1364
1634
 
1365
1635
  // packages/build/src/run.ts
1366
- var execute6 = promisify6(execFile6);
1367
- var stateSchema = z6.object({
1368
- Running: z6.boolean(),
1369
- StartedAt: z6.iso.datetime({ offset: true })
1636
+ var stateSchema = z11.object({
1637
+ Running: z11.boolean(),
1638
+ StartedAt: z11.iso.datetime({ offset: true })
1370
1639
  });
1371
1640
  var service = "plc";
1372
1641
  var runtimeProject = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
@@ -1379,7 +1648,10 @@ var runtimeDefinition = (name) => ({
1379
1648
  init: true,
1380
1649
  ports: ["127.0.0.1:4840:4840", "127.0.0.1:11740:11740"],
1381
1650
  cap_add: ["SYS_NICE", "IPC_LOCK"],
1382
- volumes: ["control-conf:/conf/codesyscontrol", "control-data:/data/codesyscontrol"],
1651
+ volumes: [
1652
+ "control-conf:/conf/codesyscontrol",
1653
+ "control-data:/data/codesyscontrol"
1654
+ ],
1383
1655
  restart: "no"
1384
1656
  }
1385
1657
  },
@@ -1394,16 +1666,13 @@ var runProject = async (config, name) => withWorkerLock(config, async () => {
1394
1666
  const definitionDirectory = await mkdtemp5(join(tmpdir5(), "tsplc-runtime-"));
1395
1667
  try {
1396
1668
  const composeFile = join(definitionDirectory, "compose.yaml");
1397
- await writeFile6(composeFile, JSON.stringify(runtimeDefinition(name)));
1398
- const docker = (...args) => execute6("docker", args, {
1399
- timeout: config.timeouts.runtime,
1400
- maxBuffer: 8 * 1024 * 1024
1401
- });
1669
+ await writeFile7(composeFile, JSON.stringify(runtimeDefinition(name)));
1670
+ const docker = (...args) => captureDocker(args, config.timeouts.runtime);
1402
1671
  const compose = (...args) => docker("compose", "--project-name", runtimeProject(name), "--file", composeFile, ...args);
1403
- const installer = await readFile8(new URL("../runtime/install.sh", import.meta.url), "utf8");
1672
+ const installer = await readFile9(new URL("../runtime/install.sh", import.meta.url), "utf8");
1404
1673
  console.log(`Installing ${build.application} in Docker service ${service}`);
1405
1674
  await compose("stop", service);
1406
- await compose("run", "--rm", "--no-deps", "-T", "--volume", `${dirname2(build.output)}:/codesys-build:ro`, "--entrypoint", "/bin/sh", service, "-c", installer, "codesys-build-install", build.application, basename4(build.output, ".app"));
1675
+ await compose("run", "--rm", "--no-deps", "-T", "--volume", `${dirname2(build.output)}:/codesys-build:ro`, "--entrypoint", "/bin/sh", service, "-c", installer, "codesys-build-install", build.application, basename5(build.output, ".app"));
1407
1676
  await compose("up", "--detach", "--no-deps", service);
1408
1677
  const containers = (await compose("ps", "--all", "--quiet", service)).stdout.trim().split(/\s+/).filter(Boolean);
1409
1678
  if (containers.length !== 1 || !containers[0]) {
@@ -1436,8 +1705,9 @@ ${log.split(`
1436
1705
  });
1437
1706
 
1438
1707
  // packages/build/src/sources.ts
1439
- import { readdir, readFile as readFile9 } from "node:fs/promises";
1440
- import { basename as basename5, resolve as resolve10 } from "node:path";
1708
+ import { readdir, readFile as readFile10 } from "node:fs/promises";
1709
+ import { basename as basename6, resolve as resolve11 } from "node:path";
1710
+ import { identifierPattern as identifierPattern4 } from "@tsplc/iec/st";
1441
1711
  var prefixes = {
1442
1712
  FB: "function_block",
1443
1713
  PRG: "program",
@@ -1469,7 +1739,7 @@ var assertUnique = (objects, scope) => {
1469
1739
  }
1470
1740
  };
1471
1741
  var readUnit = async (name, files, role, interfaceMember = false) => {
1472
- if (!/^[A-Za-z_][A-Za-z_0-9]*$/.test(name)) {
1742
+ if (!identifierPattern4.test(name)) {
1473
1743
  throw new Error(`Invalid IEC object name: ${name}`);
1474
1744
  }
1475
1745
  for (const [part, candidates] of Object.entries(files)) {
@@ -1495,7 +1765,7 @@ var readUnit = async (name, files, role, interfaceMember = false) => {
1495
1765
  kind: "action",
1496
1766
  name,
1497
1767
  declaration: "",
1498
- implementation: await readFile9(combined, "utf8"),
1768
+ implementation: await readFile10(combined, "utf8"),
1499
1769
  source: combined
1500
1770
  };
1501
1771
  }
@@ -1503,7 +1773,7 @@ var readUnit = async (name, files, role, interfaceMember = false) => {
1503
1773
  if (!combined) {
1504
1774
  throw new Error(`Property accessors use one .st file: ${path}`);
1505
1775
  }
1506
- const body = await readFile9(combined, "utf8");
1776
+ const body = await readFile10(combined, "utf8");
1507
1777
  const header = `METHOD ${name}
1508
1778
  `;
1509
1779
  const parsed = parseSource(`${header}${body}
@@ -1522,7 +1792,7 @@ END_METHOD`, {
1522
1792
  throw new Error(`Missing declaration for ${path}`);
1523
1793
  }
1524
1794
  const sourcePath = combined ?? declaration ?? path;
1525
- const parsed = parseSource(await readFile9(sourcePath, "utf8"), {
1795
+ const parsed = parseSource(await readFile10(sourcePath, "utf8"), {
1526
1796
  filename: sourcePath,
1527
1797
  name,
1528
1798
  declarationOnly: !combined || interfaceMember
@@ -1549,7 +1819,7 @@ END_METHOD`, {
1549
1819
  }
1550
1820
  return {
1551
1821
  ...parsed,
1552
- ...implementation ? { implementation: await readFile9(implementation, "utf8") } : {},
1822
+ ...implementation ? { implementation: await readFile10(implementation, "utf8") } : {},
1553
1823
  source: sourcePath
1554
1824
  };
1555
1825
  };
@@ -1560,7 +1830,7 @@ var loadSources2 = async (config) => {
1560
1830
  const groups = new Map;
1561
1831
  for (const entry of entries) {
1562
1832
  if (entry.isSymbolicLink()) {
1563
- throw new Error(`Source symlinks are not supported: ${resolve10(directory, entry.name)}`);
1833
+ throw new Error(`Source symlinks are not supported: ${resolve11(directory, entry.name)}`);
1564
1834
  }
1565
1835
  if (!entry.isFile() || !/\.st$/i.test(entry.name)) {
1566
1836
  continue;
@@ -1568,7 +1838,7 @@ var loadSources2 = async (config) => {
1568
1838
  const stem = entry.name.slice(0, -3);
1569
1839
  const suffix = /^(.*)\.(declaration|implementation)$/.exec(stem);
1570
1840
  const generic = ["source", "declaration", "implementation"].includes(stem);
1571
- const name = generic ? basename5(directory) : suffix?.[1] ?? stem;
1841
+ const name = generic ? basename6(directory) : suffix?.[1] ?? stem;
1572
1842
  const section = suffix?.[2] ?? stem;
1573
1843
  const part = section === "declaration" || section === "implementation" ? section : "combined";
1574
1844
  const key = name.toLowerCase();
@@ -1576,11 +1846,11 @@ var loadSources2 = async (config) => {
1576
1846
  name,
1577
1847
  files: { combined: [], declaration: [], implementation: [] }
1578
1848
  };
1579
- group.files[part].push(resolve10(directory, entry.name));
1849
+ group.files[part].push(resolve11(directory, entry.name));
1580
1850
  groups.set(key, group);
1581
1851
  }
1582
1852
  const units = [];
1583
- const ownKey = basename5(directory).toLowerCase();
1853
+ const ownKey = basename6(directory).toLowerCase();
1584
1854
  const ordered = [...groups].sort(([a], [b]) => Number(b === ownKey) - Number(a === ownKey));
1585
1855
  for (const [key, { name, files }] of ordered) {
1586
1856
  const ownProperty = units.find((unit) => unit.kind === "property" && unit.name.toLowerCase() === ownKey);
@@ -1614,19 +1884,20 @@ var loadSources2 = async (config) => {
1614
1884
  if (own.kind === "property" || own.kind === "interface" && childRole === "action") {
1615
1885
  throw new Error(`Unsupported ${entry.name} under ${own.name}`);
1616
1886
  }
1617
- await visit(resolve10(directory, entry.name), [], own, childRole);
1887
+ await visit(resolve11(directory, entry.name), [], own, childRole);
1618
1888
  } else if (parent) {
1619
- await visit(resolve10(directory, entry.name), [], parent, role);
1889
+ await visit(resolve11(directory, entry.name), [], parent, role);
1620
1890
  } else {
1621
- await visit(resolve10(directory, entry.name), [...folder, entry.name]);
1891
+ await visit(resolve11(directory, entry.name), [...folder, entry.name]);
1622
1892
  }
1623
1893
  }
1624
1894
  };
1625
- await visit(resolve10(config.sourceDir), []);
1895
+ await visit(resolve11(config.sourceDir), []);
1626
1896
  assertUnique(objects, "Application");
1627
- if (config.io)
1897
+ if (config.io) {
1628
1898
  bindStructuredTextIo(objects, config.io);
1629
- const entry = objects.find((object) => object.source === resolve10(config.entry));
1899
+ }
1900
+ const entry = objects.find((object) => object.source === resolve11(config.entry));
1630
1901
  if (!entry) {
1631
1902
  throw new Error(`Entry is not a discovered source: ${config.entry}`);
1632
1903
  }
@@ -1635,15 +1906,28 @@ var loadSources2 = async (config) => {
1635
1906
  }
1636
1907
  if (config.tasks) {
1637
1908
  const programs = new Set(objects.filter((object) => object.kind === "program").map((object) => object.name));
1638
- for (const task of config.tasks)
1639
- for (const program of task.programs)
1640
- if (!programs.has(program))
1909
+ for (const task of config.tasks) {
1910
+ for (const program of task.programs) {
1911
+ if (!programs.has(program)) {
1641
1912
  throw new Error(`Task ${task.name} references an undiscovered PROGRAM ${program}`);
1913
+ }
1914
+ }
1915
+ }
1642
1916
  }
1643
1917
  return { entry: entry.name, objects };
1644
1918
  };
1645
1919
 
1646
1920
  // packages/build/src/cli.ts
1921
+ var commandSchema = z12.enum([
1922
+ "configure",
1923
+ "install",
1924
+ "check",
1925
+ "build",
1926
+ "run",
1927
+ "download",
1928
+ "online-change",
1929
+ "inspect"
1930
+ ]);
1647
1931
  async function main() {
1648
1932
  const { values, positionals } = parseArgs({
1649
1933
  allowPositionals: true,
@@ -1656,75 +1940,67 @@ async function main() {
1656
1940
  runtime: { type: "boolean" }
1657
1941
  }
1658
1942
  });
1659
- const command = positionals[0];
1660
- const commands = new Set([
1661
- "configure",
1662
- "install",
1663
- "check",
1664
- "build",
1665
- "run",
1666
- "download",
1667
- "online-change",
1668
- "inspect"
1669
- ]);
1670
- if (positionals.length > 1)
1943
+ const [name] = positionals;
1944
+ if (positionals.length > 1) {
1671
1945
  throw new Error("Specify one command.");
1672
- if (!command || values.help) {
1946
+ }
1947
+ if (!name || values.help) {
1673
1948
  console.log("tsplc-build configure|install|check|build|run|download|online-change|inspect [--config tsplc.config.ts] [--read symbol] [--runtime]");
1674
1949
  return;
1675
1950
  }
1676
- if (!commands.has(command))
1677
- throw new Error(`Unknown command ${command}.`);
1678
- if (values.runtime && command !== "configure")
1951
+ const parsed = commandSchema.safeParse(name);
1952
+ if (!parsed.success) {
1953
+ throw new Error(`Unknown command ${name}.`);
1954
+ }
1955
+ const command = parsed.data;
1956
+ if (values.runtime && command !== "configure") {
1679
1957
  throw new Error("--runtime applies only to configure.");
1958
+ }
1680
1959
  if (command === "configure") {
1681
1960
  await (values.runtime ? configureRuntime() : configureDocker());
1682
1961
  return;
1683
1962
  }
1684
- const { config, configFile, root } = await loadTsplcConfig(values.config);
1963
+ const loaded = await loadTsplcConfig(values.config);
1964
+ const { config, configFile, root } = loaded;
1685
1965
  if (command === "install") {
1686
- const libraries = await installLibraries(config.dependencies, root, {
1966
+ const libraries = await installLibraries2(config.dependencies, root, {
1687
1967
  frozen: values["frozen-lockfile"]
1688
1968
  });
1689
1969
  console.log(`Installed ${libraries.length} CODESYS libraries.`);
1690
1970
  return;
1691
1971
  }
1692
- if (!config.build)
1972
+ if (!config.build) {
1693
1973
  throw new Error("Configure build options in tsplc.config.ts.");
1974
+ }
1694
1975
  if (command === "inspect") {
1695
- console.log(JSON.stringify(await inspectController(resolveConfig2({ ...config.build, controller: controllerFor(config, command) }, configFile), values.read), null, 2));
1976
+ console.log(JSON.stringify(await inspectController(resolveConfig2({ ...config.build, controller: controllerFor2(config, command) }, configFile), values.read), null, 2));
1696
1977
  return;
1697
1978
  }
1698
- if (config.compiler)
1979
+ if (config.compiler) {
1699
1980
  throw new Error("Use tsplc for TypeScript projects. tsplc-build accepts raw Structured Text.");
1700
- const build = rawBuildConfig(config);
1701
- const hardware = await loadHardware(config, root);
1702
- const io = resolveIo(config, hardware);
1981
+ }
1703
1982
  if (command === "check") {
1704
- const sources = await loadSources2(resolveConfig2({ ...build, io }, configFile));
1983
+ const build = rawBuildConfig2(config);
1984
+ const hardware = await loadHardware2(config, root);
1985
+ const sources = await loadSources2(resolveConfig2({ ...build, io: resolveIo2(config, hardware) }, configFile));
1705
1986
  console.log(`Validated ${sources.objects.length} Structured Text objects.`);
1706
1987
  return;
1707
1988
  }
1708
- const libraries = await installLibraries(config.dependencies, root, {
1709
- frozen: values["frozen-lockfile"]
1989
+ const settings = await rawEngineeringSettings(loaded, {
1990
+ command,
1991
+ frozenLockfile: values["frozen-lockfile"]
1710
1992
  });
1711
- const settings = resolveConfig2({
1712
- ...build,
1713
- libraries,
1714
- io,
1715
- deviceTree: await deviceTree(config, hardware),
1716
- controller: controllerFor(config, command)
1717
- }, configFile);
1718
- if (command === "build")
1993
+ if (command === "build") {
1719
1994
  await buildProject(settings);
1720
- else if (command === "run") {
1995
+ } else if (command === "run") {
1721
1996
  await buildProject(settings);
1722
1997
  await runProject(settings, config.name);
1723
- } else if (command === "download" || command === "online-change")
1998
+ } else {
1724
1999
  await updateController(settings, command, {
1725
2000
  initializeUser: values["initialize-user"],
1726
2001
  read: values.read
1727
2002
  });
2003
+ }
1728
2004
  }
1729
2005
  try {
1730
2006
  await main();
@@ -1733,5 +2009,5 @@ try {
1733
2009
  process.exitCode = 1;
1734
2010
  }
1735
2011
 
1736
- //# debugId=4ED16E2EF93604DB64756E2164756E21
2012
+ //# debugId=F72D15EC02DA92D364756E2164756E21
1737
2013
  //# sourceMappingURL=cli.js.map