@tsplc/compiler 0.2.17 → 0.2.18

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
package/project/plant.ts DELETED
@@ -1,509 +0,0 @@
1
- import { existsSync } from "node:fs";
2
- import { basename, relative, resolve, sep } from "node:path";
3
- import { createInterface } from "node:readline/promises";
4
- import { pathToFileURL } from "node:url";
5
- import {
6
- AgentOperationError,
7
- type AgentClient,
8
- createAgentClient,
9
- type ReleaseFile,
10
- } from "@tsplc/agent/client";
11
- import type { Credentials, ReleaseManifest, Target, Variable } from "@tsplc/agent";
12
- import type { LoginCommand, LoginResult } from "@tsplc/build";
13
- import { controllerFor, simulationConfig, type loadTsplcConfig } from "@tsplc/config";
14
- import { LoginUnavailable, noLogin } from "@tsplc/debug";
15
- import { hasErrors } from "@tsplc/compiler/ir";
16
- import { generateProject } from "@tsplc/typegen";
17
- import { z } from "zod";
18
- import { buildProject, projectTargets } from "./project.ts";
19
- import { bundleServer } from "./server.ts";
20
-
21
- export const plantCommands = new Set([
22
- "deploy",
23
- "target",
24
- "status",
25
- "login",
26
- "logout",
27
- "vars",
28
- "read",
29
- "write",
30
- "force",
31
- "unforce",
32
- "start",
33
- "stop",
34
- "reset",
35
- ]);
36
-
37
- export interface PlantFlags {
38
- download?: boolean;
39
- "initialize-user"?: boolean;
40
- restore?: boolean;
41
- select?: boolean;
42
- simulate?: boolean;
43
- yes?: boolean;
44
- "frozen-lockfile"?: boolean;
45
- }
46
-
47
- type LoadedConfig = Awaited<ReturnType<typeof loadTsplcConfig>>;
48
-
49
- const ask = async (question: string) => {
50
- const lines = createInterface({ input: process.stdin, output: process.stdout });
51
- try {
52
- return (await lines.question(question)).trim();
53
- } finally {
54
- lines.close();
55
- }
56
- };
57
-
58
- /** Reads a line without echoing it. */
59
- const askSecret = (question: string) =>
60
- new Promise<string>((accept, reject) => {
61
- if (!process.stdin.isTTY) {
62
- reject(new Error("The controller password needs an interactive terminal."));
63
- return;
64
- }
65
- // Echo goes off before the prompt appears, so nothing typed at it can show.
66
- process.stdin.setRawMode(true);
67
- process.stdin.setEncoding("utf8");
68
- process.stdin.resume();
69
- process.stdout.write(question);
70
- let secret = "";
71
- const finish = () => {
72
- process.stdin.off("data", read);
73
- process.stdin.setRawMode(false);
74
- process.stdin.pause();
75
- process.stdout.write("\n");
76
- };
77
- const read = (text: string) => {
78
- for (const character of text) {
79
- if (character === "\r" || character === "\n") {
80
- finish();
81
- accept(secret);
82
- return;
83
- }
84
- if (character === "\u0003") {
85
- finish();
86
- reject(new Error("Cancelled."));
87
- return;
88
- }
89
- secret = character === "\u007f" ? secret.slice(0, -1) : secret + character;
90
- }
91
- };
92
- process.stdin.on("data", read);
93
- });
94
-
95
- const choose = async <T>(question: string, items: readonly T[], label: (item: T) => string) => {
96
- items.forEach((item, index) => console.log(` ${index + 1}. ${label(item)}`));
97
- while (true) {
98
- const item = items[Number(await ask(`${question} [1-${items.length}]: `)) - 1];
99
- if (item !== undefined) return item;
100
- }
101
- };
102
-
103
- const confirm = async (question: string, flags: PlantFlags) =>
104
- flags.yes || /^y(es)?$/i.test(await ask(`${question} [y/N]: `));
105
-
106
- const askCredentials = async (): Promise<Credentials> => ({
107
- username: await ask("Controller username: "),
108
- password: await askSecret("Controller password: "),
109
- });
110
-
111
- const progress = (message: string) => console.log(` ${message}`);
112
-
113
- /** Prints progress with the minutes and seconds since it was made, so the slow steps show. */
114
- const timedProgress = () => {
115
- const start = Date.now();
116
- return (message: string) => {
117
- const seconds = Math.round((Date.now() - start) / 1000);
118
- progress(`${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")} ${message}`);
119
- };
120
- };
121
-
122
- /** The plant agent named by TSPLC_AGENT_URL and TSPLC_AGENT_TOKEN. */
123
- export const connect = () => {
124
- const environment = z
125
- .object({
126
- TSPLC_AGENT_URL: z.url({
127
- error: "Set TSPLC_AGENT_URL to the plant agent, such as http://line-pc:4850",
128
- }),
129
- TSPLC_AGENT_TOKEN: z.string({ error: "Set TSPLC_AGENT_TOKEN to the plant agent's token" }),
130
- })
131
- .parse(process.env);
132
- return createAgentClient({
133
- url: environment.TSPLC_AGENT_URL,
134
- token: environment.TSPLC_AGENT_TOKEN,
135
- });
136
- };
137
-
138
- /**
139
- * Reads through the agent's open login, as `tsplc read` does, without opening one: the
140
- * debugger has no controller credentials.
141
- */
142
- export const readThroughAgent =
143
- (agent: AgentClient) =>
144
- async ([first, ...rest]: string[]) => {
145
- if (!first) return {};
146
- try {
147
- const result = await agent.command({ command: "read", expressions: [first, ...rest] });
148
- if (!("values" in result)) throw new Error("The agent answered a read without values");
149
- return result.values;
150
- } catch (error) {
151
- const { login } = await agent.status();
152
- if (!login) throw new LoginUnavailable(noLogin, { cause: error });
153
- if ("error" in login) throw new Error(login.error, { cause: error });
154
- throw error;
155
- }
156
- };
157
-
158
- const selectTarget = async (agent: AgentClient): Promise<Target> => {
159
- const interfaces = await agent.interfaces();
160
- if (!interfaces.length) throw new Error("The plant PC has no IPv4 network.");
161
- const network =
162
- interfaces.length === 1 && interfaces[0]
163
- ? interfaces[0]
164
- : await choose(
165
- "Which network is the controller on?",
166
- interfaces,
167
- (item) => `${item.name} ${item.address}/${item.prefixLength}`,
168
- );
169
- console.log(`Scanning ${network.address}/${network.prefixLength} for CODESYS controllers…`);
170
- const found = await agent.discover(network.name);
171
- const manual = { address: "", port: 11740, hostname: null };
172
- const choice = await choose("Which controller?", [...found, manual], (item) =>
173
- item === manual
174
- ? "Enter an address"
175
- : `${item.address}${item.hostname ? ` (${item.hostname})` : ""}`,
176
- );
177
- const host = choice === manual ? await ask("Controller address: ") : choice.address;
178
- return agent.setTarget({ host, port: choice.port });
179
- };
180
-
181
- /** Every published leaf the generated contract describes, as CODESYS expressions name it. */
182
- const contractVariables = async (config: LoadedConfig["config"], root: string) => {
183
- if (!config.typegen) return [];
184
- const contract = z
185
- .object({
186
- symbols: z.array(z.object({ name: z.string(), gvl: z.string(), type: z.string() })),
187
- typeFields: z.record(z.string(), z.array(z.object({ field: z.string(), type: z.string() }))),
188
- })
189
- .parse(await import(pathToFileURL(resolve(root, config.typegen.dir, "plc.ts")).href));
190
- return contract.symbols.flatMap(({ name, gvl, type }): Variable[] => {
191
- const path = `${gvl}.${name}`;
192
- const fields = contract.typeFields[type];
193
- if (!fields) return [{ path, type }];
194
- return fields.map((field) => ({
195
- path:
196
- field.field === ""
197
- ? path
198
- : `${path}${field.field.startsWith("[") ? "" : "."}${field.field}`,
199
- type: field.type,
200
- }));
201
- });
202
- };
203
-
204
- /**
205
- * The variable holding the bearer token the PLC sends the project's own server: the HTTP
206
- * credential for the server's base URL.
207
- */
208
- export const serverTokenEnv = (config: LoadedConfig["config"]) =>
209
- config.codesys?.http?.credentials.find(({ originEnv }) => originEnv === config.server?.baseUrlEnv)
210
- ?.bearerTokenEnv;
211
-
212
- /**
213
- * Compiles the program and bundles its server into the files `tsplc deploy` uploads: the
214
- * production program, or with `--simulate` the development one without fieldbus I/O, for a
215
- * virtual PLC whose inputs a plant simulation writes, as `tsplc run --simulate` builds it.
216
- */
217
- const prepareRelease = async (file: string, loaded: LoadedConfig, flags: PlantFlags) => {
218
- const { config, root } = loaded;
219
- if (!config.compiler) throw new Error("tsplc deploy deploys tsPLC programs; configure compiler.");
220
- const command = flags.simulate ? "run" : "deploy";
221
- const emitted = await buildProject(file, {
222
- emitOnly: true,
223
- forController: true,
224
- frozenLockfile: flags["frozen-lockfile"],
225
- ...(flags.simulate
226
- ? { loaded: { ...loaded, config: simulationConfig(config) }, configured: config }
227
- : { loaded }),
228
- buildTarget: flags.simulate ? "development" : "production",
229
- controller: controllerFor(config, command),
230
- });
231
- if (hasErrors(emitted.diagnostics)) return { diagnostics: emitted.diagnostics };
232
- const settings = emitted.controllerConfig;
233
- if (!settings) throw new Error("Configure build settings for deployment.");
234
- await generateProject(file, { loaded, targets: await projectTargets(file, { loaded }) });
235
-
236
- const portable = (path: string) => path.split(sep).join("/");
237
- const libraries = (settings.libraries ?? []).map((library) => ({
238
- ...library,
239
- release: `libraries/${library.sha256}-${basename(library.path)}`,
240
- }));
241
- const files: ReleaseFile[] = [
242
- { path: "template.project", content: Bun.file(settings.template) },
243
- ...libraries.map((library) => ({ path: library.release, content: Bun.file(library.path) })),
244
- ];
245
- // The agent compiles only the ST. Plain TypeScript programs emit their generated modules under `.tsplc/`.
246
- for await (const source of new Bun.Glob("**/*.st").scan({ cwd: settings.sourceDir, dot: true }))
247
- files.push({
248
- path: `st/${portable(source)}`,
249
- content: Bun.file(resolve(settings.sourceDir, source)),
250
- });
251
- // The agent's debugger reads the program through its debug manifest.
252
- const debugManifest = resolve(settings.sourceDir, "debug.json");
253
- if (existsSync(debugManifest))
254
- files.push({ path: "debug.json", content: Bun.file(debugManifest) });
255
- let server: string | undefined;
256
- if (config.server?.runtime) {
257
- const script = await bundleServer(config, root);
258
- server = `server/${basename(script)}`;
259
- files.push({ path: server, content: Bun.file(script) });
260
- }
261
- const manifest: ReleaseManifest = {
262
- // Paths are relative to the release; the agent supplies the output and controller settings.
263
- config: {
264
- io: {},
265
- deviceTree: settings.deviceTree,
266
- controller: settings.controller,
267
- libraryReferences: settings.libraryReferences,
268
- libraries: libraries.map(({ release, ...library }) => ({ ...library, path: release })),
269
- task: settings.task,
270
- tasks: settings.tasks,
271
- removeObjects: settings.removeObjects,
272
- symbols: settings.symbols,
273
- timeouts: settings.timeouts,
274
- template: "template.project",
275
- sourceDir: "st",
276
- entry: `st/${portable(relative(settings.sourceDir, settings.entry))}`,
277
- },
278
- variables: await contractVariables(config, root),
279
- server,
280
- debug: config.debug,
281
- serverTokenEnv: serverTokenEnv(config),
282
- };
283
- return { release: { manifest, files } };
284
- };
285
-
286
- const deploy = async (
287
- agent: AgentClient,
288
- file: string,
289
- loaded: LoadedConfig,
290
- flags: PlantFlags,
291
- ) => {
292
- const status = await agent.status();
293
- if (status.login) throw new Error("A login is open; log out before deploying: tsplc logout");
294
- const target = !status.target || flags.select ? await selectTarget(agent) : status.target;
295
- console.log(`Building the release for ${target.host}…`);
296
- const building = timedProgress();
297
- const { release, diagnostics } = await prepareRelease(file, loaded, flags);
298
- if (!release) return { diagnostics };
299
- building("Built");
300
- if (
301
- flags.download &&
302
- !(await confirm(
303
- "A full download stops the running application while it loads. Continue?",
304
- flags,
305
- ))
306
- )
307
- throw new Error("Cancelled.");
308
- const credentials = await askCredentials();
309
- const settings = {
310
- credentials,
311
- download: flags.download ?? false,
312
- initializeUser: flags["initialize-user"] ?? false,
313
- };
314
- console.log(
315
- release.manifest.server ? "Deploying the server and the program…" : "Deploying the program…",
316
- );
317
- const deploying = timedProgress();
318
- deploying("Uploading");
319
- try {
320
- return await agent.deploy(release, settings, deploying);
321
- } catch (error) {
322
- if (
323
- !(error instanceof AgentOperationError && error.downloadRequired) ||
324
- !(await confirm(
325
- `${error.message}. A full download stops the running application while it loads. Download now?`,
326
- flags,
327
- ))
328
- )
329
- throw error;
330
- return agent.deploy(release, { ...settings, download: true }, timedProgress());
331
- }
332
- };
333
-
334
- /** Opens a login when none is working; it stays open across commands until `tsplc logout`. */
335
- const ensureLogin = async (agent: AgentClient) => {
336
- const { login } = await agent.status();
337
- if (login && "state" in login) return;
338
- if (login) {
339
- console.log(`The open login failed (${login.error}); replacing it.`);
340
- await agent.logout();
341
- }
342
- const credentials = await askCredentials();
343
- console.log(
344
- "Logging in. CODESYS takes a few minutes to start; the login stays open until tsplc logout.",
345
- );
346
- await agent.login(credentials, progress);
347
- };
348
-
349
- /** The children of `prefix` in the variable tree, with array indexes folded into one range. */
350
- export const variableChildren = (variables: readonly Variable[], prefix: string) => {
351
- const children = new Map<string, { type?: string; leaves: number }>();
352
- const start = prefix.toLowerCase();
353
- for (const { path, type } of variables) {
354
- const lower = path.toLowerCase();
355
- if (
356
- prefix &&
357
- !(lower === start || lower.startsWith(`${start}.`) || lower.startsWith(`${start}[`))
358
- )
359
- continue;
360
- const rest = path.slice(prefix.length).replace(/^\./, "");
361
- if (rest === "") return [{ name: path, type, leaves: 1 }];
362
- const name = /^(\[[^\]]*\]|[^.[]+)/.exec(rest)?.[0] ?? rest;
363
- const child = children.get(name) ?? { leaves: 0 };
364
- children.set(name, { type: rest === name ? type : undefined, leaves: child.leaves + 1 });
365
- }
366
- const indexes = [...children.keys()]
367
- .filter((name) => /^\[\d+\]$/.test(name))
368
- .map((name) => Number(name.slice(1, -1)));
369
- const listed = [...children].filter(([name]) => !/^\[\d+\]$/.test(name));
370
- if (indexes.length) {
371
- const first = children.get(`[${Math.min(...indexes)}]`);
372
- listed.unshift([`[${Math.min(...indexes)}..${Math.max(...indexes)}]`, first ?? { leaves: 0 }]);
373
- }
374
- return listed.map(([name, child]) => ({ name, ...child }));
375
- };
376
-
377
- const printLogin = (result: LoginResult) => {
378
- if ("values" in result) {
379
- for (const [expression, value] of Object.entries(result.values))
380
- console.log(`${expression} = ${value}`);
381
- return;
382
- }
383
- console.log(`Application ${result.state}`);
384
- if (result.forced.length) console.log(`Forced: ${result.forced.join(", ")}`);
385
- };
386
-
387
- /**
388
- * Runs a command against the plant agent named by TSPLC_AGENT_URL and TSPLC_AGENT_TOKEN.
389
- * Returns a deployment's compiler diagnostics when the program doesn't compile.
390
- */
391
- export const runPlantCommand = async (
392
- command: string,
393
- args: string[],
394
- flags: PlantFlags,
395
- project: { file: string; load: () => Promise<LoadedConfig> },
396
- ) => {
397
- const agent = connect();
398
- const expect = (count: number, usage: string) => {
399
- if (args.length !== count) throw new Error(`Usage: tsplc ${command} ${usage}`);
400
- };
401
- const send = async (loginCommand: LoginCommand) => {
402
- await ensureLogin(agent);
403
- printLogin(await agent.command(loginCommand));
404
- };
405
- switch (command) {
406
- case "deploy": {
407
- expect(0, "[--download] [--select] [--initialize-user] [--simulate]");
408
- const deployed = await deploy(agent, project.file, await project.load(), flags);
409
- if ("diagnostics" in deployed) return deployed;
410
- console.log(`Deployed release ${deployed.id} (${deployed.operation}).`);
411
- return;
412
- }
413
- case "target": {
414
- expect(0, "");
415
- const target = await selectTarget(agent);
416
- console.log(`Deployments now go to ${target.host}:${target.port}.`);
417
- return;
418
- }
419
- case "status": {
420
- expect(0, "");
421
- const status = await agent.status();
422
- console.log(
423
- `Controller ${status.target ? `${status.target.host}:${status.target.port}` : "not selected (tsplc target)"}`,
424
- );
425
- console.log(
426
- `Release ${status.release ? `${status.release.id}, ${status.release.operation} at ${status.release.deployedAt}` : "none"}`,
427
- );
428
- console.log(
429
- `Server ${status.server ? `${status.server.running ? "running" : "restarting"} (${status.server.executable})` : "none"}`,
430
- );
431
- const { login } = status;
432
- if (!login) console.log("Login closed");
433
- else if ("error" in login) console.log(`Login failed: ${login.error} (tsplc logout)`);
434
- else
435
- console.log(
436
- `Login open; application ${login.state}${login.forced.length ? `; forced: ${login.forced.join(", ")}` : ""}`,
437
- );
438
- return;
439
- }
440
- case "login":
441
- expect(0, "");
442
- await ensureLogin(agent);
443
- printLogin(await agent.command({ command: "state" }));
444
- return;
445
- case "logout": {
446
- expect(0, "");
447
- const { login } = await agent.status();
448
- const forced = login && "forced" in login ? login.forced : [];
449
- if (
450
- forced.length &&
451
- !(await confirm(
452
- `Forced: ${forced.join(", ")}. Forces stay on the controller after logout. Log out anyway?`,
453
- flags,
454
- ))
455
- )
456
- throw new Error("Cancelled.");
457
- const { failure } = await agent.logout();
458
- console.log(
459
- failure
460
- ? `The login couldn't log out (${failure}); its container was removed.`
461
- : "Logged out.",
462
- );
463
- return;
464
- }
465
- case "vars": {
466
- if (args.length > 1) throw new Error("Usage: tsplc vars [path]");
467
- const variables = await agent.variables();
468
- const children = variableChildren(variables, args[0] ?? "");
469
- if (!children.length) throw new Error(`No published variable ${args[0]}.`);
470
- for (const child of children)
471
- console.log(`${child.name.padEnd(32)} ${child.type ?? `${child.leaves} variables`}`);
472
- return;
473
- }
474
- case "read": {
475
- const [first, ...rest] = args;
476
- if (!first) throw new Error("Usage: tsplc read <expression>...");
477
- return send({ command: "read", expressions: [first, ...rest] });
478
- }
479
- case "write":
480
- case "force": {
481
- const [expression, value, ...extra] = args;
482
- if (!expression || !value || extra.length)
483
- throw new Error(`Usage: tsplc ${command} <expression> <value>`);
484
- return send({ command, values: { [expression]: value } });
485
- }
486
- case "unforce":
487
- return send({ command: "unforce", expressions: args, restore: flags.restore ?? false });
488
- case "start":
489
- expect(0, "");
490
- return send({ command: "start" });
491
- case "stop":
492
- expect(0, "");
493
- if (!(await confirm("Stop the application on the controller?", flags)))
494
- throw new Error("Cancelled.");
495
- return send({ command: "stop" });
496
- case "reset": {
497
- expect(1, "warm|cold");
498
- const kind = z.enum(["warm", "cold"]).parse(args[0]);
499
- if (
500
- !(await confirm(
501
- `Reset the application (${kind})? It stops and reinitializes its variables.`,
502
- flags,
503
- ))
504
- )
505
- throw new Error("Cancelled.");
506
- return send({ command: "reset", kind: kind === "warm" ? "Warm" : "Cold" });
507
- }
508
- }
509
- };