@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
@@ -4,32 +4,54 @@ import { tmpdir } from "node:os";
4
4
  import { dirname, resolve } from "node:path";
5
5
  import { packageDirectory } from "./package-path.ts";
6
6
 
7
+ /** The workspace packages container code imports, each copied with the files Bun runs it from. */
8
+ const containerPackages = [
9
+ {
10
+ entry: "@tsplc/config/build",
11
+ directory: "shared-config",
12
+ files: ["src", "templates", "package.json"],
13
+ },
14
+ {
15
+ entry: "@tsplc/iec",
16
+ directory: "shared-iec",
17
+ files: ["src", "package.json"],
18
+ },
19
+ ];
20
+
7
21
  export async function prepareDockerContext() {
8
- const context = await mkdtemp(resolve(tmpdir(), "tsplc-docker-"));
9
- try {
10
- for (const directory of ["src", "python", "docker", "runtime"])
11
- await cp(resolve(packageDirectory, directory), resolve(context, directory), {
12
- recursive: true,
13
- });
14
- const configRoot = resolve(
15
- dirname(createRequire(import.meta.url).resolve("@tsplc/config/build")),
16
- "..",
17
- );
18
- await mkdir(resolve(context, "shared-config"));
19
- await cp(resolve(configRoot, "src"), resolve(context, "shared-config/src"), {
20
- recursive: true,
21
- });
22
- await cp(resolve(configRoot, "templates"), resolve(context, "shared-config/templates"), {
23
- recursive: true,
24
- });
25
- await cp(resolve(configRoot, "package.json"), resolve(context, "shared-config/package.json"));
26
- await writeFile(
27
- resolve(context, "package.json"),
28
- JSON.stringify({ type: "module", dependencies: { zod: "4.3.6", jiti: "2.7.0" } }),
29
- );
30
- return context;
31
- } catch (cause) {
32
- await rm(context, { recursive: true, force: true });
33
- throw cause;
34
- }
22
+ const context = await mkdtemp(resolve(tmpdir(), "tsplc-docker-"));
23
+ try {
24
+ for (const directory of ["src", "python", "docker", "runtime"]) {
25
+ await cp(
26
+ resolve(packageDirectory, directory),
27
+ resolve(context, directory),
28
+ {
29
+ recursive: true,
30
+ },
31
+ );
32
+ }
33
+ for (const { entry, directory, files } of containerPackages) {
34
+ const root = resolve(
35
+ dirname(createRequire(import.meta.url).resolve(entry)),
36
+ "..",
37
+ );
38
+ await mkdir(resolve(context, directory));
39
+ for (const file of files) {
40
+ await cp(resolve(root, file), resolve(context, directory, file), {
41
+ recursive: true,
42
+ });
43
+ }
44
+ }
45
+ await writeFile(
46
+ resolve(context, "package.json"),
47
+ JSON.stringify({
48
+ type: "module",
49
+ dependencies: { zod: "4.3.6", jiti: "2.7.0" },
50
+ }),
51
+ );
52
+ return context;
53
+ } catch (cause) {
54
+ await rm(context, { recursive: true, force: true });
55
+ throw cause;
56
+ }
35
57
  }
package/src/docker-run.ts CHANGED
@@ -1,83 +1,103 @@
1
- import { spawn } from "node:child_process";
1
+ import { execFile, spawn } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
3
  import { copyFile, cp, mkdir, readFile, writeFile } from "node:fs/promises";
4
4
  import { basename, posix, relative, resolve, sep } from "node:path";
5
- import type { ResolvedConfig } from "./config.ts";
5
+ import { promisify } from "node:util";
6
+ import type { ResolvedConfig } from "@tsplc/config/build";
7
+
8
+ const execute = promisify(execFile);
9
+
10
+ /** Run a Docker client command with its output captured instead of shown on this terminal. */
11
+ export const captureDocker = (args: string[], timeout: number) =>
12
+ execute("docker", args, { timeout, maxBuffer: 8 * 1024 * 1024 });
6
13
 
7
14
  /** Run a Docker client command attached to this terminal and forward interruption to it. */
8
- export const runDocker = (args: string[], failure: (status: string | number | null) => string) =>
9
- new Promise<void>((accept, reject) => {
10
- const child = spawn("docker", args, {
11
- stdio: ["inherit", process.env["TSPLC_LOG_STDERR"] === "1" ? 2 : "inherit", "inherit"],
12
- });
13
- const interrupt = () => child.kill("SIGINT");
14
- const terminate = () => child.kill("SIGTERM");
15
- process.on("SIGINT", interrupt);
16
- process.on("SIGTERM", terminate);
17
- const cleanup = () => {
18
- process.off("SIGINT", interrupt);
19
- process.off("SIGTERM", terminate);
20
- };
21
- child.once("error", (cause) => {
22
- cleanup();
23
- reject(
24
- new Error("Cannot start Docker. Install and start Docker Desktop or Docker Engine", {
25
- cause,
26
- }),
27
- );
28
- });
29
- child.once("exit", (code, signal) => {
30
- cleanup();
31
- if (code === 0) {
32
- accept();
33
- } else {
34
- reject(new Error(failure(signal ?? code)));
35
- }
36
- });
37
- });
15
+ export const runDocker = (
16
+ args: string[],
17
+ failure: (status: string | number | null) => string,
18
+ ) =>
19
+ new Promise<void>((accept, reject) => {
20
+ const child = spawn("docker", args, {
21
+ stdio: [
22
+ "inherit",
23
+ process.env["TSPLC_LOG_STDERR"] === "1" ? 2 : "inherit",
24
+ "inherit",
25
+ ],
26
+ });
27
+ const interrupt = () => child.kill("SIGINT");
28
+ const terminate = () => child.kill("SIGTERM");
29
+ process.on("SIGINT", interrupt);
30
+ process.on("SIGTERM", terminate);
31
+ const cleanup = () => {
32
+ process.off("SIGINT", interrupt);
33
+ process.off("SIGTERM", terminate);
34
+ };
35
+ child.once("error", (cause) => {
36
+ cleanup();
37
+ reject(
38
+ new Error(
39
+ "Cannot start Docker. Install and start Docker Desktop or Docker Engine",
40
+ {
41
+ cause,
42
+ },
43
+ ),
44
+ );
45
+ });
46
+ child.once("exit", (code, signal) => {
47
+ cleanup();
48
+ if (code === 0) {
49
+ accept();
50
+ } else {
51
+ reject(new Error(failure(signal ?? code)));
52
+ }
53
+ });
54
+ });
38
55
 
39
56
  const bindMount = (source: string, target: string, readonly = false) =>
40
- `type=bind,"source=${source.replaceAll('"', '""')}",target=${target}${readonly ? ",readonly" : ""}`;
57
+ `type=bind,"source=${source.replaceAll('"', '""')}",target=${target}${readonly ? ",readonly" : ""}`;
41
58
 
42
59
  /** Copies the libraries to `directory`, which the container sees as `root`. */
43
60
  async function mountLibraries(
44
- libraries: ResolvedConfig["libraries"],
45
- directory: string,
46
- root = "/input",
61
+ libraries: ResolvedConfig["libraries"],
62
+ directory: string,
63
+ root = "/input",
47
64
  ) {
48
- if (!libraries?.length) return undefined;
49
- await mkdir(resolve(directory, "libraries"), { recursive: true });
50
- return Promise.all(
51
- libraries.map(async (library) => {
52
- const data = await readFile(library.path);
53
- if (createHash("sha256").update(data).digest("hex") !== library.sha256)
54
- throw new Error(`Library changed after installation: ${library.title}`);
55
- const filename = `${library.sha256}-${basename(library.path)}`;
56
- await writeFile(resolve(directory, "libraries", filename), data);
57
- return { ...library, path: `${root}/libraries/${filename}` };
58
- }),
59
- );
65
+ if (!libraries?.length) {
66
+ return undefined;
67
+ }
68
+ await mkdir(resolve(directory, "libraries"), { recursive: true });
69
+ return Promise.all(
70
+ libraries.map(async (library) => {
71
+ const data = await readFile(library.path);
72
+ if (createHash("sha256").update(data).digest("hex") !== library.sha256) {
73
+ throw new Error(`Library changed after installation: ${library.title}`);
74
+ }
75
+ const filename = `${library.sha256}-${basename(library.path)}`;
76
+ await writeFile(resolve(directory, "libraries", filename), data);
77
+ return { ...library, path: `${root}/libraries/${filename}` };
78
+ }),
79
+ );
60
80
  }
61
81
 
62
82
  /** The config a builder container reads: host-only settings removed, paths inside the container. */
63
83
  const containerConfig = (
64
- config: ResolvedConfig,
65
- paths: { sourceDir: string; template: string },
66
- libraries: ResolvedConfig["libraries"] | [],
84
+ config: ResolvedConfig,
85
+ paths: { sourceDir: string; template: string },
86
+ libraries: ResolvedConfig["libraries"] | [],
67
87
  ) => ({
68
- ...config,
69
- libraries,
70
- configFile: undefined,
71
- docker: undefined,
72
- codesys: undefined,
73
- sourceDir: paths.sourceDir,
74
- entry: posix.resolve(
75
- paths.sourceDir,
76
- relative(config.sourceDir, config.entry).split(sep).join("/"),
77
- ),
78
- template: paths.template,
79
- outDir: "/output",
80
- runtime: undefined,
88
+ ...config,
89
+ libraries,
90
+ configFile: undefined,
91
+ docker: undefined,
92
+ codesys: undefined,
93
+ sourceDir: paths.sourceDir,
94
+ entry: posix.resolve(
95
+ paths.sourceDir,
96
+ relative(config.sourceDir, config.entry).split(sep).join("/"),
97
+ ),
98
+ template: paths.template,
99
+ outDir: "/output",
100
+ runtime: undefined,
81
101
  });
82
102
 
83
103
  /**
@@ -85,24 +105,26 @@ const containerConfig = (
85
105
  * which a warm container sees as `root`, and writes their config there. Returns its container path.
86
106
  */
87
107
  export const writeOperationRequest = async (
88
- config: ResolvedConfig,
89
- directory: string,
90
- root: string,
108
+ config: ResolvedConfig,
109
+ directory: string,
110
+ root: string,
91
111
  ) => {
92
- await mkdir(directory, { recursive: true });
93
- await cp(config.sourceDir, resolve(directory, "sources"), { recursive: true });
94
- await copyFile(config.template, resolve(directory, "template.project"));
95
- await writeFile(
96
- resolve(directory, "config.json"),
97
- JSON.stringify(
98
- containerConfig(
99
- config,
100
- { sourceDir: `${root}/sources`, template: `${root}/template.project` },
101
- await mountLibraries(config.libraries, directory, root),
102
- ),
103
- ),
104
- );
105
- return `${root}/config.json`;
112
+ await mkdir(directory, { recursive: true });
113
+ await cp(config.sourceDir, resolve(directory, "sources"), {
114
+ recursive: true,
115
+ });
116
+ await copyFile(config.template, resolve(directory, "template.project"));
117
+ await writeFile(
118
+ resolve(directory, "config.json"),
119
+ JSON.stringify(
120
+ containerConfig(
121
+ config,
122
+ { sourceDir: `${root}/sources`, template: `${root}/template.project` },
123
+ await mountLibraries(config.libraries, directory, root),
124
+ ),
125
+ ),
126
+ );
127
+ return `${root}/config.json`;
106
128
  };
107
129
 
108
130
  /**
@@ -112,35 +134,39 @@ export const writeOperationRequest = async (
112
134
  * stay outside.
113
135
  */
114
136
  export const prepareContainerRun = async (
115
- config: ResolvedConfig,
116
- requestDirectory: string,
117
- options: { network: string; environment?: string[]; sources: boolean },
137
+ config: ResolvedConfig,
138
+ requestDirectory: string,
139
+ options: { network: string; environment?: string[]; sources: boolean },
118
140
  ) => {
119
- await writeFile(
120
- resolve(requestDirectory, "config.json"),
121
- JSON.stringify(
122
- containerConfig(
123
- config,
124
- { sourceDir: "/sources", template: "/template.project" },
125
- options.sources ? await mountLibraries(config.libraries, requestDirectory) : [],
126
- ),
127
- ),
128
- );
129
- return [
130
- "--init",
131
- ...(config.docker?.cpuSet ? ["--cpuset-cpus", config.docker.cpuSet] : []),
132
- "--network",
133
- options.network,
134
- ...(process.getuid && process.getgid
135
- ? ["--user", `${process.getuid()}:${process.getgid()}`]
136
- : []),
137
- ...(options.environment ?? []).flatMap((name) => ["--env", name]),
138
- "--mount",
139
- bindMount(requestDirectory, "/input", true),
140
- ...(options.sources ? ["--mount", bindMount(config.sourceDir, "/sources", true)] : []),
141
- "--mount",
142
- bindMount(config.template, "/template.project", true),
143
- "--mount",
144
- bindMount(config.outDir, "/output"),
145
- ];
141
+ await writeFile(
142
+ resolve(requestDirectory, "config.json"),
143
+ JSON.stringify(
144
+ containerConfig(
145
+ config,
146
+ { sourceDir: "/sources", template: "/template.project" },
147
+ options.sources
148
+ ? await mountLibraries(config.libraries, requestDirectory)
149
+ : [],
150
+ ),
151
+ ),
152
+ );
153
+ return [
154
+ "--init",
155
+ ...(config.docker?.cpuSet ? ["--cpuset-cpus", config.docker.cpuSet] : []),
156
+ "--network",
157
+ options.network,
158
+ ...(process.getuid && process.getgid
159
+ ? ["--user", `${process.getuid()}:${process.getgid()}`]
160
+ : []),
161
+ ...(options.environment ?? []).flatMap((name) => ["--env", name]),
162
+ "--mount",
163
+ bindMount(requestDirectory, "/input", true),
164
+ ...(options.sources
165
+ ? ["--mount", bindMount(config.sourceDir, "/sources", true)]
166
+ : []),
167
+ "--mount",
168
+ bindMount(config.template, "/template.project", true),
169
+ "--mount",
170
+ bindMount(config.outDir, "/output"),
171
+ ];
146
172
  };
@@ -0,0 +1,42 @@
1
+ import {
2
+ controllerFor,
3
+ type loadTsplcConfig,
4
+ rawBuildConfig,
5
+ simulationConfig,
6
+ } from "@tsplc/config";
7
+ import { deviceTree } from "@tsplc/typegen";
8
+ import { loadHardware, resolveIo } from "@tsplc/typegen/hardware";
9
+ import { resolveConfig } from "@tsplc/config/build";
10
+ import { installLibraries } from "./libraries.ts";
11
+
12
+ /**
13
+ * The settings a raw Structured Text project builds, runs and updates its controller with:
14
+ * libraries installed, IO bound and the device tree generated from the project's hardware.
15
+ * A simulated project leaves out the fieldbus IO and device tree, so a plant simulator writes
16
+ * the inputs instead.
17
+ */
18
+ export const rawEngineeringSettings = async (
19
+ { config, configFile, root }: Awaited<ReturnType<typeof loadTsplcConfig>>,
20
+ options: {
21
+ command: "build" | "run" | "download" | "online-change";
22
+ frozenLockfile?: boolean;
23
+ simulate?: boolean;
24
+ },
25
+ ) => {
26
+ const hardwareConfig = options.simulate ? simulationConfig(config) : config;
27
+ const build = rawBuildConfig(config);
28
+ const libraries = await installLibraries(config.dependencies, root, {
29
+ frozen: options.frozenLockfile,
30
+ });
31
+ const hardware = await loadHardware(hardwareConfig, root);
32
+ return resolveConfig(
33
+ {
34
+ ...build,
35
+ libraries,
36
+ io: resolveIo(hardwareConfig, hardware),
37
+ deviceTree: await deviceTree(hardwareConfig, hardware),
38
+ controller: controllerFor(config, options.command),
39
+ },
40
+ configFile,
41
+ );
42
+ };
@@ -1,45 +1,46 @@
1
- export { commandArgumentSchema } from "@tsplc/config/build";
2
- import type { ResolvedConfig } from "../config";
1
+ import type { ResolvedConfig } from "@tsplc/config/build";
3
2
 
4
3
  export const codesysCommandFilename = "run.cmd";
5
4
 
6
5
  // Keep arguments in the Windows command line: Wine's direct launcher loses the
7
6
  // quoting CODESYS needs around profile names containing spaces.
8
7
  export const codesysCommand = [
9
- "@echo off",
10
- "setlocal DisableDelayedExpansion",
11
- '"%CODESYS_BUILD_EXE%" --profile="%CODESYS_BUILD_PROFILE%" --noUI --runscript="%CODESYS_BUILD_SCRIPT%"',
12
- 'set "CODESYS_BUILD_STATUS=%errorlevel%"',
13
- 'if not "%CODESYS_BUILD_STATUS%"=="0" echo CODESYS Windows exit status: %CODESYS_BUILD_STATUS%',
14
- "exit /b %CODESYS_BUILD_STATUS%",
15
- "",
8
+ "@echo off",
9
+ "setlocal DisableDelayedExpansion",
10
+ '"%CODESYS_BUILD_EXE%" --profile="%CODESYS_BUILD_PROFILE%" --noUI --runscript="%CODESYS_BUILD_SCRIPT%"',
11
+ 'set "CODESYS_BUILD_STATUS=%errorlevel%"',
12
+ 'if not "%CODESYS_BUILD_STATUS%"=="0" echo CODESYS Windows exit status: %CODESYS_BUILD_STATUS%',
13
+ "exit /b %CODESYS_BUILD_STATUS%",
14
+ "",
16
15
  ].join("\r\n");
17
16
 
18
17
  export const getHostCommand = (
19
- config: Pick<ResolvedConfig["codesys"], "commandProcessor" | "wine">,
20
- platform: NodeJS.Platform = process.platform,
18
+ config: Pick<ResolvedConfig["codesys"], "commandProcessor" | "wine">,
19
+ platform: NodeJS.Platform = process.platform,
21
20
  ) => {
22
- if (platform === "win32") {
23
- return {
24
- args: ["/d", "/c", codesysCommandFilename],
25
- executable: config.commandProcessor,
26
- };
27
- }
28
- const wine = config.wine?.binary ?? "wine";
29
- const args = ["cmd", "/d", "/c", codesysCommandFilename];
30
- // --noUI suppresses the IDE, but CODESYS can still allocate a Wine console.
31
- // A private PTY makes Wine use its Unix console instead of a desktop window.
32
- return {
33
- args:
34
- platform === "darwin"
35
- ? ["-q", "/dev/null", wine, ...args]
36
- : [
37
- "-q",
38
- "-e",
39
- "-c",
40
- [wine, ...args].map((argument) => `'${argument.replaceAll("'", "'\\''")}'`).join(" "),
41
- "/dev/null",
42
- ],
43
- executable: "script",
44
- };
21
+ if (platform === "win32") {
22
+ return {
23
+ args: ["/d", "/c", codesysCommandFilename],
24
+ executable: config.commandProcessor,
25
+ };
26
+ }
27
+ const wine = config.wine?.binary ?? "wine";
28
+ const args = ["cmd", "/d", "/c", codesysCommandFilename];
29
+ // --noUI suppresses the IDE, but CODESYS can still allocate a Wine console.
30
+ // A private PTY makes Wine use its Unix console instead of a desktop window.
31
+ return {
32
+ args:
33
+ platform === "darwin"
34
+ ? ["-q", "/dev/null", wine, ...args]
35
+ : [
36
+ "-q",
37
+ "-e",
38
+ "-c",
39
+ [wine, ...args]
40
+ .map((argument) => `'${argument.replaceAll("'", "'\\''")}'`)
41
+ .join(" "),
42
+ "/dev/null",
43
+ ],
44
+ executable: "script",
45
+ };
45
46
  };