@tsplc/compiler 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 (157) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +920 -943
  3. package/dist/cli.js.map +13 -10
  4. package/dist/codesys.js +3893 -3352
  5. package/dist/codesys.js.map +29 -20
  6. package/dist/elaborate-capture.js +33 -17
  7. package/dist/elaborate-capture.js.map +3 -3
  8. package/dist/index.js +8787 -6855
  9. package/dist/index.js.map +40 -20
  10. package/dist/ir.js +1575 -1072
  11. package/dist/ir.js.map +21 -17
  12. package/dist/math.js.map +2 -2
  13. package/dist/project.js +154 -60
  14. package/dist/project.js.map +5 -5
  15. package/dist/telemetry.js +27 -9
  16. package/dist/telemetry.js.map +5 -5
  17. package/package.json +112 -112
  18. package/src/codesys/config.ts +50 -0
  19. package/src/codesys/debug.ts +670 -0
  20. package/src/codesys/emit.ts +142 -0
  21. package/src/codesys/engineering.ts +109 -0
  22. package/src/codesys/expressions.ts +92 -0
  23. package/src/codesys/global-lists.ts +250 -0
  24. package/src/codesys/global-names.ts +68 -0
  25. package/src/codesys/http.ts +890 -0
  26. package/src/codesys/index.ts +30 -0
  27. package/src/codesys/instrumentation.ts +430 -0
  28. package/src/codesys/io-paths.ts +140 -0
  29. package/src/codesys/manifest.ts +643 -0
  30. package/src/codesys/names.ts +81 -0
  31. package/src/codesys/numeric.ts +409 -0
  32. package/src/codesys/operands.ts +62 -0
  33. package/src/codesys/plan.ts +605 -0
  34. package/src/codesys/programs.ts +53 -0
  35. package/src/codesys/publication.ts +171 -0
  36. package/src/codesys/routines.ts +603 -0
  37. package/src/codesys/sources.ts +71 -0
  38. package/src/codesys/st-files.ts +115 -0
  39. package/src/codesys/storage.ts +97 -0
  40. package/src/codesys/symbols.ts +220 -0
  41. package/src/codesys/task-access.ts +320 -0
  42. package/src/codesys/telemetry.ts +732 -0
  43. package/src/codesys/types.ts +250 -0
  44. package/src/codesys/vendor.ts +150 -0
  45. package/src/frontend/analyzer.ts +794 -0
  46. package/src/frontend/async.ts +317 -1137
  47. package/src/frontend/blocks.ts +537 -403
  48. package/src/frontend/configuration.ts +176 -144
  49. package/src/frontend/const-functions.ts +183 -148
  50. package/src/frontend/cooperative.ts +73 -43
  51. package/src/frontend/coroutines.ts +1032 -0
  52. package/src/frontend/elaborate/calls.ts +535 -0
  53. package/src/frontend/elaborate/capture.ts +157 -101
  54. package/src/frontend/elaborate/dialect.ts +257 -0
  55. package/src/frontend/elaborate/expressions.ts +992 -0
  56. package/src/frontend/elaborate/frame.ts +53 -0
  57. package/src/frontend/elaborate/graph.ts +116 -71
  58. package/src/frontend/elaborate/imports.ts +70 -0
  59. package/src/frontend/elaborate/index.ts +435 -331
  60. package/src/frontend/elaborate/initializers.ts +198 -0
  61. package/src/frontend/elaborate/layouts.ts +591 -384
  62. package/src/frontend/elaborate/model.ts +264 -169
  63. package/src/frontend/elaborate/specialize.ts +343 -2586
  64. package/src/frontend/elaborate/statements.ts +606 -0
  65. package/src/frontend/elaborate/storage.ts +546 -0
  66. package/src/frontend/elaborate/values.ts +58 -0
  67. package/src/frontend/elaborate/writes.ts +100 -0
  68. package/src/frontend/exposure.ts +172 -140
  69. package/src/frontend/expressions.ts +1383 -0
  70. package/src/frontend/intrinsics.ts +337 -0
  71. package/src/frontend/module-graph.ts +89 -59
  72. package/src/frontend/positions.ts +271 -200
  73. package/src/frontend/promise-chains.ts +897 -0
  74. package/src/frontend/promises.ts +390 -747
  75. package/src/frontend/routines.ts +181 -0
  76. package/src/frontend/sdk.ts +82 -0
  77. package/src/frontend/services.ts +506 -372
  78. package/src/frontend/statements.ts +855 -0
  79. package/src/frontend/tasks.ts +471 -0
  80. package/src/frontend/telemetry.ts +174 -0
  81. package/src/frontend/types.ts +845 -551
  82. package/src/frontend/typescript.ts +323 -2543
  83. package/src/index.ts +5 -5
  84. package/src/ir/aggregates.ts +275 -0
  85. package/src/ir/allocation.ts +84 -0
  86. package/src/ir/core-model.ts +146 -0
  87. package/src/ir/declarations.ts +295 -0
  88. package/src/ir/diagnostics.ts +61 -0
  89. package/src/ir/domains.ts +152 -0
  90. package/src/ir/fold.ts +342 -0
  91. package/src/ir/index.ts +90 -0
  92. package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
  93. package/src/ir/layouts.ts +181 -0
  94. package/src/ir/link.ts +354 -0
  95. package/src/ir/model.ts +386 -0
  96. package/{ir → src/ir}/normalization-error.ts +4 -4
  97. package/src/ir/normalize.ts +70 -0
  98. package/src/ir/numeric.ts +171 -0
  99. package/src/ir/ranges.ts +256 -0
  100. package/src/ir/routine.ts +1163 -0
  101. package/src/ir/scalars.ts +321 -0
  102. package/src/ir/types.ts +127 -0
  103. package/src/project/artifacts.ts +342 -0
  104. package/src/project/cli.ts +177 -0
  105. package/src/project/debugger.ts +82 -0
  106. package/src/project/index.ts +6 -0
  107. package/src/project/plant.ts +467 -0
  108. package/src/project/project-commands.ts +372 -0
  109. package/src/project/project.ts +457 -0
  110. package/src/project/release.ts +153 -0
  111. package/src/project/server.ts +150 -0
  112. package/src/project/terminal.ts +32 -0
  113. package/stdlib/math.ts +14 -10
  114. package/stdlib/telemetry.ts +71 -47
  115. package/types/async.d.ts +46 -40
  116. package/types/data-types.d.ts +26 -26
  117. package/types/globals.d.ts +41 -38
  118. package/types/index.d.ts +96 -51
  119. package/types/plc.d.ts +3 -4
  120. package/types/telemetry.d.ts +14 -14
  121. package/backends/codesys/config.ts +0 -54
  122. package/backends/codesys/debug.ts +0 -509
  123. package/backends/codesys/emit.ts +0 -1738
  124. package/backends/codesys/engineering.ts +0 -88
  125. package/backends/codesys/global-names.ts +0 -49
  126. package/backends/codesys/http.ts +0 -675
  127. package/backends/codesys/index.ts +0 -13
  128. package/backends/codesys/io-paths.ts +0 -105
  129. package/backends/codesys/manifest.ts +0 -312
  130. package/backends/codesys/names.ts +0 -76
  131. package/backends/codesys/numeric.ts +0 -356
  132. package/backends/codesys/plan.ts +0 -457
  133. package/backends/codesys/publication.ts +0 -59
  134. package/backends/codesys/storage.ts +0 -70
  135. package/backends/codesys/task-access.ts +0 -293
  136. package/backends/codesys/telemetry.ts +0 -593
  137. package/backends/codesys/types.ts +0 -179
  138. package/backends/codesys/vendor.ts +0 -108
  139. package/ir/aggregates.ts +0 -333
  140. package/ir/allocation.ts +0 -74
  141. package/ir/core-model.ts +0 -129
  142. package/ir/core.ts +0 -64
  143. package/ir/declarations.ts +0 -208
  144. package/ir/diagnostics.ts +0 -43
  145. package/ir/domains.ts +0 -96
  146. package/ir/index.ts +0 -8
  147. package/ir/link.ts +0 -185
  148. package/ir/model.ts +0 -346
  149. package/ir/routine.ts +0 -859
  150. package/ir/scalars.ts +0 -675
  151. package/ir/types.ts +0 -76
  152. package/project/artifacts.ts +0 -277
  153. package/project/cli.ts +0 -395
  154. package/project/index.ts +0 -1
  155. package/project/plant.ts +0 -509
  156. package/project/project.ts +0 -358
  157. package/project/server.ts +0 -113
@@ -0,0 +1,342 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ lstat,
4
+ mkdir,
5
+ readdir,
6
+ readFile,
7
+ rename,
8
+ rm,
9
+ writeFile,
10
+ } from "node:fs/promises";
11
+ import { dirname, join } from "node:path";
12
+ import type { buildCodesys } from "@tsplc/compiler/codesys";
13
+ import { sha256Digest } from "@tsplc/config/build";
14
+ import { z } from "zod";
15
+
16
+ const missing = (cause: unknown): boolean =>
17
+ cause instanceof Error && "code" in cause && cause.code === "ENOENT";
18
+ const digest = (value: string | Uint8Array): string =>
19
+ createHash("sha256").update(value).digest("hex");
20
+
21
+ // Ownership is an explicit boundary: generated files must match their manifest,
22
+ // and engineering trees must belong to this configuration before vendor writes.
23
+ const generatedFileSchema = z.object({
24
+ path: z
25
+ .string()
26
+ .regex(/^[A-Za-z0-9_ .-]+(?:\/[A-Za-z0-9_ .-]+)*$/)
27
+ .refine(
28
+ (path) =>
29
+ !path.split("/").some((part) => part === "." || part === "..") &&
30
+ !["manifest.json", "receipt.json"].includes(path),
31
+ ),
32
+ sha256: sha256Digest,
33
+ });
34
+
35
+ /** The manifest's envelope; its entries are checked one by one to name the failure. */
36
+ const manifestSchema = z.object({
37
+ kind: z.literal("tsplc-artifacts"),
38
+ version: z.literal(1),
39
+ configFile: z.string(),
40
+ files: z.array(z.unknown()),
41
+ });
42
+
43
+ type Manifest = Omit<z.infer<typeof manifestSchema>, "files"> & {
44
+ files: z.infer<typeof generatedFileSchema>[];
45
+ };
46
+
47
+ const buildStatusSchema = z.enum(["emitted", "vendor-compiled"]);
48
+
49
+ const receiptSchema = z.object({
50
+ kind: z.literal("tsplc-build"),
51
+ version: z.literal(1),
52
+ configFile: z.string(),
53
+ status: buildStatusSchema,
54
+ });
55
+
56
+ const engineeringMarkerSchema = z.object({
57
+ kind: z.literal("tsplc-engineering"),
58
+ version: z.literal(1),
59
+ configFile: z.string(),
60
+ });
61
+
62
+ function manifest(value: unknown, configFile: string): Manifest {
63
+ const parsed = manifestSchema.safeParse(value);
64
+ if (!parsed.success || parsed.data.configFile !== configFile) {
65
+ throw new Error(
66
+ "Output directory has no matching tsPLC ownership manifest.",
67
+ );
68
+ }
69
+
70
+ const files = parsed.data.files.map((item) => {
71
+ const file = generatedFileSchema.safeParse(item);
72
+ if (!file.success) {
73
+ throw new Error("Invalid generated file ownership entry.");
74
+ }
75
+ return file.data;
76
+ });
77
+ if (new Set(files.map((item) => item.path)).size !== files.length) {
78
+ throw new Error("Duplicate generated file ownership entry.");
79
+ }
80
+ return { ...parsed.data, files };
81
+ }
82
+
83
+ async function directory(path: string): Promise<boolean> {
84
+ try {
85
+ const entry = await lstat(path);
86
+ if (!entry.isDirectory() || entry.isSymbolicLink()) {
87
+ throw new Error(`Generated directory must be a real directory: ${path}`);
88
+ }
89
+ return true;
90
+ } catch (cause) {
91
+ if (missing(cause)) {
92
+ return false;
93
+ }
94
+ throw cause;
95
+ }
96
+ }
97
+
98
+ async function filesIn(path: string, prefix = ""): Promise<string[]> {
99
+ const result: string[] = [];
100
+ for (const entry of await readdir(path, { withFileTypes: true })) {
101
+ const name = prefix + entry.name;
102
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
103
+ result.push(...(await filesIn(join(path, entry.name), `${name}/`)));
104
+ } else {
105
+ result.push(name);
106
+ }
107
+ }
108
+ return result;
109
+ }
110
+
111
+ export async function engineeringDirectory(
112
+ path: string,
113
+ configFile: string,
114
+ ): Promise<void> {
115
+ const marker = join(path, "ownership.json");
116
+ const exists = await directory(path);
117
+ if (!exists || !(await readdir(path)).length) {
118
+ await mkdir(path, { recursive: true });
119
+ await writeFile(
120
+ marker,
121
+ `${JSON.stringify({ kind: "tsplc-engineering", version: 1, configFile }, null, 2)}\n`,
122
+ { flag: "wx" },
123
+ );
124
+ } else {
125
+ const entry = await lstat(marker).catch((cause: unknown) => {
126
+ if (missing(cause)) {
127
+ throw new Error(
128
+ `Engineering cache has no matching tsPLC ownership marker: ${path}`,
129
+ );
130
+ }
131
+ throw cause;
132
+ });
133
+ if (!entry.isFile() || entry.isSymbolicLink()) {
134
+ throw new Error("Engineering ownership marker must be a real file.");
135
+ }
136
+ const value = engineeringMarkerSchema.safeParse(
137
+ JSON.parse(await readFile(marker, "utf8")),
138
+ );
139
+ if (!value.success || value.data.configFile !== configFile) {
140
+ throw new Error(
141
+ `Engineering cache has no matching tsPLC ownership marker: ${path}`,
142
+ );
143
+ }
144
+ }
145
+
146
+ const inspect = async (directory: string): Promise<void> => {
147
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
148
+ const child = join(directory, entry.name);
149
+ if (entry.isSymbolicLink()) {
150
+ throw new Error(
151
+ `Engineering cache must not contain symlinks: ${child}`,
152
+ );
153
+ }
154
+ if (entry.isDirectory()) {
155
+ await inspect(child);
156
+ }
157
+ }
158
+ };
159
+ await inspect(path);
160
+ }
161
+
162
+ export async function owned(
163
+ configFile: string,
164
+ withdrawReceipt = false,
165
+ ): Promise<{
166
+ root: string;
167
+ output: string;
168
+ ownership?: Manifest;
169
+ unknown: string[];
170
+ }> {
171
+ const root = join(dirname(configFile), ".tsplc");
172
+ const output = join(root, "artifacts");
173
+ if (!(await directory(root)) || !(await directory(output))) {
174
+ return { root, output, unknown: [] };
175
+ }
176
+
177
+ const manifestPath = join(output, "manifest.json");
178
+ const manifestEntry = await lstat(manifestPath);
179
+ if (!manifestEntry.isFile() || manifestEntry.isSymbolicLink()) {
180
+ throw new Error("Ownership manifest must be a real file.");
181
+ }
182
+ const ownership = manifest(
183
+ JSON.parse(await readFile(manifestPath, "utf8")),
184
+ configFile,
185
+ );
186
+ const receipt = join(output, "receipt.json");
187
+ try {
188
+ const entry = await lstat(receipt);
189
+ if (!entry.isFile() || entry.isSymbolicLink()) {
190
+ throw new Error("Build receipt must be a real file.");
191
+ }
192
+ const value = receiptSchema.safeParse(
193
+ JSON.parse(await readFile(receipt, "utf8")),
194
+ );
195
+ if (!value.success || value.data.configFile !== configFile) {
196
+ throw new Error("Build receipt is not owned by this configuration.");
197
+ }
198
+ if (withdrawReceipt) {
199
+ await rm(receipt);
200
+ }
201
+ } catch (cause) {
202
+ if (!missing(cause)) {
203
+ throw cause;
204
+ }
205
+ }
206
+
207
+ const names = new Set([
208
+ ...ownership.files.map((file) => file.path),
209
+ "manifest.json",
210
+ "receipt.json",
211
+ ]);
212
+ for (const file of ownership.files) {
213
+ let parent = output;
214
+ for (const part of file.path.split("/").slice(0, -1)) {
215
+ parent = join(parent, part);
216
+ if (!(await directory(parent))) {
217
+ throw new Error(`Missing generated directory: ${parent}`);
218
+ }
219
+ }
220
+ const path = join(output, file.path);
221
+ const entry = await lstat(path);
222
+ if (
223
+ !entry.isFile() ||
224
+ entry.isSymbolicLink() ||
225
+ digest(await readFile(path)) !== file.sha256
226
+ ) {
227
+ throw new Error(
228
+ `Generated file was replaced or edited; preserve it before rebuilding/cleaning: ${path}`,
229
+ );
230
+ }
231
+ }
232
+ return {
233
+ root,
234
+ output,
235
+ ownership,
236
+ unknown: (await filesIn(output)).filter((name) => !names.has(name)),
237
+ };
238
+ }
239
+
240
+ interface Receipt {
241
+ configFile: string;
242
+ status: z.infer<typeof buildStatusSchema>;
243
+ vendor?: Pick<
244
+ Awaited<ReturnType<typeof buildCodesys>>,
245
+ "application" | "tasks"
246
+ >;
247
+ }
248
+
249
+ // Compile in a separate staging tree. Recheck ownership immediately before the
250
+ // swap, because the vendor build may have given the user time to edit old files.
251
+ export async function publishArtifacts(
252
+ staging: string,
253
+ previous: Awaited<ReturnType<typeof owned>>,
254
+ receipt: Receipt,
255
+ ): Promise<void> {
256
+ const configFile = receipt.configFile;
257
+ const generated = (await filesIn(staging)).sort();
258
+ const ownership: Manifest = {
259
+ kind: "tsplc-artifacts",
260
+ version: 1,
261
+ configFile,
262
+ files: [],
263
+ };
264
+ for (const path of generated) {
265
+ ownership.files.push({
266
+ path,
267
+ sha256: digest(await readFile(join(staging, path))),
268
+ });
269
+ }
270
+ await writeFile(
271
+ join(staging, "manifest.json"),
272
+ `${JSON.stringify(ownership, null, 2)}\n`,
273
+ );
274
+ await writeFile(
275
+ join(staging, "receipt.json"),
276
+ `${JSON.stringify(
277
+ {
278
+ kind: "tsplc-build",
279
+ version: 1,
280
+ generatedAt: new Date().toISOString(),
281
+ ...receipt,
282
+ },
283
+ null,
284
+ 2,
285
+ )}\n`,
286
+ );
287
+
288
+ const current = await owned(configFile);
289
+ if (
290
+ JSON.stringify(current.ownership) !== JSON.stringify(previous.ownership)
291
+ ) {
292
+ throw new Error(
293
+ "Output ownership changed during the build; preserve it before rebuilding.",
294
+ );
295
+ }
296
+ if (current.unknown.length) {
297
+ throw new Error(
298
+ `Output contains unrelated files: ${current.unknown.join(", ")}`,
299
+ );
300
+ }
301
+
302
+ const backup = `${staging}-previous`;
303
+ if (previous.ownership) {
304
+ await rename(previous.output, backup);
305
+ }
306
+ try {
307
+ await rename(staging, previous.output);
308
+ } catch (cause) {
309
+ if (previous.ownership) {
310
+ await rename(backup, previous.output);
311
+ }
312
+ throw cause;
313
+ }
314
+ if (previous.ownership) {
315
+ await rm(backup, { recursive: true });
316
+ }
317
+ }
318
+
319
+ export async function cleanArtifacts(configFile: string): Promise<void> {
320
+ const generated = await owned(configFile);
321
+ if (!generated.ownership) {
322
+ return;
323
+ }
324
+ for (const entry of generated.ownership.files) {
325
+ await rm(join(generated.output, entry.path));
326
+ }
327
+ await rm(join(generated.output, "receipt.json"), { force: true });
328
+ await rm(join(generated.output, "manifest.json"));
329
+
330
+ // Remove empty generated directories while preserving unrelated files.
331
+ const removeEmpty = async (path: string): Promise<void> => {
332
+ for (const entry of await readdir(path, { withFileTypes: true })) {
333
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
334
+ await removeEmpty(join(path, entry.name));
335
+ }
336
+ }
337
+ if (!(await readdir(path)).length) {
338
+ await rm(path, { recursive: true });
339
+ }
340
+ };
341
+ await removeEmpty(generated.output);
342
+ }
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env bun
2
+ import { parseArgs } from "node:util";
3
+ import { loadTsplcConfig } from "@tsplc/config";
4
+ import { formatDiagnostic, hasErrors } from "@tsplc/compiler/ir";
5
+ import { serveProjectDebugger } from "./debugger.ts";
6
+ import { connect, plantCommand, runPlantCommand } from "./plant.ts";
7
+ import {
8
+ type CommandResult,
9
+ DiagnosticFailure,
10
+ checkProjectFlags,
11
+ projectCommand,
12
+ runProjectCommand,
13
+ } from "./project-commands.ts";
14
+
15
+ const usage = `tsplc install|typegen|check|build|run|download|online-change|inspect|clean|configure [--config tsplc.config.ts] [--target name] [--plc|--server] [--simulate] [--runtime] [--emit-only] [--format json] [--read symbol]
16
+
17
+ Plant agent (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN):
18
+ tsplc deploy [--target name] [--download] [--select] [--initialize-user] [--simulate]
19
+ tsplc target | status | login | logout
20
+ tsplc vars [path] | read <expression>... | write <expression> <value>
21
+ tsplc force <expression> <value> | unforce [expression]... [--restore]
22
+ tsplc start | stop | reset warm|cold (-y skips confirmations)
23
+
24
+ Debugger, on http://127.0.0.1, for the built .tsplc/artifacts/st/debug.json; it reads through
25
+ the plant agent's login (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN), or --opcua at config monitor:
26
+ tsplc debug [--target name] [--port 4870] [--server-url url] [--opcua]`;
27
+
28
+ async function main() {
29
+ const { values, positionals } = parseArgs({
30
+ allowPositionals: true,
31
+ options: {
32
+ config: { type: "string" },
33
+ target: { type: "string" },
34
+ help: { type: "boolean", short: "h" },
35
+ "emit-only": { type: "boolean" },
36
+ format: { type: "string" },
37
+ read: { type: "string", multiple: true },
38
+ "initialize-user": { type: "boolean" },
39
+ "frozen-lockfile": { type: "boolean" },
40
+ check: { type: "boolean" },
41
+ plc: { type: "boolean" },
42
+ server: { type: "boolean" },
43
+ simulate: { type: "boolean" },
44
+ runtime: { type: "boolean" },
45
+ download: { type: "boolean" },
46
+ restore: { type: "boolean" },
47
+ select: { type: "boolean" },
48
+ yes: { type: "boolean", short: "y" },
49
+ port: { type: "string" },
50
+ "server-url": { type: "string" },
51
+ opcua: { type: "boolean" },
52
+ },
53
+ });
54
+ const [name, ...args] = positionals;
55
+ const file = values.config ?? "tsplc.config.ts";
56
+ if (!name || values.help) {
57
+ console.log(usage);
58
+ return 0;
59
+ }
60
+ if (name === "debug") {
61
+ if (args.length) {
62
+ throw new Error(
63
+ "Usage: tsplc debug [--target name] [--port 4870] [--server-url url] [--opcua]",
64
+ );
65
+ }
66
+ await serveProjectDebugger(
67
+ await loadTsplcConfig(file, {
68
+ env: process.env,
69
+ target: values.target,
70
+ forAgent: false,
71
+ }),
72
+ values,
73
+ );
74
+ return 0;
75
+ }
76
+ const plant = plantCommand(name);
77
+ if (plant) {
78
+ const failed = await runPlantCommand(
79
+ connect(process.env),
80
+ plant,
81
+ args,
82
+ values,
83
+ {
84
+ file,
85
+ load: () =>
86
+ loadTsplcConfig(file, {
87
+ env: process.env,
88
+ target: values.target,
89
+ forAgent: true,
90
+ }),
91
+ },
92
+ process.env,
93
+ );
94
+ return failed ? report(failed, values.format) : 0;
95
+ }
96
+ if (args.length) {
97
+ throw new Error("Specify one command.");
98
+ }
99
+ const command = projectCommand(name);
100
+ if (!command) {
101
+ throw new Error(`Unknown command ${name}.`);
102
+ }
103
+ checkProjectFlags(command, values);
104
+ const result = await withProgressOnStderr(values.format === "json", () =>
105
+ runProjectCommand(command, file, values, process.env),
106
+ );
107
+ return report(result, values.format);
108
+ }
109
+
110
+ /**
111
+ * Sends progress to stderr while `run` runs, so stdout holds only the JSON result. Docker
112
+ * commands that `@tsplc/build` runs follow `TSPLC_LOG_STDERR`.
113
+ */
114
+ async function withProgressOnStderr<T>(
115
+ enabled: boolean,
116
+ run: () => Promise<T>,
117
+ ) {
118
+ if (!enabled) {
119
+ return run();
120
+ }
121
+ const log = console.log;
122
+ const previousLogTarget = process.env["TSPLC_LOG_STDERR"];
123
+ console.log = console.error;
124
+ process.env["TSPLC_LOG_STDERR"] = "1";
125
+ try {
126
+ return await run();
127
+ } finally {
128
+ console.log = log;
129
+ if (previousLogTarget === undefined) {
130
+ delete process.env["TSPLC_LOG_STDERR"];
131
+ } else {
132
+ process.env["TSPLC_LOG_STDERR"] = previousLogTarget;
133
+ }
134
+ }
135
+ }
136
+
137
+ function report(result: CommandResult, format: string | undefined) {
138
+ const diagnostics = result.diagnostics ?? [];
139
+ const ok = !hasErrors(diagnostics);
140
+ if (format === "json") {
141
+ console.log(JSON.stringify({ ok, ...result }));
142
+ } else {
143
+ for (const diagnostic of diagnostics) {
144
+ console.error(formatDiagnostic(diagnostic));
145
+ }
146
+ if (ok) {
147
+ console.log("tsPLC completed.");
148
+ }
149
+ }
150
+ return ok ? 0 : 1;
151
+ }
152
+
153
+ try {
154
+ process.exitCode = await main();
155
+ } catch (cause) {
156
+ // main() may fail before its options parse, so detect JSON output from raw argv.
157
+ const json =
158
+ process.argv.includes("json") || process.argv.includes("--format=json");
159
+ if (cause instanceof DiagnosticFailure) {
160
+ process.exitCode = report(cause.result, json ? "json" : undefined);
161
+ } else {
162
+ const message = cause instanceof Error ? cause.message : String(cause);
163
+ if (json) {
164
+ console.log(
165
+ JSON.stringify({
166
+ ok: false,
167
+ diagnostics: [
168
+ { origin: "config", code: "PLC5003", severity: "error", message },
169
+ ],
170
+ }),
171
+ );
172
+ } else {
173
+ console.error(message);
174
+ }
175
+ process.exitCode = 1;
176
+ }
177
+ }
@@ -0,0 +1,82 @@
1
+ import { existsSync } from "node:fs";
2
+ import { relative, resolve } from "node:path";
3
+ import { serverTokenEnv, type loadTsplcConfig } from "@tsplc/config";
4
+ import {
5
+ createDebugger,
6
+ createLoginAdapter,
7
+ createOpcUaAdapter,
8
+ loadManifest,
9
+ opcUaConnection,
10
+ serveDebugger,
11
+ } from "@tsplc/debug";
12
+ import { connect, readThroughAgent } from "./plant.ts";
13
+
14
+ /**
15
+ * Serves the debugger for the project's last build until interrupted. It reads the controller
16
+ * through the plant agent's login, or with `--opcua` at the config's `monitor` endpoint, and
17
+ * follows the server's telemetry and requests when the server's base URL (`--server-url`, or
18
+ * `server.baseUrlEnv`) and the PLC's bearer token are in the config's environment.
19
+ */
20
+ export async function serveProjectDebugger(
21
+ { config, root, env }: Awaited<ReturnType<typeof loadTsplcConfig>>,
22
+ flags: { port?: string; "server-url"?: string; opcua?: boolean },
23
+ ) {
24
+ if (flags.opcua && !config.monitor) {
25
+ throw new Error(
26
+ "Configure monitor with the controller's OPC UA endpoint to use --opcua.",
27
+ );
28
+ }
29
+ const agentUrl = env["TSPLC_AGENT_URL"];
30
+ if (!flags.opcua && !(agentUrl && env["TSPLC_AGENT_TOKEN"])) {
31
+ throw new Error(
32
+ "Set TSPLC_AGENT_URL and TSPLC_AGENT_TOKEN to read through the plant agent's login, or pass --opcua for a local virtual PLC.",
33
+ );
34
+ }
35
+ const file = resolve(root, ".tsplc/artifacts/st/debug.json");
36
+ if (!existsSync(file)) {
37
+ throw new Error(
38
+ `No debug manifest at ${relative(process.cwd(), file)}: build with debug configured.`,
39
+ );
40
+ }
41
+ const port = Number(flags.port ?? 4870);
42
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
43
+ throw new Error("--port must be a TCP port.");
44
+ }
45
+ const manifest = await loadManifest(file);
46
+ const serverUrl =
47
+ flags["server-url"] ??
48
+ (config.server?.baseUrlEnv && env[config.server.baseUrlEnv]);
49
+ const tokenEnv = serverTokenEnv(config);
50
+ const token = tokenEnv && env[tokenEnv];
51
+ const log = (message: string) =>
52
+ console.log(`${new Date().toISOString()} ${message}`);
53
+ const debug = await createDebugger({
54
+ manifest,
55
+ adapter:
56
+ flags.opcua && config.monitor
57
+ ? createOpcUaAdapter(opcUaConnection(config.monitor, { root, env }))
58
+ : createLoginAdapter({
59
+ read: readThroughAgent(connect(env)),
60
+ probe: manifest.build.target,
61
+ endpoint: `the plant agent at ${agentUrl}`,
62
+ }),
63
+ stateDirectory: resolve(root, ".tsplc/debug"),
64
+ watch: config.debug?.watch ?? {},
65
+ ...(serverUrl && token && { server: { url: serverUrl, token } }),
66
+ projectRoot: root,
67
+ log,
68
+ });
69
+ const server = serveDebugger(debug, { port, log });
70
+ console.log(`tsPLC debugger at ${server.url}`);
71
+ if (!serverUrl || !token) {
72
+ console.log(
73
+ "Not following the server's telemetry and requests: set server.baseUrlEnv or --server-url, and the server's bearer token variable.",
74
+ );
75
+ }
76
+ await new Promise((stopped) => {
77
+ process.once("SIGINT", stopped);
78
+ process.once("SIGTERM", stopped);
79
+ });
80
+ await server.stop(true);
81
+ await debug.close();
82
+ }
@@ -0,0 +1,6 @@
1
+ export {
2
+ checkProject,
3
+ buildProject,
4
+ cleanProject,
5
+ projectTargets,
6
+ } from "./project.ts";