@tsplc/build 0.5.7 → 0.5.9

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.
package/docker/Dockerfile CHANGED
@@ -188,6 +188,9 @@ COPY docker/entrypoint.sh docker/runner.ts docker/config.ts ./docker/
188
188
  RUN chmod +x docker/entrypoint.sh
189
189
  ENV WINEPREFIX=/tmp/codesys-wine HOME=/tmp/codesys-home WINEARCH=win64 \
190
190
  WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--disable-gpu
191
+ # The CODESYS engineering this image installs, which a controller baseline is matched on.
192
+ ARG TSPLC_ENGINEERING=
193
+ ENV TSPLC_ENGINEERING=${TSPLC_ENGINEERING}
191
194
  WORKDIR /workspace
192
195
  ENTRYPOINT ["/opt/codesys-build/docker/entrypoint.sh"]
193
196
  CMD ["--help"]
package/docker/runner.ts CHANGED
@@ -3,7 +3,7 @@ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
3
3
  import { resolve } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
5
  import { parseArgs } from "node:util";
6
- import { tcpPort } from "@tsplc/config/build";
6
+ import { sha256Digest, tcpPort } from "@tsplc/config/build";
7
7
  import { z } from "zod";
8
8
  import { buildFiles, publishBuild } from "../src/artifacts";
9
9
  import { buildInContainer } from "../src/build";
@@ -119,9 +119,15 @@ if (!values.job) {
119
119
  process.exit(code);
120
120
  }
121
121
 
122
+ // The image's build records the CODESYS engineering it installs; older images record none.
123
+ const engineering =
124
+ sha256Digest.or(z.literal("")).parse(process.env.TSPLC_ENGINEERING ?? "") ||
125
+ null;
126
+
122
127
  if (operation === "login") {
123
128
  await serveControllerLogin(config, {
124
129
  imageId: imageIdSchema.parse(values["image-id"]),
130
+ engineering,
125
131
  port: portSchema.parse(values.port),
126
132
  });
127
133
  process.exit(0);
@@ -130,6 +136,7 @@ if (operation === "login") {
130
136
  if (operation === "warm") {
131
137
  await serveWarmController(config, {
132
138
  imageId: imageIdSchema.parse(values["image-id"]),
139
+ engineering,
133
140
  port: portSchema.parse(values.port),
134
141
  loadConfig: async (path) =>
135
142
  resolveContainerConfig(JSON.parse(await readFile(path, "utf8")), path),
@@ -145,6 +152,7 @@ if (operation !== "build") {
145
152
  .parse(JSON.parse(values.read ?? "[]"));
146
153
  await runControllerSession(config, operation, {
147
154
  imageId,
155
+ engineering,
148
156
  operationId,
149
157
  scratch: containerScratch,
150
158
  read,
package/package.json CHANGED
@@ -15,7 +15,7 @@
15
15
  "url": "git+https://github.com/rip-technologies/tsplc.git",
16
16
  "directory": "packages/build"
17
17
  },
18
- "version": "0.5.7",
18
+ "version": "0.5.9",
19
19
  "type": "module",
20
20
  "exports": {
21
21
  ".": {
@@ -54,9 +54,9 @@
54
54
  },
55
55
  "dependencies": {
56
56
  "zod": "4.3.6",
57
- "@tsplc/config": "0.5.7",
58
- "@tsplc/typegen": "0.5.7",
59
- "@tsplc/iec": "0.5.7"
57
+ "@tsplc/config": "0.5.9",
58
+ "@tsplc/typegen": "0.5.9",
59
+ "@tsplc/iec": "0.5.9"
60
60
  },
61
61
  "bin": {
62
62
  "tsplc-build": "./dist/cli.js"
@@ -5,7 +5,7 @@ import io
5
5
  import json
6
6
  import os
7
7
  import re
8
- from build import (CompilerError, clear_diagnostics, fail_on_errors, import_source, keep_device_tree,
8
+ from build import (CompilerError, clear_diagnostics, import_source, keep_device_tree,
9
9
  open_template, reported_errors, write_progress)
10
10
  from hardware import update_device_tree, verify_pinned
11
11
  from System import Activator, AppDomain, Array, Enum, Environment, Object
@@ -42,6 +42,32 @@ def download_required(message):
42
42
  return error
43
43
 
44
44
 
45
+ CANNOT_APPLY = 'CODESYS cannot apply this source as an online change; use an explicit download'
46
+
47
+
48
+ def refusal_with_reasons(diagnostics):
49
+ return download_required('\n'.join([CANNOT_APPLY + ':'] + [item['text'] for item in diagnostics]))
50
+
51
+
52
+ def fail_on_online_change_errors(engine):
53
+ """CODESYS reports its advice that no online change is possible as an error of the incremental
54
+ build. That advice is a refusal only a full download resolves, and it says why; any other error
55
+ is the source's, and still fails the operation."""
56
+ errors = reported_errors(engine)
57
+ others = [error for error in errors if not error['text'].startswith(NO_ONLINE_CHANGE)]
58
+ if others:
59
+ raise CompilerError(others)
60
+ if errors:
61
+ raise refusal_with_reasons(errors)
62
+
63
+
64
+ def fail_on_online_code_errors(engine):
65
+ """The source built, so what generating its online-change code reports is about the change."""
66
+ errors = reported_errors(engine)
67
+ if errors:
68
+ raise refusal_with_reasons(errors)
69
+
70
+
45
71
  def core_application(online_application):
46
72
  # The shipped scripting wrapper omits Keep from its login switch. Its core
47
73
  # application provides a session-only login, which never compiles/downloads.
@@ -239,7 +265,7 @@ def generate_online_code(application):
239
265
  prop = environment.GetProperty('LanguageModelMgr', BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
240
266
  manager = prop.GetValue(None, None)
241
267
  if not manager.GenerateCode(application.guid, True, False):
242
- raise RuntimeError('CODESYS cannot generate an online change for this source')
268
+ raise download_required('CODESYS cannot generate an online change for this source; use an explicit download')
243
269
 
244
270
 
245
271
  def consolidated_manager():
@@ -484,6 +510,8 @@ def run_online(engine, request, log, prepared=None, keep=None):
484
510
  online_app = engine.online.create_online_application(application)
485
511
  core = core_application(online_app)
486
512
  if not previous or str(application.guid) != previous['applicationGuid']:
513
+ if request['operation'] == 'online-change':
514
+ raise download_required('Online change requires the saved downloaded application; use an explicit download')
487
515
  raise RuntimeError('Online change requires the saved downloaded application')
488
516
  progress('Checking downloaded controller identity and state')
489
517
  session_login(core)
@@ -528,7 +556,7 @@ def run_online(engine, request, log, prepared=None, keep=None):
528
556
  # whether a source edit can be applied as an online change.
529
557
  progress('Building application incrementally for online change')
530
558
  application.build()
531
- fail_on_errors(engine)
559
+ fail_on_online_change_errors(engine)
532
560
  if request['operation'] == 'download':
533
561
  online_app = engine.online.create_online_application(application)
534
562
  core = core_application(online_app)
@@ -551,10 +579,11 @@ def run_online(engine, request, log, prepared=None, keep=None):
551
579
  expected = controller_ids(core)
552
580
  if not application.is_uptodate:
553
581
  if not application.is_online_change_possible:
554
- raise download_required('CODESYS cannot apply this source as an online change; use an explicit download')
582
+ raise download_required(CANNOT_APPLY + '. CODESYS gave no reason; the usual causes are a '
583
+ 'changed task configuration, a variable whose type changed, or a changed device.')
555
584
  progress('Generating online-change code')
556
585
  generate_online_code(application)
557
- fail_on_errors(engine)
586
+ fail_on_online_code_errors(engine)
558
587
  expected = context_ids(consolidated_manager().GetCompileContext(application.guid))
559
588
  mode = loaded_type('_3S.CoDeSys.Core.Online.BootProjectTransferMode')
560
589
  enter_phase(request, u'transfer')
@@ -109,6 +109,7 @@ const checkReceipt = (
109
109
  if (
110
110
  result.operationId !== expected.operationId ||
111
111
  result.operation !== expected.operation ||
112
+ result.imageId !== expected.imageId ||
112
113
  !sameBaseline(result, expected)
113
114
  ) {
114
115
  throw new Error(
@@ -19,6 +19,8 @@ export const controllerResultSchema = z.strictObject({
19
19
  operationId: z.uuid(),
20
20
  operation: z.enum(["download", "online-change", "inspect"]),
21
21
  imageId: imageIdSchema,
22
+ /** The builder image's CODESYS engineering, when the image records it. */
23
+ engineering: sha256Digest.optional(),
22
24
  templateHash: sha256Digest,
23
25
  target: z.strictObject({
24
26
  network: z.string().nonempty(),
@@ -94,12 +96,21 @@ export const controllerTarget = (
94
96
 
95
97
  export type Baseline = Pick<
96
98
  ControllerResult,
97
- "imageId" | "templateHash" | "target"
99
+ "imageId" | "engineering" | "templateHash" | "target"
98
100
  >;
99
101
 
100
- /** Whether two controller states share an image, template and target, so one can follow the other. */
102
+ /**
103
+ * Whether two controller states were made by builders that compile alike: images with the same
104
+ * CODESYS engineering, or the same image when either doesn't record its engineering.
105
+ */
106
+ const sameBuilder = (state: Baseline, expected: Baseline) =>
107
+ state.engineering && expected.engineering
108
+ ? state.engineering === expected.engineering
109
+ : state.imageId === expected.imageId;
110
+
111
+ /** Whether two controller states share a builder, template and target, so one can follow the other. */
101
112
  export const sameBaseline = (state: Baseline, expected: Baseline) =>
102
- state.imageId === expected.imageId &&
113
+ sameBuilder(state, expected) &&
103
114
  state.templateHash === expected.templateHash &&
104
115
  JSON.stringify(state.target) === JSON.stringify(expected.target);
105
116
 
@@ -4,6 +4,7 @@ import { cp, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { resolve } from "node:path";
5
5
  import {
6
6
  controllerBudgets,
7
+ cyclicTasksSchema,
7
8
  type ResolvedConfig,
8
9
  sha256Digest,
9
10
  } from "@tsplc/config/build";
@@ -26,6 +27,7 @@ import {
26
27
  } from "./controller-protocol";
27
28
  import { deviceTreeSettings, writeDeviceTree } from "./device-tree";
28
29
  import {
30
+ CodesysExitedError,
29
31
  createCodesysWorker,
30
32
  type PhasedBudget,
31
33
  withWorkerLock,
@@ -35,6 +37,12 @@ import {
35
37
  } from "./host/codesys-worker";
36
38
  import { toWindowsPath } from "./host/windows-path";
37
39
  import { importRequest } from "./import-request";
40
+ import {
41
+ type CommittedObject,
42
+ committedObjectSchema,
43
+ describeFinding,
44
+ onlineChangeFindings,
45
+ } from "./online-change-check";
38
46
  import { loadSources } from "./sources";
39
47
 
40
48
  // Vendor code/data IDs are .NET Guid values derived from the compiler's data;
@@ -47,7 +55,9 @@ const pointerSchema = z.strictObject({
47
55
  generation: z.uuid(),
48
56
  });
49
57
  const baselineSchema = controllerResultSchema.extend({
50
- objects: z.array(z.record(z.string(), z.unknown())),
58
+ objects: z.array(committedObjectSchema),
59
+ // The task plan the download configured, which an online change can't change.
60
+ tasks: cyclicTasksSchema.optional(),
51
61
  files: z.record(z.string(), sha256Digest),
52
62
  // The device tree's adapter settings the download wrote, which an online change can't change.
53
63
  deviceSettings: sha256Digest.optional(),
@@ -165,7 +175,7 @@ const committedBaseline = async (
165
175
  root: string,
166
176
  expected: Pick<
167
177
  z.infer<typeof baselineSchema>,
168
- "imageId" | "templateHash" | "target"
178
+ "imageId" | "engineering" | "templateHash" | "target"
169
179
  >,
170
180
  ) => {
171
181
  const committed = await readCommitted(root);
@@ -194,6 +204,42 @@ const copyCommitted = async (committed: Committed, destination: string) => {
194
204
  }
195
205
  };
196
206
 
207
+ /**
208
+ * CODESYS crashes generating an online change that moves a block holding a network client, such as
209
+ * a job with a service call. The controller keeps its running program, and a download resolves it.
210
+ */
211
+ const crashedOnlineChange = (cause: unknown) =>
212
+ new DownloadRequiredError(
213
+ `CODESYS crashed on this online change, as it does when one moves a block that holds a network client; ${explicitDownload}`,
214
+ { cause },
215
+ );
216
+
217
+ /**
218
+ * Refuses, before CODESYS runs, an online change CODESYS would refuse or apply wrongly, naming
219
+ * the variable or task that causes it; reports the state the change restarts.
220
+ */
221
+ const checkOnlineChange = (
222
+ baseline: z.infer<typeof baselineSchema>,
223
+ objects: readonly CommittedObject[],
224
+ config: Pick<ResolvedConfig, "tasks">,
225
+ progress: (message: string) => void,
226
+ ) => {
227
+ const findings = onlineChangeFindings({
228
+ before: baseline.objects,
229
+ after: objects,
230
+ tasks: { before: baseline.tasks ?? null, after: config.tasks ?? null },
231
+ });
232
+ const refusals = findings.filter((finding) => finding.refuses);
233
+ if (refusals.length) {
234
+ throw new DownloadRequiredError(
235
+ `This change can't be applied as an online change; ${explicitDownload}:\n${refusals.map(describeFinding).join("\n")}`,
236
+ );
237
+ }
238
+ for (const finding of findings) {
239
+ progress(`Online change: ${describeFinding(finding)}`);
240
+ }
241
+ };
242
+
197
243
  /** A CODESYS worker that handles the `online` request written to `requestDirectory` when `run`. */
198
244
  interface OnlineWorker {
199
245
  requestDirectory: string;
@@ -230,6 +276,8 @@ const restoreResultSchema = z.object({
230
276
 
231
277
  interface SessionOptions {
232
278
  imageId: string;
279
+ /** The image's CODESYS engineering, or null for an image that doesn't record it. */
280
+ engineering: string | null;
233
281
  operationId: string;
234
282
  scratch: string;
235
283
  initializeUser?: boolean;
@@ -283,7 +331,12 @@ const controllerSession = async (
283
331
  const templateHash = sha256(await readFile(config.template));
284
332
  // A different image, template, controller or device tree structure needs a fresh download from the template.
285
333
  const target = controllerTarget(config, settings);
286
- const expected = { imageId: options.imageId, templateHash, target };
334
+ const expected = {
335
+ imageId: options.imageId,
336
+ engineering: options.engineering ?? undefined,
337
+ templateHash,
338
+ target,
339
+ };
287
340
  const jobConfig = {
288
341
  ...config,
289
342
  outDir: jobOutput(config.outDir, options.operationId),
@@ -502,6 +555,7 @@ const controllerSession = async (
502
555
  await writeJson(resolve(committedDirectory, "manifest.json"), {
503
556
  ...receipt,
504
557
  objects,
558
+ ...(config.tasks && { tasks: config.tasks }),
505
559
  files,
506
560
  deviceSettings,
507
561
  });
@@ -552,6 +606,9 @@ const controllerSession = async (
552
606
  const baseline = previous?.baseline;
553
607
  progress("Loading the program's sources");
554
608
  const sources = operation === "inspect" ? null : await loadSources(config);
609
+ if (operation === "online-change" && baseline && sources) {
610
+ checkOnlineChange(baseline, sources.objects, config, progress);
611
+ }
555
612
  const request = {
556
613
  libraryReferences: config.libraryReferences,
557
614
  // Only a download without a baseline starts from the template; the others keep the downloaded project's tree.
@@ -587,6 +644,12 @@ const controllerSession = async (
587
644
  })
588
645
  .parse(
589
646
  await runConnected(request).catch(async (failure: unknown) => {
647
+ if (
648
+ operation === "online-change" &&
649
+ failure instanceof CodesysExitedError
650
+ ) {
651
+ throw crashedOnlineChange(failure);
652
+ }
590
653
  if (
591
654
  operation !== "download" ||
592
655
  (await workerPhase(phase)) !== "transfer"
@@ -603,6 +666,7 @@ const controllerSession = async (
603
666
  operationId: options.operationId,
604
667
  operation,
605
668
  imageId: options.imageId,
669
+ engineering: options.engineering ?? undefined,
606
670
  templateHash,
607
671
  target,
608
672
  generation: operation === "inspect" ? baseline?.generation : generation,
@@ -631,7 +695,7 @@ const controllerSession = async (
631
695
  */
632
696
  export const serveControllerLogin = async (
633
697
  config: ResolvedConfig,
634
- options: { imageId: string; port: number },
698
+ options: { imageId: string; engineering: string | null; port: number },
635
699
  ) => {
636
700
  if (!config.online) {
637
701
  throw new Error("Controller logins require online settings");
@@ -639,6 +703,7 @@ export const serveControllerLogin = async (
639
703
  const root = controllerDirectory(config.outDir);
640
704
  const committed = await committedBaseline(root, {
641
705
  imageId: options.imageId,
706
+ engineering: options.engineering ?? undefined,
642
707
  templateHash: sha256(await readFile(config.template)),
643
708
  target: controllerTarget(config, config.online),
644
709
  });
@@ -774,6 +839,7 @@ export const serveWarmController = async (
774
839
  config: ResolvedConfig,
775
840
  options: {
776
841
  imageId: string;
842
+ engineering: string | null;
777
843
  port: number;
778
844
  loadConfig: (path: string) => Promise<ResolvedConfig>;
779
845
  },
@@ -844,6 +910,7 @@ export const serveWarmController = async (
844
910
  body.operation,
845
911
  {
846
912
  imageId: options.imageId,
913
+ engineering: options.engineering,
847
914
  operationId: body.operationId,
848
915
  scratch: containerScratch,
849
916
  initializeUser: body.initializeUser,
@@ -852,18 +919,14 @@ export const serveWarmController = async (
852
919
  },
853
920
  online,
854
921
  ).catch((error: unknown) => {
855
- // CODESYS crashes generating an online change that moves a block holding a network
856
- // client, such as a job with a service call. The controller keeps its running program.
922
+ // A worker that died on an online change crashed generating it.
857
923
  if (
858
924
  body.operation !== "online-change" ||
859
925
  worker.alive(session.current)
860
926
  ) {
861
927
  throw error;
862
928
  }
863
- throw new DownloadRequiredError(
864
- `CODESYS crashed on this online change, as it does when one moves a block that holds a network client; ${explicitDownload}`,
865
- { cause: error },
866
- );
929
+ throw crashedOnlineChange(error);
867
930
  });
868
931
  return {
869
932
  reply: Response.json({ ok: true, result: reported.receipt }),
@@ -104,7 +104,7 @@ const listFiles = async (
104
104
 
105
105
  /** A digest of named texts and files, which changes when a name or a file's content does. */
106
106
  const digestFiles = async (
107
- files: { name: string; path: string }[],
107
+ files: { name: string; read: () => Promise<Uint8Array | string> }[],
108
108
  texts: Record<string, string>,
109
109
  ) => {
110
110
  const hash = createHash("sha256");
@@ -113,7 +113,7 @@ const digestFiles = async (
113
113
  }
114
114
  for (const file of [...files].sort((a, b) => a.name.localeCompare(b.name))) {
115
115
  hash.update(`${file.name}\0`);
116
- hash.update(await readFile(file.path));
116
+ hash.update(await file.read());
117
117
  hash.update("\0");
118
118
  }
119
119
  return hash.digest("hex");
@@ -134,7 +134,7 @@ export const containerCodeDigest = async () =>
134
134
  )
135
135
  ).map((name) => ({
136
136
  name: posix.join(posix.dirname(target), name),
137
- path: resolve(dirname(source), name),
137
+ read: () => readFile(resolve(dirname(source), name)),
138
138
  })),
139
139
  ),
140
140
  )
@@ -214,11 +214,38 @@ export const builderRecipe = async () =>
214
214
  digestFiles(
215
215
  (await recipeFiles()).map((name) => ({
216
216
  name,
217
- path: resolve(packageDirectory, name),
217
+ read: () => readFile(resolve(packageDirectory, name)),
218
218
  })),
219
219
  { manifest: JSON.stringify(await containerManifest()) },
220
220
  );
221
221
 
222
+ /** The Dockerfile's lines that install Bun, which runs tsPLC's own code and compiles nothing. */
223
+ const toolingLine = /\bbun\b/i;
224
+
225
+ /**
226
+ * The CODESYS engineering the builder image installs: its recipe without Bun and the third-party
227
+ * packages tsPLC's code runs on. Images with the same engineering compile a project alike, so an
228
+ * online change can follow a download made with another of them.
229
+ */
230
+ export const engineeringRecipe = async () =>
231
+ digestFiles(
232
+ (await recipeFiles()).map((name) => ({
233
+ name,
234
+ read: async () => {
235
+ const content = await readFile(resolve(packageDirectory, name));
236
+ if (name !== "docker/Dockerfile") {
237
+ return content;
238
+ }
239
+ return content
240
+ .toString("utf8")
241
+ .split("\n")
242
+ .filter((line) => !toolingLine.test(line))
243
+ .join("\n");
244
+ },
245
+ })),
246
+ {},
247
+ );
248
+
222
249
  /** The package's files `builderRecipe` covers, beside the third-party manifest. */
223
250
  export const recipeFiles = () =>
224
251
  listFiles(packageDirectory, resolve(packageDirectory, "docker"), recipeFile);
@@ -176,6 +176,9 @@ export const withWorkerLock = async <T>(
176
176
  };
177
177
 
178
178
  /** The caller holds withWorkerLock throughout a command, so the mailbox has one writer. */
179
+ /** CODESYS's process ended before it replied, which is how it crashes. */
180
+ export class CodesysExitedError extends Error {}
181
+
179
182
  export const createCodesysWorker = (config: ResolvedConfig) => {
180
183
  const host = createCodesysHost(config);
181
184
  const statePath = resolve(config.outDir, ".codesys/session.json");
@@ -264,7 +267,7 @@ export const createCodesysWorker = (config: ResolvedConfig) => {
264
267
  return response.data.result;
265
268
  }
266
269
  if (!isProcessAlive(session.pid)) {
267
- throw new Error(
270
+ throw new CodesysExitedError(
268
271
  `CODESYS exited before completing ${command.action}. See ${session.directory}/codesys.log`,
269
272
  );
270
273
  }
package/src/images.ts CHANGED
@@ -2,7 +2,11 @@ import { copyFile, cp, mkdir, mkdtemp, rm } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { resolve } from "node:path";
4
4
  import { dockerImage } from "@tsplc/config/build";
5
- import { builderRecipe, prepareDockerContext } from "./docker-context";
5
+ import {
6
+ builderRecipe,
7
+ engineeringRecipe,
8
+ prepareDockerContext,
9
+ } from "./docker-context";
6
10
  import { packageDirectory } from "./package-path";
7
11
 
8
12
  export const builderImage = dockerImage;
@@ -86,6 +90,8 @@ export async function buildBuilderImage(options: {
86
90
  `SETUP_PLATFORM=${options.setupPlatform}`,
87
91
  "--build-arg",
88
92
  `INSTALLER_SOURCE=${options.installer ? "installer-local" : "installer-download"}`,
93
+ "--build-arg",
94
+ `TSPLC_ENGINEERING=${await engineeringRecipe()}`,
89
95
  "--label",
90
96
  `${recipeLabel}=${await builderRecipe()}`,
91
97
  "--progress",