@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.
- package/LICENSE +21 -0
- package/README.md +41 -2
- package/dist/cli.js +2325 -0
- package/dist/cli.js.map +26 -0
- package/dist/clock.js +11 -0
- package/dist/clock.js.map +11 -0
- package/dist/codesys.js +6558 -0
- package/dist/codesys.js.map +51 -0
- package/dist/collections.js +399 -0
- package/dist/collections.js.map +10 -0
- package/dist/index.js +16076 -0
- package/dist/index.js.map +61 -0
- package/dist/ir.js +3948 -0
- package/dist/ir.js.map +35 -0
- package/dist/retain.js +10 -0
- package/dist/retain.js.map +10 -0
- package/dist/signals.js +115 -0
- package/dist/signals.js.map +10 -0
- package/dist/telemetry.js +121 -0
- package/dist/telemetry.js.map +12 -0
- package/package.json +122 -4
- package/src/codesys/config.ts +50 -0
- package/src/codesys/debug.ts +655 -0
- package/src/codesys/emit.ts +185 -0
- package/src/codesys/endpoints.ts +111 -0
- package/src/codesys/engineering.ts +96 -0
- package/src/codesys/explain/expressions.ts +445 -0
- package/src/codesys/explain/flags.ts +134 -0
- package/src/codesys/explain/parameters.ts +53 -0
- package/src/codesys/explain/rows.ts +182 -0
- package/src/codesys/explain/tables.ts +79 -0
- package/src/codesys/explain/tasks.ts +68 -0
- package/src/codesys/explain/writes.ts +497 -0
- package/src/codesys/explain.ts +149 -0
- package/src/codesys/expressions.ts +100 -0
- package/src/codesys/global-lists.ts +284 -0
- package/src/codesys/global-names.ts +66 -0
- package/src/codesys/http.ts +1078 -0
- package/src/codesys/index.ts +13 -0
- package/src/codesys/instrumentation.ts +574 -0
- package/src/codesys/io-paths.ts +149 -0
- package/src/codesys/loops.ts +101 -0
- package/src/codesys/manifest.ts +684 -0
- package/src/codesys/names.ts +58 -0
- package/src/codesys/numeric.ts +516 -0
- package/src/codesys/plan.ts +688 -0
- package/src/codesys/programs.ts +138 -0
- package/src/codesys/publication.ts +99 -0
- package/src/codesys/required.ts +8 -0
- package/src/codesys/routines.ts +247 -0
- package/src/codesys/scan-clock.ts +103 -0
- package/src/codesys/scheduling.ts +96 -0
- package/src/codesys/service-channels.ts +24 -0
- package/src/codesys/sources.ts +118 -0
- package/src/codesys/st-files.ts +219 -0
- package/src/codesys/statements.ts +409 -0
- package/src/codesys/storage.ts +150 -0
- package/src/codesys/symbols.ts +240 -0
- package/src/codesys/task-access.ts +186 -0
- package/src/codesys/telemetry-settings.ts +19 -0
- package/src/codesys/telemetry.ts +852 -0
- package/src/codesys/types.ts +310 -0
- package/src/codesys/vendor.ts +113 -0
- package/src/frontend/analyzer.ts +779 -0
- package/src/frontend/async.ts +530 -0
- package/src/frontend/blocks.ts +578 -0
- package/src/frontend/configuration.ts +83 -0
- package/src/frontend/const-functions.ts +204 -0
- package/src/frontend/control-flow.ts +787 -0
- package/src/frontend/cooperative.ts +114 -0
- package/src/frontend/coroutines.ts +1336 -0
- package/src/frontend/dialect-names.ts +104 -0
- package/src/frontend/elaborate/array-searches.ts +224 -0
- package/src/frontend/elaborate/assignments.ts +343 -0
- package/src/frontend/elaborate/calls.ts +1342 -0
- package/src/frontend/elaborate/capture-protocol.ts +237 -0
- package/src/frontend/elaborate/capture.ts +388 -0
- package/src/frontend/elaborate/declarations.ts +124 -0
- package/src/frontend/elaborate/dialect.ts +473 -0
- package/src/frontend/elaborate/expressions.ts +2171 -0
- package/src/frontend/elaborate/filtered-arrays.ts +643 -0
- package/src/frontend/elaborate/frame.ts +145 -0
- package/src/frontend/elaborate/generics.ts +123 -0
- package/src/frontend/elaborate/graph.ts +141 -0
- package/src/frontend/elaborate/imports.ts +105 -0
- package/src/frontend/elaborate/index.ts +851 -0
- package/src/frontend/elaborate/initializers.ts +235 -0
- package/src/frontend/elaborate/iterators.ts +1541 -0
- package/src/frontend/elaborate/layouts.ts +1025 -0
- package/src/frontend/elaborate/model.ts +478 -0
- package/src/frontend/elaborate/names.ts +134 -0
- package/src/frontend/elaborate/reduce.ts +900 -0
- package/src/frontend/elaborate/references.ts +727 -0
- package/src/frontend/elaborate/retention.ts +284 -0
- package/src/frontend/elaborate/specialize.ts +1137 -0
- package/src/frontend/elaborate/statements.ts +1220 -0
- package/src/frontend/elaborate/storage.ts +836 -0
- package/src/frontend/elaborate/time-constructors.ts +34 -0
- package/src/frontend/elaborate/values.ts +200 -0
- package/src/frontend/elaborate/writes.ts +415 -0
- package/src/frontend/expressions.ts +1382 -0
- package/src/frontend/generated-names.ts +95 -0
- package/src/frontend/intrinsics.ts +382 -0
- package/src/frontend/lowering-key.ts +23 -0
- package/src/frontend/module-graph.ts +156 -0
- package/src/frontend/positions.ts +359 -0
- package/src/frontend/promise-chains.ts +872 -0
- package/src/frontend/promises.ts +419 -0
- package/src/frontend/routines.ts +239 -0
- package/src/frontend/sdk.ts +187 -0
- package/src/frontend/services.ts +609 -0
- package/src/frontend/statements.ts +871 -0
- package/src/frontend/tasks.ts +526 -0
- package/src/frontend/telemetry.ts +174 -0
- package/src/frontend/types.ts +1073 -0
- package/src/frontend/typescript.ts +651 -0
- package/src/index.ts +9 -0
- package/src/ir/aggregates.ts +291 -0
- package/src/ir/allocation.ts +96 -0
- package/src/ir/conditions.ts +855 -0
- package/src/ir/core-model.ts +289 -0
- package/src/ir/declarations.ts +281 -0
- package/src/ir/diagnostics.ts +68 -0
- package/src/ir/domains.ts +151 -0
- package/src/ir/fold.ts +279 -0
- package/src/ir/identity.ts +19 -0
- package/src/ir/index.ts +137 -0
- package/src/ir/job-errors.ts +69 -0
- package/src/ir/layouts.ts +211 -0
- package/src/ir/link.ts +302 -0
- package/src/ir/model.ts +394 -0
- package/src/ir/normalization-error.ts +10 -0
- package/src/ir/normalize.ts +52 -0
- package/src/ir/numeric.ts +163 -0
- package/src/ir/operands.ts +160 -0
- package/src/ir/ranges.ts +420 -0
- package/src/ir/routine.ts +1116 -0
- package/src/ir/scalars.ts +453 -0
- package/src/ir/share.ts +790 -0
- package/src/ir/short-circuit.ts +140 -0
- package/src/ir/tables.ts +111 -0
- package/src/ir/temporaries.ts +138 -0
- package/src/ir/types.ts +151 -0
- package/src/project/artifacts.ts +424 -0
- package/src/project/cli.ts +211 -0
- package/src/project/debugger.ts +111 -0
- package/src/project/deployments.ts +387 -0
- package/src/project/flags.ts +14 -0
- package/src/project/git.ts +35 -0
- package/src/project/plant.ts +629 -0
- package/src/project/project-commands.ts +507 -0
- package/src/project/project.ts +559 -0
- package/src/project/release.ts +152 -0
- package/src/project/server-check.ts +54 -0
- package/src/project/server.ts +165 -0
- package/src/project/terminal.ts +45 -0
- package/src/runtime/async.ts +207 -0
- package/src/runtime/launch.ts +59 -0
- package/src/runtime/main.ts +59 -0
- package/src/runtime/missing-file.ts +3 -0
- package/src/runtime/process.ts +177 -0
- package/src/runtime/program.ts +109 -0
- package/src/runtime/retain.ts +108 -0
- package/src/runtime/runtime.ts +324 -0
- package/src/runtime/settings.ts +27 -0
- package/src/runtime/storage.ts +456 -0
- package/src/runtime/symbols.ts +97 -0
- package/src/runtime/telemetry.ts +154 -0
- package/src/runtime/transport.ts +168 -0
- package/stdlib/clock.ts +8 -0
- package/stdlib/collections.ts +534 -0
- package/stdlib/plc-time.ts +2 -0
- package/stdlib/retain.ts +4 -0
- package/stdlib/signals.ts +142 -0
- package/stdlib/telemetry.ts +89 -0
- package/types/async.d.ts +87 -0
- package/types/clock.d.ts +8 -0
- package/types/config.d.ts +2 -0
- package/types/data-types.d.ts +31 -0
- package/types/dialect.d.ts +49 -0
- package/types/globals.d.ts +10 -0
- package/types/index.d.ts +212 -0
- package/types/retain.d.ts +12 -0
- package/types/telemetry.d.ts +47 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { relative, resolve } from "node:path";
|
|
3
|
+
import type { ParseArgsOptionsConfig } from "node:util";
|
|
4
|
+
import type { AgentClient } from "@tsplc/agent/client";
|
|
5
|
+
import {
|
|
6
|
+
agentUrlEnv,
|
|
7
|
+
type LoadedConfig,
|
|
8
|
+
serverBaseUrl,
|
|
9
|
+
serverTokenEnv,
|
|
10
|
+
} from "@tsplc/config";
|
|
11
|
+
import { tcpPort } from "@tsplc/config/build";
|
|
12
|
+
import {
|
|
13
|
+
emittedStDirectory,
|
|
14
|
+
generatedDirectory,
|
|
15
|
+
} from "@tsplc/config/project-files";
|
|
16
|
+
import {
|
|
17
|
+
createDebugger,
|
|
18
|
+
createOpcUaAdapter,
|
|
19
|
+
loadDebugBuild,
|
|
20
|
+
loginReader,
|
|
21
|
+
opcUaConnection,
|
|
22
|
+
serveDebugger,
|
|
23
|
+
} from "@tsplc/debug";
|
|
24
|
+
import { debugManifestFile } from "@tsplc/debug/manifest";
|
|
25
|
+
import { type Flags, flag } from "./flags";
|
|
26
|
+
import { connect, readThroughAgent } from "./plant";
|
|
27
|
+
|
|
28
|
+
type Monitor = NonNullable<LoadedConfig["config"]["monitor"]>;
|
|
29
|
+
|
|
30
|
+
/** Where the debugger serves without `--port`. */
|
|
31
|
+
const debuggerPort = 4870;
|
|
32
|
+
|
|
33
|
+
/** The flags of `tsplc debug`. */
|
|
34
|
+
export const debugOptions = {
|
|
35
|
+
port: { type: "string" },
|
|
36
|
+
"server-url": { type: "string" },
|
|
37
|
+
opcua: flag,
|
|
38
|
+
} as const satisfies ParseArgsOptionsConfig;
|
|
39
|
+
|
|
40
|
+
export const debugUsage = `[--target name] [--port ${debuggerPort}] [--server-url url] [--opcua]`;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Serves the debugger for the project's last build until interrupted. It reads the controller
|
|
44
|
+
* through the plant agent's login, or with `--opcua` at the config's `monitor` endpoint, and
|
|
45
|
+
* follows the server's telemetry and requests when the server's base URL (`--server-url`, or
|
|
46
|
+
* `server.baseUrlEnv`) and the PLC's bearer token are in the config's environment.
|
|
47
|
+
*/
|
|
48
|
+
export async function serveProjectDebugger(
|
|
49
|
+
{ config, root, env }: LoadedConfig,
|
|
50
|
+
flags: Flags<typeof debugOptions>,
|
|
51
|
+
) {
|
|
52
|
+
if (flags.opcua && !config.monitor) {
|
|
53
|
+
throw new Error(
|
|
54
|
+
"Configure monitor with the controller's OPC UA endpoint to use --opcua.",
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
const reader: { monitor: Monitor } | { agent: AgentClient } =
|
|
58
|
+
flags.opcua && config.monitor
|
|
59
|
+
? { monitor: config.monitor }
|
|
60
|
+
: { agent: connect(env) };
|
|
61
|
+
const file = resolve(root, emittedStDirectory, debugManifestFile);
|
|
62
|
+
if (!existsSync(file)) {
|
|
63
|
+
throw new Error(
|
|
64
|
+
`No debug manifest at ${relative(process.cwd(), file)}: build the program first, with tsplc build or tsplc build --emit-only.`,
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
const port = tcpPort.safeParse(Number(flags.port ?? debuggerPort));
|
|
68
|
+
if (!port.success) {
|
|
69
|
+
throw new Error("--port must be a TCP port.");
|
|
70
|
+
}
|
|
71
|
+
const serverUrl = flags["server-url"] ?? serverBaseUrl(config, env);
|
|
72
|
+
const tokenEnv = serverTokenEnv(config);
|
|
73
|
+
const token = tokenEnv && env[tokenEnv];
|
|
74
|
+
const log = (message: string) =>
|
|
75
|
+
console.log(`${new Date().toISOString()} ${message}`);
|
|
76
|
+
const build = await loadDebugBuild(file);
|
|
77
|
+
const debug = await createDebugger({
|
|
78
|
+
...build,
|
|
79
|
+
...("monitor" in reader
|
|
80
|
+
? {
|
|
81
|
+
// An OPC UA endpoint reports no forced list.
|
|
82
|
+
adapter: createOpcUaAdapter(
|
|
83
|
+
opcUaConnection(reader.monitor, { root, env }),
|
|
84
|
+
),
|
|
85
|
+
forced: null,
|
|
86
|
+
}
|
|
87
|
+
: loginReader(build.manifest, {
|
|
88
|
+
read: readThroughAgent(reader.agent),
|
|
89
|
+
status: async () => (await reader.agent.status()).login,
|
|
90
|
+
endpoint: `the plant agent at ${env[agentUrlEnv]}`,
|
|
91
|
+
})),
|
|
92
|
+
stateDirectory: resolve(root, generatedDirectory, "debug"),
|
|
93
|
+
watch: config.debug?.watch ?? {},
|
|
94
|
+
...(serverUrl && token && { server: { url: serverUrl, token } }),
|
|
95
|
+
projectRoot: root,
|
|
96
|
+
log,
|
|
97
|
+
});
|
|
98
|
+
const server = serveDebugger(debug, { port: port.data, log });
|
|
99
|
+
console.log(`tsPLC debugger at ${server.url}`);
|
|
100
|
+
if (!serverUrl || !token) {
|
|
101
|
+
console.log(
|
|
102
|
+
"Not following the server's telemetry and requests: set server.baseUrlEnv or --server-url, and the server's bearer token variable.",
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
await new Promise((stopped) => {
|
|
106
|
+
process.once("SIGINT", stopped);
|
|
107
|
+
process.once("SIGTERM", stopped);
|
|
108
|
+
});
|
|
109
|
+
await server.stop(true);
|
|
110
|
+
await debug.close();
|
|
111
|
+
}
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import type {
|
|
3
|
+
DeploymentMode,
|
|
4
|
+
DeploymentRecord,
|
|
5
|
+
DeployOptions,
|
|
6
|
+
GitSource,
|
|
7
|
+
} from "@tsplc/agent";
|
|
8
|
+
import { type AgentClient, AgentUnreachable } from "@tsplc/agent/client";
|
|
9
|
+
import { describeFinding } from "@tsplc/build";
|
|
10
|
+
import { progress, timedProgress } from "./terminal";
|
|
11
|
+
|
|
12
|
+
/** `tsplc deploy --wait` and the like exit with this while the deployment waits on a person. */
|
|
13
|
+
export const awaitingApprovalExit = 2;
|
|
14
|
+
|
|
15
|
+
/** How a command that follows a deployment may ask before it approves one. */
|
|
16
|
+
export interface Approval {
|
|
17
|
+
/** Approve without asking: `--yes`. */
|
|
18
|
+
yes: boolean;
|
|
19
|
+
/** Someone at a terminal can answer. */
|
|
20
|
+
interactive: boolean;
|
|
21
|
+
/** Asks a yes-or-no question. */
|
|
22
|
+
confirm: (question: string) => Promise<boolean>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** What a command that queues a deployment does once it is queued. */
|
|
26
|
+
export interface Follow {
|
|
27
|
+
/** Follow it until it finishes: `--wait`. */
|
|
28
|
+
wait: boolean;
|
|
29
|
+
approval: Approval;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** How often, a second apart, following a deployment reconnects before it gives up. */
|
|
33
|
+
const reconnectAttempts = 5;
|
|
34
|
+
const reconnectDelay = 1000;
|
|
35
|
+
|
|
36
|
+
const stateMessage = (record: DeploymentRecord) => {
|
|
37
|
+
switch (record.state) {
|
|
38
|
+
case "queued":
|
|
39
|
+
return "Queued.";
|
|
40
|
+
case "building":
|
|
41
|
+
return "Building the release…";
|
|
42
|
+
case "applying":
|
|
43
|
+
return record.operation === "download"
|
|
44
|
+
? "Downloading the program; the application stops while it loads…"
|
|
45
|
+
: "Applying the online change…";
|
|
46
|
+
case "starting":
|
|
47
|
+
return "Starting the server…";
|
|
48
|
+
case "verifying":
|
|
49
|
+
return "Checking the deployment's health…";
|
|
50
|
+
default:
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const printFindings = (record: DeploymentRecord) => {
|
|
56
|
+
if (!record.findings.length) {
|
|
57
|
+
progress("No findings.");
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
for (const finding of record.findings) {
|
|
61
|
+
progress(
|
|
62
|
+
`${finding.refuses ? "refuses" : "note"}: ${describeFinding(finding)}`,
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/** Whether to approve: `--yes` does, a person may, and null when nobody can be asked. */
|
|
68
|
+
const decide = async (approval: Approval, question: string) => {
|
|
69
|
+
if (approval.yes) {
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
if (!approval.interactive) {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
return approval.confirm(question);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Shows what a deployment waits on and approves it when the deployer agrees. False when it is
|
|
80
|
+
* left waiting.
|
|
81
|
+
*/
|
|
82
|
+
const approve = async (
|
|
83
|
+
agent: AgentClient,
|
|
84
|
+
record: DeploymentRecord,
|
|
85
|
+
reason: "review" | "downloadRequired",
|
|
86
|
+
{ url, approval }: { url: string; approval: Approval },
|
|
87
|
+
) => {
|
|
88
|
+
const download = reason === "downloadRequired";
|
|
89
|
+
if (download) {
|
|
90
|
+
console.log(
|
|
91
|
+
"Only a full download can deploy this release, and a full download stops the running application while it loads.",
|
|
92
|
+
);
|
|
93
|
+
} else {
|
|
94
|
+
console.log("The review found what the online change would do:");
|
|
95
|
+
}
|
|
96
|
+
printFindings(record);
|
|
97
|
+
const approved = await decide(
|
|
98
|
+
approval,
|
|
99
|
+
download ? "Download now?" : "Apply it?",
|
|
100
|
+
);
|
|
101
|
+
if (!approved) {
|
|
102
|
+
console.log(
|
|
103
|
+
approved === null
|
|
104
|
+
? `It waits for approval on the dashboard: ${url}`
|
|
105
|
+
: `It waits for approval or cancellation on the dashboard: ${url}`,
|
|
106
|
+
);
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
await agent.approve(record.id, { download });
|
|
110
|
+
console.log(download ? "Approved the full download." : "Approved.");
|
|
111
|
+
return true;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Follows a deployment until it finishes, printing its log and the states it goes through, and
|
|
116
|
+
* asking for approval when it waits on one. Reconnects from the last log line it printed. The
|
|
117
|
+
* exit code: 0 when it is ready, `awaitingApprovalExit` when it is left waiting; a failed or
|
|
118
|
+
* canceled deployment throws.
|
|
119
|
+
*/
|
|
120
|
+
export const followDeployment = async (
|
|
121
|
+
agent: AgentClient,
|
|
122
|
+
deployment: { id: string; url: string },
|
|
123
|
+
approval: Approval,
|
|
124
|
+
): Promise<number> => {
|
|
125
|
+
const seen: {
|
|
126
|
+
after: number;
|
|
127
|
+
state: DeploymentRecord["state"] | null;
|
|
128
|
+
approval: string | null;
|
|
129
|
+
failures: number;
|
|
130
|
+
} = { after: 0, state: null, approval: null, failures: 0 };
|
|
131
|
+
|
|
132
|
+
/** The exit code once the deployment is done with this command, else undefined. */
|
|
133
|
+
const onRecord = async (record: DeploymentRecord) => {
|
|
134
|
+
if (record.state !== seen.state) {
|
|
135
|
+
seen.state = record.state;
|
|
136
|
+
const message = stateMessage(record);
|
|
137
|
+
if (message) {
|
|
138
|
+
console.log(message);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (record.state !== "awaitingApproval" || !record.approval) {
|
|
142
|
+
seen.approval = null;
|
|
143
|
+
} else {
|
|
144
|
+
const asked = `${record.approval.reason}: ${record.approval.message}`;
|
|
145
|
+
if (asked !== seen.approval) {
|
|
146
|
+
seen.approval = asked;
|
|
147
|
+
console.log(record.approval.message);
|
|
148
|
+
const approved = await approve(agent, record, record.approval.reason, {
|
|
149
|
+
url: deployment.url,
|
|
150
|
+
approval,
|
|
151
|
+
});
|
|
152
|
+
if (!approved) {
|
|
153
|
+
return awaitingApprovalExit;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (record.state === "ready") {
|
|
158
|
+
const { health } = record;
|
|
159
|
+
console.log(
|
|
160
|
+
health
|
|
161
|
+
? `Ready: controller ${health.controller}, server ${health.server}, PLC ${health.plc}.${health.detail ? ` ${health.detail}` : ""}`
|
|
162
|
+
: "Ready.",
|
|
163
|
+
);
|
|
164
|
+
return 0;
|
|
165
|
+
}
|
|
166
|
+
if (record.state === "error") {
|
|
167
|
+
throw new Error(
|
|
168
|
+
`The deployment failed: ${record.error?.message ?? "no reason given"}. ${deployment.url}`,
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
if (record.state === "canceled") {
|
|
172
|
+
throw new Error(`The deployment was canceled. ${deployment.url}`);
|
|
173
|
+
}
|
|
174
|
+
return undefined;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
while (true) {
|
|
178
|
+
try {
|
|
179
|
+
for await (const event of agent.deploymentEvents(
|
|
180
|
+
deployment.id,
|
|
181
|
+
seen.after,
|
|
182
|
+
)) {
|
|
183
|
+
seen.failures = 0;
|
|
184
|
+
if (event.kind === "record") {
|
|
185
|
+
const exit = await onRecord(event.record);
|
|
186
|
+
if (exit !== undefined) {
|
|
187
|
+
return exit;
|
|
188
|
+
}
|
|
189
|
+
} else if (event.line.seq > seen.after) {
|
|
190
|
+
seen.after = event.line.seq;
|
|
191
|
+
progress(
|
|
192
|
+
event.line.level === "info"
|
|
193
|
+
? event.line.message
|
|
194
|
+
: `${event.line.level}: ${event.line.message}`,
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
} catch (error) {
|
|
199
|
+
if (!(error instanceof AgentUnreachable)) {
|
|
200
|
+
throw error;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
// The stream broke, or ended before the deployment finished.
|
|
204
|
+
seen.failures += 1;
|
|
205
|
+
if (seen.failures > reconnectAttempts) {
|
|
206
|
+
throw new Error(
|
|
207
|
+
`Lost the connection to the plant agent; the deployment goes on: ${deployment.url}`,
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
await Bun.sleep(reconnectDelay);
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
/** Prints a queued deployment's page, then follows it when asked to. */
|
|
215
|
+
const queued = async (
|
|
216
|
+
agent: AgentClient,
|
|
217
|
+
created: { id: string; url: string },
|
|
218
|
+
follow: Follow,
|
|
219
|
+
) => {
|
|
220
|
+
console.log(`Deployment ${created.id} queued: ${created.url}`);
|
|
221
|
+
if (!follow.wait) {
|
|
222
|
+
return 0;
|
|
223
|
+
}
|
|
224
|
+
return followDeployment(agent, created, follow.approval);
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
/** Uploads a built release as a queued deployment and prints its page. */
|
|
228
|
+
export const submitDeployment = async (
|
|
229
|
+
agent: AgentClient,
|
|
230
|
+
release: Parameters<AgentClient["queueDeployment"]>[0],
|
|
231
|
+
settings: Omit<DeployOptions, "deployment">,
|
|
232
|
+
request: { mode: DeploymentMode; git: GitSource | null },
|
|
233
|
+
follow: Follow,
|
|
234
|
+
) => {
|
|
235
|
+
const uploading = timedProgress();
|
|
236
|
+
const created = await agent.queueDeployment(
|
|
237
|
+
release,
|
|
238
|
+
{ ...settings, deployment: request },
|
|
239
|
+
uploading,
|
|
240
|
+
);
|
|
241
|
+
uploading("Uploaded");
|
|
242
|
+
if (request.mode === "review" && !follow.wait) {
|
|
243
|
+
console.log("Once reviewed, it waits for approval on its page.");
|
|
244
|
+
}
|
|
245
|
+
return queued(agent, created, follow);
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
/** The deployments `GET /api/deployments` answers, newest first, with the running and last healthy ones. */
|
|
249
|
+
type DeploymentList = Awaited<ReturnType<AgentClient["deployments"]>>;
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Where `tsplc rollback` goes without an id: the newest deployment before the running one that
|
|
253
|
+
* ran healthy with another release. Without a running one, the last healthy one.
|
|
254
|
+
*/
|
|
255
|
+
export const rollbackTarget = ({
|
|
256
|
+
deployments,
|
|
257
|
+
current,
|
|
258
|
+
lastGood,
|
|
259
|
+
}: DeploymentList) => {
|
|
260
|
+
const index = deployments.findIndex(({ id }) => id === current);
|
|
261
|
+
const running = deployments[index];
|
|
262
|
+
if (!running) {
|
|
263
|
+
return deployments.find(({ id }) => id === lastGood);
|
|
264
|
+
}
|
|
265
|
+
return deployments
|
|
266
|
+
.slice(index + 1)
|
|
267
|
+
.find(
|
|
268
|
+
(deployment) =>
|
|
269
|
+
deployment.state === "ready" &&
|
|
270
|
+
deployment.activeFrom !== null &&
|
|
271
|
+
deployment.release !== running.release,
|
|
272
|
+
);
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
const age = (from: string, now: number) => {
|
|
276
|
+
const seconds = Math.max(0, Math.round((now - Date.parse(from)) / 1000));
|
|
277
|
+
if (seconds < 60) {
|
|
278
|
+
return `${seconds}s`;
|
|
279
|
+
}
|
|
280
|
+
if (seconds < 3600) {
|
|
281
|
+
return `${Math.floor(seconds / 60)}m`;
|
|
282
|
+
}
|
|
283
|
+
if (seconds < 48 * 3600) {
|
|
284
|
+
return `${Math.floor(seconds / 3600)}h`;
|
|
285
|
+
}
|
|
286
|
+
return `${Math.floor(seconds / 86400)}d`;
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
const commitLabel = (git: GitSource | null) =>
|
|
290
|
+
git ? `${git.commit.slice(0, 7)}${git.dirty ? "*" : ""}` : "-";
|
|
291
|
+
|
|
292
|
+
const requester = ({ requestedBy }: DeploymentRecord) =>
|
|
293
|
+
requestedBy.user && requestedBy.host
|
|
294
|
+
? `${requestedBy.user}@${requestedBy.host}`
|
|
295
|
+
: (requestedBy.user ?? requestedBy.identity.name);
|
|
296
|
+
|
|
297
|
+
/** `tsplc deployments`: the agent's deployments, newest first, or as JSON. */
|
|
298
|
+
export const printDeployments = async (
|
|
299
|
+
agent: AgentClient,
|
|
300
|
+
flags: { format?: "json" | "text" },
|
|
301
|
+
) => {
|
|
302
|
+
const list = await agent.deployments();
|
|
303
|
+
if (flags.format === "json") {
|
|
304
|
+
console.log(JSON.stringify({ ok: true, ...list }));
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
if (!list.deployments.length) {
|
|
308
|
+
console.log("No deployments yet.");
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
const now = Date.now();
|
|
312
|
+
const header = ["ID", "STATE", "AGE", "RELEASE", "COMMIT", "BY", ""];
|
|
313
|
+
const rows = [
|
|
314
|
+
header,
|
|
315
|
+
...list.deployments.map((deployment) => [
|
|
316
|
+
deployment.id,
|
|
317
|
+
deployment.state,
|
|
318
|
+
age(deployment.createdAt, now),
|
|
319
|
+
deployment.release,
|
|
320
|
+
commitLabel(deployment.git),
|
|
321
|
+
requester(deployment),
|
|
322
|
+
[
|
|
323
|
+
deployment.id === list.current ? "current" : "",
|
|
324
|
+
deployment.id === list.lastGood ? "last good" : "",
|
|
325
|
+
]
|
|
326
|
+
.filter(Boolean)
|
|
327
|
+
.join(", "),
|
|
328
|
+
]),
|
|
329
|
+
];
|
|
330
|
+
const widths = header.map((_, column) =>
|
|
331
|
+
Math.max(...rows.map((row) => row[column]?.length ?? 0)),
|
|
332
|
+
);
|
|
333
|
+
for (const row of rows) {
|
|
334
|
+
console.log(
|
|
335
|
+
row
|
|
336
|
+
.map((cell, column) => cell.padEnd(widths[column] ?? 0))
|
|
337
|
+
.join(" ")
|
|
338
|
+
.trimEnd(),
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
/** `tsplc rollback [id]`: deploys that deployment's release again, by default the last good one before the running one. */
|
|
344
|
+
export const rollBack = async (
|
|
345
|
+
agent: AgentClient,
|
|
346
|
+
id: string | undefined,
|
|
347
|
+
follow: Follow,
|
|
348
|
+
) => {
|
|
349
|
+
const target = id ?? rollbackTarget(await agent.deployments())?.id;
|
|
350
|
+
if (!target) {
|
|
351
|
+
throw new Error(
|
|
352
|
+
"No earlier healthy deployment to roll back to; name one: tsplc rollback <id>",
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
console.log(`Rolling back to ${target}…`);
|
|
356
|
+
return queued(agent, await agent.rollback(target), follow);
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
/** `tsplc redeploy <id>`: deploys that deployment's release again. */
|
|
360
|
+
export const redeploy = async (
|
|
361
|
+
agent: AgentClient,
|
|
362
|
+
id: string,
|
|
363
|
+
mode: DeploymentMode,
|
|
364
|
+
follow: Follow,
|
|
365
|
+
) => queued(agent, await agent.redeploy(id, mode), follow);
|
|
366
|
+
|
|
367
|
+
/** The command that opens a URL in the desktop's browser, by platform. */
|
|
368
|
+
const openers: Partial<Record<NodeJS.Platform, string[]>> = {
|
|
369
|
+
darwin: ["open"],
|
|
370
|
+
win32: ["cmd", "/c", "start", ""],
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
/** `tsplc dashboard`: prints the agent's dashboard, and opens it when someone is at the terminal. */
|
|
374
|
+
export const openDashboard = (agent: AgentClient, interactive: boolean) => {
|
|
375
|
+
const url = new URL("/", agent.url).href;
|
|
376
|
+
console.log(url);
|
|
377
|
+
if (!interactive) {
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
const [command = "xdg-open", ...args] = openers[process.platform] ?? [
|
|
381
|
+
"xdg-open",
|
|
382
|
+
];
|
|
383
|
+
// Without a desktop to open it on, the printed URL is the answer.
|
|
384
|
+
spawn(command, [...args, url], { stdio: "ignore", detached: true })
|
|
385
|
+
.on("error", () => {})
|
|
386
|
+
.unref();
|
|
387
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ParseArgsOptionsConfig, parseArgs } from "node:util";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
/** The flags `options` declares, as `parseArgs` reads them. */
|
|
5
|
+
export type Flags<Options extends ParseArgsOptionsConfig> = ReturnType<
|
|
6
|
+
typeof parseArgs<{ options: Options }>
|
|
7
|
+
>["values"];
|
|
8
|
+
|
|
9
|
+
/** A flag that takes no value. */
|
|
10
|
+
export const flag = { type: "boolean" } as const;
|
|
11
|
+
|
|
12
|
+
/** `--format`: JSON results on standard output, or text. */
|
|
13
|
+
export const outputFormatSchema = z.enum(["json", "text"]);
|
|
14
|
+
export type OutputFormat = z.infer<typeof outputFormatSchema>;
|
|
@@ -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
|
+
};
|