@tsplc/compiler 0.2.17 → 0.2.19

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 (157) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +920 -943
  3. package/dist/cli.js.map +13 -10
  4. package/dist/codesys.js +3893 -3352
  5. package/dist/codesys.js.map +29 -20
  6. package/dist/elaborate-capture.js +33 -17
  7. package/dist/elaborate-capture.js.map +3 -3
  8. package/dist/index.js +8787 -6855
  9. package/dist/index.js.map +40 -20
  10. package/dist/ir.js +1575 -1072
  11. package/dist/ir.js.map +21 -17
  12. package/dist/math.js.map +2 -2
  13. package/dist/project.js +154 -60
  14. package/dist/project.js.map +5 -5
  15. package/dist/telemetry.js +27 -9
  16. package/dist/telemetry.js.map +5 -5
  17. package/package.json +112 -112
  18. package/src/codesys/config.ts +50 -0
  19. package/src/codesys/debug.ts +670 -0
  20. package/src/codesys/emit.ts +142 -0
  21. package/src/codesys/engineering.ts +109 -0
  22. package/src/codesys/expressions.ts +92 -0
  23. package/src/codesys/global-lists.ts +250 -0
  24. package/src/codesys/global-names.ts +68 -0
  25. package/src/codesys/http.ts +890 -0
  26. package/src/codesys/index.ts +30 -0
  27. package/src/codesys/instrumentation.ts +430 -0
  28. package/src/codesys/io-paths.ts +140 -0
  29. package/src/codesys/manifest.ts +643 -0
  30. package/src/codesys/names.ts +81 -0
  31. package/src/codesys/numeric.ts +409 -0
  32. package/src/codesys/operands.ts +62 -0
  33. package/src/codesys/plan.ts +605 -0
  34. package/src/codesys/programs.ts +53 -0
  35. package/src/codesys/publication.ts +171 -0
  36. package/src/codesys/routines.ts +603 -0
  37. package/src/codesys/sources.ts +71 -0
  38. package/src/codesys/st-files.ts +115 -0
  39. package/src/codesys/storage.ts +97 -0
  40. package/src/codesys/symbols.ts +220 -0
  41. package/src/codesys/task-access.ts +320 -0
  42. package/src/codesys/telemetry.ts +732 -0
  43. package/src/codesys/types.ts +250 -0
  44. package/src/codesys/vendor.ts +150 -0
  45. package/src/frontend/analyzer.ts +794 -0
  46. package/src/frontend/async.ts +317 -1137
  47. package/src/frontend/blocks.ts +537 -403
  48. package/src/frontend/configuration.ts +176 -144
  49. package/src/frontend/const-functions.ts +183 -148
  50. package/src/frontend/cooperative.ts +73 -43
  51. package/src/frontend/coroutines.ts +1032 -0
  52. package/src/frontend/elaborate/calls.ts +535 -0
  53. package/src/frontend/elaborate/capture.ts +157 -101
  54. package/src/frontend/elaborate/dialect.ts +257 -0
  55. package/src/frontend/elaborate/expressions.ts +992 -0
  56. package/src/frontend/elaborate/frame.ts +53 -0
  57. package/src/frontend/elaborate/graph.ts +116 -71
  58. package/src/frontend/elaborate/imports.ts +70 -0
  59. package/src/frontend/elaborate/index.ts +435 -331
  60. package/src/frontend/elaborate/initializers.ts +198 -0
  61. package/src/frontend/elaborate/layouts.ts +591 -384
  62. package/src/frontend/elaborate/model.ts +264 -169
  63. package/src/frontend/elaborate/specialize.ts +343 -2586
  64. package/src/frontend/elaborate/statements.ts +606 -0
  65. package/src/frontend/elaborate/storage.ts +546 -0
  66. package/src/frontend/elaborate/values.ts +58 -0
  67. package/src/frontend/elaborate/writes.ts +100 -0
  68. package/src/frontend/exposure.ts +172 -140
  69. package/src/frontend/expressions.ts +1383 -0
  70. package/src/frontend/intrinsics.ts +337 -0
  71. package/src/frontend/module-graph.ts +89 -59
  72. package/src/frontend/positions.ts +271 -200
  73. package/src/frontend/promise-chains.ts +897 -0
  74. package/src/frontend/promises.ts +390 -747
  75. package/src/frontend/routines.ts +181 -0
  76. package/src/frontend/sdk.ts +82 -0
  77. package/src/frontend/services.ts +506 -372
  78. package/src/frontend/statements.ts +855 -0
  79. package/src/frontend/tasks.ts +471 -0
  80. package/src/frontend/telemetry.ts +174 -0
  81. package/src/frontend/types.ts +845 -551
  82. package/src/frontend/typescript.ts +323 -2543
  83. package/src/index.ts +5 -5
  84. package/src/ir/aggregates.ts +275 -0
  85. package/src/ir/allocation.ts +84 -0
  86. package/src/ir/core-model.ts +146 -0
  87. package/src/ir/declarations.ts +295 -0
  88. package/src/ir/diagnostics.ts +61 -0
  89. package/src/ir/domains.ts +152 -0
  90. package/src/ir/fold.ts +342 -0
  91. package/src/ir/index.ts +90 -0
  92. package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
  93. package/src/ir/layouts.ts +181 -0
  94. package/src/ir/link.ts +354 -0
  95. package/src/ir/model.ts +386 -0
  96. package/{ir → src/ir}/normalization-error.ts +4 -4
  97. package/src/ir/normalize.ts +70 -0
  98. package/src/ir/numeric.ts +171 -0
  99. package/src/ir/ranges.ts +256 -0
  100. package/src/ir/routine.ts +1163 -0
  101. package/src/ir/scalars.ts +321 -0
  102. package/src/ir/types.ts +127 -0
  103. package/src/project/artifacts.ts +342 -0
  104. package/src/project/cli.ts +177 -0
  105. package/src/project/debugger.ts +82 -0
  106. package/src/project/index.ts +6 -0
  107. package/src/project/plant.ts +467 -0
  108. package/src/project/project-commands.ts +372 -0
  109. package/src/project/project.ts +457 -0
  110. package/src/project/release.ts +153 -0
  111. package/src/project/server.ts +150 -0
  112. package/src/project/terminal.ts +32 -0
  113. package/stdlib/math.ts +14 -10
  114. package/stdlib/telemetry.ts +71 -47
  115. package/types/async.d.ts +46 -40
  116. package/types/data-types.d.ts +26 -26
  117. package/types/globals.d.ts +41 -38
  118. package/types/index.d.ts +96 -51
  119. package/types/plc.d.ts +3 -4
  120. package/types/telemetry.d.ts +14 -14
  121. package/backends/codesys/config.ts +0 -54
  122. package/backends/codesys/debug.ts +0 -509
  123. package/backends/codesys/emit.ts +0 -1738
  124. package/backends/codesys/engineering.ts +0 -88
  125. package/backends/codesys/global-names.ts +0 -49
  126. package/backends/codesys/http.ts +0 -675
  127. package/backends/codesys/index.ts +0 -13
  128. package/backends/codesys/io-paths.ts +0 -105
  129. package/backends/codesys/manifest.ts +0 -312
  130. package/backends/codesys/names.ts +0 -76
  131. package/backends/codesys/numeric.ts +0 -356
  132. package/backends/codesys/plan.ts +0 -457
  133. package/backends/codesys/publication.ts +0 -59
  134. package/backends/codesys/storage.ts +0 -70
  135. package/backends/codesys/task-access.ts +0 -293
  136. package/backends/codesys/telemetry.ts +0 -593
  137. package/backends/codesys/types.ts +0 -179
  138. package/backends/codesys/vendor.ts +0 -108
  139. package/ir/aggregates.ts +0 -333
  140. package/ir/allocation.ts +0 -74
  141. package/ir/core-model.ts +0 -129
  142. package/ir/core.ts +0 -64
  143. package/ir/declarations.ts +0 -208
  144. package/ir/diagnostics.ts +0 -43
  145. package/ir/domains.ts +0 -96
  146. package/ir/index.ts +0 -8
  147. package/ir/link.ts +0 -185
  148. package/ir/model.ts +0 -346
  149. package/ir/routine.ts +0 -859
  150. package/ir/scalars.ts +0 -675
  151. package/ir/types.ts +0 -76
  152. package/project/artifacts.ts +0 -277
  153. package/project/cli.ts +0 -395
  154. package/project/index.ts +0 -1
  155. package/project/plant.ts +0 -509
  156. package/project/project.ts +0 -358
  157. package/project/server.ts +0 -113
@@ -1,358 +0,0 @@
1
- import { copyFile, mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
2
- import { dirname, join, resolve } from "node:path";
3
- import {
4
- buildCodesys,
5
- codesysBuildConfig,
6
- type CodesysPlan,
7
- type CodesysProject,
8
- type SourceMapping,
9
- diagnoseCodesys,
10
- emitCodesys,
11
- ioTargets,
12
- publicationSelectors,
13
- planCodesys,
14
- } from "@tsplc/compiler/codesys";
15
- import { analyze, checkHostConfig } from "@tsplc/compiler";
16
- import {
17
- type Controller,
18
- type BuildTarget,
19
- type NormalizedConfig,
20
- type ResolvedTsplcConfig,
21
- compilerConfig,
22
- loadTsplcConfig,
23
- } from "@tsplc/config";
24
- import { deviceTree, type ProjectTargets, loadHardware, resolveIo } from "@tsplc/typegen";
25
- import { installLibraries } from "@tsplc/build";
26
- import { type Diagnostic, hasErrors, normalizeModule } from "@tsplc/compiler/ir";
27
- import { cleanArtifacts, engineeringDirectory, owned, publishArtifacts } from "./artifacts.ts";
28
-
29
- const failure = (origin: Diagnostic["origin"], code: string, cause: unknown): Diagnostic => ({
30
- origin,
31
- code,
32
- severity: "error",
33
- message: cause instanceof Error ? cause.message : String(cause),
34
- });
35
-
36
- type LoadedConfig = Awaited<ReturnType<typeof loadTsplcConfig>>;
37
-
38
- async function loadProject(
39
- file: string,
40
- loaded?: LoadedConfig,
41
- buildTarget?: BuildTarget,
42
- configured?: ResolvedTsplcConfig,
43
- ): Promise<{
44
- config?: NormalizedConfig;
45
- configFile: string;
46
- shared?: ResolvedTsplcConfig;
47
- project?: CodesysProject;
48
- diagnostics: readonly Diagnostic[];
49
- }> {
50
- let configFile = resolve(file);
51
- try {
52
- configFile = await realpath(configFile);
53
- const diagnostics = checkHostConfig(configFile);
54
- if (hasErrors(diagnostics)) return { configFile, diagnostics };
55
- const shared = (loaded ?? (await loadTsplcConfig(configFile))).config;
56
- const root = dirname(configFile);
57
- const catalog = await loadHardware(shared, root);
58
-
59
- const config = compilerConfig(shared, resolveIo(shared, catalog), buildTarget);
60
- return {
61
- configFile,
62
- shared,
63
- config: { ...config, ...sourceInput(config, root) },
64
- project: {
65
- root,
66
- ...(shared.debug && { debug: shared.debug }),
67
- ...(shared.telemetry && { telemetry: shared.telemetry }),
68
- ...(shared.server && { server: shared.server }),
69
- // A simulation build drops fieldbus IO, but the debugger still shows the hardware it stands in for.
70
- hardware: {
71
- catalog: configured ? await loadHardware(configured, root) : catalog,
72
- config: configured ?? shared,
73
- tree: shared.codesys?.deviceTree !== undefined,
74
- },
75
- },
76
- diagnostics,
77
- };
78
- } catch (cause) {
79
- return { configFile, diagnostics: [failure("config", "PLC5003", cause)] };
80
- }
81
- }
82
-
83
- /** The analyzer's entry points, resolved against the config file's directory. */
84
- function sourceInput(
85
- compiler: { tsconfig: string; programs: Record<string, { module: string; export: string }> },
86
- root: string,
87
- ) {
88
- return {
89
- tsconfig: resolve(root, compiler.tsconfig),
90
- programs: Object.fromEntries(
91
- Object.entries(compiler.programs).map(([name, entry]) => [
92
- name,
93
- { ...entry, module: resolve(root, entry.module) },
94
- ]),
95
- ),
96
- };
97
- }
98
-
99
- /**
100
- * I/O keys and publication selectors from analyzed PLC source. It ignores the
101
- * config's own type errors, so a typo cannot switch off the types that flag it;
102
- * it is undefined only while the source itself fails analysis.
103
- */
104
- export async function projectTargets(
105
- file = "tsplc.config.ts",
106
- options: { loaded?: LoadedConfig } = {},
107
- ): Promise<ProjectTargets | undefined> {
108
- const configFile = await realpath(resolve(file));
109
- const { config } = options.loaded ?? (await loadTsplcConfig(configFile));
110
- if (!config.compiler) return undefined;
111
- const source = analyze({
112
- ...sourceInput(config.compiler, dirname(configFile)),
113
- services: config.server,
114
- });
115
- const core = source.module && normalizeModule(source.module).core;
116
- return core ? { io: ioTargets(core), publication: publicationSelectors(core) } : undefined;
117
- }
118
-
119
- export async function checkProject(
120
- file = "tsplc.config.ts",
121
- options: {
122
- loaded?: LoadedConfig;
123
- buildTarget?: BuildTarget;
124
- /** The configuration `loaded` simulates, whose hardware the debug manifest describes. */
125
- configured?: ResolvedTsplcConfig;
126
- } = {},
127
- ): Promise<{
128
- configFile: string;
129
- config?: NormalizedConfig;
130
- shared?: ResolvedTsplcConfig;
131
- plan?: CodesysPlan;
132
- diagnostics: readonly Diagnostic[];
133
- }> {
134
- const loaded = await loadProject(file, options.loaded, options.buildTarget, options.configured);
135
- if (!loaded.config || !loaded.project) {
136
- return loaded;
137
- }
138
-
139
- const config = loaded.config;
140
- if (config.target.kind !== "codesys") {
141
- return {
142
- ...loaded,
143
- diagnostics: [failure("backend", "PLC7001", `Unsupported target: ${config.target.kind}`)],
144
- };
145
- }
146
-
147
- const source = analyze({
148
- tsconfig: config.tsconfig,
149
- programs: config.programs,
150
- services: loaded.shared?.server,
151
- });
152
- if (!source.module) {
153
- return { ...loaded, diagnostics: source.diagnostics };
154
- }
155
- const normalized = normalizeModule(source.module);
156
- if (!normalized.core) {
157
- return { ...loaded, diagnostics: normalized.diagnostics };
158
- }
159
-
160
- const tasks = config.tasks.map((task) => ({
161
- name: task.name,
162
- intervalNanoseconds: task.schedule.interval.nanoseconds,
163
- priority: task.priority,
164
- programs: task.programs,
165
- }));
166
- const planned = planCodesys(normalized.core, { tasks }, config.target.options, loaded.project);
167
- return {
168
- ...loaded,
169
- ...planned,
170
- diagnostics: [
171
- ...loaded.diagnostics,
172
- ...source.diagnostics,
173
- ...normalized.diagnostics,
174
- ...planned.diagnostics,
175
- ],
176
- };
177
- }
178
-
179
- /** The installed libraries and fieldbus device tree a CODESYS project of this program needs. */
180
- async function engineeringInputs(
181
- shared: ResolvedTsplcConfig,
182
- configFile: string,
183
- bundle: Pick<ReturnType<typeof emitCodesys>, "ioMappings">,
184
- frozen?: boolean,
185
- ) {
186
- const root = dirname(configFile);
187
- const tree = await deviceTree(shared, await loadHardware(shared, root));
188
- return {
189
- libraries: await installLibraries(shared.dependencies, root, { frozen }),
190
- // The emitted names locate mapped IO; the tree maps their channels.
191
- deviceTree: tree && {
192
- ...tree,
193
- mappings: bundle.ioMappings.map(({ address, variable }) => ({ address, variable })),
194
- },
195
- };
196
- }
197
-
198
- export async function buildProject(
199
- file = "tsplc.config.ts",
200
- options: {
201
- emitOnly?: boolean;
202
- frozenLockfile?: boolean;
203
- loaded?: LoadedConfig;
204
- controller?: Controller;
205
- buildTarget?: BuildTarget;
206
- configured?: ResolvedTsplcConfig;
207
- /** Resolve libraries and the device tree into `controllerConfig` even when only emitting. */
208
- forController?: boolean;
209
- } = {},
210
- ): Promise<{
211
- directory?: string;
212
- status?: "emitted" | "vendor-compiled";
213
- controllerConfig?: ReturnType<typeof codesysBuildConfig>;
214
- diagnostics: readonly Diagnostic[];
215
- }> {
216
- let staging: string | undefined;
217
- try {
218
- const configFile = await realpath(resolve(file));
219
- // Withdraw the previous success receipt before checking the new source.
220
- // Old artifacts remain owned and intact until publication succeeds.
221
- const previous = await owned(configFile, true);
222
- if (previous.unknown.length) {
223
- throw new Error(`Output contains unrelated files: ${previous.unknown.join(", ")}`);
224
- }
225
-
226
- const checked = await checkProject(configFile, {
227
- loaded: options.loaded,
228
- buildTarget: options.buildTarget,
229
- configured: options.configured,
230
- });
231
- if (!checked.plan || !checked.config) {
232
- return { diagnostics: checked.diagnostics };
233
- }
234
- const bundle = emitCodesys(checked.plan);
235
- if (hasErrors(bundle.diagnostics)) {
236
- return { diagnostics: bundle.diagnostics };
237
- }
238
- const shared = checked.shared;
239
- const engineering =
240
- shared && (!options.emitOnly || options.forController)
241
- ? await engineeringInputs(shared, configFile, bundle, options.frozenLockfile)
242
- : undefined;
243
- const controllerConfig = shared?.build
244
- ? codesysBuildConfig(checked.plan, bundle, {
245
- configFile,
246
- sourceDir: join(previous.output, "st"),
247
- outDir: resolve(dirname(configFile), shared.build.outDir),
248
- controller: options.controller,
249
- ...engineering,
250
- })
251
- : undefined;
252
-
253
- await mkdir(previous.root, { recursive: true });
254
- staging = await mkdtemp(join(previous.root, "stage-"));
255
- const artifacts = [
256
- ...bundle.artifacts,
257
- { path: "mappings.json", content: `${JSON.stringify(compactMappings(bundle.mappings))}\n` },
258
- { path: "io-symbols.json", content: `${JSON.stringify(bundle.ioSymbols, null, 2)}\n` },
259
- { path: "publication.json", content: `${JSON.stringify(bundle.publication, null, 2)}\n` },
260
- { path: "config.json", content: `${JSON.stringify(checked.config, null, 2)}\n` },
261
- ...(bundle.debug
262
- ? [{ path: "debug.json", content: `${JSON.stringify(bundle.debug)}\n` }]
263
- : []),
264
- ];
265
- for (const artifact of artifacts) {
266
- const path = join(staging, "st", artifact.path);
267
- await mkdir(dirname(path), { recursive: true });
268
- await writeFile(path, artifact.content);
269
- }
270
-
271
- let vendor: Awaited<ReturnType<typeof buildCodesys>> | undefined;
272
- if (!options.emitOnly) {
273
- // The engineering cache has its own ownership marker and survives clean.
274
- const outDir = shared?.build
275
- ? resolve(dirname(configFile), shared.build.outDir ?? "build")
276
- : join(previous.root, "engineering");
277
- await engineeringDirectory(outDir, configFile);
278
- try {
279
- vendor = await buildCodesys(checked.plan, bundle, {
280
- configFile,
281
- sourceDir: join(staging, "st"),
282
- outDir,
283
- controller: options.controller,
284
- ...engineering,
285
- });
286
- } catch (cause) {
287
- return { diagnostics: diagnoseCodesys(cause, bundle) };
288
- }
289
-
290
- const vendorArtifacts = [
291
- ["Application.project", vendor.project],
292
- ["Application.app", vendor.output],
293
- ["Application.crc", vendor.checksum],
294
- ] as const;
295
- for (const [name, path] of vendorArtifacts) {
296
- if (!path) continue;
297
- const destination = join(staging, "vendor", name);
298
- await mkdir(dirname(destination), { recursive: true });
299
- await copyFile(path, destination);
300
- }
301
- }
302
-
303
- const status = vendor ? "vendor-compiled" : "emitted";
304
- await publishArtifacts(staging, previous, {
305
- configFile,
306
- status,
307
- ...(vendor && { vendor: { application: vendor.application, tasks: vendor.tasks } }),
308
- });
309
- // Publication moved this directory into place; it is no longer staging.
310
- staging = undefined;
311
- return {
312
- directory: previous.output,
313
- status,
314
- ...(controllerConfig && { controllerConfig }),
315
- diagnostics: [...checked.diagnostics, ...bundle.diagnostics],
316
- };
317
- } catch (cause) {
318
- return { diagnostics: [failure("config", "PLC5004", cause)] };
319
- } finally {
320
- if (staging) {
321
- await rm(staging, { recursive: true, force: true });
322
- }
323
- }
324
- }
325
-
326
- /**
327
- * Source mappings with each ST path and source file written once: `mappings` rows are
328
- * `[object, line, file, start, end, sourceLine, sourceColumn]`, indexing `objects` and `files`.
329
- */
330
- function compactMappings(mappings: readonly SourceMapping[]) {
331
- const objects = new Map<string, number>(),
332
- files = new Map<string, number>();
333
- const index = (table: Map<string, number>, value: string) => {
334
- if (!table.has(value)) table.set(value, table.size);
335
- return table.get(value)!;
336
- };
337
- const rows = mappings.map(({ path, line, span }) => [
338
- index(objects, path),
339
- line,
340
- index(files, span.file),
341
- span.start,
342
- span.end,
343
- span.line,
344
- span.column,
345
- ]);
346
- return { objects: [...objects.keys()], files: [...files.keys()], mappings: rows };
347
- }
348
-
349
- export async function cleanProject(file = "tsplc.config.ts"): Promise<{
350
- diagnostics: readonly Diagnostic[];
351
- }> {
352
- try {
353
- await cleanArtifacts(await realpath(resolve(file)));
354
- return { diagnostics: [] };
355
- } catch (cause) {
356
- return { diagnostics: [failure("config", "PLC5004", cause)] };
357
- }
358
- }
package/project/server.ts DELETED
@@ -1,113 +0,0 @@
1
- import { existsSync } from "node:fs";
2
- import { mkdtemp, mkdir, rm, rename } from "node:fs/promises";
3
- import { dirname, resolve, join } from "node:path";
4
- import { createRequire } from "node:module";
5
- import ts from "typescript";
6
- import type { ResolvedTsplcConfig } from "@tsplc/config";
7
- import { typeCheckOnly } from "@tsplc/compiler";
8
-
9
- export const resolveServerModule = (root: string, name: string) =>
10
- name.startsWith(".") || name.startsWith("/") || existsSync(resolve(root, name))
11
- ? resolve(root, name)
12
- : createRequire(join(root, "package.json")).resolve(name);
13
-
14
- const kebabCase = (name: string) =>
15
- name
16
- .replace(/([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])/g, "$1$3-$2$4")
17
- .replace(/[^A-Za-z0-9]+/g, "-")
18
- .replace(/^-|-$/g, "")
19
- .toLowerCase();
20
-
21
- /** The host entry, type-checked as it will be built. */
22
- const checkedServerEntry = (config: ResolvedTsplcConfig, root: string) => {
23
- const runtime = config.server?.runtime;
24
- if (!runtime) throw new Error("Configure server.runtime to build the server.");
25
- const entry = resolveServerModule(root, runtime.entry);
26
- const tsconfig = ts.findConfigFile(dirname(entry), ts.sys.fileExists);
27
- if (!tsconfig) throw new Error("Server entry requires a tsconfig.json.");
28
- const read = ts.readConfigFile(tsconfig, ts.sys.readFile);
29
- if (read.error) throw new Error(ts.flattenDiagnosticMessageText(read.error.messageText, "\n"));
30
- const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(tsconfig));
31
- const program = ts.createProgram({
32
- rootNames: [entry, ...parsed.fileNames.filter((file) => /\.d\.[cm]?ts$/.test(file))],
33
- options: { ...parsed.options, ...typeCheckOnly },
34
- projectReferences: parsed.projectReferences,
35
- });
36
- const diagnostics = [...parsed.errors, ...ts.getPreEmitDiagnostics(program)];
37
- if (diagnostics.length)
38
- throw new Error(
39
- ts.formatDiagnosticsWithColorAndContext(diagnostics, {
40
- getCanonicalFileName: (path) => path,
41
- getCurrentDirectory: () => root,
42
- getNewLine: () => "\n",
43
- }),
44
- );
45
- return { entry, runtime };
46
- };
47
-
48
- /**
49
- * Bundles the host entry, which starts its own listener, into one minified script,
50
- * `build/server/<name>-services.js`, which the plant agent runs on its own Bun. It is a few MB
51
- * where an executable, which embeds Bun, is over 100, and deployments upload it.
52
- */
53
- export const bundleServer = async (config: ResolvedTsplcConfig, root: string) => {
54
- const { entry } = checkedServerEntry(config, root);
55
- const outFile = resolve(root, "build/server", `${kebabCase(config.name)}-services.js`);
56
- const result = await Bun.build({
57
- entrypoints: [entry],
58
- target: "bun",
59
- minify: true,
60
- env: "disable",
61
- });
62
- if (!result.success) throw new AggregateError(result.logs, "Server bundle build failed.");
63
- const [script, ...assets] = result.outputs;
64
- if (!script || assets.length)
65
- throw new Error(
66
- `The server bundle needs files beside its script (${assets.map(({ path }) => path).join(", ")}), which deployments don't carry.`,
67
- );
68
- await mkdir(dirname(outFile), { recursive: true });
69
- await Bun.write(outFile, script);
70
- return outFile;
71
- };
72
-
73
- /** Compiles the host entry, which starts its own listener, into `build/server/<name>-services`. */
74
- export const buildServer = async (config: ResolvedTsplcConfig, root: string) => {
75
- const { entry, runtime } = checkedServerEntry(config, root);
76
- const windows = runtime.target
77
- ? runtime.target.includes("windows")
78
- : process.platform === "win32";
79
- const outFile = resolve(
80
- root,
81
- "build/server",
82
- `${kebabCase(config.name)}-services${windows ? ".exe" : ""}`,
83
- );
84
- await mkdir(dirname(outFile), { recursive: true });
85
- // Compile beside the output so dependency resolution starts from the owning project.
86
- const staging = await mkdtemp(join(dirname(outFile), ".tsplc-server-"));
87
- try {
88
- const binary = join(staging, "server");
89
- const result = await Bun.build({
90
- entrypoints: [entry],
91
- env: "disable",
92
- compile: {
93
- outfile: binary,
94
- ...(runtime.target ? { target: runtime.target } : {}),
95
- autoloadDotenv: false,
96
- autoloadBunfig: false,
97
- autoloadTsconfig: false,
98
- autoloadPackageJson: false,
99
- },
100
- });
101
- if (!result.success) throw new AggregateError(result.logs, "Server executable build failed.");
102
- // Bun names a Windows executable itself.
103
- await rename(windows ? `${binary}.exe` : binary, outFile);
104
- return {
105
- server: {
106
- executable: outFile,
107
- target: runtime.target ?? `bun-${process.platform}-${process.arch}`,
108
- },
109
- };
110
- } finally {
111
- await rm(staging, { recursive: true, force: true });
112
- }
113
- };