@tsplc/compiler 0.5.13 → 0.5.15

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 (263) hide show
  1. package/README.md +33 -8
  2. package/dist/cli.js +794 -621
  3. package/dist/cli.js.map +19 -16
  4. package/dist/clock.js +5 -2
  5. package/dist/clock.js.map +5 -4
  6. package/dist/codesys.js +4162 -4157
  7. package/dist/codesys.js.map +43 -29
  8. package/dist/index.js +7852 -6549
  9. package/dist/index.js.map +53 -50
  10. package/dist/ir.js +2482 -2277
  11. package/dist/ir.js.map +28 -25
  12. package/dist/retain.js +3 -1
  13. package/dist/retain.js.map +3 -3
  14. package/dist/signals.js +115 -0
  15. package/dist/signals.js.map +10 -0
  16. package/dist/telemetry.js +25 -20
  17. package/dist/telemetry.js.map +6 -6
  18. package/package.json +19 -39
  19. package/src/codesys/config.ts +3 -3
  20. package/src/codesys/debug.ts +92 -108
  21. package/src/codesys/emit.ts +100 -88
  22. package/src/codesys/endpoints.ts +111 -0
  23. package/src/codesys/engineering.ts +30 -54
  24. package/src/codesys/explain/expressions.ts +445 -0
  25. package/src/codesys/explain/flags.ts +134 -0
  26. package/src/codesys/explain/parameters.ts +53 -0
  27. package/src/codesys/explain/rows.ts +182 -0
  28. package/src/codesys/explain/tables.ts +79 -0
  29. package/src/codesys/explain/tasks.ts +68 -0
  30. package/src/codesys/explain/writes.ts +497 -0
  31. package/src/codesys/explain.ts +85 -1401
  32. package/src/codesys/expressions.ts +41 -33
  33. package/src/codesys/global-lists.ts +114 -94
  34. package/src/codesys/global-names.ts +12 -14
  35. package/src/codesys/http.ts +428 -388
  36. package/src/codesys/instrumentation.ts +142 -148
  37. package/src/codesys/io-paths.ts +31 -23
  38. package/src/codesys/loops.ts +101 -0
  39. package/src/codesys/manifest.ts +269 -269
  40. package/src/codesys/names.ts +10 -33
  41. package/src/codesys/numeric.ts +89 -42
  42. package/src/codesys/plan.ts +202 -190
  43. package/src/codesys/programs.ts +23 -16
  44. package/src/codesys/publication.ts +13 -86
  45. package/src/codesys/required.ts +8 -0
  46. package/src/codesys/routines.ts +103 -489
  47. package/src/codesys/scheduling.ts +96 -0
  48. package/src/codesys/service-channels.ts +23 -0
  49. package/src/codesys/sources.ts +34 -28
  50. package/src/codesys/st-files.ts +112 -105
  51. package/src/codesys/statements.ts +409 -0
  52. package/src/codesys/storage.ts +41 -23
  53. package/src/codesys/symbols.ts +130 -119
  54. package/src/codesys/task-access.ts +65 -221
  55. package/src/codesys/telemetry-settings.ts +19 -0
  56. package/src/codesys/telemetry.ts +185 -148
  57. package/src/codesys/types.ts +69 -109
  58. package/src/codesys/vendor.ts +13 -50
  59. package/src/frontend/analyzer.ts +66 -111
  60. package/src/frontend/async.ts +316 -128
  61. package/src/frontend/blocks.ts +178 -154
  62. package/src/frontend/configuration.ts +49 -153
  63. package/src/frontend/const-functions.ts +50 -40
  64. package/src/frontend/control-flow.ts +164 -129
  65. package/src/frontend/cooperative.ts +17 -9
  66. package/src/frontend/coroutines.ts +539 -441
  67. package/src/frontend/dialect-names.ts +104 -0
  68. package/src/frontend/elaborate/array-searches.ts +77 -69
  69. package/src/frontend/elaborate/assignments.ts +68 -77
  70. package/src/frontend/elaborate/calls.ts +878 -512
  71. package/src/frontend/elaborate/capture-protocol.ts +118 -21
  72. package/src/frontend/elaborate/capture.ts +196 -109
  73. package/src/frontend/elaborate/declarations.ts +124 -0
  74. package/src/frontend/elaborate/dialect.ts +119 -46
  75. package/src/frontend/elaborate/expressions.ts +763 -442
  76. package/src/frontend/elaborate/filtered-arrays.ts +127 -91
  77. package/src/frontend/elaborate/frame.ts +50 -2
  78. package/src/frontend/elaborate/generics.ts +20 -34
  79. package/src/frontend/elaborate/graph.ts +13 -87
  80. package/src/frontend/elaborate/imports.ts +0 -5
  81. package/src/frontend/elaborate/index.ts +416 -169
  82. package/src/frontend/elaborate/initializers.ts +64 -42
  83. package/src/frontend/elaborate/iterators.ts +228 -364
  84. package/src/frontend/elaborate/layouts.ts +477 -116
  85. package/src/frontend/elaborate/model.ts +113 -55
  86. package/src/frontend/elaborate/references.ts +116 -138
  87. package/src/frontend/elaborate/retention.ts +137 -59
  88. package/src/frontend/elaborate/specialize.ts +617 -308
  89. package/src/frontend/elaborate/statements.ts +436 -247
  90. package/src/frontend/elaborate/storage.ts +280 -213
  91. package/src/frontend/elaborate/time-constructors.ts +34 -0
  92. package/src/frontend/elaborate/values.ts +77 -7
  93. package/src/frontend/elaborate/writes.ts +98 -84
  94. package/src/frontend/expressions.ts +149 -151
  95. package/src/frontend/generated-names.ts +3 -3
  96. package/src/frontend/intrinsics.ts +31 -17
  97. package/src/frontend/lowering-key.ts +23 -0
  98. package/src/frontend/module-graph.ts +105 -43
  99. package/src/frontend/positions.ts +43 -35
  100. package/src/frontend/promise-chains.ts +226 -266
  101. package/src/frontend/promises.ts +88 -67
  102. package/src/frontend/routines.ts +122 -65
  103. package/src/frontend/sdk.ts +104 -5
  104. package/src/frontend/services.ts +149 -102
  105. package/src/frontend/statements.ts +60 -64
  106. package/src/frontend/tasks.ts +151 -96
  107. package/src/frontend/telemetry.ts +1 -1
  108. package/src/frontend/types.ts +366 -181
  109. package/src/frontend/typescript.ts +239 -112
  110. package/src/index.ts +2 -1
  111. package/src/ir/aggregates.ts +90 -75
  112. package/src/ir/allocation.ts +29 -18
  113. package/src/ir/conditions.ts +38 -78
  114. package/src/ir/core-model.ts +128 -11
  115. package/src/ir/declarations.ts +18 -32
  116. package/src/ir/diagnostics.ts +25 -18
  117. package/src/ir/domains.ts +26 -23
  118. package/src/ir/fold.ts +55 -50
  119. package/src/ir/identity.ts +10 -0
  120. package/src/ir/index.ts +31 -7
  121. package/src/ir/job-errors.ts +30 -8
  122. package/src/ir/layouts.ts +63 -34
  123. package/src/ir/link.ts +11 -46
  124. package/src/ir/model.ts +25 -6
  125. package/src/ir/normalize.ts +3 -28
  126. package/src/ir/numeric.ts +45 -18
  127. package/src/ir/operands.ts +102 -0
  128. package/src/ir/ranges.ts +242 -67
  129. package/src/ir/routine.ts +126 -183
  130. package/src/ir/scalars.ts +29 -25
  131. package/src/ir/share.ts +323 -343
  132. package/src/ir/short-circuit.ts +140 -0
  133. package/src/ir/tables.ts +111 -0
  134. package/src/ir/temporaries.ts +15 -113
  135. package/src/ir/types.ts +32 -8
  136. package/src/project/artifacts.ts +143 -71
  137. package/src/project/cli.ts +104 -87
  138. package/src/project/debugger.ts +48 -34
  139. package/src/project/deployments.ts +12 -68
  140. package/src/project/flags.ts +14 -0
  141. package/src/project/plant.ts +293 -225
  142. package/src/project/project-commands.ts +254 -192
  143. package/src/project/project.ts +184 -141
  144. package/src/project/release.ts +22 -28
  145. package/src/project/server.ts +22 -26
  146. package/src/project/terminal.ts +13 -2
  147. package/src/runtime/async.ts +17 -13
  148. package/src/runtime/launch.ts +5 -2
  149. package/src/runtime/main.ts +8 -3
  150. package/src/runtime/missing-file.ts +3 -0
  151. package/src/runtime/process.ts +24 -19
  152. package/src/runtime/program.ts +20 -53
  153. package/src/runtime/retain.ts +18 -10
  154. package/src/runtime/runtime.ts +47 -60
  155. package/src/runtime/settings.ts +27 -0
  156. package/src/runtime/storage.ts +49 -74
  157. package/src/runtime/symbols.ts +19 -75
  158. package/src/runtime/telemetry.ts +37 -14
  159. package/src/runtime/transport.ts +26 -30
  160. package/stdlib/clock.ts +4 -2
  161. package/stdlib/plc-time.ts +2 -0
  162. package/stdlib/retain.ts +2 -0
  163. package/stdlib/signals.ts +142 -0
  164. package/stdlib/telemetry.ts +5 -12
  165. package/types/dialect.d.ts +49 -0
  166. package/types/globals.d.ts +2 -42
  167. package/types/index.d.ts +3 -1
  168. package/types/retain.d.ts +8 -2
  169. package/types/telemetry.d.ts +3 -0
  170. package/dist/bun-runtime.js +0 -1472
  171. package/dist/bun-runtime.js.map +0 -26
  172. package/dist/elaborate-capture.js +0 -304
  173. package/dist/elaborate-capture.js.map +0 -11
  174. package/dist/math.js +0 -24
  175. package/dist/math.js.map +0 -10
  176. package/dist/project.js +0 -626
  177. package/dist/project.js.map +0 -12
  178. package/dist/server-check.js +0 -59
  179. package/dist/server-check.js.map +0 -11
  180. package/src/frontend/exposure.ts +0 -181
  181. package/src/project/index.ts +0 -6
  182. package/src/runtime/.runtime-65O4JH/server/router.ts +0 -17
  183. package/src/runtime/.runtime-65O4JH/src/cell.ts +0 -45
  184. package/src/runtime/.runtime-65O4JH/src/controller.ts +0 -58
  185. package/src/runtime/.runtime-65O4JH/src/lane.ts +0 -6
  186. package/src/runtime/.runtime-65O4JH/src/main.ts +0 -11
  187. package/src/runtime/.runtime-65O4JH/src/services.ts +0 -8
  188. package/src/runtime/.runtime-65O4JH/tsconfig.json +0 -13
  189. package/src/runtime/.runtime-65O4JH/tsplc.config.ts +0 -31
  190. package/src/runtime/.runtime-Brw2kO/server/router.ts +0 -17
  191. package/src/runtime/.runtime-Brw2kO/src/cell.ts +0 -45
  192. package/src/runtime/.runtime-Brw2kO/src/controller.ts +0 -58
  193. package/src/runtime/.runtime-Brw2kO/src/lane.ts +0 -6
  194. package/src/runtime/.runtime-Brw2kO/src/main.ts +0 -11
  195. package/src/runtime/.runtime-Brw2kO/src/services.ts +0 -8
  196. package/src/runtime/.runtime-Brw2kO/tsconfig.json +0 -13
  197. package/src/runtime/.runtime-Brw2kO/tsplc.config.ts +0 -31
  198. package/src/runtime/.runtime-NHfu1D/server/router.ts +0 -17
  199. package/src/runtime/.runtime-NHfu1D/src/cell.ts +0 -45
  200. package/src/runtime/.runtime-NHfu1D/src/controller.ts +0 -58
  201. package/src/runtime/.runtime-NHfu1D/src/lane.ts +0 -6
  202. package/src/runtime/.runtime-NHfu1D/src/main.ts +0 -11
  203. package/src/runtime/.runtime-NHfu1D/src/services.ts +0 -8
  204. package/src/runtime/.runtime-NHfu1D/tsconfig.json +0 -13
  205. package/src/runtime/.runtime-NHfu1D/tsplc.config.ts +0 -31
  206. package/src/runtime/.runtime-VaUSOu/server/router.ts +0 -17
  207. package/src/runtime/.runtime-VaUSOu/src/cell.ts +0 -45
  208. package/src/runtime/.runtime-VaUSOu/src/controller.ts +0 -58
  209. package/src/runtime/.runtime-VaUSOu/src/lane.ts +0 -6
  210. package/src/runtime/.runtime-VaUSOu/src/main.ts +0 -11
  211. package/src/runtime/.runtime-VaUSOu/src/services.ts +0 -8
  212. package/src/runtime/.runtime-VaUSOu/tsconfig.json +0 -13
  213. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +0 -31
  214. package/src/runtime/.runtime-WbtNvR/server/router.ts +0 -17
  215. package/src/runtime/.runtime-WbtNvR/src/cell.ts +0 -45
  216. package/src/runtime/.runtime-WbtNvR/src/controller.ts +0 -58
  217. package/src/runtime/.runtime-WbtNvR/src/lane.ts +0 -6
  218. package/src/runtime/.runtime-WbtNvR/src/main.ts +0 -11
  219. package/src/runtime/.runtime-WbtNvR/src/services.ts +0 -8
  220. package/src/runtime/.runtime-WbtNvR/tsconfig.json +0 -13
  221. package/src/runtime/.runtime-WbtNvR/tsplc.config.ts +0 -31
  222. package/src/runtime/.runtime-opcua-GMPUt8/server/router.ts +0 -17
  223. package/src/runtime/.runtime-opcua-GMPUt8/src/cell.ts +0 -45
  224. package/src/runtime/.runtime-opcua-GMPUt8/src/controller.ts +0 -58
  225. package/src/runtime/.runtime-opcua-GMPUt8/src/lane.ts +0 -6
  226. package/src/runtime/.runtime-opcua-GMPUt8/src/main.ts +0 -11
  227. package/src/runtime/.runtime-opcua-GMPUt8/src/services.ts +0 -8
  228. package/src/runtime/.runtime-opcua-GMPUt8/tsconfig.json +0 -13
  229. package/src/runtime/.runtime-opcua-GMPUt8/tsplc.config.ts +0 -31
  230. package/src/runtime/.runtime-opcua-UwafxO/server/router.ts +0 -17
  231. package/src/runtime/.runtime-opcua-UwafxO/src/cell.ts +0 -45
  232. package/src/runtime/.runtime-opcua-UwafxO/src/controller.ts +0 -58
  233. package/src/runtime/.runtime-opcua-UwafxO/src/lane.ts +0 -6
  234. package/src/runtime/.runtime-opcua-UwafxO/src/main.ts +0 -11
  235. package/src/runtime/.runtime-opcua-UwafxO/src/services.ts +0 -8
  236. package/src/runtime/.runtime-opcua-UwafxO/tsconfig.json +0 -13
  237. package/src/runtime/.runtime-opcua-UwafxO/tsplc.config.ts +0 -31
  238. package/src/runtime/.runtime-opcua-ecaSee/server/router.ts +0 -17
  239. package/src/runtime/.runtime-opcua-ecaSee/src/cell.ts +0 -45
  240. package/src/runtime/.runtime-opcua-ecaSee/src/controller.ts +0 -58
  241. package/src/runtime/.runtime-opcua-ecaSee/src/lane.ts +0 -6
  242. package/src/runtime/.runtime-opcua-ecaSee/src/main.ts +0 -11
  243. package/src/runtime/.runtime-opcua-ecaSee/src/services.ts +0 -8
  244. package/src/runtime/.runtime-opcua-ecaSee/tsconfig.json +0 -13
  245. package/src/runtime/.runtime-opcua-ecaSee/tsplc.config.ts +0 -31
  246. package/src/runtime/.runtime-opcua-y91UCm/server/router.ts +0 -17
  247. package/src/runtime/.runtime-opcua-y91UCm/src/cell.ts +0 -45
  248. package/src/runtime/.runtime-opcua-y91UCm/src/controller.ts +0 -58
  249. package/src/runtime/.runtime-opcua-y91UCm/src/lane.ts +0 -6
  250. package/src/runtime/.runtime-opcua-y91UCm/src/main.ts +0 -11
  251. package/src/runtime/.runtime-opcua-y91UCm/src/services.ts +0 -8
  252. package/src/runtime/.runtime-opcua-y91UCm/tsconfig.json +0 -13
  253. package/src/runtime/.runtime-opcua-y91UCm/tsplc.config.ts +0 -31
  254. package/src/runtime/.runtime-ybIxYh/server/router.ts +0 -17
  255. package/src/runtime/.runtime-ybIxYh/src/cell.ts +0 -45
  256. package/src/runtime/.runtime-ybIxYh/src/controller.ts +0 -58
  257. package/src/runtime/.runtime-ybIxYh/src/lane.ts +0 -6
  258. package/src/runtime/.runtime-ybIxYh/src/main.ts +0 -11
  259. package/src/runtime/.runtime-ybIxYh/src/services.ts +0 -8
  260. package/src/runtime/.runtime-ybIxYh/tsconfig.json +0 -13
  261. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +0 -31
  262. package/stdlib/math.ts +0 -23
  263. package/types/plc.d.ts +0 -4
package/dist/cli.js.map CHANGED
@@ -1,23 +1,26 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/project/cli.ts", "../src/project/debugger.ts", "../src/project/plant.ts", "../src/project/deployments.ts", "../src/project/terminal.ts", "../src/project/git.ts", "../src/project/release.ts", "../src/project/project.ts", "../src/runtime/launch.ts", "../src/project/artifacts.ts", "../src/project/server.ts", "../src/project/plant.ts", "../src/project/project-commands.ts", "../src/runtime/process.ts"],
3
+ "sources": ["../src/project/cli.ts", "../src/project/debugger.ts", "../src/project/flags.ts", "../src/project/plant.ts", "../src/project/deployments.ts", "../src/project/terminal.ts", "../src/project/git.ts", "../src/project/release.ts", "../src/project/project.ts", "../src/runtime/launch.ts", "../src/project/artifacts.ts", "../src/runtime/missing-file.ts", "../src/project/server.ts", "../src/project/flags.ts", "../src/project/plant.ts", "../src/project/project-commands.ts", "../src/runtime/process.ts"],
4
4
  "sourcesContent": [
5
- "#!/usr/bin/env bun\nimport { existsSync } from \"node:fs\";\nimport { parseArgs } from \"node:util\";\nimport { formatDiagnostic, hasErrors } from \"@tsplc/compiler/ir\";\nimport { loadTsplcConfig } from \"@tsplc/config\";\nimport { z } from \"zod\";\nimport { serveProjectDebugger } from \"./debugger\";\nimport { connect, plantCommand, runPlantCommand } from \"./plant\";\nimport {\n\ttype CommandResult,\n\tcheckProjectFlags,\n\tDiagnosticFailure,\n\tprojectCommand,\n\trunProjectCommand,\n} from \"./project-commands\";\n\nconst 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]\n\nRun the TypeScript program in Bun instead of CODESYS, with OPC UA on opc.tcp://127.0.0.1:4840:\n tsplc run --simulate --bun [--foreground] [--target name]\n\nPlant agent (the target's agent, else TSPLC_AGENT_URL; TSPLC_AGENT_TOKEN):\n tsplc deploy [--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait]\n tsplc deployments [--format json] | dashboard\n tsplc rollback [id] [--wait] | redeploy <id> [--review] [--wait]\n (--wait follows the deployment and exits 2 while it waits for approval; -y approves)\n tsplc target | status | login | logout\n tsplc vars [path] | read <expression>... | write <expression> <value>\n tsplc force <expression> <value> | unforce [expression]... [--restore]\n tsplc start | stop | reset warm|cold (-y skips confirmations)\n tsplc restart [warm|cold] resets and starts the application, with or without a login\n\nDebugger, on http://127.0.0.1, for the built .tsplc/artifacts/st/debug.json; it reads through\nthe plant agent's login (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN), or --opcua at config monitor:\n tsplc debug [--target name] [--port 4870] [--server-url url] [--opcua]`;\n\nconst formatSchema = z.enum([\"json\", \"text\"]).optional();\n\n/**\n * The `--format` the command line names, read before it is fully parsed so a command that fails\n * to parse still answers in that format. A positional `json` is an argument, not a format.\n */\nconst requestedFormat = (argv: readonly string[]) => {\n\tconst index = argv.findIndex(\n\t\t(argument) => argument === \"--format\" || argument.startsWith(\"--format=\"),\n\t);\n\tconst flag = argv[index];\n\tif (index < 0 || flag === undefined) {\n\t\treturn undefined;\n\t}\n\treturn flag === \"--format\" ? argv[index + 1] : flag.slice(\"--format=\".length);\n};\n\nconst outputFormat = (format: string | undefined) => {\n\tconst parsed = formatSchema.safeParse(format);\n\tif (!parsed.success) {\n\t\tthrow new Error(\"--format must be json or text.\");\n\t}\n\treturn parsed.data;\n};\n\nasync function main() {\n\tconst { values: parsed, positionals } = parseArgs({\n\t\tallowPositionals: true,\n\t\toptions: {\n\t\t\tconfig: { type: \"string\" },\n\t\t\ttarget: { type: \"string\" },\n\t\t\thelp: { type: \"boolean\", short: \"h\" },\n\t\t\t\"emit-only\": { type: \"boolean\" },\n\t\t\tformat: { type: \"string\" },\n\t\t\tread: { type: \"string\", multiple: true },\n\t\t\t\"initialize-user\": { type: \"boolean\" },\n\t\t\t\"frozen-lockfile\": { type: \"boolean\" },\n\t\t\tcheck: { type: \"boolean\" },\n\t\t\tplc: { type: \"boolean\" },\n\t\t\tserver: { type: \"boolean\" },\n\t\t\tsimulate: { type: \"boolean\" },\n\t\t\truntime: { type: \"boolean\" },\n\t\t\tbun: { type: \"boolean\" },\n\t\t\tforeground: { type: \"boolean\" },\n\t\t\tdownload: { type: \"boolean\" },\n\t\t\trestore: { type: \"boolean\" },\n\t\t\tselect: { type: \"boolean\" },\n\t\t\tyes: { type: \"boolean\", short: \"y\" },\n\t\t\tport: { type: \"string\" },\n\t\t\t\"server-url\": { type: \"string\" },\n\t\t\topcua: { type: \"boolean\" },\n\t\t\treview: { type: \"boolean\" },\n\t\t\twait: { type: \"boolean\" },\n\t\t},\n\t});\n\tconst values = {\n\t\t...parsed,\n\t\tformat: outputFormat(parsed.format),\n\t};\n\tconst [name, ...args] = positionals;\n\tconst file = values.config ?? \"tsplc.config.ts\";\n\tif (!name || values.help) {\n\t\tconsole.log(usage);\n\t\treturn 0;\n\t}\n\tif (name === \"debug\") {\n\t\tif (args.length) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Usage: tsplc debug [--target name] [--port 4870] [--server-url url] [--opcua]\",\n\t\t\t);\n\t\t}\n\t\tawait serveProjectDebugger(\n\t\t\tawait loadTsplcConfig(file, {\n\t\t\t\tenv: process.env,\n\t\t\t\ttarget: values.target,\n\t\t\t\tforAgent: false,\n\t\t\t}),\n\t\t\tvalues,\n\t\t);\n\t\treturn 0;\n\t}\n\tconst plant = plantCommand(name);\n\tif (plant) {\n\t\tconst load = () =>\n\t\t\tloadTsplcConfig(file, {\n\t\t\t\tenv: process.env,\n\t\t\t\ttarget: values.target,\n\t\t\t\tforAgent: true,\n\t\t\t});\n\t\t// In a project, the target names the agent; elsewhere TSPLC_AGENT_URL does.\n\t\tconst loaded = existsSync(file) ? await load() : undefined;\n\t\tconst env = loaded?.env ?? process.env;\n\t\tconst outcome = await runPlantCommand(connect(env), plant, args, values, {\n\t\t\tfile,\n\t\t\tload: loaded ? async () => loaded : load,\n\t\t\tenvironment: env,\n\t\t\tinteractive: process.stdin.isTTY === true,\n\t\t});\n\t\tif (!outcome) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn \"exitCode\" in outcome\n\t\t\t? outcome.exitCode\n\t\t\t: report(outcome, values.format);\n\t}\n\tif (args.length) {\n\t\tthrow new Error(\"Specify one command.\");\n\t}\n\tconst command = projectCommand(name);\n\tif (!command) {\n\t\tthrow new Error(`Unknown command ${name}.`);\n\t}\n\tcheckProjectFlags(command, values);\n\treturn report(\n\t\tawait runProjectCommand(command, file, values, { ...process.env }),\n\t\tvalues.format,\n\t);\n}\n\nfunction report(result: CommandResult, format: string | undefined) {\n\tconst diagnostics = result.diagnostics ?? [];\n\tconst ok = !hasErrors(diagnostics);\n\tif (format === \"json\") {\n\t\tconsole.log(JSON.stringify({ ok, ...result }));\n\t} else {\n\t\tfor (const diagnostic of diagnostics) {\n\t\t\tconsole.error(formatDiagnostic(diagnostic));\n\t\t}\n\t\tif (ok) {\n\t\t\tconsole.log(\"tsPLC completed.\");\n\t\t}\n\t}\n\treturn ok ? 0 : 1;\n}\n\ntry {\n\tprocess.exitCode = await main();\n} catch (cause) {\n\tconst json = requestedFormat(process.argv.slice(2)) === \"json\";\n\tif (cause instanceof DiagnosticFailure) {\n\t\tprocess.exitCode = report(cause.result, json ? \"json\" : undefined);\n\t} else {\n\t\tconst message = cause instanceof Error ? cause.message : String(cause);\n\t\tif (json) {\n\t\t\tconsole.log(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tok: false,\n\t\t\t\t\tdiagnostics: [\n\t\t\t\t\t\t{ origin: \"config\", code: \"PLC5003\", severity: \"error\", message },\n\t\t\t\t\t],\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\tconsole.error(message);\n\t\t}\n\t\tprocess.exitCode = 1;\n\t}\n}\n",
6
- "import { existsSync } from \"node:fs\";\nimport { relative, resolve } from \"node:path\";\nimport { type LoadedConfig, serverTokenEnv } from \"@tsplc/config\";\nimport { tcpPort } from \"@tsplc/config/build\";\nimport {\n\temittedStDirectory,\n\tgeneratedDirectory,\n} from \"@tsplc/config/project-files\";\nimport {\n\tcreateDebugger,\n\tcreateLoginAdapter,\n\tcreateOpcUaAdapter,\n\tloadExplanations,\n\tloadManifest,\n\topcUaConnection,\n\tserveDebugger,\n} from \"@tsplc/debug\";\nimport { debugManifestFile } from \"@tsplc/debug/manifest\";\nimport { connect, readThroughAgent } from \"./plant\";\n\n/**\n * Serves the debugger for the project's last build until interrupted. It reads the controller\n * through the plant agent's login, or with `--opcua` at the config's `monitor` endpoint, and\n * follows the server's telemetry and requests when the server's base URL (`--server-url`, or\n * `server.baseUrlEnv`) and the PLC's bearer token are in the config's environment.\n */\nexport async function serveProjectDebugger(\n\t{ config, root, env }: LoadedConfig,\n\tflags: { port?: string; \"server-url\"?: string; opcua?: boolean },\n) {\n\tif (flags.opcua && !config.monitor) {\n\t\tthrow new Error(\n\t\t\t\"Configure monitor with the controller's OPC UA endpoint to use --opcua.\",\n\t\t);\n\t}\n\tconst agentUrl = env.TSPLC_AGENT_URL;\n\tif (!flags.opcua && !(agentUrl && env.TSPLC_AGENT_TOKEN)) {\n\t\tthrow new Error(\n\t\t\t\"Set TSPLC_AGENT_URL and TSPLC_AGENT_TOKEN to read through the plant agent's login, or pass --opcua for a local virtual PLC.\",\n\t\t);\n\t}\n\tconst file = resolve(root, emittedStDirectory, debugManifestFile);\n\tif (!existsSync(file)) {\n\t\tthrow new Error(\n\t\t\t`No debug manifest at ${relative(process.cwd(), file)}: build with debug configured.`,\n\t\t);\n\t}\n\tconst port = tcpPort.safeParse(Number(flags.port ?? 4870));\n\tif (!port.success) {\n\t\tthrow new Error(\"--port must be a TCP port.\");\n\t}\n\tconst manifest = await loadManifest(file);\n\tconst serverUrl =\n\t\tflags[\"server-url\"] ??\n\t\t(config.server?.baseUrlEnv && env[config.server.baseUrlEnv]);\n\tconst tokenEnv = serverTokenEnv(config);\n\tconst token = tokenEnv && env[tokenEnv];\n\tconst log = (message: string) =>\n\t\tconsole.log(`${new Date().toISOString()} ${message}`);\n\tconst debug = await createDebugger({\n\t\tmanifest,\n\t\tadapter:\n\t\t\tflags.opcua && config.monitor\n\t\t\t\t? createOpcUaAdapter(opcUaConnection(config.monitor, { root, env }))\n\t\t\t\t: createLoginAdapter({\n\t\t\t\t\t\tread: readThroughAgent(connect(env)),\n\t\t\t\t\t\tprobe: manifest.build.target,\n\t\t\t\t\t\tendpoint: `the plant agent at ${agentUrl}`,\n\t\t\t\t\t}),\n\t\tstateDirectory: resolve(root, generatedDirectory, \"debug\"),\n\t\twatch: config.debug?.watch ?? {},\n\t\t...(serverUrl && token && { server: { url: serverUrl, token } }),\n\t\tprojectRoot: root,\n\t\texplanations: await loadExplanations(file, manifest),\n\t\t// The forced list comes from the agent's login; an OPC UA endpoint has no such list.\n\t\tforced: flags.opcua\n\t\t\t? null\n\t\t\t: async () => {\n\t\t\t\t\tconst { login } = await connect(env).status();\n\t\t\t\t\treturn login && \"forced\" in login ? login.forced : null;\n\t\t\t\t},\n\t\tlog,\n\t});\n\tconst server = serveDebugger(debug, { port: port.data, log });\n\tconsole.log(`tsPLC debugger at ${server.url}`);\n\tif (!serverUrl || !token) {\n\t\tconsole.log(\n\t\t\t\"Not following the server's telemetry and requests: set server.baseUrlEnv or --server-url, and the server's bearer token variable.\",\n\t\t);\n\t}\n\tawait new Promise((stopped) => {\n\t\tprocess.once(\"SIGINT\", stopped);\n\t\tprocess.once(\"SIGTERM\", stopped);\n\t});\n\tawait server.stop(true);\n\tawait debug.close();\n}\n",
7
- "import {\n\task,\n\taskCredentials,\n\ttype Credentials,\n\ttype Target,\n\ttype Variable,\n} from \"@tsplc/agent\";\nimport { type AgentClient, createAgentClient } from \"@tsplc/agent/client\";\nimport type { LoginCommand, LoginResult } from \"@tsplc/build\";\nimport type { CompileEnvironment } from \"@tsplc/compiler\";\nimport {\n\ttype LoadedConfig,\n\ttype PlantVariables,\n\treleaseEnvironment,\n} from \"@tsplc/config\";\nimport { LoginUnavailable, noLogin } from \"@tsplc/debug\";\nimport { z } from \"zod\";\nimport {\n\ttype Approval,\n\ttype Follow,\n\topenDashboard,\n\tprintDeployments,\n\tredeploy,\n\trollBack,\n\tsubmitDeployment,\n} from \"./deployments\";\nimport { gitSource } from \"./git\";\nimport { prepareRelease } from \"./release\";\nimport { choose, confirm, progress, timedProgress } from \"./terminal\";\n\nconst plantCommands = [\n\t\"deploy\",\n\t\"deployments\",\n\t\"rollback\",\n\t\"redeploy\",\n\t\"dashboard\",\n\t\"target\",\n\t\"status\",\n\t\"login\",\n\t\"logout\",\n\t\"vars\",\n\t\"read\",\n\t\"write\",\n\t\"force\",\n\t\"unforce\",\n\t\"start\",\n\t\"stop\",\n\t\"reset\",\n\t\"restart\",\n] as const;\n\nexport type PlantCommand = (typeof plantCommands)[number];\n\nexport const plantCommand = (name: string) =>\n\tplantCommands.find((command) => command === name);\n\nexport interface PlantFlags {\n\tdownload?: boolean;\n\tformat?: \"json\" | \"text\";\n\treview?: boolean;\n\twait?: boolean;\n\t\"initialize-user\"?: boolean;\n\trestore?: boolean;\n\tselect?: boolean;\n\tsimulate?: boolean;\n\tyes?: boolean;\n\t\"frozen-lockfile\"?: boolean;\n}\n\n/** The plant agent named by TSPLC_AGENT_URL and TSPLC_AGENT_TOKEN in `env`, where a target's agent sets the URL. */\nexport const connect = (env: Record<string, string | undefined>) => {\n\tconst environment = z\n\t\t.object({\n\t\t\tTSPLC_AGENT_URL: z.url({\n\t\t\t\terror:\n\t\t\t\t\t\"Configure the target's agent, or set TSPLC_AGENT_URL to the plant agent, such as http://plant-pc:4850\",\n\t\t\t}),\n\t\t\tTSPLC_AGENT_TOKEN: z.string({\n\t\t\t\terror: \"Set TSPLC_AGENT_TOKEN to the plant agent's token\",\n\t\t\t}),\n\t\t})\n\t\t.parse(env);\n\treturn createAgentClient({\n\t\turl: environment.TSPLC_AGENT_URL,\n\t\ttoken: environment.TSPLC_AGENT_TOKEN,\n\t});\n};\n\n/**\n * Reads through the agent's open login, as `tsplc read` does, without opening one: the\n * debugger has no controller credentials.\n */\nexport const readThroughAgent =\n\t(agent: AgentClient) =>\n\tasync ([first, ...rest]: string[]) => {\n\t\tif (!first) {\n\t\t\treturn {};\n\t\t}\n\t\ttry {\n\t\t\tconst result = await agent.command({\n\t\t\t\tcommand: \"read\",\n\t\t\t\texpressions: [first, ...rest],\n\t\t\t});\n\t\t\tif (!(\"values\" in result)) {\n\t\t\t\tthrow new Error(\"The agent answered a read without values\");\n\t\t\t}\n\t\t\treturn result.values;\n\t\t} catch (error) {\n\t\t\tconst { login } = await agent.status();\n\t\t\tif (!login) {\n\t\t\t\tthrow new LoginUnavailable(noLogin, { cause: error });\n\t\t\t}\n\t\t\tif (\"error\" in login) {\n\t\t\t\tthrow new Error(login.error, { cause: error });\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\nconst selectTarget = async (agent: AgentClient): Promise<Target> => {\n\tconst interfaces = await agent.interfaces();\n\tif (!interfaces.length) {\n\t\tthrow new Error(\"The plant PC has no IPv4 network.\");\n\t}\n\tconst network =\n\t\tinterfaces.length === 1 && interfaces[0]\n\t\t\t? interfaces[0]\n\t\t\t: await choose(\n\t\t\t\t\t\"Which network is the controller on?\",\n\t\t\t\t\tinterfaces,\n\t\t\t\t\t(item) => `${item.name} ${item.address}/${item.prefixLength}`,\n\t\t\t\t);\n\tconsole.log(\n\t\t`Scanning ${network.address}/${network.prefixLength} for CODESYS controllers…`,\n\t);\n\tconst found = await agent.discover(network.name);\n\tconst manual = { address: \"\", port: 11740, hostname: null };\n\tconst choice = await choose(\n\t\t\"Which controller?\",\n\t\t[...found, manual],\n\t\t(item) =>\n\t\t\titem === manual\n\t\t\t\t? \"Enter an address\"\n\t\t\t\t: `${item.address}${item.hostname ? ` (${item.hostname})` : \"\"}`,\n\t);\n\tconst host =\n\t\tchoice === manual ? await ask(\"Controller address: \") : choice.address;\n\treturn agent.setTarget({ host, port: choice.port });\n};\n\n/**\n * The controller user to send: TSPLC_CONTROLLER_USERNAME and TSPLC_CONTROLLER_PASSWORD from\n * `environment`, else null for the user stored on the agent, else what `prompt` asks for. Initializing\n * the controller's user creates the one sent, so it never leaves it to the stored one.\n */\nexport const controllerCredentials = async (\n\tenvironment: CompileEnvironment,\n\tagent: { stored: boolean; initializeUser: boolean },\n\tprompt: () => Promise<Credentials>,\n): Promise<Credentials | null> => {\n\tconst username = environment.TSPLC_CONTROLLER_USERNAME;\n\tconst password = environment.TSPLC_CONTROLLER_PASSWORD;\n\tif (username && password) {\n\t\treturn { username, password };\n\t}\n\tif (username || password) {\n\t\tthrow new Error(\n\t\t\t\"Set both TSPLC_CONTROLLER_USERNAME and TSPLC_CONTROLLER_PASSWORD, or neither.\",\n\t\t);\n\t}\n\treturn agent.stored && !agent.initializeUser ? null : prompt();\n};\n\n/** The plant PC's variables and secrets by name, as `variables A, B and secret C`, or null when it holds none. */\nconst plantSummary = ({ values, secrets }: PlantVariables) => {\n\tconst named = (noun: string, names: readonly string[]) =>\n\t\tnames.length\n\t\t\t? `${noun}${names.length === 1 ? \"\" : \"s\"} ${names.join(\", \")}`\n\t\t\t: null;\n\tconst parts = [\n\t\tnamed(\"variable\", Object.keys(values)),\n\t\tnamed(\"secret\", secrets),\n\t].filter((part) => part !== null);\n\treturn parts.length ? parts.join(\" and \") : null;\n};\n\nconst deploy = async (\n\tagent: AgentClient,\n\tfile: string,\n\tloaded: LoadedConfig,\n\tflags: PlantFlags,\n\tenvironment: CompileEnvironment,\n\tfollow: Follow,\n) => {\n\tconst status = await agent.status();\n\tif (status.login) {\n\t\tthrow new Error(\"A login is open; log out before deploying: tsplc logout\");\n\t}\n\tconst target =\n\t\t!status.target || flags.select ? await selectTarget(agent) : status.target;\n\tconst plant = await agent.releaseVariables(\n\t\tloaded.config.secrets?.service ?? null,\n\t);\n\tconst built = releaseEnvironment(\n\t\tloaded.config,\n\t\t{ env: environment, values: loaded.values },\n\t\tplant,\n\t);\n\tconsole.log(`Building the release for ${target.host}…`);\n\tconst held = plantSummary(plant);\n\tif (held) {\n\t\tconsole.log(` With the plant PC's ${held}`);\n\t}\n\tconst building = timedProgress();\n\tconst { release, diagnostics } = await prepareRelease(\n\t\tfile,\n\t\tloaded,\n\t\tflags,\n\t\tbuilt,\n\t);\n\tif (!release) {\n\t\treturn { diagnostics };\n\t}\n\tbuilding(\"Built\");\n\tif (\n\t\tflags.download &&\n\t\t!(await confirm(\n\t\t\t\"A full download stops the running application while it loads. Continue?\",\n\t\t\tflags,\n\t\t))\n\t) {\n\t\tthrow new Error(\"Cancelled.\");\n\t}\n\tconst credentials = await controllerCredentials(\n\t\tenvironment,\n\t\t{\n\t\t\tstored: status.credentialsStored,\n\t\t\tinitializeUser: flags[\"initialize-user\"] ?? false,\n\t\t},\n\t\taskCredentials,\n\t);\n\tconst settings = {\n\t\tcredentials,\n\t\tdownload: flags.download ?? false,\n\t\tinitializeUser: flags[\"initialize-user\"] ?? false,\n\t};\n\tconsole.log(\n\t\trelease.manifest.server\n\t\t\t? \"Uploading the server and the program…\"\n\t\t\t: \"Uploading the program…\",\n\t);\n\treturn {\n\t\texitCode: await submitDeployment(\n\t\t\tagent,\n\t\t\trelease,\n\t\t\tsettings,\n\t\t\t{\n\t\t\t\tmode: flags.review ? \"review\" : \"apply\",\n\t\t\t\tgit: await gitSource(loaded.root),\n\t\t\t},\n\t\t\tfollow,\n\t\t),\n\t};\n};\n\n/** Opens a login when none is working; it stays open across commands until `tsplc logout`. */\nconst ensureLogin = async (\n\tagent: AgentClient,\n\tenvironment: CompileEnvironment,\n) => {\n\tconst { login, credentialsStored } = await agent.status();\n\tif (login && \"state\" in login) {\n\t\treturn;\n\t}\n\tif (login) {\n\t\tconsole.log(`The open login failed (${login.error}); replacing it.`);\n\t\tawait agent.logout();\n\t}\n\tconst credentials = await controllerCredentials(\n\t\tenvironment,\n\t\t{ stored: credentialsStored, initializeUser: false },\n\t\taskCredentials,\n\t);\n\tconsole.log(\n\t\t\"Logging in. CODESYS takes a few minutes to start; the login stays open until tsplc logout.\",\n\t);\n\tawait agent.login(credentials, progress);\n};\n\n/** The children of `prefix` in the variable tree, with array indexes folded into one range. */\nexport const variableChildren = (\n\tvariables: readonly Variable[],\n\tprefix: string,\n) => {\n\tconst children = new Map<string, { type?: string; leaves: number }>();\n\tconst start = prefix.toLowerCase();\n\tfor (const { path, type } of variables) {\n\t\tconst lower = path.toLowerCase();\n\t\tif (\n\t\t\tprefix &&\n\t\t\t!(\n\t\t\t\tlower === start ||\n\t\t\t\tlower.startsWith(`${start}.`) ||\n\t\t\t\tlower.startsWith(`${start}[`)\n\t\t\t)\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst rest = path.slice(prefix.length).replace(/^\\./, \"\");\n\t\tif (rest === \"\") {\n\t\t\treturn [{ name: path, type, leaves: 1 }];\n\t\t}\n\t\tconst name = /^(\\[[^\\]]*\\]|[^.[]+)/.exec(rest)?.[0] ?? rest;\n\t\tconst child = children.get(name) ?? { leaves: 0 };\n\t\tchildren.set(name, {\n\t\t\ttype: rest === name ? type : undefined,\n\t\t\tleaves: child.leaves + 1,\n\t\t});\n\t}\n\tconst indexes = [...children.keys()]\n\t\t.filter((name) => /^\\[\\d+\\]$/.test(name))\n\t\t.map((name) => Number(name.slice(1, -1)));\n\tconst listed = [...children].filter(([name]) => !/^\\[\\d+\\]$/.test(name));\n\tif (indexes.length) {\n\t\tconst first = children.get(`[${Math.min(...indexes)}]`);\n\t\tlisted.unshift([\n\t\t\t`[${Math.min(...indexes)}..${Math.max(...indexes)}]`,\n\t\t\tfirst ?? { leaves: 0 },\n\t\t]);\n\t}\n\treturn listed.map(([name, child]) => ({ name, ...child }));\n};\n\nconst printStatus = async (agent: AgentClient) => {\n\tconst status = await agent.status();\n\tconsole.log(\n\t\t`Controller ${status.target ? `${status.target.host}:${status.target.port}` : \"not selected (tsplc target)\"}`,\n\t);\n\tconsole.log(\n\t\t`Release ${status.release ? `${status.release.id}, ${status.release.operation} at ${status.release.deployedAt}` : \"none\"}`,\n\t);\n\tconsole.log(\n\t\t`Server ${status.server ? `${status.server.running ? \"running\" : \"restarting\"} (${status.server.executable})` : \"none\"}`,\n\t);\n\tconst { login } = status;\n\tif (!login) {\n\t\tconsole.log(\"Login closed\");\n\t} else if (\"error\" in login) {\n\t\tconsole.log(`Login failed: ${login.error} (tsplc logout)`);\n\t} else {\n\t\tconsole.log(\n\t\t\t`Login open; application ${login.state}${login.forced.length ? `; forced: ${login.forced.join(\", \")}` : \"\"}`,\n\t\t);\n\t}\n};\n\n/** Lists the deployed release's published variables under `path`, or its roots. */\nconst printVariables = async (agent: AgentClient, path: string | undefined) => {\n\tconst children = variableChildren(await agent.variables(), path ?? \"\");\n\tif (!children.length) {\n\t\tthrow new Error(`No published variable ${path}.`);\n\t}\n\tfor (const child of children) {\n\t\tconsole.log(\n\t\t\t`${child.name.padEnd(32)} ${child.type ?? `${child.leaves} variables`}`,\n\t\t);\n\t}\n};\n\nconst printLogin = (result: LoginResult) => {\n\tif (\"values\" in result) {\n\t\tfor (const [expression, value] of Object.entries(result.values)) {\n\t\t\tconsole.log(`${expression} = ${value}`);\n\t\t}\n\t\treturn;\n\t}\n\tconsole.log(`Application ${result.state}`);\n\tif (result.forced.length) {\n\t\tconsole.log(`Forced: ${result.forced.join(\", \")}`);\n\t}\n};\n\n/**\n * Runs a command against the plant agent. Returns a deployment's compiler diagnostics when the\n * program doesn't compile, and the exit code of a command that queues a deployment.\n */\nexport const runPlantCommand = async (\n\tagent: AgentClient,\n\tcommand: PlantCommand,\n\targs: string[],\n\tflags: PlantFlags,\n\tproject: {\n\t\tfile: string;\n\t\tload: () => Promise<LoadedConfig>;\n\t\t/** What the release's compilation reads. */\n\t\tenvironment: CompileEnvironment;\n\t\t/** Someone at a terminal can answer prompts. */\n\t\tinteractive: boolean;\n\t},\n) => {\n\tconst approval: Approval = {\n\t\tyes: flags.yes ?? false,\n\t\tinteractive: project.interactive,\n\t\tconfirm: (question) => confirm(question, {}),\n\t};\n\tconst follow = { wait: flags.wait ?? false, approval };\n\tconst expect = (count: number, usage: string) => {\n\t\tif (args.length !== count) {\n\t\t\tthrow new Error(`Usage: tsplc ${command} ${usage}`);\n\t\t}\n\t};\n\tconst send = async (loginCommand: LoginCommand) => {\n\t\tawait ensureLogin(agent, project.environment);\n\t\tprintLogin(await agent.command(loginCommand));\n\t};\n\tswitch (command) {\n\t\tcase \"deploy\":\n\t\t\texpect(\n\t\t\t\t0,\n\t\t\t\t\"[--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait] [-y]\",\n\t\t\t);\n\t\t\treturn deploy(\n\t\t\t\tagent,\n\t\t\t\tproject.file,\n\t\t\t\tawait project.load(),\n\t\t\t\tflags,\n\t\t\t\tproject.environment,\n\t\t\t\tfollow,\n\t\t\t);\n\t\tcase \"deployments\":\n\t\t\texpect(0, \"[--format json]\");\n\t\t\treturn printDeployments(agent, flags);\n\t\tcase \"rollback\":\n\t\t\tif (args.length > 1) {\n\t\t\t\tthrow new Error(\"Usage: tsplc rollback [id] [--wait] [-y]\");\n\t\t\t}\n\t\t\treturn { exitCode: await rollBack(agent, args[0], follow) };\n\t\tcase \"redeploy\": {\n\t\t\tconst [id, ...extra] = args;\n\t\t\tif (!id || extra.length) {\n\t\t\t\tthrow new Error(\"Usage: tsplc redeploy <id> [--review] [--wait] [-y]\");\n\t\t\t}\n\t\t\treturn {\n\t\t\t\texitCode: await redeploy(\n\t\t\t\t\tagent,\n\t\t\t\t\tid,\n\t\t\t\t\tflags.review ? \"review\" : \"apply\",\n\t\t\t\t\tfollow,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t\tcase \"dashboard\":\n\t\t\texpect(0, \"\");\n\t\t\treturn openDashboard(agent, project.interactive);\n\t\tcase \"target\": {\n\t\t\texpect(0, \"\");\n\t\t\tconst target = await selectTarget(agent);\n\t\t\tconsole.log(`Deployments now go to ${target.host}:${target.port}.`);\n\t\t\treturn;\n\t\t}\n\t\tcase \"status\":\n\t\t\texpect(0, \"\");\n\t\t\treturn printStatus(agent);\n\t\tcase \"login\":\n\t\t\texpect(0, \"\");\n\t\t\tawait ensureLogin(agent, project.environment);\n\t\t\tprintLogin(await agent.command({ command: \"state\" }));\n\t\t\treturn;\n\t\tcase \"logout\": {\n\t\t\texpect(0, \"\");\n\t\t\tconst { login } = await agent.status();\n\t\t\tconst forced = login && \"forced\" in login ? login.forced : [];\n\t\t\tif (\n\t\t\t\tforced.length &&\n\t\t\t\t!(await confirm(\n\t\t\t\t\t`Forced: ${forced.join(\", \")}. Forces stay on the controller after logout. Log out anyway?`,\n\t\t\t\t\tflags,\n\t\t\t\t))\n\t\t\t) {\n\t\t\t\tthrow new Error(\"Cancelled.\");\n\t\t\t}\n\t\t\tconst { failure } = await agent.logout();\n\t\t\tconsole.log(\n\t\t\t\tfailure\n\t\t\t\t\t? `The login couldn't log out (${failure}); its container was removed.`\n\t\t\t\t\t: \"Logged out.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tcase \"vars\":\n\t\t\tif (args.length > 1) {\n\t\t\t\tthrow new Error(\"Usage: tsplc vars [path]\");\n\t\t\t}\n\t\t\treturn printVariables(agent, args[0]);\n\t\tcase \"read\": {\n\t\t\tconst [first, ...rest] = args;\n\t\t\tif (!first) {\n\t\t\t\tthrow new Error(\"Usage: tsplc read <expression>...\");\n\t\t\t}\n\t\t\treturn send({ command: \"read\", expressions: [first, ...rest] });\n\t\t}\n\t\tcase \"write\":\n\t\tcase \"force\": {\n\t\t\tconst [expression, value, ...extra] = args;\n\t\t\tif (!expression || !value || extra.length) {\n\t\t\t\tthrow new Error(`Usage: tsplc ${command} <expression> <value>`);\n\t\t\t}\n\t\t\treturn send({ command, values: { [expression]: value } });\n\t\t}\n\t\tcase \"unforce\":\n\t\t\treturn send({\n\t\t\t\tcommand: \"unforce\",\n\t\t\t\texpressions: args,\n\t\t\t\trestore: flags.restore ?? false,\n\t\t\t});\n\t\tcase \"start\":\n\t\t\texpect(0, \"\");\n\t\t\treturn send({ command: \"start\" });\n\t\tcase \"stop\":\n\t\t\texpect(0, \"\");\n\t\t\tif (!(await confirm(\"Stop the application on the controller?\", flags))) {\n\t\t\t\tthrow new Error(\"Cancelled.\");\n\t\t\t}\n\t\t\treturn send({ command: \"stop\" });\n\t\tcase \"restart\": {\n\t\t\tif (args.length > 1) {\n\t\t\t\tthrow new Error(\"Usage: tsplc restart [warm|cold] [-y]\");\n\t\t\t}\n\t\t\tconst reset = z.enum([\"warm\", \"cold\"]).parse(args[0] ?? \"warm\");\n\t\t\tif (\n\t\t\t\t!(await confirm(\n\t\t\t\t\t`Reset the application (${reset}) and start it again? Its variables go back to their initial values${reset === \"warm\" ? \", but for retain ones\" : \"\"}.`,\n\t\t\t\t\tflags,\n\t\t\t\t))\n\t\t\t) {\n\t\t\t\tthrow new Error(\"Cancelled.\");\n\t\t\t}\n\t\t\tconst { state } = await agent.restartController({ reset });\n\t\t\tconsole.log(\n\t\t\t\t`Reset ${reset}; the application is ${state === \"run\" ? \"running\" : state}.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tcase \"reset\": {\n\t\t\texpect(1, \"warm|cold\");\n\t\t\tconst kind = z.enum([\"warm\", \"cold\"]).parse(args[0]);\n\t\t\tif (\n\t\t\t\t!(await confirm(\n\t\t\t\t\t`Reset the application (${kind})? It stops and reinitializes its variables.`,\n\t\t\t\t\tflags,\n\t\t\t\t))\n\t\t\t) {\n\t\t\t\tthrow new Error(\"Cancelled.\");\n\t\t\t}\n\t\t\treturn send({\n\t\t\t\tcommand: \"reset\",\n\t\t\t\tkind: kind === \"warm\" ? \"Warm\" : \"Cold\",\n\t\t\t});\n\t\t}\n\t}\n};\n",
8
- "import { spawn } from \"node:child_process\";\nimport type {\n\tDeploymentMode,\n\tDeploymentRecord,\n\tDeployOptions,\n\tGitSource,\n} from \"@tsplc/agent\";\nimport {\n\ttype AgentClient,\n\tAgentOperationError,\n\tAgentUnreachable,\n} from \"@tsplc/agent/client\";\nimport { describeFinding } from \"@tsplc/build\";\nimport { progress, timedProgress } from \"./terminal\";\n\n/** `tsplc deploy --wait` and the like exit with this while the deployment waits on a person. */\nexport const awaitingApprovalExit = 2;\n\n/** How a command that follows a deployment may ask before it approves one. */\nexport interface Approval {\n\t/** Approve without asking: `--yes`. */\n\tyes: boolean;\n\t/** Someone at a terminal can answer. */\n\tinteractive: boolean;\n\t/** Asks a yes-or-no question. */\n\tconfirm: (question: string) => Promise<boolean>;\n}\n\n/** What a command that queues a deployment does once it is queued. */\nexport interface Follow {\n\t/** Follow it until it finishes: `--wait`. */\n\twait: boolean;\n\tapproval: Approval;\n}\n\n/** How often, a second apart, following a deployment reconnects before it gives up. */\nconst reconnectAttempts = 5;\nconst reconnectDelay = 1000;\n\nconst stateMessage = (record: DeploymentRecord) => {\n\tswitch (record.state) {\n\t\tcase \"queued\":\n\t\t\treturn \"Queued.\";\n\t\tcase \"building\":\n\t\t\treturn \"Building the release…\";\n\t\tcase \"applying\":\n\t\t\treturn record.operation === \"download\"\n\t\t\t\t? \"Downloading the program; the application stops while it loads…\"\n\t\t\t\t: \"Applying the online change…\";\n\t\tcase \"starting\":\n\t\t\treturn \"Starting the server…\";\n\t\tcase \"verifying\":\n\t\t\treturn \"Checking the deployment's health…\";\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n};\n\nconst printFindings = (record: DeploymentRecord) => {\n\tif (!record.findings.length) {\n\t\tprogress(\"No findings.\");\n\t\treturn;\n\t}\n\tfor (const finding of record.findings) {\n\t\tprogress(\n\t\t\t`${finding.refuses ? \"refuses\" : \"note\"}: ${describeFinding(finding)}`,\n\t\t);\n\t}\n};\n\n/** Whether to approve: `--yes` does, a person may, and null when nobody can be asked. */\nconst decide = async (approval: Approval, question: string) => {\n\tif (approval.yes) {\n\t\treturn true;\n\t}\n\tif (!approval.interactive) {\n\t\treturn null;\n\t}\n\treturn approval.confirm(question);\n};\n\n/**\n * Shows what a deployment waits on and approves it when the deployer agrees. False when it is\n * left waiting.\n */\nconst approve = async (\n\tagent: AgentClient,\n\trecord: DeploymentRecord,\n\treason: \"review\" | \"downloadRequired\",\n\t{ url, approval }: { url: string; approval: Approval },\n) => {\n\tconst download = reason === \"downloadRequired\";\n\tif (download) {\n\t\tconsole.log(\n\t\t\t\"Only a full download can deploy this release, and a full download stops the running application while it loads.\",\n\t\t);\n\t} else {\n\t\tconsole.log(\"The review found what the online change would do:\");\n\t}\n\tprintFindings(record);\n\tconst approved = await decide(\n\t\tapproval,\n\t\tdownload ? \"Download now?\" : \"Apply it?\",\n\t);\n\tif (!approved) {\n\t\tconsole.log(\n\t\t\tapproved === null\n\t\t\t\t? `It waits for approval on the dashboard: ${url}`\n\t\t\t\t: `It waits for approval or cancellation on the dashboard: ${url}`,\n\t\t);\n\t\treturn false;\n\t}\n\tawait agent.approve(record.id, { download });\n\tconsole.log(download ? \"Approved the full download.\" : \"Approved.\");\n\treturn true;\n};\n\n/**\n * Follows a deployment until it finishes, printing its log and the states it goes through, and\n * asking for approval when it waits on one. Reconnects from the last log line it printed. The\n * exit code: 0 when it is ready, `awaitingApprovalExit` when it is left waiting; a failed or\n * canceled deployment throws.\n */\nexport const followDeployment = async (\n\tagent: AgentClient,\n\tdeployment: { id: string; url: string },\n\tapproval: Approval,\n): Promise<number> => {\n\tconst seen: {\n\t\tafter: number;\n\t\tstate: DeploymentRecord[\"state\"] | null;\n\t\tapproval: string | null;\n\t\tfailures: number;\n\t} = { after: 0, state: null, approval: null, failures: 0 };\n\n\t/** The exit code once the deployment is done with this command, else undefined. */\n\tconst onRecord = async (record: DeploymentRecord) => {\n\t\tif (record.state !== seen.state) {\n\t\t\tseen.state = record.state;\n\t\t\tconst message = stateMessage(record);\n\t\t\tif (message) {\n\t\t\t\tconsole.log(message);\n\t\t\t}\n\t\t}\n\t\tif (record.state !== \"awaitingApproval\" || !record.approval) {\n\t\t\tseen.approval = null;\n\t\t} else {\n\t\t\tconst asked = `${record.approval.reason}: ${record.approval.message}`;\n\t\t\tif (asked !== seen.approval) {\n\t\t\t\tseen.approval = asked;\n\t\t\t\tconsole.log(record.approval.message);\n\t\t\t\tconst approved = await approve(agent, record, record.approval.reason, {\n\t\t\t\t\turl: deployment.url,\n\t\t\t\t\tapproval,\n\t\t\t\t});\n\t\t\t\tif (!approved) {\n\t\t\t\t\treturn awaitingApprovalExit;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (record.state === \"ready\") {\n\t\t\tconst { health } = record;\n\t\t\tconsole.log(\n\t\t\t\thealth\n\t\t\t\t\t? `Ready: controller ${health.controller}, server ${health.server}, PLC ${health.plc}.${health.detail ? ` ${health.detail}` : \"\"}`\n\t\t\t\t\t: \"Ready.\",\n\t\t\t);\n\t\t\treturn 0;\n\t\t}\n\t\tif (record.state === \"error\") {\n\t\t\tthrow new Error(\n\t\t\t\t`The deployment failed: ${record.error?.message ?? \"no reason given\"}. ${deployment.url}`,\n\t\t\t);\n\t\t}\n\t\tif (record.state === \"canceled\") {\n\t\t\tthrow new Error(`The deployment was canceled. ${deployment.url}`);\n\t\t}\n\t\treturn undefined;\n\t};\n\n\twhile (true) {\n\t\ttry {\n\t\t\tfor await (const event of agent.deploymentEvents(\n\t\t\t\tdeployment.id,\n\t\t\t\tseen.after,\n\t\t\t)) {\n\t\t\t\tseen.failures = 0;\n\t\t\t\tif (event.kind === \"record\") {\n\t\t\t\t\tconst exit = await onRecord(event.record);\n\t\t\t\t\tif (exit !== undefined) {\n\t\t\t\t\t\treturn exit;\n\t\t\t\t\t}\n\t\t\t\t} else if (event.line.seq > seen.after) {\n\t\t\t\t\tseen.after = event.line.seq;\n\t\t\t\t\tprogress(\n\t\t\t\t\t\tevent.line.level === \"info\"\n\t\t\t\t\t\t\t? event.line.message\n\t\t\t\t\t\t\t: `${event.line.level}: ${event.line.message}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof AgentUnreachable)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\t// The stream broke, or ended before the deployment finished.\n\t\tseen.failures += 1;\n\t\tif (seen.failures > reconnectAttempts) {\n\t\t\tthrow new Error(\n\t\t\t\t`Lost the connection to the plant agent; the deployment goes on: ${deployment.url}`,\n\t\t\t);\n\t\t}\n\t\tawait Bun.sleep(reconnectDelay);\n\t}\n};\n\n/** Prints a queued deployment's page, then follows it when asked to. */\nconst queued = async (\n\tagent: AgentClient,\n\tcreated: { id: string; url: string },\n\tfollow: Follow,\n) => {\n\tconsole.log(`Deployment ${created.id} queued: ${created.url}`);\n\tif (!follow.wait) {\n\t\treturn 0;\n\t}\n\treturn followDeployment(agent, created, follow.approval);\n};\n\n/**\n * Uploads a built release as a queued deployment and prints its page. An agent without the\n * deployments API deploys it at once instead, as `tsplc deploy` did before.\n */\nexport const submitDeployment = async (\n\tagent: AgentClient,\n\trelease: Parameters<AgentClient[\"deploy\"]>[0],\n\tsettings: Omit<DeployOptions, \"deployment\">,\n\trequest: { mode: DeploymentMode; git: GitSource | null },\n\tfollow: Follow,\n) => {\n\tconst uploading = timedProgress();\n\tconst created = await agent.queueDeployment(\n\t\trelease,\n\t\t{ ...settings, deployment: request },\n\t\tuploading,\n\t);\n\tif (created) {\n\t\tuploading(\"Uploaded\");\n\t\tif (request.mode === \"review\" && !follow.wait) {\n\t\t\tconsole.log(\"Once reviewed, it waits for approval on its page.\");\n\t\t}\n\t\treturn queued(agent, created, follow);\n\t}\n\tif (request.mode === \"review\") {\n\t\tthrow new Error(\n\t\t\t\"This plant agent can't review a deployment before applying it; deploy without --review.\",\n\t\t);\n\t}\n\tconsole.log(\"This plant agent can't queue deployments; deploying at once.\");\n\tconst deployed = await deployAtOnce(\n\t\tagent,\n\t\trelease,\n\t\tsettings,\n\t\tfollow.approval,\n\t);\n\tconsole.log(`Deployed release ${deployed.id} (${deployed.operation}).`);\n\treturn 0;\n};\n\n/** Deploys through `POST /deploy`, offering a full download when only one can deploy. */\nconst deployAtOnce = async (\n\tagent: AgentClient,\n\trelease: Parameters<AgentClient[\"deploy\"]>[0],\n\tsettings: Omit<DeployOptions, \"deployment\">,\n\tapproval: Approval,\n) => {\n\tconst deploying = timedProgress();\n\ttry {\n\t\treturn await agent.deploy(release, settings, deploying);\n\t} catch (error) {\n\t\tif (\n\t\t\t!(error instanceof AgentOperationError && error.downloadRequired) ||\n\t\t\t!(\n\t\t\t\tapproval.yes ||\n\t\t\t\t(await approval.confirm(\n\t\t\t\t\t`${error.message}. A full download stops the running application while it loads. Download now?`,\n\t\t\t\t))\n\t\t\t)\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\t\treturn agent.deploy(\n\t\t\trelease,\n\t\t\t{ ...settings, download: true },\n\t\t\ttimedProgress(),\n\t\t);\n\t}\n};\n\n/** The deployments `GET /api/deployments` answers, newest first, with the running and last healthy ones. */\ninterface DeploymentList {\n\tdeployments: DeploymentRecord[];\n\tcurrent: string | null;\n\tlastGood: string | null;\n}\n\n/**\n * Where `tsplc rollback` goes without an id: the newest deployment before the running one that\n * ran healthy with another release. Without a running one, the last healthy one.\n */\nexport const rollbackTarget = ({\n\tdeployments,\n\tcurrent,\n\tlastGood,\n}: DeploymentList) => {\n\tconst index = deployments.findIndex(({ id }) => id === current);\n\tconst running = deployments[index];\n\tif (!running) {\n\t\treturn deployments.find(({ id }) => id === lastGood);\n\t}\n\treturn deployments\n\t\t.slice(index + 1)\n\t\t.find(\n\t\t\t(deployment) =>\n\t\t\t\tdeployment.state === \"ready\" &&\n\t\t\t\tdeployment.activeFrom !== null &&\n\t\t\t\tdeployment.release !== running.release,\n\t\t);\n};\n\nconst age = (from: string, now: number) => {\n\tconst seconds = Math.max(0, Math.round((now - Date.parse(from)) / 1000));\n\tif (seconds < 60) {\n\t\treturn `${seconds}s`;\n\t}\n\tif (seconds < 3600) {\n\t\treturn `${Math.floor(seconds / 60)}m`;\n\t}\n\tif (seconds < 48 * 3600) {\n\t\treturn `${Math.floor(seconds / 3600)}h`;\n\t}\n\treturn `${Math.floor(seconds / 86400)}d`;\n};\n\nconst commitLabel = (git: GitSource | null) =>\n\tgit ? `${git.commit.slice(0, 7)}${git.dirty ? \"*\" : \"\"}` : \"-\";\n\nconst requester = ({ requestedBy }: DeploymentRecord) =>\n\trequestedBy.user && requestedBy.host\n\t\t? `${requestedBy.user}@${requestedBy.host}`\n\t\t: (requestedBy.user ?? requestedBy.identity.name);\n\n/** `tsplc deployments`: the agent's deployments, newest first, or as JSON. */\nexport const printDeployments = async (\n\tagent: AgentClient,\n\tflags: { format?: \"json\" | \"text\" },\n) => {\n\tconst list = await agent.deployments();\n\tif (flags.format === \"json\") {\n\t\tconsole.log(JSON.stringify({ ok: true, ...list }));\n\t\treturn;\n\t}\n\tif (!list.deployments.length) {\n\t\tconsole.log(\"No deployments yet.\");\n\t\treturn;\n\t}\n\tconst now = Date.now();\n\tconst rows = [\n\t\t[\"ID\", \"STATE\", \"AGE\", \"RELEASE\", \"COMMIT\", \"BY\", \"\"],\n\t\t...list.deployments.map((deployment) => [\n\t\t\tdeployment.id,\n\t\t\tdeployment.state,\n\t\t\tage(deployment.createdAt, now),\n\t\t\tdeployment.release,\n\t\t\tcommitLabel(deployment.git),\n\t\t\trequester(deployment),\n\t\t\t[\n\t\t\t\tdeployment.id === list.current ? \"current\" : \"\",\n\t\t\t\tdeployment.id === list.lastGood ? \"last good\" : \"\",\n\t\t\t]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(\", \"),\n\t\t]),\n\t];\n\tconst widths = rows[0]?.map((_, column) =>\n\t\tMath.max(...rows.map((row) => row[column]?.length ?? 0)),\n\t);\n\tfor (const row of rows) {\n\t\tconsole.log(\n\t\t\trow\n\t\t\t\t.map((cell, column) => cell.padEnd(widths?.[column] ?? 0))\n\t\t\t\t.join(\" \")\n\t\t\t\t.trimEnd(),\n\t\t);\n\t}\n};\n\n/** `tsplc rollback [id]`: deploys that deployment's release again, by default the last good one before the running one. */\nexport const rollBack = async (\n\tagent: AgentClient,\n\tid: string | undefined,\n\tfollow: Follow,\n) => {\n\tconst target = id ?? rollbackTarget(await agent.deployments())?.id;\n\tif (!target) {\n\t\tthrow new Error(\n\t\t\t\"No earlier healthy deployment to roll back to; name one: tsplc rollback <id>\",\n\t\t);\n\t}\n\tconsole.log(`Rolling back to ${target}…`);\n\treturn queued(agent, await agent.rollback(target), follow);\n};\n\n/** `tsplc redeploy <id>`: deploys that deployment's release again. */\nexport const redeploy = async (\n\tagent: AgentClient,\n\tid: string,\n\tmode: DeploymentMode,\n\tfollow: Follow,\n) => queued(agent, await agent.redeploy(id, mode), follow);\n\n/** The command that opens a URL in the desktop's browser, by platform. */\nconst openers: Partial<Record<NodeJS.Platform, string[]>> = {\n\tdarwin: [\"open\"],\n\twin32: [\"cmd\", \"/c\", \"start\", \"\"],\n};\n\n/** `tsplc dashboard`: prints the agent's dashboard, and opens it when someone is at the terminal. */\nexport const openDashboard = (agent: AgentClient, interactive: boolean) => {\n\tconst url = new URL(\"/\", agent.url).href;\n\tconsole.log(url);\n\tif (!interactive) {\n\t\treturn;\n\t}\n\tconst [command = \"xdg-open\", ...args] = openers[process.platform] ?? [\n\t\t\"xdg-open\",\n\t];\n\t// Without a desktop to open it on, the printed URL is the answer.\n\tspawn(command, [...args, url], { stdio: \"ignore\", detached: true })\n\t\t.on(\"error\", () => {})\n\t\t.unref();\n};\n",
9
- "import { ask } from \"@tsplc/agent\";\n\nexport const choose = async <T>(\n\tquestion: string,\n\titems: readonly T[],\n\tlabel: (item: T) => string,\n) => {\n\titems.forEach((item, index) => {\n\t\tconsole.log(` ${index + 1}. ${label(item)}`);\n\t});\n\twhile (true) {\n\t\tconst item =\n\t\t\titems[Number(await ask(`${question} [1-${items.length}]: `)) - 1];\n\t\tif (item !== undefined) {\n\t\t\treturn item;\n\t\t}\n\t}\n};\n\nexport const confirm = async (question: string, flags: { yes?: boolean }) =>\n\tflags.yes || /^y(es)?$/i.test(await ask(`${question} [y/N]: `));\n\nexport const progress = (message: string) => console.log(` ${message}`);\n\n/** Prints progress with the minutes and seconds since it was made, so the slow steps show. */\nexport const timedProgress = () => {\n\tconst start = Date.now();\n\treturn (message: string) => {\n\t\tconst seconds = Math.round((Date.now() - start) / 1000);\n\t\tprogress(\n\t\t\t`${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, \"0\")} ${message}`,\n\t\t);\n\t};\n};\n",
5
+ "#!/usr/bin/env bun\nimport { existsSync } from \"node:fs\";\nimport { type ParseArgsOptionsConfig, parseArgs } from \"node:util\";\nimport { formatDiagnostic, hasErrors } from \"@tsplc/compiler/ir\";\nimport { agentTokenEnv, agentUrlEnv, loadTsplcConfig } from \"@tsplc/config\";\nimport { opcuaPort } from \"@tsplc/config/build\";\nimport {\n\tconfigFileName,\n\temittedStDirectory,\n} from \"@tsplc/config/project-files\";\nimport { debugManifestFile } from \"@tsplc/debug/manifest\";\nimport { z } from \"zod\";\nimport { debugOptions, debugUsage, serveProjectDebugger } from \"./debugger\";\nimport { type Flags, type OutputFormat, outputFormatSchema } from \"./flags\";\nimport {\n\tconnect,\n\tisPlantCommand,\n\ttype PlantCommand,\n\tplantOptions,\n\trunPlantCommand,\n} from \"./plant\";\nimport {\n\ttype CommandResult,\n\tcheckProjectFlags,\n\tDiagnosticFailure,\n\tisProjectCommand,\n\tprojectOptions,\n\trunProjectCommand,\n} from \"./project-commands\";\n\nconst usage = `tsplc install|typegen|check|build|run|download|online-change|inspect|clean|configure [--config ${configFileName}] [--target name] [--plc|--server] [--simulate] [--runtime] [--emit-only] [--format json] [--read symbol]\n [--frozen-lockfile] [--check] [--initialize-user]\n\nRun the TypeScript program in Bun instead of CODESYS, with OPC UA on opc.tcp://127.0.0.1:${opcuaPort}:\n tsplc run --simulate --bun [--foreground] [--target name]\n\nPlant agent (the target's agent, else ${agentUrlEnv}; ${agentTokenEnv}):\n tsplc deploy [--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait]\n tsplc deployments [--format json] | dashboard\n tsplc rollback [id] [--wait] | redeploy <id> [--review] [--wait]\n (--wait follows the deployment and exits 2 while it waits for approval; -y approves)\n tsplc target | status | login | logout\n tsplc vars [path] | read <expression>... | write <expression> <value>\n tsplc force <expression> <value> | unforce [expression]... [--restore]\n tsplc start | stop | reset warm|cold (-y skips confirmations)\n tsplc restart [warm|cold] resets and starts the application, with or without a login\n\nDebugger, on http://127.0.0.1, for the built ${emittedStDirectory}/${debugManifestFile}; it reads through\nthe plant agent's login (${agentUrlEnv}, ${agentTokenEnv}), or --opcua at config monitor:\n tsplc debug ${debugUsage}`;\n\n/** Every command's flags, and those of the CLI itself. */\nconst options = {\n\tconfig: { type: \"string\" },\n\ttarget: { type: \"string\" },\n\thelp: { type: \"boolean\", short: \"h\" },\n\tformat: { type: \"string\" },\n\t...projectOptions,\n\t...plantOptions,\n\t...debugOptions,\n} as const satisfies ParseArgsOptionsConfig;\n\ntype Values = Omit<Flags<typeof options>, \"format\"> & { format?: OutputFormat };\n\n/**\n * The `--format` the command line names, read before it is fully parsed so a command that fails\n * to parse still answers in that format. A positional `json` is an argument, not a format.\n */\nconst requestedFormat = (argv: readonly string[]) => {\n\tconst index = argv.findIndex(\n\t\t(argument) => argument === \"--format\" || argument.startsWith(\"--format=\"),\n\t);\n\tconst flag = argv[index];\n\tif (index < 0 || flag === undefined) {\n\t\treturn undefined;\n\t}\n\treturn flag === \"--format\" ? argv[index + 1] : flag.slice(\"--format=\".length);\n};\n\nconst outputFormat = (format: string | undefined) => {\n\tconst parsed = outputFormatSchema.optional().safeParse(format);\n\tif (!parsed.success) {\n\t\tthrow new Error(\"--format must be json or text.\");\n\t}\n\treturn parsed.data;\n};\n\n/** `tsplc debug`: serves the debugger until interrupted. */\nconst debug = async (args: string[], values: Values, file: string) => {\n\tif (args.length) {\n\t\tthrow new Error(`Usage: tsplc debug ${debugUsage}`);\n\t}\n\tawait serveProjectDebugger(\n\t\tawait loadTsplcConfig(file, {\n\t\t\tenv: process.env,\n\t\t\ttarget: values.target,\n\t\t\tforAgent: false,\n\t\t}),\n\t\tvalues,\n\t);\n\treturn 0;\n};\n\n/** A plant command, against the target's agent in a project and the environment's elsewhere. */\nconst plant = async (\n\tcommand: PlantCommand,\n\targs: string[],\n\tvalues: Values,\n\tfile: string,\n) => {\n\tconst load = () =>\n\t\tloadTsplcConfig(file, {\n\t\t\tenv: process.env,\n\t\t\ttarget: values.target,\n\t\t\tforAgent: true,\n\t\t});\n\tconst loaded = existsSync(file) ? await load() : undefined;\n\tconst env = loaded?.env ?? process.env;\n\tconst outcome = await runPlantCommand(connect(env), command, args, values, {\n\t\tload: loaded ? async () => loaded : load,\n\t\tenvironment: env,\n\t\tinteractive: process.stdin.isTTY === true,\n\t});\n\tif (!outcome) {\n\t\treturn 0;\n\t}\n\treturn \"exitCode\" in outcome\n\t\t? outcome.exitCode\n\t\t: report(outcome, values.format);\n};\n\nasync function main() {\n\tconst { values: parsed, positionals } = parseArgs({\n\t\tallowPositionals: true,\n\t\toptions,\n\t});\n\tconst values = { ...parsed, format: outputFormat(parsed.format) };\n\tconst [name, ...args] = positionals;\n\tconst file = values.config ?? configFileName;\n\tif (!name || values.help) {\n\t\tconsole.log(usage);\n\t\treturn 0;\n\t}\n\tif (name === \"debug\") {\n\t\treturn debug(args, values, file);\n\t}\n\tif (isPlantCommand(name)) {\n\t\treturn plant(name, args, values, file);\n\t}\n\tif (args.length) {\n\t\tthrow new Error(\"Specify one command.\");\n\t}\n\tif (!isProjectCommand(name)) {\n\t\tthrow new Error(`Unknown command ${name}.`);\n\t}\n\tcheckProjectFlags(name, values);\n\treturn report(\n\t\tawait runProjectCommand(name, file, values, process.env),\n\t\tvalues.format,\n\t);\n}\n\nfunction report(result: CommandResult, format: OutputFormat | undefined) {\n\tconst diagnostics = result.diagnostics ?? [];\n\tconst ok = !hasErrors(diagnostics);\n\tif (format === \"json\") {\n\t\tconsole.log(JSON.stringify({ ok, ...result }));\n\t} else {\n\t\tfor (const diagnostic of diagnostics) {\n\t\t\tconsole.error(formatDiagnostic(diagnostic));\n\t\t}\n\t\tfor (const [expression, value] of Object.entries(result.values ?? {})) {\n\t\t\tconsole.log(`${expression} = ${value}`);\n\t\t}\n\t\tif (ok) {\n\t\t\tconsole.log(\"tsPLC completed.\");\n\t\t}\n\t}\n\treturn ok ? 0 : 1;\n}\n\nfunction causeMessage(cause: unknown) {\n\tif (cause instanceof z.ZodError) {\n\t\treturn z.prettifyError(cause);\n\t}\n\treturn cause instanceof Error ? cause.message : String(cause);\n}\n\ntry {\n\tprocess.exitCode = await main();\n} catch (cause) {\n\tconst json = requestedFormat(process.argv.slice(2)) === \"json\";\n\tif (cause instanceof DiagnosticFailure) {\n\t\tprocess.exitCode = report(cause.result, json ? \"json\" : undefined);\n\t} else {\n\t\tconst message = causeMessage(cause);\n\t\tif (json) {\n\t\t\tconsole.log(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tok: false,\n\t\t\t\t\tdiagnostics: [\n\t\t\t\t\t\t{ origin: \"config\", code: \"PLC5003\", severity: \"error\", message },\n\t\t\t\t\t],\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\tconsole.error(message);\n\t\t}\n\t\tprocess.exitCode = 1;\n\t}\n}\n",
6
+ "import { existsSync } from \"node:fs\";\nimport { relative, resolve } from \"node:path\";\nimport type { ParseArgsOptionsConfig } from \"node:util\";\nimport type { AgentClient } from \"@tsplc/agent/client\";\nimport {\n\tagentUrlEnv,\n\ttype LoadedConfig,\n\tserverBaseUrl,\n\tserverTokenEnv,\n} from \"@tsplc/config\";\nimport { tcpPort } from \"@tsplc/config/build\";\nimport {\n\temittedStDirectory,\n\tgeneratedDirectory,\n} from \"@tsplc/config/project-files\";\nimport {\n\tcreateDebugger,\n\tcreateOpcUaAdapter,\n\tloadDebugBuild,\n\tloginReader,\n\topcUaConnection,\n\tserveDebugger,\n} from \"@tsplc/debug\";\nimport { debugManifestFile } from \"@tsplc/debug/manifest\";\nimport { type Flags, flag } from \"./flags\";\nimport { connect, readThroughAgent } from \"./plant\";\n\ntype Monitor = NonNullable<LoadedConfig[\"config\"][\"monitor\"]>;\n\n/** Where the debugger serves without `--port`. */\nconst debuggerPort = 4870;\n\n/** The flags of `tsplc debug`. */\nexport const debugOptions = {\n\tport: { type: \"string\" },\n\t\"server-url\": { type: \"string\" },\n\topcua: flag,\n} as const satisfies ParseArgsOptionsConfig;\n\nexport const debugUsage = `[--target name] [--port ${debuggerPort}] [--server-url url] [--opcua]`;\n\n/**\n * Serves the debugger for the project's last build until interrupted. It reads the controller\n * through the plant agent's login, or with `--opcua` at the config's `monitor` endpoint, and\n * follows the server's telemetry and requests when the server's base URL (`--server-url`, or\n * `server.baseUrlEnv`) and the PLC's bearer token are in the config's environment.\n */\nexport async function serveProjectDebugger(\n\t{ config, root, env }: LoadedConfig,\n\tflags: Flags<typeof debugOptions>,\n) {\n\tif (flags.opcua && !config.monitor) {\n\t\tthrow new Error(\n\t\t\t\"Configure monitor with the controller's OPC UA endpoint to use --opcua.\",\n\t\t);\n\t}\n\tconst reader: { monitor: Monitor } | { agent: AgentClient } =\n\t\tflags.opcua && config.monitor\n\t\t\t? { monitor: config.monitor }\n\t\t\t: { agent: connect(env) };\n\tconst file = resolve(root, emittedStDirectory, debugManifestFile);\n\tif (!existsSync(file)) {\n\t\tthrow new Error(\n\t\t\t`No debug manifest at ${relative(process.cwd(), file)}: build the program first, with tsplc build or tsplc build --emit-only.`,\n\t\t);\n\t}\n\tconst port = tcpPort.safeParse(Number(flags.port ?? debuggerPort));\n\tif (!port.success) {\n\t\tthrow new Error(\"--port must be a TCP port.\");\n\t}\n\tconst serverUrl = flags[\"server-url\"] ?? serverBaseUrl(config, env);\n\tconst tokenEnv = serverTokenEnv(config);\n\tconst token = tokenEnv && env[tokenEnv];\n\tconst log = (message: string) =>\n\t\tconsole.log(`${new Date().toISOString()} ${message}`);\n\tconst build = await loadDebugBuild(file);\n\tconst debug = await createDebugger({\n\t\t...build,\n\t\t...(\"monitor\" in reader\n\t\t\t? {\n\t\t\t\t\t// An OPC UA endpoint reports no forced list.\n\t\t\t\t\tadapter: createOpcUaAdapter(\n\t\t\t\t\t\topcUaConnection(reader.monitor, { root, env }),\n\t\t\t\t\t),\n\t\t\t\t\tforced: null,\n\t\t\t\t}\n\t\t\t: loginReader(build.manifest, {\n\t\t\t\t\tread: readThroughAgent(reader.agent),\n\t\t\t\t\tstatus: async () => (await reader.agent.status()).login,\n\t\t\t\t\tendpoint: `the plant agent at ${env[agentUrlEnv]}`,\n\t\t\t\t})),\n\t\tstateDirectory: resolve(root, generatedDirectory, \"debug\"),\n\t\twatch: config.debug?.watch ?? {},\n\t\t...(serverUrl && token && { server: { url: serverUrl, token } }),\n\t\tprojectRoot: root,\n\t\tlog,\n\t});\n\tconst server = serveDebugger(debug, { port: port.data, log });\n\tconsole.log(`tsPLC debugger at ${server.url}`);\n\tif (!serverUrl || !token) {\n\t\tconsole.log(\n\t\t\t\"Not following the server's telemetry and requests: set server.baseUrlEnv or --server-url, and the server's bearer token variable.\",\n\t\t);\n\t}\n\tawait new Promise((stopped) => {\n\t\tprocess.once(\"SIGINT\", stopped);\n\t\tprocess.once(\"SIGTERM\", stopped);\n\t});\n\tawait server.stop(true);\n\tawait debug.close();\n}\n",
7
+ "import type { ParseArgsOptionsConfig, parseArgs } from \"node:util\";\nimport { z } from \"zod\";\n\n/** The flags `options` declares, as `parseArgs` reads them. */\nexport type Flags<Options extends ParseArgsOptionsConfig> = ReturnType<\n\ttypeof parseArgs<{ options: Options }>\n>[\"values\"];\n\n/** A flag that takes no value. */\nexport const flag = { type: \"boolean\" } as const;\n\n/** `--format`: JSON results on standard output, or text. */\nexport const outputFormatSchema = z.enum([\"json\", \"text\"]);\nexport type OutputFormat = z.infer<typeof outputFormatSchema>;\n",
8
+ "import type { ParseArgsOptionsConfig } from \"node:util\";\nimport {\n\task,\n\taskCredentials,\n\ttype Credentials,\n\ttype Target,\n\ttype Variable,\n} from \"@tsplc/agent\";\nimport { type AgentClient, createAgentClient } from \"@tsplc/agent/client\";\nimport { type LoginCommand, type LoginResult, resetLabel } from \"@tsplc/build\";\nimport type { Diagnostic } from \"@tsplc/compiler/ir\";\nimport {\n\tagentTokenEnv,\n\tagentUrlEnv,\n\ttype Environment,\n\ttype LoadedConfig,\n\ttype PlantVariables,\n\treleaseEnvironment,\n} from \"@tsplc/config\";\nimport { runtimePort } from \"@tsplc/config/build\";\nimport { LoginUnavailable, noLogin } from \"@tsplc/debug\";\nimport { isWithin } from \"@tsplc/iec/st\";\nimport { arrayIndex, symbolPathSegments } from \"@tsplc/opcua/contract\";\nimport { controllerRestartSchema } from \"@tsplc/server/plant-agent\";\nimport { z } from \"zod\";\nimport {\n\ttype Approval,\n\ttype Follow,\n\topenDashboard,\n\tprintDeployments,\n\tredeploy,\n\trollBack,\n\tsubmitDeployment,\n} from \"./deployments\";\nimport { type Flags, flag, type OutputFormat } from \"./flags\";\nimport { gitSource } from \"./git\";\nimport { prepareRelease } from \"./release\";\nimport {\n\tchoose,\n\tconfirm,\n\tconfirmOrCancel,\n\tprogress,\n\ttimedProgress,\n} from \"./terminal\";\n\n/** The flags of the plant commands. */\nexport const plantOptions = {\n\tdownload: flag,\n\treview: flag,\n\twait: flag,\n\t\"initialize-user\": flag,\n\trestore: flag,\n\tselect: flag,\n\tsimulate: flag,\n\tyes: { type: \"boolean\", short: \"y\" },\n\t\"frozen-lockfile\": flag,\n} as const satisfies ParseArgsOptionsConfig;\n\nexport type PlantFlags = Flags<typeof plantOptions> & { format?: OutputFormat };\n\n/** The plant agent named by `agentUrlEnv` and `agentTokenEnv` in `env`, where a target's agent sets the URL. */\nexport const connect = (env: Record<string, string | undefined>) => {\n\tconst environment = z\n\t\t.object({\n\t\t\t[agentUrlEnv]: z.url({\n\t\t\t\terror: `Configure the target's agent, or set ${agentUrlEnv} to the plant agent, such as http://plant-pc:4850`,\n\t\t\t}),\n\t\t\t[agentTokenEnv]: z.string({\n\t\t\t\terror: `Set ${agentTokenEnv} to the plant agent's token`,\n\t\t\t}),\n\t\t})\n\t\t.parse(env);\n\treturn createAgentClient({\n\t\turl: environment[agentUrlEnv],\n\t\ttoken: environment[agentTokenEnv],\n\t});\n};\n\n/**\n * Reads through the agent's open login, as `tsplc read` does, without opening one: the\n * debugger has no controller credentials.\n */\nexport const readThroughAgent =\n\t(agent: AgentClient) =>\n\tasync ([first, ...rest]: string[]) => {\n\t\tif (!first) {\n\t\t\treturn {};\n\t\t}\n\t\ttry {\n\t\t\tconst result = await agent.command({\n\t\t\t\tcommand: \"read\",\n\t\t\t\texpressions: [first, ...rest],\n\t\t\t});\n\t\t\tif (!(\"values\" in result)) {\n\t\t\t\tthrow new Error(\"The agent answered a read without values\");\n\t\t\t}\n\t\t\treturn result.values;\n\t\t} catch (error) {\n\t\t\tconst { login } = await agent.status();\n\t\t\tif (!login) {\n\t\t\t\tthrow new LoginUnavailable(noLogin, { cause: error });\n\t\t\t}\n\t\t\tif (\"error\" in login) {\n\t\t\t\tthrow new Error(login.error, { cause: error });\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\nconst selectTarget = async (agent: AgentClient): Promise<Target> => {\n\tconst interfaces = await agent.interfaces();\n\tif (!interfaces.length) {\n\t\tthrow new Error(\"The plant PC has no IPv4 network.\");\n\t}\n\tconst network =\n\t\tinterfaces.length === 1 && interfaces[0]\n\t\t\t? interfaces[0]\n\t\t\t: await choose(\n\t\t\t\t\t\"Which network is the controller on?\",\n\t\t\t\t\tinterfaces,\n\t\t\t\t\t(item) => `${item.name} ${item.address}/${item.prefixLength}`,\n\t\t\t\t);\n\tconsole.log(\n\t\t`Scanning ${network.address}/${network.prefixLength} for CODESYS controllers…`,\n\t);\n\tconst found = await agent.discover(network.name);\n\tconst manual = { address: \"\", port: runtimePort, hostname: null };\n\tconst choice = await choose(\n\t\t\"Which controller?\",\n\t\t[...found, manual],\n\t\t(item) =>\n\t\t\titem === manual\n\t\t\t\t? \"Enter an address\"\n\t\t\t\t: `${item.address}${item.hostname ? ` (${item.hostname})` : \"\"}`,\n\t);\n\tconst host =\n\t\tchoice === manual ? await ask(\"Controller address: \") : choice.address;\n\treturn agent.setTarget({ host, port: choice.port });\n};\n\n/**\n * The controller user to send: TSPLC_CONTROLLER_USERNAME and TSPLC_CONTROLLER_PASSWORD from\n * `environment`, else null for the user stored on the agent, else what `prompt` asks for. Initializing\n * the controller's user creates the one sent, so it never leaves it to the stored one.\n */\nexport const controllerCredentials = async (\n\tenvironment: Environment,\n\tagent: { stored: boolean; initializeUser: boolean },\n\tprompt: () => Promise<Credentials>,\n): Promise<Credentials | null> => {\n\tconst username = environment.TSPLC_CONTROLLER_USERNAME;\n\tconst password = environment.TSPLC_CONTROLLER_PASSWORD;\n\tif (username && password) {\n\t\treturn { username, password };\n\t}\n\tif (username || password) {\n\t\tthrow new Error(\n\t\t\t\"Set both TSPLC_CONTROLLER_USERNAME and TSPLC_CONTROLLER_PASSWORD, or neither.\",\n\t\t);\n\t}\n\treturn agent.stored && !agent.initializeUser ? null : prompt();\n};\n\n/** The plant PC's variables and secrets by name, as `variables A, B and secret C`, or null when it holds none. */\nconst plantSummary = ({ values, secrets }: PlantVariables) => {\n\tconst named = (noun: string, names: readonly string[]) =>\n\t\tnames.length\n\t\t\t? `${noun}${names.length === 1 ? \"\" : \"s\"} ${names.join(\", \")}`\n\t\t\t: null;\n\tconst parts = [\n\t\tnamed(\"variable\", Object.keys(values)),\n\t\tnamed(\"secret\", secrets),\n\t].filter((part) => part !== null);\n\treturn parts.length ? parts.join(\" and \") : null;\n};\n\nconst deploy = async (\n\tagent: AgentClient,\n\tloaded: LoadedConfig,\n\tflags: PlantFlags,\n\tfollow: Follow,\n) => {\n\tconst status = await agent.status();\n\tif (status.login) {\n\t\tthrow new Error(\"A login is open; log out before deploying: tsplc logout\");\n\t}\n\tconst target =\n\t\t!status.target || flags.select ? await selectTarget(agent) : status.target;\n\tconst initializeUser = flags[\"initialize-user\"] ?? false;\n\tconst plant = await agent.releaseVariables(\n\t\tloaded.config.secrets?.service ?? null,\n\t);\n\tconst built = releaseEnvironment(loaded.config, loaded, plant);\n\tconsole.log(`Building the release for ${target.host}…`);\n\tconst held = plantSummary(plant);\n\tif (held) {\n\t\tconsole.log(` With the plant PC's ${held}`);\n\t}\n\tconst building = timedProgress();\n\tconst { release, diagnostics } = await prepareRelease(loaded, flags, built);\n\tif (!release) {\n\t\treturn { diagnostics };\n\t}\n\tbuilding(\"Built\");\n\tif (flags.download) {\n\t\tawait confirmOrCancel(\n\t\t\t\"A full download stops the running application while it loads. Continue?\",\n\t\t\tflags,\n\t\t);\n\t}\n\tconst credentials = await controllerCredentials(\n\t\tloaded.env,\n\t\t{ stored: status.credentialsStored, initializeUser },\n\t\taskCredentials,\n\t);\n\tconst settings = {\n\t\tcredentials,\n\t\tdownload: flags.download ?? false,\n\t\tinitializeUser,\n\t};\n\tconsole.log(\n\t\trelease.manifest.server\n\t\t\t? \"Uploading the server and the program…\"\n\t\t\t: \"Uploading the program…\",\n\t);\n\treturn {\n\t\texitCode: await submitDeployment(\n\t\t\tagent,\n\t\t\trelease,\n\t\t\tsettings,\n\t\t\t{\n\t\t\t\tmode: flags.review ? \"review\" : \"apply\",\n\t\t\t\tgit: await gitSource(loaded.root),\n\t\t\t},\n\t\t\tfollow,\n\t\t),\n\t};\n};\n\n/** Opens a login when none is working; it stays open across commands until `tsplc logout`. */\nconst ensureLogin = async (agent: AgentClient, environment: Environment) => {\n\tconst { login, credentialsStored } = await agent.status();\n\tif (login && \"state\" in login) {\n\t\treturn;\n\t}\n\tif (login) {\n\t\tconsole.log(`The open login failed (${login.error}); replacing it.`);\n\t\tawait agent.logout();\n\t}\n\tconst credentials = await controllerCredentials(\n\t\tenvironment,\n\t\t{ stored: credentialsStored, initializeUser: false },\n\t\taskCredentials,\n\t);\n\tconsole.log(\n\t\t\"Logging in. CODESYS takes a few minutes to start; the login stays open until tsplc logout.\",\n\t);\n\tawait agent.login(credentials, progress);\n};\n\n/** The children of `prefix` in the variable tree, with array indexes folded into one range. */\nexport const variableChildren = (\n\tvariables: readonly Variable[],\n\tprefix: string,\n) => {\n\tconst children = new Map<string, { type?: string; leaves: number }>();\n\tfor (const { path, type } of variables) {\n\t\tif (prefix && !isWithin(prefix, path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst rest = path.slice(prefix.length).replace(/^\\./, \"\");\n\t\tif (rest === \"\") {\n\t\t\treturn [{ name: path, type, leaves: 1 }];\n\t\t}\n\t\tconst name = symbolPathSegments(rest)[0] ?? rest;\n\t\tconst child = children.get(name) ?? { leaves: 0 };\n\t\tchildren.set(name, {\n\t\t\ttype: rest === name ? type : undefined,\n\t\t\tleaves: child.leaves + 1,\n\t\t});\n\t}\n\tconst indexes = [...children.keys()]\n\t\t.map(arrayIndex)\n\t\t.filter((index) => index !== undefined);\n\tconst listed = [...children].filter(\n\t\t([name]) => arrayIndex(name) === undefined,\n\t);\n\tif (indexes.length) {\n\t\tconst first = children.get(`[${Math.min(...indexes)}]`);\n\t\tlisted.unshift([\n\t\t\t`[${Math.min(...indexes)}..${Math.max(...indexes)}]`,\n\t\t\tfirst ?? { leaves: 0 },\n\t\t]);\n\t}\n\treturn listed.map(([name, child]) => ({ name, ...child }));\n};\n\nconst printStatus = async (agent: AgentClient) => {\n\tconst status = await agent.status();\n\tconsole.log(\n\t\t`Controller ${status.target ? `${status.target.host}:${status.target.port}` : \"not selected (tsplc target)\"}`,\n\t);\n\tconsole.log(\n\t\t`Release ${status.release ? `${status.release.id}, ${status.release.operation} at ${status.release.deployedAt}` : \"none\"}`,\n\t);\n\tconsole.log(\n\t\t`Server ${status.server ? `${status.server.running ? \"running\" : \"restarting\"} (${status.server.executable})` : \"none\"}`,\n\t);\n\tconst { login } = status;\n\tif (!login) {\n\t\tconsole.log(\"Login closed\");\n\t} else if (\"error\" in login) {\n\t\tconsole.log(`Login failed: ${login.error} (tsplc logout)`);\n\t} else {\n\t\tconsole.log(\n\t\t\t`Login open; application ${login.state}${login.forced.length ? `; forced: ${login.forced.join(\", \")}` : \"\"}`,\n\t\t);\n\t}\n};\n\n/** Lists the deployed release's published variables under `path`, or its roots. */\nconst printVariables = async (agent: AgentClient, path: string | undefined) => {\n\tconst children = variableChildren(await agent.variables(), path ?? \"\");\n\tif (!children.length) {\n\t\tthrow new Error(`No published variable ${path}.`);\n\t}\n\tfor (const child of children) {\n\t\tconsole.log(\n\t\t\t`${child.name.padEnd(32)} ${child.type ?? `${child.leaves} variables`}`,\n\t\t);\n\t}\n};\n\nconst printLogin = (result: LoginResult) => {\n\tif (\"values\" in result) {\n\t\tfor (const [expression, value] of Object.entries(result.values)) {\n\t\t\tconsole.log(`${expression} = ${value}`);\n\t\t}\n\t\treturn;\n\t}\n\tconsole.log(`Application ${result.state}`);\n\tif (result.forced.length) {\n\t\tconsole.log(`Forced: ${result.forced.join(\", \")}`);\n\t}\n};\n\ninterface PlantContext {\n\tagent: AgentClient;\n\targs: string[];\n\tflags: PlantFlags;\n\tproject: {\n\t\tload: () => Promise<LoadedConfig>;\n\t\t/**\n\t\t * Where a login-backed command reads the controller user: the loaded config's environment\n\t\t * in a project, else this process's.\n\t\t */\n\t\tenvironment: Environment;\n\t\t/** Someone at a terminal can answer prompts. */\n\t\tinteractive: boolean;\n\t};\n\tfollow: Follow;\n\t/** Throws the command's usage. */\n\tusage: () => never;\n\t/** Sends a login command through a login that is open, opening one first if none works. */\n\tsend: (command: LoginCommand) => Promise<void>;\n}\n\ninterface PlantCommandEntry {\n\t/** Its arguments and flags, after `tsplc <command>`. */\n\tusage: string;\n\t/** A deployment's compiler diagnostics when the program doesn't compile, the exit code of a command that queues a deployment. */\n\trun: (\n\t\tcontext: PlantContext,\n\t) => Promise<\n\t\t{ diagnostics: readonly Diagnostic[] } | { exitCode: number } | undefined\n\t>;\n}\n\n/** Throws `usage` unless the command has no arguments. */\nconst none = ({ args, usage }: PlantContext) => {\n\tif (args.length) {\n\t\tusage();\n\t}\n};\n\nconst plantCommands = {\n\tdeploy: {\n\t\tusage:\n\t\t\t\"[--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait] [-y]\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tconst { agent, project, flags, follow } = context;\n\t\t\treturn deploy(agent, await project.load(), flags, follow);\n\t\t},\n\t},\n\tdeployments: {\n\t\tusage: \"[--format json]\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tawait printDeployments(context.agent, context.flags);\n\t\t\treturn undefined;\n\t\t},\n\t},\n\trollback: {\n\t\tusage: \"[id] [--wait] [-y]\",\n\t\trun: async ({ agent, args, follow, usage }) => {\n\t\t\tif (args.length > 1) {\n\t\t\t\tusage();\n\t\t\t}\n\t\t\treturn { exitCode: await rollBack(agent, args[0], follow) };\n\t\t},\n\t},\n\tredeploy: {\n\t\tusage: \"<id> [--review] [--wait] [-y]\",\n\t\trun: async ({ agent, args: [id, ...extra], flags, follow, usage }) => {\n\t\t\tif (!id || extra.length) {\n\t\t\t\treturn usage();\n\t\t\t}\n\t\t\treturn {\n\t\t\t\texitCode: await redeploy(\n\t\t\t\t\tagent,\n\t\t\t\t\tid,\n\t\t\t\t\tflags.review ? \"review\" : \"apply\",\n\t\t\t\t\tfollow,\n\t\t\t\t),\n\t\t\t};\n\t\t},\n\t},\n\tdashboard: {\n\t\tusage: \"\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\topenDashboard(context.agent, context.project.interactive);\n\t\t\treturn undefined;\n\t\t},\n\t},\n\ttarget: {\n\t\tusage: \"\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tconst target = await selectTarget(context.agent);\n\t\t\tconsole.log(`Deployments now go to ${target.host}:${target.port}.`);\n\t\t\treturn undefined;\n\t\t},\n\t},\n\tstatus: {\n\t\tusage: \"\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tawait printStatus(context.agent);\n\t\t\treturn undefined;\n\t\t},\n\t},\n\tlogin: {\n\t\tusage: \"\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tawait ensureLogin(context.agent, context.project.environment);\n\t\t\tprintLogin(await context.agent.command({ command: \"state\" }));\n\t\t\treturn undefined;\n\t\t},\n\t},\n\tlogout: {\n\t\tusage: \"\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tconst { agent, flags } = context;\n\t\t\tconst { login } = await agent.status();\n\t\t\tconst forced = login && \"forced\" in login ? login.forced : [];\n\t\t\tif (forced.length) {\n\t\t\t\tawait confirmOrCancel(\n\t\t\t\t\t`Forced: ${forced.join(\", \")}. Forces stay on the controller after logout. Log out anyway?`,\n\t\t\t\t\tflags,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst { failure } = await agent.logout();\n\t\t\tconsole.log(\n\t\t\t\tfailure\n\t\t\t\t\t? `The login couldn't log out (${failure}); its container was removed.`\n\t\t\t\t\t: \"Logged out.\",\n\t\t\t);\n\t\t\treturn undefined;\n\t\t},\n\t},\n\tvars: {\n\t\tusage: \"[path]\",\n\t\trun: async ({ agent, args, usage }) => {\n\t\t\tif (args.length > 1) {\n\t\t\t\tusage();\n\t\t\t}\n\t\t\tawait printVariables(agent, args[0]);\n\t\t\treturn undefined;\n\t\t},\n\t},\n\tread: {\n\t\tusage: \"<expression>...\",\n\t\trun: async ({ args: [first, ...rest], send, usage }) => {\n\t\t\tif (!first) {\n\t\t\t\treturn usage();\n\t\t\t}\n\t\t\tawait send({ command: \"read\", expressions: [first, ...rest] });\n\t\t\treturn undefined;\n\t\t},\n\t},\n\twrite: {\n\t\tusage: \"<expression> <value>\",\n\t\trun: (context) => setValue(\"write\", context),\n\t},\n\tforce: {\n\t\tusage: \"<expression> <value>\",\n\t\trun: (context) => setValue(\"force\", context),\n\t},\n\tunforce: {\n\t\tusage: \"[expression]... [--restore]\",\n\t\trun: async ({ args, flags, send }) => {\n\t\t\tawait send({\n\t\t\t\tcommand: \"unforce\",\n\t\t\t\texpressions: args,\n\t\t\t\trestore: flags.restore ?? false,\n\t\t\t});\n\t\t\treturn undefined;\n\t\t},\n\t},\n\tstart: {\n\t\tusage: \"\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tawait context.send({ command: \"start\" });\n\t\t\treturn undefined;\n\t\t},\n\t},\n\tstop: {\n\t\tusage: \"\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tawait confirmOrCancel(\n\t\t\t\t\"Stop the application on the controller?\",\n\t\t\t\tcontext.flags,\n\t\t\t);\n\t\t\tawait context.send({ command: \"stop\" });\n\t\t\treturn undefined;\n\t\t},\n\t},\n\treset: {\n\t\tusage: \"warm|cold\",\n\t\trun: async ({ args, flags, send, usage }) => {\n\t\t\tif (args.length !== 1) {\n\t\t\t\tusage();\n\t\t\t}\n\t\t\tconst kind = controllerRestartSchema.shape.reset.parse(args[0]);\n\t\t\tawait confirmOrCancel(\n\t\t\t\t`Reset the application (${kind})? It stops and reinitializes its variables.`,\n\t\t\t\tflags,\n\t\t\t);\n\t\t\tawait send({ command: \"reset\", kind: resetLabel(kind) });\n\t\t\treturn undefined;\n\t\t},\n\t},\n\trestart: {\n\t\tusage: \"[warm|cold] [-y]\",\n\t\trun: async ({ agent, args, flags, usage }) => {\n\t\t\tif (args.length > 1) {\n\t\t\t\tusage();\n\t\t\t}\n\t\t\tconst reset = controllerRestartSchema.shape.reset.parse(\n\t\t\t\targs[0] ?? \"warm\",\n\t\t\t);\n\t\t\tawait confirmOrCancel(\n\t\t\t\t`Reset the application (${reset}) and start it again? Its variables go back to their initial values${reset === \"warm\" ? \", but for retain ones\" : \"\"}.`,\n\t\t\t\tflags,\n\t\t\t);\n\t\t\tconst { state } = await agent.restartController({ reset });\n\t\t\tconsole.log(\n\t\t\t\t`Reset ${reset}; the application is ${state === \"run\" ? \"running\" : state}.`,\n\t\t\t);\n\t\t\treturn undefined;\n\t\t},\n\t},\n} satisfies Record<string, PlantCommandEntry>;\n\n/** `tsplc write` and `tsplc force`: one expression and its value. */\nasync function setValue(\n\tcommand: \"write\" | \"force\",\n\t{ args: [expression, value, ...extra], send, usage }: PlantContext,\n) {\n\tif (!expression || !value || extra.length) {\n\t\treturn usage();\n\t}\n\tawait send({ command, values: { [expression]: value } });\n\treturn undefined;\n}\n\nexport type PlantCommand = keyof typeof plantCommands;\n\nexport const isPlantCommand = (name: string): name is PlantCommand =>\n\tObject.hasOwn(plantCommands, name);\n\n/**\n * Runs a command against the plant agent. Returns a deployment's compiler diagnostics when the\n * program doesn't compile, and the exit code of a command that queues a deployment.\n */\nexport const runPlantCommand = (\n\tagent: AgentClient,\n\tcommand: PlantCommand,\n\targs: string[],\n\tflags: PlantFlags,\n\tproject: PlantContext[\"project\"],\n) => {\n\tconst entry: PlantCommandEntry = plantCommands[command];\n\tconst approval: Approval = {\n\t\tyes: flags.yes ?? false,\n\t\tinteractive: project.interactive,\n\t\tconfirm,\n\t};\n\treturn entry.run({\n\t\tagent,\n\t\targs,\n\t\tflags,\n\t\tproject,\n\t\tfollow: { wait: flags.wait ?? false, approval },\n\t\tusage: () => {\n\t\t\tthrow new Error(`Usage: tsplc ${command} ${entry.usage}`);\n\t\t},\n\t\tsend: async (loginCommand) => {\n\t\t\tawait ensureLogin(agent, project.environment);\n\t\t\tprintLogin(await agent.command(loginCommand));\n\t\t},\n\t});\n};\n",
9
+ "import { spawn } from \"node:child_process\";\nimport type {\n\tDeploymentMode,\n\tDeploymentRecord,\n\tDeployOptions,\n\tGitSource,\n} from \"@tsplc/agent\";\nimport { type AgentClient, AgentUnreachable } from \"@tsplc/agent/client\";\nimport { describeFinding } from \"@tsplc/build\";\nimport { progress, timedProgress } from \"./terminal\";\n\n/** `tsplc deploy --wait` and the like exit with this while the deployment waits on a person. */\nexport const awaitingApprovalExit = 2;\n\n/** How a command that follows a deployment may ask before it approves one. */\nexport interface Approval {\n\t/** Approve without asking: `--yes`. */\n\tyes: boolean;\n\t/** Someone at a terminal can answer. */\n\tinteractive: boolean;\n\t/** Asks a yes-or-no question. */\n\tconfirm: (question: string) => Promise<boolean>;\n}\n\n/** What a command that queues a deployment does once it is queued. */\nexport interface Follow {\n\t/** Follow it until it finishes: `--wait`. */\n\twait: boolean;\n\tapproval: Approval;\n}\n\n/** How often, a second apart, following a deployment reconnects before it gives up. */\nconst reconnectAttempts = 5;\nconst reconnectDelay = 1000;\n\nconst stateMessage = (record: DeploymentRecord) => {\n\tswitch (record.state) {\n\t\tcase \"queued\":\n\t\t\treturn \"Queued.\";\n\t\tcase \"building\":\n\t\t\treturn \"Building the release…\";\n\t\tcase \"applying\":\n\t\t\treturn record.operation === \"download\"\n\t\t\t\t? \"Downloading the program; the application stops while it loads…\"\n\t\t\t\t: \"Applying the online change…\";\n\t\tcase \"starting\":\n\t\t\treturn \"Starting the server…\";\n\t\tcase \"verifying\":\n\t\t\treturn \"Checking the deployment's health…\";\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n};\n\nconst printFindings = (record: DeploymentRecord) => {\n\tif (!record.findings.length) {\n\t\tprogress(\"No findings.\");\n\t\treturn;\n\t}\n\tfor (const finding of record.findings) {\n\t\tprogress(\n\t\t\t`${finding.refuses ? \"refuses\" : \"note\"}: ${describeFinding(finding)}`,\n\t\t);\n\t}\n};\n\n/** Whether to approve: `--yes` does, a person may, and null when nobody can be asked. */\nconst decide = async (approval: Approval, question: string) => {\n\tif (approval.yes) {\n\t\treturn true;\n\t}\n\tif (!approval.interactive) {\n\t\treturn null;\n\t}\n\treturn approval.confirm(question);\n};\n\n/**\n * Shows what a deployment waits on and approves it when the deployer agrees. False when it is\n * left waiting.\n */\nconst approve = async (\n\tagent: AgentClient,\n\trecord: DeploymentRecord,\n\treason: \"review\" | \"downloadRequired\",\n\t{ url, approval }: { url: string; approval: Approval },\n) => {\n\tconst download = reason === \"downloadRequired\";\n\tif (download) {\n\t\tconsole.log(\n\t\t\t\"Only a full download can deploy this release, and a full download stops the running application while it loads.\",\n\t\t);\n\t} else {\n\t\tconsole.log(\"The review found what the online change would do:\");\n\t}\n\tprintFindings(record);\n\tconst approved = await decide(\n\t\tapproval,\n\t\tdownload ? \"Download now?\" : \"Apply it?\",\n\t);\n\tif (!approved) {\n\t\tconsole.log(\n\t\t\tapproved === null\n\t\t\t\t? `It waits for approval on the dashboard: ${url}`\n\t\t\t\t: `It waits for approval or cancellation on the dashboard: ${url}`,\n\t\t);\n\t\treturn false;\n\t}\n\tawait agent.approve(record.id, { download });\n\tconsole.log(download ? \"Approved the full download.\" : \"Approved.\");\n\treturn true;\n};\n\n/**\n * Follows a deployment until it finishes, printing its log and the states it goes through, and\n * asking for approval when it waits on one. Reconnects from the last log line it printed. The\n * exit code: 0 when it is ready, `awaitingApprovalExit` when it is left waiting; a failed or\n * canceled deployment throws.\n */\nexport const followDeployment = async (\n\tagent: AgentClient,\n\tdeployment: { id: string; url: string },\n\tapproval: Approval,\n): Promise<number> => {\n\tconst seen: {\n\t\tafter: number;\n\t\tstate: DeploymentRecord[\"state\"] | null;\n\t\tapproval: string | null;\n\t\tfailures: number;\n\t} = { after: 0, state: null, approval: null, failures: 0 };\n\n\t/** The exit code once the deployment is done with this command, else undefined. */\n\tconst onRecord = async (record: DeploymentRecord) => {\n\t\tif (record.state !== seen.state) {\n\t\t\tseen.state = record.state;\n\t\t\tconst message = stateMessage(record);\n\t\t\tif (message) {\n\t\t\t\tconsole.log(message);\n\t\t\t}\n\t\t}\n\t\tif (record.state !== \"awaitingApproval\" || !record.approval) {\n\t\t\tseen.approval = null;\n\t\t} else {\n\t\t\tconst asked = `${record.approval.reason}: ${record.approval.message}`;\n\t\t\tif (asked !== seen.approval) {\n\t\t\t\tseen.approval = asked;\n\t\t\t\tconsole.log(record.approval.message);\n\t\t\t\tconst approved = await approve(agent, record, record.approval.reason, {\n\t\t\t\t\turl: deployment.url,\n\t\t\t\t\tapproval,\n\t\t\t\t});\n\t\t\t\tif (!approved) {\n\t\t\t\t\treturn awaitingApprovalExit;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (record.state === \"ready\") {\n\t\t\tconst { health } = record;\n\t\t\tconsole.log(\n\t\t\t\thealth\n\t\t\t\t\t? `Ready: controller ${health.controller}, server ${health.server}, PLC ${health.plc}.${health.detail ? ` ${health.detail}` : \"\"}`\n\t\t\t\t\t: \"Ready.\",\n\t\t\t);\n\t\t\treturn 0;\n\t\t}\n\t\tif (record.state === \"error\") {\n\t\t\tthrow new Error(\n\t\t\t\t`The deployment failed: ${record.error?.message ?? \"no reason given\"}. ${deployment.url}`,\n\t\t\t);\n\t\t}\n\t\tif (record.state === \"canceled\") {\n\t\t\tthrow new Error(`The deployment was canceled. ${deployment.url}`);\n\t\t}\n\t\treturn undefined;\n\t};\n\n\twhile (true) {\n\t\ttry {\n\t\t\tfor await (const event of agent.deploymentEvents(\n\t\t\t\tdeployment.id,\n\t\t\t\tseen.after,\n\t\t\t)) {\n\t\t\t\tseen.failures = 0;\n\t\t\t\tif (event.kind === \"record\") {\n\t\t\t\t\tconst exit = await onRecord(event.record);\n\t\t\t\t\tif (exit !== undefined) {\n\t\t\t\t\t\treturn exit;\n\t\t\t\t\t}\n\t\t\t\t} else if (event.line.seq > seen.after) {\n\t\t\t\t\tseen.after = event.line.seq;\n\t\t\t\t\tprogress(\n\t\t\t\t\t\tevent.line.level === \"info\"\n\t\t\t\t\t\t\t? event.line.message\n\t\t\t\t\t\t\t: `${event.line.level}: ${event.line.message}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof AgentUnreachable)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\t// The stream broke, or ended before the deployment finished.\n\t\tseen.failures += 1;\n\t\tif (seen.failures > reconnectAttempts) {\n\t\t\tthrow new Error(\n\t\t\t\t`Lost the connection to the plant agent; the deployment goes on: ${deployment.url}`,\n\t\t\t);\n\t\t}\n\t\tawait Bun.sleep(reconnectDelay);\n\t}\n};\n\n/** Prints a queued deployment's page, then follows it when asked to. */\nconst queued = async (\n\tagent: AgentClient,\n\tcreated: { id: string; url: string },\n\tfollow: Follow,\n) => {\n\tconsole.log(`Deployment ${created.id} queued: ${created.url}`);\n\tif (!follow.wait) {\n\t\treturn 0;\n\t}\n\treturn followDeployment(agent, created, follow.approval);\n};\n\n/** Uploads a built release as a queued deployment and prints its page. */\nexport const submitDeployment = async (\n\tagent: AgentClient,\n\trelease: Parameters<AgentClient[\"queueDeployment\"]>[0],\n\tsettings: Omit<DeployOptions, \"deployment\">,\n\trequest: { mode: DeploymentMode; git: GitSource | null },\n\tfollow: Follow,\n) => {\n\tconst uploading = timedProgress();\n\tconst created = await agent.queueDeployment(\n\t\trelease,\n\t\t{ ...settings, deployment: request },\n\t\tuploading,\n\t);\n\tuploading(\"Uploaded\");\n\tif (request.mode === \"review\" && !follow.wait) {\n\t\tconsole.log(\"Once reviewed, it waits for approval on its page.\");\n\t}\n\treturn queued(agent, created, follow);\n};\n\n/** The deployments `GET /api/deployments` answers, newest first, with the running and last healthy ones. */\ntype DeploymentList = Awaited<ReturnType<AgentClient[\"deployments\"]>>;\n\n/**\n * Where `tsplc rollback` goes without an id: the newest deployment before the running one that\n * ran healthy with another release. Without a running one, the last healthy one.\n */\nexport const rollbackTarget = ({\n\tdeployments,\n\tcurrent,\n\tlastGood,\n}: DeploymentList) => {\n\tconst index = deployments.findIndex(({ id }) => id === current);\n\tconst running = deployments[index];\n\tif (!running) {\n\t\treturn deployments.find(({ id }) => id === lastGood);\n\t}\n\treturn deployments\n\t\t.slice(index + 1)\n\t\t.find(\n\t\t\t(deployment) =>\n\t\t\t\tdeployment.state === \"ready\" &&\n\t\t\t\tdeployment.activeFrom !== null &&\n\t\t\t\tdeployment.release !== running.release,\n\t\t);\n};\n\nconst age = (from: string, now: number) => {\n\tconst seconds = Math.max(0, Math.round((now - Date.parse(from)) / 1000));\n\tif (seconds < 60) {\n\t\treturn `${seconds}s`;\n\t}\n\tif (seconds < 3600) {\n\t\treturn `${Math.floor(seconds / 60)}m`;\n\t}\n\tif (seconds < 48 * 3600) {\n\t\treturn `${Math.floor(seconds / 3600)}h`;\n\t}\n\treturn `${Math.floor(seconds / 86400)}d`;\n};\n\nconst commitLabel = (git: GitSource | null) =>\n\tgit ? `${git.commit.slice(0, 7)}${git.dirty ? \"*\" : \"\"}` : \"-\";\n\nconst requester = ({ requestedBy }: DeploymentRecord) =>\n\trequestedBy.user && requestedBy.host\n\t\t? `${requestedBy.user}@${requestedBy.host}`\n\t\t: (requestedBy.user ?? requestedBy.identity.name);\n\n/** `tsplc deployments`: the agent's deployments, newest first, or as JSON. */\nexport const printDeployments = async (\n\tagent: AgentClient,\n\tflags: { format?: \"json\" | \"text\" },\n) => {\n\tconst list = await agent.deployments();\n\tif (flags.format === \"json\") {\n\t\tconsole.log(JSON.stringify({ ok: true, ...list }));\n\t\treturn;\n\t}\n\tif (!list.deployments.length) {\n\t\tconsole.log(\"No deployments yet.\");\n\t\treturn;\n\t}\n\tconst now = Date.now();\n\tconst header = [\"ID\", \"STATE\", \"AGE\", \"RELEASE\", \"COMMIT\", \"BY\", \"\"];\n\tconst rows = [\n\t\theader,\n\t\t...list.deployments.map((deployment) => [\n\t\t\tdeployment.id,\n\t\t\tdeployment.state,\n\t\t\tage(deployment.createdAt, now),\n\t\t\tdeployment.release,\n\t\t\tcommitLabel(deployment.git),\n\t\t\trequester(deployment),\n\t\t\t[\n\t\t\t\tdeployment.id === list.current ? \"current\" : \"\",\n\t\t\t\tdeployment.id === list.lastGood ? \"last good\" : \"\",\n\t\t\t]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(\", \"),\n\t\t]),\n\t];\n\tconst widths = header.map((_, column) =>\n\t\tMath.max(...rows.map((row) => row[column]?.length ?? 0)),\n\t);\n\tfor (const row of rows) {\n\t\tconsole.log(\n\t\t\trow\n\t\t\t\t.map((cell, column) => cell.padEnd(widths[column] ?? 0))\n\t\t\t\t.join(\" \")\n\t\t\t\t.trimEnd(),\n\t\t);\n\t}\n};\n\n/** `tsplc rollback [id]`: deploys that deployment's release again, by default the last good one before the running one. */\nexport const rollBack = async (\n\tagent: AgentClient,\n\tid: string | undefined,\n\tfollow: Follow,\n) => {\n\tconst target = id ?? rollbackTarget(await agent.deployments())?.id;\n\tif (!target) {\n\t\tthrow new Error(\n\t\t\t\"No earlier healthy deployment to roll back to; name one: tsplc rollback <id>\",\n\t\t);\n\t}\n\tconsole.log(`Rolling back to ${target}…`);\n\treturn queued(agent, await agent.rollback(target), follow);\n};\n\n/** `tsplc redeploy <id>`: deploys that deployment's release again. */\nexport const redeploy = async (\n\tagent: AgentClient,\n\tid: string,\n\tmode: DeploymentMode,\n\tfollow: Follow,\n) => queued(agent, await agent.redeploy(id, mode), follow);\n\n/** The command that opens a URL in the desktop's browser, by platform. */\nconst openers: Partial<Record<NodeJS.Platform, string[]>> = {\n\tdarwin: [\"open\"],\n\twin32: [\"cmd\", \"/c\", \"start\", \"\"],\n};\n\n/** `tsplc dashboard`: prints the agent's dashboard, and opens it when someone is at the terminal. */\nexport const openDashboard = (agent: AgentClient, interactive: boolean) => {\n\tconst url = new URL(\"/\", agent.url).href;\n\tconsole.log(url);\n\tif (!interactive) {\n\t\treturn;\n\t}\n\tconst [command = \"xdg-open\", ...args] = openers[process.platform] ?? [\n\t\t\"xdg-open\",\n\t];\n\t// Without a desktop to open it on, the printed URL is the answer.\n\tspawn(command, [...args, url], { stdio: \"ignore\", detached: true })\n\t\t.on(\"error\", () => {})\n\t\t.unref();\n};\n",
10
+ "import { ask } from \"@tsplc/agent\";\n\nexport const choose = async <T>(\n\tquestion: string,\n\titems: readonly T[],\n\tlabel: (item: T) => string,\n) => {\n\titems.forEach((item, index) => {\n\t\tconsole.log(` ${index + 1}. ${label(item)}`);\n\t});\n\twhile (true) {\n\t\tconst item =\n\t\t\titems[Number(await ask(`${question} [1-${items.length}]: `)) - 1];\n\t\tif (item !== undefined) {\n\t\t\treturn item;\n\t\t}\n\t}\n};\n\n/** Asks a yes-or-no question; no unless the answer is yes. */\nexport const confirm = async (question: string) =>\n\t/^y(es)?$/i.test(await ask(`${question} [y/N]: `));\n\n/** Goes on when `--yes` is given or the answer is yes, else stops the command as cancelled. */\nexport const confirmOrCancel = async (\n\tquestion: string,\n\tflags: { yes?: boolean },\n) => {\n\tif (!flags.yes && !(await confirm(question))) {\n\t\tthrow new Error(\"Cancelled.\");\n\t}\n};\n\nexport const progress = (message: string) => console.log(` ${message}`);\n\n/** Prints progress with the minutes and seconds since it was made, so the slow steps show. */\nexport const timedProgress = () => {\n\tconst start = Date.now();\n\treturn (message: string) => {\n\t\tconst seconds = Math.round((Date.now() - start) / 1000);\n\t\tprogress(\n\t\t\t`${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, \"0\")} ${message}`,\n\t\t);\n\t};\n};\n",
10
11
  "import { execFile } from \"node:child_process\";\nimport type { GitSource } from \"@tsplc/agent\";\n\n/** What `git` prints for `args` in `directory`, or null when it fails or isn't installed. */\nconst git = (directory: string, args: readonly string[]) =>\n\tnew Promise<string | null>((resolve) => {\n\t\texecFile(\"git\", args, { cwd: directory }, (error, stdout) => {\n\t\t\tresolve(error ? null : stdout.trim());\n\t\t});\n\t});\n\n/**\n * The commit checked out in `directory`, for a deployment to record. Null outside a git checkout,\n * before its first commit or without git: a deployment never fails for want of it.\n */\nexport const gitSource = async (\n\tdirectory: string,\n): Promise<GitSource | null> => {\n\tconst commit = await git(directory, [\"rev-parse\", \"--verify\", \"HEAD\"]);\n\tif (!commit) {\n\t\treturn null;\n\t}\n\tconst [branch, status, message] = await Promise.all([\n\t\tgit(directory, [\"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"]),\n\t\tgit(directory, [\"status\", \"--porcelain\"]),\n\t\tgit(directory, [\"log\", \"-1\", \"--format=%s\"]),\n\t]);\n\treturn {\n\t\tcommit,\n\t\tbranch: branch || null,\n\t\t// A status that can't be read can't vouch for a clean tree.\n\t\tdirty: status !== \"\",\n\t\tmessage: message || null,\n\t};\n};\n",
11
- "import { existsSync } from \"node:fs\";\nimport { basename, relative, resolve, sep } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { ReleaseManifest } from \"@tsplc/agent\";\nimport type { ReleaseFile } from \"@tsplc/agent/client\";\nimport type { CompileEnvironment } from \"@tsplc/compiler\";\nimport { hasErrors } from \"@tsplc/compiler/ir\";\nimport {\n\tbuildTargetFor,\n\tcontrollerFor,\n\ttype LoadedConfig,\n\tserverTokenEnv,\n} from \"@tsplc/config\";\nimport type { ReleaseConfig } from \"@tsplc/config/build\";\nimport { explainFileName } from \"@tsplc/debug/explain-file\";\nimport { debugManifestFile } from \"@tsplc/debug/manifest\";\nimport { contractVariables, plcContractSchema } from \"@tsplc/opcua/contract\";\nimport { generatedFiles, generateProject } from \"@tsplc/typegen\";\nimport { buildConfigs, buildProject } from \"./project\";\nimport { bundleServer, checkServer } from \"./server\";\n\n/** Every published leaf the generated contract describes, as CODESYS expressions name it. */\nconst releaseVariables = async (\n\tconfig: LoadedConfig[\"config\"],\n\troot: string,\n) => {\n\tif (!config.typegen) {\n\t\treturn [];\n\t}\n\tconst contract = plcContractSchema.parse(\n\t\tawait import(\n\t\t\tpathToFileURL(resolve(root, config.typegen.dir, generatedFiles.contract))\n\t\t\t\t.href\n\t\t),\n\t);\n\treturn contractVariables(contract).map(({ path, type }) => ({ path, type }));\n};\n\n/**\n * Compiles the program and bundles its server into the files `tsplc deploy` uploads: the\n * production program, or with `--simulate` the development one without fieldbus I/O, for a\n * virtual PLC whose inputs a plant simulation writes, as `tsplc run --simulate` builds it.\n */\nexport const prepareRelease = async (\n\tfile: string,\n\tloaded: LoadedConfig,\n\tflags: { simulate?: boolean; \"frozen-lockfile\"?: boolean },\n\tbuilt: {\n\t\t/** What the build reads, with the plant PC's values and placeholders for its secrets. */\n\t\tenv: CompileEnvironment;\n\t\t/** Every plain value the release carries to its server. */\n\t\tvalues: ReleaseManifest[\"values\"];\n\t\t/** The secrets the agent fills in. */\n\t\tsecrets: ReleaseManifest[\"secrets\"];\n\t},\n) => {\n\t// Every step reads the loaded config's environment, so it carries the plant PC's.\n\tconst project: LoadedConfig = { ...loaded, env: built.env };\n\tconst { config, root } = project;\n\tif (!config.compiler) {\n\t\tthrow new Error(\"tsplc deploy deploys tsPLC programs; configure compiler.\");\n\t}\n\tconst command = flags.simulate ? \"run\" : \"deploy\";\n\tconst serverCheck = config.server?.runtime\n\t\t? checkServer(config, root)\n\t\t: undefined;\n\t// A failed PLC build reports its own diagnostics; the check's outcome is read only after a success.\n\tserverCheck?.catch(() => undefined);\n\tconst emitted = await buildProject(file, {\n\t\temitOnly: true,\n\t\tforController: true,\n\t\tfrozenLockfile: flags[\"frozen-lockfile\"],\n\t\t...buildConfigs(project, flags),\n\t\tbuildTarget: buildTargetFor(command),\n\t\tcontroller: controllerFor(config, command),\n\t});\n\tif (hasErrors(emitted.diagnostics)) {\n\t\treturn { diagnostics: emitted.diagnostics };\n\t}\n\tconst settings = emitted.controllerConfig;\n\tif (!settings) {\n\t\tthrow new Error(\"Configure build settings for deployment.\");\n\t}\n\tawait generateProject(file, { loaded: project, targets: emitted.targets });\n\n\tconst portable = (path: string) => path.split(sep).join(\"/\");\n\tconst libraries = (settings.libraries ?? []).map((library) => ({\n\t\t...library,\n\t\trelease: `libraries/${library.sha256}-${basename(library.path)}`,\n\t}));\n\tconst files: ReleaseFile[] = [\n\t\t{ path: \"template.project\", content: Bun.file(settings.template) },\n\t\t...libraries.map((library) => ({\n\t\t\tpath: library.release,\n\t\t\tcontent: Bun.file(library.path),\n\t\t})),\n\t];\n\t// The agent compiles only the ST. Plain TypeScript programs emit their generated modules under `.tsplc/`.\n\tfor await (const source of new Bun.Glob(\"**/*.st\").scan({\n\t\tcwd: settings.sourceDir,\n\t\tdot: true,\n\t})) {\n\t\tfiles.push({\n\t\t\tpath: `st/${portable(source)}`,\n\t\t\tcontent: Bun.file(resolve(settings.sourceDir, source)),\n\t\t});\n\t}\n\t// The agent's debugger reads the program through its debug manifest, and explains it with `explain.json`.\n\tfor (const name of [debugManifestFile, explainFileName]) {\n\t\tconst path = resolve(settings.sourceDir, name);\n\t\tif (existsSync(path)) {\n\t\t\tfiles.push({ path: name, content: Bun.file(path) });\n\t\t}\n\t}\n\tconst serverScript =\n\t\tserverCheck && (await bundleServer(await serverCheck, config, root));\n\tconst server = serverScript\n\t\t? {\n\t\t\t\tpath: `server/${basename(serverScript)}`,\n\t\t\t\tcontent: Bun.file(serverScript),\n\t\t\t}\n\t\t: undefined;\n\tif (server) {\n\t\tfiles.push(server);\n\t}\n\t// Paths are relative to the release. Naming every release field keeps a new build setting\n\t// from reaching the agent, or being left behind, without a decision here.\n\tconst releaseConfig: {\n\t\t[Key in keyof Required<ReleaseConfig>]: ReleaseConfig[Key];\n\t} = {\n\t\tio: {},\n\t\tdeviceTree: settings.deviceTree,\n\t\tcontroller: settings.controller,\n\t\tlibraryReferences: settings.libraryReferences,\n\t\tlibraries: libraries.map(({ release, ...library }) => ({\n\t\t\t...library,\n\t\t\tpath: release,\n\t\t})),\n\t\ttask: settings.task,\n\t\ttasks: settings.tasks,\n\t\tremoveObjects: settings.removeObjects,\n\t\tsymbols: settings.symbols,\n\t\ttimeouts: settings.timeouts,\n\t\ttemplate: \"template.project\",\n\t\tsourceDir: \"st\",\n\t\tentry: `st/${portable(relative(settings.sourceDir, settings.entry))}`,\n\t};\n\tconst manifest: ReleaseManifest = {\n\t\tconfig: releaseConfig,\n\t\tvariables: await releaseVariables(config, root),\n\t\tserver: server?.path,\n\t\tdebug: config.debug,\n\t\tserverTokenEnv: serverTokenEnv(config),\n\t\tsecrets: built.secrets,\n\t\tvalues: built.values,\n\t};\n\treturn { release: { manifest, files } };\n};\n",
12
- "import {\n\tcopyFile,\n\tmkdir,\n\tmkdtemp,\n\trealpath,\n\trm,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { installLibraries, type ProgressOptions } from \"@tsplc/build\";\nimport {\n\tanalyze,\n\ttype CompileEnvironment,\n\tcheckHostConfig,\n} from \"@tsplc/compiler\";\nimport {\n\tbuildCodesys,\n\ttype CodesysPlan,\n\ttype CodesysProject,\n\tcodesysBuildConfig,\n\tdiagnoseCodesys,\n\temitCodesys,\n\tioTargets,\n\tplanCodesys,\n\tpublicationSelectors,\n\ttype SourceMapping,\n} from \"@tsplc/compiler/codesys\";\nimport {\n\ttype Diagnostic,\n\thasErrors,\n\tnormalizeModule,\n\ttype VerifiedCoreModule,\n} from \"@tsplc/compiler/ir\";\nimport {\n\ttype BuildTarget,\n\ttype Controller,\n\tcompilerConfig,\n\ttype LoadedConfig,\n\tloadTsplcConfig,\n\ttype NormalizedConfig,\n\ttype ResolvedTsplcConfig,\n\tsimulationConfig,\n} from \"@tsplc/config\";\nimport { emittedFiles, emittedStDirectory } from \"@tsplc/config/project-files\";\nimport { explainFileName } from \"@tsplc/debug/explain-file\";\nimport { debugManifestFile } from \"@tsplc/debug/manifest\";\nimport {\n\tdeviceTree,\n\tloadHardware,\n\ttype ProjectTargets,\n\tresolveIo,\n} from \"@tsplc/typegen\";\nimport { serviceRoutes } from \"../runtime/launch\";\nimport {\n\tcleanArtifacts,\n\tengineeringDirectory,\n\towned,\n\tpublishArtifacts,\n} from \"./artifacts\";\n\n/** The emitted ST's directory inside the compiler's artifacts directory. */\nconst emittedSt = basename(emittedStDirectory);\n\nconst failure = (\n\torigin: Diagnostic[\"origin\"],\n\tcode: string,\n\tcause: unknown,\n): Diagnostic => ({\n\torigin,\n\tcode,\n\tseverity: \"error\",\n\tmessage: cause instanceof Error ? cause.message : String(cause),\n});\n\n/**\n * `buildProject`'s `loaded` and `configured` options. With `simulate` the build omits fieldbus\n * I/O so a plant simulator can write the inputs; generated types and the debug manifest keep\n * describing the hardware project.\n */\nexport const buildConfigs = (\n\tloaded: LoadedConfig,\n\toptions: { simulate?: boolean },\n) =>\n\toptions.simulate\n\t\t? {\n\t\t\t\tloaded: { ...loaded, config: simulationConfig(loaded.config) },\n\t\t\t\tconfigured: loaded.config,\n\t\t\t}\n\t\t: { loaded };\n\ninterface ProjectOptions {\n\tloaded?: LoadedConfig;\n\tbuildTarget?: BuildTarget;\n\t/** The configuration `loaded` simulates, whose hardware the debug manifest describes. */\n\tconfigured?: ResolvedTsplcConfig;\n\t/**\n\t * The host config check's diagnostics, when the caller ran it before loading the config. The\n\t * check type-checks the config and takes seconds.\n\t */\n\thostConfigDiagnostics?: readonly Diagnostic[];\n\t/** What the program's `env()` calls, endpoints and telemetry read; this process's environment by default. */\n\tenvironment?: CompileEnvironment;\n}\n\n/** Loads the config in `environment`, this process's by default, with its only target's values. */\nconst loadEnvironment = (environment: CompileEnvironment | undefined) => ({\n\tenv: environment ?? process.env,\n\ttarget: undefined,\n\tforAgent: false,\n});\n\nasync function loadProject(\n\tfile: string,\n\t{\n\t\tloaded,\n\t\tbuildTarget,\n\t\tconfigured,\n\t\thostConfigDiagnostics,\n\t\tenvironment,\n\t}: ProjectOptions,\n): Promise<{\n\tconfig?: NormalizedConfig;\n\tconfigFile: string;\n\tshared?: ResolvedTsplcConfig;\n\tproject?: CodesysProject;\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\tlet configFile = resolve(file);\n\ttry {\n\t\tconfigFile = await realpath(configFile);\n\t\tconst diagnostics = hostConfigDiagnostics ?? checkHostConfig(configFile);\n\t\tif (hasErrors(diagnostics)) {\n\t\t\treturn { configFile, diagnostics };\n\t\t}\n\t\tconst { config: shared, env } =\n\t\t\tloaded ??\n\t\t\t(await loadTsplcConfig(configFile, loadEnvironment(environment)));\n\t\tconst root = dirname(configFile);\n\t\tconst catalog = await loadHardware(shared, root);\n\n\t\tconst config = compilerConfig(\n\t\t\tshared,\n\t\t\tresolveIo(shared, catalog),\n\t\t\tbuildTarget,\n\t\t);\n\t\treturn {\n\t\t\tconfigFile,\n\t\t\tshared,\n\t\t\tconfig: { ...config, ...sourceInput(config, root) },\n\t\t\tproject: {\n\t\t\t\troot,\n\t\t\t\tenvironment: env,\n\t\t\t\t...(shared.debug && { debug: shared.debug }),\n\t\t\t\t...(shared.telemetry && { telemetry: shared.telemetry }),\n\t\t\t\t...(shared.server && { server: shared.server }),\n\t\t\t\t...(shared.hmi && { hmi: shared.hmi }),\n\t\t\t\t// A simulation build drops fieldbus IO, but the debugger still shows the hardware it stands in for.\n\t\t\t\thardware: {\n\t\t\t\t\tcatalog: configured ? await loadHardware(configured, root) : catalog,\n\t\t\t\t\tconfig: configured ?? shared,\n\t\t\t\t\ttree: shared.codesys?.deviceTree !== undefined,\n\t\t\t\t},\n\t\t\t},\n\t\t\tdiagnostics,\n\t\t};\n\t} catch (cause) {\n\t\treturn { configFile, diagnostics: [failure(\"config\", \"PLC5003\", cause)] };\n\t}\n}\n\n/** The analyzer's entry points, resolved against the config file's directory. */\nfunction sourceInput(\n\tcompiler: {\n\t\ttsconfig: string;\n\t\tprograms: Record<string, { module: string; export: string }>;\n\t},\n\troot: string,\n) {\n\treturn {\n\t\ttsconfig: resolve(root, compiler.tsconfig),\n\t\tprograms: Object.fromEntries(\n\t\t\tObject.entries(compiler.programs).map(([name, entry]) => [\n\t\t\t\tname,\n\t\t\t\t{ ...entry, module: resolve(root, entry.module) },\n\t\t\t]),\n\t\t),\n\t};\n}\n\n/**\n * I/O keys and publication selectors from analyzed PLC source. It ignores the\n * config's own type errors, so a typo cannot switch off the types that flag it;\n * it is undefined only while the source itself fails analysis.\n */\nexport async function projectTargets(\n\tfile = \"tsplc.config.ts\",\n\toptions: Pick<ProjectOptions, \"loaded\" | \"environment\"> = {},\n): Promise<ProjectTargets | undefined> {\n\tconst configFile = await realpath(resolve(file));\n\tconst { config, env } =\n\t\toptions.loaded ??\n\t\t(await loadTsplcConfig(configFile, loadEnvironment(options.environment)));\n\tif (!config.compiler) {\n\t\treturn undefined;\n\t}\n\tconst source = analyze({\n\t\t...sourceInput(config.compiler, dirname(configFile)),\n\t\tservices: config.server,\n\t\tenvironment: env,\n\t});\n\tconst core = source.module && normalizeModule(source.module).core;\n\treturn core ? coreTargets(core) : undefined;\n}\n\nconst coreTargets = (core: VerifiedCoreModule): ProjectTargets => ({\n\tio: ioTargets(core),\n\tpublication: publicationSelectors(core),\n});\n\nexport async function checkProject(\n\tfile = \"tsplc.config.ts\",\n\toptions: ProjectOptions = {},\n): Promise<{\n\tconfigFile: string;\n\tconfig?: NormalizedConfig;\n\tshared?: ResolvedTsplcConfig;\n\tplan?: CodesysPlan;\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\tconst loaded = await loadProject(file, options);\n\tif (!loaded.config || !loaded.project) {\n\t\treturn loaded;\n\t}\n\n\tconst config = loaded.config;\n\tif (config.target.kind !== \"codesys\") {\n\t\treturn {\n\t\t\t...loaded,\n\t\t\tdiagnostics: [\n\t\t\t\tfailure(\n\t\t\t\t\t\"backend\",\n\t\t\t\t\t\"PLC7001\",\n\t\t\t\t\t`Unsupported target: ${config.target.kind}`,\n\t\t\t\t),\n\t\t\t],\n\t\t};\n\t}\n\n\tconst source = analyze({\n\t\ttsconfig: config.tsconfig,\n\t\tprograms: config.programs,\n\t\tservices: loaded.shared?.server,\n\t\tenvironment: loaded.project.environment,\n\t});\n\tif (!source.module) {\n\t\treturn { ...loaded, diagnostics: source.diagnostics };\n\t}\n\tconst normalized = normalizeModule(source.module);\n\tif (!normalized.core) {\n\t\treturn { ...loaded, diagnostics: normalized.diagnostics };\n\t}\n\n\tconst tasks = config.tasks.map((task) => ({\n\t\tname: task.name,\n\t\tintervalNanoseconds: task.schedule.interval.nanoseconds,\n\t\tpriority: task.priority,\n\t\tprograms: task.programs,\n\t}));\n\tconst planned = planCodesys(\n\t\tnormalized.core,\n\t\t{ tasks },\n\t\tconfig.target.options,\n\t\tloaded.project,\n\t);\n\treturn {\n\t\t...loaded,\n\t\t...planned,\n\t\tdiagnostics: [\n\t\t\t...loaded.diagnostics,\n\t\t\t...source.diagnostics,\n\t\t\t...normalized.diagnostics,\n\t\t\t...planned.diagnostics,\n\t\t],\n\t};\n}\n\n/** The installed libraries and fieldbus device tree a CODESYS project of this program needs. */\nasync function engineeringInputs(\n\tshared: ResolvedTsplcConfig,\n\tconfigFile: string,\n\tbundle: Pick<ReturnType<typeof emitCodesys>, \"ioMappings\">,\n\toptions: { frozen?: boolean },\n) {\n\tconst root = dirname(configFile);\n\tconst tree = await deviceTree(shared, await loadHardware(shared, root));\n\treturn {\n\t\tlibraries: await installLibraries(shared.dependencies, root, options),\n\t\t// The emitted names locate mapped IO; the tree maps their channels.\n\t\tdeviceTree: tree && {\n\t\t\t...tree,\n\t\t\tmappings: bundle.ioMappings.map(({ address, variable }) => ({\n\t\t\t\taddress,\n\t\t\t\tvariable,\n\t\t\t})),\n\t\t},\n\t};\n}\n\nexport async function buildProject(\n\tfile = \"tsplc.config.ts\",\n\toptions: ProjectOptions & {\n\t\temitOnly?: boolean;\n\t\tfrozenLockfile?: boolean;\n\t\tcontroller?: Controller;\n\t\t/** Resolve libraries and the device tree into `controllerConfig` even when only emitting. */\n\t\tforController?: boolean;\n\t} & ProgressOptions = {},\n): Promise<{\n\tdirectory?: string;\n\tstatus?: \"emitted\" | \"vendor-compiled\";\n\tcontrollerConfig?: ReturnType<typeof codesysBuildConfig>;\n\t/** What `projectTargets` reads from the program, from this build's own analysis. */\n\ttargets?: ProjectTargets;\n\t/** The route of each service procedure the program calls, as `serviceRoutes` reads them. */\n\tservices?: Readonly<Record<string, string>>;\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\tlet staging: string | undefined;\n\ttry {\n\t\tconst configFile = await realpath(resolve(file));\n\t\t// Withdraw the previous success receipt before checking the new source.\n\t\t// Old artifacts remain owned and intact until publication succeeds.\n\t\tconst previous = await owned(configFile, true);\n\t\tif (previous.unknown.length) {\n\t\t\tthrow new Error(\n\t\t\t\t`Output contains unrelated files: ${previous.unknown.join(\", \")}`,\n\t\t\t);\n\t\t}\n\n\t\tconst checked = await checkProject(configFile, options);\n\t\tif (!checked.plan || !checked.config) {\n\t\t\treturn { diagnostics: checked.diagnostics };\n\t\t}\n\t\tconst bundle = emitCodesys(checked.plan);\n\t\tif (hasErrors(bundle.diagnostics)) {\n\t\t\treturn { diagnostics: bundle.diagnostics };\n\t\t}\n\t\tconst shared = checked.shared;\n\t\tconst engineering =\n\t\t\tshared && (!options.emitOnly || options.forController)\n\t\t\t\t? await engineeringInputs(shared, configFile, bundle, {\n\t\t\t\t\t\tfrozen: options.frozenLockfile,\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\t\tconst outDir =\n\t\t\tshared?.build && resolve(dirname(configFile), shared.build.outDir);\n\t\tconst controllerConfig = outDir\n\t\t\t? codesysBuildConfig(checked.plan, bundle, {\n\t\t\t\t\tconfigFile,\n\t\t\t\t\tsourceDir: join(previous.output, emittedSt),\n\t\t\t\t\toutDir,\n\t\t\t\t\tcontroller: options.controller,\n\t\t\t\t\t...engineering,\n\t\t\t\t})\n\t\t\t: undefined;\n\n\t\tawait mkdir(previous.root, { recursive: true });\n\t\tstaging = await mkdtemp(join(previous.root, \"stage-\"));\n\t\tconst artifacts = [\n\t\t\t...bundle.artifacts,\n\t\t\t{\n\t\t\t\tpath: \"mappings.json\",\n\t\t\t\tcontent: `${JSON.stringify(compactMappings(bundle.mappings))}\\n`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: emittedFiles.ioSymbols,\n\t\t\t\tcontent: `${JSON.stringify(bundle.ioSymbols, null, 2)}\\n`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: emittedFiles.publication,\n\t\t\t\tcontent: `${JSON.stringify(bundle.publication, null, 2)}\\n`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: \"config.json\",\n\t\t\t\tcontent: `${JSON.stringify(checked.config, null, 2)}\\n`,\n\t\t\t},\n\t\t\t...(bundle.debug\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: debugManifestFile,\n\t\t\t\t\t\t\tcontent: `${JSON.stringify(bundle.debug)}\\n`,\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t\t\t// The manifest's digest covers these exact bytes.\n\t\t\t...(bundle.explain === undefined\n\t\t\t\t? []\n\t\t\t\t: [{ path: explainFileName, content: bundle.explain }]),\n\t\t];\n\t\tconst stagedSt = join(staging, emittedSt);\n\t\t// Thousands of artifacts share a few hundred directories; each is made once.\n\t\tconst directories = new Set(\n\t\t\tartifacts.map((artifact) => dirname(join(stagedSt, artifact.path))),\n\t\t);\n\t\tfor (const directory of directories) {\n\t\t\tawait mkdir(directory, { recursive: true });\n\t\t}\n\t\tfor (const artifact of artifacts) {\n\t\t\tawait writeFile(join(stagedSt, artifact.path), artifact.content);\n\t\t}\n\n\t\tlet vendor: Awaited<ReturnType<typeof buildCodesys>> | undefined;\n\t\tif (!options.emitOnly) {\n\t\t\t// The engineering cache has its own ownership marker and survives clean.\n\t\t\tconst engineeringDir = outDir ?? join(previous.root, \"engineering\");\n\t\t\tawait engineeringDirectory(engineeringDir, configFile);\n\t\t\ttry {\n\t\t\t\tvendor = await buildCodesys(\n\t\t\t\t\tchecked.plan,\n\t\t\t\t\tbundle,\n\t\t\t\t\t{\n\t\t\t\t\t\tconfigFile,\n\t\t\t\t\t\tsourceDir: join(staging, emittedSt),\n\t\t\t\t\t\toutDir: engineeringDir,\n\t\t\t\t\t\tcontroller: options.controller,\n\t\t\t\t\t\t...engineering,\n\t\t\t\t\t},\n\t\t\t\t\t{ progress: options.progress },\n\t\t\t\t);\n\t\t\t} catch (cause) {\n\t\t\t\treturn { diagnostics: diagnoseCodesys(cause, bundle) };\n\t\t\t}\n\n\t\t\tconst vendorArtifacts = [\n\t\t\t\t[\"Application.project\", vendor.project],\n\t\t\t\t[\"Application.app\", vendor.output],\n\t\t\t\t[\"Application.crc\", vendor.checksum],\n\t\t\t] as const;\n\t\t\tfor (const [name, path] of vendorArtifacts) {\n\t\t\t\tif (!path) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst destination = join(staging, \"vendor\", name);\n\t\t\t\tawait mkdir(dirname(destination), { recursive: true });\n\t\t\t\tawait copyFile(path, destination);\n\t\t\t}\n\t\t}\n\n\t\tconst status = vendor ? \"vendor-compiled\" : \"emitted\";\n\t\tawait publishArtifacts(staging, previous, {\n\t\t\tconfigFile,\n\t\t\tstatus,\n\t\t\t...(vendor && {\n\t\t\t\tvendor: { application: vendor.application, tasks: vendor.tasks },\n\t\t\t}),\n\t\t});\n\t\t// Publication moved this directory into place; it is no longer staging.\n\t\tstaging = undefined;\n\t\treturn {\n\t\t\tdirectory: previous.output,\n\t\t\tstatus,\n\t\t\t...(controllerConfig && { controllerConfig }),\n\t\t\ttargets: coreTargets(checked.plan.core),\n\t\t\tservices: serviceRoutes(checked.plan.core),\n\t\t\tdiagnostics: [...checked.diagnostics, ...bundle.diagnostics],\n\t\t};\n\t} catch (cause) {\n\t\treturn { diagnostics: [failure(\"config\", \"PLC5004\", cause)] };\n\t} finally {\n\t\tif (staging) {\n\t\t\tawait rm(staging, { recursive: true, force: true });\n\t\t}\n\t}\n}\n\n/**\n * Source mappings with each ST path and source file written once: `mappings` rows are\n * `[object, line, file, start, end, sourceLine, sourceColumn]`, indexing `objects` and `files`.\n */\nfunction compactMappings(mappings: readonly SourceMapping[]) {\n\tconst objects = new Map<string, number>();\n\tconst files = new Map<string, number>();\n\tconst index = (table: Map<string, number>, value: string) => {\n\t\tconst known = table.get(value);\n\t\tif (known !== undefined) {\n\t\t\treturn known;\n\t\t}\n\t\ttable.set(value, table.size);\n\t\treturn table.size - 1;\n\t};\n\tconst rows = mappings.map(({ path, line, span }) => [\n\t\tindex(objects, path),\n\t\tline,\n\t\tindex(files, span.file),\n\t\tspan.start,\n\t\tspan.end,\n\t\tspan.line,\n\t\tspan.column,\n\t]);\n\treturn {\n\t\tobjects: [...objects.keys()],\n\t\tfiles: [...files.keys()],\n\t\tmappings: rows,\n\t};\n}\n\nexport async function cleanProject(file = \"tsplc.config.ts\"): Promise<{\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\ttry {\n\t\tawait cleanArtifacts(await realpath(resolve(file)));\n\t\treturn { diagnostics: [] };\n\t} catch (cause) {\n\t\treturn { diagnostics: [failure(\"config\", \"PLC5004\", cause)] };\n\t}\n}\n",
13
- "import type { VerifiedCoreModule } from \"@tsplc/compiler/ir\";\nimport { generatedDirectory } from \"@tsplc/config/project-files\";\nimport { serviceOfPath } from \"@tsplc/server\";\nimport { z } from \"zod\";\n\n/** The Bun runtime's files, relative to the directory that holds a project's config. */\nexport const runtimeDirectory = `${generatedDirectory}/runtime`;\nexport const runtimeFiles = {\n\t/** What the runtime runs, written by `tsplc run --bun`. */\n\tlaunch: \"launch.json\",\n\t/** The running runtime, written once it serves and removed when it stops. */\n\tstate: \"state.json\",\n\t/** Retained globals, written when the runtime stops. */\n\tretain: \"retain.json\",\n\t/** A detached runtime's output. */\n\tlog: \"plc.log\",\n\t/** The OPC UA server's certificate store. */\n\tcertificates: \"pki\",\n} as const;\n\n/** What `tsplc run --bun` hands the runtime: the config to load, with its target, and how to reach the services the build compiled calls to. */\nexport const launchSchema = z.strictObject({\n\tconfig: z.string().nonempty(),\n\ttarget: z.string().nonempty().nullable(),\n\t/** Each service procedure's route, with its wire-contract version: `/tsplc/services/<version>/<path>` by `<path>`. */\n\tservices: z.record(z.string(), z.string().startsWith(\"/tsplc/services/\")),\n});\nexport type Launch = z.infer<typeof launchSchema>;\n\n/** A runtime that serves: its process and where it publishes OPC UA. */\nexport const runtimeStateSchema = z.strictObject({\n\tpid: z.number().int().positive(),\n\tendpoint: z.string().startsWith(\"opc.tcp://\"),\n\tstartedAt: z.iso.datetime(),\n});\nexport type RuntimeState = z.infer<typeof runtimeStateSchema>;\n\n/** A service block's route: its URL's path over HTTP, the path its slots carry over OPC UA. */\nconst blockRoute = (\n\truntime: VerifiedCoreModule[\"blocks\"][number][\"runtime\"],\n) => {\n\tif (runtime?.kind === \"http\") {\n\t\treturn URL.parse(runtime.url)?.pathname;\n\t}\n\treturn runtime?.kind === \"rpc\" ? runtime.path : undefined;\n};\n\n/** The route each service call the program makes goes to, as the build compiled it. */\nexport const serviceRoutes = (core: VerifiedCoreModule) =>\n\tObject.fromEntries(\n\t\tcore.blocks.flatMap((block) => {\n\t\t\tconst route = blockRoute(block.runtime);\n\t\t\tconst procedure = route && serviceOfPath(route);\n\t\t\treturn route && procedure ? [[procedure, route] as const] : [];\n\t\t}),\n\t);\n",
14
- "import { createHash } from \"node:crypto\";\nimport {\n\tlstat,\n\tmkdir,\n\treaddir,\n\treadFile,\n\trename,\n\trm,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport type { buildCodesys } from \"@tsplc/compiler/codesys\";\nimport { sha256Digest } from \"@tsplc/config/build\";\nimport {\n\temittedStDirectory,\n\tgeneratedDirectory,\n} from \"@tsplc/config/project-files\";\nimport { z } from \"zod\";\n\nconst missing = (cause: unknown): boolean =>\n\tcause instanceof Error && \"code\" in cause && cause.code === \"ENOENT\";\nconst digest = (value: string | Uint8Array): string =>\n\tcreateHash(\"sha256\").update(value).digest(\"hex\");\n\n// Ownership is an explicit boundary: generated files must match their manifest,\n// and engineering trees must belong to this configuration before vendor writes.\nconst generatedFileSchema = z.object({\n\tpath: z\n\t\t.string()\n\t\t.regex(/^[A-Za-z0-9_ .-]+(?:\\/[A-Za-z0-9_ .-]+)*$/)\n\t\t.refine(\n\t\t\t(path) =>\n\t\t\t\t!path.split(\"/\").some((part) => part === \".\" || part === \"..\") &&\n\t\t\t\t![\"manifest.json\", \"receipt.json\"].includes(path),\n\t\t),\n\tsha256: sha256Digest,\n});\n\n/** The manifest's envelope; its entries are checked one by one to name the failure. */\nconst manifestSchema = z.object({\n\tkind: z.literal(\"tsplc-artifacts\"),\n\tversion: z.literal(1),\n\tconfigFile: z.string(),\n\tfiles: z.array(z.unknown()),\n});\n\ntype Manifest = Omit<z.infer<typeof manifestSchema>, \"files\"> & {\n\tfiles: z.infer<typeof generatedFileSchema>[];\n};\n\nconst buildStatusSchema = z.enum([\"emitted\", \"vendor-compiled\"]);\n\nconst receiptSchema = z.object({\n\tkind: z.literal(\"tsplc-build\"),\n\tversion: z.literal(1),\n\tconfigFile: z.string(),\n\tstatus: buildStatusSchema,\n});\n\nconst engineeringMarkerSchema = z.object({\n\tkind: z.literal(\"tsplc-engineering\"),\n\tversion: z.literal(1),\n\tconfigFile: z.string(),\n});\n\nfunction manifest(value: unknown, configFile: string): Manifest {\n\tconst parsed = manifestSchema.safeParse(value);\n\tif (!parsed.success || parsed.data.configFile !== configFile) {\n\t\tthrow new Error(\n\t\t\t\"Output directory has no matching tsPLC ownership manifest.\",\n\t\t);\n\t}\n\n\tconst files = parsed.data.files.map((item) => {\n\t\tconst file = generatedFileSchema.safeParse(item);\n\t\tif (!file.success) {\n\t\t\tthrow new Error(\"Invalid generated file ownership entry.\");\n\t\t}\n\t\treturn file.data;\n\t});\n\tif (new Set(files.map((item) => item.path)).size !== files.length) {\n\t\tthrow new Error(\"Duplicate generated file ownership entry.\");\n\t}\n\treturn { ...parsed.data, files };\n}\n\nasync function directory(path: string): Promise<boolean> {\n\ttry {\n\t\tconst entry = await lstat(path);\n\t\tif (!entry.isDirectory() || entry.isSymbolicLink()) {\n\t\t\tthrow new Error(`Generated directory must be a real directory: ${path}`);\n\t\t}\n\t\treturn true;\n\t} catch (cause) {\n\t\tif (missing(cause)) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow cause;\n\t}\n}\n\nasync function filesIn(path: string, prefix = \"\"): Promise<string[]> {\n\tconst result: string[] = [];\n\tfor (const entry of await readdir(path, { withFileTypes: true })) {\n\t\tconst name = prefix + entry.name;\n\t\tif (entry.isDirectory() && !entry.isSymbolicLink()) {\n\t\t\tresult.push(...(await filesIn(join(path, entry.name), `${name}/`)));\n\t\t} else {\n\t\t\tresult.push(name);\n\t\t}\n\t}\n\treturn result;\n}\n\nexport async function engineeringDirectory(\n\tpath: string,\n\tconfigFile: string,\n): Promise<void> {\n\tconst marker = join(path, \"ownership.json\");\n\tconst exists = await directory(path);\n\tif (!exists || !(await readdir(path)).length) {\n\t\tawait mkdir(path, { recursive: true });\n\t\tawait writeFile(\n\t\t\tmarker,\n\t\t\t`${JSON.stringify({ kind: \"tsplc-engineering\", version: 1, configFile }, null, 2)}\\n`,\n\t\t\t{ flag: \"wx\" },\n\t\t);\n\t} else {\n\t\tconst entry = await lstat(marker).catch((cause: unknown) => {\n\t\t\tif (missing(cause)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Engineering cache has no matching tsPLC ownership marker: ${path}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow cause;\n\t\t});\n\t\tif (!entry.isFile() || entry.isSymbolicLink()) {\n\t\t\tthrow new Error(\"Engineering ownership marker must be a real file.\");\n\t\t}\n\t\tconst value = engineeringMarkerSchema.safeParse(\n\t\t\tJSON.parse(await readFile(marker, \"utf8\")),\n\t\t);\n\t\tif (!value.success || value.data.configFile !== configFile) {\n\t\t\tthrow new Error(\n\t\t\t\t`Engineering cache has no matching tsPLC ownership marker: ${path}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst inspect = async (directory: string): Promise<void> => {\n\t\tfor (const entry of await readdir(directory, { withFileTypes: true })) {\n\t\t\tconst child = join(directory, entry.name);\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Engineering cache must not contain symlinks: ${child}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tawait inspect(child);\n\t\t\t}\n\t\t}\n\t};\n\tawait inspect(path);\n}\n\nexport async function owned(\n\tconfigFile: string,\n\twithdrawReceipt = false,\n): Promise<{\n\troot: string;\n\toutput: string;\n\townership?: Manifest;\n\tunknown: string[];\n}> {\n\tconst root = join(dirname(configFile), generatedDirectory);\n\tconst output = join(dirname(configFile), dirname(emittedStDirectory));\n\tif (!(await directory(root)) || !(await directory(output))) {\n\t\treturn { root, output, unknown: [] };\n\t}\n\n\tconst manifestPath = join(output, \"manifest.json\");\n\tconst manifestEntry = await lstat(manifestPath);\n\tif (!manifestEntry.isFile() || manifestEntry.isSymbolicLink()) {\n\t\tthrow new Error(\"Ownership manifest must be a real file.\");\n\t}\n\tconst ownership = manifest(\n\t\tJSON.parse(await readFile(manifestPath, \"utf8\")),\n\t\tconfigFile,\n\t);\n\tconst receipt = join(output, \"receipt.json\");\n\ttry {\n\t\tconst entry = await lstat(receipt);\n\t\tif (!entry.isFile() || entry.isSymbolicLink()) {\n\t\t\tthrow new Error(\"Build receipt must be a real file.\");\n\t\t}\n\t\tconst value = receiptSchema.safeParse(\n\t\t\tJSON.parse(await readFile(receipt, \"utf8\")),\n\t\t);\n\t\tif (!value.success || value.data.configFile !== configFile) {\n\t\t\tthrow new Error(\"Build receipt is not owned by this configuration.\");\n\t\t}\n\t\tif (withdrawReceipt) {\n\t\t\tawait rm(receipt);\n\t\t}\n\t} catch (cause) {\n\t\tif (!missing(cause)) {\n\t\t\tthrow cause;\n\t\t}\n\t}\n\n\tconst names = new Set([\n\t\t...ownership.files.map((file) => file.path),\n\t\t\"manifest.json\",\n\t\t\"receipt.json\",\n\t]);\n\t// Thousands of files share a few hundred directories; each is checked once.\n\tconst checked = new Set<string>();\n\tfor (const file of ownership.files) {\n\t\tlet parent = output;\n\t\tfor (const part of file.path.split(\"/\").slice(0, -1)) {\n\t\t\tparent = join(parent, part);\n\t\t\tif (checked.has(parent)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!(await directory(parent))) {\n\t\t\t\tthrow new Error(`Missing generated directory: ${parent}`);\n\t\t\t}\n\t\t\tchecked.add(parent);\n\t\t}\n\t\tconst path = join(output, file.path);\n\t\tconst entry = await lstat(path);\n\t\tif (\n\t\t\t!entry.isFile() ||\n\t\t\tentry.isSymbolicLink() ||\n\t\t\tdigest(await readFile(path)) !== file.sha256\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Generated file was replaced or edited; preserve it before rebuilding/cleaning: ${path}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn {\n\t\troot,\n\t\toutput,\n\t\townership,\n\t\tunknown: (await filesIn(output)).filter((name) => !names.has(name)),\n\t};\n}\n\ninterface Receipt {\n\tconfigFile: string;\n\tstatus: z.infer<typeof buildStatusSchema>;\n\tvendor?: Pick<\n\t\tAwaited<ReturnType<typeof buildCodesys>>,\n\t\t\"application\" | \"tasks\"\n\t>;\n}\n\n// Compile in a separate staging tree. Recheck ownership immediately before the\n// swap, because the vendor build may have given the user time to edit old files.\nexport async function publishArtifacts(\n\tstaging: string,\n\tprevious: Awaited<ReturnType<typeof owned>>,\n\treceipt: Receipt,\n): Promise<void> {\n\tconst configFile = receipt.configFile;\n\tconst generated = (await filesIn(staging)).sort();\n\tconst ownership: Manifest = {\n\t\tkind: \"tsplc-artifacts\",\n\t\tversion: 1,\n\t\tconfigFile,\n\t\tfiles: [],\n\t};\n\tfor (const path of generated) {\n\t\townership.files.push({\n\t\t\tpath,\n\t\t\tsha256: digest(await readFile(join(staging, path))),\n\t\t});\n\t}\n\tawait writeFile(\n\t\tjoin(staging, \"manifest.json\"),\n\t\t`${JSON.stringify(ownership, null, 2)}\\n`,\n\t);\n\tawait writeFile(\n\t\tjoin(staging, \"receipt.json\"),\n\t\t`${JSON.stringify(\n\t\t\t{\n\t\t\t\tkind: \"tsplc-build\",\n\t\t\t\tversion: 1,\n\t\t\t\tgeneratedAt: new Date().toISOString(),\n\t\t\t\t...receipt,\n\t\t\t},\n\t\t\tnull,\n\t\t\t2,\n\t\t)}\\n`,\n\t);\n\n\tconst current = await owned(configFile);\n\tif (\n\t\tJSON.stringify(current.ownership) !== JSON.stringify(previous.ownership)\n\t) {\n\t\tthrow new Error(\n\t\t\t\"Output ownership changed during the build; preserve it before rebuilding.\",\n\t\t);\n\t}\n\tif (current.unknown.length) {\n\t\tthrow new Error(\n\t\t\t`Output contains unrelated files: ${current.unknown.join(\", \")}`,\n\t\t);\n\t}\n\n\tconst backup = `${staging}-previous`;\n\tif (previous.ownership) {\n\t\tawait rename(previous.output, backup);\n\t}\n\ttry {\n\t\tawait rename(staging, previous.output);\n\t} catch (cause) {\n\t\tif (previous.ownership) {\n\t\t\tawait rename(backup, previous.output);\n\t\t}\n\t\tthrow cause;\n\t}\n\tif (previous.ownership) {\n\t\tawait rm(backup, { recursive: true });\n\t}\n}\n\nexport async function cleanArtifacts(configFile: string): Promise<void> {\n\tconst generated = await owned(configFile);\n\tif (!generated.ownership) {\n\t\treturn;\n\t}\n\tfor (const entry of generated.ownership.files) {\n\t\tawait rm(join(generated.output, entry.path));\n\t}\n\tawait rm(join(generated.output, \"receipt.json\"), { force: true });\n\tawait rm(join(generated.output, \"manifest.json\"));\n\n\t// Remove empty generated directories while preserving unrelated files.\n\tconst removeEmpty = async (path: string): Promise<void> => {\n\t\tfor (const entry of await readdir(path, { withFileTypes: true })) {\n\t\t\tif (entry.isDirectory() && !entry.isSymbolicLink()) {\n\t\t\t\tawait removeEmpty(join(path, entry.name));\n\t\t\t}\n\t\t}\n\t\tif (!(await readdir(path)).length) {\n\t\t\tawait rm(path, { recursive: true });\n\t\t}\n\t};\n\tawait removeEmpty(generated.output);\n}\n",
15
- "import { existsSync } from \"node:fs\";\nimport { mkdir, mkdtemp, rename, rm } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ResolvedTsplcConfig } from \"@tsplc/config\";\nimport { z } from \"zod\";\n\nconst resolveServerModule = (root: string, name: string) =>\n\tname.startsWith(\".\") ||\n\tname.startsWith(\"/\") ||\n\texistsSync(resolve(root, name))\n\t\t? resolve(root, name)\n\t\t: createRequire(join(root, \"package.json\")).resolve(name);\n\nconst kebabCase = (name: string) =>\n\tname\n\t\t.replace(/([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])/g, \"$1$3-$2$4\")\n\t\t.replace(/[^A-Za-z0-9]+/g, \"-\")\n\t\t.replace(/^-|-$/g, \"\")\n\t\t.toLowerCase();\n\n/** `build/server/<name>-services<extension>`, where the server's script or executable goes. */\nconst serverOutput = (\n\tconfig: ResolvedTsplcConfig,\n\troot: string,\n\textension: string,\n) =>\n\tresolve(\n\t\troot,\n\t\t\"build/server\",\n\t\t`${kebabCase(config.name)}-services${extension}`,\n\t);\n\n/** What `checkServer` posts to its worker: the server entry and the project root diagnostics are relative to. */\nexport const serverCheckRequestSchema = z.strictObject({\n\tentry: z.string(),\n\troot: z.string(),\n});\n\n/** The worker's answer: why the server entry fails its type check, or null when it passes. */\nexport const serverCheckResultSchema = z.strictObject({\n\tfailure: z.string().nullable(),\n});\n\n/** The type-check script beside this module: its source, or the bundle a built package ships. */\nconst serverCheckScript = () => {\n\tconst script = [\"./server-check.ts\", \"./server-check.js\"]\n\t\t.map((path) => fileURLToPath(new URL(path, import.meta.url)))\n\t\t.find((path) => existsSync(path));\n\tif (!script) {\n\t\tthrow new Error(\"The server type-check script is missing from this build.\");\n\t}\n\treturn script;\n};\n\n/** A server entry that passed its type check, and the runtime it is built for. */\nexport interface CheckedServer {\n\tentry: string;\n\truntime: NonNullable<NonNullable<ResolvedTsplcConfig[\"server\"]>[\"runtime\"]>;\n}\n\n/**\n * Type-checks the host entry as it will be built, on a worker thread: a caller that builds the\n * PLC program meanwhile awaits the result after it. The check rejects with the diagnostics.\n */\nexport const checkServer = async (\n\tconfig: ResolvedTsplcConfig,\n\troot: string,\n): Promise<CheckedServer> => {\n\tconst runtime = config.server?.runtime;\n\tif (!runtime) {\n\t\tthrow new Error(\"Configure server.runtime to build the server.\");\n\t}\n\tconst entry = resolveServerModule(root, runtime.entry);\n\tconst worker = new Worker(serverCheckScript());\n\ttry {\n\t\tconst answer = await new Promise<unknown>((resolve, reject) => {\n\t\t\tworker.onmessage = (event: MessageEvent) => resolve(event.data);\n\t\t\tworker.onerror = (event) => reject(new Error(event.message));\n\t\t\tconst request: z.infer<typeof serverCheckRequestSchema> = {\n\t\t\t\tentry,\n\t\t\t\troot,\n\t\t\t};\n\t\t\tworker.postMessage(request);\n\t\t});\n\t\tconst { failure } = serverCheckResultSchema.parse(answer);\n\t\tif (failure !== null) {\n\t\t\tthrow new Error(failure);\n\t\t}\n\t\treturn { entry, runtime };\n\t} finally {\n\t\tworker.terminate();\n\t}\n};\n\n/**\n * Bundles the host entry, which starts its own listener, into one minified script,\n * `build/server/<name>-services.js`, which the plant agent runs on its own Bun. It is a few MB\n * where an executable, which embeds Bun, is over 100, and deployments upload it.\n */\nexport const bundleServer = async (\n\t{ entry }: CheckedServer,\n\tconfig: ResolvedTsplcConfig,\n\troot: string,\n) => {\n\tconst outFile = serverOutput(config, root, \".js\");\n\tconst result = await Bun.build({\n\t\tentrypoints: [entry],\n\t\ttarget: \"bun\",\n\t\tminify: true,\n\t\tenv: \"disable\",\n\t});\n\tif (!result.success) {\n\t\tthrow new AggregateError(result.logs, \"Server bundle build failed.\");\n\t}\n\tconst [script, ...assets] = result.outputs;\n\tif (!script || assets.length) {\n\t\tthrow new Error(\n\t\t\t`The server bundle needs files beside its script (${assets.map(({ path }) => path).join(\", \")}), which deployments don't carry.`,\n\t\t);\n\t}\n\tawait mkdir(dirname(outFile), { recursive: true });\n\tawait Bun.write(outFile, script);\n\treturn outFile;\n};\n\n/** Compiles the host entry, which starts its own listener, into `build/server/<name>-services`. */\nexport const buildServer = async (\n\t{ entry, runtime }: CheckedServer,\n\tconfig: ResolvedTsplcConfig,\n\troot: string,\n) => {\n\tconst windows = runtime.target\n\t\t? runtime.target.includes(\"windows\")\n\t\t: process.platform === \"win32\";\n\tconst outFile = serverOutput(config, root, windows ? \".exe\" : \"\");\n\tawait mkdir(dirname(outFile), { recursive: true });\n\t// Compile beside the output so dependency resolution starts from the owning project.\n\tconst staging = await mkdtemp(join(dirname(outFile), \".tsplc-server-\"));\n\ttry {\n\t\tconst binary = join(staging, \"server\");\n\t\tconst result = await Bun.build({\n\t\t\tentrypoints: [entry],\n\t\t\tenv: \"disable\",\n\t\t\tcompile: {\n\t\t\t\toutfile: binary,\n\t\t\t\t...(runtime.target ? { target: runtime.target } : {}),\n\t\t\t\tautoloadDotenv: false,\n\t\t\t\tautoloadBunfig: false,\n\t\t\t\tautoloadTsconfig: false,\n\t\t\t\tautoloadPackageJson: false,\n\t\t\t},\n\t\t});\n\t\tif (!result.success) {\n\t\t\tthrow new AggregateError(result.logs, \"Server executable build failed.\");\n\t\t}\n\t\t// Bun names a Windows executable itself.\n\t\tawait rename(windows ? `${binary}.exe` : binary, outFile);\n\t\treturn {\n\t\t\tserver: {\n\t\t\t\texecutable: outFile,\n\t\t\t\ttarget: runtime.target ?? `bun-${process.platform}-${process.arch}`,\n\t\t\t},\n\t\t};\n\t} finally {\n\t\tawait rm(staging, { recursive: true, force: true });\n\t}\n};\n",
16
- "import {\n\task,\n\taskCredentials,\n\ttype Credentials,\n\ttype Target,\n\ttype Variable,\n} from \"@tsplc/agent\";\nimport { type AgentClient, createAgentClient } from \"@tsplc/agent/client\";\nimport type { LoginCommand, LoginResult } from \"@tsplc/build\";\nimport type { CompileEnvironment } from \"@tsplc/compiler\";\nimport {\n\ttype LoadedConfig,\n\ttype PlantVariables,\n\treleaseEnvironment,\n} from \"@tsplc/config\";\nimport { LoginUnavailable, noLogin } from \"@tsplc/debug\";\nimport { z } from \"zod\";\nimport {\n\ttype Approval,\n\ttype Follow,\n\topenDashboard,\n\tprintDeployments,\n\tredeploy,\n\trollBack,\n\tsubmitDeployment,\n} from \"./deployments\";\nimport { gitSource } from \"./git\";\nimport { prepareRelease } from \"./release\";\nimport { choose, confirm, progress, timedProgress } from \"./terminal\";\n\nconst plantCommands = [\n\t\"deploy\",\n\t\"deployments\",\n\t\"rollback\",\n\t\"redeploy\",\n\t\"dashboard\",\n\t\"target\",\n\t\"status\",\n\t\"login\",\n\t\"logout\",\n\t\"vars\",\n\t\"read\",\n\t\"write\",\n\t\"force\",\n\t\"unforce\",\n\t\"start\",\n\t\"stop\",\n\t\"reset\",\n\t\"restart\",\n] as const;\n\nexport type PlantCommand = (typeof plantCommands)[number];\n\nexport const plantCommand = (name: string) =>\n\tplantCommands.find((command) => command === name);\n\nexport interface PlantFlags {\n\tdownload?: boolean;\n\tformat?: \"json\" | \"text\";\n\treview?: boolean;\n\twait?: boolean;\n\t\"initialize-user\"?: boolean;\n\trestore?: boolean;\n\tselect?: boolean;\n\tsimulate?: boolean;\n\tyes?: boolean;\n\t\"frozen-lockfile\"?: boolean;\n}\n\n/** The plant agent named by TSPLC_AGENT_URL and TSPLC_AGENT_TOKEN in `env`, where a target's agent sets the URL. */\nexport const connect = (env: Record<string, string | undefined>) => {\n\tconst environment = z\n\t\t.object({\n\t\t\tTSPLC_AGENT_URL: z.url({\n\t\t\t\terror:\n\t\t\t\t\t\"Configure the target's agent, or set TSPLC_AGENT_URL to the plant agent, such as http://plant-pc:4850\",\n\t\t\t}),\n\t\t\tTSPLC_AGENT_TOKEN: z.string({\n\t\t\t\terror: \"Set TSPLC_AGENT_TOKEN to the plant agent's token\",\n\t\t\t}),\n\t\t})\n\t\t.parse(env);\n\treturn createAgentClient({\n\t\turl: environment.TSPLC_AGENT_URL,\n\t\ttoken: environment.TSPLC_AGENT_TOKEN,\n\t});\n};\n\n/**\n * Reads through the agent's open login, as `tsplc read` does, without opening one: the\n * debugger has no controller credentials.\n */\nexport const readThroughAgent =\n\t(agent: AgentClient) =>\n\tasync ([first, ...rest]: string[]) => {\n\t\tif (!first) {\n\t\t\treturn {};\n\t\t}\n\t\ttry {\n\t\t\tconst result = await agent.command({\n\t\t\t\tcommand: \"read\",\n\t\t\t\texpressions: [first, ...rest],\n\t\t\t});\n\t\t\tif (!(\"values\" in result)) {\n\t\t\t\tthrow new Error(\"The agent answered a read without values\");\n\t\t\t}\n\t\t\treturn result.values;\n\t\t} catch (error) {\n\t\t\tconst { login } = await agent.status();\n\t\t\tif (!login) {\n\t\t\t\tthrow new LoginUnavailable(noLogin, { cause: error });\n\t\t\t}\n\t\t\tif (\"error\" in login) {\n\t\t\t\tthrow new Error(login.error, { cause: error });\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\nconst selectTarget = async (agent: AgentClient): Promise<Target> => {\n\tconst interfaces = await agent.interfaces();\n\tif (!interfaces.length) {\n\t\tthrow new Error(\"The plant PC has no IPv4 network.\");\n\t}\n\tconst network =\n\t\tinterfaces.length === 1 && interfaces[0]\n\t\t\t? interfaces[0]\n\t\t\t: await choose(\n\t\t\t\t\t\"Which network is the controller on?\",\n\t\t\t\t\tinterfaces,\n\t\t\t\t\t(item) => `${item.name} ${item.address}/${item.prefixLength}`,\n\t\t\t\t);\n\tconsole.log(\n\t\t`Scanning ${network.address}/${network.prefixLength} for CODESYS controllers…`,\n\t);\n\tconst found = await agent.discover(network.name);\n\tconst manual = { address: \"\", port: 11740, hostname: null };\n\tconst choice = await choose(\n\t\t\"Which controller?\",\n\t\t[...found, manual],\n\t\t(item) =>\n\t\t\titem === manual\n\t\t\t\t? \"Enter an address\"\n\t\t\t\t: `${item.address}${item.hostname ? ` (${item.hostname})` : \"\"}`,\n\t);\n\tconst host =\n\t\tchoice === manual ? await ask(\"Controller address: \") : choice.address;\n\treturn agent.setTarget({ host, port: choice.port });\n};\n\n/**\n * The controller user to send: TSPLC_CONTROLLER_USERNAME and TSPLC_CONTROLLER_PASSWORD from\n * `environment`, else null for the user stored on the agent, else what `prompt` asks for. Initializing\n * the controller's user creates the one sent, so it never leaves it to the stored one.\n */\nexport const controllerCredentials = async (\n\tenvironment: CompileEnvironment,\n\tagent: { stored: boolean; initializeUser: boolean },\n\tprompt: () => Promise<Credentials>,\n): Promise<Credentials | null> => {\n\tconst username = environment.TSPLC_CONTROLLER_USERNAME;\n\tconst password = environment.TSPLC_CONTROLLER_PASSWORD;\n\tif (username && password) {\n\t\treturn { username, password };\n\t}\n\tif (username || password) {\n\t\tthrow new Error(\n\t\t\t\"Set both TSPLC_CONTROLLER_USERNAME and TSPLC_CONTROLLER_PASSWORD, or neither.\",\n\t\t);\n\t}\n\treturn agent.stored && !agent.initializeUser ? null : prompt();\n};\n\n/** The plant PC's variables and secrets by name, as `variables A, B and secret C`, or null when it holds none. */\nconst plantSummary = ({ values, secrets }: PlantVariables) => {\n\tconst named = (noun: string, names: readonly string[]) =>\n\t\tnames.length\n\t\t\t? `${noun}${names.length === 1 ? \"\" : \"s\"} ${names.join(\", \")}`\n\t\t\t: null;\n\tconst parts = [\n\t\tnamed(\"variable\", Object.keys(values)),\n\t\tnamed(\"secret\", secrets),\n\t].filter((part) => part !== null);\n\treturn parts.length ? parts.join(\" and \") : null;\n};\n\nconst deploy = async (\n\tagent: AgentClient,\n\tfile: string,\n\tloaded: LoadedConfig,\n\tflags: PlantFlags,\n\tenvironment: CompileEnvironment,\n\tfollow: Follow,\n) => {\n\tconst status = await agent.status();\n\tif (status.login) {\n\t\tthrow new Error(\"A login is open; log out before deploying: tsplc logout\");\n\t}\n\tconst target =\n\t\t!status.target || flags.select ? await selectTarget(agent) : status.target;\n\tconst plant = await agent.releaseVariables(\n\t\tloaded.config.secrets?.service ?? null,\n\t);\n\tconst built = releaseEnvironment(\n\t\tloaded.config,\n\t\t{ env: environment, values: loaded.values },\n\t\tplant,\n\t);\n\tconsole.log(`Building the release for ${target.host}…`);\n\tconst held = plantSummary(plant);\n\tif (held) {\n\t\tconsole.log(` With the plant PC's ${held}`);\n\t}\n\tconst building = timedProgress();\n\tconst { release, diagnostics } = await prepareRelease(\n\t\tfile,\n\t\tloaded,\n\t\tflags,\n\t\tbuilt,\n\t);\n\tif (!release) {\n\t\treturn { diagnostics };\n\t}\n\tbuilding(\"Built\");\n\tif (\n\t\tflags.download &&\n\t\t!(await confirm(\n\t\t\t\"A full download stops the running application while it loads. Continue?\",\n\t\t\tflags,\n\t\t))\n\t) {\n\t\tthrow new Error(\"Cancelled.\");\n\t}\n\tconst credentials = await controllerCredentials(\n\t\tenvironment,\n\t\t{\n\t\t\tstored: status.credentialsStored,\n\t\t\tinitializeUser: flags[\"initialize-user\"] ?? false,\n\t\t},\n\t\taskCredentials,\n\t);\n\tconst settings = {\n\t\tcredentials,\n\t\tdownload: flags.download ?? false,\n\t\tinitializeUser: flags[\"initialize-user\"] ?? false,\n\t};\n\tconsole.log(\n\t\trelease.manifest.server\n\t\t\t? \"Uploading the server and the program…\"\n\t\t\t: \"Uploading the program…\",\n\t);\n\treturn {\n\t\texitCode: await submitDeployment(\n\t\t\tagent,\n\t\t\trelease,\n\t\t\tsettings,\n\t\t\t{\n\t\t\t\tmode: flags.review ? \"review\" : \"apply\",\n\t\t\t\tgit: await gitSource(loaded.root),\n\t\t\t},\n\t\t\tfollow,\n\t\t),\n\t};\n};\n\n/** Opens a login when none is working; it stays open across commands until `tsplc logout`. */\nconst ensureLogin = async (\n\tagent: AgentClient,\n\tenvironment: CompileEnvironment,\n) => {\n\tconst { login, credentialsStored } = await agent.status();\n\tif (login && \"state\" in login) {\n\t\treturn;\n\t}\n\tif (login) {\n\t\tconsole.log(`The open login failed (${login.error}); replacing it.`);\n\t\tawait agent.logout();\n\t}\n\tconst credentials = await controllerCredentials(\n\t\tenvironment,\n\t\t{ stored: credentialsStored, initializeUser: false },\n\t\taskCredentials,\n\t);\n\tconsole.log(\n\t\t\"Logging in. CODESYS takes a few minutes to start; the login stays open until tsplc logout.\",\n\t);\n\tawait agent.login(credentials, progress);\n};\n\n/** The children of `prefix` in the variable tree, with array indexes folded into one range. */\nexport const variableChildren = (\n\tvariables: readonly Variable[],\n\tprefix: string,\n) => {\n\tconst children = new Map<string, { type?: string; leaves: number }>();\n\tconst start = prefix.toLowerCase();\n\tfor (const { path, type } of variables) {\n\t\tconst lower = path.toLowerCase();\n\t\tif (\n\t\t\tprefix &&\n\t\t\t!(\n\t\t\t\tlower === start ||\n\t\t\t\tlower.startsWith(`${start}.`) ||\n\t\t\t\tlower.startsWith(`${start}[`)\n\t\t\t)\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst rest = path.slice(prefix.length).replace(/^\\./, \"\");\n\t\tif (rest === \"\") {\n\t\t\treturn [{ name: path, type, leaves: 1 }];\n\t\t}\n\t\tconst name = /^(\\[[^\\]]*\\]|[^.[]+)/.exec(rest)?.[0] ?? rest;\n\t\tconst child = children.get(name) ?? { leaves: 0 };\n\t\tchildren.set(name, {\n\t\t\ttype: rest === name ? type : undefined,\n\t\t\tleaves: child.leaves + 1,\n\t\t});\n\t}\n\tconst indexes = [...children.keys()]\n\t\t.filter((name) => /^\\[\\d+\\]$/.test(name))\n\t\t.map((name) => Number(name.slice(1, -1)));\n\tconst listed = [...children].filter(([name]) => !/^\\[\\d+\\]$/.test(name));\n\tif (indexes.length) {\n\t\tconst first = children.get(`[${Math.min(...indexes)}]`);\n\t\tlisted.unshift([\n\t\t\t`[${Math.min(...indexes)}..${Math.max(...indexes)}]`,\n\t\t\tfirst ?? { leaves: 0 },\n\t\t]);\n\t}\n\treturn listed.map(([name, child]) => ({ name, ...child }));\n};\n\nconst printStatus = async (agent: AgentClient) => {\n\tconst status = await agent.status();\n\tconsole.log(\n\t\t`Controller ${status.target ? `${status.target.host}:${status.target.port}` : \"not selected (tsplc target)\"}`,\n\t);\n\tconsole.log(\n\t\t`Release ${status.release ? `${status.release.id}, ${status.release.operation} at ${status.release.deployedAt}` : \"none\"}`,\n\t);\n\tconsole.log(\n\t\t`Server ${status.server ? `${status.server.running ? \"running\" : \"restarting\"} (${status.server.executable})` : \"none\"}`,\n\t);\n\tconst { login } = status;\n\tif (!login) {\n\t\tconsole.log(\"Login closed\");\n\t} else if (\"error\" in login) {\n\t\tconsole.log(`Login failed: ${login.error} (tsplc logout)`);\n\t} else {\n\t\tconsole.log(\n\t\t\t`Login open; application ${login.state}${login.forced.length ? `; forced: ${login.forced.join(\", \")}` : \"\"}`,\n\t\t);\n\t}\n};\n\n/** Lists the deployed release's published variables under `path`, or its roots. */\nconst printVariables = async (agent: AgentClient, path: string | undefined) => {\n\tconst children = variableChildren(await agent.variables(), path ?? \"\");\n\tif (!children.length) {\n\t\tthrow new Error(`No published variable ${path}.`);\n\t}\n\tfor (const child of children) {\n\t\tconsole.log(\n\t\t\t`${child.name.padEnd(32)} ${child.type ?? `${child.leaves} variables`}`,\n\t\t);\n\t}\n};\n\nconst printLogin = (result: LoginResult) => {\n\tif (\"values\" in result) {\n\t\tfor (const [expression, value] of Object.entries(result.values)) {\n\t\t\tconsole.log(`${expression} = ${value}`);\n\t\t}\n\t\treturn;\n\t}\n\tconsole.log(`Application ${result.state}`);\n\tif (result.forced.length) {\n\t\tconsole.log(`Forced: ${result.forced.join(\", \")}`);\n\t}\n};\n\n/**\n * Runs a command against the plant agent. Returns a deployment's compiler diagnostics when the\n * program doesn't compile, and the exit code of a command that queues a deployment.\n */\nexport const runPlantCommand = async (\n\tagent: AgentClient,\n\tcommand: PlantCommand,\n\targs: string[],\n\tflags: PlantFlags,\n\tproject: {\n\t\tfile: string;\n\t\tload: () => Promise<LoadedConfig>;\n\t\t/** What the release's compilation reads. */\n\t\tenvironment: CompileEnvironment;\n\t\t/** Someone at a terminal can answer prompts. */\n\t\tinteractive: boolean;\n\t},\n) => {\n\tconst approval: Approval = {\n\t\tyes: flags.yes ?? false,\n\t\tinteractive: project.interactive,\n\t\tconfirm: (question) => confirm(question, {}),\n\t};\n\tconst follow = { wait: flags.wait ?? false, approval };\n\tconst expect = (count: number, usage: string) => {\n\t\tif (args.length !== count) {\n\t\t\tthrow new Error(`Usage: tsplc ${command} ${usage}`);\n\t\t}\n\t};\n\tconst send = async (loginCommand: LoginCommand) => {\n\t\tawait ensureLogin(agent, project.environment);\n\t\tprintLogin(await agent.command(loginCommand));\n\t};\n\tswitch (command) {\n\t\tcase \"deploy\":\n\t\t\texpect(\n\t\t\t\t0,\n\t\t\t\t\"[--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait] [-y]\",\n\t\t\t);\n\t\t\treturn deploy(\n\t\t\t\tagent,\n\t\t\t\tproject.file,\n\t\t\t\tawait project.load(),\n\t\t\t\tflags,\n\t\t\t\tproject.environment,\n\t\t\t\tfollow,\n\t\t\t);\n\t\tcase \"deployments\":\n\t\t\texpect(0, \"[--format json]\");\n\t\t\treturn printDeployments(agent, flags);\n\t\tcase \"rollback\":\n\t\t\tif (args.length > 1) {\n\t\t\t\tthrow new Error(\"Usage: tsplc rollback [id] [--wait] [-y]\");\n\t\t\t}\n\t\t\treturn { exitCode: await rollBack(agent, args[0], follow) };\n\t\tcase \"redeploy\": {\n\t\t\tconst [id, ...extra] = args;\n\t\t\tif (!id || extra.length) {\n\t\t\t\tthrow new Error(\"Usage: tsplc redeploy <id> [--review] [--wait] [-y]\");\n\t\t\t}\n\t\t\treturn {\n\t\t\t\texitCode: await redeploy(\n\t\t\t\t\tagent,\n\t\t\t\t\tid,\n\t\t\t\t\tflags.review ? \"review\" : \"apply\",\n\t\t\t\t\tfollow,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t\tcase \"dashboard\":\n\t\t\texpect(0, \"\");\n\t\t\treturn openDashboard(agent, project.interactive);\n\t\tcase \"target\": {\n\t\t\texpect(0, \"\");\n\t\t\tconst target = await selectTarget(agent);\n\t\t\tconsole.log(`Deployments now go to ${target.host}:${target.port}.`);\n\t\t\treturn;\n\t\t}\n\t\tcase \"status\":\n\t\t\texpect(0, \"\");\n\t\t\treturn printStatus(agent);\n\t\tcase \"login\":\n\t\t\texpect(0, \"\");\n\t\t\tawait ensureLogin(agent, project.environment);\n\t\t\tprintLogin(await agent.command({ command: \"state\" }));\n\t\t\treturn;\n\t\tcase \"logout\": {\n\t\t\texpect(0, \"\");\n\t\t\tconst { login } = await agent.status();\n\t\t\tconst forced = login && \"forced\" in login ? login.forced : [];\n\t\t\tif (\n\t\t\t\tforced.length &&\n\t\t\t\t!(await confirm(\n\t\t\t\t\t`Forced: ${forced.join(\", \")}. Forces stay on the controller after logout. Log out anyway?`,\n\t\t\t\t\tflags,\n\t\t\t\t))\n\t\t\t) {\n\t\t\t\tthrow new Error(\"Cancelled.\");\n\t\t\t}\n\t\t\tconst { failure } = await agent.logout();\n\t\t\tconsole.log(\n\t\t\t\tfailure\n\t\t\t\t\t? `The login couldn't log out (${failure}); its container was removed.`\n\t\t\t\t\t: \"Logged out.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tcase \"vars\":\n\t\t\tif (args.length > 1) {\n\t\t\t\tthrow new Error(\"Usage: tsplc vars [path]\");\n\t\t\t}\n\t\t\treturn printVariables(agent, args[0]);\n\t\tcase \"read\": {\n\t\t\tconst [first, ...rest] = args;\n\t\t\tif (!first) {\n\t\t\t\tthrow new Error(\"Usage: tsplc read <expression>...\");\n\t\t\t}\n\t\t\treturn send({ command: \"read\", expressions: [first, ...rest] });\n\t\t}\n\t\tcase \"write\":\n\t\tcase \"force\": {\n\t\t\tconst [expression, value, ...extra] = args;\n\t\t\tif (!expression || !value || extra.length) {\n\t\t\t\tthrow new Error(`Usage: tsplc ${command} <expression> <value>`);\n\t\t\t}\n\t\t\treturn send({ command, values: { [expression]: value } });\n\t\t}\n\t\tcase \"unforce\":\n\t\t\treturn send({\n\t\t\t\tcommand: \"unforce\",\n\t\t\t\texpressions: args,\n\t\t\t\trestore: flags.restore ?? false,\n\t\t\t});\n\t\tcase \"start\":\n\t\t\texpect(0, \"\");\n\t\t\treturn send({ command: \"start\" });\n\t\tcase \"stop\":\n\t\t\texpect(0, \"\");\n\t\t\tif (!(await confirm(\"Stop the application on the controller?\", flags))) {\n\t\t\t\tthrow new Error(\"Cancelled.\");\n\t\t\t}\n\t\t\treturn send({ command: \"stop\" });\n\t\tcase \"restart\": {\n\t\t\tif (args.length > 1) {\n\t\t\t\tthrow new Error(\"Usage: tsplc restart [warm|cold] [-y]\");\n\t\t\t}\n\t\t\tconst reset = z.enum([\"warm\", \"cold\"]).parse(args[0] ?? \"warm\");\n\t\t\tif (\n\t\t\t\t!(await confirm(\n\t\t\t\t\t`Reset the application (${reset}) and start it again? Its variables go back to their initial values${reset === \"warm\" ? \", but for retain ones\" : \"\"}.`,\n\t\t\t\t\tflags,\n\t\t\t\t))\n\t\t\t) {\n\t\t\t\tthrow new Error(\"Cancelled.\");\n\t\t\t}\n\t\t\tconst { state } = await agent.restartController({ reset });\n\t\t\tconsole.log(\n\t\t\t\t`Reset ${reset}; the application is ${state === \"run\" ? \"running\" : state}.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tcase \"reset\": {\n\t\t\texpect(1, \"warm|cold\");\n\t\t\tconst kind = z.enum([\"warm\", \"cold\"]).parse(args[0]);\n\t\t\tif (\n\t\t\t\t!(await confirm(\n\t\t\t\t\t`Reset the application (${kind})? It stops and reinitializes its variables.`,\n\t\t\t\t\tflags,\n\t\t\t\t))\n\t\t\t) {\n\t\t\t\tthrow new Error(\"Cancelled.\");\n\t\t\t}\n\t\t\treturn send({\n\t\t\t\tcommand: \"reset\",\n\t\t\t\tkind: kind === \"warm\" ? \"Warm\" : \"Cold\",\n\t\t\t});\n\t\t}\n\t}\n};\n",
17
- "import { resolve } from \"node:path\";\nimport {\n\tbuildProject as buildSt,\n\tcheckRawSources,\n\tconfigureDocker,\n\tconfigureRuntime,\n\tinspectProjectController,\n\tinstallLibraries,\n\ttype ProgressStream,\n\trawEngineeringSettings,\n\trunProject,\n\tupdateController,\n} from \"@tsplc/build\";\nimport { type CompileEnvironment, checkHostConfig } from \"@tsplc/compiler\";\nimport { type Diagnostic, hasErrors } from \"@tsplc/compiler/ir\";\nimport {\n\tbuildTargetFor,\n\tcontrollerFor,\n\ttype LoadedConfig,\n\tloadTsplcConfig,\n\trawBuildConfig,\n} from \"@tsplc/config\";\nimport { resolveConfig } from \"@tsplc/config/build\";\nimport { generateProject } from \"@tsplc/typegen\";\nimport { runInBun } from \"../runtime/process\";\nimport {\n\tbuildConfigs,\n\tbuildProject,\n\tcheckProject,\n\tcleanProject,\n\tprojectTargets,\n} from \"./project\";\nimport { buildServer, checkServer } from \"./server\";\n\nconst projectCommands = [\n\t\"install\",\n\t\"typegen\",\n\t\"check\",\n\t\"build\",\n\t\"run\",\n\t\"download\",\n\t\"online-change\",\n\t\"inspect\",\n\t\"clean\",\n\t\"configure\",\n] as const;\n\nexport type ProjectCommand = (typeof projectCommands)[number];\n\nexport const projectCommand = (name: string) =>\n\tprojectCommands.find((command) => command === name);\n\nexport interface ProjectFlags {\n\t\"emit-only\"?: boolean;\n\tformat?: \"json\" | \"text\";\n\tread?: string[];\n\t\"initialize-user\"?: boolean;\n\t\"frozen-lockfile\"?: boolean;\n\tcheck?: boolean;\n\tplc?: boolean;\n\tserver?: boolean;\n\tsimulate?: boolean;\n\truntime?: boolean;\n\tbun?: boolean;\n\tforeground?: boolean;\n\ttarget?: string;\n}\n\n/** Every command result; one whose diagnostics have errors fails the command. */\nexport type CommandResult = object & { diagnostics?: readonly Diagnostic[] };\n\n/** A result whose diagnostics fail the command; the CLI reports the whole result. */\nexport class DiagnosticFailure extends Error {\n\tconstructor(readonly result: CommandResult) {\n\t\tsuper(\"PLC validation failed.\");\n\t}\n}\n\n/** Rejects the flags that don't apply to `command`. */\nexport const checkProjectFlags = (\n\tcommand: ProjectCommand,\n\tflags: ProjectFlags,\n) => {\n\tif (flags[\"emit-only\"] && command !== \"build\") {\n\t\tthrow new Error(\"--emit-only is supported by build only.\");\n\t}\n\tif (flags.target && (command === \"configure\" || command === \"clean\")) {\n\t\tthrow new Error(\"--target applies only to commands that read the config.\");\n\t}\n\tif (flags.runtime && command !== \"configure\") {\n\t\tthrow new Error(\"--runtime applies only to configure.\");\n\t}\n\tif (flags.bun && (command !== \"run\" || !flags.simulate)) {\n\t\tthrow new Error(\n\t\t\t\"--bun applies only to run --simulate: the Bun runtime has no fieldbus, so a plant simulator writes its inputs.\",\n\t\t);\n\t}\n\tif (flags.foreground && !flags.bun) {\n\t\tthrow new Error(\"--foreground applies only to run --simulate --bun.\");\n\t}\n\tif ((flags.plc || flags.server) && command !== \"build\") {\n\t\tthrow new Error(\"--plc and --server apply only to build.\");\n\t}\n\t// deploy takes --simulate too, but runs as a plant command.\n\tif (\n\t\tflags.simulate &&\n\t\t![\"run\", \"download\", \"online-change\"].includes(command)\n\t) {\n\t\tthrow new Error(\n\t\t\t\"--simulate applies only to run, download, online-change and deploy.\",\n\t\t);\n\t}\n\tif (flags.plc && flags.server) {\n\t\tthrow new Error(\"Choose --plc or --server, or omit both for a full build.\");\n\t}\n\tif (flags.server && flags[\"emit-only\"]) {\n\t\tthrow new Error(\"--emit-only applies to PLC emission only.\");\n\t}\n};\n\n/** What a command runs with besides its flags: where progress goes and the environment it compiles with. */\ninterface CommandContext {\n\tprogress: ProgressStream;\n\tenvironment: CompileEnvironment;\n}\n\nexport const runProjectCommand = async (\n\tcommand: ProjectCommand,\n\tfile: string,\n\tflags: ProjectFlags,\n\tenvironment: CompileEnvironment,\n): Promise<CommandResult> => {\n\tconst context: CommandContext = {\n\t\t// A JSON result owns standard output, so progress goes to standard error.\n\t\tprogress: flags.format === \"json\" ? \"stderr\" : \"stdout\",\n\t\tenvironment,\n\t};\n\tconst { progress } = context;\n\t// The config, and the environment it compiles with, are the target's.\n\tconst load = () =>\n\t\tloadTsplcConfig(file, {\n\t\t\tenv: environment,\n\t\t\ttarget: flags.target,\n\t\t\tforAgent: false,\n\t\t});\n\tswitch (command) {\n\t\tcase \"configure\":\n\t\t\treturn configure(flags, progress);\n\t\tcase \"clean\":\n\t\t\treturn cleanProject(file);\n\t\tcase \"install\":\n\t\t\treturn install(await load(), flags);\n\t\tcase \"typegen\":\n\t\t\treturn typegen(file, await load(), flags, environment);\n\t\tcase \"check\":\n\t\t\treturn check(file, await loadCheckedConfig(file, load), environment);\n\t\tcase \"build\":\n\t\t\treturn build(file, await loadCheckedConfig(file, load), flags, context);\n\t\tcase \"run\":\n\t\t\treturn run(file, await loadCheckedConfig(file, load), flags, context);\n\t\tcase \"inspect\":\n\t\t\treturn inspectProjectController(await load(), flags.read, {\n\t\t\t\tprogress,\n\t\t\t});\n\t\tcase \"download\":\n\t\tcase \"online-change\":\n\t\t\treturn updateProgram(\n\t\t\t\tcommand,\n\t\t\t\tfile,\n\t\t\t\tawait loadCheckedConfig(file, load),\n\t\t\t\tflags,\n\t\t\t\tcontext,\n\t\t\t);\n\t}\n};\n\n/** A config loaded after its host config check, whose diagnostics the compiler reports. */\ninterface CheckedConfig {\n\tloaded: LoadedConfig;\n\thostConfigDiagnostics: readonly Diagnostic[];\n}\n\n/** Loads the config after type-checking it, so a type error fails before the config runs. */\nconst loadCheckedConfig = async (\n\tfile: string,\n\tload: () => Promise<LoadedConfig>,\n): Promise<CheckedConfig> => {\n\tconst hostConfigDiagnostics = checkHostConfig(resolve(file));\n\tif (hasErrors(hostConfigDiagnostics)) {\n\t\tthrow new DiagnosticFailure({ diagnostics: hostConfigDiagnostics });\n\t}\n\treturn { loaded: await load(), hostConfigDiagnostics };\n};\n\n/** Builds the Docker image every build uses, or with `--runtime` the local PLC runtime's. */\nconst configure = async (\n\tflags: Pick<ProjectFlags, \"runtime\">,\n\tprogress: ProgressStream,\n) => {\n\tawait (flags.runtime\n\t\t? configureRuntime({ progress })\n\t\t: configureDocker({ progress }));\n\treturn { ok: true };\n};\n\nconst install = async (\n\t{ config, root }: LoadedConfig,\n\tflags: Pick<ProjectFlags, \"frozen-lockfile\">,\n) => ({\n\tlibraries: await installLibraries(config.dependencies, root, {\n\t\tfrozen: flags[\"frozen-lockfile\"],\n\t}),\n});\n\nconst typegen = async (\n\tfile: string,\n\tloaded: LoadedConfig,\n\tflags: Pick<ProjectFlags, \"check\">,\n\tenvironment: CompileEnvironment,\n) => {\n\tconst targets = await projectTargets(file, { loaded, environment });\n\tif (loaded.config.compiler && !flags.check) {\n\t\tawait generateProject(file, { hardwareOnly: true, loaded, targets });\n\t\tconst emitted = await buildProject(file, {\n\t\t\temitOnly: true,\n\t\t\tloaded,\n\t\t\tenvironment,\n\t\t});\n\t\tif (hasErrors(emitted.diagnostics)) {\n\t\t\tthrow new DiagnosticFailure(emitted);\n\t\t}\n\t}\n\treturn generateProject(file, { check: flags.check, loaded, targets });\n};\n\nconst check = async (\n\tfile: string,\n\t{ loaded, hostConfigDiagnostics }: CheckedConfig,\n\tenvironment: CompileEnvironment,\n) => {\n\tif (loaded.config.compiler) {\n\t\treturn checkProject(file, { loaded, hostConfigDiagnostics, environment });\n\t}\n\treturn { objects: (await checkRawSources(loaded)).objects.length };\n};\n\n/**\n * The PLC program `build` and `run` compile: TypeScript through the compiler, or raw\n * Structured Text straight to the vendor build. Either refreshes the generated types.\n */\nconst buildPlc = async (\n\tcommand: \"build\" | \"run\",\n\tfile: string,\n\t{ loaded, hostConfigDiagnostics }: CheckedConfig,\n\tflags: Pick<ProjectFlags, \"emit-only\" | \"frozen-lockfile\" | \"simulate\">,\n\t{ progress, environment }: CommandContext,\n) => {\n\tconst { config } = loaded;\n\tif (config.compiler) {\n\t\t// The build's analysis already read the targets; `--format json` reports the rest.\n\t\tconst { targets, services, ...built } = await buildProject(file, {\n\t\t\tprogress,\n\t\t\tenvironment,\n\t\t\temitOnly: flags[\"emit-only\"],\n\t\t\tfrozenLockfile: flags[\"frozen-lockfile\"],\n\t\t\t...buildConfigs(loaded, flags),\n\t\t\thostConfigDiagnostics,\n\t\t\tcontroller: controllerFor(config, command),\n\t\t\tbuildTarget: buildTargetFor(command),\n\t\t});\n\t\tif (hasErrors(built.diagnostics)) {\n\t\t\tthrow new DiagnosticFailure(built);\n\t\t}\n\t\tawait generateProject(file, { loaded, targets });\n\t\treturn { built, services };\n\t}\n\tif (flags[\"emit-only\"]) {\n\t\tthrow new Error(\"Raw Structured Text is already emitted.\");\n\t}\n\tconst built = await buildSt(\n\t\tawait rawEngineeringSettings(loaded, {\n\t\t\tcommand,\n\t\t\tfrozenLockfile: flags[\"frozen-lockfile\"],\n\t\t\tsimulate: flags.simulate,\n\t\t}),\n\t\t{ progress },\n\t);\n\tawait generateProject(file, { hardwareOnly: !config.typegen, loaded });\n\treturn { built, services: undefined };\n};\n\n/** The PLC program and, unless `--plc` or `--emit-only` restricts it, the configured server. */\nconst build = async (\n\tfile: string,\n\tchecked: CheckedConfig,\n\tflags: Pick<\n\t\tProjectFlags,\n\t\t\"emit-only\" | \"frozen-lockfile\" | \"plc\" | \"server\" | \"simulate\"\n\t>,\n\tcontext: CommandContext,\n) => {\n\tconst { config, root } = checked.loaded;\n\tif (flags.server) {\n\t\treturn buildServer(await checkServer(config, root), config, root);\n\t}\n\tconst withServer =\n\t\t!flags.plc && !flags[\"emit-only\"] && config.server?.runtime;\n\t// The server's type check runs on a worker thread while the PLC program builds.\n\tconst serverCheck = withServer ? checkServer(config, root) : undefined;\n\t// A failed PLC build reports its own diagnostics; the check's outcome is read only after a success.\n\tserverCheck?.catch(() => undefined);\n\tconst { built: plc } = await buildPlc(\"build\", file, checked, flags, context);\n\tif (!serverCheck) {\n\t\treturn plc;\n\t}\n\treturn { ...plc, ...(await buildServer(await serverCheck, config, root)) };\n};\n\nconst run = async (\n\tfile: string,\n\tchecked: CheckedConfig,\n\tflags: Pick<\n\t\tProjectFlags,\n\t\t\"frozen-lockfile\" | \"simulate\" | \"bun\" | \"foreground\" | \"target\"\n\t>,\n\tcontext: CommandContext,\n) => {\n\tif (flags.bun) {\n\t\treturn runInBunRuntime(file, checked, flags, context);\n\t}\n\tconst { config, configFile } = checked.loaded;\n\tconst { built } = await buildPlc(\"run\", file, checked, flags, context);\n\tif (!config.build) {\n\t\tthrow new Error(\"Configure build to run this project.\");\n\t}\n\tawait runProject(\n\t\tresolveConfig(\n\t\t\tconfig.compiler ? config.build : rawBuildConfig(config),\n\t\t\tconfigFile,\n\t\t),\n\t\tconfig.name,\n\t\t{ progress: context.progress },\n\t);\n\treturn built;\n};\n\n/** Emits the program and runs its TypeScript in the Bun runtime instead of CODESYS. */\nconst runInBunRuntime = async (\n\tfile: string,\n\tchecked: CheckedConfig,\n\tflags: Pick<\n\t\tProjectFlags,\n\t\t\"frozen-lockfile\" | \"simulate\" | \"foreground\" | \"target\"\n\t>,\n\tcontext: CommandContext,\n) => {\n\tconst { config, configFile, root } = checked.loaded;\n\tif (!config.compiler) {\n\t\tthrow new Error(\n\t\t\t\"The Bun runtime runs a TypeScript program; this project builds raw Structured Text.\",\n\t\t);\n\t}\n\tconst { built, services } = await buildPlc(\n\t\t\"run\",\n\t\tfile,\n\t\tchecked,\n\t\t{ ...flags, \"emit-only\": true },\n\t\tcontext,\n\t);\n\tconst runtime = await runInBun({\n\t\troot,\n\t\tlaunch: {\n\t\t\tconfig: configFile,\n\t\t\ttarget: flags.target ?? null,\n\t\t\tservices: services ?? {},\n\t\t},\n\t\tenvironment: context.environment,\n\t\tforeground: flags.foreground ?? false,\n\t\tprogress: context.progress,\n\t});\n\treturn { ...built, runtime };\n};\n\n/** Downloads or online-changes the program on the configured controller. */\nconst updateProgram = async (\n\toperation: \"download\" | \"online-change\",\n\tfile: string,\n\tchecked: CheckedConfig,\n\tflags: Pick<\n\t\tProjectFlags,\n\t\t\"frozen-lockfile\" | \"simulate\" | \"initialize-user\" | \"read\"\n\t>,\n\t{ progress, environment }: CommandContext,\n) => {\n\tconst { config } = checked.loaded;\n\tif (!config.build) {\n\t\tthrow new Error(\"Configure build settings and controller connection.\");\n\t}\n\tconst settings = config.compiler\n\t\t? await emittedControllerSettings(\n\t\t\t\toperation,\n\t\t\t\tfile,\n\t\t\t\tchecked,\n\t\t\t\tflags,\n\t\t\t\tenvironment,\n\t\t\t)\n\t\t: await rawEngineeringSettings(checked.loaded, {\n\t\t\t\tcommand: operation,\n\t\t\t\tfrozenLockfile: flags[\"frozen-lockfile\"],\n\t\t\t\tsimulate: flags.simulate,\n\t\t\t});\n\treturn updateController(settings, operation, {\n\t\tinitializeUser: flags[\"initialize-user\"],\n\t\tread: flags.read,\n\t\tprogress,\n\t});\n};\n\nconst emittedControllerSettings = async (\n\toperation: \"download\" | \"online-change\",\n\tfile: string,\n\t{ loaded, hostConfigDiagnostics }: CheckedConfig,\n\tflags: Pick<ProjectFlags, \"frozen-lockfile\" | \"simulate\">,\n\tenvironment: CompileEnvironment,\n) => {\n\tconst emitted = await buildProject(file, {\n\t\temitOnly: true,\n\t\tforController: true,\n\t\tenvironment,\n\t\tfrozenLockfile: flags[\"frozen-lockfile\"],\n\t\t...buildConfigs(loaded, flags),\n\t\thostConfigDiagnostics,\n\t\tcontroller: controllerFor(loaded.config, operation),\n\t\tbuildTarget: buildTargetFor(operation),\n\t});\n\tif (hasErrors(emitted.diagnostics)) {\n\t\tthrow new DiagnosticFailure(emitted);\n\t}\n\tif (!emitted.controllerConfig) {\n\t\tthrow new Error(\"Configure build settings for deployment.\");\n\t}\n\t// Emission already resolves the generated entry/task paths. Passing\n\t// this through the input schema again would reject its configFile.\n\treturn { ...emitted.controllerConfig, io: {} };\n};\n",
18
- "import { spawn, spawnSync } from \"node:child_process\";\nimport { existsSync, openSync } from \"node:fs\";\nimport { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { fileURLToPath } from \"node:url\";\nimport { type ProgressStream, progressLog } from \"@tsplc/build\";\nimport {\n\ttype Launch,\n\ttype RuntimeState,\n\truntimeDirectory,\n\truntimeFiles,\n\truntimeStateSchema,\n} from \"./launch\";\n\n/** How long a runtime has to start serving, and to stop. */\nconst startTimeoutMs = 60_000;\nconst stopTimeoutMs = 15_000;\n\n/** The runtime's entry: this source tree's, or the bundle a built package ships beside the CLI. */\nconst runtimeScript = () => {\n\tconst script = [\"./main.ts\", \"./bun-runtime.js\"]\n\t\t.map((path) => fileURLToPath(new URL(path, import.meta.url)))\n\t\t.find((path) => existsSync(path));\n\tif (!script) {\n\t\tthrow new Error(\"The Bun runtime's script is missing from this build.\");\n\t}\n\treturn script;\n};\n\nconst alive = (pid: number) => {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\n/** Whether `pid` still runs this project's runtime, rather than a process that took over its number after a crash. */\nconst isRuntime = (pid: number, launchFile: string) => {\n\tif (!alive(pid)) {\n\t\treturn false;\n\t}\n\tif (process.platform === \"win32\") {\n\t\treturn true;\n\t}\n\tconst command = spawnSync(\"ps\", [\"-o\", \"command=\", \"-p\", String(pid)], {\n\t\tencoding: \"utf8\",\n\t}).stdout;\n\treturn command.includes(launchFile);\n};\n\nconst readState = async (file: string): Promise<RuntimeState | undefined> => {\n\tconst text = await readFile(file, \"utf8\").catch(() => undefined);\n\tif (text === undefined) {\n\t\treturn undefined;\n\t}\n\ttry {\n\t\treturn runtimeStateSchema.parse(JSON.parse(text));\n\t} catch {\n\t\treturn undefined;\n\t}\n};\n\n/** Stops the project's runtime that an earlier `run --bun` left running, which saves its retained values. */\nconst stopRunning = async (directory: string, log: (line: string) => void) => {\n\tconst stateFile = join(directory, runtimeFiles.state);\n\tconst state = await readState(stateFile);\n\tif (!state || !isRuntime(state.pid, join(directory, runtimeFiles.launch))) {\n\t\tawait rm(stateFile, { force: true });\n\t\treturn;\n\t}\n\tlog(`Stopping the Bun runtime that runs as process ${state.pid}`);\n\tprocess.kill(state.pid, \"SIGTERM\");\n\tconst deadline = Date.now() + stopTimeoutMs;\n\twhile (alive(state.pid)) {\n\t\tif (Date.now() >= deadline) {\n\t\t\tprocess.kill(state.pid, \"SIGKILL\");\n\t\t\tbreak;\n\t\t}\n\t\tawait delay(100);\n\t}\n\tawait rm(stateFile, { force: true });\n};\n\n/**\n * Starts the program in the Bun runtime, as `tsplc run --simulate --bun` does, replacing the\n * project's runtime that is running. Detached, the runtime keeps running after this returns,\n * writing to its log, until the next `run --bun` replaces it or it is sent SIGTERM; in the\n * foreground it runs, writing to this terminal, until it is interrupted.\n */\nexport const runInBun = async (options: {\n\troot: string;\n\tlaunch: Launch;\n\tenvironment: Readonly<Record<string, string | undefined>>;\n\tforeground: boolean;\n\tprogress: ProgressStream;\n}) => {\n\tconst log = progressLog(options.progress);\n\tconst directory = join(options.root, runtimeDirectory);\n\tawait mkdir(directory, { recursive: true });\n\tawait stopRunning(directory, log);\n\tconst launchFile = join(directory, runtimeFiles.launch);\n\tawait writeFile(launchFile, `${JSON.stringify(options.launch, null, 2)}\\n`);\n\tconst logFile = join(directory, runtimeFiles.log);\n\tconst command = [runtimeScript(), launchFile];\n\tif (options.foreground) {\n\t\tlog(\"Running the program in Bun; stop it with Ctrl-C\");\n\t\tconst child = spawn(process.execPath, command, {\n\t\t\tcwd: options.root,\n\t\t\tenv: options.environment,\n\t\t\tstdio: \"inherit\",\n\t\t});\n\t\t// The terminal's Ctrl-C reaches the runtime too, so this process only waits for it to stop;\n\t\t// a SIGTERM sent to this process alone is passed on.\n\t\tconst wait = () => undefined;\n\t\tconst forward = () => child.kill(\"SIGTERM\");\n\t\tprocess.on(\"SIGINT\", wait);\n\t\tprocess.on(\"SIGTERM\", forward);\n\t\tconst code = await new Promise<number | null>((resolve) =>\n\t\t\tchild.once(\"exit\", resolve),\n\t\t);\n\t\tprocess.off(\"SIGINT\", wait);\n\t\tprocess.off(\"SIGTERM\", forward);\n\t\tif (code !== 0) {\n\t\t\tthrow new Error(`The Bun runtime exited with code ${code}.`);\n\t\t}\n\t\treturn { stopped: true };\n\t}\n\tconst output = openSync(logFile, \"w\");\n\tconst child = spawn(process.execPath, command, {\n\t\tcwd: options.root,\n\t\tenv: options.environment,\n\t\tdetached: true,\n\t\tstdio: [\"ignore\", output, output],\n\t});\n\tconst exited: { code: number | null; done: boolean } = {\n\t\tcode: null,\n\t\tdone: false,\n\t};\n\tchild.once(\"exit\", (code) => {\n\t\tObject.assign(exited, { code, done: true });\n\t});\n\tconst stateFile = join(directory, runtimeFiles.state);\n\tconst deadline = Date.now() + startTimeoutMs;\n\twhile (true) {\n\t\tconst state = await readState(stateFile);\n\t\tif (state && state.pid === child.pid) {\n\t\t\tchild.unref();\n\t\t\tconst shown = relative(process.cwd(), logFile) || logFile;\n\t\t\tlog(\n\t\t\t\t`The program runs in Bun as process ${state.pid}: OPC UA at ${state.endpoint}, output in ${shown}`,\n\t\t\t);\n\t\t\treturn { ...state, log: logFile };\n\t\t}\n\t\tif (exited.done || Date.now() >= deadline) {\n\t\t\tif (!exited.done) {\n\t\t\t\tchild.kill(\"SIGTERM\");\n\t\t\t}\n\t\t\tconst tail = (await readFile(logFile, \"utf8\").catch(() => \"\"))\n\t\t\t\t.trimEnd()\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.slice(-30)\n\t\t\t\t.join(\"\\n\");\n\t\t\tthrow new Error(\n\t\t\t\t`The Bun runtime ${exited.done ? `exited with code ${exited.code}` : \"did not start in time\"}:\\n${tail}`,\n\t\t\t);\n\t\t}\n\t\tawait delay(100);\n\t}\n};\n"
12
+ "import { basename, relative, resolve, sep } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { ReleaseManifest } from \"@tsplc/agent\";\nimport type { ReleaseFile } from \"@tsplc/agent/client\";\nimport { checkHostConfig } from \"@tsplc/compiler\";\nimport { hasErrors } from \"@tsplc/compiler/ir\";\nimport {\n\tbuildTargetFor,\n\tcontrollerFor,\n\ttype Environment,\n\ttype LoadedConfig,\n\tserverTokenEnv,\n} from \"@tsplc/config\";\nimport type { ReleaseConfig } from \"@tsplc/config/build\";\nimport { explainFileName } from \"@tsplc/debug/explain-file\";\nimport { debugManifestFile } from \"@tsplc/debug/manifest\";\nimport { contractVariables, plcContractSchema } from \"@tsplc/opcua/contract\";\nimport { generateProject } from \"@tsplc/typegen\";\nimport { buildConfigs, buildTypeScriptProject } from \"./project\";\nimport { bundleServer, startServerCheck } from \"./server\";\n\n/** Every published leaf the generated contract at `file` describes, as CODESYS expressions name it. */\nconst releaseVariables = async (file: string | null) => {\n\tif (file === null) {\n\t\treturn [];\n\t}\n\tconst contract = plcContractSchema.parse(\n\t\tawait import(pathToFileURL(file).href),\n\t);\n\treturn contractVariables(contract).map(({ path, type }) => ({ path, type }));\n};\n\n/**\n * Compiles the program and bundles its server into the files `tsplc deploy` uploads: the\n * production program, or with `--simulate` the development one without fieldbus I/O, for a\n * virtual PLC whose inputs a plant simulation writes, as `tsplc run --simulate` builds it.\n */\nexport const prepareRelease = async (\n\tloaded: LoadedConfig,\n\tflags: { simulate?: boolean; \"frozen-lockfile\"?: boolean },\n\tbuilt: {\n\t\t/** What the build reads, with the plant PC's values and placeholders for its secrets. */\n\t\tenv: Environment;\n\t\t/** Every plain value the release carries to its server. */\n\t\tvalues: ReleaseManifest[\"values\"];\n\t\t/** The secrets the agent fills in. */\n\t\tsecrets: ReleaseManifest[\"secrets\"];\n\t},\n) => {\n\t// Every step reads the loaded config's environment, so it carries the plant PC's.\n\tconst project: LoadedConfig = { ...loaded, env: built.env };\n\tconst { config, root } = project;\n\tif (!config.compiler) {\n\t\tthrow new Error(\"tsplc deploy deploys tsPLC programs; configure compiler.\");\n\t}\n\tconst command = flags.simulate ? \"run\" : \"deploy\";\n\tconst serverCheck = config.server?.runtime\n\t\t? startServerCheck(config, root)\n\t\t: undefined;\n\tconst emitted = await buildTypeScriptProject(project.configFile, {\n\t\temitOnly: true,\n\t\tforController: true,\n\t\tfrozenLockfile: flags[\"frozen-lockfile\"],\n\t\t...buildConfigs(project, flags),\n\t\thostConfigDiagnostics: checkHostConfig(project.configFile),\n\t\tbuildTarget: buildTargetFor(command),\n\t\tcontroller: controllerFor(config, command),\n\t});\n\tif (hasErrors(emitted.diagnostics)) {\n\t\treturn { diagnostics: emitted.diagnostics };\n\t}\n\tconst settings = emitted.controllerConfig;\n\tif (!settings) {\n\t\tthrow new Error(\"Configure build settings for deployment.\");\n\t}\n\tconst { contract } = await generateProject(project, {\n\t\ttargets: emitted.targets,\n\t});\n\n\tconst portable = (path: string) => path.split(sep).join(\"/\");\n\tconst libraries = (settings.libraries ?? []).map((library) => ({\n\t\t...library,\n\t\trelease: `libraries/${library.sha256}-${basename(library.path)}`,\n\t}));\n\tconst files: ReleaseFile[] = [\n\t\t{ path: \"template.project\", content: Bun.file(settings.template) },\n\t\t...libraries.map((library) => ({\n\t\t\tpath: library.release,\n\t\t\tcontent: Bun.file(library.path),\n\t\t})),\n\t];\n\t// The agent compiles only the ST. Plain TypeScript programs emit their generated modules under `.tsplc/`.\n\tfor await (const source of new Bun.Glob(\"**/*.st\").scan({\n\t\tcwd: settings.sourceDir,\n\t\tdot: true,\n\t})) {\n\t\tfiles.push({\n\t\t\tpath: `st/${portable(source)}`,\n\t\t\tcontent: Bun.file(resolve(settings.sourceDir, source)),\n\t\t});\n\t}\n\t// The agent's debugger reads the program through its debug manifest, and explains it with `explain.json`.\n\tfor (const name of [debugManifestFile, explainFileName]) {\n\t\tfiles.push({\n\t\t\tpath: name,\n\t\t\tcontent: Bun.file(resolve(settings.sourceDir, name)),\n\t\t});\n\t}\n\tconst serverScript =\n\t\tserverCheck && (await bundleServer(await serverCheck, config, root));\n\tconst server = serverScript\n\t\t? {\n\t\t\t\tpath: `server/${basename(serverScript)}`,\n\t\t\t\tcontent: Bun.file(serverScript),\n\t\t\t}\n\t\t: undefined;\n\tif (server) {\n\t\tfiles.push(server);\n\t}\n\t// Paths are relative to the release. Naming every release field keeps a new build setting\n\t// from reaching the agent, or being left behind, without a decision here.\n\tconst releaseConfig: {\n\t\t[Key in keyof Required<ReleaseConfig>]: ReleaseConfig[Key];\n\t} = {\n\t\tio: settings.io,\n\t\tdeviceTree: settings.deviceTree,\n\t\tcontroller: settings.controller,\n\t\tlibraryReferences: settings.libraryReferences,\n\t\tlibraries: libraries.map(({ release, ...library }) => ({\n\t\t\t...library,\n\t\t\tpath: release,\n\t\t})),\n\t\ttask: settings.task,\n\t\ttasks: settings.tasks,\n\t\tremoveObjects: settings.removeObjects,\n\t\tsymbols: settings.symbols,\n\t\ttimeouts: settings.timeouts,\n\t\ttemplate: \"template.project\",\n\t\tsourceDir: \"st\",\n\t\tentry: `st/${portable(relative(settings.sourceDir, settings.entry))}`,\n\t};\n\tconst manifest: ReleaseManifest = {\n\t\tconfig: releaseConfig,\n\t\tvariables: await releaseVariables(contract),\n\t\tserver: server?.path,\n\t\tdebug: config.debug,\n\t\tserverTokenEnv: serverTokenEnv(config),\n\t\tsecrets: built.secrets,\n\t\tvalues: built.values,\n\t};\n\treturn { release: { manifest, files } };\n};\n",
13
+ "import {\n\tcopyFile,\n\tmkdir,\n\tmkdtemp,\n\trealpath,\n\trm,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport {\n\tbuildFiles,\n\tinstallLibraries,\n\ttype ProgressOptions,\n} from \"@tsplc/build\";\nimport { analyze, type BoundPath } from \"@tsplc/compiler\";\nimport {\n\tbuildCodesys,\n\ttype CodesysPlan,\n\ttype CodesysProject,\n\tcodesysBuildConfig,\n\tdiagnoseCodesys,\n\temitCodesys,\n\tioTargets,\n\tplanCodesys,\n\tpublicationSelectors,\n\ttype SourceMapping,\n} from \"@tsplc/compiler/codesys\";\nimport {\n\ttype Diagnostic,\n\thasErrors,\n\tnormalizeModule,\n\ttype VerifiedCoreModule,\n} from \"@tsplc/compiler/ir\";\nimport {\n\ttype BuildTarget,\n\ttype Controller,\n\tcompilerConfig,\n\ttype LoadedConfig,\n\ttype NormalizedConfig,\n\ttype ResolvedTsplcConfig,\n\tserverBaseUrl,\n\tsimulationConfig,\n\ttaskPlan,\n} from \"@tsplc/config\";\nimport {\n\tconfigFileName,\n\temittedFiles,\n\temittedStDirectory,\n} from \"@tsplc/config/project-files\";\nimport { explainFileName } from \"@tsplc/debug/explain-file\";\nimport { debugManifestFile } from \"@tsplc/debug/manifest\";\nimport {\n\tdeviceTree,\n\tloadHardware,\n\ttype ProjectTargets,\n\tresolveIo,\n} from \"@tsplc/typegen\";\nimport { serviceRoutes } from \"../runtime/launch\";\nimport {\n\tclaimed,\n\tcleanArtifacts,\n\tengineeringDirectory,\n\towned,\n\tpublishArtifacts,\n\twithdrawReceipt,\n} from \"./artifacts\";\n\nconst emittedSt = basename(emittedStDirectory);\n\nconst failure = (\n\torigin: Diagnostic[\"origin\"],\n\tcode: string,\n\tcause: unknown,\n): Diagnostic => ({\n\torigin,\n\tcode,\n\tseverity: \"error\",\n\tmessage: cause instanceof Error ? cause.message : String(cause),\n});\n\n/**\n * `buildTypeScriptProject`'s `loaded` and `configured` options. With `simulate` the build omits fieldbus\n * I/O so a plant simulator can write the inputs; generated types and the debug manifest keep\n * describing the hardware project.\n */\nexport const buildConfigs = (\n\tloaded: LoadedConfig,\n\toptions: { simulate?: boolean },\n) =>\n\toptions.simulate\n\t\t? {\n\t\t\t\tloaded: { ...loaded, config: simulationConfig(loaded.config) },\n\t\t\t\tconfigured: loaded.config,\n\t\t\t}\n\t\t: { loaded };\n\ninterface ProjectOptions {\n\t/** The config, whose `env` the program's `env()` calls, endpoints and telemetry read. */\n\tloaded: LoadedConfig;\n\tbuildTarget?: BuildTarget;\n\t/** The configuration `loaded` simulates, whose hardware the debug manifest describes. */\n\tconfigured?: ResolvedTsplcConfig;\n\t/** The host config check's diagnostics, which type-check the config before it runs. */\n\thostConfigDiagnostics: readonly Diagnostic[];\n}\n\n/** The project `file` configures, or the diagnostics of why it can't be compiled. */\nasync function loadProject(\n\tfile: string,\n\t{ loaded, buildTarget, configured, hostConfigDiagnostics }: ProjectOptions,\n): Promise<\n\t| {\n\t\t\tconfig: NormalizedConfig;\n\t\t\tconfigFile: string;\n\t\t\tshared: ResolvedTsplcConfig;\n\t\t\tproject: CodesysProject;\n\t\t\t/** The state paths the hardware's `io` binds, which a simulator writes too. */\n\t\t\tbound: BoundPath[];\n\t\t\tdiagnostics: readonly Diagnostic[];\n\t }\n\t| { configFile: string; diagnostics: readonly Diagnostic[] }\n> {\n\tconst unresolved = resolve(file);\n\tconst configFile = await realpath(unresolved).catch((cause: unknown) =>\n\t\tunloaded(unresolved, cause),\n\t);\n\tif (typeof configFile !== \"string\") {\n\t\treturn configFile;\n\t}\n\ttry {\n\t\tif (hasErrors(hostConfigDiagnostics)) {\n\t\t\treturn { configFile, diagnostics: hostConfigDiagnostics };\n\t\t}\n\t\tconst { config: shared, env } = loaded;\n\t\tif (\n\t\t\tshared.debug?.trace &&\n\t\t\tshared.server?.transport !== \"opcua\" &&\n\t\t\t!serverBaseUrl(shared, env)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t'debug.trace sends its records to the app server: configure server with baseUrlEnv and set that variable, or use server.transport \"opcua\".',\n\t\t\t);\n\t\t}\n\t\tconst root = dirname(configFile);\n\t\tconst catalog = await loadHardware(shared, root);\n\n\t\tconst config = compilerConfig(\n\t\t\tshared,\n\t\t\tresolveIo(shared, catalog),\n\t\t\tbuildTarget,\n\t\t);\n\t\tconst hardware = configured\n\t\t\t? { config: configured, catalog: await loadHardware(configured, root) }\n\t\t\t: { config: shared, catalog };\n\t\treturn {\n\t\t\tconfigFile,\n\t\t\tshared,\n\t\t\tconfig: { ...config, ...sourceInput(config, root) },\n\t\t\tproject: {\n\t\t\t\troot,\n\t\t\t\tenvironment: env,\n\t\t\t\t...(shared.debug && { debug: shared.debug }),\n\t\t\t\t...(shared.telemetry && { telemetry: shared.telemetry }),\n\t\t\t\t...(shared.server && { server: shared.server }),\n\t\t\t\t...(shared.hmi && { hmi: shared.hmi }),\n\t\t\t\t// A simulation build drops fieldbus IO, but the debugger still shows the hardware it stands in for.\n\t\t\t\thardware: {\n\t\t\t\t\t...hardware,\n\t\t\t\t\ttree: shared.codesys?.deviceTree !== undefined,\n\t\t\t\t},\n\t\t\t},\n\t\t\tbound: boundPaths(resolveIo(hardware.config, hardware.catalog)),\n\t\t\tdiagnostics: hostConfigDiagnostics,\n\t\t};\n\t} catch (cause) {\n\t\treturn unloaded(configFile, cause);\n\t}\n}\n\nconst unloaded = (configFile: string, cause: unknown) => ({\n\tconfigFile,\n\tdiagnostics: [failure(\"config\", \"PLC5003\", cause)],\n});\n\n/** The analyzer's entry points, resolved against the config file's directory. */\nfunction sourceInput(\n\tcompiler: {\n\t\ttsconfig: string;\n\t\tprograms: Record<string, { module: string; export: string }>;\n\t},\n\troot: string,\n) {\n\treturn {\n\t\ttsconfig: resolve(root, compiler.tsconfig),\n\t\tprograms: Object.fromEntries(\n\t\t\tObject.entries(compiler.programs).map(([name, entry]) => [\n\t\t\t\tname,\n\t\t\t\t{ ...entry, module: resolve(root, entry.module) },\n\t\t\t]),\n\t\t),\n\t};\n}\n\n/**\n * I/O keys and publication selectors from analyzed PLC source. It ignores the\n * config's own type errors, so a typo cannot switch off the types that flag it;\n * it is undefined only while the source itself fails analysis.\n */\nexport async function projectTargets(\n\tfile: string,\n\t{ config, env }: LoadedConfig,\n): Promise<ProjectTargets | undefined> {\n\tconst configFile = await realpath(resolve(file));\n\tif (!config.compiler) {\n\t\treturn undefined;\n\t}\n\tconst source = analyze({\n\t\t...sourceInput(config.compiler, dirname(configFile)),\n\t\tservices: config.server,\n\t\tenvironment: env,\n\t\t// A device channel's direction needs the hardware, which check and build resolve.\n\t\tio: boundPaths(config.io),\n\t});\n\tconst core = source.module && normalizeModule(source.module).core;\n\treturn core ? coreTargets(core) : undefined;\n}\n\n/** The state paths `io` binds, each marked with the `%I` address the hardware writes it from. */\nconst boundPaths = (io: ResolvedTsplcConfig[\"io\"]): BoundPath[] =>\n\tObject.entries(io).map(([path, binding]) => ({\n\t\tpath,\n\t\tinput:\n\t\t\t\"address\" in binding && binding.address.startsWith(\"%I\")\n\t\t\t\t? binding.address\n\t\t\t\t: null,\n\t}));\n\nconst coreTargets = (core: VerifiedCoreModule): ProjectTargets => ({\n\tio: ioTargets(core),\n\tpublication: publicationSelectors(core),\n});\n\nexport async function checkProject(\n\tfile: string,\n\toptions: ProjectOptions,\n): Promise<{\n\tconfigFile: string;\n\tconfig?: NormalizedConfig;\n\tshared?: ResolvedTsplcConfig;\n\tplan?: CodesysPlan;\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\tconst loaded = await loadProject(file, options);\n\tif (!(\"project\" in loaded)) {\n\t\treturn loaded;\n\t}\n\n\tconst { config } = loaded;\n\tconst source = analyze({\n\t\ttsconfig: config.tsconfig,\n\t\tprograms: config.programs,\n\t\tservices: loaded.shared.server,\n\t\tenvironment: loaded.project.environment,\n\t\tio: loaded.bound,\n\t});\n\tif (!source.module) {\n\t\treturn { ...loaded, diagnostics: source.diagnostics };\n\t}\n\tconst normalized = normalizeModule(source.module);\n\tif (!normalized.core) {\n\t\treturn { ...loaded, diagnostics: normalized.diagnostics };\n\t}\n\n\tconst tasks = taskPlan(config.tasks);\n\tconst planned = planCodesys(\n\t\tnormalized.core,\n\t\t{ tasks },\n\t\tconfig.target.options,\n\t\tloaded.project,\n\t);\n\treturn {\n\t\t...loaded,\n\t\t...planned,\n\t\tdiagnostics: [\n\t\t\t...loaded.diagnostics,\n\t\t\t...source.diagnostics,\n\t\t\t...normalized.diagnostics,\n\t\t\t...planned.diagnostics,\n\t\t],\n\t};\n}\n\n/** The installed libraries and fieldbus device tree a CODESYS project of this program needs. */\nasync function engineeringInputs(\n\tshared: ResolvedTsplcConfig,\n\tconfigFile: string,\n\tbundle: Pick<ReturnType<typeof emitCodesys>, \"ioMappings\">,\n\toptions: { frozen?: boolean },\n) {\n\tconst root = dirname(configFile);\n\tconst tree = await deviceTree(shared, await loadHardware(shared, root));\n\treturn {\n\t\tlibraries: await installLibraries(shared.dependencies, root, options),\n\t\t// The emitted names locate mapped IO; the tree maps their channels.\n\t\tdeviceTree: tree && {\n\t\t\t...tree,\n\t\t\tmappings: bundle.ioMappings.map(({ address, variable }) => ({\n\t\t\t\taddress,\n\t\t\t\tvariable,\n\t\t\t})),\n\t\t},\n\t};\n}\n\nconst missingBuildSection =\n\t'Compiling with CODESYS needs a build section in the config, for example build: { outDir: \"build/codesys\" }. Add one, or emit the Structured Text only with build --emit-only.';\n\nexport async function buildTypeScriptProject(\n\tfile: string,\n\toptions: ProjectOptions & {\n\t\temitOnly?: boolean;\n\t\tfrozenLockfile?: boolean;\n\t\tcontroller?: Controller;\n\t\t/** Resolve libraries and the device tree into `controllerConfig` even when only emitting. */\n\t\tforController?: boolean;\n\t} & ProgressOptions,\n): Promise<{\n\tdirectory?: string;\n\tstatus?: \"emitted\" | \"vendor-compiled\";\n\tcontrollerConfig?: ReturnType<typeof codesysBuildConfig>;\n\t/** What `projectTargets` reads from the program, from this build's own analysis. */\n\ttargets?: ProjectTargets;\n\t/** The route of each service procedure the program calls, as `serviceRoutes` reads them. */\n\tservices?: Readonly<Record<string, string>>;\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\tlet staging: string | undefined;\n\ttry {\n\t\tconst configFile = await realpath(resolve(file));\n\t\t// Withdraw the previous success receipt before checking the new source.\n\t\t// Old artifacts remain owned and intact until publication succeeds.\n\t\tconst claim = await claimed(configFile);\n\t\tawait withdrawReceipt(claim);\n\t\tconst previous = await owned(claim);\n\t\tif (previous.unknown.length) {\n\t\t\tthrow new Error(\n\t\t\t\t`Output contains unrelated files: ${previous.unknown.join(\", \")}`,\n\t\t\t);\n\t\t}\n\n\t\tconst checked = await checkProject(configFile, options);\n\t\tif (!checked.plan || !checked.config) {\n\t\t\treturn { diagnostics: checked.diagnostics };\n\t\t}\n\t\tconst bundle = emitCodesys(checked.plan);\n\t\tconst shared = checked.shared;\n\t\tconst outDir =\n\t\t\tshared?.build && resolve(dirname(configFile), shared.build.outDir);\n\t\tif (!options.emitOnly && !outDir) {\n\t\t\treturn {\n\t\t\t\tdiagnostics: [\n\t\t\t\t\t...checked.diagnostics,\n\t\t\t\t\tfailure(\"config\", \"PLC5003\", missingBuildSection),\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t\tconst engineering =\n\t\t\tshared && (!options.emitOnly || options.forController)\n\t\t\t\t? await engineeringInputs(shared, configFile, bundle, {\n\t\t\t\t\t\tfrozen: options.frozenLockfile,\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\t\t// The emitted ST already binds the program's I/O; bindings here would have the controller\n\t\t// build bind it a second time.\n\t\tconst controllerConfig = outDir\n\t\t\t? {\n\t\t\t\t\t...codesysBuildConfig(checked.plan, bundle, {\n\t\t\t\t\t\tconfigFile,\n\t\t\t\t\t\tsourceDir: join(previous.output, emittedSt),\n\t\t\t\t\t\toutDir,\n\t\t\t\t\t\tcontroller: options.controller,\n\t\t\t\t\t\t...engineering,\n\t\t\t\t\t}),\n\t\t\t\t\tio: {},\n\t\t\t\t}\n\t\t\t: undefined;\n\n\t\tawait mkdir(previous.root, { recursive: true });\n\t\tstaging = await mkdtemp(join(previous.root, \"stage-\"));\n\t\tconst artifacts = [\n\t\t\t...bundle.artifacts,\n\t\t\t{\n\t\t\t\tpath: \"mappings.json\",\n\t\t\t\tcontent: `${JSON.stringify(compactMappings(bundle.mappings))}\\n`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: emittedFiles.ioSymbols,\n\t\t\t\tcontent: `${JSON.stringify(bundle.ioSymbols, null, 2)}\\n`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: emittedFiles.publication,\n\t\t\t\tcontent: `${JSON.stringify(bundle.publication, null, 2)}\\n`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: \"config.json\",\n\t\t\t\tcontent: `${JSON.stringify(checked.config, null, 2)}\\n`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: debugManifestFile,\n\t\t\t\tcontent: `${JSON.stringify(bundle.debug)}\\n`,\n\t\t\t},\n\t\t\t// The manifest's digest covers these exact bytes.\n\t\t\t{ path: explainFileName, content: bundle.explain },\n\t\t];\n\t\tconst stagedSt = join(staging, emittedSt);\n\t\t// Thousands of artifacts share a few hundred directories; each is made once.\n\t\tconst directories = new Set(\n\t\t\tartifacts.map((artifact) => dirname(join(stagedSt, artifact.path))),\n\t\t);\n\t\tfor (const directory of directories) {\n\t\t\tawait mkdir(directory, { recursive: true });\n\t\t}\n\t\tfor (const artifact of artifacts) {\n\t\t\tawait writeFile(join(stagedSt, artifact.path), artifact.content);\n\t\t}\n\n\t\tconst vendor =\n\t\t\toptions.emitOnly || !outDir\n\t\t\t\t? undefined\n\t\t\t\t: await compileVendor(checked.plan, bundle, {\n\t\t\t\t\t\tconfigFile,\n\t\t\t\t\t\tstaging,\n\t\t\t\t\t\t// The engineering cache has its own ownership marker and survives clean.\n\t\t\t\t\t\tengineeringDir: outDir,\n\t\t\t\t\t\tcontroller: options.controller,\n\t\t\t\t\t\tengineering,\n\t\t\t\t\t\tprogress: options.progress,\n\t\t\t\t\t});\n\t\tif (vendor && \"diagnostics\" in vendor) {\n\t\t\treturn vendor;\n\t\t}\n\n\t\tconst status = vendor ? \"vendor-compiled\" : \"emitted\";\n\t\tawait publishArtifacts(staging, previous, {\n\t\t\tconfigFile,\n\t\t\tstatus,\n\t\t\t...(vendor && {\n\t\t\t\tvendor: { application: vendor.application, tasks: vendor.tasks },\n\t\t\t}),\n\t\t});\n\t\t// Publication moved this directory into place; it is no longer staging.\n\t\tstaging = undefined;\n\t\treturn {\n\t\t\tdirectory: previous.output,\n\t\t\tstatus,\n\t\t\t...(controllerConfig && { controllerConfig }),\n\t\t\ttargets: coreTargets(checked.plan.core),\n\t\t\tservices: serviceRoutes(checked.plan.core),\n\t\t\tdiagnostics: checked.diagnostics,\n\t\t};\n\t} catch (cause) {\n\t\treturn { diagnostics: [failure(\"config\", \"PLC5004\", cause)] };\n\t} finally {\n\t\tif (staging) {\n\t\t\tawait rm(staging, { recursive: true, force: true });\n\t\t}\n\t}\n}\n\n/**\n * Compiles the staged ST with CODESYS and copies the vendor's project, application and checksum\n * into the staging tree's `vendor/`; the compiler's diagnostics when CODESYS refuses it.\n */\nasync function compileVendor(\n\tplan: CodesysPlan,\n\tbundle: ReturnType<typeof emitCodesys>,\n\toptions: {\n\t\tconfigFile: string;\n\t\tstaging: string;\n\t\tengineeringDir: string;\n\t\tcontroller: Controller | undefined;\n\t\tengineering: Awaited<ReturnType<typeof engineeringInputs>> | undefined;\n\t} & ProgressOptions,\n) {\n\tawait engineeringDirectory(options.engineeringDir, options.configFile);\n\tconst vendor = await buildCodesys(\n\t\tplan,\n\t\tbundle,\n\t\t{\n\t\t\tconfigFile: options.configFile,\n\t\t\tsourceDir: join(options.staging, emittedSt),\n\t\t\toutDir: options.engineeringDir,\n\t\t\tcontroller: options.controller,\n\t\t\t...options.engineering,\n\t\t},\n\t\t{ progress: options.progress },\n\t).catch((cause: unknown) => ({\n\t\tdiagnostics: diagnoseCodesys(cause, bundle),\n\t}));\n\tif (\"diagnostics\" in vendor) {\n\t\treturn vendor;\n\t}\n\tfor (const artifact of [\"project\", \"output\", \"checksum\"] as const) {\n\t\tconst path = vendor[artifact];\n\t\tif (!path) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst destination = join(\n\t\t\toptions.staging,\n\t\t\t\"vendor\",\n\t\t\tbasename(buildFiles[artifact]),\n\t\t);\n\t\tawait mkdir(dirname(destination), { recursive: true });\n\t\tawait copyFile(path, destination);\n\t}\n\treturn vendor;\n}\n\n/**\n * Source mappings with each ST path and source file written once: `mappings` rows are\n * `[object, line, file, start, end, sourceLine, sourceColumn]`, indexing `objects` and `files`.\n */\nfunction compactMappings(mappings: readonly SourceMapping[]) {\n\tconst objects = new Map<string, number>();\n\tconst files = new Map<string, number>();\n\tconst index = (table: Map<string, number>, value: string) => {\n\t\tconst known = table.get(value);\n\t\tif (known !== undefined) {\n\t\t\treturn known;\n\t\t}\n\t\ttable.set(value, table.size);\n\t\treturn table.size - 1;\n\t};\n\tconst rows = mappings.map(({ path, line, span }) => [\n\t\tindex(objects, path),\n\t\tline,\n\t\tindex(files, span.file),\n\t\tspan.start,\n\t\tspan.end,\n\t\tspan.line,\n\t\tspan.column,\n\t]);\n\treturn {\n\t\tobjects: [...objects.keys()],\n\t\tfiles: [...files.keys()],\n\t\tmappings: rows,\n\t};\n}\n\nexport async function cleanProject(file = configFileName): Promise<{\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\ttry {\n\t\tawait cleanArtifacts(await realpath(resolve(file)));\n\t\treturn { diagnostics: [] };\n\t} catch (cause) {\n\t\treturn { diagnostics: [failure(\"config\", \"PLC5004\", cause)] };\n\t}\n}\n",
14
+ "import type { VerifiedCoreModule } from \"@tsplc/compiler/ir\";\nimport { generatedDirectory } from \"@tsplc/config/project-files\";\nimport { serviceOfPath } from \"@tsplc/server/wire\";\nimport { z } from \"zod\";\n\n/** The Bun runtime's files, relative to the directory that holds a project's config. */\nexport const runtimeDirectory = `${generatedDirectory}/runtime`;\nexport const runtimeFiles = {\n\t/** What the runtime runs, written by `tsplc run --bun`. */\n\tlaunch: \"launch.json\",\n\t/** The running runtime, written once it serves and removed when it stops. */\n\tstate: \"state.json\",\n\t/** Retained globals, written when the runtime stops. */\n\tretain: \"retain.json\",\n\t/** A detached runtime's output. */\n\tlog: \"plc.log\",\n\t/** The OPC UA server's certificate store. */\n\tcertificates: \"pki\",\n} as const;\n\n/** What `tsplc run --bun` hands the runtime: the config to load, with its target, and how to reach the services the build compiled calls to. */\nexport const launchSchema = z.strictObject({\n\tconfig: z.string().nonempty(),\n\ttarget: z.string().nonempty().nullable(),\n\t/** Each service procedure's route, with its wire-contract version: `/tsplc/services/<version>/<path>` by `<path>`. */\n\tservices: z.record(\n\t\tz.string(),\n\t\tz.string().refine((route) => serviceOfPath(route) !== undefined),\n\t),\n});\nexport type Launch = z.infer<typeof launchSchema>;\n\n/** A runtime that serves: its process and where it publishes OPC UA. */\nexport const runtimeStateSchema = z.strictObject({\n\tpid: z.number().int().positive(),\n\tendpoint: z.string().startsWith(\"opc.tcp://\"),\n\tstartedAt: z.iso.datetime(),\n});\nexport type RuntimeState = z.infer<typeof runtimeStateSchema>;\n\n/** A service block's route: its URL's path over HTTP, the path its slots carry over OPC UA. */\nconst blockRoute = (\n\truntime: VerifiedCoreModule[\"blocks\"][number][\"runtime\"],\n) => {\n\tif (runtime?.kind === \"http\") {\n\t\treturn URL.parse(runtime.url)?.pathname;\n\t}\n\treturn runtime?.kind === \"rpc\" ? runtime.path : undefined;\n};\n\n/** The route each service call the program makes goes to, as the build compiled it. */\nexport const serviceRoutes = (core: VerifiedCoreModule) =>\n\tObject.fromEntries(\n\t\tcore.blocks.flatMap((block) => {\n\t\t\tconst route = blockRoute(block.runtime);\n\t\t\tconst procedure = route && serviceOfPath(route);\n\t\t\treturn route && procedure ? [[procedure, route] as const] : [];\n\t\t}),\n\t);\n",
15
+ "import { createHash } from \"node:crypto\";\nimport {\n\tlstat,\n\tmkdir,\n\treaddir,\n\treadFile,\n\trename,\n\trm,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { dirname, join, relative } from \"node:path\";\nimport { cyclicTasksSchema, sha256Digest } from \"@tsplc/config/build\";\nimport {\n\temittedStDirectory,\n\tgeneratedDirectory,\n} from \"@tsplc/config/project-files\";\nimport { z } from \"zod\";\nimport { isMissingFile } from \"../runtime/missing-file\";\n\nconst digest = (value: string | Uint8Array): string =>\n\tcreateHash(\"sha256\").update(value).digest(\"hex\");\n\n/** The files that record who owns the artifacts and the engineering cache, beside what they own. */\nconst artifactFiles = {\n\t/** Every generated file with its digest, in the artifacts directory. */\n\tmanifest: \"manifest.json\",\n\t/** The last successful build, beside the manifest. */\n\treceipt: \"receipt.json\",\n\t/** The configuration an engineering cache belongs to, in the cache. */\n\tmarker: \"ownership.json\",\n} as const;\n\n/**\n * How an ownership record names its configuration: relative to the directory the record sits in,\n * so the whole project keeps its outputs when it moves or is copied.\n */\nconst configReference = (directory: string, configFile: string) =>\n\trelative(directory, configFile);\n\n/** Whether a record in `directory` names `configFile`; older records hold its absolute path. */\nconst namesConfig = (recorded: string, directory: string, configFile: string) =>\n\trecorded === configReference(directory, configFile) ||\n\trecorded === configFile;\n\nconst generatedFileSchema = z.object({\n\tpath: z\n\t\t.string()\n\t\t.regex(/^[A-Za-z0-9_ .-]+(?:\\/[A-Za-z0-9_ .-]+)*$/)\n\t\t.refine(\n\t\t\t(path) =>\n\t\t\t\t!path.split(\"/\").some((part) => part === \".\" || part === \"..\") &&\n\t\t\t\tpath !== artifactFiles.manifest &&\n\t\t\t\tpath !== artifactFiles.receipt,\n\t\t),\n\tsha256: sha256Digest,\n});\n\n/** The manifest's envelope; its entries are checked one by one to name the failure. */\nconst manifestSchema = z.object({\n\tkind: z.literal(\"tsplc-artifacts\"),\n\tversion: z.literal(1),\n\tconfigFile: z.string(),\n\tfiles: z.array(z.unknown()),\n});\n\ntype Manifest = Omit<z.infer<typeof manifestSchema>, \"files\"> & {\n\tfiles: z.infer<typeof generatedFileSchema>[];\n};\n\nconst receiptSchema = z.object({\n\tkind: z.literal(\"tsplc-build\"),\n\tversion: z.literal(1),\n\tgeneratedAt: z.iso.datetime(),\n\tconfigFile: z.string(),\n\tstatus: z.enum([\"emitted\", \"vendor-compiled\"]),\n\t/** The application and tasks CODESYS compiled. */\n\tvendor: z\n\t\t.object({ application: z.string(), tasks: cyclicTasksSchema.optional() })\n\t\t.optional(),\n});\n\nconst engineeringMarkerSchema = z.object({\n\tkind: z.literal(\"tsplc-engineering\"),\n\tversion: z.literal(1),\n\tconfigFile: z.string(),\n});\n\nfunction manifest(\n\tvalue: unknown,\n\toutput: string,\n\tconfigFile: string,\n): Manifest {\n\tconst parsed = manifestSchema.safeParse(value);\n\tif (\n\t\t!parsed.success ||\n\t\t!namesConfig(parsed.data.configFile, output, configFile)\n\t) {\n\t\tthrow new Error(\n\t\t\t\"Output directory has no matching tsPLC ownership manifest.\",\n\t\t);\n\t}\n\n\tconst files = parsed.data.files.map((item) => {\n\t\tconst file = generatedFileSchema.safeParse(item);\n\t\tif (!file.success) {\n\t\t\tthrow new Error(\"Invalid generated file ownership entry.\");\n\t\t}\n\t\treturn file.data;\n\t});\n\tif (new Set(files.map((item) => item.path)).size !== files.length) {\n\t\tthrow new Error(\"Duplicate generated file ownership entry.\");\n\t}\n\treturn { ...parsed.data, files };\n}\n\nasync function directory(path: string): Promise<boolean> {\n\ttry {\n\t\tconst entry = await lstat(path);\n\t\tif (!entry.isDirectory() || entry.isSymbolicLink()) {\n\t\t\tthrow new Error(`Generated directory must be a real directory: ${path}`);\n\t\t}\n\t\treturn true;\n\t} catch (cause) {\n\t\tif (isMissingFile(cause)) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow cause;\n\t}\n}\n\nasync function filesIn(path: string, prefix = \"\"): Promise<string[]> {\n\tconst result: string[] = [];\n\tfor (const entry of await readdir(path, { withFileTypes: true })) {\n\t\tconst name = prefix + entry.name;\n\t\tif (entry.isDirectory() && !entry.isSymbolicLink()) {\n\t\t\tresult.push(...(await filesIn(join(path, entry.name), `${name}/`)));\n\t\t} else {\n\t\t\tresult.push(name);\n\t\t}\n\t}\n\treturn result;\n}\n\nexport async function engineeringDirectory(\n\tpath: string,\n\tconfigFile: string,\n): Promise<void> {\n\tconst marker = join(path, artifactFiles.marker);\n\tconst exists = await directory(path);\n\tif (!exists || !(await readdir(path)).length) {\n\t\tawait mkdir(path, { recursive: true });\n\t\tawait writeFile(\n\t\t\tmarker,\n\t\t\t`${JSON.stringify(\n\t\t\t\t{\n\t\t\t\t\tkind: \"tsplc-engineering\",\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tconfigFile: configReference(path, configFile),\n\t\t\t\t} satisfies z.infer<typeof engineeringMarkerSchema>,\n\t\t\t\tnull,\n\t\t\t\t2,\n\t\t\t)}\\n`,\n\t\t\t{ flag: \"wx\" },\n\t\t);\n\t} else if (!(await ownedMarker(path, configFile))) {\n\t\tthrow new Error(\n\t\t\t`Engineering cache has no matching tsPLC ownership marker: ${path}`,\n\t\t);\n\t}\n\n\tconst inspect = async (directory: string): Promise<void> => {\n\t\tfor (const entry of await readdir(directory, { withFileTypes: true })) {\n\t\t\tconst child = join(directory, entry.name);\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Engineering cache must not contain symlinks: ${child}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tawait inspect(child);\n\t\t\t}\n\t\t}\n\t};\n\tawait inspect(path);\n}\n\n/** Whether the engineering cache at `path` has a marker that names `configFile`; false when there is none. */\nconst ownedMarker = async (path: string, configFile: string) => {\n\tconst marker = join(path, artifactFiles.marker);\n\tconst entry = await lstat(marker).catch((cause: unknown) => {\n\t\tif (isMissingFile(cause)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tthrow cause;\n\t});\n\tif (!entry) {\n\t\treturn false;\n\t}\n\tif (!entry.isFile() || entry.isSymbolicLink()) {\n\t\tthrow new Error(\"Engineering ownership marker must be a real file.\");\n\t}\n\tconst value = engineeringMarkerSchema.safeParse(\n\t\tJSON.parse(await readFile(marker, \"utf8\")),\n\t);\n\treturn value.success && namesConfig(value.data.configFile, path, configFile);\n};\n\n/**\n * The artifacts directory of `configFile` and the manifest of what it owns there, once its\n * manifest and receipt name this configuration. `owned` goes on to check the owned files.\n */\nexport async function claimed(configFile: string): Promise<{\n\troot: string;\n\toutput: string;\n\townership?: Manifest;\n}> {\n\tconst root = join(dirname(configFile), generatedDirectory);\n\tconst output = join(dirname(configFile), dirname(emittedStDirectory));\n\tif (!(await directory(root)) || !(await directory(output))) {\n\t\treturn { root, output };\n\t}\n\n\tconst manifestPath = join(output, artifactFiles.manifest);\n\tconst manifestEntry = await lstat(manifestPath).catch((cause: unknown) => {\n\t\tif (isMissingFile(cause)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tthrow cause;\n\t});\n\t// Without a manifest nothing here is owned; `owned` lists whatever is there as unrelated.\n\tif (!manifestEntry) {\n\t\treturn { root, output };\n\t}\n\tif (!manifestEntry.isFile() || manifestEntry.isSymbolicLink()) {\n\t\tthrow new Error(\"Ownership manifest must be a real file.\");\n\t}\n\tconst ownership = manifest(\n\t\tJSON.parse(await readFile(manifestPath, \"utf8\")),\n\t\toutput,\n\t\tconfigFile,\n\t);\n\tconst receipt = join(output, artifactFiles.receipt);\n\ttry {\n\t\tconst entry = await lstat(receipt);\n\t\tif (!entry.isFile() || entry.isSymbolicLink()) {\n\t\t\tthrow new Error(\"Build receipt must be a real file.\");\n\t\t}\n\t\tconst value = receiptSchema.safeParse(\n\t\t\tJSON.parse(await readFile(receipt, \"utf8\")),\n\t\t);\n\t\tif (\n\t\t\t!value.success ||\n\t\t\t!namesConfig(value.data.configFile, output, configFile)\n\t\t) {\n\t\t\tthrow new Error(\"Build receipt is not owned by this configuration.\");\n\t\t}\n\t} catch (cause) {\n\t\tif (!isMissingFile(cause)) {\n\t\t\tthrow cause;\n\t\t}\n\t}\n\treturn { root, output, ownership };\n}\n\n/** The artifacts `claimed` found, with every owned file checked unchanged, and the files they don't own. */\nexport async function owned(\n\tclaim: Awaited<ReturnType<typeof claimed>>,\n): Promise<{\n\troot: string;\n\toutput: string;\n\townership?: Manifest;\n\tunknown: string[];\n}> {\n\tconst { output, ownership } = claim;\n\tif (!ownership) {\n\t\treturn {\n\t\t\t...claim,\n\t\t\tunknown: (await directory(output)) ? await filesIn(output) : [],\n\t\t};\n\t}\n\tconst names = new Set([\n\t\t...ownership.files.map((file) => file.path),\n\t\tartifactFiles.manifest,\n\t\tartifactFiles.receipt,\n\t]);\n\t// Thousands of files share a few hundred directories; each is checked once.\n\tconst checked = new Set<string>();\n\tfor (const file of ownership.files) {\n\t\tlet parent = output;\n\t\tfor (const part of file.path.split(\"/\").slice(0, -1)) {\n\t\t\tparent = join(parent, part);\n\t\t\tif (checked.has(parent)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!(await directory(parent))) {\n\t\t\t\tthrow new Error(`Missing generated directory: ${parent}`);\n\t\t\t}\n\t\t\tchecked.add(parent);\n\t\t}\n\t\tconst path = join(output, file.path);\n\t\tconst entry = await lstat(path);\n\t\tif (\n\t\t\t!entry.isFile() ||\n\t\t\tentry.isSymbolicLink() ||\n\t\t\tdigest(await readFile(path)) !== file.sha256\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Generated file was replaced or edited; preserve it before rebuilding/cleaning: ${path}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn {\n\t\t...claim,\n\t\tunknown: (await filesIn(output)).filter((name) => !names.has(name)),\n\t};\n}\n\n/** Removes the last successful build's receipt from the artifacts `claimed` found, if they have one. */\nexport const withdrawReceipt = async ({\n\toutput,\n}: Awaited<ReturnType<typeof claimed>>) => {\n\tawait rm(join(output, artifactFiles.receipt), { force: true });\n};\n\n/** What a build's receipt records about it, with the absolute path of its config file. */\ntype Receipt = Omit<\n\tz.input<typeof receiptSchema>,\n\t\"kind\" | \"version\" | \"generatedAt\"\n>;\n\n// Compile in a separate staging tree. Recheck ownership immediately before the\n// swap, because the vendor build may have given the user time to edit old files.\nexport async function publishArtifacts(\n\tstaging: string,\n\tprevious: Awaited<ReturnType<typeof owned>>,\n\treceipt: Receipt,\n): Promise<void> {\n\tconst configFile = configReference(previous.output, receipt.configFile);\n\tconst generated = (await filesIn(staging)).sort();\n\tconst ownership: Manifest = {\n\t\tkind: \"tsplc-artifacts\",\n\t\tversion: 1,\n\t\tconfigFile,\n\t\tfiles: [],\n\t};\n\tfor (const path of generated) {\n\t\townership.files.push({\n\t\t\tpath,\n\t\t\tsha256: digest(await readFile(join(staging, path))),\n\t\t});\n\t}\n\tawait writeFile(\n\t\tjoin(staging, artifactFiles.manifest),\n\t\t`${JSON.stringify(ownership, null, 2)}\\n`,\n\t);\n\tawait writeFile(\n\t\tjoin(staging, artifactFiles.receipt),\n\t\t`${JSON.stringify(\n\t\t\t{\n\t\t\t\tkind: \"tsplc-build\",\n\t\t\t\tversion: 1,\n\t\t\t\tgeneratedAt: new Date().toISOString(),\n\t\t\t\t...receipt,\n\t\t\t\tconfigFile,\n\t\t\t} satisfies z.input<typeof receiptSchema>,\n\t\t\tnull,\n\t\t\t2,\n\t\t)}\\n`,\n\t);\n\n\tconst current = await owned(await claimed(receipt.configFile));\n\tif (\n\t\tJSON.stringify(current.ownership) !== JSON.stringify(previous.ownership)\n\t) {\n\t\tthrow new Error(\n\t\t\t\"Output ownership changed during the build; preserve it before rebuilding.\",\n\t\t);\n\t}\n\tif (current.unknown.length) {\n\t\tthrow new Error(\n\t\t\t`Output contains unrelated files: ${current.unknown.join(\", \")}`,\n\t\t);\n\t}\n\n\tconst backup = `${staging}-previous`;\n\tif (previous.ownership) {\n\t\tawait rename(previous.output, backup);\n\t}\n\ttry {\n\t\tawait rename(staging, previous.output);\n\t} catch (cause) {\n\t\tif (previous.ownership) {\n\t\t\tawait rename(backup, previous.output);\n\t\t}\n\t\tthrow cause;\n\t}\n\tif (previous.ownership) {\n\t\tawait rm(backup, { recursive: true });\n\t}\n}\n\nexport async function cleanArtifacts(configFile: string): Promise<void> {\n\tconst generated = await owned(await claimed(configFile));\n\tif (!generated.ownership) {\n\t\treturn;\n\t}\n\tfor (const entry of generated.ownership.files) {\n\t\tawait rm(join(generated.output, entry.path));\n\t}\n\tawait rm(join(generated.output, artifactFiles.receipt), { force: true });\n\tawait rm(join(generated.output, artifactFiles.manifest));\n\n\tconst removeEmpty = async (path: string): Promise<void> => {\n\t\tfor (const entry of await readdir(path, { withFileTypes: true })) {\n\t\t\tif (entry.isDirectory() && !entry.isSymbolicLink()) {\n\t\t\t\tawait removeEmpty(join(path, entry.name));\n\t\t\t}\n\t\t}\n\t\tif (!(await readdir(path)).length) {\n\t\t\tawait rm(path, { recursive: true });\n\t\t}\n\t};\n\tawait removeEmpty(generated.output);\n}\n",
16
+ "/** Whether a file operation failed because the file isn't there, rather than because it can't be read. */\nexport const isMissingFile = (cause: unknown): boolean =>\n\tcause instanceof Error && \"code\" in cause && cause.code === \"ENOENT\";\n",
17
+ "import { existsSync } from \"node:fs\";\nimport { mkdir, mkdtemp, rename, rm } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { projectSlugs, type ResolvedTsplcConfig } from \"@tsplc/config\";\nimport { generatedDirectory } from \"@tsplc/config/project-files\";\nimport { z } from \"zod\";\n\nconst resolveServerModule = (root: string, name: string) =>\n\tname.startsWith(\".\") ||\n\tname.startsWith(\"/\") ||\n\texistsSync(resolve(root, name))\n\t\t? resolve(root, name)\n\t\t: createRequire(join(root, \"package.json\")).resolve(name);\n\n/**\n * `.tsplc/server/<name>-services<extension>`, where the server's script or executable goes: beside\n * the other generated outputs, never inside `build.outDir`, the CODESYS engineering cache.\n */\nconst serverOutput = (\n\tconfig: ResolvedTsplcConfig,\n\troot: string,\n\textension: string,\n) =>\n\tresolve(\n\t\troot,\n\t\tgeneratedDirectory,\n\t\t\"server\",\n\t\t`${projectSlugs.kebab(config.name)}-services${extension}`,\n\t);\n\n/** What `checkServer` posts to its worker: the server entry and the project root diagnostics are relative to. */\nexport const serverCheckRequestSchema = z.strictObject({\n\tentry: z.string(),\n\troot: z.string(),\n});\n\n/** The worker's answer: why the server entry fails its type check, or null when it passes. */\nexport const serverCheckResultSchema = z.strictObject({\n\tfailure: z.string().nullable(),\n});\n\n/** A server entry that passed its type check, and the runtime it is built for. */\nexport interface CheckedServer {\n\tentry: string;\n\truntime: NonNullable<NonNullable<ResolvedTsplcConfig[\"server\"]>[\"runtime\"]>;\n}\n\n/**\n * Type-checks the host entry as it will be built, on a worker thread: a caller that builds the\n * PLC program meanwhile awaits the result after it. The check rejects with the diagnostics.\n */\nexport const checkServer = async (\n\tconfig: ResolvedTsplcConfig,\n\troot: string,\n): Promise<CheckedServer> => {\n\tconst runtime = config.server?.runtime;\n\tif (!runtime) {\n\t\tthrow new Error(\"Configure server.runtime to build the server.\");\n\t}\n\tconst entry = resolveServerModule(root, runtime.entry);\n\tconst worker = new Worker(import.meta.resolve(\"#server-check\"));\n\ttry {\n\t\tconst answer = await new Promise<unknown>((resolve, reject) => {\n\t\t\tworker.onmessage = (event: MessageEvent) => resolve(event.data);\n\t\t\tworker.onerror = (event) => reject(new Error(event.message));\n\t\t\tconst request: z.infer<typeof serverCheckRequestSchema> = {\n\t\t\t\tentry,\n\t\t\t\troot,\n\t\t\t};\n\t\t\tworker.postMessage(request);\n\t\t});\n\t\tconst { failure } = serverCheckResultSchema.parse(answer);\n\t\tif (failure !== null) {\n\t\t\tthrow new Error(failure);\n\t\t}\n\t\treturn { entry, runtime };\n\t} finally {\n\t\tworker.terminate();\n\t}\n};\n\n/**\n * `checkServer` started now, for a caller that builds the PLC program meanwhile: a failed PLC\n * build reports its own diagnostics, so the check's outcome is read only after a success.\n */\nexport const startServerCheck = (config: ResolvedTsplcConfig, root: string) => {\n\tconst check = checkServer(config, root);\n\tcheck.catch(() => undefined);\n\treturn check;\n};\n\n/**\n * Bundles the host entry, which starts its own listener, into one minified script,\n * `.tsplc/server/<name>-services.js`, which the plant agent runs on its own Bun. It is a few MB\n * where an executable, which embeds Bun, is over 100, and deployments upload it.\n */\nexport const bundleServer = async (\n\t{ entry }: CheckedServer,\n\tconfig: ResolvedTsplcConfig,\n\troot: string,\n) => {\n\tconst outFile = serverOutput(config, root, \".js\");\n\tconst result = await Bun.build({\n\t\tentrypoints: [entry],\n\t\ttarget: \"bun\",\n\t\tminify: true,\n\t\tenv: \"disable\",\n\t});\n\tif (!result.success) {\n\t\tthrow new AggregateError(result.logs, \"Server bundle build failed.\");\n\t}\n\tconst [script, ...assets] = result.outputs;\n\tif (!script || assets.length) {\n\t\tthrow new Error(\n\t\t\t`The server bundle needs files beside its script (${assets.map(({ path }) => path).join(\", \")}), which deployments don't carry.`,\n\t\t);\n\t}\n\tawait mkdir(dirname(outFile), { recursive: true });\n\tawait Bun.write(outFile, script);\n\treturn outFile;\n};\n\n/** Compiles the host entry, which starts its own listener, into `.tsplc/server/<name>-services`. */\nexport const buildServer = async (\n\t{ entry, runtime }: CheckedServer,\n\tconfig: ResolvedTsplcConfig,\n\troot: string,\n) => {\n\tconst windows = runtime.target\n\t\t? runtime.target.includes(\"windows\")\n\t\t: process.platform === \"win32\";\n\tconst outFile = serverOutput(config, root, windows ? \".exe\" : \"\");\n\tawait mkdir(dirname(outFile), { recursive: true });\n\t// Compile beside the output so dependency resolution starts from the owning project.\n\tconst staging = await mkdtemp(join(dirname(outFile), \".tsplc-server-\"));\n\ttry {\n\t\tconst binary = join(staging, \"server\");\n\t\tconst result = await Bun.build({\n\t\t\tentrypoints: [entry],\n\t\t\tenv: \"disable\",\n\t\t\tcompile: {\n\t\t\t\toutfile: binary,\n\t\t\t\t...(runtime.target ? { target: runtime.target } : {}),\n\t\t\t\tautoloadDotenv: false,\n\t\t\t\tautoloadBunfig: false,\n\t\t\t\tautoloadTsconfig: false,\n\t\t\t\tautoloadPackageJson: false,\n\t\t\t},\n\t\t});\n\t\tif (!result.success) {\n\t\t\tthrow new AggregateError(result.logs, \"Server executable build failed.\");\n\t\t}\n\t\t// Bun names a Windows executable itself.\n\t\tawait rename(windows ? `${binary}.exe` : binary, outFile);\n\t\treturn {\n\t\t\tserver: {\n\t\t\t\texecutable: outFile,\n\t\t\t\ttarget: runtime.target ?? `bun-${process.platform}-${process.arch}`,\n\t\t\t},\n\t\t};\n\t} finally {\n\t\tawait rm(staging, { recursive: true, force: true });\n\t}\n};\n",
18
+ "import type { ParseArgsOptionsConfig, parseArgs } from \"node:util\";\nimport { z } from \"zod\";\n\n/** The flags `options` declares, as `parseArgs` reads them. */\nexport type Flags<Options extends ParseArgsOptionsConfig> = ReturnType<\n\ttypeof parseArgs<{ options: Options }>\n>[\"values\"];\n\n/** A flag that takes no value. */\nexport const flag = { type: \"boolean\" } as const;\n\n/** `--format`: JSON results on standard output, or text. */\nexport const outputFormatSchema = z.enum([\"json\", \"text\"]);\nexport type OutputFormat = z.infer<typeof outputFormatSchema>;\n",
19
+ "import type { ParseArgsOptionsConfig } from \"node:util\";\nimport {\n\task,\n\taskCredentials,\n\ttype Credentials,\n\ttype Target,\n\ttype Variable,\n} from \"@tsplc/agent\";\nimport { type AgentClient, createAgentClient } from \"@tsplc/agent/client\";\nimport { type LoginCommand, type LoginResult, resetLabel } from \"@tsplc/build\";\nimport type { Diagnostic } from \"@tsplc/compiler/ir\";\nimport {\n\tagentTokenEnv,\n\tagentUrlEnv,\n\ttype Environment,\n\ttype LoadedConfig,\n\ttype PlantVariables,\n\treleaseEnvironment,\n} from \"@tsplc/config\";\nimport { runtimePort } from \"@tsplc/config/build\";\nimport { LoginUnavailable, noLogin } from \"@tsplc/debug\";\nimport { isWithin } from \"@tsplc/iec/st\";\nimport { arrayIndex, symbolPathSegments } from \"@tsplc/opcua/contract\";\nimport { controllerRestartSchema } from \"@tsplc/server/plant-agent\";\nimport { z } from \"zod\";\nimport {\n\ttype Approval,\n\ttype Follow,\n\topenDashboard,\n\tprintDeployments,\n\tredeploy,\n\trollBack,\n\tsubmitDeployment,\n} from \"./deployments\";\nimport { type Flags, flag, type OutputFormat } from \"./flags\";\nimport { gitSource } from \"./git\";\nimport { prepareRelease } from \"./release\";\nimport {\n\tchoose,\n\tconfirm,\n\tconfirmOrCancel,\n\tprogress,\n\ttimedProgress,\n} from \"./terminal\";\n\n/** The flags of the plant commands. */\nexport const plantOptions = {\n\tdownload: flag,\n\treview: flag,\n\twait: flag,\n\t\"initialize-user\": flag,\n\trestore: flag,\n\tselect: flag,\n\tsimulate: flag,\n\tyes: { type: \"boolean\", short: \"y\" },\n\t\"frozen-lockfile\": flag,\n} as const satisfies ParseArgsOptionsConfig;\n\nexport type PlantFlags = Flags<typeof plantOptions> & { format?: OutputFormat };\n\n/** The plant agent named by `agentUrlEnv` and `agentTokenEnv` in `env`, where a target's agent sets the URL. */\nexport const connect = (env: Record<string, string | undefined>) => {\n\tconst environment = z\n\t\t.object({\n\t\t\t[agentUrlEnv]: z.url({\n\t\t\t\terror: `Configure the target's agent, or set ${agentUrlEnv} to the plant agent, such as http://plant-pc:4850`,\n\t\t\t}),\n\t\t\t[agentTokenEnv]: z.string({\n\t\t\t\terror: `Set ${agentTokenEnv} to the plant agent's token`,\n\t\t\t}),\n\t\t})\n\t\t.parse(env);\n\treturn createAgentClient({\n\t\turl: environment[agentUrlEnv],\n\t\ttoken: environment[agentTokenEnv],\n\t});\n};\n\n/**\n * Reads through the agent's open login, as `tsplc read` does, without opening one: the\n * debugger has no controller credentials.\n */\nexport const readThroughAgent =\n\t(agent: AgentClient) =>\n\tasync ([first, ...rest]: string[]) => {\n\t\tif (!first) {\n\t\t\treturn {};\n\t\t}\n\t\ttry {\n\t\t\tconst result = await agent.command({\n\t\t\t\tcommand: \"read\",\n\t\t\t\texpressions: [first, ...rest],\n\t\t\t});\n\t\t\tif (!(\"values\" in result)) {\n\t\t\t\tthrow new Error(\"The agent answered a read without values\");\n\t\t\t}\n\t\t\treturn result.values;\n\t\t} catch (error) {\n\t\t\tconst { login } = await agent.status();\n\t\t\tif (!login) {\n\t\t\t\tthrow new LoginUnavailable(noLogin, { cause: error });\n\t\t\t}\n\t\t\tif (\"error\" in login) {\n\t\t\t\tthrow new Error(login.error, { cause: error });\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\nconst selectTarget = async (agent: AgentClient): Promise<Target> => {\n\tconst interfaces = await agent.interfaces();\n\tif (!interfaces.length) {\n\t\tthrow new Error(\"The plant PC has no IPv4 network.\");\n\t}\n\tconst network =\n\t\tinterfaces.length === 1 && interfaces[0]\n\t\t\t? interfaces[0]\n\t\t\t: await choose(\n\t\t\t\t\t\"Which network is the controller on?\",\n\t\t\t\t\tinterfaces,\n\t\t\t\t\t(item) => `${item.name} ${item.address}/${item.prefixLength}`,\n\t\t\t\t);\n\tconsole.log(\n\t\t`Scanning ${network.address}/${network.prefixLength} for CODESYS controllers…`,\n\t);\n\tconst found = await agent.discover(network.name);\n\tconst manual = { address: \"\", port: runtimePort, hostname: null };\n\tconst choice = await choose(\n\t\t\"Which controller?\",\n\t\t[...found, manual],\n\t\t(item) =>\n\t\t\titem === manual\n\t\t\t\t? \"Enter an address\"\n\t\t\t\t: `${item.address}${item.hostname ? ` (${item.hostname})` : \"\"}`,\n\t);\n\tconst host =\n\t\tchoice === manual ? await ask(\"Controller address: \") : choice.address;\n\treturn agent.setTarget({ host, port: choice.port });\n};\n\n/**\n * The controller user to send: TSPLC_CONTROLLER_USERNAME and TSPLC_CONTROLLER_PASSWORD from\n * `environment`, else null for the user stored on the agent, else what `prompt` asks for. Initializing\n * the controller's user creates the one sent, so it never leaves it to the stored one.\n */\nexport const controllerCredentials = async (\n\tenvironment: Environment,\n\tagent: { stored: boolean; initializeUser: boolean },\n\tprompt: () => Promise<Credentials>,\n): Promise<Credentials | null> => {\n\tconst username = environment.TSPLC_CONTROLLER_USERNAME;\n\tconst password = environment.TSPLC_CONTROLLER_PASSWORD;\n\tif (username && password) {\n\t\treturn { username, password };\n\t}\n\tif (username || password) {\n\t\tthrow new Error(\n\t\t\t\"Set both TSPLC_CONTROLLER_USERNAME and TSPLC_CONTROLLER_PASSWORD, or neither.\",\n\t\t);\n\t}\n\treturn agent.stored && !agent.initializeUser ? null : prompt();\n};\n\n/** The plant PC's variables and secrets by name, as `variables A, B and secret C`, or null when it holds none. */\nconst plantSummary = ({ values, secrets }: PlantVariables) => {\n\tconst named = (noun: string, names: readonly string[]) =>\n\t\tnames.length\n\t\t\t? `${noun}${names.length === 1 ? \"\" : \"s\"} ${names.join(\", \")}`\n\t\t\t: null;\n\tconst parts = [\n\t\tnamed(\"variable\", Object.keys(values)),\n\t\tnamed(\"secret\", secrets),\n\t].filter((part) => part !== null);\n\treturn parts.length ? parts.join(\" and \") : null;\n};\n\nconst deploy = async (\n\tagent: AgentClient,\n\tloaded: LoadedConfig,\n\tflags: PlantFlags,\n\tfollow: Follow,\n) => {\n\tconst status = await agent.status();\n\tif (status.login) {\n\t\tthrow new Error(\"A login is open; log out before deploying: tsplc logout\");\n\t}\n\tconst target =\n\t\t!status.target || flags.select ? await selectTarget(agent) : status.target;\n\tconst initializeUser = flags[\"initialize-user\"] ?? false;\n\tconst plant = await agent.releaseVariables(\n\t\tloaded.config.secrets?.service ?? null,\n\t);\n\tconst built = releaseEnvironment(loaded.config, loaded, plant);\n\tconsole.log(`Building the release for ${target.host}…`);\n\tconst held = plantSummary(plant);\n\tif (held) {\n\t\tconsole.log(` With the plant PC's ${held}`);\n\t}\n\tconst building = timedProgress();\n\tconst { release, diagnostics } = await prepareRelease(loaded, flags, built);\n\tif (!release) {\n\t\treturn { diagnostics };\n\t}\n\tbuilding(\"Built\");\n\tif (flags.download) {\n\t\tawait confirmOrCancel(\n\t\t\t\"A full download stops the running application while it loads. Continue?\",\n\t\t\tflags,\n\t\t);\n\t}\n\tconst credentials = await controllerCredentials(\n\t\tloaded.env,\n\t\t{ stored: status.credentialsStored, initializeUser },\n\t\taskCredentials,\n\t);\n\tconst settings = {\n\t\tcredentials,\n\t\tdownload: flags.download ?? false,\n\t\tinitializeUser,\n\t};\n\tconsole.log(\n\t\trelease.manifest.server\n\t\t\t? \"Uploading the server and the program…\"\n\t\t\t: \"Uploading the program…\",\n\t);\n\treturn {\n\t\texitCode: await submitDeployment(\n\t\t\tagent,\n\t\t\trelease,\n\t\t\tsettings,\n\t\t\t{\n\t\t\t\tmode: flags.review ? \"review\" : \"apply\",\n\t\t\t\tgit: await gitSource(loaded.root),\n\t\t\t},\n\t\t\tfollow,\n\t\t),\n\t};\n};\n\n/** Opens a login when none is working; it stays open across commands until `tsplc logout`. */\nconst ensureLogin = async (agent: AgentClient, environment: Environment) => {\n\tconst { login, credentialsStored } = await agent.status();\n\tif (login && \"state\" in login) {\n\t\treturn;\n\t}\n\tif (login) {\n\t\tconsole.log(`The open login failed (${login.error}); replacing it.`);\n\t\tawait agent.logout();\n\t}\n\tconst credentials = await controllerCredentials(\n\t\tenvironment,\n\t\t{ stored: credentialsStored, initializeUser: false },\n\t\taskCredentials,\n\t);\n\tconsole.log(\n\t\t\"Logging in. CODESYS takes a few minutes to start; the login stays open until tsplc logout.\",\n\t);\n\tawait agent.login(credentials, progress);\n};\n\n/** The children of `prefix` in the variable tree, with array indexes folded into one range. */\nexport const variableChildren = (\n\tvariables: readonly Variable[],\n\tprefix: string,\n) => {\n\tconst children = new Map<string, { type?: string; leaves: number }>();\n\tfor (const { path, type } of variables) {\n\t\tif (prefix && !isWithin(prefix, path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst rest = path.slice(prefix.length).replace(/^\\./, \"\");\n\t\tif (rest === \"\") {\n\t\t\treturn [{ name: path, type, leaves: 1 }];\n\t\t}\n\t\tconst name = symbolPathSegments(rest)[0] ?? rest;\n\t\tconst child = children.get(name) ?? { leaves: 0 };\n\t\tchildren.set(name, {\n\t\t\ttype: rest === name ? type : undefined,\n\t\t\tleaves: child.leaves + 1,\n\t\t});\n\t}\n\tconst indexes = [...children.keys()]\n\t\t.map(arrayIndex)\n\t\t.filter((index) => index !== undefined);\n\tconst listed = [...children].filter(\n\t\t([name]) => arrayIndex(name) === undefined,\n\t);\n\tif (indexes.length) {\n\t\tconst first = children.get(`[${Math.min(...indexes)}]`);\n\t\tlisted.unshift([\n\t\t\t`[${Math.min(...indexes)}..${Math.max(...indexes)}]`,\n\t\t\tfirst ?? { leaves: 0 },\n\t\t]);\n\t}\n\treturn listed.map(([name, child]) => ({ name, ...child }));\n};\n\nconst printStatus = async (agent: AgentClient) => {\n\tconst status = await agent.status();\n\tconsole.log(\n\t\t`Controller ${status.target ? `${status.target.host}:${status.target.port}` : \"not selected (tsplc target)\"}`,\n\t);\n\tconsole.log(\n\t\t`Release ${status.release ? `${status.release.id}, ${status.release.operation} at ${status.release.deployedAt}` : \"none\"}`,\n\t);\n\tconsole.log(\n\t\t`Server ${status.server ? `${status.server.running ? \"running\" : \"restarting\"} (${status.server.executable})` : \"none\"}`,\n\t);\n\tconst { login } = status;\n\tif (!login) {\n\t\tconsole.log(\"Login closed\");\n\t} else if (\"error\" in login) {\n\t\tconsole.log(`Login failed: ${login.error} (tsplc logout)`);\n\t} else {\n\t\tconsole.log(\n\t\t\t`Login open; application ${login.state}${login.forced.length ? `; forced: ${login.forced.join(\", \")}` : \"\"}`,\n\t\t);\n\t}\n};\n\n/** Lists the deployed release's published variables under `path`, or its roots. */\nconst printVariables = async (agent: AgentClient, path: string | undefined) => {\n\tconst children = variableChildren(await agent.variables(), path ?? \"\");\n\tif (!children.length) {\n\t\tthrow new Error(`No published variable ${path}.`);\n\t}\n\tfor (const child of children) {\n\t\tconsole.log(\n\t\t\t`${child.name.padEnd(32)} ${child.type ?? `${child.leaves} variables`}`,\n\t\t);\n\t}\n};\n\nconst printLogin = (result: LoginResult) => {\n\tif (\"values\" in result) {\n\t\tfor (const [expression, value] of Object.entries(result.values)) {\n\t\t\tconsole.log(`${expression} = ${value}`);\n\t\t}\n\t\treturn;\n\t}\n\tconsole.log(`Application ${result.state}`);\n\tif (result.forced.length) {\n\t\tconsole.log(`Forced: ${result.forced.join(\", \")}`);\n\t}\n};\n\ninterface PlantContext {\n\tagent: AgentClient;\n\targs: string[];\n\tflags: PlantFlags;\n\tproject: {\n\t\tload: () => Promise<LoadedConfig>;\n\t\t/**\n\t\t * Where a login-backed command reads the controller user: the loaded config's environment\n\t\t * in a project, else this process's.\n\t\t */\n\t\tenvironment: Environment;\n\t\t/** Someone at a terminal can answer prompts. */\n\t\tinteractive: boolean;\n\t};\n\tfollow: Follow;\n\t/** Throws the command's usage. */\n\tusage: () => never;\n\t/** Sends a login command through a login that is open, opening one first if none works. */\n\tsend: (command: LoginCommand) => Promise<void>;\n}\n\ninterface PlantCommandEntry {\n\t/** Its arguments and flags, after `tsplc <command>`. */\n\tusage: string;\n\t/** A deployment's compiler diagnostics when the program doesn't compile, the exit code of a command that queues a deployment. */\n\trun: (\n\t\tcontext: PlantContext,\n\t) => Promise<\n\t\t{ diagnostics: readonly Diagnostic[] } | { exitCode: number } | undefined\n\t>;\n}\n\n/** Throws `usage` unless the command has no arguments. */\nconst none = ({ args, usage }: PlantContext) => {\n\tif (args.length) {\n\t\tusage();\n\t}\n};\n\nconst plantCommands = {\n\tdeploy: {\n\t\tusage:\n\t\t\t\"[--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait] [-y]\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tconst { agent, project, flags, follow } = context;\n\t\t\treturn deploy(agent, await project.load(), flags, follow);\n\t\t},\n\t},\n\tdeployments: {\n\t\tusage: \"[--format json]\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tawait printDeployments(context.agent, context.flags);\n\t\t\treturn undefined;\n\t\t},\n\t},\n\trollback: {\n\t\tusage: \"[id] [--wait] [-y]\",\n\t\trun: async ({ agent, args, follow, usage }) => {\n\t\t\tif (args.length > 1) {\n\t\t\t\tusage();\n\t\t\t}\n\t\t\treturn { exitCode: await rollBack(agent, args[0], follow) };\n\t\t},\n\t},\n\tredeploy: {\n\t\tusage: \"<id> [--review] [--wait] [-y]\",\n\t\trun: async ({ agent, args: [id, ...extra], flags, follow, usage }) => {\n\t\t\tif (!id || extra.length) {\n\t\t\t\treturn usage();\n\t\t\t}\n\t\t\treturn {\n\t\t\t\texitCode: await redeploy(\n\t\t\t\t\tagent,\n\t\t\t\t\tid,\n\t\t\t\t\tflags.review ? \"review\" : \"apply\",\n\t\t\t\t\tfollow,\n\t\t\t\t),\n\t\t\t};\n\t\t},\n\t},\n\tdashboard: {\n\t\tusage: \"\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\topenDashboard(context.agent, context.project.interactive);\n\t\t\treturn undefined;\n\t\t},\n\t},\n\ttarget: {\n\t\tusage: \"\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tconst target = await selectTarget(context.agent);\n\t\t\tconsole.log(`Deployments now go to ${target.host}:${target.port}.`);\n\t\t\treturn undefined;\n\t\t},\n\t},\n\tstatus: {\n\t\tusage: \"\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tawait printStatus(context.agent);\n\t\t\treturn undefined;\n\t\t},\n\t},\n\tlogin: {\n\t\tusage: \"\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tawait ensureLogin(context.agent, context.project.environment);\n\t\t\tprintLogin(await context.agent.command({ command: \"state\" }));\n\t\t\treturn undefined;\n\t\t},\n\t},\n\tlogout: {\n\t\tusage: \"\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tconst { agent, flags } = context;\n\t\t\tconst { login } = await agent.status();\n\t\t\tconst forced = login && \"forced\" in login ? login.forced : [];\n\t\t\tif (forced.length) {\n\t\t\t\tawait confirmOrCancel(\n\t\t\t\t\t`Forced: ${forced.join(\", \")}. Forces stay on the controller after logout. Log out anyway?`,\n\t\t\t\t\tflags,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst { failure } = await agent.logout();\n\t\t\tconsole.log(\n\t\t\t\tfailure\n\t\t\t\t\t? `The login couldn't log out (${failure}); its container was removed.`\n\t\t\t\t\t: \"Logged out.\",\n\t\t\t);\n\t\t\treturn undefined;\n\t\t},\n\t},\n\tvars: {\n\t\tusage: \"[path]\",\n\t\trun: async ({ agent, args, usage }) => {\n\t\t\tif (args.length > 1) {\n\t\t\t\tusage();\n\t\t\t}\n\t\t\tawait printVariables(agent, args[0]);\n\t\t\treturn undefined;\n\t\t},\n\t},\n\tread: {\n\t\tusage: \"<expression>...\",\n\t\trun: async ({ args: [first, ...rest], send, usage }) => {\n\t\t\tif (!first) {\n\t\t\t\treturn usage();\n\t\t\t}\n\t\t\tawait send({ command: \"read\", expressions: [first, ...rest] });\n\t\t\treturn undefined;\n\t\t},\n\t},\n\twrite: {\n\t\tusage: \"<expression> <value>\",\n\t\trun: (context) => setValue(\"write\", context),\n\t},\n\tforce: {\n\t\tusage: \"<expression> <value>\",\n\t\trun: (context) => setValue(\"force\", context),\n\t},\n\tunforce: {\n\t\tusage: \"[expression]... [--restore]\",\n\t\trun: async ({ args, flags, send }) => {\n\t\t\tawait send({\n\t\t\t\tcommand: \"unforce\",\n\t\t\t\texpressions: args,\n\t\t\t\trestore: flags.restore ?? false,\n\t\t\t});\n\t\t\treturn undefined;\n\t\t},\n\t},\n\tstart: {\n\t\tusage: \"\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tawait context.send({ command: \"start\" });\n\t\t\treturn undefined;\n\t\t},\n\t},\n\tstop: {\n\t\tusage: \"\",\n\t\trun: async (context) => {\n\t\t\tnone(context);\n\t\t\tawait confirmOrCancel(\n\t\t\t\t\"Stop the application on the controller?\",\n\t\t\t\tcontext.flags,\n\t\t\t);\n\t\t\tawait context.send({ command: \"stop\" });\n\t\t\treturn undefined;\n\t\t},\n\t},\n\treset: {\n\t\tusage: \"warm|cold\",\n\t\trun: async ({ args, flags, send, usage }) => {\n\t\t\tif (args.length !== 1) {\n\t\t\t\tusage();\n\t\t\t}\n\t\t\tconst kind = controllerRestartSchema.shape.reset.parse(args[0]);\n\t\t\tawait confirmOrCancel(\n\t\t\t\t`Reset the application (${kind})? It stops and reinitializes its variables.`,\n\t\t\t\tflags,\n\t\t\t);\n\t\t\tawait send({ command: \"reset\", kind: resetLabel(kind) });\n\t\t\treturn undefined;\n\t\t},\n\t},\n\trestart: {\n\t\tusage: \"[warm|cold] [-y]\",\n\t\trun: async ({ agent, args, flags, usage }) => {\n\t\t\tif (args.length > 1) {\n\t\t\t\tusage();\n\t\t\t}\n\t\t\tconst reset = controllerRestartSchema.shape.reset.parse(\n\t\t\t\targs[0] ?? \"warm\",\n\t\t\t);\n\t\t\tawait confirmOrCancel(\n\t\t\t\t`Reset the application (${reset}) and start it again? Its variables go back to their initial values${reset === \"warm\" ? \", but for retain ones\" : \"\"}.`,\n\t\t\t\tflags,\n\t\t\t);\n\t\t\tconst { state } = await agent.restartController({ reset });\n\t\t\tconsole.log(\n\t\t\t\t`Reset ${reset}; the application is ${state === \"run\" ? \"running\" : state}.`,\n\t\t\t);\n\t\t\treturn undefined;\n\t\t},\n\t},\n} satisfies Record<string, PlantCommandEntry>;\n\n/** `tsplc write` and `tsplc force`: one expression and its value. */\nasync function setValue(\n\tcommand: \"write\" | \"force\",\n\t{ args: [expression, value, ...extra], send, usage }: PlantContext,\n) {\n\tif (!expression || !value || extra.length) {\n\t\treturn usage();\n\t}\n\tawait send({ command, values: { [expression]: value } });\n\treturn undefined;\n}\n\nexport type PlantCommand = keyof typeof plantCommands;\n\nexport const isPlantCommand = (name: string): name is PlantCommand =>\n\tObject.hasOwn(plantCommands, name);\n\n/**\n * Runs a command against the plant agent. Returns a deployment's compiler diagnostics when the\n * program doesn't compile, and the exit code of a command that queues a deployment.\n */\nexport const runPlantCommand = (\n\tagent: AgentClient,\n\tcommand: PlantCommand,\n\targs: string[],\n\tflags: PlantFlags,\n\tproject: PlantContext[\"project\"],\n) => {\n\tconst entry: PlantCommandEntry = plantCommands[command];\n\tconst approval: Approval = {\n\t\tyes: flags.yes ?? false,\n\t\tinteractive: project.interactive,\n\t\tconfirm,\n\t};\n\treturn entry.run({\n\t\tagent,\n\t\targs,\n\t\tflags,\n\t\tproject,\n\t\tfollow: { wait: flags.wait ?? false, approval },\n\t\tusage: () => {\n\t\t\tthrow new Error(`Usage: tsplc ${command} ${entry.usage}`);\n\t\t},\n\t\tsend: async (loginCommand) => {\n\t\t\tawait ensureLogin(agent, project.environment);\n\t\t\tprintLogin(await agent.command(loginCommand));\n\t\t},\n\t});\n};\n",
20
+ "import { resolve } from \"node:path\";\nimport type { ParseArgsOptionsConfig } from \"node:util\";\nimport {\n\tcheckRawSources,\n\tcompileStructuredText,\n\tconfigureDocker,\n\tconfigureRuntime,\n\tinspectProjectController,\n\tinstallLibraries,\n\ttype ProgressStream,\n\trawEngineeringSettings,\n\trunProject,\n\tupdateController,\n} from \"@tsplc/build\";\nimport { checkHostConfig } from \"@tsplc/compiler\";\nimport { type Diagnostic, hasErrors } from \"@tsplc/compiler/ir\";\nimport {\n\tbuildTargetFor,\n\tcontrollerFor,\n\ttype Environment,\n\ttype LoadedConfig,\n\tloadTsplcConfig,\n\trawBuildConfig,\n} from \"@tsplc/config\";\nimport { resolveConfig } from \"@tsplc/config/build\";\nimport { generateProject } from \"@tsplc/typegen\";\nimport { runInBun } from \"../runtime/process\";\nimport { type Flags, flag, type OutputFormat } from \"./flags\";\nimport {\n\tbuildConfigs,\n\tbuildTypeScriptProject,\n\tcheckProject,\n\tcleanProject,\n\tprojectTargets,\n} from \"./project\";\nimport { buildServer, checkServer, startServerCheck } from \"./server\";\n\n/** The flags of the project commands. */\nexport const projectOptions = {\n\t\"emit-only\": flag,\n\tread: { type: \"string\", multiple: true },\n\t\"initialize-user\": flag,\n\t\"frozen-lockfile\": flag,\n\tcheck: flag,\n\tplc: flag,\n\tserver: flag,\n\tsimulate: flag,\n\truntime: flag,\n\tbun: flag,\n\tforeground: flag,\n} as const satisfies ParseArgsOptionsConfig;\n\nexport type ProjectFlags = Flags<typeof projectOptions> & {\n\tformat?: OutputFormat;\n\ttarget?: string;\n};\n\n/**\n * Every command result; one whose diagnostics have errors fails the command. `values` are the\n * `--read` expressions' values, which text output prints too.\n */\nexport type CommandResult = object & {\n\tdiagnostics?: readonly Diagnostic[];\n\tvalues?: Readonly<Record<string, string>>;\n};\n\n/** A result whose diagnostics fail the command; the CLI reports the whole result. */\nexport class DiagnosticFailure extends Error {\n\tconstructor(readonly result: CommandResult) {\n\t\tsuper(\"PLC validation failed.\");\n\t}\n}\n\n/**\n * The flags only some commands take, in the order they are checked, with what using one\n * elsewhere is told. `--simulate`, `--frozen-lockfile` and `--initialize-user` are deploy's too, a\n * plant command; the last group belongs to plant commands and the debugger only.\n */\nconst restrictedFlags = [\n\t[\"emit-only\", \"--emit-only is supported by build only.\"],\n\t[\"target\", \"--target applies only to commands that read the config.\"],\n\t[\"runtime\", \"--runtime applies only to configure.\"],\n\t[\n\t\t\"bun\",\n\t\t\"--bun applies only to run --simulate: the Bun runtime has no fieldbus, so a plant simulator writes its inputs.\",\n\t],\n\t[\"foreground\", \"--foreground applies only to run --simulate --bun.\"],\n\t[\"plc\", \"--plc and --server apply only to build.\"],\n\t[\"server\", \"--plc and --server apply only to build.\"],\n\t[\n\t\t\"simulate\",\n\t\t\"--simulate applies only to run, download, online-change and deploy.\",\n\t],\n\t[\"check\", \"--check applies only to typegen.\"],\n\t[\"read\", \"--read applies only to inspect, download and online-change.\"],\n\t[\n\t\t\"frozen-lockfile\",\n\t\t\"--frozen-lockfile applies only to install, build, run, download, online-change and deploy.\",\n\t],\n\t[\"initialize-user\", \"--initialize-user applies only to download and deploy.\"],\n\t[\"download\", \"--download applies only to deploy.\"],\n\t[\"select\", \"--select applies only to deploy.\"],\n\t[\"review\", \"--review applies only to deploy and redeploy.\"],\n\t[\"wait\", \"--wait applies only to deploy, rollback and redeploy.\"],\n\t[\"restore\", \"--restore applies only to unforce.\"],\n\t[\"yes\", \"-y applies only to plant agent commands.\"],\n\t[\"port\", \"--port applies only to debug.\"],\n\t[\"server-url\", \"--server-url applies only to debug.\"],\n\t[\"opcua\", \"--opcua applies only to debug.\"],\n] as const;\ntype RestrictedFlag = (typeof restrictedFlags)[number][0];\n\n/** A flag that means something only beside another one. */\nconst prerequisites: Partial<Record<RestrictedFlag, RestrictedFlag>> = {\n\tbun: \"simulate\",\n\tforeground: \"bun\",\n};\n\ninterface ProjectContext {\n\tfile: string;\n\tflags: ProjectFlags;\n\tenvironment: Environment;\n\tprogress: ProgressStream;\n\t/** The config with the target the flags name, in `environment`. */\n\tload: () => Promise<LoadedConfig>;\n}\n\ninterface ProjectCommandEntry {\n\t/** The restricted flags it takes. */\n\ttakes: readonly RestrictedFlag[];\n\t/** Rejects flags that don't go together, before the config loads. */\n\tcheck?: (flags: ProjectFlags) => void;\n\trun: (context: ProjectContext) => Promise<CommandResult>;\n}\n\nconst projectCommands = {\n\tinstall: {\n\t\ttakes: [\"target\", \"frozen-lockfile\"],\n\t\trun: async ({ load, flags }) => install(await load(), flags),\n\t},\n\ttypegen: {\n\t\ttakes: [\"target\", \"check\"],\n\t\trun: async ({ load, flags }) => typegen(await load(), flags),\n\t},\n\tcheck: {\n\t\ttakes: [\"target\"],\n\t\trun: async ({ file, load }) => check(await loadCheckedConfig(file, load)),\n\t},\n\tbuild: {\n\t\ttakes: [\"target\", \"emit-only\", \"plc\", \"server\", \"frozen-lockfile\"],\n\t\tcheck: (flags) => {\n\t\t\tif (flags.plc && flags.server) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Choose --plc or --server, or omit both for a full build.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (flags.server && flags[\"emit-only\"]) {\n\t\t\t\tthrow new Error(\"--emit-only applies to PLC emission only.\");\n\t\t\t}\n\t\t},\n\t\trun: async ({ file, load, flags, progress }) =>\n\t\t\tbuild(await loadCheckedConfig(file, load), flags, progress),\n\t},\n\trun: {\n\t\ttakes: [\"target\", \"simulate\", \"bun\", \"foreground\", \"frozen-lockfile\"],\n\t\trun: async ({ file, load, flags, progress }) =>\n\t\t\trun(await loadCheckedConfig(file, load), flags, progress),\n\t},\n\tdownload: {\n\t\ttakes: [\"target\", \"simulate\", \"read\", \"frozen-lockfile\", \"initialize-user\"],\n\t\trun: async ({ file, load, flags, progress }) =>\n\t\t\tupdateProgram(\n\t\t\t\t\"download\",\n\t\t\t\tawait loadCheckedConfig(file, load),\n\t\t\t\tflags,\n\t\t\t\tprogress,\n\t\t\t),\n\t},\n\t\"online-change\": {\n\t\ttakes: [\"target\", \"simulate\", \"read\", \"frozen-lockfile\"],\n\t\trun: async ({ file, load, flags, progress }) =>\n\t\t\tupdateProgram(\n\t\t\t\t\"online-change\",\n\t\t\t\tawait loadCheckedConfig(file, load),\n\t\t\t\tflags,\n\t\t\t\tprogress,\n\t\t\t),\n\t},\n\tinspect: {\n\t\ttakes: [\"target\", \"read\"],\n\t\trun: async ({ load, flags, progress }) =>\n\t\t\tinspectProjectController(await load(), flags.read, { progress }),\n\t},\n\tclean: { takes: [], run: ({ file }) => cleanProject(file) },\n\tconfigure: {\n\t\ttakes: [\"runtime\"],\n\t\trun: ({ flags, progress, environment }) =>\n\t\t\tconfigure(flags, progress, environment),\n\t},\n} satisfies Record<string, ProjectCommandEntry>;\n\nexport type ProjectCommand = keyof typeof projectCommands;\n\nexport const isProjectCommand = (name: string): name is ProjectCommand =>\n\tObject.hasOwn(projectCommands, name);\n\n/** Rejects the flags that don't apply to `command`, among every flag the command line parsed. */\nexport const checkProjectFlags = (\n\tcommand: ProjectCommand,\n\tflags: ProjectFlags & Partial<Record<RestrictedFlag, unknown>>,\n) => {\n\tconst entry: ProjectCommandEntry = projectCommands[command];\n\tfor (const [name, message] of restrictedFlags) {\n\t\tconst prerequisite = prerequisites[name];\n\t\tconst applies =\n\t\t\tentry.takes.includes(name) &&\n\t\t\t(prerequisite === undefined || flags[prerequisite]);\n\t\tif (flags[name] && !applies) {\n\t\t\tthrow new Error(message);\n\t\t}\n\t}\n\tentry.check?.(flags);\n};\n\n/** Runs `command` in this process's `environment`, which the config's target values overlay. */\nexport const runProjectCommand = (\n\tcommand: ProjectCommand,\n\tfile: string,\n\tflags: ProjectFlags,\n\tenvironment: Environment,\n): Promise<CommandResult> =>\n\tprojectCommands[command].run({\n\t\tfile,\n\t\tflags,\n\t\tenvironment,\n\t\t// A JSON result owns standard output, so progress goes to standard error.\n\t\tprogress: flags.format === \"json\" ? \"stderr\" : \"stdout\",\n\t\tload: () =>\n\t\t\tloadTsplcConfig(file, {\n\t\t\t\tenv: environment,\n\t\t\t\ttarget: flags.target,\n\t\t\t\tforAgent: false,\n\t\t\t}),\n\t});\n\n/** A config loaded after its host config check, whose diagnostics the compiler reports. */\ninterface CheckedConfig {\n\tloaded: LoadedConfig;\n\thostConfigDiagnostics: readonly Diagnostic[];\n}\n\n/** Loads the config after type-checking it, so a type error fails before the config runs. */\nconst loadCheckedConfig = async (\n\tfile: string,\n\tload: () => Promise<LoadedConfig>,\n): Promise<CheckedConfig> => {\n\tconst hostConfigDiagnostics = checkHostConfig(resolve(file));\n\tif (hasErrors(hostConfigDiagnostics)) {\n\t\tthrow new DiagnosticFailure({ diagnostics: hostConfigDiagnostics });\n\t}\n\treturn { loaded: await load(), hostConfigDiagnostics };\n};\n\n/** Builds the Docker image every build uses, or with `--runtime` the local PLC runtime's. */\nconst configure = async (\n\tflags: Pick<ProjectFlags, \"runtime\">,\n\tprogress: ProgressStream,\n\tenvironment: Environment,\n) => {\n\tawait (flags.runtime\n\t\t? configureRuntime({ progress })\n\t\t: configureDocker({\n\t\t\t\tprogress,\n\t\t\t\twinetricksCache: environment.CODESYS_WINETRICKS_CACHE || null,\n\t\t\t}));\n\treturn { ok: true };\n};\n\nconst install = async (\n\t{ config, root }: LoadedConfig,\n\tflags: Pick<ProjectFlags, \"frozen-lockfile\">,\n) => ({\n\tlibraries: await installLibraries(config.dependencies, root, {\n\t\tfrozen: flags[\"frozen-lockfile\"],\n\t}),\n});\n\nconst typegen = async (\n\tloaded: LoadedConfig,\n\tflags: Pick<ProjectFlags, \"check\">,\n) => {\n\tconst targets = await projectTargets(loaded.configFile, loaded);\n\t// `--check` compares the committed files with this source's contract, so it emits too.\n\tif (loaded.config.compiler) {\n\t\tif (!flags.check) {\n\t\t\tawait generateProject(loaded, { hardwareOnly: true, targets });\n\t\t}\n\t\tconst emitted = await buildTypeScriptProject(loaded.configFile, {\n\t\t\temitOnly: true,\n\t\t\tloaded,\n\t\t\thostConfigDiagnostics: checkHostConfig(loaded.configFile),\n\t\t});\n\t\tif (hasErrors(emitted.diagnostics)) {\n\t\t\tthrow new DiagnosticFailure(emitted);\n\t\t}\n\t}\n\tconst { catalog, io, files } = await generateProject(loaded, {\n\t\tcheck: flags.check,\n\t\ttargets,\n\t});\n\treturn { catalog, io, files };\n};\n\n/** The check's verdict; the plan and the loaded config stay out, since they hold the environment. */\nconst check = async (checked: CheckedConfig) => {\n\tif (checked.loaded.config.compiler) {\n\t\tconst { configFile, diagnostics } = await checkProject(\n\t\t\tchecked.loaded.configFile,\n\t\t\tchecked,\n\t\t);\n\t\treturn { configFile, diagnostics };\n\t}\n\treturn { objects: (await checkRawSources(checked.loaded)).objects.length };\n};\n\n/**\n * The PLC program `build` and `run` compile: TypeScript through the compiler, or raw\n * Structured Text straight to the vendor build. Either refreshes the generated types.\n */\nconst buildPlc = async (\n\tcommand: \"build\" | \"run\",\n\t{ loaded, hostConfigDiagnostics }: CheckedConfig,\n\tflags: Pick<ProjectFlags, \"emit-only\" | \"frozen-lockfile\" | \"simulate\">,\n\tprogress: ProgressStream,\n) => {\n\tconst { config, configFile } = loaded;\n\tif (config.compiler) {\n\t\t// The build's analysis already read the targets; `--format json` reports the rest.\n\t\tconst { targets, services, ...built } = await buildTypeScriptProject(\n\t\t\tconfigFile,\n\t\t\t{\n\t\t\t\tprogress,\n\t\t\t\temitOnly: flags[\"emit-only\"],\n\t\t\t\tfrozenLockfile: flags[\"frozen-lockfile\"],\n\t\t\t\t...buildConfigs(loaded, flags),\n\t\t\t\thostConfigDiagnostics,\n\t\t\t\tcontroller: controllerFor(config, command),\n\t\t\t\tbuildTarget: buildTargetFor(command),\n\t\t\t},\n\t\t);\n\t\tif (hasErrors(built.diagnostics)) {\n\t\t\tthrow new DiagnosticFailure(built);\n\t\t}\n\t\tawait generateProject(loaded, { targets });\n\t\treturn { built, services };\n\t}\n\tif (flags[\"emit-only\"]) {\n\t\tthrow new Error(\"Raw Structured Text is already emitted.\");\n\t}\n\tconst built = await compileStructuredText(\n\t\tawait rawEngineeringSettings(loaded, {\n\t\t\tcommand,\n\t\t\tfrozenLockfile: flags[\"frozen-lockfile\"],\n\t\t\tsimulate: flags.simulate,\n\t\t}),\n\t\t{ progress },\n\t);\n\tawait generateProject(loaded);\n\treturn { built, services: undefined };\n};\n\n/** The PLC program and, unless `--plc` or `--emit-only` restricts it, the configured server. */\nconst build = async (\n\tchecked: CheckedConfig,\n\tflags: Pick<\n\t\tProjectFlags,\n\t\t\"emit-only\" | \"frozen-lockfile\" | \"plc\" | \"server\" | \"simulate\"\n\t>,\n\tprogress: ProgressStream,\n) => {\n\tconst { config, root } = checked.loaded;\n\tif (flags.server) {\n\t\treturn buildServer(await checkServer(config, root), config, root);\n\t}\n\tconst withServer =\n\t\t!flags.plc && !flags[\"emit-only\"] && config.server?.runtime;\n\tconst serverCheck = withServer ? startServerCheck(config, root) : undefined;\n\tconst { built: plc } = await buildPlc(\"build\", checked, flags, progress);\n\tif (!serverCheck) {\n\t\treturn plc;\n\t}\n\treturn { ...plc, ...(await buildServer(await serverCheck, config, root)) };\n};\n\nconst run = async (\n\tchecked: CheckedConfig,\n\tflags: Pick<\n\t\tProjectFlags,\n\t\t\"frozen-lockfile\" | \"simulate\" | \"bun\" | \"foreground\" | \"target\"\n\t>,\n\tprogress: ProgressStream,\n) => {\n\tif (flags.bun) {\n\t\treturn runInBunRuntime(checked, flags, progress);\n\t}\n\tconst { config, configFile } = checked.loaded;\n\tconst { built } = await buildPlc(\"run\", checked, flags, progress);\n\tif (!config.build) {\n\t\tthrow new Error(\"Configure build to run this project.\");\n\t}\n\tawait runProject(\n\t\tresolveConfig(\n\t\t\tconfig.compiler ? config.build : rawBuildConfig(config),\n\t\t\tconfigFile,\n\t\t),\n\t\tconfig.name,\n\t\t{ progress },\n\t);\n\treturn built;\n};\n\n/** Emits the program and runs its TypeScript in the Bun runtime instead of CODESYS. */\nconst runInBunRuntime = async (\n\tchecked: CheckedConfig,\n\tflags: Pick<\n\t\tProjectFlags,\n\t\t\"frozen-lockfile\" | \"simulate\" | \"foreground\" | \"target\"\n\t>,\n\tprogress: ProgressStream,\n) => {\n\tconst { config, configFile, env, root } = checked.loaded;\n\tif (!config.compiler) {\n\t\tthrow new Error(\n\t\t\t\"The Bun runtime runs a TypeScript program; this project builds raw Structured Text.\",\n\t\t);\n\t}\n\tconst { built, services } = await buildPlc(\n\t\t\"run\",\n\t\tchecked,\n\t\t{ ...flags, \"emit-only\": true },\n\t\tprogress,\n\t);\n\tconst runtime = await runInBun({\n\t\troot,\n\t\tlaunch: {\n\t\t\tconfig: configFile,\n\t\t\ttarget: flags.target ?? null,\n\t\t\tservices: services ?? {},\n\t\t},\n\t\tenvironment: env,\n\t\tforeground: flags.foreground ?? false,\n\t\tprogress,\n\t});\n\treturn { ...built, runtime };\n};\n\n/** Downloads or online-changes the program on the configured controller. */\nconst updateProgram = async (\n\toperation: \"download\" | \"online-change\",\n\tchecked: CheckedConfig,\n\tflags: Pick<\n\t\tProjectFlags,\n\t\t\"frozen-lockfile\" | \"simulate\" | \"initialize-user\" | \"read\"\n\t>,\n\tprogress: ProgressStream,\n) => {\n\tconst { config, env } = checked.loaded;\n\tif (!config.build) {\n\t\tthrow new Error(\"Configure build settings and controller connection.\");\n\t}\n\tconst settings = config.compiler\n\t\t? await emittedControllerSettings(operation, checked, flags)\n\t\t: await rawEngineeringSettings(checked.loaded, {\n\t\t\t\tcommand: operation,\n\t\t\t\tfrozenLockfile: flags[\"frozen-lockfile\"],\n\t\t\t\tsimulate: flags.simulate,\n\t\t\t});\n\treturn updateController(settings, operation, {\n\t\tinitializeUser: flags[\"initialize-user\"],\n\t\tread: flags.read,\n\t\tprogress,\n\t\tenvironment: env,\n\t});\n};\n\nconst emittedControllerSettings = async (\n\toperation: \"download\" | \"online-change\",\n\t{ loaded, hostConfigDiagnostics }: CheckedConfig,\n\tflags: Pick<ProjectFlags, \"frozen-lockfile\" | \"simulate\">,\n) => {\n\tconst emitted = await buildTypeScriptProject(loaded.configFile, {\n\t\temitOnly: true,\n\t\tforController: true,\n\t\tfrozenLockfile: flags[\"frozen-lockfile\"],\n\t\t...buildConfigs(loaded, flags),\n\t\thostConfigDiagnostics,\n\t\tcontroller: controllerFor(loaded.config, operation),\n\t\tbuildTarget: buildTargetFor(operation),\n\t});\n\tif (hasErrors(emitted.diagnostics)) {\n\t\tthrow new DiagnosticFailure(emitted);\n\t}\n\tif (!emitted.controllerConfig) {\n\t\tthrow new Error(\"Configure build settings for deployment.\");\n\t}\n\treturn emitted.controllerConfig;\n};\n",
21
+ "import { spawn, spawnSync } from \"node:child_process\";\nimport { openSync } from \"node:fs\";\nimport { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { fileURLToPath } from \"node:url\";\nimport { type ProgressStream, progressLog } from \"@tsplc/build\";\nimport type { Environment } from \"@tsplc/config\";\nimport {\n\ttype Launch,\n\ttype RuntimeState,\n\truntimeDirectory,\n\truntimeFiles,\n\truntimeStateSchema,\n} from \"./launch\";\nimport { isMissingFile } from \"./missing-file\";\n\n/** How long a runtime has to start serving, and to stop. */\nconst startTimeoutMs = 60_000;\nconst stopTimeoutMs = 15_000;\n\n/** Whether `pid` runs: a process this user may not signal runs too. */\nconst alive = (pid: number) => {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (cause) {\n\t\treturn cause instanceof Error && \"code\" in cause && cause.code === \"EPERM\";\n\t}\n};\n\n/** Whether `pid` still runs this project's runtime, rather than a process that took over its number after a crash. */\nconst isRuntime = (pid: number, launchFile: string) => {\n\tif (!alive(pid)) {\n\t\treturn false;\n\t}\n\t// Windows has no `ps` to name the process's command, so any process with the number counts.\n\tif (process.platform === \"win32\") {\n\t\treturn true;\n\t}\n\tconst command = spawnSync(\"ps\", [\"-o\", \"command=\", \"-p\", String(pid)], {\n\t\tencoding: \"utf8\",\n\t}).stdout;\n\treturn command.includes(launchFile);\n};\n\n/** The running runtime's state; undefined when no runtime serves. */\nconst readState = async (file: string): Promise<RuntimeState | undefined> => {\n\tconst text = await readFile(file, \"utf8\").catch((cause: unknown) => {\n\t\tif (isMissingFile(cause)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tthrow cause;\n\t});\n\tif (text === undefined) {\n\t\treturn undefined;\n\t}\n\ttry {\n\t\treturn runtimeStateSchema.parse(JSON.parse(text));\n\t} catch (cause) {\n\t\tthrow new Error(\n\t\t\t`${file} is not a Bun runtime's state: delete it once no runtime runs.`,\n\t\t\t{ cause },\n\t\t);\n\t}\n};\n\n/** Stops the project's runtime that an earlier `run --bun` left running, which saves its retained values. */\nconst stopRunning = async (directory: string, log: (line: string) => void) => {\n\tconst stateFile = join(directory, runtimeFiles.state);\n\tconst state = await readState(stateFile);\n\tif (!state || !isRuntime(state.pid, join(directory, runtimeFiles.launch))) {\n\t\tawait rm(stateFile, { force: true });\n\t\treturn;\n\t}\n\tlog(`Stopping the Bun runtime that runs as process ${state.pid}`);\n\tprocess.kill(state.pid, \"SIGTERM\");\n\tconst deadline = Date.now() + stopTimeoutMs;\n\twhile (alive(state.pid)) {\n\t\tif (Date.now() >= deadline) {\n\t\t\tprocess.kill(state.pid, \"SIGKILL\");\n\t\t\tbreak;\n\t\t}\n\t\tawait delay(100);\n\t}\n\tawait rm(stateFile, { force: true });\n};\n\n/**\n * Starts the program in the Bun runtime, as `tsplc run --simulate --bun` does, replacing the\n * project's runtime that is running. Detached, the runtime keeps running after this returns,\n * writing to its log, until the next `run --bun` replaces it or it is sent SIGTERM; in the\n * foreground it runs, writing to this terminal, until it is interrupted.\n */\nexport const runInBun = async (options: {\n\troot: string;\n\tlaunch: Launch;\n\tenvironment: Environment;\n\tforeground: boolean;\n\tprogress: ProgressStream;\n}) => {\n\tconst log = progressLog(options.progress);\n\tconst directory = join(options.root, runtimeDirectory);\n\tawait mkdir(directory, { recursive: true });\n\tawait stopRunning(directory, log);\n\tconst launchFile = join(directory, runtimeFiles.launch);\n\tawait writeFile(launchFile, `${JSON.stringify(options.launch, null, 2)}\\n`);\n\tconst logFile = join(directory, runtimeFiles.log);\n\tconst command = [\n\t\tfileURLToPath(import.meta.resolve(\"#bun-runtime\")),\n\t\tlaunchFile,\n\t];\n\tif (options.foreground) {\n\t\tlog(\"Running the program in Bun; stop it with Ctrl-C\");\n\t\tconst child = spawn(process.execPath, command, {\n\t\t\tcwd: options.root,\n\t\t\tenv: options.environment,\n\t\t\tstdio: \"inherit\",\n\t\t});\n\t\t// The terminal's Ctrl-C reaches the runtime too, so this process only waits for it to stop;\n\t\t// a SIGTERM sent to this process alone is passed on.\n\t\tconst wait = () => undefined;\n\t\tconst forward = () => child.kill(\"SIGTERM\");\n\t\tprocess.on(\"SIGINT\", wait);\n\t\tprocess.on(\"SIGTERM\", forward);\n\t\tconst code = await new Promise<number | null>((resolve) =>\n\t\t\tchild.once(\"exit\", resolve),\n\t\t);\n\t\tprocess.off(\"SIGINT\", wait);\n\t\tprocess.off(\"SIGTERM\", forward);\n\t\tif (code !== 0) {\n\t\t\tthrow new Error(`The Bun runtime exited with code ${code}.`);\n\t\t}\n\t\treturn { stopped: true };\n\t}\n\tconst output = openSync(logFile, \"w\");\n\tconst child = spawn(process.execPath, command, {\n\t\tcwd: options.root,\n\t\tenv: options.environment,\n\t\tdetached: true,\n\t\tstdio: [\"ignore\", output, output],\n\t});\n\tconst exited: { code: number | null; done: boolean } = {\n\t\tcode: null,\n\t\tdone: false,\n\t};\n\tchild.once(\"exit\", (code) => {\n\t\tObject.assign(exited, { code, done: true });\n\t});\n\tconst stateFile = join(directory, runtimeFiles.state);\n\tconst deadline = Date.now() + startTimeoutMs;\n\twhile (true) {\n\t\tconst state = await readState(stateFile);\n\t\tif (state && state.pid === child.pid) {\n\t\t\tchild.unref();\n\t\t\tconst shown = relative(process.cwd(), logFile) || logFile;\n\t\t\tlog(\n\t\t\t\t`The program runs in Bun as process ${state.pid}: OPC UA at ${state.endpoint}, output in ${shown}`,\n\t\t\t);\n\t\t\treturn { ...state, log: logFile };\n\t\t}\n\t\tif (exited.done || Date.now() >= deadline) {\n\t\t\tif (!exited.done) {\n\t\t\t\tchild.kill(\"SIGTERM\");\n\t\t\t}\n\t\t\tconst tail = (await readFile(logFile, \"utf8\").catch(() => \"\"))\n\t\t\t\t.trimEnd()\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.slice(-30)\n\t\t\t\t.join(\"\\n\");\n\t\t\tthrow new Error(\n\t\t\t\t`The Bun runtime ${exited.done ? `exited with code ${exited.code}` : \"did not start in time\"}:\\n${tail}`,\n\t\t\t);\n\t\t}\n\t\tawait delay(100);\n\t}\n};\n"
19
22
  ],
20
- "mappings": ";;;;AACA,uBAAS;AACT;AACA,wCAA2B;AAC3B,4BAAS;AACT,cAAS;;;ACLT,uBAAS;AACT,qBAAS,sBAAU;AACnB,2BAA4B;AAC5B;AACA;AAAA,wBACC;AAAA,wBACA;AAAA;AAED;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,8BAAS;;;ACjBT;AAAA,SACC;AAAA;AAAA;AAMD;AAGA;AAAA;AAAA;AAKA;AACA,cAAS;;;AChBT;AAOA;AAAA;AAAA;AAAA;AAKA;;;ACZA;AAEO,IAAM,SAAS,OACrB,UACA,OACA,UACI;AAAA,EACJ,MAAM,QAAQ,CAAC,MAAM,UAAU;AAAA,IAC9B,QAAQ,IAAI,KAAK,QAAQ,MAAM,MAAM,IAAI,GAAG;AAAA,GAC5C;AAAA,EACD,OAAO,MAAM;AAAA,IACZ,MAAM,OACL,MAAM,OAAO,MAAM,IAAI,GAAG,eAAe,MAAM,WAAW,CAAC,IAAI;AAAA,IAChE,IAAI,SAAS,WAAW;AAAA,MACvB,OAAO;AAAA,IACR;AAAA,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