@tsplc/build 0.2.17 → 0.2.18

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/index.js CHANGED
@@ -1,20 +1,17 @@
1
1
  // packages/build/src/artifacts.ts
2
- import { copyFile, cp, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
2
+ import {
3
+ copyFile,
4
+ cp,
5
+ readFile,
6
+ rename,
7
+ rm,
8
+ stat,
9
+ writeFile
10
+ } from "node:fs/promises";
3
11
  import { resolve } from "node:path";
12
+ import { identifierPattern } from "@tsplc/iec/st";
4
13
  import { z } from "zod";
5
-
6
- // packages/build/src/config.ts
7
- import {
8
- configSchema,
9
- controllerSchema,
10
- cyclicTasksSchema,
11
- dockerImage,
12
- defineBuildConfig,
13
- resolveConfig,
14
- loadConfig
15
- } from "@tsplc/config/build";
16
-
17
- // packages/build/src/artifacts.ts
14
+ import { cyclicTasksSchema } from "@tsplc/config/build";
18
15
  var buildFiles = {
19
16
  project: "Application.project",
20
17
  output: "runtime/Application.app",
@@ -25,7 +22,7 @@ var buildFiles = {
25
22
  };
26
23
  var receiptSchema = z.object({
27
24
  mode: z.literal("build"),
28
- application: z.string().regex(/^[A-Za-z_][A-Za-z_0-9]*$/),
25
+ application: z.string().regex(identifierPattern),
29
26
  tasks: cyclicTasksSchema.optional()
30
27
  });
31
28
  var readBuild = async (directory) => {
@@ -35,7 +32,11 @@ var readBuild = async (directory) => {
35
32
  cause: receipt.error
36
33
  });
37
34
  }
38
- for (const file of [buildFiles.project, buildFiles.output, buildFiles.checksum]) {
35
+ for (const file of [
36
+ buildFiles.project,
37
+ buildFiles.output,
38
+ buildFiles.checksum
39
+ ]) {
39
40
  const artifact = await stat(resolve(directory, file));
40
41
  if (!artifact.isFile() || artifact.size === 0) {
41
42
  throw new Error(`CODESYS produced an empty artifact: ${file}`);
@@ -50,13 +51,16 @@ var readBuild = async (directory) => {
50
51
  };
51
52
  };
52
53
 
54
+ // packages/build/src/build.ts
55
+ import { dockerImage as dockerImage2 } from "@tsplc/config/build";
56
+
53
57
  // packages/build/src/docker-build.ts
54
- import { execFile } from "node:child_process";
55
58
  import { randomUUID } from "node:crypto";
56
59
  import { cp as cp4, mkdir as mkdir3, mkdtemp as mkdtemp2, readFile as readFile3, rm as rm3 } from "node:fs/promises";
57
60
  import { tmpdir as tmpdir2 } from "node:os";
58
61
  import { resolve as resolve5 } from "node:path";
59
- import { promisify } from "node:util";
62
+ import { z as z3 } from "zod";
63
+ import { dockerImage } from "@tsplc/config/build";
60
64
 
61
65
  // packages/build/src/docker-context.ts
62
66
  import { cp as cp2, mkdir, mkdtemp, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
@@ -70,23 +74,39 @@ import { fileURLToPath } from "node:url";
70
74
  var packageDirectory = resolve2(fileURLToPath(new URL("..", import.meta.url)));
71
75
 
72
76
  // packages/build/src/docker-context.ts
77
+ var containerPackages = [
78
+ {
79
+ entry: "@tsplc/config/build",
80
+ directory: "shared-config",
81
+ files: ["src", "templates", "package.json"]
82
+ },
83
+ {
84
+ entry: "@tsplc/iec",
85
+ directory: "shared-iec",
86
+ files: ["src", "package.json"]
87
+ }
88
+ ];
73
89
  async function prepareDockerContext() {
74
90
  const context = await mkdtemp(resolve3(tmpdir(), "tsplc-docker-"));
75
91
  try {
76
- for (const directory of ["src", "python", "docker", "runtime"])
92
+ for (const directory of ["src", "python", "docker", "runtime"]) {
77
93
  await cp2(resolve3(packageDirectory, directory), resolve3(context, directory), {
78
94
  recursive: true
79
95
  });
80
- const configRoot = resolve3(dirname(createRequire(import.meta.url).resolve("@tsplc/config/build")), "..");
81
- await mkdir(resolve3(context, "shared-config"));
82
- await cp2(resolve3(configRoot, "src"), resolve3(context, "shared-config/src"), {
83
- recursive: true
84
- });
85
- await cp2(resolve3(configRoot, "templates"), resolve3(context, "shared-config/templates"), {
86
- recursive: true
87
- });
88
- await cp2(resolve3(configRoot, "package.json"), resolve3(context, "shared-config/package.json"));
89
- await writeFile2(resolve3(context, "package.json"), JSON.stringify({ type: "module", dependencies: { zod: "4.3.6", jiti: "2.7.0" } }));
96
+ }
97
+ for (const { entry, directory, files } of containerPackages) {
98
+ const root = resolve3(dirname(createRequire(import.meta.url).resolve(entry)), "..");
99
+ await mkdir(resolve3(context, directory));
100
+ for (const file of files) {
101
+ await cp2(resolve3(root, file), resolve3(context, directory, file), {
102
+ recursive: true
103
+ });
104
+ }
105
+ }
106
+ await writeFile2(resolve3(context, "package.json"), JSON.stringify({
107
+ type: "module",
108
+ dependencies: { zod: "4.3.6", jiti: "2.7.0" }
109
+ }));
90
110
  return context;
91
111
  } catch (cause) {
92
112
  await rm2(context, { recursive: true, force: true });
@@ -132,13 +152,20 @@ var buildFailureSchema = z2.strictObject({
132
152
  });
133
153
 
134
154
  // packages/build/src/docker-run.ts
135
- import { spawn } from "node:child_process";
155
+ import { execFile, spawn } from "node:child_process";
136
156
  import { createHash } from "node:crypto";
137
157
  import { copyFile as copyFile2, cp as cp3, mkdir as mkdir2, readFile as readFile2, writeFile as writeFile3 } from "node:fs/promises";
138
158
  import { basename, posix, relative, resolve as resolve4, sep } from "node:path";
159
+ import { promisify } from "node:util";
160
+ var execute = promisify(execFile);
161
+ var captureDocker = (args, timeout) => execute("docker", args, { timeout, maxBuffer: 8 * 1024 * 1024 });
139
162
  var runDocker = (args, failure) => new Promise((accept, reject) => {
140
163
  const child = spawn("docker", args, {
141
- stdio: ["inherit", process.env["TSPLC_LOG_STDERR"] === "1" ? 2 : "inherit", "inherit"]
164
+ stdio: [
165
+ "inherit",
166
+ process.env["TSPLC_LOG_STDERR"] === "1" ? 2 : "inherit",
167
+ "inherit"
168
+ ]
142
169
  });
143
170
  const interrupt = () => child.kill("SIGINT");
144
171
  const terminate = () => child.kill("SIGTERM");
@@ -165,13 +192,15 @@ var runDocker = (args, failure) => new Promise((accept, reject) => {
165
192
  });
166
193
  var bindMount = (source, target, readonly = false) => `type=bind,"source=${source.replaceAll('"', '""')}",target=${target}${readonly ? ",readonly" : ""}`;
167
194
  async function mountLibraries(libraries, directory, root = "/input") {
168
- if (!libraries?.length)
195
+ if (!libraries?.length) {
169
196
  return;
197
+ }
170
198
  await mkdir2(resolve4(directory, "libraries"), { recursive: true });
171
199
  return Promise.all(libraries.map(async (library) => {
172
200
  const data = await readFile2(library.path);
173
- if (createHash("sha256").update(data).digest("hex") !== library.sha256)
201
+ if (createHash("sha256").update(data).digest("hex") !== library.sha256) {
174
202
  throw new Error(`Library changed after installation: ${library.title}`);
203
+ }
175
204
  const filename = `${library.sha256}-${basename(library.path)}`;
176
205
  await writeFile3(resolve4(directory, "libraries", filename), data);
177
206
  return { ...library, path: `${root}/libraries/${filename}` };
@@ -191,7 +220,9 @@ var containerConfig = (config, paths, libraries) => ({
191
220
  });
192
221
  var writeOperationRequest = async (config, directory, root) => {
193
222
  await mkdir2(directory, { recursive: true });
194
- await cp3(config.sourceDir, resolve4(directory, "sources"), { recursive: true });
223
+ await cp3(config.sourceDir, resolve4(directory, "sources"), {
224
+ recursive: true
225
+ });
195
226
  await copyFile2(config.template, resolve4(directory, "template.project"));
196
227
  await writeFile3(resolve4(directory, "config.json"), JSON.stringify(containerConfig(config, { sourceDir: `${root}/sources`, template: `${root}/template.project` }, await mountLibraries(config.libraries, directory, root))));
197
228
  return `${root}/config.json`;
@@ -216,9 +247,8 @@ var prepareContainerRun = async (config, requestDirectory, options) => {
216
247
  };
217
248
 
218
249
  // packages/build/src/docker-build.ts
219
- var execute = promisify(execFile);
220
250
  var publishedImage = async (image) => {
221
- const { version } = JSON.parse(await readFile3(resolve5(packageDirectory, "package.json"), "utf8"));
251
+ const { version } = z3.object({ version: z3.string() }).parse(JSON.parse(await readFile3(resolve5(packageDirectory, "package.json"), "utf8")));
222
252
  return `ghcr.io/livingforjesus/${image.split(":")[0]}:${version}`;
223
253
  };
224
254
  var pullPublished = async (image) => {
@@ -235,7 +265,7 @@ var pullPublished = async (image) => {
235
265
  };
236
266
  var configureDocker = async () => {
237
267
  const image = dockerImage;
238
- const { stdout } = await execute("docker", ["info", "--format", "{{.OSType}}/{{.Architecture}}"], { timeout: 30000 }).catch((cause) => {
268
+ const { stdout } = await captureDocker(["info", "--format", "{{.OSType}}/{{.Architecture}}"], 30000).catch((cause) => {
239
269
  throw new Error("Cannot connect to Docker. Install and start Docker Desktop or Docker Engine", {
240
270
  cause
241
271
  });
@@ -245,8 +275,9 @@ var configureDocker = async () => {
245
275
  if (!arm && architecture !== "linux/x86_64" && architecture !== "linux/amd64") {
246
276
  throw new Error("The builder requires a Linux Docker server on ARM64 or AMD64");
247
277
  }
248
- if (await pullPublished(image))
278
+ if (await pullPublished(image)) {
249
279
  return image;
280
+ }
250
281
  const context = await mkdtemp2(resolve5(tmpdir2(), "codesys-installer-"));
251
282
  let buildContext;
252
283
  try {
@@ -291,16 +322,35 @@ var runtimeImage = "tsplc-control-linux-sl:4.22.0.0";
291
322
  var configureRuntime = async () => {
292
323
  const context = resolve5(packageDirectory, "docker/control-linux-sl");
293
324
  console.log(`Preparing the local PLC runtime (${runtimeImage}).`);
294
- await runDocker(["build", "--platform", "linux/amd64", "--progress", "plain", "-t", runtimeImage, context], (status) => `Runtime image build failed (${status}). Review the image-build output`);
325
+ await runDocker([
326
+ "build",
327
+ "--platform",
328
+ "linux/amd64",
329
+ "--progress",
330
+ "plain",
331
+ "-t",
332
+ runtimeImage,
333
+ context
334
+ ], (status) => `Runtime image build failed (${status}). Review the image-build output`);
295
335
  return runtimeImage;
296
336
  };
297
337
  var gatewayImage = "tsplc-edge-gateway:4.22.0.0";
298
338
  var configureGateway = async () => {
299
- if (await pullPublished(gatewayImage))
339
+ if (await pullPublished(gatewayImage)) {
300
340
  return gatewayImage;
341
+ }
301
342
  const context = resolve5(packageDirectory, "docker/edge-gateway");
302
343
  console.log(`Preparing the CODESYS gateway (${gatewayImage}).`);
303
- await runDocker(["build", "--platform", "linux/amd64", "--progress", "plain", "-t", gatewayImage, context], (status) => `Gateway image build failed (${status}). Review the image-build output`);
344
+ await runDocker([
345
+ "build",
346
+ "--platform",
347
+ "linux/amd64",
348
+ "--progress",
349
+ "plain",
350
+ "-t",
351
+ gatewayImage,
352
+ context
353
+ ], (status) => `Gateway image build failed (${status}). Review the image-build output`);
304
354
  return gatewayImage;
305
355
  };
306
356
  var buildInDocker = async (config, image) => {
@@ -313,7 +363,10 @@ var buildInDocker = async (config, image) => {
313
363
  const args = [
314
364
  "run",
315
365
  "--rm",
316
- ...await prepareContainerRun(config, requestDirectory, { network: "none", sources: true }),
366
+ ...await prepareContainerRun(config, requestDirectory, {
367
+ network: "none",
368
+ sources: true
369
+ }),
317
370
  image,
318
371
  "--request",
319
372
  "/input/config.json",
@@ -326,21 +379,25 @@ var buildInDocker = async (config, image) => {
326
379
  } catch (cause) {
327
380
  const message = cause instanceof Error ? cause.message : String(cause);
328
381
  const failure = await readFile3(failurePath, "utf8").then((text) => buildFailureSchema.parse(JSON.parse(text))).catch((error) => {
329
- if (error instanceof Error && "code" in error && error.code === "ENOENT")
382
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
330
383
  return;
384
+ }
331
385
  throw new AggregateError([cause, error], `${message}. Invalid CODESYS failure metadata (${failurePath})`, { cause: error });
332
386
  });
333
- if (!failure)
387
+ if (!failure) {
334
388
  throw cause;
335
- if (failure.operationId !== operationId)
389
+ }
390
+ if (failure.operationId !== operationId) {
336
391
  throw new Error(`${message}. CODESYS failure metadata belongs to a different Docker build`, {
337
392
  cause
338
393
  });
394
+ }
339
395
  if (cause instanceof Error) {
340
396
  cause.message = `${message}
341
397
  ${failure.message}`;
342
- if (failure.diagnostics.length)
398
+ if (failure.diagnostics.length) {
343
399
  cause.cause = new CodesysCompilerError(failure.message, failure.diagnostics);
400
+ }
344
401
  }
345
402
  throw cause;
346
403
  }
@@ -364,10 +421,9 @@ import {
364
421
  } from "node:fs/promises";
365
422
  import { resolve as resolve6 } from "node:path";
366
423
  import { setTimeout as delay } from "node:timers/promises";
367
- import { z as z4 } from "zod";
424
+ import { z as z5 } from "zod";
368
425
 
369
426
  // packages/build/src/host/codesys-command.ts
370
- import { commandArgumentSchema } from "@tsplc/config/build";
371
427
  var codesysCommand = [
372
428
  "@echo off",
373
429
  "setlocal DisableDelayedExpansion",
@@ -382,28 +438,31 @@ var codesysCommand = [
382
438
  // packages/build/src/host/codesys-host.ts
383
439
  import { execFile as execFile3, spawn as spawn2 } from "node:child_process";
384
440
  import { promisify as promisify3 } from "node:util";
385
- import { z as z3 } from "zod";
441
+ import { z as z4 } from "zod";
386
442
 
387
443
  // packages/build/src/host/windows-path.ts
388
444
  import { execFile as execFile2 } from "node:child_process";
389
445
  import { promisify as promisify2 } from "node:util";
390
- import { codesysTimeouts } from "@tsplc/config/build";
446
+ import {
447
+ codesysTimeouts,
448
+ commandArgumentSchema
449
+ } from "@tsplc/config/build";
391
450
  var execute2 = promisify2(execFile2);
392
451
 
393
452
  // packages/build/src/host/codesys-host.ts
394
453
  var execute3 = promisify3(execFile3);
395
- var exitSchema = z3.object({
396
- pid: z3.int().positive(),
397
- code: z3.int().nullable(),
398
- signal: z3.string().nullable()
454
+ var exitSchema = z4.object({
455
+ pid: z4.int().positive(),
456
+ code: z4.int().nullable(),
457
+ signal: z4.string().nullable()
399
458
  });
400
459
 
401
460
  // packages/build/src/host/codesys-worker.ts
402
461
  var pythonDirectory = resolve6(packageDirectory, "python");
403
- var sessionSchema = z4.object({
404
- directory: z4.string(),
405
- fingerprint: z4.string(),
406
- pid: z4.int().positive()
462
+ var sessionSchema = z5.object({
463
+ directory: z5.string(),
464
+ fingerprint: z5.string(),
465
+ pid: z5.int().positive()
407
466
  });
408
467
  var hasCode = (error, code) => error instanceof Error && ("code" in error) && error.code === code;
409
468
  var isProcessAlive = (pid) => {
@@ -456,11 +515,23 @@ var withWorkerLock = async (config, run) => {
456
515
  // packages/build/src/sources.ts
457
516
  import { readdir, readFile as readFile5 } from "node:fs/promises";
458
517
  import { basename as basename3, resolve as resolve7 } from "node:path";
518
+ import { identifierPattern as identifierPattern3 } from "@tsplc/iec/st";
459
519
 
460
520
  // packages/build/src/st/parse.ts
461
521
  import { basename as basename2 } from "node:path";
522
+ import {
523
+ globalSections,
524
+ identifierPattern as identifierPattern2,
525
+ qualifiers,
526
+ variableSections as variableSections2
527
+ } from "@tsplc/iec/st";
462
528
 
463
529
  // packages/build/src/st/declarations.ts
530
+ import {
531
+ conditionalDirective,
532
+ modifiers,
533
+ variableSections
534
+ } from "@tsplc/iec/st";
464
535
  var objectKinds = {
465
536
  PROGRAM: "program",
466
537
  FUNCTION_BLOCK: "function_block",
@@ -470,29 +541,6 @@ var objectKinds = {
470
541
  INTERFACE: "interface",
471
542
  PROPERTY: "property"
472
543
  };
473
- var modifiers = new Set([
474
- "PUBLIC",
475
- "PRIVATE",
476
- "PROTECTED",
477
- "INTERNAL",
478
- "FINAL",
479
- "ABSTRACT",
480
- "OVERRIDE"
481
- ]);
482
- var globalSections = new Set(["VAR_GLOBAL", "VAR_CONFIG"]);
483
- var variableSections = new Set([
484
- ...globalSections,
485
- "VAR",
486
- "VAR_INPUT",
487
- "VAR_OUTPUT",
488
- "VAR_IN_OUT",
489
- "VAR_TEMP",
490
- "VAR_STAT",
491
- "VAR_INST",
492
- "VAR_EXTERNAL",
493
- "VAR_ACCESS",
494
- "VAR_GENERIC"
495
- ]);
496
544
  var closingObjects = new Set(Object.keys(objectKinds).map((kind) => `END_${kind}`));
497
545
  var declarationKeywords = new Set([
498
546
  ...Object.keys(objectKinds),
@@ -510,12 +558,7 @@ var declarationKeywords = new Set([
510
558
  "CONFIGURATION",
511
559
  "END_CONFIGURATION"
512
560
  ]);
513
- var conditionalDirective = (token) => {
514
- if (token?.kind === "pragma") {
515
- return /^\{\s*(IF|ELSIF|ELSE|END_IF)\b/i.exec(token.value)?.[1]?.toUpperCase();
516
- }
517
- };
518
- var isDeclarationPragma = (token) => token?.kind === "pragma" && !conditionalDirective(token);
561
+ var isDeclarationPragma = (token) => token?.kind === "pragma" && !conditionalDirective(token.value);
519
562
  var readDeclarationPragmas = (reader) => {
520
563
  while (isDeclarationPragma(reader.peek())) {
521
564
  reader.take();
@@ -609,7 +652,7 @@ var readVariableSection = (reader) => {
609
652
  if (variableSections.has(token.value) || closingObjects.has(token.value)) {
610
653
  reader.fail("Missing END_VAR", token);
611
654
  }
612
- const directive = conditionalDirective(token);
655
+ const directive = token.kind === "pragma" && conditionalDirective(token.value);
613
656
  if (!directive) {
614
657
  continue;
615
658
  }
@@ -661,6 +704,8 @@ var readDeclarationSections = (reader) => {
661
704
  };
662
705
 
663
706
  // packages/build/src/st/lexer.ts
707
+ import { blockCommentEnd, lineCommentEnd, stringEnd } from "@tsplc/iec/st";
708
+
664
709
  class StSyntaxError extends Error {
665
710
  constructor(source, offset, filename, message) {
666
711
  const lines = source.slice(0, offset).split(/\r\n|\r|\n/);
@@ -675,16 +720,7 @@ var tokenize = (source, filename = "<source>") => {
675
720
  throw new StSyntaxError(source, start, filename, message);
676
721
  };
677
722
  const quoted = () => {
678
- const start = offset;
679
- const quote = source[offset++];
680
- while (offset < source.length) {
681
- if (source[offset] === "$") {
682
- offset += 2;
683
- } else if (source[offset++] === quote) {
684
- return;
685
- }
686
- }
687
- fail(start, "Unterminated string");
723
+ offset = stringEnd(source, offset) ?? fail(offset, "Unterminated string");
688
724
  };
689
725
  while (offset < source.length) {
690
726
  const start = offset;
@@ -694,28 +730,11 @@ var tokenize = (source, filename = "<source>") => {
694
730
  continue;
695
731
  }
696
732
  if (source.startsWith("//", offset)) {
697
- while (offset < source.length && !/[\r\n]/.test(source[offset] ?? "")) {
698
- offset++;
699
- }
733
+ offset = lineCommentEnd(source, start);
700
734
  continue;
701
735
  }
702
736
  if (source.startsWith("(*", offset)) {
703
- offset += 2;
704
- let depth = 1;
705
- while (offset < source.length && depth > 0) {
706
- if (source.startsWith("(*", offset)) {
707
- depth++;
708
- offset += 2;
709
- } else if (source.startsWith("*)", offset)) {
710
- depth--;
711
- offset += 2;
712
- } else {
713
- offset++;
714
- }
715
- }
716
- if (depth) {
717
- fail(start, "Unterminated block comment");
718
- }
737
+ offset = blockCommentEnd(source, start) ?? fail(start, "Unterminated block comment");
719
738
  continue;
720
739
  }
721
740
  if (character === "'" || character === '"') {
@@ -865,14 +884,14 @@ var parseGlobals = (reader, options) => {
865
884
  const start = reader.index;
866
885
  readVariableSection(reader);
867
886
  for (const token of reader.tokens.slice(start + 1, reader.index)) {
868
- if (token.kind !== "word" || !["CONSTANT", "RETAIN", "PERSISTENT", "NON_RETAIN"].includes(token.value)) {
887
+ if (token.kind !== "word" || !qualifiers.has(token.value)) {
869
888
  break;
870
889
  }
871
890
  persistent ||= token.value === "PERSISTENT";
872
891
  }
873
892
  }
874
893
  const name = options.name ?? basename2(reader.filename, ".st");
875
- if (!/^[A-Za-z_][A-Za-z_0-9]*$/.test(name)) {
894
+ if (!identifierPattern2.test(name)) {
876
895
  reader.fail("Global list requires an IEC filename or an explicit name", header);
877
896
  }
878
897
  return {
@@ -887,7 +906,7 @@ var validateImplementation = (reader, tokens) => {
887
906
  if (token.kind !== "word") {
888
907
  continue;
889
908
  }
890
- if (variableSections.has(token.value) || token.value === "END_VAR") {
909
+ if (variableSections2.has(token.value) || token.value === "END_VAR") {
891
910
  reader.fail("Variable declaration outside the declaration section; conditional declaration envelopes are not supported", token);
892
911
  }
893
912
  if (declarationKeywords.has(token.value)) {
@@ -956,61 +975,59 @@ var parseSource = (source, options = {}) => {
956
975
  };
957
976
 
958
977
  // packages/build/src/io.ts
959
- var arrayType = /^ARRAY\s*\[\s*(-?\d+)\s*\.\.\s*(-?\d+)\s*\]\s*OF\s+(\w+)$/;
960
- var layout = (type) => {
961
- const array = arrayType.exec(type);
962
- return array ? { element: array[3], length: Number(array[2]) - Number(array[1]) + 1 } : { element: type, length: 1 };
963
- };
964
- var widths = {
965
- BOOL: "X",
966
- BYTE: "B",
967
- SINT: "B",
968
- USINT: "B",
969
- WORD: "W",
970
- INT: "W",
971
- UINT: "W",
972
- DWORD: "D",
973
- DINT: "D",
974
- UDINT: "D",
975
- REAL: "D"
978
+ import { ioArray, ioScalarBits, sizePrefix } from "@tsplc/iec";
979
+ import { qualifiers as qualifiers2, variableSections as variableSections3 } from "@tsplc/iec/st";
980
+ var span = (type) => ioArray(type) ?? { element: type, length: 1 };
981
+ var addressSize = (type) => {
982
+ const bits = ioScalarBits(type);
983
+ return bits === undefined || bits === 64 ? undefined : sizePrefix(bits);
976
984
  };
977
985
  function bindStructuredTextIo(objects, bindings) {
978
986
  const declarations = [];
979
987
  const visit = (object) => {
980
988
  const tokens = tokenize(object.declaration, object.source);
981
- let section = false, start = 0;
982
- for (let i = 0;i < tokens.length; i++) {
983
- const token = tokens[i];
984
- if (variableSections.has(token.value)) {
989
+ let section = false;
990
+ let start = 0;
991
+ for (const [index, token] of tokens.entries()) {
992
+ if (variableSections3.has(token.value)) {
985
993
  section = true;
986
- start = i + 1;
994
+ start = index + 1;
987
995
  continue;
988
996
  }
989
997
  if (token.value === "END_VAR") {
990
998
  section = false;
991
999
  continue;
992
1000
  }
993
- if (!section || token.value !== ";")
1001
+ if (!section || token.value !== ";") {
1002
+ continue;
1003
+ }
1004
+ const part = tokens.slice(start, index).filter((t) => t.kind !== "pragma");
1005
+ start = index + 1;
1006
+ const colon = part.find((t) => t.value === ":");
1007
+ if (!colon) {
994
1008
  continue;
995
- const part = tokens.slice(start, i).filter((t) => t.kind !== "pragma");
996
- start = i + 1;
997
- const colonIndex = part.findIndex((t) => t.value === ":");
998
- if (colonIndex < 1)
1009
+ }
1010
+ const colonIndex = part.indexOf(colon);
1011
+ if (colonIndex < 1) {
999
1012
  continue;
1000
- const names = part.slice(0, colonIndex).filter((t) => t.kind === "word" && !["CONSTANT", "RETAIN", "PERSISTENT", "AT"].includes(t.value));
1001
- const at = part.findIndex((t) => t.value === "AT");
1002
- const variables = at < 0 ? names : names.filter((t) => t.start < part[at].start);
1013
+ }
1014
+ const names = part.slice(0, colonIndex).filter((t) => t.kind === "word" && !qualifiers2.has(t.value) && t.value !== "AT");
1015
+ const at = part.find((t) => t.value === "AT");
1016
+ const variables = at ? names.filter((t) => t.start < at.start) : names;
1003
1017
  const initializer = part.findIndex((t, index) => index > colonIndex && t.value === ":=");
1004
1018
  const typeTokens = part.slice(colonIndex + 1, initializer < 0 ? undefined : initializer);
1005
- const type = typeTokens.length ? object.declaration.slice(typeTokens[0].start, typeTokens.at(-1).end).replace(/\s+/g, " ").toUpperCase() : "";
1006
- for (const name of variables)
1019
+ const [first] = typeTokens;
1020
+ const last = typeTokens.at(-1);
1021
+ const type = first && last ? object.declaration.slice(first.start, last.end).replace(/\s+/g, " ").toUpperCase() : "";
1022
+ for (const name of variables) {
1007
1023
  declarations.push({
1008
1024
  object,
1009
1025
  name: name.value,
1010
1026
  names: variables,
1011
- colon: part[colonIndex],
1027
+ colon,
1012
1028
  type
1013
1029
  });
1030
+ }
1014
1031
  }
1015
1032
  object.children.forEach(visit);
1016
1033
  };
@@ -1018,30 +1035,44 @@ function bindStructuredTextIo(objects, bindings) {
1018
1035
  const edits = new Map;
1019
1036
  for (const [symbol, binding] of Object.entries(bindings)) {
1020
1037
  const parts = symbol.toUpperCase().split(".");
1021
- if (parts.length > 2)
1038
+ if (parts.length > 2) {
1022
1039
  throw new Error(`${symbol}: direct IO maps a scalar declaration, not a nested field.`);
1040
+ }
1023
1041
  const matches = declarations.filter((d) => d.name === parts.at(-1) && (parts.length === 1 || d.object.name.toUpperCase() === parts[0]));
1024
- if (matches.length !== 1)
1042
+ const [declaration, ...others] = matches;
1043
+ if (!declaration || others.length) {
1025
1044
  throw new Error(`${symbol}: expected one ST variable declaration, found ${matches.length}. Use Object.Variable to disambiguate.`);
1026
- const declaration = matches[0];
1027
- if (declaration.names.length !== 1)
1045
+ }
1046
+ const [variable, ...siblings] = declaration.names;
1047
+ if (!variable || siblings.length) {
1028
1048
  throw new Error(`${symbol}: declare mapped IO variables separately.`);
1029
- const declared = layout(declaration.type);
1030
- if (!widths[declared.element] || declared.length > 1 && declared.element === "BOOL" || binding.address[2] !== widths[declared.element])
1049
+ }
1050
+ const declared = span(declaration.type);
1051
+ const size = addressSize(declared.element);
1052
+ if (!size || declared.length > 1 && declared.element === "BOOL" || binding.address[2] !== size) {
1031
1053
  throw new Error(`${symbol}: ${declaration.type} is incompatible with ${binding.address}.`);
1032
- const expected = binding.type && layout(binding.type.replace(/\s+/g, " ").toUpperCase());
1033
- if (expected && (expected.element !== declared.element || expected.length !== declared.length))
1054
+ }
1055
+ const expected = binding.type && span(binding.type.replace(/\s+/g, " ").toUpperCase());
1056
+ if (expected && (expected.element !== declared.element || expected.length !== declared.length)) {
1034
1057
  throw new Error(`${symbol}: expected ${binding.type}, found ${declaration.type}.`);
1058
+ }
1035
1059
  const list = edits.get(declaration.object) ?? [];
1036
- const start = declaration.names[0].end;
1037
- if (list.some((e) => e.start === start))
1060
+ const start = variable.end;
1061
+ if (list.some((e) => e.start === start)) {
1038
1062
  throw new Error(`${symbol}: the variable has more than one IO binding.`);
1039
- list.push({ start, end: declaration.colon.start, text: ` AT ${binding.address} ` });
1063
+ }
1064
+ list.push({
1065
+ start,
1066
+ end: declaration.colon.start,
1067
+ text: ` AT ${binding.address} `
1068
+ });
1040
1069
  edits.set(declaration.object, list);
1041
1070
  }
1042
- for (const [object, list] of edits)
1043
- for (const edit of list.sort((a, b) => b.start - a.start))
1071
+ for (const [object, list] of edits) {
1072
+ for (const edit of list.sort((a, b) => b.start - a.start)) {
1044
1073
  object.declaration = object.declaration.slice(0, edit.start) + edit.text + object.declaration.slice(edit.end);
1074
+ }
1075
+ }
1045
1076
  }
1046
1077
 
1047
1078
  // packages/build/src/sources.ts
@@ -1076,7 +1107,7 @@ var assertUnique = (objects, scope) => {
1076
1107
  }
1077
1108
  };
1078
1109
  var readUnit = async (name, files, role, interfaceMember = false) => {
1079
- if (!/^[A-Za-z_][A-Za-z_0-9]*$/.test(name)) {
1110
+ if (!identifierPattern3.test(name)) {
1080
1111
  throw new Error(`Invalid IEC object name: ${name}`);
1081
1112
  }
1082
1113
  for (const [part, candidates] of Object.entries(files)) {
@@ -1231,8 +1262,9 @@ var loadSources = async (config) => {
1231
1262
  };
1232
1263
  await visit(resolve7(config.sourceDir), []);
1233
1264
  assertUnique(objects, "Application");
1234
- if (config.io)
1265
+ if (config.io) {
1235
1266
  bindStructuredTextIo(objects, config.io);
1267
+ }
1236
1268
  const entry = objects.find((object) => object.source === resolve7(config.entry));
1237
1269
  if (!entry) {
1238
1270
  throw new Error(`Entry is not a discovered source: ${config.entry}`);
@@ -1242,75 +1274,103 @@ var loadSources = async (config) => {
1242
1274
  }
1243
1275
  if (config.tasks) {
1244
1276
  const programs = new Set(objects.filter((object) => object.kind === "program").map((object) => object.name));
1245
- for (const task of config.tasks)
1246
- for (const program of task.programs)
1247
- if (!programs.has(program))
1277
+ for (const task of config.tasks) {
1278
+ for (const program of task.programs) {
1279
+ if (!programs.has(program)) {
1248
1280
  throw new Error(`Task ${task.name} references an undiscovered PROGRAM ${program}`);
1281
+ }
1282
+ }
1283
+ }
1249
1284
  }
1250
1285
  return { entry: entry.name, objects };
1251
1286
  };
1252
1287
 
1253
1288
  // packages/build/src/build.ts
1254
1289
  var buildProject = async (config) => {
1255
- if (!config.docker)
1290
+ if (!config.docker) {
1256
1291
  throw new Error("Builds require a Docker builder image.");
1257
- return buildInDocker(config, dockerImage);
1292
+ }
1293
+ return buildInDocker(config, dockerImage2);
1258
1294
  };
1295
+
1296
+ // packages/build/src/index.ts
1297
+ import {
1298
+ configSchema,
1299
+ defineBuildConfig,
1300
+ loadConfig,
1301
+ resolveConfig as resolveConfig2
1302
+ } from "@tsplc/config/build";
1303
+
1259
1304
  // packages/build/src/controller-online.ts
1260
- import { execFile as execFile4 } from "node:child_process";
1261
1305
  import { existsSync } from "node:fs";
1262
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
1306
+ import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
1263
1307
  import { mkdir as mkdir5, mkdtemp as mkdtemp3, readFile as readFile6, rm as rm5 } from "node:fs/promises";
1264
1308
  import { tmpdir as tmpdir3 } from "node:os";
1265
1309
  import { posix as posix2, resolve as resolve8 } from "node:path";
1266
1310
  import { setTimeout as delay2 } from "node:timers/promises";
1267
- import { promisify as promisify4 } from "node:util";
1268
- import { z as z5 } from "zod";
1269
- var execute4 = promisify4(execFile4);
1270
- var imageIdSchema = z5.string().regex(/^sha256:[a-f0-9]{64}$/);
1271
- var endpointSchema = z5.strictObject({
1272
- host: z5.string().nonempty(),
1273
- port: z5.number().int().min(1).max(65535)
1311
+ import { z as z7 } from "zod";
1312
+ import { dockerImage as dockerImage3 } from "@tsplc/config/build";
1313
+
1314
+ // packages/build/src/controller-protocol.ts
1315
+ import { createHash as createHash2 } from "node:crypto";
1316
+ import { z as z6 } from "zod";
1317
+ import {
1318
+ controllerSchema,
1319
+ sha256Digest,
1320
+ tcpPort
1321
+ } from "@tsplc/config/build";
1322
+ var imageIdSchema = z6.string().regex(/^sha256:[a-f0-9]{64}$/);
1323
+ var endpointSchema = z6.strictObject({
1324
+ host: z6.string().nonempty(),
1325
+ port: tcpPort
1274
1326
  });
1275
- var controllerResultSchema = z5.strictObject({
1276
- schemaVersion: z5.literal(1),
1277
- operationId: z5.uuid(),
1278
- operation: z5.enum(["download", "online-change", "inspect"]),
1327
+ var controllerResultSchema = z6.strictObject({
1328
+ schemaVersion: z6.literal(1),
1329
+ operationId: z6.uuid(),
1330
+ operation: z6.enum(["download", "online-change", "inspect"]),
1279
1331
  imageId: imageIdSchema,
1280
- templateHash: z5.string().regex(/^[a-f0-9]{64}$/),
1281
- target: z5.strictObject({
1282
- network: z5.string().nonempty(),
1332
+ templateHash: sha256Digest,
1333
+ target: z6.strictObject({
1334
+ network: z6.string().nonempty(),
1283
1335
  gateway: endpointSchema,
1284
1336
  device: endpointSchema,
1285
1337
  controller: controllerSchema.optional(),
1286
- deviceTree: z5.string().regex(/^[a-f0-9]{64}$/).optional()
1338
+ deviceTree: sha256Digest.optional()
1287
1339
  }),
1288
- generation: z5.string().nonempty(),
1289
- application: z5.string().nonempty(),
1290
- applicationGuid: z5.string().nonempty(),
1291
- controllerIds: z5.strictObject({
1292
- codeId: z5.string().nonempty(),
1293
- dataId: z5.string().nonempty()
1340
+ generation: z6.string().nonempty(),
1341
+ application: z6.string().nonempty(),
1342
+ applicationGuid: z6.string().nonempty(),
1343
+ controllerIds: z6.strictObject({
1344
+ codeId: z6.string().nonempty(),
1345
+ dataId: z6.string().nonempty()
1294
1346
  }),
1295
- state: z5.string().nonempty(),
1296
- values: z5.record(z5.string(), z5.string())
1347
+ state: z6.string().nonempty(),
1348
+ values: z6.record(z6.string(), z6.string())
1297
1349
  });
1298
- var controllerCredentialsSchema = z5.strictObject({
1299
- username: z5.string().nonempty(),
1300
- password: z5.string().nonempty()
1350
+ var controllerCredentialsSchema = z6.strictObject({
1351
+ username: z6.string().nonempty(),
1352
+ password: z6.string().nonempty()
1301
1353
  });
1302
- var warmOperationSchema = z5.strictObject({
1303
- operation: z5.enum(["download", "online-change"]),
1304
- operationId: z5.uuid(),
1305
- request: z5.string().nonempty(),
1306
- initializeUser: z5.boolean(),
1354
+ var warmOperationSchema = z6.strictObject({
1355
+ operation: z6.enum(["download", "online-change"]),
1356
+ operationId: z6.uuid(),
1357
+ request: z6.string().nonempty(),
1358
+ initializeUser: z6.boolean(),
1307
1359
  credentials: controllerCredentialsSchema.optional()
1308
1360
  });
1309
- var failureReason = (error) => {
1310
- const message = error instanceof Error ? error.message : String(error);
1311
- return (message.trim().split(`
1312
- `).at(-1) ?? message).replace(/^\w+: /, "");
1361
+ var tracebackFailure = (traceback) => {
1362
+ const text = traceback.trim();
1363
+ const lastFrame = text.lastIndexOf(`
1364
+ File `);
1365
+ if (lastFrame === -1) {
1366
+ return text;
1367
+ }
1368
+ const [, ...rest] = text.slice(lastFrame + 1).split(`
1369
+ `);
1370
+ return ((rest[0]?.startsWith(" ")) ? rest.slice(1) : rest).join(`
1371
+ `);
1313
1372
  };
1373
+ var failureReason = (error) => tracebackFailure(error instanceof Error ? error.message : String(error)).replace(/^\w+: /, "");
1314
1374
  var controllerTarget = (config, online) => ({
1315
1375
  network: online.network,
1316
1376
  gateway: online.gateway,
@@ -1320,8 +1380,40 @@ var controllerTarget = (config, online) => ({
1320
1380
  deviceTree: createHash2("sha256").update(JSON.stringify(config.deviceTree)).digest("hex")
1321
1381
  }
1322
1382
  });
1383
+ var sameBaseline = (state, expected) => state.imageId === expected.imageId && state.templateHash === expected.templateHash && JSON.stringify(state.target) === JSON.stringify(expected.target);
1384
+ var explicitDownload = "use an explicit download";
1385
+ var loginCommandSchema = z6.discriminatedUnion("command", [
1386
+ z6.strictObject({ command: z6.literal("state") }),
1387
+ z6.strictObject({
1388
+ command: z6.literal("read"),
1389
+ expressions: z6.array(z6.string().nonempty()).nonempty()
1390
+ }),
1391
+ z6.strictObject({
1392
+ command: z6.enum(["write", "force"]),
1393
+ values: z6.record(z6.string().nonempty(), z6.string().nonempty())
1394
+ }),
1395
+ z6.strictObject({
1396
+ command: z6.literal("unforce"),
1397
+ expressions: z6.array(z6.string().nonempty()),
1398
+ restore: z6.boolean()
1399
+ }),
1400
+ z6.strictObject({ command: z6.enum(["start", "stop"]) }),
1401
+ z6.strictObject({
1402
+ command: z6.literal("reset"),
1403
+ kind: z6.enum(["Warm", "Cold"])
1404
+ })
1405
+ ]);
1406
+ var loginResultSchema = z6.union([
1407
+ z6.strictObject({ values: z6.record(z6.string(), z6.string()) }),
1408
+ z6.strictObject({ state: z6.string(), forced: z6.array(z6.string()) })
1409
+ ]);
1410
+
1411
+ // packages/build/src/controller-online.ts
1323
1412
  var credentialEnvironment = (config) => {
1324
- const names = config.online?.credentials ? [config.online.credentials.usernameEnv, config.online.credentials.passwordEnv] : [];
1413
+ const names = config.online?.credentials ? [
1414
+ config.online.credentials.usernameEnv,
1415
+ config.online.credentials.passwordEnv
1416
+ ] : [];
1325
1417
  for (const name of names) {
1326
1418
  if (process.env[name] === undefined) {
1327
1419
  throw new Error(`Controller credential environment variable ${name} is not set`);
@@ -1333,17 +1425,17 @@ var controllerConnection = async (config) => {
1333
1425
  if (!config.docker || !config.online) {
1334
1426
  throw new Error("Docker image and online gateway/device configuration are required for controller operations");
1335
1427
  }
1336
- const { stdout } = await execute4("docker", ["image", "inspect", "--format", "{{.Id}}", dockerImage], { timeout: config.timeouts.hostCommand }).catch((cause) => {
1337
- throw new Error(`Cannot inspect Docker builder image ${dockerImage}. Install and start Docker, then run tsplc-build configure if the image is missing`, { cause });
1428
+ const { stdout } = await captureDocker(["image", "inspect", "--format", "{{.Id}}", dockerImage3], config.timeouts.hostCommand).catch((cause) => {
1429
+ throw new Error(`Cannot inspect Docker builder image ${dockerImage3}. Install and start Docker, then run tsplc-build configure if the image is missing`, { cause });
1338
1430
  });
1339
1431
  return {
1340
1432
  imageId: imageIdSchema.parse(stdout.trim()),
1341
- templateHash: createHash2("sha256").update(await readFile6(config.template)).digest("hex"),
1433
+ templateHash: createHash3("sha256").update(await readFile6(config.template)).digest("hex"),
1342
1434
  target: controllerTarget(config, config.online)
1343
1435
  };
1344
1436
  };
1345
1437
  var checkReceipt = (result, expected, diagnostics) => {
1346
- 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)) {
1438
+ if (result.operationId !== expected.operationId || result.operation !== expected.operation || !sameBaseline(result, expected)) {
1347
1439
  throw new Error(`Controller receipt does not match this operation's image, template or target. Inspect ${diagnostics} for diagnostics`);
1348
1440
  }
1349
1441
  return result;
@@ -1377,11 +1469,13 @@ var controllerOperation = async (config, operation, options) => {
1377
1469
  ...options.initializeUser ? ["--initialize-user"] : [],
1378
1470
  ...options.read ? ["--read", JSON.stringify(options.read)] : []
1379
1471
  ], (status) => `Docker controller operation failed (${status}). Inspect ${diagnostics} for diagnostics`).catch(async (cause) => {
1380
- if (!existsSync(failure))
1472
+ if (!existsSync(failure)) {
1381
1473
  throw cause;
1382
- const reason = (await readFile6(failure, "utf8")).trim().split(`
1383
- `).at(-1);
1384
- throw new Error(`${reason}. Inspect ${diagnostics} for diagnostics`, { cause });
1474
+ }
1475
+ const reason = tracebackFailure(await readFile6(failure, "utf8"));
1476
+ throw new Error(`${reason}. Inspect ${diagnostics} for diagnostics`, {
1477
+ cause
1478
+ });
1385
1479
  });
1386
1480
  const result = await readFile6(resolve8(diagnostics, "result.json"), "utf8").then((content) => controllerResultSchema.parse(JSON.parse(content))).catch((cause) => {
1387
1481
  throw new Error(`Docker did not produce a valid controller receipt. Inspect ${diagnostics} for diagnostics`, { cause });
@@ -1393,36 +1487,17 @@ var controllerOperation = async (config, operation, options) => {
1393
1487
  };
1394
1488
  var updateController = (config, operation, options = {}) => controllerOperation(config, operation, options);
1395
1489
  var inspectController = (config, read) => controllerOperation(config, "inspect", { read });
1396
- var explicitDownload = "use an explicit download";
1397
- var loginCommandSchema = z5.discriminatedUnion("command", [
1398
- z5.strictObject({ command: z5.literal("state") }),
1399
- z5.strictObject({
1400
- command: z5.literal("read"),
1401
- expressions: z5.array(z5.string().nonempty()).nonempty()
1402
- }),
1403
- z5.strictObject({
1404
- command: z5.enum(["write", "force"]),
1405
- values: z5.record(z5.string().nonempty(), z5.string().nonempty())
1406
- }),
1407
- z5.strictObject({
1408
- command: z5.literal("unforce"),
1409
- expressions: z5.array(z5.string().nonempty()),
1410
- restore: z5.boolean()
1411
- }),
1412
- z5.strictObject({ command: z5.enum(["start", "stop"]) }),
1413
- z5.strictObject({ command: z5.literal("reset"), kind: z5.enum(["Warm", "Cold"]) })
1414
- ]);
1415
- var loginResultSchema = z5.union([
1416
- z5.strictObject({ values: z5.record(z5.string(), z5.string()) }),
1417
- z5.strictObject({ state: z5.string(), forced: z5.array(z5.string()) })
1418
- ]);
1419
- var loginReplySchema = z5.discriminatedUnion("ok", [
1420
- z5.strictObject({ ok: z5.literal(true), result: z5.unknown() }),
1421
- z5.strictObject({ ok: z5.literal(false), error: z5.string() })
1490
+ var loginReplySchema = z7.discriminatedUnion("ok", [
1491
+ z7.strictObject({ ok: z7.literal(true), result: z7.unknown() }),
1492
+ z7.strictObject({ ok: z7.literal(false), error: z7.string() })
1422
1493
  ]);
1423
1494
  var loginPort = 4851;
1424
1495
  var warmPort = 4852;
1425
- var docker = (args, timeout) => execute4("docker", args, { timeout }).then(({ stdout }) => stdout.trim());
1496
+ var docker = (args, timeout) => captureDocker(args, timeout).then(({ stdout }) => stdout.trim());
1497
+ var recentLogs = async (name, timeout) => {
1498
+ const logs = await captureDocker(["logs", "--tail", "40", name], timeout);
1499
+ return `${logs.stdout}${logs.stderr}`;
1500
+ };
1426
1501
  var isRunning = async (name, timeout) => await docker(["container", "ls", "--quiet", "--filter", `name=^${name}$`], timeout) !== "";
1427
1502
  var callContainer = async (name, port, method, body) => {
1428
1503
  const child = Bun.spawn([
@@ -1436,7 +1511,12 @@ var callContainer = async (name, port, method, body) => {
1436
1511
  ...method === "GET" ? ["--max-time", "5"] : [],
1437
1512
  "--request",
1438
1513
  method,
1439
- ...body === undefined ? [] : ["--header", "Content-Type: application/json", "--data-binary", "@-"],
1514
+ ...body === undefined ? [] : [
1515
+ "--header",
1516
+ "Content-Type: application/json",
1517
+ "--data-binary",
1518
+ "@-"
1519
+ ],
1440
1520
  `http://127.0.0.1:${port}/`
1441
1521
  ], {
1442
1522
  stdin: body === undefined ? "ignore" : new Blob([JSON.stringify(body)]),
@@ -1448,11 +1528,13 @@ var callContainer = async (name, port, method, body) => {
1448
1528
  new Response(child.stderr).text(),
1449
1529
  child.exited
1450
1530
  ]);
1451
- if (code !== 0)
1531
+ if (code !== 0) {
1452
1532
  throw new Error(errors.trim() || `docker exec failed (${code})`);
1533
+ }
1453
1534
  const reply = loginReplySchema.parse(JSON.parse(output));
1454
- if (!reply.ok)
1535
+ if (!reply.ok) {
1455
1536
  throw new Error(reply.error);
1537
+ }
1456
1538
  return reply.result;
1457
1539
  };
1458
1540
  var answers = (name, port) => callContainer(name, port, "GET").then(() => true, () => false);
@@ -1507,12 +1589,12 @@ var openControllerLogin = async (config, name) => {
1507
1589
  const deadline = Date.now() + config.timeouts.startup + config.timeouts.build;
1508
1590
  while (Date.now() < deadline) {
1509
1591
  if (!await isRunning(name, timeout)) {
1510
- const logs = await execute4("docker", ["logs", "--tail", "40", name], { timeout });
1511
1592
  throw new Error(`The controller login failed:
1512
- ${logs.stdout}${logs.stderr}`);
1593
+ ${await recentLogs(name, timeout)}`);
1513
1594
  }
1514
- if (await login.ready())
1595
+ if (await login.ready()) {
1515
1596
  return login;
1597
+ }
1516
1598
  await delay2(2000);
1517
1599
  }
1518
1600
  await docker(["rm", "--force", name], timeout);
@@ -1521,9 +1603,22 @@ ${logs.stdout}${logs.stderr}`);
1521
1603
  var warmController = async (config, name, connection) => {
1522
1604
  const timeout = config.timeouts.hostCommand;
1523
1605
  const { imageId, target } = connection;
1524
- const settings = createHash2("sha256").update(JSON.stringify({ imageId, target, timeouts: config.timeouts, docker: config.docker })).digest("hex");
1606
+ const settings = createHash3("sha256").update(JSON.stringify({
1607
+ imageId,
1608
+ target,
1609
+ timeouts: config.timeouts,
1610
+ docker: config.docker
1611
+ })).digest("hex");
1525
1612
  const label = `tsplc.warm=${settings}`;
1526
- const running = async () => await docker(["container", "ls", "--quiet", "--filter", `name=^${name}$`, "--filter", `label=${label}`], timeout) !== "";
1613
+ const running = async () => await docker([
1614
+ "container",
1615
+ "ls",
1616
+ "--quiet",
1617
+ "--filter",
1618
+ `name=^${name}$`,
1619
+ "--filter",
1620
+ `label=${label}`
1621
+ ], timeout) !== "";
1527
1622
  if (!await running() || !await answers(name, warmPort)) {
1528
1623
  await docker(["rm", "--force", name], timeout);
1529
1624
  const requestDirectory = resolve8(config.outDir, ".codesys/warm-request");
@@ -1552,12 +1647,12 @@ var warmController = async (config, name, connection) => {
1552
1647
  const deadline = Date.now() + config.timeouts.startup;
1553
1648
  while (Date.now() < deadline) {
1554
1649
  if (!await running()) {
1555
- const logs = await execute4("docker", ["logs", "--tail", "40", name], { timeout });
1556
1650
  throw new Error(`CODESYS failed to start:
1557
- ${logs.stdout}${logs.stderr}`);
1651
+ ${await recentLogs(name, timeout)}`);
1558
1652
  }
1559
- if (await answers(name, warmPort))
1653
+ if (await answers(name, warmPort)) {
1560
1654
  return;
1655
+ }
1561
1656
  await delay2(2000);
1562
1657
  }
1563
1658
  await docker(["rm", "--force", name], timeout);
@@ -1596,153 +1691,98 @@ var updateWarmController = async (config, name, operation, options = {}) => {
1596
1691
  await rm5(directory, { recursive: true, force: true });
1597
1692
  }
1598
1693
  };
1599
- // packages/build/src/run.ts
1600
- import { execFile as execFile5 } from "node:child_process";
1601
- import { mkdtemp as mkdtemp4, readFile as readFile7, rm as rm6, writeFile as writeFile5 } from "node:fs/promises";
1602
- import { tmpdir as tmpdir4 } from "node:os";
1603
- import { basename as basename4, dirname as dirname2, join } from "node:path";
1604
- import { setTimeout as delay3 } from "node:timers/promises";
1605
- import { promisify as promisify5 } from "node:util";
1606
- import { z as z6 } from "zod";
1607
-
1608
- // packages/build/src/runtime-status.ts
1609
- var getApplicationStatus = (log, application, startedAt) => {
1610
- const event = log.split(/\r?\n/).reverse().find((line) => {
1611
- const timestamp = Date.parse(line.split(",")[0] ?? "");
1612
- if (!Number.isFinite(timestamp) || timestamp < startedAt) {
1613
- return false;
1614
- }
1615
- return line.includes(`<app>${application}</app>`) && /\b(started|stopped|exception|corrupt|failed|denied)\b/i.test(line) && !line.includes("load started");
1616
- });
1617
- if (!event) {
1618
- return "pending";
1619
- }
1620
- return event.includes(`Application [<app>${application}</app>] started`) ? "running" : "failed";
1621
- };
1694
+ // packages/build/src/engineering-settings.ts
1695
+ import {
1696
+ controllerFor,
1697
+ rawBuildConfig,
1698
+ simulationConfig
1699
+ } from "@tsplc/config";
1700
+ import { deviceTree } from "@tsplc/typegen";
1701
+ import { loadHardware, resolveIo } from "@tsplc/typegen/hardware";
1702
+ import { resolveConfig } from "@tsplc/config/build";
1622
1703
 
1623
- // packages/build/src/run.ts
1624
- var execute5 = promisify5(execFile5);
1625
- var stateSchema = z6.object({
1626
- Running: z6.boolean(),
1627
- StartedAt: z6.iso.datetime({ offset: true })
1704
+ // packages/build/src/libraries.ts
1705
+ import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
1706
+ import { mkdir as mkdir6, readFile as readFile7, rename as rename3, writeFile as writeFile5 } from "node:fs/promises";
1707
+ import { basename as basename4, relative as relative2, resolve as resolve9 } from "node:path";
1708
+ import { sha256Digest as sha256Digest2 } from "@tsplc/config/build";
1709
+ import { z as z8 } from "zod";
1710
+ var libraryRegistry = "https://store-archive.codesys.com/CODESYSLibs";
1711
+ var libraryFile = /\.(?:compiled-library(?:-v\d+)?|library)$/i;
1712
+ var installedLibrarySchema = z8.object({
1713
+ title: z8.string(),
1714
+ company: z8.string().optional(),
1715
+ version: z8.string().optional(),
1716
+ namespace: z8.string().optional(),
1717
+ path: z8.string(),
1718
+ sha256: sha256Digest2,
1719
+ url: z8.string().optional()
1628
1720
  });
1629
- var service = "plc";
1630
- var runtimeProject = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
1631
- var runtimeDefinition = (name) => ({
1632
- services: {
1633
- [service]: {
1634
- image: runtimeImage,
1635
- platform: "linux/amd64",
1636
- hostname: `${runtimeProject(name)}-${service}`,
1637
- init: true,
1638
- ports: ["127.0.0.1:4840:4840", "127.0.0.1:11740:11740"],
1639
- cap_add: ["SYS_NICE", "IPC_LOCK"],
1640
- volumes: ["control-conf:/conf/codesyscontrol", "control-data:/data/codesyscontrol"],
1641
- restart: "no"
1642
- }
1643
- },
1644
- volumes: { "control-conf": {}, "control-data": {} }
1721
+ var libraryLockSchema = z8.object({
1722
+ version: z8.literal(1),
1723
+ dependencies: z8.record(z8.string(), installedLibrarySchema)
1645
1724
  });
1646
- var runProject = async (config, name) => withWorkerLock(config, async () => {
1647
- const build = await readBuild(config.outDir).catch((cause) => {
1648
- throw new Error(`No complete build in ${config.outDir}. Run tsplc-build build first.`, {
1649
- cause
1650
- });
1651
- });
1652
- const definitionDirectory = await mkdtemp4(join(tmpdir4(), "tsplc-runtime-"));
1653
- try {
1654
- const composeFile = join(definitionDirectory, "compose.yaml");
1655
- await writeFile5(composeFile, JSON.stringify(runtimeDefinition(name)));
1656
- const docker = (...args) => execute5("docker", args, {
1657
- timeout: config.timeouts.runtime,
1658
- maxBuffer: 8 * 1024 * 1024
1659
- });
1660
- const compose = (...args) => docker("compose", "--project-name", runtimeProject(name), "--file", composeFile, ...args);
1661
- const installer = await readFile7(new URL("../runtime/install.sh", import.meta.url), "utf8");
1662
- console.log(`Installing ${build.application} in Docker service ${service}`);
1663
- await compose("stop", service);
1664
- 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"));
1665
- await compose("up", "--detach", "--no-deps", service);
1666
- const containers = (await compose("ps", "--all", "--quiet", service)).stdout.trim().split(/\s+/).filter(Boolean);
1667
- if (containers.length !== 1 || !containers[0]) {
1668
- throw new Error(`Expected one container for Compose service ${service}`);
1669
- }
1670
- const container = containers[0];
1671
- const deadline = Date.now() + config.timeouts.runtime;
1672
- while (true) {
1673
- const state = stateSchema.parse(JSON.parse((await docker("inspect", "--format", "{{json .State}}", container)).stdout));
1674
- if (!state.Running) {
1675
- throw new Error(`Docker service ${service} exited before the application started. Check docker logs ${container}.`);
1676
- }
1677
- const { stdout: log } = await docker("exec", container, "/bin/sh", "-c", "if [ -f /data/codesyscontrol/codesyscontrol.log ]; then cat /data/codesyscontrol/codesyscontrol.log; fi");
1678
- const status = getApplicationStatus(log, build.application, Date.parse(state.StartedAt));
1679
- if (status === "running") {
1680
- console.log(`${build.application} is running in ${service}`);
1681
- return { ...build, container };
1682
- }
1683
- if (status === "failed" || Date.now() >= deadline) {
1684
- throw new Error(`CODESYS did not start ${build.application}. Runtime log:
1685
- ${log.split(`
1686
- `).slice(-25).join(`
1687
- `)}`);
1688
- }
1689
- await delay3(250);
1725
+ var readLock = async (file) => {
1726
+ const text = await readFile7(file, "utf8").catch((cause) => {
1727
+ if (cause && typeof cause === "object" && "code" in cause && cause.code === "ENOENT") {
1728
+ return;
1690
1729
  }
1691
- } finally {
1692
- await rm6(definitionDirectory, { force: true, recursive: true });
1730
+ throw cause;
1731
+ });
1732
+ if (text === undefined) {
1733
+ return { version: 1, dependencies: {} };
1693
1734
  }
1694
- });
1695
- // packages/build/src/libraries.ts
1696
- import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
1697
- import { mkdir as mkdir6, readFile as readFile8, rename as rename3, writeFile as writeFile6 } from "node:fs/promises";
1698
- import { basename as basename5, relative as relative2, resolve as resolve9 } from "node:path";
1699
- var libraryRegistry = "https://store-archive.codesys.com/CODESYSLibs";
1700
- var libraryFile = /\.(?:compiled-library(?:-v\d+)?|library)$/i;
1701
- var hash = (data) => createHash3("sha256").update(data).digest("hex");
1735
+ const lock = libraryLockSchema.safeParse(JSON.parse(text));
1736
+ if (!lock.success) {
1737
+ throw new Error("Invalid tsplc.lock.json.", { cause: lock.error });
1738
+ }
1739
+ return lock.data;
1740
+ };
1741
+ var hash = (data) => createHash4("sha256").update(data).digest("hex");
1702
1742
  var component = (name) => {
1703
- if (!name.trim() || /[/\\\0\r\n]/.test(name) || name === "." || name === "..")
1743
+ if (!name.trim() || /[/\\\0\r\n]/.test(name) || name === "." || name === "..") {
1704
1744
  throw new Error(`Invalid library registry component: ${name}.`);
1745
+ }
1705
1746
  return encodeURIComponent(name);
1706
1747
  };
1707
1748
  async function response(url, fetcher) {
1708
1749
  const result = await fetcher(url, { signal: AbortSignal.timeout(30000) });
1709
- if (!result.ok)
1750
+ if (!result.ok) {
1710
1751
  throw new Error(`Library registry ${result.status}: ${url}`);
1752
+ }
1711
1753
  return result;
1712
1754
  }
1713
1755
  async function libraryIndex(path = ["System"], fetcher = fetch) {
1714
1756
  const url = `${libraryRegistry}/${path.map(component).join("/")}/index`;
1715
1757
  const result = await response(url, fetcher);
1716
1758
  const text = await result.text();
1717
- if (text.length > 4000000 || /<html/i.test(text))
1759
+ if (text.length > 4000000 || /<html/i.test(text)) {
1718
1760
  throw new Error(`Invalid library registry index: ${url}`);
1761
+ }
1719
1762
  return text.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
1720
1763
  }
1721
1764
  async function validateLibrary(title, version, company = "System", fetcher = fetch) {
1722
- if (!(await libraryIndex([company], fetcher)).includes(title))
1765
+ if (!(await libraryIndex([company], fetcher)).includes(title)) {
1723
1766
  throw new Error(`Unknown CODESYS library ${company}/${title}. Names are case sensitive.`);
1767
+ }
1724
1768
  const versions = await libraryIndex([company, title], fetcher);
1725
- if (!versions.includes(version))
1769
+ if (!versions.includes(version)) {
1726
1770
  throw new Error(`Unknown version ${version} for ${title}. Available: ${versions.join(", ")}`);
1771
+ }
1727
1772
  const filenames = (await libraryIndex([company, title, version], fetcher)).filter((name) => libraryFile.test(name));
1728
- if (filenames.length !== 1)
1773
+ const [filename, ...others] = filenames;
1774
+ if (filename === undefined || others.length) {
1729
1775
  throw new Error(`Expected one library payload for ${title} ${version}, received ${filenames.length}.`);
1776
+ }
1730
1777
  return {
1731
- filename: filenames[0],
1732
- url: `${libraryRegistry}/${[company, title, version, filenames[0]].map(component).join("/")}`
1778
+ filename,
1779
+ url: `${libraryRegistry}/${[company, title, version, filename].map(component).join("/")}`
1733
1780
  };
1734
1781
  }
1735
1782
  async function installLibraries(dependencies, root, options = {}) {
1736
- const file = resolve9(root, "tsplc.lock.json"), store = resolve9(root, ".tsplc/libraries");
1737
- let previous = { version: 1, dependencies: {} };
1738
- try {
1739
- previous = JSON.parse(await readFile8(file, "utf8"));
1740
- } catch (cause) {
1741
- if (!(cause && typeof cause === "object" && ("code" in cause) && cause.code === "ENOENT"))
1742
- throw cause;
1743
- }
1744
- if (previous.version !== 1 || !previous.dependencies || typeof previous.dependencies !== "object")
1745
- throw new Error("Invalid tsplc.lock.json.");
1783
+ const file = resolve9(root, "tsplc.lock.json");
1784
+ const store = resolve9(root, ".tsplc/libraries");
1785
+ const previous = await readLock(file);
1746
1786
  const installed = {};
1747
1787
  const fetcher = options.fetcher ?? fetch;
1748
1788
  await mkdir6(store, { recursive: true });
@@ -1754,23 +1794,26 @@ async function installLibraries(dependencies, root, options = {}) {
1754
1794
  const same = prior !== undefined && prior.namespace === settings.namespace && ("path" in settings ? prior.url === undefined && prior.path === resolve9(root, settings.path) : prior.version === settings.version && prior.company === (settings.company ?? "System"));
1755
1795
  if (same) {
1756
1796
  try {
1757
- if (hash(await readFile8(prior.path)) === prior.sha256) {
1797
+ if (hash(await readFile7(prior.path)) === prior.sha256) {
1758
1798
  installed[title] = prior;
1759
1799
  continue;
1760
1800
  }
1761
1801
  } catch {}
1762
- if (options.frozen)
1802
+ if (options.frozen) {
1763
1803
  throw new Error(`Locked library ${title} is missing or changed.`);
1764
- } else if (options.frozen)
1804
+ }
1805
+ } else if (options.frozen) {
1765
1806
  throw new Error(`Dependency ${title} differs from tsplc.lock.json.`);
1807
+ }
1766
1808
  if ("path" in settings) {
1767
1809
  const path = resolve9(root, settings.path);
1768
- if (!libraryFile.test(path))
1810
+ if (!libraryFile.test(path)) {
1769
1811
  throw new Error(`${title}: expected a .library or .compiled-library file.`);
1812
+ }
1770
1813
  installed[title] = {
1771
1814
  title,
1772
1815
  path,
1773
- sha256: hash(await readFile8(path)),
1816
+ sha256: hash(await readFile7(path)),
1774
1817
  ...settings.namespace ? { namespace: settings.namespace } : {}
1775
1818
  };
1776
1819
  } else {
@@ -1778,13 +1821,16 @@ async function installLibraries(dependencies, root, options = {}) {
1778
1821
  const payload = await validateLibrary(title, settings.version, company, fetcher);
1779
1822
  const result = await response(payload.url, fetcher);
1780
1823
  const data = new Uint8Array(await result.arrayBuffer());
1781
- if (!data.length || data.length > 256 * 1024 * 1024)
1824
+ if (!data.length || data.length > 256 * 1024 * 1024) {
1782
1825
  throw new Error(`${title}: invalid library payload size.`);
1826
+ }
1783
1827
  const sha256 = hash(data);
1784
- if (same && prior.sha256 !== sha256)
1828
+ if (same && prior.sha256 !== sha256) {
1785
1829
  throw new Error(`Registry payload changed for locked library ${title} ${settings.version}.`);
1786
- const path = resolve9(store, `${sha256}-${basename5(payload.filename)}`), temp = `${path}.${randomUUID3()}.tmp`;
1787
- await writeFile6(temp, data, { flag: "wx" });
1830
+ }
1831
+ const path = resolve9(store, `${sha256}-${basename4(payload.filename)}`);
1832
+ const temp = `${path}.${randomUUID3()}.tmp`;
1833
+ await writeFile5(temp, data, { flag: "wx" });
1788
1834
  await rename3(temp, path);
1789
1835
  installed[title] = {
1790
1836
  title,
@@ -1797,20 +1843,134 @@ async function installLibraries(dependencies, root, options = {}) {
1797
1843
  };
1798
1844
  }
1799
1845
  }
1800
- if (options.frozen && Object.keys(previous.dependencies).some((name) => !Object.hasOwn(dependencies, name)))
1846
+ if (options.frozen && Object.keys(previous.dependencies).some((name) => !Object.hasOwn(dependencies, name))) {
1801
1847
  throw new Error("Removed dependencies differ from tsplc.lock.json.");
1848
+ }
1802
1849
  if (!options.frozen) {
1803
1850
  const temp = `${file}.${randomUUID3()}.tmp`;
1804
1851
  const portable = Object.fromEntries(Object.entries(installed).map(([title, library]) => [
1805
1852
  title,
1806
- { ...library, path: relative2(root, library.path).replaceAll("\\", "/") }
1853
+ {
1854
+ ...library,
1855
+ path: relative2(root, library.path).replaceAll("\\", "/")
1856
+ }
1807
1857
  ]));
1808
- await writeFile6(temp, JSON.stringify({ version: 1, dependencies: portable }, null, 2) + `
1858
+ await writeFile5(temp, JSON.stringify({ version: 1, dependencies: portable }, null, 2) + `
1809
1859
  `);
1810
1860
  await rename3(temp, file);
1811
1861
  }
1812
1862
  return Object.values(installed);
1813
1863
  }
1864
+
1865
+ // packages/build/src/engineering-settings.ts
1866
+ var rawEngineeringSettings = async ({ config, configFile, root }, options) => {
1867
+ const hardwareConfig = options.simulate ? simulationConfig(config) : config;
1868
+ const build = rawBuildConfig(config);
1869
+ const libraries = await installLibraries(config.dependencies, root, {
1870
+ frozen: options.frozenLockfile
1871
+ });
1872
+ const hardware = await loadHardware(hardwareConfig, root);
1873
+ return resolveConfig({
1874
+ ...build,
1875
+ libraries,
1876
+ io: resolveIo(hardwareConfig, hardware),
1877
+ deviceTree: await deviceTree(hardwareConfig, hardware),
1878
+ controller: controllerFor(config, options.command)
1879
+ }, configFile);
1880
+ };
1881
+ // packages/build/src/run.ts
1882
+ import { mkdtemp as mkdtemp4, readFile as readFile8, rm as rm6, writeFile as writeFile6 } from "node:fs/promises";
1883
+ import { tmpdir as tmpdir4 } from "node:os";
1884
+ import { basename as basename5, dirname as dirname2, join } from "node:path";
1885
+ import { setTimeout as delay3 } from "node:timers/promises";
1886
+ import { z as z9 } from "zod";
1887
+
1888
+ // packages/build/src/runtime-status.ts
1889
+ var getApplicationStatus = (log, application, startedAt) => {
1890
+ const event = log.split(/\r?\n/).reverse().find((line) => {
1891
+ const timestamp = Date.parse(line.split(",")[0] ?? "");
1892
+ if (!Number.isFinite(timestamp) || timestamp < startedAt) {
1893
+ return false;
1894
+ }
1895
+ return line.includes(`<app>${application}</app>`) && /\b(started|stopped|exception|corrupt|failed|denied)\b/i.test(line) && !line.includes("load started");
1896
+ });
1897
+ if (!event) {
1898
+ return "pending";
1899
+ }
1900
+ return event.includes(`Application [<app>${application}</app>] started`) ? "running" : "failed";
1901
+ };
1902
+
1903
+ // packages/build/src/run.ts
1904
+ var stateSchema = z9.object({
1905
+ Running: z9.boolean(),
1906
+ StartedAt: z9.iso.datetime({ offset: true })
1907
+ });
1908
+ var service = "plc";
1909
+ var runtimeProject = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
1910
+ var runtimeDefinition = (name) => ({
1911
+ services: {
1912
+ [service]: {
1913
+ image: runtimeImage,
1914
+ platform: "linux/amd64",
1915
+ hostname: `${runtimeProject(name)}-${service}`,
1916
+ init: true,
1917
+ ports: ["127.0.0.1:4840:4840", "127.0.0.1:11740:11740"],
1918
+ cap_add: ["SYS_NICE", "IPC_LOCK"],
1919
+ volumes: [
1920
+ "control-conf:/conf/codesyscontrol",
1921
+ "control-data:/data/codesyscontrol"
1922
+ ],
1923
+ restart: "no"
1924
+ }
1925
+ },
1926
+ volumes: { "control-conf": {}, "control-data": {} }
1927
+ });
1928
+ var runProject = async (config, name) => withWorkerLock(config, async () => {
1929
+ const build = await readBuild(config.outDir).catch((cause) => {
1930
+ throw new Error(`No complete build in ${config.outDir}. Run tsplc-build build first.`, {
1931
+ cause
1932
+ });
1933
+ });
1934
+ const definitionDirectory = await mkdtemp4(join(tmpdir4(), "tsplc-runtime-"));
1935
+ try {
1936
+ const composeFile = join(definitionDirectory, "compose.yaml");
1937
+ await writeFile6(composeFile, JSON.stringify(runtimeDefinition(name)));
1938
+ const docker = (...args) => captureDocker(args, config.timeouts.runtime);
1939
+ const compose = (...args) => docker("compose", "--project-name", runtimeProject(name), "--file", composeFile, ...args);
1940
+ const installer = await readFile8(new URL("../runtime/install.sh", import.meta.url), "utf8");
1941
+ console.log(`Installing ${build.application} in Docker service ${service}`);
1942
+ await compose("stop", service);
1943
+ 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"));
1944
+ await compose("up", "--detach", "--no-deps", service);
1945
+ const containers = (await compose("ps", "--all", "--quiet", service)).stdout.trim().split(/\s+/).filter(Boolean);
1946
+ if (containers.length !== 1 || !containers[0]) {
1947
+ throw new Error(`Expected one container for Compose service ${service}`);
1948
+ }
1949
+ const container = containers[0];
1950
+ const deadline = Date.now() + config.timeouts.runtime;
1951
+ while (true) {
1952
+ const state = stateSchema.parse(JSON.parse((await docker("inspect", "--format", "{{json .State}}", container)).stdout));
1953
+ if (!state.Running) {
1954
+ throw new Error(`Docker service ${service} exited before the application started. Check docker logs ${container}.`);
1955
+ }
1956
+ const { stdout: log } = await docker("exec", container, "/bin/sh", "-c", "if [ -f /data/codesyscontrol/codesyscontrol.log ]; then cat /data/codesyscontrol/codesyscontrol.log; fi");
1957
+ const status = getApplicationStatus(log, build.application, Date.parse(state.StartedAt));
1958
+ if (status === "running") {
1959
+ console.log(`${build.application} is running in ${service}`);
1960
+ return { ...build, container };
1961
+ }
1962
+ if (status === "failed" || Date.now() >= deadline) {
1963
+ throw new Error(`CODESYS did not start ${build.application}. Runtime log:
1964
+ ${log.split(`
1965
+ `).slice(-25).join(`
1966
+ `)}`);
1967
+ }
1968
+ await delay3(250);
1969
+ }
1970
+ } finally {
1971
+ await rm6(definitionDirectory, { force: true, recursive: true });
1972
+ }
1973
+ });
1814
1974
  export {
1815
1975
  CodesysCompilerError,
1816
1976
  StSyntaxError,
@@ -1833,8 +1993,9 @@ export {
1833
1993
  loginResultSchema,
1834
1994
  openControllerLogin,
1835
1995
  parseSource,
1996
+ rawEngineeringSettings,
1836
1997
  readBuild,
1837
- resolveConfig,
1998
+ resolveConfig2 as resolveConfig,
1838
1999
  runProject,
1839
2000
  startWarmController,
1840
2001
  updateController,
@@ -1842,5 +2003,5 @@ export {
1842
2003
  validateLibrary
1843
2004
  };
1844
2005
 
1845
- //# debugId=1BBEC553384F902964756E2164756E21
2006
+ //# debugId=184411194E92563564756E2164756E21
1846
2007
  //# sourceMappingURL=index.js.map