@tsplc/compiler 0.2.14 → 0.2.16

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 (54) hide show
  1. package/backends/codesys/debug.ts +509 -0
  2. package/backends/codesys/emit.ts +701 -9
  3. package/backends/codesys/http.ts +110 -34
  4. package/backends/codesys/index.ts +2 -1
  5. package/backends/codesys/io-paths.ts +3 -1
  6. package/backends/codesys/manifest.ts +312 -0
  7. package/backends/codesys/plan.ts +39 -9
  8. package/backends/codesys/publication.ts +2 -2
  9. package/backends/codesys/storage.ts +10 -3
  10. package/backends/codesys/task-access.ts +51 -1
  11. package/backends/codesys/telemetry.ts +593 -0
  12. package/backends/codesys/types.ts +2 -1
  13. package/dist/cli.js +190 -33
  14. package/dist/cli.js.map +6 -6
  15. package/dist/codesys.js +2148 -432
  16. package/dist/codesys.js.map +14 -11
  17. package/dist/elaborate-capture.js +7 -1
  18. package/dist/elaborate-capture.js.map +3 -3
  19. package/dist/index.js +877 -459
  20. package/dist/index.js.map +16 -15
  21. package/dist/ir.js +87 -23
  22. package/dist/ir.js.map +10 -9
  23. package/dist/project.js +42 -9
  24. package/dist/project.js.map +3 -3
  25. package/dist/telemetry.js +83 -0
  26. package/dist/telemetry.js.map +12 -0
  27. package/ir/core-model.ts +13 -0
  28. package/ir/core.ts +1 -0
  29. package/ir/errors.ts +20 -0
  30. package/ir/index.ts +1 -0
  31. package/ir/link.ts +17 -8
  32. package/ir/model.ts +39 -0
  33. package/ir/routine.ts +62 -29
  34. package/ir/types.ts +7 -1
  35. package/package.json +12 -6
  36. package/project/cli.ts +96 -6
  37. package/project/plant.ts +58 -9
  38. package/project/project.ts +56 -10
  39. package/src/frontend/async.ts +284 -195
  40. package/src/frontend/configuration.ts +7 -21
  41. package/src/frontend/const-functions.ts +44 -38
  42. package/src/frontend/elaborate/capture.ts +7 -0
  43. package/src/frontend/elaborate/index.ts +135 -61
  44. package/src/frontend/elaborate/layouts.ts +8 -0
  45. package/src/frontend/elaborate/model.ts +13 -0
  46. package/src/frontend/elaborate/specialize.ts +302 -111
  47. package/src/frontend/exposure.ts +28 -26
  48. package/src/frontend/positions.ts +272 -0
  49. package/src/frontend/promises.ts +52 -47
  50. package/src/frontend/services.ts +16 -26
  51. package/src/frontend/types.ts +14 -0
  52. package/src/frontend/typescript.ts +185 -65
  53. package/stdlib/telemetry.ts +72 -0
  54. package/types/telemetry.d.ts +44 -0
@@ -68,7 +68,8 @@ END_STRUCT
68
68
  END_TYPE
69
69
  `;
70
70
  } else if (type.kind === "array") {
71
- declaration = `TYPE ${name} : ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)};
71
+ // Typegen publishes each key of a `Record<Enum, T>` as its own contract variable.
72
+ declaration = `${type.index ? "{attribute 'tsplc_keyed'}\n" : ""}TYPE ${name} : ARRAY[${type.lowerBound}..${type.lowerBound + type.length - 1}] OF ${this.name(type.element)};
72
73
  END_TYPE
73
74
  `;
74
75
  } else if (type.kind === "string") {
package/dist/cli.js CHANGED
@@ -73,14 +73,15 @@ var buildServer = async (config, root) => {
73
73
  };
74
74
 
75
75
  // packages/compiler/project/cli.ts
76
+ import { existsSync as existsSync4 } from "fs";
76
77
  import { parseArgs } from "util";
77
- import { resolve as resolve6 } from "path";
78
+ import { relative as relative2, resolve as resolve6 } from "path";
78
79
  import {
79
80
  buildTargetFor,
80
81
  controllerFor as controllerFor2,
81
82
  loadTsplcConfig as loadTsplcConfig3,
82
83
  rawBuildConfig,
83
- simulationConfig
84
+ simulationConfig as simulationConfig2
84
85
  } from "@tsplc/config";
85
86
  import {
86
87
  buildProject as buildSt,
@@ -94,12 +95,21 @@ import {
94
95
  updateController
95
96
  } from "@tsplc/build";
96
97
  import { checkHostConfig as checkHostConfig3 } from "@tsplc/compiler";
98
+ import {
99
+ createDebugger,
100
+ createLoginAdapter,
101
+ createOpcUaAdapter,
102
+ loadManifest,
103
+ opcUaConnection,
104
+ serveDebugger
105
+ } from "@tsplc/debug";
97
106
  import { formatDiagnostic, hasErrors as hasErrors4 } from "@tsplc/compiler/ir";
98
107
  import { deviceTree as deviceTree3 } from "@tsplc/typegen";
99
108
  import { loadHardware as loadHardware3, resolveIo as resolveIo3 } from "@tsplc/typegen/hardware";
100
109
  import { generateProject as generateProject2 } from "@tsplc/typegen";
101
110
 
102
111
  // packages/compiler/project/plant.ts
112
+ import { existsSync as existsSync3 } from "node:fs";
103
113
  import { basename, relative, resolve as resolve4, sep } from "node:path";
104
114
  import { createInterface } from "node:readline/promises";
105
115
  import { pathToFileURL } from "node:url";
@@ -107,7 +117,8 @@ import {
107
117
  AgentOperationError,
108
118
  createAgentClient
109
119
  } from "@tsplc/agent/client";
110
- import { controllerFor } from "@tsplc/config";
120
+ import { controllerFor, simulationConfig } from "@tsplc/config";
121
+ import { LoginUnavailable, noLogin } from "@tsplc/debug";
111
122
  import { hasErrors as hasErrors2 } from "@tsplc/compiler/ir";
112
123
  import { generateProject } from "@tsplc/typegen";
113
124
  import { z } from "zod";
@@ -335,7 +346,7 @@ var failure = (origin, code, cause) => ({
335
346
  severity: "error",
336
347
  message: cause instanceof Error ? cause.message : String(cause)
337
348
  });
338
- async function loadProject(file, loaded, buildTarget) {
349
+ async function loadProject(file, loaded, buildTarget, configured) {
339
350
  let configFile = resolve2(file);
340
351
  try {
341
352
  configFile = await realpath(configFile);
@@ -344,11 +355,23 @@ async function loadProject(file, loaded, buildTarget) {
344
355
  return { configFile, diagnostics };
345
356
  const shared = (loaded ?? await loadTsplcConfig(configFile)).config;
346
357
  const root = dirname3(configFile);
347
- const config = compilerConfig(shared, resolveIo(shared, await loadHardware(shared, root)), buildTarget);
358
+ const catalog = await loadHardware(shared, root);
359
+ const config = compilerConfig(shared, resolveIo(shared, catalog), buildTarget);
348
360
  return {
349
361
  configFile,
350
362
  shared,
351
363
  config: { ...config, ...sourceInput(config, root) },
364
+ project: {
365
+ root,
366
+ ...shared.debug && { debug: shared.debug },
367
+ ...shared.telemetry && { telemetry: shared.telemetry },
368
+ ...shared.server && { server: shared.server },
369
+ hardware: {
370
+ catalog: configured ? await loadHardware(configured, root) : catalog,
371
+ config: configured ?? shared,
372
+ tree: shared.codesys?.deviceTree !== undefined
373
+ }
374
+ },
352
375
  diagnostics
353
376
  };
354
377
  } catch (cause) {
@@ -377,8 +400,8 @@ async function projectTargets(file = "tsplc.config.ts", options = {}) {
377
400
  return core ? { io: ioTargets(core), publication: publicationSelectors(core) } : undefined;
378
401
  }
379
402
  async function checkProject(file = "tsplc.config.ts", options = {}) {
380
- const loaded = await loadProject(file, options.loaded, options.buildTarget);
381
- if (!loaded.config) {
403
+ const loaded = await loadProject(file, options.loaded, options.buildTarget, options.configured);
404
+ if (!loaded.config || !loaded.project) {
382
405
  return loaded;
383
406
  }
384
407
  const config = loaded.config;
@@ -406,7 +429,7 @@ async function checkProject(file = "tsplc.config.ts", options = {}) {
406
429
  priority: task.priority,
407
430
  programs: task.programs
408
431
  }));
409
- const planned = planCodesys(normalized.core, { tasks }, config.target.options);
432
+ const planned = planCodesys(normalized.core, { tasks }, config.target.options, loaded.project);
410
433
  return {
411
434
  ...loaded,
412
435
  ...planned,
@@ -439,7 +462,8 @@ async function buildProject(file = "tsplc.config.ts", options = {}) {
439
462
  }
440
463
  const checked = await checkProject(configFile, {
441
464
  loaded: options.loaded,
442
- buildTarget: options.buildTarget
465
+ buildTarget: options.buildTarget,
466
+ configured: options.configured
443
467
  });
444
468
  if (!checked.plan || !checked.config) {
445
469
  return { diagnostics: checked.diagnostics };
@@ -461,14 +485,16 @@ async function buildProject(file = "tsplc.config.ts", options = {}) {
461
485
  staging = await mkdtemp2(join3(previous.root, "stage-"));
462
486
  const artifacts = [
463
487
  ...bundle.artifacts,
464
- { path: "mappings.json", content: `${JSON.stringify(bundle.mappings, null, 2)}
488
+ { path: "mappings.json", content: `${JSON.stringify(compactMappings(bundle.mappings))}
465
489
  ` },
466
490
  { path: "io-symbols.json", content: `${JSON.stringify(bundle.ioSymbols, null, 2)}
467
491
  ` },
468
492
  { path: "publication.json", content: `${JSON.stringify(bundle.publication, null, 2)}
469
493
  ` },
470
494
  { path: "config.json", content: `${JSON.stringify(checked.config, null, 2)}
471
- ` }
495
+ ` },
496
+ ...bundle.debug ? [{ path: "debug.json", content: `${JSON.stringify(bundle.debug)}
497
+ ` }] : []
472
498
  ];
473
499
  for (const artifact of artifacts) {
474
500
  const path = join3(staging, "st", artifact.path);
@@ -524,6 +550,24 @@ async function buildProject(file = "tsplc.config.ts", options = {}) {
524
550
  }
525
551
  }
526
552
  }
553
+ function compactMappings(mappings) {
554
+ const objects = new Map, files = new Map;
555
+ const index = (table, value) => {
556
+ if (!table.has(value))
557
+ table.set(value, table.size);
558
+ return table.get(value);
559
+ };
560
+ const rows = mappings.map(({ path, line, span }) => [
561
+ index(objects, path),
562
+ line,
563
+ index(files, span.file),
564
+ span.start,
565
+ span.end,
566
+ span.line,
567
+ span.column
568
+ ]);
569
+ return { objects: [...objects.keys()], files: [...files.keys()], mappings: rows };
570
+ }
527
571
 
528
572
  // packages/compiler/project/server.ts
529
573
  import { existsSync as existsSync2 } from "node:fs";
@@ -673,6 +717,23 @@ var connect = () => {
673
717
  token: environment.TSPLC_AGENT_TOKEN
674
718
  });
675
719
  };
720
+ var readThroughAgent = (agent) => async ([first, ...rest]) => {
721
+ if (!first)
722
+ return {};
723
+ try {
724
+ const result = await agent.command({ command: "read", expressions: [first, ...rest] });
725
+ if (!("values" in result))
726
+ throw new Error("The agent answered a read without values");
727
+ return result.values;
728
+ } catch (error) {
729
+ const { login } = await agent.status();
730
+ if (!login)
731
+ throw new LoginUnavailable(noLogin, { cause: error });
732
+ if ("error" in login)
733
+ throw new Error(login.error, { cause: error });
734
+ throw error;
735
+ }
736
+ };
676
737
  var selectTarget = async (agent) => {
677
738
  const interfaces = await agent.interfaces();
678
739
  if (!interfaces.length)
@@ -703,17 +764,19 @@ var contractVariables = async (config, root) => {
703
764
  }));
704
765
  });
705
766
  };
767
+ var serverTokenEnv = (config) => config.codesys?.http?.credentials.find(({ originEnv }) => originEnv === config.server?.baseUrlEnv)?.bearerTokenEnv;
706
768
  var prepareRelease = async (file, loaded, flags) => {
707
769
  const { config, root } = loaded;
708
770
  if (!config.compiler)
709
771
  throw new Error("tsplc deploy deploys tsPLC programs; configure compiler.");
772
+ const command = flags.simulate ? "run" : "deploy";
710
773
  const emitted = await buildProject(file, {
711
774
  emitOnly: true,
712
775
  forController: true,
713
776
  frozenLockfile: flags["frozen-lockfile"],
714
- loaded,
715
- buildTarget: "production",
716
- controller: controllerFor(config, "deploy")
777
+ ...flags.simulate ? { loaded: { ...loaded, config: simulationConfig(config) }, configured: config } : { loaded },
778
+ buildTarget: flags.simulate ? "development" : "production",
779
+ controller: controllerFor(config, command)
717
780
  });
718
781
  if (hasErrors2(emitted.diagnostics))
719
782
  return { diagnostics: emitted.diagnostics };
@@ -735,6 +798,9 @@ var prepareRelease = async (file, loaded, flags) => {
735
798
  path: `st/${portable(source)}`,
736
799
  content: Bun.file(resolve4(settings.sourceDir, source))
737
800
  });
801
+ const debugManifest = resolve4(settings.sourceDir, "debug.json");
802
+ if (existsSync3(debugManifest))
803
+ files.push({ path: "debug.json", content: Bun.file(debugManifest) });
738
804
  let server;
739
805
  if (config.server?.runtime) {
740
806
  const script = await bundleServer(config, root);
@@ -758,7 +824,9 @@ var prepareRelease = async (file, loaded, flags) => {
758
824
  entry: `st/${portable(relative(settings.sourceDir, settings.entry))}`
759
825
  },
760
826
  variables: await contractVariables(config, root),
761
- server
827
+ server,
828
+ debug: config.debug,
829
+ serverTokenEnv: serverTokenEnv(config)
762
830
  };
763
831
  return { release: { manifest, files } };
764
832
  };
@@ -848,7 +916,7 @@ var runPlantCommand = async (command, args, flags, project) => {
848
916
  };
849
917
  switch (command) {
850
918
  case "deploy": {
851
- expect(0, "[--download] [--select] [--initialize-user]");
919
+ expect(0, "[--download] [--select] [--initialize-user] [--simulate]");
852
920
  const deployed = await deploy(agent, project.file, await project.load(), flags);
853
921
  if ("diagnostics" in deployed)
854
922
  return deployed;
@@ -887,8 +955,8 @@ var runPlantCommand = async (command, args, flags, project) => {
887
955
  const forced = login && "forced" in login ? login.forced : [];
888
956
  if (forced.length && !await confirm(`Forced: ${forced.join(", ")}. Forces stay on the controller after logout. Log out anyway?`, flags))
889
957
  throw new Error("Cancelled.");
890
- await agent.logout();
891
- console.log("Logged out.");
958
+ const { failure } = await agent.logout();
959
+ console.log(failure ? `The login couldn't log out (${failure}); its container was removed.` : "Logged out.");
892
960
  return;
893
961
  }
894
962
  case "vars": {
@@ -961,7 +1029,7 @@ var failure2 = (origin, code, cause) => ({
961
1029
  severity: "error",
962
1030
  message: cause instanceof Error ? cause.message : String(cause)
963
1031
  });
964
- async function loadProject2(file, loaded, buildTarget) {
1032
+ async function loadProject2(file, loaded, buildTarget, configured) {
965
1033
  let configFile = resolve5(file);
966
1034
  try {
967
1035
  configFile = await realpath2(configFile);
@@ -970,11 +1038,23 @@ async function loadProject2(file, loaded, buildTarget) {
970
1038
  return { configFile, diagnostics };
971
1039
  const shared = (loaded ?? await loadTsplcConfig2(configFile)).config;
972
1040
  const root = dirname5(configFile);
973
- const config = compilerConfig2(shared, resolveIo2(shared, await loadHardware2(shared, root)), buildTarget);
1041
+ const catalog = await loadHardware2(shared, root);
1042
+ const config = compilerConfig2(shared, resolveIo2(shared, catalog), buildTarget);
974
1043
  return {
975
1044
  configFile,
976
1045
  shared,
977
1046
  config: { ...config, ...sourceInput2(config, root) },
1047
+ project: {
1048
+ root,
1049
+ ...shared.debug && { debug: shared.debug },
1050
+ ...shared.telemetry && { telemetry: shared.telemetry },
1051
+ ...shared.server && { server: shared.server },
1052
+ hardware: {
1053
+ catalog: configured ? await loadHardware2(configured, root) : catalog,
1054
+ config: configured ?? shared,
1055
+ tree: shared.codesys?.deviceTree !== undefined
1056
+ }
1057
+ },
978
1058
  diagnostics
979
1059
  };
980
1060
  } catch (cause) {
@@ -1003,8 +1083,8 @@ async function projectTargets2(file = "tsplc.config.ts", options = {}) {
1003
1083
  return core ? { io: ioTargets2(core), publication: publicationSelectors2(core) } : undefined;
1004
1084
  }
1005
1085
  async function checkProject2(file = "tsplc.config.ts", options = {}) {
1006
- const loaded = await loadProject2(file, options.loaded, options.buildTarget);
1007
- if (!loaded.config) {
1086
+ const loaded = await loadProject2(file, options.loaded, options.buildTarget, options.configured);
1087
+ if (!loaded.config || !loaded.project) {
1008
1088
  return loaded;
1009
1089
  }
1010
1090
  const config = loaded.config;
@@ -1032,7 +1112,7 @@ async function checkProject2(file = "tsplc.config.ts", options = {}) {
1032
1112
  priority: task.priority,
1033
1113
  programs: task.programs
1034
1114
  }));
1035
- const planned = planCodesys2(normalized.core, { tasks }, config.target.options);
1115
+ const planned = planCodesys2(normalized.core, { tasks }, config.target.options, loaded.project);
1036
1116
  return {
1037
1117
  ...loaded,
1038
1118
  ...planned,
@@ -1065,7 +1145,8 @@ async function buildProject2(file = "tsplc.config.ts", options = {}) {
1065
1145
  }
1066
1146
  const checked = await checkProject2(configFile, {
1067
1147
  loaded: options.loaded,
1068
- buildTarget: options.buildTarget
1148
+ buildTarget: options.buildTarget,
1149
+ configured: options.configured
1069
1150
  });
1070
1151
  if (!checked.plan || !checked.config) {
1071
1152
  return { diagnostics: checked.diagnostics };
@@ -1087,14 +1168,16 @@ async function buildProject2(file = "tsplc.config.ts", options = {}) {
1087
1168
  staging = await mkdtemp4(join5(previous.root, "stage-"));
1088
1169
  const artifacts = [
1089
1170
  ...bundle.artifacts,
1090
- { path: "mappings.json", content: `${JSON.stringify(bundle.mappings, null, 2)}
1171
+ { path: "mappings.json", content: `${JSON.stringify(compactMappings2(bundle.mappings))}
1091
1172
  ` },
1092
1173
  { path: "io-symbols.json", content: `${JSON.stringify(bundle.ioSymbols, null, 2)}
1093
1174
  ` },
1094
1175
  { path: "publication.json", content: `${JSON.stringify(bundle.publication, null, 2)}
1095
1176
  ` },
1096
1177
  { path: "config.json", content: `${JSON.stringify(checked.config, null, 2)}
1097
- ` }
1178
+ ` },
1179
+ ...bundle.debug ? [{ path: "debug.json", content: `${JSON.stringify(bundle.debug)}
1180
+ ` }] : []
1098
1181
  ];
1099
1182
  for (const artifact of artifacts) {
1100
1183
  const path = join5(staging, "st", artifact.path);
@@ -1150,6 +1233,24 @@ async function buildProject2(file = "tsplc.config.ts", options = {}) {
1150
1233
  }
1151
1234
  }
1152
1235
  }
1236
+ function compactMappings2(mappings) {
1237
+ const objects = new Map, files = new Map;
1238
+ const index = (table, value) => {
1239
+ if (!table.has(value))
1240
+ table.set(value, table.size);
1241
+ return table.get(value);
1242
+ };
1243
+ const rows = mappings.map(({ path, line, span }) => [
1244
+ index(objects, path),
1245
+ line,
1246
+ index(files, span.file),
1247
+ span.start,
1248
+ span.end,
1249
+ span.line,
1250
+ span.column
1251
+ ]);
1252
+ return { objects: [...objects.keys()], files: [...files.keys()], mappings: rows };
1253
+ }
1153
1254
  async function cleanProject(file = "tsplc.config.ts") {
1154
1255
  try {
1155
1256
  await cleanArtifacts(await realpath2(resolve5(file)));
@@ -1179,7 +1280,10 @@ async function main() {
1179
1280
  download: { type: "boolean" },
1180
1281
  restore: { type: "boolean" },
1181
1282
  select: { type: "boolean" },
1182
- yes: { type: "boolean", short: "y" }
1283
+ yes: { type: "boolean", short: "y" },
1284
+ port: { type: "string" },
1285
+ "server-url": { type: "string" },
1286
+ opcua: { type: "boolean" }
1183
1287
  }
1184
1288
  });
1185
1289
  const command = positionals[0], file = values.config ?? "tsplc.config.ts";
@@ -1187,11 +1291,21 @@ async function main() {
1187
1291
  console.log(`tsplc install|typegen|check|build|run|download|online-change|inspect|clean|configure [--config tsplc.config.ts] [--plc|--server] [--simulate] [--runtime] [--emit-only] [--format json] [--read symbol]
1188
1292
 
1189
1293
  Plant agent (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN):
1190
- tsplc deploy [--download] [--select] [--initialize-user]
1294
+ tsplc deploy [--download] [--select] [--initialize-user] [--simulate]
1191
1295
  tsplc target | status | login | logout
1192
1296
  tsplc vars [path] | read <expression>... | write <expression> <value>
1193
1297
  tsplc force <expression> <value> | unforce [expression]... [--restore]
1194
- tsplc start | stop | reset warm|cold (-y skips confirmations)`);
1298
+ tsplc start | stop | reset warm|cold (-y skips confirmations)
1299
+
1300
+ Debugger, on http://127.0.0.1, for the built .tsplc/artifacts/st/debug.json; it reads through
1301
+ the plant agent's login (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN), or --opcua at config monitor:
1302
+ tsplc debug [--port 4870] [--server-url url] [--opcua]`);
1303
+ return 0;
1304
+ }
1305
+ if (command === "debug") {
1306
+ if (positionals.length > 1)
1307
+ throw new Error("Usage: tsplc debug [--port 4870] [--server-url url] [--opcua]");
1308
+ await serveProjectDebugger(await loadTsplcConfig3(file), values);
1195
1309
  return 0;
1196
1310
  }
1197
1311
  if (plantCommands.has(command)) {
@@ -1224,8 +1338,8 @@ Plant agent (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN):
1224
1338
  throw new Error("--runtime applies only to configure.");
1225
1339
  if ((values.plc || values.server) && command !== "build")
1226
1340
  throw new Error("--plc and --server apply only to build.");
1227
- if (values.simulate && !["run", "download", "online-change"].includes(command))
1228
- throw new Error("--simulate applies only to run, download and online-change.");
1341
+ if (values.simulate && !["run", "download", "online-change", "deploy"].includes(command))
1342
+ throw new Error("--simulate applies only to run, download, online-change and deploy.");
1229
1343
  if (values.plc && values.server)
1230
1344
  throw new Error("Choose --plc or --server, or omit both for a full build.");
1231
1345
  if (values.server && values["emit-only"])
@@ -1250,7 +1364,7 @@ Plant agent (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN):
1250
1364
  }
1251
1365
  const loaded = await loadTsplcConfig3(file);
1252
1366
  const { config, configFile, root } = loaded;
1253
- const target = values.simulate ? { ...loaded, config: simulationConfig(config) } : loaded;
1367
+ const target = values.simulate ? { ...loaded, config: simulationConfig2(config) } : loaded;
1254
1368
  if (command === "install")
1255
1369
  result = {
1256
1370
  libraries: await installLibraries3(config.dependencies, root, {
@@ -1281,6 +1395,7 @@ Plant agent (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN):
1281
1395
  emitOnly: values["emit-only"],
1282
1396
  frozenLockfile: values["frozen-lockfile"],
1283
1397
  loaded: target,
1398
+ ...values.simulate && { configured: config },
1284
1399
  controller: controllerFor2(config, command),
1285
1400
  buildTarget: buildTargetFor(command)
1286
1401
  });
@@ -1333,6 +1448,7 @@ Plant agent (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN):
1333
1448
  forController: true,
1334
1449
  frozenLockfile: values["frozen-lockfile"],
1335
1450
  loaded: target,
1451
+ ...values.simulate && { configured: config },
1336
1452
  buildTarget: buildTargetFor(command)
1337
1453
  });
1338
1454
  if (hasErrors4(emitted.diagnostics))
@@ -1366,6 +1482,47 @@ Plant agent (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN):
1366
1482
  }
1367
1483
  return report(result, values.format);
1368
1484
  }
1485
+ async function serveProjectDebugger({ config, root }, flags) {
1486
+ if (flags.opcua && !config.monitor)
1487
+ throw new Error("Configure monitor with the controller's OPC UA endpoint to use --opcua.");
1488
+ const agentUrl = process.env["TSPLC_AGENT_URL"];
1489
+ if (!flags.opcua && !(agentUrl && process.env["TSPLC_AGENT_TOKEN"]))
1490
+ throw new Error("Set TSPLC_AGENT_URL and TSPLC_AGENT_TOKEN to read through the plant agent's login, or pass --opcua for a local virtual PLC.");
1491
+ const file = resolve6(root, ".tsplc/artifacts/st/debug.json");
1492
+ if (!existsSync4(file))
1493
+ throw new Error(`No debug manifest at ${relative2(process.cwd(), file)}: build with debug configured.`);
1494
+ const port = Number(flags.port ?? 4870);
1495
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
1496
+ throw new Error("--port must be a TCP port.");
1497
+ const manifest = await loadManifest(file);
1498
+ const serverUrl = flags["server-url"] ?? (config.server?.baseUrlEnv && process.env[config.server.baseUrlEnv]);
1499
+ const tokenEnv = serverTokenEnv(config);
1500
+ const token = tokenEnv && process.env[tokenEnv];
1501
+ const log = (message) => console.log(`${new Date().toISOString()} ${message}`);
1502
+ const debug = await createDebugger({
1503
+ manifest,
1504
+ adapter: flags.opcua && config.monitor ? createOpcUaAdapter(opcUaConnection(config.monitor, { root, env: process.env })) : createLoginAdapter({
1505
+ read: readThroughAgent(connect()),
1506
+ probe: manifest.build.target,
1507
+ endpoint: `the plant agent at ${agentUrl}`
1508
+ }),
1509
+ stateDirectory: resolve6(root, ".tsplc/debug"),
1510
+ watch: config.debug?.watch ?? {},
1511
+ ...serverUrl && token && { server: { url: serverUrl, token } },
1512
+ projectRoot: root,
1513
+ log
1514
+ });
1515
+ const server = serveDebugger(debug, { port, log });
1516
+ console.log(`tsPLC debugger at ${server.url}`);
1517
+ if (!serverUrl || !token)
1518
+ console.log("Not following the server's telemetry and requests: set server.baseUrlEnv or --server-url, and the server's bearer token variable.");
1519
+ await new Promise((stopped) => {
1520
+ process.once("SIGINT", stopped);
1521
+ process.once("SIGTERM", stopped);
1522
+ });
1523
+ await server.stop(true);
1524
+ await debug.close();
1525
+ }
1369
1526
 
1370
1527
  class DiagnosticFailure extends Error {
1371
1528
  result;
@@ -1406,5 +1563,5 @@ try {
1406
1563
  }
1407
1564
  }
1408
1565
 
1409
- //# debugId=4A829D9CF6D16B2264756E2164756E21
1566
+ //# debugId=66EFA12A78CD380A64756E2164756E21
1410
1567
  //# sourceMappingURL=cli.js.map