@tsplc/tmp-compiler 0.0.0-stage → 0.6.2

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 (184) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/dist/cli.js +2325 -0
  4. package/dist/cli.js.map +26 -0
  5. package/dist/clock.js +11 -0
  6. package/dist/clock.js.map +11 -0
  7. package/dist/codesys.js +6558 -0
  8. package/dist/codesys.js.map +51 -0
  9. package/dist/collections.js +399 -0
  10. package/dist/collections.js.map +10 -0
  11. package/dist/index.js +16076 -0
  12. package/dist/index.js.map +61 -0
  13. package/dist/ir.js +3948 -0
  14. package/dist/ir.js.map +35 -0
  15. package/dist/retain.js +10 -0
  16. package/dist/retain.js.map +10 -0
  17. package/dist/signals.js +115 -0
  18. package/dist/signals.js.map +10 -0
  19. package/dist/telemetry.js +121 -0
  20. package/dist/telemetry.js.map +12 -0
  21. package/package.json +122 -4
  22. package/src/codesys/config.ts +50 -0
  23. package/src/codesys/debug.ts +655 -0
  24. package/src/codesys/emit.ts +185 -0
  25. package/src/codesys/endpoints.ts +111 -0
  26. package/src/codesys/engineering.ts +96 -0
  27. package/src/codesys/explain/expressions.ts +445 -0
  28. package/src/codesys/explain/flags.ts +134 -0
  29. package/src/codesys/explain/parameters.ts +53 -0
  30. package/src/codesys/explain/rows.ts +182 -0
  31. package/src/codesys/explain/tables.ts +79 -0
  32. package/src/codesys/explain/tasks.ts +68 -0
  33. package/src/codesys/explain/writes.ts +497 -0
  34. package/src/codesys/explain.ts +149 -0
  35. package/src/codesys/expressions.ts +100 -0
  36. package/src/codesys/global-lists.ts +284 -0
  37. package/src/codesys/global-names.ts +66 -0
  38. package/src/codesys/http.ts +1078 -0
  39. package/src/codesys/index.ts +13 -0
  40. package/src/codesys/instrumentation.ts +574 -0
  41. package/src/codesys/io-paths.ts +149 -0
  42. package/src/codesys/loops.ts +101 -0
  43. package/src/codesys/manifest.ts +684 -0
  44. package/src/codesys/names.ts +58 -0
  45. package/src/codesys/numeric.ts +516 -0
  46. package/src/codesys/plan.ts +688 -0
  47. package/src/codesys/programs.ts +138 -0
  48. package/src/codesys/publication.ts +99 -0
  49. package/src/codesys/required.ts +8 -0
  50. package/src/codesys/routines.ts +247 -0
  51. package/src/codesys/scan-clock.ts +103 -0
  52. package/src/codesys/scheduling.ts +96 -0
  53. package/src/codesys/service-channels.ts +24 -0
  54. package/src/codesys/sources.ts +118 -0
  55. package/src/codesys/st-files.ts +219 -0
  56. package/src/codesys/statements.ts +409 -0
  57. package/src/codesys/storage.ts +150 -0
  58. package/src/codesys/symbols.ts +240 -0
  59. package/src/codesys/task-access.ts +186 -0
  60. package/src/codesys/telemetry-settings.ts +19 -0
  61. package/src/codesys/telemetry.ts +852 -0
  62. package/src/codesys/types.ts +310 -0
  63. package/src/codesys/vendor.ts +113 -0
  64. package/src/frontend/analyzer.ts +779 -0
  65. package/src/frontend/async.ts +530 -0
  66. package/src/frontend/blocks.ts +578 -0
  67. package/src/frontend/configuration.ts +83 -0
  68. package/src/frontend/const-functions.ts +204 -0
  69. package/src/frontend/control-flow.ts +787 -0
  70. package/src/frontend/cooperative.ts +114 -0
  71. package/src/frontend/coroutines.ts +1336 -0
  72. package/src/frontend/dialect-names.ts +104 -0
  73. package/src/frontend/elaborate/array-searches.ts +224 -0
  74. package/src/frontend/elaborate/assignments.ts +343 -0
  75. package/src/frontend/elaborate/calls.ts +1342 -0
  76. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  77. package/src/frontend/elaborate/capture.ts +388 -0
  78. package/src/frontend/elaborate/declarations.ts +124 -0
  79. package/src/frontend/elaborate/dialect.ts +473 -0
  80. package/src/frontend/elaborate/expressions.ts +2171 -0
  81. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  82. package/src/frontend/elaborate/frame.ts +145 -0
  83. package/src/frontend/elaborate/generics.ts +123 -0
  84. package/src/frontend/elaborate/graph.ts +141 -0
  85. package/src/frontend/elaborate/imports.ts +105 -0
  86. package/src/frontend/elaborate/index.ts +851 -0
  87. package/src/frontend/elaborate/initializers.ts +235 -0
  88. package/src/frontend/elaborate/iterators.ts +1541 -0
  89. package/src/frontend/elaborate/layouts.ts +1025 -0
  90. package/src/frontend/elaborate/model.ts +478 -0
  91. package/src/frontend/elaborate/names.ts +134 -0
  92. package/src/frontend/elaborate/reduce.ts +900 -0
  93. package/src/frontend/elaborate/references.ts +727 -0
  94. package/src/frontend/elaborate/retention.ts +284 -0
  95. package/src/frontend/elaborate/specialize.ts +1137 -0
  96. package/src/frontend/elaborate/statements.ts +1220 -0
  97. package/src/frontend/elaborate/storage.ts +836 -0
  98. package/src/frontend/elaborate/time-constructors.ts +34 -0
  99. package/src/frontend/elaborate/values.ts +200 -0
  100. package/src/frontend/elaborate/writes.ts +415 -0
  101. package/src/frontend/expressions.ts +1382 -0
  102. package/src/frontend/generated-names.ts +95 -0
  103. package/src/frontend/intrinsics.ts +382 -0
  104. package/src/frontend/lowering-key.ts +23 -0
  105. package/src/frontend/module-graph.ts +156 -0
  106. package/src/frontend/positions.ts +359 -0
  107. package/src/frontend/promise-chains.ts +872 -0
  108. package/src/frontend/promises.ts +419 -0
  109. package/src/frontend/routines.ts +239 -0
  110. package/src/frontend/sdk.ts +187 -0
  111. package/src/frontend/services.ts +609 -0
  112. package/src/frontend/statements.ts +871 -0
  113. package/src/frontend/tasks.ts +526 -0
  114. package/src/frontend/telemetry.ts +174 -0
  115. package/src/frontend/types.ts +1073 -0
  116. package/src/frontend/typescript.ts +651 -0
  117. package/src/index.ts +9 -0
  118. package/src/ir/aggregates.ts +291 -0
  119. package/src/ir/allocation.ts +96 -0
  120. package/src/ir/conditions.ts +855 -0
  121. package/src/ir/core-model.ts +289 -0
  122. package/src/ir/declarations.ts +281 -0
  123. package/src/ir/diagnostics.ts +68 -0
  124. package/src/ir/domains.ts +151 -0
  125. package/src/ir/fold.ts +279 -0
  126. package/src/ir/identity.ts +19 -0
  127. package/src/ir/index.ts +137 -0
  128. package/src/ir/job-errors.ts +69 -0
  129. package/src/ir/layouts.ts +211 -0
  130. package/src/ir/link.ts +302 -0
  131. package/src/ir/model.ts +394 -0
  132. package/src/ir/normalization-error.ts +10 -0
  133. package/src/ir/normalize.ts +52 -0
  134. package/src/ir/numeric.ts +163 -0
  135. package/src/ir/operands.ts +160 -0
  136. package/src/ir/ranges.ts +420 -0
  137. package/src/ir/routine.ts +1116 -0
  138. package/src/ir/scalars.ts +453 -0
  139. package/src/ir/share.ts +790 -0
  140. package/src/ir/short-circuit.ts +140 -0
  141. package/src/ir/tables.ts +111 -0
  142. package/src/ir/temporaries.ts +138 -0
  143. package/src/ir/types.ts +151 -0
  144. package/src/project/artifacts.ts +424 -0
  145. package/src/project/cli.ts +211 -0
  146. package/src/project/debugger.ts +111 -0
  147. package/src/project/deployments.ts +387 -0
  148. package/src/project/flags.ts +14 -0
  149. package/src/project/git.ts +35 -0
  150. package/src/project/plant.ts +629 -0
  151. package/src/project/project-commands.ts +507 -0
  152. package/src/project/project.ts +559 -0
  153. package/src/project/release.ts +152 -0
  154. package/src/project/server-check.ts +54 -0
  155. package/src/project/server.ts +165 -0
  156. package/src/project/terminal.ts +45 -0
  157. package/src/runtime/async.ts +207 -0
  158. package/src/runtime/launch.ts +59 -0
  159. package/src/runtime/main.ts +59 -0
  160. package/src/runtime/missing-file.ts +3 -0
  161. package/src/runtime/process.ts +177 -0
  162. package/src/runtime/program.ts +109 -0
  163. package/src/runtime/retain.ts +108 -0
  164. package/src/runtime/runtime.ts +324 -0
  165. package/src/runtime/settings.ts +27 -0
  166. package/src/runtime/storage.ts +456 -0
  167. package/src/runtime/symbols.ts +97 -0
  168. package/src/runtime/telemetry.ts +154 -0
  169. package/src/runtime/transport.ts +168 -0
  170. package/stdlib/clock.ts +8 -0
  171. package/stdlib/collections.ts +534 -0
  172. package/stdlib/plc-time.ts +2 -0
  173. package/stdlib/retain.ts +4 -0
  174. package/stdlib/signals.ts +142 -0
  175. package/stdlib/telemetry.ts +89 -0
  176. package/types/async.d.ts +87 -0
  177. package/types/clock.d.ts +8 -0
  178. package/types/config.d.ts +2 -0
  179. package/types/data-types.d.ts +31 -0
  180. package/types/dialect.d.ts +49 -0
  181. package/types/globals.d.ts +10 -0
  182. package/types/index.d.ts +212 -0
  183. package/types/retain.d.ts +12 -0
  184. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,559 @@
1
+ import {
2
+ copyFile,
3
+ mkdir,
4
+ mkdtemp,
5
+ realpath,
6
+ rm,
7
+ writeFile,
8
+ } from "node:fs/promises";
9
+ import { basename, dirname, join, resolve } from "node:path";
10
+ import {
11
+ buildFiles,
12
+ installLibraries,
13
+ type ProgressOptions,
14
+ } from "@tsplc/build";
15
+ import { analyze, type BoundPath } from "@tsplc/compiler";
16
+ import {
17
+ buildCodesys,
18
+ type CodesysPlan,
19
+ type CodesysProject,
20
+ codesysBuildConfig,
21
+ diagnoseCodesys,
22
+ emitCodesys,
23
+ ioTargets,
24
+ planCodesys,
25
+ publicationSelectors,
26
+ type SourceMapping,
27
+ } from "@tsplc/compiler/codesys";
28
+ import {
29
+ type Diagnostic,
30
+ hasErrors,
31
+ normalizeModule,
32
+ type VerifiedCoreModule,
33
+ } from "@tsplc/compiler/ir";
34
+ import {
35
+ type BuildTarget,
36
+ type Controller,
37
+ compilerConfig,
38
+ type LoadedConfig,
39
+ type NormalizedConfig,
40
+ type ResolvedTsplcConfig,
41
+ serverBaseUrl,
42
+ simulationConfig,
43
+ taskPlan,
44
+ } from "@tsplc/config";
45
+ import {
46
+ configFileName,
47
+ emittedFiles,
48
+ emittedStDirectory,
49
+ } from "@tsplc/config/project-files";
50
+ import { explainFileName } from "@tsplc/debug/explain-file";
51
+ import { debugManifestFile } from "@tsplc/debug/manifest";
52
+ import {
53
+ deviceTree,
54
+ loadHardware,
55
+ type ProjectTargets,
56
+ resolveIo,
57
+ } from "@tsplc/typegen";
58
+ import { serviceRoutes } from "../runtime/launch";
59
+ import {
60
+ claimed,
61
+ cleanArtifacts,
62
+ engineeringDirectory,
63
+ owned,
64
+ publishArtifacts,
65
+ withdrawReceipt,
66
+ } from "./artifacts";
67
+
68
+ const emittedSt = basename(emittedStDirectory);
69
+
70
+ const failure = (
71
+ origin: Diagnostic["origin"],
72
+ code: string,
73
+ cause: unknown,
74
+ ): Diagnostic => ({
75
+ origin,
76
+ code,
77
+ severity: "error",
78
+ message: cause instanceof Error ? cause.message : String(cause),
79
+ });
80
+
81
+ /**
82
+ * `buildTypeScriptProject`'s `loaded` and `configured` options. With `simulate` the build omits fieldbus
83
+ * I/O so a plant simulator can write the inputs; generated types and the debug manifest keep
84
+ * describing the hardware project.
85
+ */
86
+ export const buildConfigs = (
87
+ loaded: LoadedConfig,
88
+ options: { simulate?: boolean },
89
+ ) =>
90
+ options.simulate
91
+ ? {
92
+ loaded: { ...loaded, config: simulationConfig(loaded.config) },
93
+ configured: loaded.config,
94
+ }
95
+ : { loaded };
96
+
97
+ interface ProjectOptions {
98
+ /** The config, whose `env` the program's `env()` calls, endpoints and telemetry read. */
99
+ loaded: LoadedConfig;
100
+ buildTarget?: BuildTarget;
101
+ /** The configuration `loaded` simulates, whose hardware the debug manifest describes. */
102
+ configured?: ResolvedTsplcConfig;
103
+ /** The host config check's diagnostics, which type-check the config before it runs. */
104
+ hostConfigDiagnostics: readonly Diagnostic[];
105
+ }
106
+
107
+ /** The project `file` configures, or the diagnostics of why it can't be compiled. */
108
+ async function loadProject(
109
+ file: string,
110
+ { loaded, buildTarget, configured, hostConfigDiagnostics }: ProjectOptions,
111
+ ): Promise<
112
+ | {
113
+ config: NormalizedConfig;
114
+ configFile: string;
115
+ shared: ResolvedTsplcConfig;
116
+ project: CodesysProject;
117
+ /** The state paths the hardware's `io` binds, which a simulator writes too. */
118
+ bound: BoundPath[];
119
+ diagnostics: readonly Diagnostic[];
120
+ }
121
+ | { configFile: string; diagnostics: readonly Diagnostic[] }
122
+ > {
123
+ const unresolved = resolve(file);
124
+ const configFile = await realpath(unresolved).catch((cause: unknown) =>
125
+ unloaded(unresolved, cause),
126
+ );
127
+ if (typeof configFile !== "string") {
128
+ return configFile;
129
+ }
130
+ try {
131
+ if (hasErrors(hostConfigDiagnostics)) {
132
+ return { configFile, diagnostics: hostConfigDiagnostics };
133
+ }
134
+ const { config: shared, env } = loaded;
135
+ if (
136
+ shared.debug?.trace &&
137
+ shared.server?.transport !== "opcua" &&
138
+ !serverBaseUrl(shared, env)
139
+ ) {
140
+ throw new Error(
141
+ 'debug.trace sends its records to the app server: configure server with baseUrlEnv and set that variable, or use server.transport "opcua".',
142
+ );
143
+ }
144
+ const root = dirname(configFile);
145
+ const catalog = await loadHardware(shared, root);
146
+
147
+ const config = compilerConfig(
148
+ shared,
149
+ resolveIo(shared, catalog),
150
+ buildTarget,
151
+ );
152
+ const hardware = configured
153
+ ? { config: configured, catalog: await loadHardware(configured, root) }
154
+ : { config: shared, catalog };
155
+ return {
156
+ configFile,
157
+ shared,
158
+ config: { ...config, ...sourceInput(config, root) },
159
+ project: {
160
+ root,
161
+ environment: env,
162
+ ...(shared.debug && { debug: shared.debug }),
163
+ ...(shared.telemetry && { telemetry: shared.telemetry }),
164
+ ...(shared.server && { server: shared.server }),
165
+ ...(shared.hmi && { hmi: shared.hmi }),
166
+ // A simulation build drops fieldbus IO, but the debugger still shows the hardware it stands in for.
167
+ hardware: {
168
+ ...hardware,
169
+ tree: shared.codesys?.deviceTree !== undefined,
170
+ },
171
+ },
172
+ bound: boundPaths(resolveIo(hardware.config, hardware.catalog)),
173
+ diagnostics: hostConfigDiagnostics,
174
+ };
175
+ } catch (cause) {
176
+ return unloaded(configFile, cause);
177
+ }
178
+ }
179
+
180
+ const unloaded = (configFile: string, cause: unknown) => ({
181
+ configFile,
182
+ diagnostics: [failure("config", "PLC5003", cause)],
183
+ });
184
+
185
+ /** The analyzer's entry points, resolved against the config file's directory. */
186
+ function sourceInput(
187
+ compiler: {
188
+ tsconfig: string;
189
+ programs: Record<string, { module: string; export: string }>;
190
+ },
191
+ root: string,
192
+ ) {
193
+ return {
194
+ tsconfig: resolve(root, compiler.tsconfig),
195
+ programs: Object.fromEntries(
196
+ Object.entries(compiler.programs).map(([name, entry]) => [
197
+ name,
198
+ { ...entry, module: resolve(root, entry.module) },
199
+ ]),
200
+ ),
201
+ };
202
+ }
203
+
204
+ /**
205
+ * I/O keys and publication selectors from analyzed PLC source. It ignores the
206
+ * config's own type errors, so a typo cannot switch off the types that flag it;
207
+ * it is undefined only while the source itself fails analysis.
208
+ */
209
+ export async function projectTargets(
210
+ file: string,
211
+ { config, env }: LoadedConfig,
212
+ ): Promise<ProjectTargets | undefined> {
213
+ const configFile = await realpath(resolve(file));
214
+ if (!config.compiler) {
215
+ return undefined;
216
+ }
217
+ const source = analyze({
218
+ ...sourceInput(config.compiler, dirname(configFile)),
219
+ services: config.server,
220
+ environment: env,
221
+ // A device channel's direction needs the hardware, which check and build resolve.
222
+ io: boundPaths(config.io),
223
+ });
224
+ const core = source.module && normalizeModule(source.module).core;
225
+ return core ? coreTargets(core) : undefined;
226
+ }
227
+
228
+ /** The state paths `io` binds, each marked with the `%I` address the hardware writes it from. */
229
+ const boundPaths = (io: ResolvedTsplcConfig["io"]): BoundPath[] =>
230
+ Object.entries(io).map(([path, binding]) => ({
231
+ path,
232
+ input:
233
+ "address" in binding && binding.address.startsWith("%I")
234
+ ? binding.address
235
+ : null,
236
+ }));
237
+
238
+ const coreTargets = (core: VerifiedCoreModule): ProjectTargets => ({
239
+ io: ioTargets(core),
240
+ publication: publicationSelectors(core),
241
+ });
242
+
243
+ export async function checkProject(
244
+ file: string,
245
+ options: ProjectOptions,
246
+ ): Promise<{
247
+ configFile: string;
248
+ config?: NormalizedConfig;
249
+ shared?: ResolvedTsplcConfig;
250
+ plan?: CodesysPlan;
251
+ diagnostics: readonly Diagnostic[];
252
+ }> {
253
+ const loaded = await loadProject(file, options);
254
+ if (!("project" in loaded)) {
255
+ return loaded;
256
+ }
257
+
258
+ const { config } = loaded;
259
+ const source = analyze({
260
+ tsconfig: config.tsconfig,
261
+ programs: config.programs,
262
+ services: loaded.shared.server,
263
+ environment: loaded.project.environment,
264
+ io: loaded.bound,
265
+ });
266
+ if (!source.module) {
267
+ return { ...loaded, diagnostics: source.diagnostics };
268
+ }
269
+ const normalized = normalizeModule(source.module);
270
+ if (!normalized.core) {
271
+ return { ...loaded, diagnostics: normalized.diagnostics };
272
+ }
273
+
274
+ const tasks = taskPlan(config.tasks);
275
+ const planned = planCodesys(
276
+ normalized.core,
277
+ { tasks },
278
+ config.target.options,
279
+ loaded.project,
280
+ );
281
+ return {
282
+ ...loaded,
283
+ ...planned,
284
+ diagnostics: [
285
+ ...loaded.diagnostics,
286
+ ...source.diagnostics,
287
+ ...normalized.diagnostics,
288
+ ...planned.diagnostics,
289
+ ],
290
+ };
291
+ }
292
+
293
+ /** The installed libraries and fieldbus device tree a CODESYS project of this program needs. */
294
+ async function engineeringInputs(
295
+ shared: ResolvedTsplcConfig,
296
+ configFile: string,
297
+ bundle: Pick<ReturnType<typeof emitCodesys>, "ioMappings">,
298
+ options: { frozen?: boolean },
299
+ ) {
300
+ const root = dirname(configFile);
301
+ const tree = await deviceTree(shared, await loadHardware(shared, root));
302
+ return {
303
+ libraries: await installLibraries(shared.dependencies, root, options),
304
+ // The emitted names locate mapped IO; the tree maps their channels.
305
+ deviceTree: tree && {
306
+ ...tree,
307
+ mappings: bundle.ioMappings.map(({ address, variable }) => ({
308
+ address,
309
+ variable,
310
+ })),
311
+ },
312
+ };
313
+ }
314
+
315
+ const missingBuildSection =
316
+ '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.';
317
+
318
+ export async function buildTypeScriptProject(
319
+ file: string,
320
+ options: ProjectOptions & {
321
+ emitOnly?: boolean;
322
+ frozenLockfile?: boolean;
323
+ controller?: Controller;
324
+ /** Resolve libraries and the device tree into `controllerConfig` even when only emitting. */
325
+ forController?: boolean;
326
+ } & ProgressOptions,
327
+ ): Promise<{
328
+ directory?: string;
329
+ status?: "emitted" | "vendor-compiled";
330
+ controllerConfig?: ReturnType<typeof codesysBuildConfig>;
331
+ /** What `projectTargets` reads from the program, from this build's own analysis. */
332
+ targets?: ProjectTargets;
333
+ /** The route of each service procedure the program calls, as `serviceRoutes` reads them. */
334
+ services?: Readonly<Record<string, string>>;
335
+ diagnostics: readonly Diagnostic[];
336
+ }> {
337
+ let staging: string | undefined;
338
+ try {
339
+ const configFile = await realpath(resolve(file));
340
+ // Withdraw the previous success receipt before checking the new source.
341
+ // Old artifacts remain owned and intact until publication succeeds.
342
+ const claim = await claimed(configFile);
343
+ await withdrawReceipt(claim);
344
+ const previous = await owned(claim);
345
+ if (previous.unknown.length) {
346
+ throw new Error(
347
+ `Output contains unrelated files: ${previous.unknown.join(", ")}`,
348
+ );
349
+ }
350
+
351
+ const checked = await checkProject(configFile, options);
352
+ if (!checked.plan || !checked.config) {
353
+ return { diagnostics: checked.diagnostics };
354
+ }
355
+ const bundle = emitCodesys(checked.plan);
356
+ const shared = checked.shared;
357
+ const outDir =
358
+ shared?.build && resolve(dirname(configFile), shared.build.outDir);
359
+ if (!options.emitOnly && !outDir) {
360
+ return {
361
+ diagnostics: [
362
+ ...checked.diagnostics,
363
+ failure("config", "PLC5003", missingBuildSection),
364
+ ],
365
+ };
366
+ }
367
+ const engineering =
368
+ shared && (!options.emitOnly || options.forController)
369
+ ? await engineeringInputs(shared, configFile, bundle, {
370
+ frozen: options.frozenLockfile,
371
+ })
372
+ : undefined;
373
+ // The emitted ST already binds the program's I/O; bindings here would have the controller
374
+ // build bind it a second time.
375
+ const controllerConfig = outDir
376
+ ? {
377
+ ...codesysBuildConfig(checked.plan, bundle, {
378
+ configFile,
379
+ sourceDir: join(previous.output, emittedSt),
380
+ outDir,
381
+ controller: options.controller,
382
+ ...engineering,
383
+ }),
384
+ io: {},
385
+ }
386
+ : undefined;
387
+
388
+ await mkdir(previous.root, { recursive: true });
389
+ staging = await mkdtemp(join(previous.root, "stage-"));
390
+ const artifacts = [
391
+ ...bundle.artifacts,
392
+ {
393
+ path: "mappings.json",
394
+ content: `${JSON.stringify(compactMappings(bundle.mappings))}\n`,
395
+ },
396
+ {
397
+ path: emittedFiles.ioSymbols,
398
+ content: `${JSON.stringify(bundle.ioSymbols, null, 2)}\n`,
399
+ },
400
+ {
401
+ path: emittedFiles.publication,
402
+ content: `${JSON.stringify(bundle.publication, null, 2)}\n`,
403
+ },
404
+ {
405
+ path: "config.json",
406
+ content: `${JSON.stringify(checked.config, null, 2)}\n`,
407
+ },
408
+ {
409
+ path: debugManifestFile,
410
+ content: `${JSON.stringify(bundle.debug)}\n`,
411
+ },
412
+ // The manifest's digest covers these exact bytes.
413
+ { path: explainFileName, content: bundle.explain },
414
+ ];
415
+ const stagedSt = join(staging, emittedSt);
416
+ // Thousands of artifacts share a few hundred directories; each is made once.
417
+ const directories = new Set(
418
+ artifacts.map((artifact) => dirname(join(stagedSt, artifact.path))),
419
+ );
420
+ for (const directory of directories) {
421
+ await mkdir(directory, { recursive: true });
422
+ }
423
+ for (const artifact of artifacts) {
424
+ await writeFile(join(stagedSt, artifact.path), artifact.content);
425
+ }
426
+
427
+ const vendor =
428
+ options.emitOnly || !outDir
429
+ ? undefined
430
+ : await compileVendor(checked.plan, bundle, {
431
+ configFile,
432
+ staging,
433
+ // The engineering cache has its own ownership marker and survives clean.
434
+ engineeringDir: outDir,
435
+ controller: options.controller,
436
+ engineering,
437
+ progress: options.progress,
438
+ });
439
+ if (vendor && "diagnostics" in vendor) {
440
+ return vendor;
441
+ }
442
+
443
+ const status = vendor ? "vendor-compiled" : "emitted";
444
+ await publishArtifacts(staging, previous, {
445
+ configFile,
446
+ status,
447
+ ...(vendor && {
448
+ vendor: { application: vendor.application, tasks: vendor.tasks },
449
+ }),
450
+ });
451
+ // Publication moved this directory into place; it is no longer staging.
452
+ staging = undefined;
453
+ return {
454
+ directory: previous.output,
455
+ status,
456
+ ...(controllerConfig && { controllerConfig }),
457
+ targets: coreTargets(checked.plan.core),
458
+ services: serviceRoutes(checked.plan.core),
459
+ diagnostics: checked.diagnostics,
460
+ };
461
+ } catch (cause) {
462
+ return { diagnostics: [failure("config", "PLC5004", cause)] };
463
+ } finally {
464
+ if (staging) {
465
+ await rm(staging, { recursive: true, force: true });
466
+ }
467
+ }
468
+ }
469
+
470
+ /**
471
+ * Compiles the staged ST with CODESYS and copies the vendor's project, application and checksum
472
+ * into the staging tree's `vendor/`; the compiler's diagnostics when CODESYS refuses it.
473
+ */
474
+ async function compileVendor(
475
+ plan: CodesysPlan,
476
+ bundle: ReturnType<typeof emitCodesys>,
477
+ options: {
478
+ configFile: string;
479
+ staging: string;
480
+ engineeringDir: string;
481
+ controller: Controller | undefined;
482
+ engineering: Awaited<ReturnType<typeof engineeringInputs>> | undefined;
483
+ } & ProgressOptions,
484
+ ) {
485
+ await engineeringDirectory(options.engineeringDir, options.configFile);
486
+ const vendor = await buildCodesys(
487
+ plan,
488
+ bundle,
489
+ {
490
+ configFile: options.configFile,
491
+ sourceDir: join(options.staging, emittedSt),
492
+ outDir: options.engineeringDir,
493
+ controller: options.controller,
494
+ ...options.engineering,
495
+ },
496
+ { progress: options.progress },
497
+ ).catch((cause: unknown) => ({
498
+ diagnostics: diagnoseCodesys(cause, bundle),
499
+ }));
500
+ if ("diagnostics" in vendor) {
501
+ return vendor;
502
+ }
503
+ for (const artifact of ["project", "output", "checksum"] as const) {
504
+ const path = vendor[artifact];
505
+ if (!path) {
506
+ continue;
507
+ }
508
+ const destination = join(
509
+ options.staging,
510
+ "vendor",
511
+ basename(buildFiles[artifact]),
512
+ );
513
+ await mkdir(dirname(destination), { recursive: true });
514
+ await copyFile(path, destination);
515
+ }
516
+ return vendor;
517
+ }
518
+
519
+ /**
520
+ * Source mappings with each ST path and source file written once: `mappings` rows are
521
+ * `[object, line, file, start, end, sourceLine, sourceColumn]`, indexing `objects` and `files`.
522
+ */
523
+ function compactMappings(mappings: readonly SourceMapping[]) {
524
+ const objects = new Map<string, number>();
525
+ const files = new Map<string, number>();
526
+ const index = (table: Map<string, number>, value: string) => {
527
+ const known = table.get(value);
528
+ if (known !== undefined) {
529
+ return known;
530
+ }
531
+ table.set(value, table.size);
532
+ return table.size - 1;
533
+ };
534
+ const rows = mappings.map(({ path, line, span }) => [
535
+ index(objects, path),
536
+ line,
537
+ index(files, span.file),
538
+ span.start,
539
+ span.end,
540
+ span.line,
541
+ span.column,
542
+ ]);
543
+ return {
544
+ objects: [...objects.keys()],
545
+ files: [...files.keys()],
546
+ mappings: rows,
547
+ };
548
+ }
549
+
550
+ export async function cleanProject(file = configFileName): Promise<{
551
+ diagnostics: readonly Diagnostic[];
552
+ }> {
553
+ try {
554
+ await cleanArtifacts(await realpath(resolve(file)));
555
+ return { diagnostics: [] };
556
+ } catch (cause) {
557
+ return { diagnostics: [failure("config", "PLC5004", cause)] };
558
+ }
559
+ }
@@ -0,0 +1,152 @@
1
+ import { basename, relative, resolve, sep } from "node:path";
2
+ import { pathToFileURL } from "node:url";
3
+ import type { ReleaseManifest } from "@tsplc/agent";
4
+ import type { ReleaseFile } from "@tsplc/agent/client";
5
+ import { checkHostConfig } from "@tsplc/compiler";
6
+ import { hasErrors } from "@tsplc/compiler/ir";
7
+ import {
8
+ buildTargetFor,
9
+ controllerFor,
10
+ type Environment,
11
+ type LoadedConfig,
12
+ serverTokenEnv,
13
+ } from "@tsplc/config";
14
+ import type { ReleaseConfig } from "@tsplc/config/build";
15
+ import { explainFileName } from "@tsplc/debug/explain-file";
16
+ import { debugManifestFile } from "@tsplc/debug/manifest";
17
+ import { contractVariables, plcContractSchema } from "@tsplc/opcua/contract";
18
+ import { generateProject } from "@tsplc/typegen";
19
+ import { buildConfigs, buildTypeScriptProject } from "./project";
20
+ import { bundleServer, startServerCheck } from "./server";
21
+
22
+ /** Every published leaf the generated contract at `file` describes, as CODESYS expressions name it. */
23
+ const releaseVariables = async (file: string | null) => {
24
+ if (file === null) {
25
+ return [];
26
+ }
27
+ const contract = plcContractSchema.parse(
28
+ await import(pathToFileURL(file).href),
29
+ );
30
+ return contractVariables(contract).map(({ path, type }) => ({ path, type }));
31
+ };
32
+
33
+ /**
34
+ * Compiles the program and bundles its server into the files `tsplc deploy` uploads: the
35
+ * production program, or with `--simulate` the development one without fieldbus I/O, for a
36
+ * virtual PLC whose inputs a plant simulation writes, as `tsplc run --simulate` builds it.
37
+ */
38
+ export const prepareRelease = async (
39
+ loaded: LoadedConfig,
40
+ flags: { simulate?: boolean; "frozen-lockfile"?: boolean },
41
+ built: {
42
+ /** What the build reads, with the plant PC's values and placeholders for its secrets. */
43
+ env: Environment;
44
+ /** Every plain value the release carries to its server. */
45
+ values: ReleaseManifest["values"];
46
+ /** The secrets the agent fills in. */
47
+ secrets: ReleaseManifest["secrets"];
48
+ },
49
+ ) => {
50
+ // Every step reads the loaded config's environment, so it carries the plant PC's.
51
+ const project: LoadedConfig = { ...loaded, env: built.env };
52
+ const { config, root } = project;
53
+ if (!config.compiler) {
54
+ throw new Error("tsplc deploy deploys tsPLC programs; configure compiler.");
55
+ }
56
+ const command = flags.simulate ? "run" : "deploy";
57
+ const serverCheck = config.server?.runtime
58
+ ? startServerCheck(config, root)
59
+ : undefined;
60
+ const emitted = await buildTypeScriptProject(project.configFile, {
61
+ emitOnly: true,
62
+ forController: true,
63
+ frozenLockfile: flags["frozen-lockfile"],
64
+ ...buildConfigs(project, flags),
65
+ hostConfigDiagnostics: checkHostConfig(project.configFile),
66
+ buildTarget: buildTargetFor(command),
67
+ controller: controllerFor(config, command),
68
+ });
69
+ if (hasErrors(emitted.diagnostics)) {
70
+ return { diagnostics: emitted.diagnostics };
71
+ }
72
+ const settings = emitted.controllerConfig;
73
+ if (!settings) {
74
+ throw new Error("Configure build settings for deployment.");
75
+ }
76
+ const { contract } = await generateProject(project, {
77
+ targets: emitted.targets,
78
+ });
79
+
80
+ const portable = (path: string) => path.split(sep).join("/");
81
+ const libraries = (settings.libraries ?? []).map((library) => ({
82
+ ...library,
83
+ release: `libraries/${library.sha256}-${basename(library.path)}`,
84
+ }));
85
+ const files: ReleaseFile[] = [
86
+ { path: "template.project", content: Bun.file(settings.template) },
87
+ ...libraries.map((library) => ({
88
+ path: library.release,
89
+ content: Bun.file(library.path),
90
+ })),
91
+ ];
92
+ // The agent compiles only the ST. Plain TypeScript programs emit their generated modules under `.tsplc/`.
93
+ for await (const source of new Bun.Glob("**/*.st").scan({
94
+ cwd: settings.sourceDir,
95
+ dot: true,
96
+ })) {
97
+ files.push({
98
+ path: `st/${portable(source)}`,
99
+ content: Bun.file(resolve(settings.sourceDir, source)),
100
+ });
101
+ }
102
+ // The agent's debugger reads the program through its debug manifest, and explains it with `explain.json`.
103
+ for (const name of [debugManifestFile, explainFileName]) {
104
+ files.push({
105
+ path: name,
106
+ content: Bun.file(resolve(settings.sourceDir, name)),
107
+ });
108
+ }
109
+ const serverScript =
110
+ serverCheck && (await bundleServer(await serverCheck, config, root));
111
+ const server = serverScript
112
+ ? {
113
+ path: `server/${basename(serverScript)}`,
114
+ content: Bun.file(serverScript),
115
+ }
116
+ : undefined;
117
+ if (server) {
118
+ files.push(server);
119
+ }
120
+ // Paths are relative to the release. Naming every release field keeps a new build setting
121
+ // from reaching the agent, or being left behind, without a decision here.
122
+ const releaseConfig: {
123
+ [Key in keyof Required<ReleaseConfig>]: ReleaseConfig[Key];
124
+ } = {
125
+ io: settings.io,
126
+ deviceTree: settings.deviceTree,
127
+ controller: settings.controller,
128
+ libraryReferences: settings.libraryReferences,
129
+ libraries: libraries.map(({ release, ...library }) => ({
130
+ ...library,
131
+ path: release,
132
+ })),
133
+ task: settings.task,
134
+ tasks: settings.tasks,
135
+ removeObjects: settings.removeObjects,
136
+ symbols: settings.symbols,
137
+ timeouts: settings.timeouts,
138
+ template: "template.project",
139
+ sourceDir: "st",
140
+ entry: `st/${portable(relative(settings.sourceDir, settings.entry))}`,
141
+ };
142
+ const manifest: ReleaseManifest = {
143
+ config: releaseConfig,
144
+ variables: await releaseVariables(contract),
145
+ server: server?.path,
146
+ debug: config.debug,
147
+ serverTokenEnv: serverTokenEnv(config),
148
+ secrets: built.secrets,
149
+ values: built.values,
150
+ };
151
+ return { release: { manifest, files } };
152
+ };