@tsplc/compiler 0.5.9 → 0.5.12

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 (74) hide show
  1. package/dist/cli.js +396 -66
  2. package/dist/cli.js.map +10 -8
  3. package/dist/codesys.js +2 -2
  4. package/dist/codesys.js.map +1 -1
  5. package/package.json +9 -9
  6. package/src/project/cli.ts +15 -3
  7. package/src/project/deployments.ts +443 -0
  8. package/src/project/git.ts +35 -0
  9. package/src/project/plant.ts +119 -36
  10. package/src/project/release.ts +15 -6
  11. package/src/runtime/.runtime-65O4JH/server/router.ts +17 -0
  12. package/src/runtime/.runtime-65O4JH/src/cell.ts +45 -0
  13. package/src/runtime/.runtime-65O4JH/src/controller.ts +58 -0
  14. package/src/runtime/.runtime-65O4JH/src/lane.ts +6 -0
  15. package/src/runtime/.runtime-65O4JH/src/main.ts +11 -0
  16. package/src/runtime/.runtime-65O4JH/src/services.ts +8 -0
  17. package/src/runtime/.runtime-65O4JH/tsconfig.json +13 -0
  18. package/src/runtime/.runtime-65O4JH/tsplc.config.ts +31 -0
  19. package/src/runtime/.runtime-Brw2kO/server/router.ts +17 -0
  20. package/src/runtime/.runtime-Brw2kO/src/cell.ts +45 -0
  21. package/src/runtime/.runtime-Brw2kO/src/controller.ts +58 -0
  22. package/src/runtime/.runtime-Brw2kO/src/lane.ts +6 -0
  23. package/src/runtime/.runtime-Brw2kO/src/main.ts +11 -0
  24. package/src/runtime/.runtime-Brw2kO/src/services.ts +8 -0
  25. package/src/runtime/.runtime-Brw2kO/tsconfig.json +13 -0
  26. package/src/runtime/.runtime-Brw2kO/tsplc.config.ts +31 -0
  27. package/src/runtime/.runtime-NHfu1D/server/router.ts +17 -0
  28. package/src/runtime/.runtime-NHfu1D/src/cell.ts +45 -0
  29. package/src/runtime/.runtime-NHfu1D/src/controller.ts +58 -0
  30. package/src/runtime/.runtime-NHfu1D/src/lane.ts +6 -0
  31. package/src/runtime/.runtime-NHfu1D/src/main.ts +11 -0
  32. package/src/runtime/.runtime-NHfu1D/src/services.ts +8 -0
  33. package/src/runtime/.runtime-NHfu1D/tsconfig.json +13 -0
  34. package/src/runtime/.runtime-NHfu1D/tsplc.config.ts +31 -0
  35. package/src/runtime/.runtime-WbtNvR/server/router.ts +17 -0
  36. package/src/runtime/.runtime-WbtNvR/src/cell.ts +45 -0
  37. package/src/runtime/.runtime-WbtNvR/src/controller.ts +58 -0
  38. package/src/runtime/.runtime-WbtNvR/src/lane.ts +6 -0
  39. package/src/runtime/.runtime-WbtNvR/src/main.ts +11 -0
  40. package/src/runtime/.runtime-WbtNvR/src/services.ts +8 -0
  41. package/src/runtime/.runtime-WbtNvR/tsconfig.json +13 -0
  42. package/src/runtime/.runtime-WbtNvR/tsplc.config.ts +31 -0
  43. package/src/runtime/.runtime-opcua-GMPUt8/server/router.ts +17 -0
  44. package/src/runtime/.runtime-opcua-GMPUt8/src/cell.ts +45 -0
  45. package/src/runtime/.runtime-opcua-GMPUt8/src/controller.ts +58 -0
  46. package/src/runtime/.runtime-opcua-GMPUt8/src/lane.ts +6 -0
  47. package/src/runtime/.runtime-opcua-GMPUt8/src/main.ts +11 -0
  48. package/src/runtime/.runtime-opcua-GMPUt8/src/services.ts +8 -0
  49. package/src/runtime/.runtime-opcua-GMPUt8/tsconfig.json +13 -0
  50. package/src/runtime/.runtime-opcua-GMPUt8/tsplc.config.ts +31 -0
  51. package/src/runtime/.runtime-opcua-UwafxO/server/router.ts +17 -0
  52. package/src/runtime/.runtime-opcua-UwafxO/src/cell.ts +45 -0
  53. package/src/runtime/.runtime-opcua-UwafxO/src/controller.ts +58 -0
  54. package/src/runtime/.runtime-opcua-UwafxO/src/lane.ts +6 -0
  55. package/src/runtime/.runtime-opcua-UwafxO/src/main.ts +11 -0
  56. package/src/runtime/.runtime-opcua-UwafxO/src/services.ts +8 -0
  57. package/src/runtime/.runtime-opcua-UwafxO/tsconfig.json +13 -0
  58. package/src/runtime/.runtime-opcua-UwafxO/tsplc.config.ts +31 -0
  59. package/src/runtime/.runtime-opcua-ecaSee/server/router.ts +17 -0
  60. package/src/runtime/.runtime-opcua-ecaSee/src/cell.ts +45 -0
  61. package/src/runtime/.runtime-opcua-ecaSee/src/controller.ts +58 -0
  62. package/src/runtime/.runtime-opcua-ecaSee/src/lane.ts +6 -0
  63. package/src/runtime/.runtime-opcua-ecaSee/src/main.ts +11 -0
  64. package/src/runtime/.runtime-opcua-ecaSee/src/services.ts +8 -0
  65. package/src/runtime/.runtime-opcua-ecaSee/tsconfig.json +13 -0
  66. package/src/runtime/.runtime-opcua-ecaSee/tsplc.config.ts +31 -0
  67. package/src/runtime/.runtime-opcua-y91UCm/server/router.ts +17 -0
  68. package/src/runtime/.runtime-opcua-y91UCm/src/cell.ts +45 -0
  69. package/src/runtime/.runtime-opcua-y91UCm/src/controller.ts +58 -0
  70. package/src/runtime/.runtime-opcua-y91UCm/src/lane.ts +6 -0
  71. package/src/runtime/.runtime-opcua-y91UCm/src/main.ts +11 -0
  72. package/src/runtime/.runtime-opcua-y91UCm/src/services.ts +8 -0
  73. package/src/runtime/.runtime-opcua-y91UCm/tsconfig.json +13 -0
  74. package/src/runtime/.runtime-opcua-y91UCm/tsplc.config.ts +31 -0
@@ -0,0 +1,443 @@
1
+ import { spawn } from "node:child_process";
2
+ import type {
3
+ DeploymentMode,
4
+ DeploymentRecord,
5
+ DeployOptions,
6
+ GitSource,
7
+ } from "@tsplc/agent";
8
+ import {
9
+ type AgentClient,
10
+ AgentOperationError,
11
+ AgentUnreachable,
12
+ } from "@tsplc/agent/client";
13
+ import { describeFinding } from "@tsplc/build";
14
+ import { progress, timedProgress } from "./terminal";
15
+
16
+ /** `tsplc deploy --wait` and the like exit with this while the deployment waits on a person. */
17
+ export const awaitingApprovalExit = 2;
18
+
19
+ /** How a command that follows a deployment may ask before it approves one. */
20
+ export interface Approval {
21
+ /** Approve without asking: `--yes`. */
22
+ yes: boolean;
23
+ /** Someone at a terminal can answer. */
24
+ interactive: boolean;
25
+ /** Asks a yes-or-no question. */
26
+ confirm: (question: string) => Promise<boolean>;
27
+ }
28
+
29
+ /** What a command that queues a deployment does once it is queued. */
30
+ export interface Follow {
31
+ /** Follow it until it finishes: `--wait`. */
32
+ wait: boolean;
33
+ approval: Approval;
34
+ }
35
+
36
+ /** How often, a second apart, following a deployment reconnects before it gives up. */
37
+ const reconnectAttempts = 5;
38
+ const reconnectDelay = 1000;
39
+
40
+ const stateMessage = (record: DeploymentRecord) => {
41
+ switch (record.state) {
42
+ case "queued":
43
+ return "Queued.";
44
+ case "building":
45
+ return "Building the release…";
46
+ case "applying":
47
+ return record.operation === "download"
48
+ ? "Downloading the program; the application stops while it loads…"
49
+ : "Applying the online change…";
50
+ case "starting":
51
+ return "Starting the server…";
52
+ case "verifying":
53
+ return "Checking the deployment's health…";
54
+ default:
55
+ return undefined;
56
+ }
57
+ };
58
+
59
+ const printFindings = (record: DeploymentRecord) => {
60
+ if (!record.findings.length) {
61
+ progress("No findings.");
62
+ return;
63
+ }
64
+ for (const finding of record.findings) {
65
+ progress(
66
+ `${finding.refuses ? "refuses" : "note"}: ${describeFinding(finding)}`,
67
+ );
68
+ }
69
+ };
70
+
71
+ /** Whether to approve: `--yes` does, a person may, and null when nobody can be asked. */
72
+ const decide = async (approval: Approval, question: string) => {
73
+ if (approval.yes) {
74
+ return true;
75
+ }
76
+ if (!approval.interactive) {
77
+ return null;
78
+ }
79
+ return approval.confirm(question);
80
+ };
81
+
82
+ /**
83
+ * Shows what a deployment waits on and approves it when the deployer agrees. False when it is
84
+ * left waiting.
85
+ */
86
+ const approve = async (
87
+ agent: AgentClient,
88
+ record: DeploymentRecord,
89
+ reason: "review" | "downloadRequired",
90
+ { url, approval }: { url: string; approval: Approval },
91
+ ) => {
92
+ const download = reason === "downloadRequired";
93
+ if (download) {
94
+ console.log(
95
+ "Only a full download can deploy this release, and a full download stops the running application while it loads.",
96
+ );
97
+ } else {
98
+ console.log("The review found what the online change would do:");
99
+ }
100
+ printFindings(record);
101
+ const approved = await decide(
102
+ approval,
103
+ download ? "Download now?" : "Apply it?",
104
+ );
105
+ if (!approved) {
106
+ console.log(
107
+ approved === null
108
+ ? `It waits for approval on the dashboard: ${url}`
109
+ : `It waits for approval or cancellation on the dashboard: ${url}`,
110
+ );
111
+ return false;
112
+ }
113
+ await agent.approve(record.id, { download });
114
+ console.log(download ? "Approved the full download." : "Approved.");
115
+ return true;
116
+ };
117
+
118
+ /**
119
+ * Follows a deployment until it finishes, printing its log and the states it goes through, and
120
+ * asking for approval when it waits on one. Reconnects from the last log line it printed. The
121
+ * exit code: 0 when it is ready, `awaitingApprovalExit` when it is left waiting; a failed or
122
+ * canceled deployment throws.
123
+ */
124
+ export const followDeployment = async (
125
+ agent: AgentClient,
126
+ deployment: { id: string; url: string },
127
+ approval: Approval,
128
+ ): Promise<number> => {
129
+ const seen: {
130
+ after: number;
131
+ state: DeploymentRecord["state"] | null;
132
+ approval: string | null;
133
+ failures: number;
134
+ } = { after: 0, state: null, approval: null, failures: 0 };
135
+
136
+ /** The exit code once the deployment is done with this command, else undefined. */
137
+ const onRecord = async (record: DeploymentRecord) => {
138
+ if (record.state !== seen.state) {
139
+ seen.state = record.state;
140
+ const message = stateMessage(record);
141
+ if (message) {
142
+ console.log(message);
143
+ }
144
+ }
145
+ if (record.state !== "awaitingApproval" || !record.approval) {
146
+ seen.approval = null;
147
+ } else {
148
+ const asked = `${record.approval.reason}: ${record.approval.message}`;
149
+ if (asked !== seen.approval) {
150
+ seen.approval = asked;
151
+ console.log(record.approval.message);
152
+ const approved = await approve(agent, record, record.approval.reason, {
153
+ url: deployment.url,
154
+ approval,
155
+ });
156
+ if (!approved) {
157
+ return awaitingApprovalExit;
158
+ }
159
+ }
160
+ }
161
+ if (record.state === "ready") {
162
+ const { health } = record;
163
+ console.log(
164
+ health
165
+ ? `Ready: controller ${health.controller}, server ${health.server}, PLC ${health.plc}.${health.detail ? ` ${health.detail}` : ""}`
166
+ : "Ready.",
167
+ );
168
+ return 0;
169
+ }
170
+ if (record.state === "error") {
171
+ throw new Error(
172
+ `The deployment failed: ${record.error?.message ?? "no reason given"}. ${deployment.url}`,
173
+ );
174
+ }
175
+ if (record.state === "canceled") {
176
+ throw new Error(`The deployment was canceled. ${deployment.url}`);
177
+ }
178
+ return undefined;
179
+ };
180
+
181
+ while (true) {
182
+ try {
183
+ for await (const event of agent.deploymentEvents(
184
+ deployment.id,
185
+ seen.after,
186
+ )) {
187
+ seen.failures = 0;
188
+ if (event.kind === "record") {
189
+ const exit = await onRecord(event.record);
190
+ if (exit !== undefined) {
191
+ return exit;
192
+ }
193
+ } else if (event.line.seq > seen.after) {
194
+ seen.after = event.line.seq;
195
+ progress(
196
+ event.line.level === "info"
197
+ ? event.line.message
198
+ : `${event.line.level}: ${event.line.message}`,
199
+ );
200
+ }
201
+ }
202
+ } catch (error) {
203
+ if (!(error instanceof AgentUnreachable)) {
204
+ throw error;
205
+ }
206
+ }
207
+ // The stream broke, or ended before the deployment finished.
208
+ seen.failures += 1;
209
+ if (seen.failures > reconnectAttempts) {
210
+ throw new Error(
211
+ `Lost the connection to the plant agent; the deployment goes on: ${deployment.url}`,
212
+ );
213
+ }
214
+ await Bun.sleep(reconnectDelay);
215
+ }
216
+ };
217
+
218
+ /** Prints a queued deployment's page, then follows it when asked to. */
219
+ const queued = async (
220
+ agent: AgentClient,
221
+ created: { id: string; url: string },
222
+ follow: Follow,
223
+ ) => {
224
+ console.log(`Deployment ${created.id} queued: ${created.url}`);
225
+ if (!follow.wait) {
226
+ return 0;
227
+ }
228
+ return followDeployment(agent, created, follow.approval);
229
+ };
230
+
231
+ /**
232
+ * Uploads a built release as a queued deployment and prints its page. An agent without the
233
+ * deployments API deploys it at once instead, as `tsplc deploy` did before.
234
+ */
235
+ export const submitDeployment = async (
236
+ agent: AgentClient,
237
+ release: Parameters<AgentClient["deploy"]>[0],
238
+ settings: Omit<DeployOptions, "deployment">,
239
+ request: { mode: DeploymentMode; git: GitSource | null },
240
+ follow: Follow,
241
+ ) => {
242
+ const uploading = timedProgress();
243
+ const created = await agent.queueDeployment(
244
+ release,
245
+ { ...settings, deployment: request },
246
+ uploading,
247
+ );
248
+ if (created) {
249
+ uploading("Uploaded");
250
+ if (request.mode === "review" && !follow.wait) {
251
+ console.log("Once reviewed, it waits for approval on its page.");
252
+ }
253
+ return queued(agent, created, follow);
254
+ }
255
+ if (request.mode === "review") {
256
+ throw new Error(
257
+ "This plant agent can't review a deployment before applying it; deploy without --review.",
258
+ );
259
+ }
260
+ console.log("This plant agent can't queue deployments; deploying at once.");
261
+ const deployed = await deployAtOnce(
262
+ agent,
263
+ release,
264
+ settings,
265
+ follow.approval,
266
+ );
267
+ console.log(`Deployed release ${deployed.id} (${deployed.operation}).`);
268
+ return 0;
269
+ };
270
+
271
+ /** Deploys through `POST /deploy`, offering a full download when only one can deploy. */
272
+ const deployAtOnce = async (
273
+ agent: AgentClient,
274
+ release: Parameters<AgentClient["deploy"]>[0],
275
+ settings: Omit<DeployOptions, "deployment">,
276
+ approval: Approval,
277
+ ) => {
278
+ const deploying = timedProgress();
279
+ try {
280
+ return await agent.deploy(release, settings, deploying);
281
+ } catch (error) {
282
+ if (
283
+ !(error instanceof AgentOperationError && error.downloadRequired) ||
284
+ !(
285
+ approval.yes ||
286
+ (await approval.confirm(
287
+ `${error.message}. A full download stops the running application while it loads. Download now?`,
288
+ ))
289
+ )
290
+ ) {
291
+ throw error;
292
+ }
293
+ return agent.deploy(
294
+ release,
295
+ { ...settings, download: true },
296
+ timedProgress(),
297
+ );
298
+ }
299
+ };
300
+
301
+ /** The deployments `GET /api/deployments` answers, newest first, with the running and last healthy ones. */
302
+ interface DeploymentList {
303
+ deployments: DeploymentRecord[];
304
+ current: string | null;
305
+ lastGood: string | null;
306
+ }
307
+
308
+ /**
309
+ * Where `tsplc rollback` goes without an id: the newest deployment before the running one that
310
+ * ran healthy with another release. Without a running one, the last healthy one.
311
+ */
312
+ export const rollbackTarget = ({
313
+ deployments,
314
+ current,
315
+ lastGood,
316
+ }: DeploymentList) => {
317
+ const index = deployments.findIndex(({ id }) => id === current);
318
+ const running = deployments[index];
319
+ if (!running) {
320
+ return deployments.find(({ id }) => id === lastGood);
321
+ }
322
+ return deployments
323
+ .slice(index + 1)
324
+ .find(
325
+ (deployment) =>
326
+ deployment.state === "ready" &&
327
+ deployment.activeFrom !== null &&
328
+ deployment.release !== running.release,
329
+ );
330
+ };
331
+
332
+ const age = (from: string, now: number) => {
333
+ const seconds = Math.max(0, Math.round((now - Date.parse(from)) / 1000));
334
+ if (seconds < 60) {
335
+ return `${seconds}s`;
336
+ }
337
+ if (seconds < 3600) {
338
+ return `${Math.floor(seconds / 60)}m`;
339
+ }
340
+ if (seconds < 48 * 3600) {
341
+ return `${Math.floor(seconds / 3600)}h`;
342
+ }
343
+ return `${Math.floor(seconds / 86400)}d`;
344
+ };
345
+
346
+ const commitLabel = (git: GitSource | null) =>
347
+ git ? `${git.commit.slice(0, 7)}${git.dirty ? "*" : ""}` : "-";
348
+
349
+ const requester = ({ requestedBy }: DeploymentRecord) =>
350
+ requestedBy.user && requestedBy.host
351
+ ? `${requestedBy.user}@${requestedBy.host}`
352
+ : (requestedBy.user ?? requestedBy.identity.name);
353
+
354
+ /** `tsplc deployments`: the agent's deployments, newest first, or as JSON. */
355
+ export const printDeployments = async (
356
+ agent: AgentClient,
357
+ flags: { format?: "json" | "text" },
358
+ ) => {
359
+ const list = await agent.deployments();
360
+ if (flags.format === "json") {
361
+ console.log(JSON.stringify({ ok: true, ...list }));
362
+ return;
363
+ }
364
+ if (!list.deployments.length) {
365
+ console.log("No deployments yet.");
366
+ return;
367
+ }
368
+ const now = Date.now();
369
+ const rows = [
370
+ ["ID", "STATE", "AGE", "RELEASE", "COMMIT", "BY", ""],
371
+ ...list.deployments.map((deployment) => [
372
+ deployment.id,
373
+ deployment.state,
374
+ age(deployment.createdAt, now),
375
+ deployment.release,
376
+ commitLabel(deployment.git),
377
+ requester(deployment),
378
+ [
379
+ deployment.id === list.current ? "current" : "",
380
+ deployment.id === list.lastGood ? "last good" : "",
381
+ ]
382
+ .filter(Boolean)
383
+ .join(", "),
384
+ ]),
385
+ ];
386
+ const widths = rows[0]?.map((_, column) =>
387
+ Math.max(...rows.map((row) => row[column]?.length ?? 0)),
388
+ );
389
+ for (const row of rows) {
390
+ console.log(
391
+ row
392
+ .map((cell, column) => cell.padEnd(widths?.[column] ?? 0))
393
+ .join(" ")
394
+ .trimEnd(),
395
+ );
396
+ }
397
+ };
398
+
399
+ /** `tsplc rollback [id]`: deploys that deployment's release again, by default the last good one before the running one. */
400
+ export const rollBack = async (
401
+ agent: AgentClient,
402
+ id: string | undefined,
403
+ follow: Follow,
404
+ ) => {
405
+ const target = id ?? rollbackTarget(await agent.deployments())?.id;
406
+ if (!target) {
407
+ throw new Error(
408
+ "No earlier healthy deployment to roll back to; name one: tsplc rollback <id>",
409
+ );
410
+ }
411
+ console.log(`Rolling back to ${target}…`);
412
+ return queued(agent, await agent.rollback(target), follow);
413
+ };
414
+
415
+ /** `tsplc redeploy <id>`: deploys that deployment's release again. */
416
+ export const redeploy = async (
417
+ agent: AgentClient,
418
+ id: string,
419
+ mode: DeploymentMode,
420
+ follow: Follow,
421
+ ) => queued(agent, await agent.redeploy(id, mode), follow);
422
+
423
+ /** The command that opens a URL in the desktop's browser, by platform. */
424
+ const openers: Partial<Record<NodeJS.Platform, string[]>> = {
425
+ darwin: ["open"],
426
+ win32: ["cmd", "/c", "start", ""],
427
+ };
428
+
429
+ /** `tsplc dashboard`: prints the agent's dashboard, and opens it when someone is at the terminal. */
430
+ export const openDashboard = (agent: AgentClient, interactive: boolean) => {
431
+ const url = new URL("/", agent.url).href;
432
+ console.log(url);
433
+ if (!interactive) {
434
+ return;
435
+ }
436
+ const [command = "xdg-open", ...args] = openers[process.platform] ?? [
437
+ "xdg-open",
438
+ ];
439
+ // Without a desktop to open it on, the printed URL is the answer.
440
+ spawn(command, [...args, url], { stdio: "ignore", detached: true })
441
+ .on("error", () => {})
442
+ .unref();
443
+ };
@@ -0,0 +1,35 @@
1
+ import { execFile } from "node:child_process";
2
+ import type { GitSource } from "@tsplc/agent";
3
+
4
+ /** What `git` prints for `args` in `directory`, or null when it fails or isn't installed. */
5
+ const git = (directory: string, args: readonly string[]) =>
6
+ new Promise<string | null>((resolve) => {
7
+ execFile("git", args, { cwd: directory }, (error, stdout) => {
8
+ resolve(error ? null : stdout.trim());
9
+ });
10
+ });
11
+
12
+ /**
13
+ * The commit checked out in `directory`, for a deployment to record. Null outside a git checkout,
14
+ * before its first commit or without git: a deployment never fails for want of it.
15
+ */
16
+ export const gitSource = async (
17
+ directory: string,
18
+ ): Promise<GitSource | null> => {
19
+ const commit = await git(directory, ["rev-parse", "--verify", "HEAD"]);
20
+ if (!commit) {
21
+ return null;
22
+ }
23
+ const [branch, status, message] = await Promise.all([
24
+ git(directory, ["symbolic-ref", "--quiet", "--short", "HEAD"]),
25
+ git(directory, ["status", "--porcelain"]),
26
+ git(directory, ["log", "-1", "--format=%s"]),
27
+ ]);
28
+ return {
29
+ commit,
30
+ branch: branch || null,
31
+ // A status that can't be read can't vouch for a clean tree.
32
+ dirty: status !== "",
33
+ message: message || null,
34
+ };
35
+ };