@tsplc/build 0.2.16 → 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
@@ -2,72 +2,76 @@ import { execFile } from "node:child_process";
2
2
  import { readdir, realpath } from "node:fs/promises";
3
3
  import { relative, resolve, sep, win32 } from "node:path";
4
4
  import { promisify } from "node:util";
5
- import type { ResolvedConfig } from "../config";
6
- import { commandArgumentSchema } from "./codesys-command";
7
- import { codesysTimeouts } from "@tsplc/config/build";
5
+ import {
6
+ codesysTimeouts,
7
+ commandArgumentSchema,
8
+ type ResolvedConfig,
9
+ } from "@tsplc/config/build";
8
10
 
9
11
  const execute = promisify(execFile);
10
12
 
11
13
  export const toWindowsPath = async (
12
- path: string,
13
- wine: ResolvedConfig["codesys"]["wine"],
14
- platform: NodeJS.Platform = process.platform,
14
+ path: string,
15
+ wine: ResolvedConfig["codesys"]["wine"],
16
+ platform: NodeJS.Platform = process.platform,
15
17
  ) => {
16
- if (platform === "win32") {
17
- return commandArgumentSchema.parse(win32.resolve(path));
18
- }
19
- if (!wine?.prefix) {
20
- throw new Error("Configure codesys.wine.prefix for CODESYS on macOS/Linux");
21
- }
18
+ if (platform === "win32") {
19
+ return commandArgumentSchema.parse(win32.resolve(path));
20
+ }
21
+ if (!wine?.prefix) {
22
+ throw new Error("Configure codesys.wine.prefix for CODESYS on macOS/Linux");
23
+ }
22
24
 
23
- // Resolve filesystem aliases (e.g. macOS /var -> /private/var) so the file
24
- // and drive roots are compared using the same paths. Fall back to the absolute
25
- // spelling when realpath cannot resolve the file, such as before it exists.
26
- const absolute = await realpath(resolve(path)).catch(() => resolve(path));
27
- // Wine stores drive mappings as symlinks, e.g. dosdevices/c: -> ../drive_c.
28
- // Reading these links avoids starting Wine just to convert a path.
29
- const devices = resolve(wine.prefix, "dosdevices");
30
- const drives = await readdir(devices).catch(() => []);
31
- const mappings = await Promise.all(
32
- drives
33
- .filter((drive) => /^[a-z]:$/i.test(drive))
34
- .map(async (drive) => {
35
- const root = await realpath(resolve(devices, drive)).catch(() => undefined);
36
- if (!root) {
37
- return;
38
- }
25
+ // Resolve filesystem aliases (e.g. macOS /var -> /private/var) so the file
26
+ // and drive roots are compared using the same paths. Fall back to the absolute
27
+ // spelling when realpath cannot resolve the file, such as before it exists.
28
+ const absolute = await realpath(resolve(path)).catch(() => resolve(path));
29
+ // Wine stores drive mappings as symlinks, e.g. dosdevices/c: -> ../drive_c.
30
+ // Reading these links avoids starting Wine just to convert a path.
31
+ const devices = resolve(wine.prefix, "dosdevices");
32
+ const drives = await readdir(devices).catch(() => []);
33
+ const mappings = await Promise.all(
34
+ drives
35
+ .filter((drive) => /^[a-z]:$/i.test(drive))
36
+ .map(async (drive) => {
37
+ const root = await realpath(resolve(devices, drive)).catch(
38
+ () => undefined,
39
+ );
40
+ if (!root) {
41
+ return;
42
+ }
39
43
 
40
- const suffix = relative(root, absolute);
41
- // ".." or "../..." means the file is outside this drive's root.
42
- // Match a full segment so a name such as "..notes" remains valid.
43
- if (suffix === ".." || suffix.startsWith(`..${sep}`)) {
44
- return;
45
- }
44
+ const suffix = relative(root, absolute);
45
+ // ".." or "../..." means the file is outside this drive's root.
46
+ // Match a full segment so a name such as "..notes" remains valid.
47
+ if (suffix === ".." || suffix.startsWith(`..${sep}`)) {
48
+ return;
49
+ }
46
50
 
47
- return {
48
- root,
49
- windows: win32.join(`${drive.toUpperCase()}\\`, ...suffix.split(sep)),
50
- };
51
- }),
52
- );
53
- // Mappings can overlap: C: -> /wine/drive_c and Z: -> / may both contain
54
- // the file. Prefer the longest matching root to use the most specific drive.
55
- const [mapping] = mappings
56
- .filter((value) => value !== undefined)
57
- .sort((a, b) => b.root.length - a.root.length);
58
- if (mapping) {
59
- return commandArgumentSchema.parse(mapping.windows);
60
- }
51
+ return {
52
+ root,
53
+ windows: win32.join(`${drive.toUpperCase()}\\`, ...suffix.split(sep)),
54
+ };
55
+ }),
56
+ );
57
+ // Mappings can overlap: C: -> /wine/drive_c and Z: -> / may both contain
58
+ // the file. Prefer the longest matching root to use the most specific drive.
59
+ const [mapping] = mappings
60
+ .filter((value) => value !== undefined)
61
+ .sort((a, b) => b.root.length - a.root.length);
62
+ if (mapping) {
63
+ return commandArgumentSchema.parse(mapping.windows);
64
+ }
61
65
 
62
- // No readable drive mapping covers the path; ask Wine to convert it instead.
63
- const result = await execute(
64
- wine.pathBinary,
65
- ["-w", resolve(path)],
66
- // Wine inherits OS process settings.
67
- {
68
- env: { ...process.env, WINEPREFIX: wine.prefix, WINEDEBUG: wine.debug },
69
- timeout: codesysTimeouts.hostCommand,
70
- },
71
- );
72
- return commandArgumentSchema.parse(result.stdout.trim());
66
+ // No readable drive mapping covers the path; ask Wine to convert it instead.
67
+ const result = await execute(
68
+ wine.pathBinary,
69
+ ["-w", resolve(path)],
70
+ // Wine inherits OS process settings.
71
+ {
72
+ env: { ...process.env, WINEPREFIX: wine.prefix, WINEDEBUG: wine.debug },
73
+ timeout: codesysTimeouts.hostCommand,
74
+ },
75
+ );
76
+ return commandArgumentSchema.parse(result.stdout.trim());
73
77
  };
@@ -0,0 +1,24 @@
1
+ import type { ResolvedConfig } from "@tsplc/config/build";
2
+ import { toWindowsPath } from "./host/windows-path";
3
+ import type { loadSources } from "./sources";
4
+
5
+ /**
6
+ * What a build and a controller operation both ask the worker to import into the project: the
7
+ * libraries at their Windows paths, the sources, unless the operation has none, and the task plan.
8
+ */
9
+ export const importRequest = async (
10
+ config: ResolvedConfig,
11
+ sources: Awaited<ReturnType<typeof loadSources>> | null,
12
+ ) => ({
13
+ libraries: await Promise.all(
14
+ (config.libraries ?? []).map(async (library) => ({
15
+ ...library,
16
+ path: await toWindowsPath(library.path, config.codesys.wine),
17
+ })),
18
+ ),
19
+ ...sources,
20
+ task: config.task,
21
+ ...(config.tasks && { tasks: config.tasks }),
22
+ removeObjects: config.removeObjects,
23
+ symbols: config.symbols,
24
+ });
package/src/index.ts CHANGED
@@ -1,46 +1,52 @@
1
1
  export { buildProject } from "./build";
2
2
  export {
3
- type CodesysBuildConfig,
4
- type CyclicTask,
5
- configSchema,
6
- defineConfig,
7
- loadConfig,
8
- type ResolvedConfig,
9
- resolveConfig,
10
- } from "./config";
3
+ type CodesysBuildConfig,
4
+ type CyclicTask,
5
+ configSchema,
6
+ defineBuildConfig as defineConfig,
7
+ loadConfig,
8
+ type ResolvedConfig,
9
+ resolveConfig,
10
+ } from "@tsplc/config/build";
11
11
  export {
12
- type ControllerLogin,
13
- type ControllerResult,
14
- explicitDownload,
15
- failureReason,
16
- findControllerLogin,
17
- inspectController,
18
- type LoginCommand,
19
- loginCommandSchema,
20
- type LoginResult,
21
- loginResultSchema,
22
- openControllerLogin,
23
- startWarmController,
24
- updateController,
25
- updateWarmController,
12
+ type ControllerLogin,
13
+ findControllerLogin,
14
+ inspectController,
15
+ openControllerLogin,
16
+ startWarmController,
17
+ updateController,
18
+ updateWarmController,
26
19
  } from "./controller-online";
27
- export { type CodesysCompilerDiagnostic, CodesysCompilerError } from "./diagnostics";
20
+ export {
21
+ type ControllerResult,
22
+ explicitDownload,
23
+ failureReason,
24
+ type LoginCommand,
25
+ loginCommandSchema,
26
+ type LoginResult,
27
+ loginResultSchema,
28
+ } from "./controller-protocol";
29
+ export {
30
+ type CodesysCompilerDiagnostic,
31
+ CodesysCompilerError,
32
+ } from "./diagnostics";
33
+ export { rawEngineeringSettings } from "./engineering-settings";
28
34
  export { runProject } from "./run";
29
35
  export { loadSources, type SourceObject } from "./sources";
30
36
  export { StSyntaxError } from "./st/lexer";
31
37
  export { type ObjectKind, type ParsedSource, parseSource } from "./st/parse";
32
38
 
33
39
  export {
34
- installLibraries,
35
- validateLibrary,
36
- libraryIndex,
37
- type InstalledLibrary,
40
+ installLibraries,
41
+ validateLibrary,
42
+ libraryIndex,
43
+ type InstalledLibrary,
38
44
  } from "./libraries.ts";
39
45
 
40
46
  export {
41
- configureDocker,
42
- configureGateway,
43
- configureRuntime,
44
- gatewayImage,
47
+ configureDocker,
48
+ configureGateway,
49
+ configureRuntime,
50
+ gatewayImage,
45
51
  } from "./docker-build.ts";
46
52
  export { readBuild } from "./artifacts.ts";
package/src/io.ts CHANGED
@@ -1,127 +1,163 @@
1
+ import { ioArray, ioScalarBits, sizePrefix } from "@tsplc/iec";
2
+ import { qualifiers, variableSections } from "@tsplc/iec/st";
1
3
  import type { SourceObject } from "./sources.ts";
2
4
  import { tokenize, type Token } from "./st/lexer.ts";
3
- import { variableSections } from "./st/declarations.ts";
4
5
 
5
6
  export interface DirectIoBinding {
6
- address: string;
7
- type?: string;
7
+ address: string;
8
+ type?: string;
8
9
  }
9
- // A span binds at its first element: ARRAY[l..u] OF <element> with consecutive addresses.
10
- const arrayType = /^ARRAY\s*\[\s*(-?\d+)\s*\.\.\s*(-?\d+)\s*\]\s*OF\s+(\w+)$/;
11
- const layout = (type: string) => {
12
- const array = arrayType.exec(type);
13
- return array
14
- ? { element: array[3]!, length: Number(array[2]) - Number(array[1]) + 1 }
15
- : { element: type, length: 1 };
16
- };
17
- const widths: Record<string, string> = {
18
- BOOL: "X",
19
- BYTE: "B",
20
- SINT: "B",
21
- USINT: "B",
22
- WORD: "W",
23
- INT: "W",
24
- UINT: "W",
25
- DWORD: "D",
26
- DINT: "D",
27
- UDINT: "D",
28
- REAL: "D",
10
+ const span = (type: string) => ioArray(type) ?? { element: type, length: 1 };
11
+ // Direct addresses by the width of one element; 64-bit types have no direct form.
12
+ const addressSize = (type: string) => {
13
+ const bits = ioScalarBits(type);
14
+ return bits === undefined || bits === 64 ? undefined : sizePrefix(bits);
29
15
  };
30
16
 
31
17
  /** Apply the shared mapping to declarations in memory; authored ST stays untouched. */
32
18
  export function bindStructuredTextIo(
33
- objects: SourceObject[],
34
- bindings: Record<string, DirectIoBinding>,
19
+ objects: SourceObject[],
20
+ bindings: Record<string, DirectIoBinding>,
35
21
  ) {
36
- const declarations: {
37
- object: SourceObject;
38
- name: string;
39
- names: Token[];
40
- colon: Token;
41
- type: string;
42
- }[] = [];
43
- const visit = (object: SourceObject) => {
44
- const tokens = tokenize(object.declaration, object.source);
45
- let section = false,
46
- start = 0;
47
- for (let i = 0; i < tokens.length; i++) {
48
- const token = tokens[i]!;
49
- if (variableSections.has(token.value)) {
50
- section = true;
51
- start = i + 1;
52
- continue;
53
- }
54
- if (token.value === "END_VAR") {
55
- section = false;
56
- continue;
57
- }
58
- if (!section || token.value !== ";") continue;
59
- const part = tokens.slice(start, i).filter((t) => t.kind !== "pragma");
60
- start = i + 1;
61
- const colonIndex = part.findIndex((t) => t.value === ":");
62
- if (colonIndex < 1) continue;
63
- const names = part
64
- .slice(0, colonIndex)
65
- .filter(
66
- (t) => t.kind === "word" && !["CONSTANT", "RETAIN", "PERSISTENT", "AT"].includes(t.value),
67
- );
68
- const at = part.findIndex((t) => t.value === "AT");
69
- const variables = at < 0 ? names : names.filter((t) => t.start < part[at]!.start);
70
- const initializer = part.findIndex((t, index) => index > colonIndex && t.value === ":=");
71
- const typeTokens = part.slice(colonIndex + 1, initializer < 0 ? undefined : initializer);
72
- const type = typeTokens.length
73
- ? object.declaration
74
- .slice(typeTokens[0]!.start, typeTokens.at(-1)!.end)
75
- .replace(/\s+/g, " ")
76
- .toUpperCase()
77
- : "";
78
- for (const name of variables)
79
- declarations.push({
80
- object,
81
- name: name.value,
82
- names: variables,
83
- colon: part[colonIndex]!,
84
- type,
85
- });
86
- }
87
- object.children.forEach(visit);
88
- };
89
- objects.forEach(visit);
90
- const edits = new Map<SourceObject, { start: number; end: number; text: string }[]>();
91
- for (const [symbol, binding] of Object.entries(bindings)) {
92
- const parts = symbol.toUpperCase().split(".");
93
- if (parts.length > 2)
94
- throw new Error(`${symbol}: direct IO maps a scalar declaration, not a nested field.`);
95
- const matches = declarations.filter(
96
- (d) =>
97
- d.name === parts.at(-1) && (parts.length === 1 || d.object.name.toUpperCase() === parts[0]),
98
- );
99
- if (matches.length !== 1)
100
- throw new Error(
101
- `${symbol}: expected one ST variable declaration, found ${matches.length}. Use Object.Variable to disambiguate.`,
102
- );
103
- const declaration = matches[0]!;
104
- if (declaration.names.length !== 1)
105
- throw new Error(`${symbol}: declare mapped IO variables separately.`);
106
- const declared = layout(declaration.type);
107
- if (
108
- !widths[declared.element] ||
109
- (declared.length > 1 && declared.element === "BOOL") ||
110
- binding.address[2] !== widths[declared.element]
111
- )
112
- throw new Error(`${symbol}: ${declaration.type} is incompatible with ${binding.address}.`);
113
- const expected = binding.type && layout(binding.type.replace(/\s+/g, " ").toUpperCase());
114
- if (expected && (expected.element !== declared.element || expected.length !== declared.length))
115
- throw new Error(`${symbol}: expected ${binding.type}, found ${declaration.type}.`);
116
- const list = edits.get(declaration.object) ?? [];
117
- const start = declaration.names[0]!.end;
118
- if (list.some((e) => e.start === start))
119
- throw new Error(`${symbol}: the variable has more than one IO binding.`);
120
- list.push({ start, end: declaration.colon.start, text: ` AT ${binding.address} ` });
121
- edits.set(declaration.object, list);
122
- }
123
- for (const [object, list] of edits)
124
- for (const edit of list.sort((a, b) => b.start - a.start))
125
- object.declaration =
126
- object.declaration.slice(0, edit.start) + edit.text + object.declaration.slice(edit.end);
22
+ const declarations: {
23
+ object: SourceObject;
24
+ name: string;
25
+ names: Token[];
26
+ colon: Token;
27
+ type: string;
28
+ }[] = [];
29
+ const visit = (object: SourceObject) => {
30
+ const tokens = tokenize(object.declaration, object.source);
31
+ let section = false;
32
+ let start = 0;
33
+ for (const [index, token] of tokens.entries()) {
34
+ if (variableSections.has(token.value)) {
35
+ section = true;
36
+ start = index + 1;
37
+ continue;
38
+ }
39
+ if (token.value === "END_VAR") {
40
+ section = false;
41
+ continue;
42
+ }
43
+ if (!section || token.value !== ";") {
44
+ continue;
45
+ }
46
+ const part = tokens
47
+ .slice(start, index)
48
+ .filter((t) => t.kind !== "pragma");
49
+ start = index + 1;
50
+ const colon = part.find((t) => t.value === ":");
51
+ if (!colon) {
52
+ continue;
53
+ }
54
+ const colonIndex = part.indexOf(colon);
55
+ if (colonIndex < 1) {
56
+ continue;
57
+ }
58
+ const names = part
59
+ .slice(0, colonIndex)
60
+ .filter(
61
+ (t) =>
62
+ t.kind === "word" && !qualifiers.has(t.value) && t.value !== "AT",
63
+ );
64
+ const at = part.find((t) => t.value === "AT");
65
+ const variables = at ? names.filter((t) => t.start < at.start) : names;
66
+ const initializer = part.findIndex(
67
+ (t, index) => index > colonIndex && t.value === ":=",
68
+ );
69
+ const typeTokens = part.slice(
70
+ colonIndex + 1,
71
+ initializer < 0 ? undefined : initializer,
72
+ );
73
+ const [first] = typeTokens;
74
+ const last = typeTokens.at(-1);
75
+ const type =
76
+ first && last
77
+ ? object.declaration
78
+ .slice(first.start, last.end)
79
+ .replace(/\s+/g, " ")
80
+ .toUpperCase()
81
+ : "";
82
+ for (const name of variables) {
83
+ declarations.push({
84
+ object,
85
+ name: name.value,
86
+ names: variables,
87
+ colon,
88
+ type,
89
+ });
90
+ }
91
+ }
92
+ object.children.forEach(visit);
93
+ };
94
+ objects.forEach(visit);
95
+ const edits = new Map<
96
+ SourceObject,
97
+ { start: number; end: number; text: string }[]
98
+ >();
99
+ for (const [symbol, binding] of Object.entries(bindings)) {
100
+ const parts = symbol.toUpperCase().split(".");
101
+ if (parts.length > 2) {
102
+ throw new Error(
103
+ `${symbol}: direct IO maps a scalar declaration, not a nested field.`,
104
+ );
105
+ }
106
+ const matches = declarations.filter(
107
+ (d) =>
108
+ d.name === parts.at(-1) &&
109
+ (parts.length === 1 || d.object.name.toUpperCase() === parts[0]),
110
+ );
111
+ const [declaration, ...others] = matches;
112
+ if (!declaration || others.length) {
113
+ throw new Error(
114
+ `${symbol}: expected one ST variable declaration, found ${matches.length}. Use Object.Variable to disambiguate.`,
115
+ );
116
+ }
117
+ const [variable, ...siblings] = declaration.names;
118
+ if (!variable || siblings.length) {
119
+ throw new Error(`${symbol}: declare mapped IO variables separately.`);
120
+ }
121
+ const declared = span(declaration.type);
122
+ const size = addressSize(declared.element);
123
+ if (
124
+ !size ||
125
+ (declared.length > 1 && declared.element === "BOOL") ||
126
+ binding.address[2] !== size
127
+ ) {
128
+ throw new Error(
129
+ `${symbol}: ${declaration.type} is incompatible with ${binding.address}.`,
130
+ );
131
+ }
132
+ const expected =
133
+ binding.type && span(binding.type.replace(/\s+/g, " ").toUpperCase());
134
+ if (
135
+ expected &&
136
+ (expected.element !== declared.element ||
137
+ expected.length !== declared.length)
138
+ ) {
139
+ throw new Error(
140
+ `${symbol}: expected ${binding.type}, found ${declaration.type}.`,
141
+ );
142
+ }
143
+ const list = edits.get(declaration.object) ?? [];
144
+ const start = variable.end;
145
+ if (list.some((e) => e.start === start)) {
146
+ throw new Error(`${symbol}: the variable has more than one IO binding.`);
147
+ }
148
+ list.push({
149
+ start,
150
+ end: declaration.colon.start,
151
+ text: ` AT ${binding.address} `,
152
+ });
153
+ edits.set(declaration.object, list);
154
+ }
155
+ for (const [object, list] of edits) {
156
+ for (const edit of list.sort((a, b) => b.start - a.start)) {
157
+ object.declaration =
158
+ object.declaration.slice(0, edit.start) +
159
+ edit.text +
160
+ object.declaration.slice(edit.end);
161
+ }
162
+ }
127
163
  }