@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/src/run.ts CHANGED
@@ -1,133 +1,157 @@
1
- import { execFile } from "node:child_process";
2
1
  import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
2
  import { tmpdir } from "node:os";
4
3
  import { basename, dirname, join } from "node:path";
5
4
  import { setTimeout as delay } from "node:timers/promises";
6
- import { promisify } from "node:util";
7
5
  import { z } from "zod";
8
6
  import { readBuild } from "./artifacts";
9
- import type { ResolvedConfig } from "./config";
7
+ import type { ResolvedConfig } from "@tsplc/config/build";
10
8
  import { runtimeImage } from "./docker-build";
9
+ import { captureDocker } from "./docker-run";
11
10
  import { withWorkerLock } from "./host/codesys-worker";
12
11
  import { getApplicationStatus } from "./runtime-status";
13
12
 
14
- const execute = promisify(execFile);
15
13
  const stateSchema = z.object({
16
- Running: z.boolean(),
17
- StartedAt: z.iso.datetime({ offset: true }),
14
+ Running: z.boolean(),
15
+ StartedAt: z.iso.datetime({ offset: true }),
18
16
  });
19
17
 
20
18
  const service = "plc";
21
19
 
22
20
  /** The Docker Compose project of a tsPLC project: `FrameAssembly` runs as `frame-assembly`. */
23
21
  export const runtimeProject = (name: string) =>
24
- name
25
- .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
26
- .toLowerCase()
27
- .replace(/[^a-z0-9_-]+/g, "-");
22
+ name
23
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
24
+ .toLowerCase()
25
+ .replace(/[^a-z0-9_-]+/g, "-");
28
26
 
29
27
  /** The local PLC: named volumes keep its provisioning and the installed application across restarts. */
30
28
  export const runtimeDefinition = (name: string) => ({
31
- services: {
32
- [service]: {
33
- image: runtimeImage,
34
- platform: "linux/amd64",
35
- hostname: `${runtimeProject(name)}-${service}`,
36
- init: true,
37
- ports: ["127.0.0.1:4840:4840", "127.0.0.1:11740:11740"],
38
- cap_add: ["SYS_NICE", "IPC_LOCK"],
39
- volumes: ["control-conf:/conf/codesyscontrol", "control-data:/data/codesyscontrol"],
40
- restart: "no",
41
- },
42
- },
43
- volumes: { "control-conf": {}, "control-data": {} },
29
+ services: {
30
+ [service]: {
31
+ image: runtimeImage,
32
+ platform: "linux/amd64",
33
+ hostname: `${runtimeProject(name)}-${service}`,
34
+ init: true,
35
+ ports: ["127.0.0.1:4840:4840", "127.0.0.1:11740:11740"],
36
+ cap_add: ["SYS_NICE", "IPC_LOCK"],
37
+ volumes: [
38
+ "control-conf:/conf/codesyscontrol",
39
+ "control-data:/data/codesyscontrol",
40
+ ],
41
+ restart: "no",
42
+ },
43
+ },
44
+ volumes: { "control-conf": {}, "control-data": {} },
44
45
  });
45
46
 
46
47
  /** Deploy the completed boot application to the project's local PLC container. */
47
48
  export const runProject = async (
48
- config: Pick<ResolvedConfig, "outDir" | "timeouts">,
49
- name: string,
49
+ config: Pick<ResolvedConfig, "outDir" | "timeouts">,
50
+ name: string,
50
51
  ) =>
51
- withWorkerLock(config, async () => {
52
- // Validate before stopping anything. A missing receipt includes a failed rebuild.
53
- const build = await readBuild(config.outDir).catch((cause: unknown) => {
54
- throw new Error(`No complete build in ${config.outDir}. Run tsplc-build build first.`, {
55
- cause,
56
- });
57
- });
58
- const definitionDirectory = await mkdtemp(join(tmpdir(), "tsplc-runtime-"));
59
- try {
60
- const composeFile = join(definitionDirectory, "compose.yaml");
61
- // JSON is valid YAML.
62
- await writeFile(composeFile, JSON.stringify(runtimeDefinition(name)));
63
- const docker = (...args: string[]) =>
64
- execute("docker", args, {
65
- timeout: config.timeouts.runtime,
66
- maxBuffer: 8 * 1024 * 1024,
67
- });
68
- const compose = (...args: string[]) =>
69
- docker("compose", "--project-name", runtimeProject(name), "--file", composeFile, ...args);
70
- const installer = await readFile(new URL("../runtime/install.sh", import.meta.url), "utf8");
71
- console.log(`Installing ${build.application} in Docker service ${service}`);
72
- await compose("stop", service);
73
- // The helper uses the service's volumes without starting its PLC or publishing
74
- // ports. Its read-only artifact mount is removed with the helper container.
75
- await compose(
76
- "run",
77
- "--rm",
78
- "--no-deps",
79
- "-T",
80
- "--volume",
81
- `${dirname(build.output)}:/codesys-build:ro`,
82
- "--entrypoint",
83
- "/bin/sh",
84
- service,
85
- "-c",
86
- installer,
87
- "codesys-build-install",
88
- build.application,
89
- basename(build.output, ".app"),
90
- );
91
- await compose("up", "--detach", "--no-deps", service);
92
- const containers = (await compose("ps", "--all", "--quiet", service)).stdout
93
- .trim()
94
- .split(/\s+/)
95
- .filter(Boolean);
96
- if (containers.length !== 1 || !containers[0]) {
97
- throw new Error(`Expected one container for Compose service ${service}`);
98
- }
99
- const container = containers[0];
100
- const deadline = Date.now() + config.timeouts.runtime;
101
- while (true) {
102
- const state = stateSchema.parse(
103
- JSON.parse((await docker("inspect", "--format", "{{json .State}}", container)).stdout),
104
- );
105
- if (!state.Running) {
106
- throw new Error(
107
- `Docker service ${service} exited before the application started. Check docker logs ${container}.`,
108
- );
109
- }
110
- // Use this container start time, not the host clock or an old "started" event.
111
- const { stdout: log } = await docker(
112
- "exec",
113
- container,
114
- "/bin/sh",
115
- "-c",
116
- "if [ -f /data/codesyscontrol/codesyscontrol.log ]; then cat /data/codesyscontrol/codesyscontrol.log; fi",
117
- );
118
- const status = getApplicationStatus(log, build.application, Date.parse(state.StartedAt));
119
- if (status === "running") {
120
- console.log(`${build.application} is running in ${service}`);
121
- return { ...build, container };
122
- }
123
- if (status === "failed" || Date.now() >= deadline) {
124
- throw new Error(
125
- `CODESYS did not start ${build.application}. Runtime log:\n${log.split("\n").slice(-25).join("\n")}`,
126
- );
127
- }
128
- await delay(250);
129
- }
130
- } finally {
131
- await rm(definitionDirectory, { force: true, recursive: true });
132
- }
133
- });
52
+ withWorkerLock(config, async () => {
53
+ // Validate before stopping anything. A missing receipt includes a failed rebuild.
54
+ const build = await readBuild(config.outDir).catch((cause: unknown) => {
55
+ throw new Error(
56
+ `No complete build in ${config.outDir}. Run tsplc-build build first.`,
57
+ {
58
+ cause,
59
+ },
60
+ );
61
+ });
62
+ const definitionDirectory = await mkdtemp(join(tmpdir(), "tsplc-runtime-"));
63
+ try {
64
+ const composeFile = join(definitionDirectory, "compose.yaml");
65
+ // JSON is valid YAML.
66
+ await writeFile(composeFile, JSON.stringify(runtimeDefinition(name)));
67
+ const docker = (...args: string[]) =>
68
+ captureDocker(args, config.timeouts.runtime);
69
+ const compose = (...args: string[]) =>
70
+ docker(
71
+ "compose",
72
+ "--project-name",
73
+ runtimeProject(name),
74
+ "--file",
75
+ composeFile,
76
+ ...args,
77
+ );
78
+ const installer = await readFile(
79
+ new URL("../runtime/install.sh", import.meta.url),
80
+ "utf8",
81
+ );
82
+ console.log(
83
+ `Installing ${build.application} in Docker service ${service}`,
84
+ );
85
+ await compose("stop", service);
86
+ // The helper uses the service's volumes without starting its PLC or publishing
87
+ // ports. Its read-only artifact mount is removed with the helper container.
88
+ await compose(
89
+ "run",
90
+ "--rm",
91
+ "--no-deps",
92
+ "-T",
93
+ "--volume",
94
+ `${dirname(build.output)}:/codesys-build:ro`,
95
+ "--entrypoint",
96
+ "/bin/sh",
97
+ service,
98
+ "-c",
99
+ installer,
100
+ "codesys-build-install",
101
+ build.application,
102
+ basename(build.output, ".app"),
103
+ );
104
+ await compose("up", "--detach", "--no-deps", service);
105
+ const containers = (
106
+ await compose("ps", "--all", "--quiet", service)
107
+ ).stdout
108
+ .trim()
109
+ .split(/\s+/)
110
+ .filter(Boolean);
111
+ if (containers.length !== 1 || !containers[0]) {
112
+ throw new Error(
113
+ `Expected one container for Compose service ${service}`,
114
+ );
115
+ }
116
+ const container = containers[0];
117
+ const deadline = Date.now() + config.timeouts.runtime;
118
+ while (true) {
119
+ const state = stateSchema.parse(
120
+ JSON.parse(
121
+ (await docker("inspect", "--format", "{{json .State}}", container))
122
+ .stdout,
123
+ ),
124
+ );
125
+ if (!state.Running) {
126
+ throw new Error(
127
+ `Docker service ${service} exited before the application started. Check docker logs ${container}.`,
128
+ );
129
+ }
130
+ // Use this container start time, not the host clock or an old "started" event.
131
+ const { stdout: log } = await docker(
132
+ "exec",
133
+ container,
134
+ "/bin/sh",
135
+ "-c",
136
+ "if [ -f /data/codesyscontrol/codesyscontrol.log ]; then cat /data/codesyscontrol/codesyscontrol.log; fi",
137
+ );
138
+ const status = getApplicationStatus(
139
+ log,
140
+ build.application,
141
+ Date.parse(state.StartedAt),
142
+ );
143
+ if (status === "running") {
144
+ console.log(`${build.application} is running in ${service}`);
145
+ return { ...build, container };
146
+ }
147
+ if (status === "failed" || Date.now() >= deadline) {
148
+ throw new Error(
149
+ `CODESYS did not start ${build.application}. Runtime log:\n${log.split("\n").slice(-25).join("\n")}`,
150
+ );
151
+ }
152
+ await delay(250);
153
+ }
154
+ } finally {
155
+ await rm(definitionDirectory, { force: true, recursive: true });
156
+ }
157
+ });
@@ -1,21 +1,27 @@
1
1
  /** Runtime stdout is buffered in Docker. Its log file records start/stop events immediately. */
2
- export const getApplicationStatus = (log: string, application: string, startedAt: number) => {
3
- const event = log
4
- .split(/\r?\n/)
5
- .reverse()
6
- .find((line) => {
7
- const timestamp = Date.parse(line.split(",")[0] ?? "");
8
- if (!Number.isFinite(timestamp) || timestamp < startedAt) {
9
- return false;
10
- }
11
- return (
12
- line.includes(`<app>${application}</app>`) &&
13
- /\b(started|stopped|exception|corrupt|failed|denied)\b/i.test(line) &&
14
- !line.includes("load started")
15
- );
16
- });
17
- if (!event) {
18
- return "pending";
19
- }
20
- return event.includes(`Application [<app>${application}</app>] started`) ? "running" : "failed";
2
+ export const getApplicationStatus = (
3
+ log: string,
4
+ application: string,
5
+ startedAt: number,
6
+ ) => {
7
+ const event = log
8
+ .split(/\r?\n/)
9
+ .reverse()
10
+ .find((line) => {
11
+ const timestamp = Date.parse(line.split(",")[0] ?? "");
12
+ if (!Number.isFinite(timestamp) || timestamp < startedAt) {
13
+ return false;
14
+ }
15
+ return (
16
+ line.includes(`<app>${application}</app>`) &&
17
+ /\b(started|stopped|exception|corrupt|failed|denied)\b/i.test(line) &&
18
+ !line.includes("load started")
19
+ );
20
+ });
21
+ if (!event) {
22
+ return "pending";
23
+ }
24
+ return event.includes(`Application [<app>${application}</app>] started`)
25
+ ? "running"
26
+ : "failed";
21
27
  };