@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
@@ -1,12 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/project/project.ts", "../src/runtime/launch.ts", "../src/project/artifacts.ts"],
4
- "sourcesContent": [
5
- "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",
6
- "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",
7
- "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"
8
- ],
9
- "mappings": ";AAAA;AAAA;AAAA,WAEC;AAAA;AAAA;AAAA,QAGA;AAAA,eACA;AAAA;AAED,8BAAmB,kBAAS;AAC5B;AACA;AAAA;AAAA;AAAA;AAKA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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,OAAO;AAAA,IACR;AAAA,IACA,MAAM,IAAI,OAAO,MAAM,IAAI;AAAA,IAC3B,OAAO,MAAM,OAAO;AAAA;AAAA,EAErB,MAAM,OAAO,SAAS,IAAI,GAAG,MAAM,MAAM,WAAW;AAAA,IACnD,MAAM,SAAS,IAAI;AAAA,IACnB;AAAA,IACA,MAAM,OAAO,KAAK,IAAI;AAAA,IACtB,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,EACN,CAAC;AAAA,EACD,OAAO;AAAA,IACN,SAAS,CAAC,GAAG,QAAQ,KAAK,CAAC;AAAA,IAC3B,OAAO,CAAC,GAAG,MAAM,KAAK,CAAC;AAAA,IACvB,UAAU;AAAA,EACX;AAAA;AAGM,eAAe,YAAY,CAAC,OAAO,mBAEvC;AAAA,EACF,IAAI;AAAA,IACH,MAAM,eAAe,MAAM,SAAS,QAAQ,IAAI,CAAC,CAAC;AAAA,IAClD,OAAO,EAAE,aAAa,CAAC,EAAE;AAAA,IACxB,OAAO,OAAO;AAAA,IACf,OAAO,EAAE,aAAa,CAAC,QAAQ,UAAU,WAAW,KAAK,CAAC,EAAE;AAAA;AAAA;",
10
- "debugId": "245EC16F9FA9A58064756E2164756E21",
11
- "names": []
12
- }
@@ -1,59 +0,0 @@
1
- // @bun
2
- // packages/compiler/src/project/server-check.ts
3
- import { dirname } from "path";
4
- import { typeCheckOnly } from "@tsplc/compiler";
5
- import ts from "typescript";
6
-
7
- // packages/compiler/src/project/server.ts
8
- import { z } from "zod";
9
- var serverCheckRequestSchema = z.strictObject({
10
- entry: z.string(),
11
- root: z.string()
12
- });
13
- var serverCheckResultSchema = z.strictObject({
14
- failure: z.string().nullable()
15
- });
16
-
17
- // packages/compiler/src/project/server-check.ts
18
- var serverFailure = ({
19
- entry,
20
- root
21
- }) => {
22
- const tsconfig = ts.findConfigFile(dirname(entry), ts.sys.fileExists);
23
- if (!tsconfig) {
24
- return "Server entry requires a tsconfig.json.";
25
- }
26
- const read = ts.readConfigFile(tsconfig, ts.sys.readFile);
27
- if (read.error) {
28
- return ts.flattenDiagnosticMessageText(read.error.messageText, `
29
- `);
30
- }
31
- const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(tsconfig));
32
- const program = ts.createProgram({
33
- rootNames: [
34
- entry,
35
- ...parsed.fileNames.filter((file) => /\.d\.[cm]?ts$/.test(file))
36
- ],
37
- options: { ...parsed.options, ...typeCheckOnly },
38
- projectReferences: parsed.projectReferences
39
- });
40
- const diagnostics = [...parsed.errors, ...ts.getPreEmitDiagnostics(program)];
41
- if (!diagnostics.length) {
42
- return null;
43
- }
44
- return ts.formatDiagnosticsWithColorAndContext(diagnostics, {
45
- getCanonicalFileName: (path) => path,
46
- getCurrentDirectory: () => root,
47
- getNewLine: () => `
48
- `
49
- });
50
- };
51
- self.onmessage = (event) => {
52
- const result = {
53
- failure: serverFailure(serverCheckRequestSchema.parse(event.data))
54
- };
55
- self.postMessage(result);
56
- };
57
-
58
- //# debugId=81486E03709D174864756E2164756E21
59
- //# sourceMappingURL=server-check.js.map
@@ -1,11 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/project/server-check.ts", "../src/project/server.ts"],
4
- "sourcesContent": [
5
- "import { dirname } from \"node:path\";\nimport { typeCheckOnly } from \"@tsplc/compiler\";\nimport ts from \"typescript\";\nimport type { z } from \"zod\";\nimport {\n\tserverCheckRequestSchema,\n\ttype serverCheckResultSchema,\n} from \"./server\";\n\n/** Type-checks the server entry under the tsconfig beside it, as it will be built. */\nconst serverFailure = ({\n\tentry,\n\troot,\n}: z.infer<typeof serverCheckRequestSchema>): string | null => {\n\tconst tsconfig = ts.findConfigFile(dirname(entry), ts.sys.fileExists);\n\tif (!tsconfig) {\n\t\treturn \"Server entry requires a tsconfig.json.\";\n\t}\n\tconst read = ts.readConfigFile(tsconfig, ts.sys.readFile);\n\tif (read.error) {\n\t\treturn ts.flattenDiagnosticMessageText(read.error.messageText, \"\\n\");\n\t}\n\tconst parsed = ts.parseJsonConfigFileContent(\n\t\tread.config,\n\t\tts.sys,\n\t\tdirname(tsconfig),\n\t);\n\tconst program = ts.createProgram({\n\t\trootNames: [\n\t\t\tentry,\n\t\t\t...parsed.fileNames.filter((file) => /\\.d\\.[cm]?ts$/.test(file)),\n\t\t],\n\t\toptions: { ...parsed.options, ...typeCheckOnly },\n\t\tprojectReferences: parsed.projectReferences,\n\t});\n\tconst diagnostics = [...parsed.errors, ...ts.getPreEmitDiagnostics(program)];\n\tif (!diagnostics.length) {\n\t\treturn null;\n\t}\n\treturn ts.formatDiagnosticsWithColorAndContext(diagnostics, {\n\t\tgetCanonicalFileName: (path) => path,\n\t\tgetCurrentDirectory: () => root,\n\t\tgetNewLine: () => \"\\n\",\n\t});\n};\n\n// A worker thread runs this module, so the check of a server's thousands of files overlaps the PLC build.\ndeclare const self: Worker;\nself.onmessage = (event: MessageEvent) => {\n\tconst result: z.infer<typeof serverCheckResultSchema> = {\n\t\tfailure: serverFailure(serverCheckRequestSchema.parse(event.data)),\n\t};\n\tself.postMessage(result);\n};\n",
6
- "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"
7
- ],
8
- "mappings": ";;AAAA;AACA;AACA;;;ACIA;AA6BO,IAAM,2BAA2B,EAAE,aAAa;AAAA,EACtD,OAAO,EAAE,OAAO;AAAA,EAChB,MAAM,EAAE,OAAO;AAChB,CAAC;AAGM,IAAM,0BAA0B,EAAE,aAAa;AAAA,EACrD,SAAS,EAAE,OAAO,EAAE,SAAS;AAC9B,CAAC;;;ADjCD,IAAM,gBAAgB;AAAA,EACrB;AAAA,EACA;AAAA,MAC8D;AAAA,EAC9D,MAAM,WAAW,GAAG,eAAe,QAAQ,KAAK,GAAG,GAAG,IAAI,UAAU;AAAA,EACpE,IAAI,CAAC,UAAU;AAAA,IACd,OAAO;AAAA,EACR;AAAA,EACA,MAAM,OAAO,GAAG,eAAe,UAAU,GAAG,IAAI,QAAQ;AAAA,EACxD,IAAI,KAAK,OAAO;AAAA,IACf,OAAO,GAAG,6BAA6B,KAAK,MAAM,aAAa;AAAA,CAAI;AAAA,EACpE;AAAA,EACA,MAAM,SAAS,GAAG,2BACjB,KAAK,QACL,GAAG,KACH,QAAQ,QAAQ,CACjB;AAAA,EACA,MAAM,UAAU,GAAG,cAAc;AAAA,IAChC,WAAW;AAAA,MACV;AAAA,MACA,GAAG,OAAO,UAAU,OAAO,CAAC,SAAS,gBAAgB,KAAK,IAAI,CAAC;AAAA,IAChE;AAAA,IACA,SAAS,KAAK,OAAO,YAAY,cAAc;AAAA,IAC/C,mBAAmB,OAAO;AAAA,EAC3B,CAAC;AAAA,EACD,MAAM,cAAc,CAAC,GAAG,OAAO,QAAQ,GAAG,GAAG,sBAAsB,OAAO,CAAC;AAAA,EAC3E,IAAI,CAAC,YAAY,QAAQ;AAAA,IACxB,OAAO;AAAA,EACR;AAAA,EACA,OAAO,GAAG,qCAAqC,aAAa;AAAA,IAC3D,sBAAsB,CAAC,SAAS;AAAA,IAChC,qBAAqB,MAAM;AAAA,IAC3B,YAAY,MAAM;AAAA;AAAA,EACnB,CAAC;AAAA;AAKF,KAAK,YAAY,CAAC,UAAwB;AAAA,EACzC,MAAM,SAAkD;AAAA,IACvD,SAAS,cAAc,yBAAyB,MAAM,MAAM,IAAI,CAAC;AAAA,EAClE;AAAA,EACA,KAAK,YAAY,MAAM;AAAA;",
9
- "debugId": "81486E03709D174864756E2164756E21",
10
- "names": []
11
- }
@@ -1,181 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { type Diagnostic, error } from "@tsplc/compiler/ir";
3
- import { elementaryType, isIntegerValued } from "@tsplc/iec";
4
- import ts from "typescript";
5
- import { runtimeSources } from "./module-graph";
6
- import {
7
- copied,
8
- type Edit,
9
- edited,
10
- from,
11
- joined,
12
- type Mapped,
13
- mapped,
14
- type Positions,
15
- } from "./positions";
16
- import { namesSdk, symbolAt } from "./sdk";
17
-
18
- /** Telemetry carries a BOOL, an integer or bit string of up to 32 bits, or a bounded STRING. */
19
- const telemetryType = (annotation: string): boolean => {
20
- const type = elementaryType(annotation);
21
- return (
22
- type?.family === "bool" ||
23
- (isIntegerValued(type) && type.bits <= 32) ||
24
- /^STRING<\d+>$/.test(annotation)
25
- );
26
- };
27
-
28
- /** Telemetry is sampled by its authored task and published read-only by the backend. */
29
- export const lowerExposure = (
30
- program: ts.Program,
31
- sdk: string,
32
- positions: Positions,
33
- ) => {
34
- const checker = program.getTypeChecker();
35
- const sources = new Map<string, Mapped>();
36
- const diagnostics: Diagnostic[] = [];
37
- const variables = new Map<string, { name: string; version: string }>();
38
- const names = new Set<string>();
39
- for (const source of runtimeSources(program)) {
40
- if (source.isDeclarationFile) {
41
- continue;
42
- }
43
- const edits: Edit[] = [];
44
- const extra: Mapped[] = [];
45
- const visit = (node: ts.Node): void => {
46
- if (
47
- !ts.isCallExpression(node) ||
48
- !namesSdk(checker, sdk, node.expression, "expose")
49
- ) {
50
- ts.forEachChild(node, visit);
51
- return;
52
- }
53
- const fail = (message: string) =>
54
- diagnostics.push(error("PLC1014", message, positions.node(node)));
55
- const [label, values] = node.arguments;
56
- if (
57
- !label ||
58
- !ts.isStringLiteral(label) ||
59
- !/^[A-Za-z_][A-Za-z0-9_]*$/.test(label.text) ||
60
- label.text === "__proto__" ||
61
- !values ||
62
- !ts.isObjectLiteralExpression(values) ||
63
- !ts.isExpressionStatement(node.parent)
64
- ) {
65
- fail(
66
- "expose requires a literal machine name and a flat telemetry object in a synchronous cyclic routine.",
67
- );
68
- return;
69
- }
70
- let owner: ts.Node | undefined = node.parent;
71
- while (owner && !ts.isFunctionLike(owner)) {
72
- owner = owner.parent;
73
- }
74
- if (
75
- !owner ||
76
- (ts.canHaveModifiers(owner) &&
77
- ts
78
- .getModifiers(owner)
79
- ?.some((value) => value.kind === ts.SyntaxKind.AsyncKeyword))
80
- ) {
81
- fail(
82
- "Sample telemetry from a synchronous cyclic routine, outside async continuations.",
83
- );
84
- return;
85
- }
86
- if (names.has(label.text)) {
87
- fail(`Duplicate machine exposure ${label.text}.`);
88
- return;
89
- }
90
- names.add(label.text);
91
- const fields: { name: string; type: string; value: Mapped }[] = [];
92
- for (const property of values.properties) {
93
- if (
94
- !ts.isPropertyAssignment(property) ||
95
- !ts.isIdentifier(property.name) ||
96
- ["contractVersion", "__proto__"].includes(property.name.text)
97
- ) {
98
- fail(
99
- "Telemetry uses named scalar fields; contractVersion and __proto__ are reserved.",
100
- );
101
- return;
102
- }
103
- const value = property.initializer;
104
- const type = checker.getTypeAtLocation(value);
105
- let annotation: string | undefined;
106
- if (type.flags & ts.TypeFlags.BooleanLike) {
107
- annotation = "BOOL";
108
- }
109
- const declaration = symbolAt(
110
- checker,
111
- ts.isPropertyAccessExpression(value) ? value.name : value,
112
- )?.valueDeclaration;
113
- if (
114
- declaration &&
115
- (ts.isPropertySignature(declaration) ||
116
- ts.isPropertyDeclaration(declaration) ||
117
- ts.isVariableDeclaration(declaration) ||
118
- ts.isParameter(declaration)) &&
119
- declaration.type
120
- ) {
121
- const text = declaration.type.getText(declaration.getSourceFile());
122
- if (telemetryType(text)) {
123
- annotation = text;
124
- }
125
- }
126
- if (!annotation) {
127
- fail(
128
- `Telemetry ${property.name.text} needs a concrete BOOL, integer up to 32 bits or bounded STRING annotation.`,
129
- );
130
- return;
131
- }
132
- fields.push({
133
- name: property.name.text,
134
- type: annotation,
135
- value: copied(value),
136
- });
137
- }
138
- if (!fields.length) {
139
- fail("Expose at least one telemetry field.");
140
- return;
141
- }
142
- const name = `tsplcExposed_${label.text}`;
143
- const record = `TsplcTelemetry_${label.text}`;
144
- const version = createHash("sha256")
145
- .update(
146
- JSON.stringify({
147
- abi: 1,
148
- name: label.text,
149
- fields: fields.map(({ name, type }) => ({ name, type })),
150
- }),
151
- )
152
- .digest("hex");
153
- extra.push(
154
- from(
155
- node,
156
- `export interface ${record}{contractVersion:STRING<64>;${fields.map((field) => `${field.name}:${field.type}`).join(";")}}\nexport let ${name}:${record}=defaultValue<${record}>();`,
157
- ),
158
- );
159
- variables.set(`${source.fileName}:${name}`, {
160
- name: label.text,
161
- version,
162
- });
163
- edits.push({
164
- start: node.getStart(source),
165
- end: node.end,
166
- text: mapped`{${name}.contractVersion=${JSON.stringify(version)};${joined(
167
- fields.map((field) => mapped`${name}.${field.name}=${field.value};`),
168
- "",
169
- )}}`,
170
- });
171
- };
172
- visit(source);
173
- if (edits.length) {
174
- sources.set(
175
- source.fileName,
176
- mapped`${edited(source, edits)}\n${joined(extra, "\n")}`,
177
- );
178
- }
179
- }
180
- return { sources, diagnostics, variables };
181
- };
@@ -1,6 +0,0 @@
1
- export {
2
- buildProject,
3
- checkProject,
4
- cleanProject,
5
- projectTargets,
6
- } from "./project";
@@ -1,17 +0,0 @@
1
- import { initTRPC } from "@trpc/server";
2
- import { iec, type PlcMeta } from "@tsplc/server";
3
- import { z } from "zod";
4
-
5
- const api = initTRPC.meta<PlcMeta>().create();
6
- /** Callable by the PLC through createServiceClient. */
7
- const plcProcedure = api.procedure.meta({ plc: true });
8
-
9
- export const appRouter = api.router({
10
- cell: api.router({
11
- report: plcProcedure
12
- .input(z.strictObject({ count: iec.UINT(), running: z.boolean() }))
13
- .output(z.strictObject({ answer: iec.DINT() }))
14
- .mutation(({ input }) => ({ answer: input.count * 2 + 1 })),
15
- }),
16
- });
17
- export type AppRouter = typeof appRouter;
@@ -1,45 +0,0 @@
1
- import { retain } from "@tsplc/compiler/retain";
2
- import { Lane } from "./lane";
3
-
4
- export type Mode = "idle" | "running";
5
-
6
- export interface Card {
7
- input: { sensor: BOOL };
8
- output: { motion: BOOL; speed: INT };
9
- }
10
-
11
- /** The cell's IO, its operator's controls and its counts: what the program publishes. */
12
- export interface Cell {
13
- cards: Card[];
14
- mode: Mode;
15
- start: BOOL;
16
- bump: BOOL;
17
- count: UINT;
18
- scans: UDINT;
19
- lanes: Record<Lane, BOOL>;
20
- lastLane: Lane | undefined;
21
- report: BOOL;
22
- replies: UDINT;
23
- answer: DINT;
24
- failures: UDINT;
25
- settings: { speed: INT };
26
- }
27
-
28
- export const createCell = (): Cell => ({
29
- cards: Array.from({ length: 3 }, () => ({
30
- input: { sensor: false },
31
- output: { motion: false, speed: 0 },
32
- })),
33
- mode: "idle",
34
- start: false,
35
- bump: false,
36
- count: 0,
37
- scans: 0,
38
- lanes: { [Lane.Unknown]: false, [Lane.Left]: false, [Lane.Right]: false },
39
- lastLane: undefined,
40
- report: false,
41
- replies: 0,
42
- answer: 0,
43
- failures: 0,
44
- settings: retain({ speed: 50 }),
45
- });
@@ -1,58 +0,0 @@
1
- import { telemetry } from "@tsplc/compiler/telemetry";
2
- import type { Cell } from "./cell";
3
- import { Lane } from "./lane";
4
- import type { ReportReply, Services } from "./services";
5
-
6
- export class CellController {
7
- private sending = false;
8
-
9
- constructor(
10
- private readonly cell: Cell,
11
- private readonly services: Services,
12
- ) {}
13
-
14
- scan(): void {
15
- const cell = this.cell;
16
- cell.scans += 1;
17
- for (const card of cell.cards) {
18
- card.output.motion = card.input.sensor && cell.mode === "running";
19
- card.output.speed = card.input.sensor ? cell.settings.speed : 0;
20
- }
21
- if (cell.start) {
22
- cell.start = false;
23
- cell.mode = "running";
24
- }
25
- if (cell.bump) {
26
- cell.bump = false;
27
- cell.count = cell.count + 1;
28
- }
29
- cell.lastLane = undefined;
30
- if (cell.lanes[Lane.Left]) {
31
- cell.lastLane = Lane.Left;
32
- }
33
- if (cell.lanes[Lane.Right]) {
34
- cell.lastLane = Lane.Right;
35
- }
36
- if (cell.report && !this.sending) {
37
- cell.report = false;
38
- void this.send();
39
- }
40
- }
41
-
42
- private async send(): Promise<void> {
43
- this.sending = true;
44
- try {
45
- const reply: ReportReply = await this.services.cell.report({
46
- count: this.cell.count,
47
- running: this.cell.mode === "running",
48
- });
49
- this.cell.replies += 1;
50
- this.cell.answer = reply.answer;
51
- telemetry.info("Report answered", { answer: reply.answer });
52
- } catch (error) {
53
- this.cell.failures += 1;
54
- telemetry.captureException(error);
55
- }
56
- this.sending = false;
57
- }
58
- }
@@ -1,6 +0,0 @@
1
- /** Where the cell sends a part. */
2
- export enum Lane {
3
- Unknown = 0,
4
- Left = 1,
5
- Right = 2,
6
- }
@@ -1,11 +0,0 @@
1
- import { createCell } from "./cell";
2
- import { CellController } from "./controller";
3
- import { services } from "./services";
4
-
5
- export const cell = createCell();
6
- const controller = new CellController(cell, services);
7
-
8
- /** One PLC scan. */
9
- export function main(): void {
10
- controller.scan();
11
- }
@@ -1,8 +0,0 @@
1
- import type { inferRouterOutputs } from "@trpc/server";
2
- import { createServiceClient } from "@tsplc/compiler/async";
3
- import type { AppRouter } from "../server/router";
4
-
5
- /** The server procedures the program calls. */
6
- export const services = createServiceClient<AppRouter>();
7
- export type Services = typeof services;
8
- export type ReportReply = inferRouterOutputs<AppRouter>["cell"]["report"];
@@ -1,13 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "strict": true,
4
- "target": "ES2022",
5
- "module": "ESNext",
6
- "moduleResolution": "Bundler",
7
- "noEmit": true,
8
- "skipLibCheck": true,
9
- "types": ["bun", "@tsplc/compiler/globals"],
10
- "allowImportingTsExtensions": true
11
- },
12
- "include": ["src/**/*.ts", "server/**/*.ts"]
13
- }
@@ -1,31 +0,0 @@
1
- import { defineConfig, ms } from "@tsplc/config";
2
-
3
- /** A cell whose plain TypeScript program the Bun runtime runs in the compiler's tests. */
4
- export default defineConfig({
5
- name: "BunRuntimeCell",
6
- backend: "codesys",
7
- build: { outDir: "build/codesys", symbols: true },
8
- codesys: {
9
- http: {
10
- timeoutMs: 2000,
11
- credentials: [
12
- { originEnv: "CELL_SERVER_URL", bearerTokenEnv: "CELL_SERVER_TOKEN" },
13
- ],
14
- },
15
- programNames: { main: "Main" },
16
- },
17
- compiler: {
18
- programs: { main: { module: "src/main.ts", export: "main" } },
19
- },
20
- tasks: [
21
- {
22
- name: "MainTask",
23
- priority: 1,
24
- schedule: { kind: "cyclic", interval: ms(20) },
25
- programs: ["main"],
26
- },
27
- ],
28
- publish: { development: ["cell"], production: ["cell"] },
29
- server: { transport: "http", baseUrlEnv: "CELL_SERVER_URL" },
30
- typegen: { dir: "generated" },
31
- });
@@ -1,17 +0,0 @@
1
- import { initTRPC } from "@trpc/server";
2
- import { iec, type PlcMeta } from "@tsplc/server";
3
- import { z } from "zod";
4
-
5
- const api = initTRPC.meta<PlcMeta>().create();
6
- /** Callable by the PLC through createServiceClient. */
7
- const plcProcedure = api.procedure.meta({ plc: true });
8
-
9
- export const appRouter = api.router({
10
- cell: api.router({
11
- report: plcProcedure
12
- .input(z.strictObject({ count: iec.UINT(), running: z.boolean() }))
13
- .output(z.strictObject({ answer: iec.DINT() }))
14
- .mutation(({ input }) => ({ answer: input.count * 2 + 1 })),
15
- }),
16
- });
17
- export type AppRouter = typeof appRouter;
@@ -1,45 +0,0 @@
1
- import { retain } from "@tsplc/compiler/retain";
2
- import { Lane } from "./lane";
3
-
4
- export type Mode = "idle" | "running";
5
-
6
- export interface Card {
7
- input: { sensor: BOOL };
8
- output: { motion: BOOL; speed: INT };
9
- }
10
-
11
- /** The cell's IO, its operator's controls and its counts: what the program publishes. */
12
- export interface Cell {
13
- cards: Card[];
14
- mode: Mode;
15
- start: BOOL;
16
- bump: BOOL;
17
- count: UINT;
18
- scans: UDINT;
19
- lanes: Record<Lane, BOOL>;
20
- lastLane: Lane | undefined;
21
- report: BOOL;
22
- replies: UDINT;
23
- answer: DINT;
24
- failures: UDINT;
25
- settings: { speed: INT };
26
- }
27
-
28
- export const createCell = (): Cell => ({
29
- cards: Array.from({ length: 3 }, () => ({
30
- input: { sensor: false },
31
- output: { motion: false, speed: 0 },
32
- })),
33
- mode: "idle",
34
- start: false,
35
- bump: false,
36
- count: 0,
37
- scans: 0,
38
- lanes: { [Lane.Unknown]: false, [Lane.Left]: false, [Lane.Right]: false },
39
- lastLane: undefined,
40
- report: false,
41
- replies: 0,
42
- answer: 0,
43
- failures: 0,
44
- settings: retain({ speed: 50 }),
45
- });