@tsplc/tmp-agent 0.0.0-stage → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +26 -2
  2. package/dist/cli.js +4888 -0
  3. package/dist/cli.js.map +53 -0
  4. package/dist/client.js +514 -0
  5. package/dist/client.js.map +12 -0
  6. package/dist/index.js +3680 -0
  7. package/dist/index.js.map +41 -0
  8. package/package.json +61 -4
  9. package/src/access.ts +260 -0
  10. package/src/agent.ts +461 -0
  11. package/src/audit.ts +74 -0
  12. package/src/cli.ts +290 -0
  13. package/src/client.ts +407 -0
  14. package/src/codesys.ts +195 -0
  15. package/src/dashboard/index.ts +159 -0
  16. package/src/dashboard/ui/access.ts +191 -0
  17. package/src/dashboard/ui/actions.ts +207 -0
  18. package/src/dashboard/ui/api.ts +138 -0
  19. package/src/dashboard/ui/app.ts +41 -0
  20. package/src/dashboard/ui/approval.ts +131 -0
  21. package/src/dashboard/ui/audit.ts +115 -0
  22. package/src/dashboard/ui/contract.ts +19 -0
  23. package/src/dashboard/ui/dashboard.css +1332 -0
  24. package/src/dashboard/ui/deployment.ts +431 -0
  25. package/src/dashboard/ui/deployments.ts +319 -0
  26. package/src/dashboard/ui/details.ts +214 -0
  27. package/src/dashboard/ui/dom.ts +87 -0
  28. package/src/dashboard/ui/environment.ts +345 -0
  29. package/src/dashboard/ui/format.ts +124 -0
  30. package/src/dashboard/ui/logs.ts +126 -0
  31. package/src/dashboard/ui/main.ts +88 -0
  32. package/src/dashboard/ui/overlay.ts +144 -0
  33. package/src/dashboard/ui/shell.ts +185 -0
  34. package/src/dashboard/ui/source.ts +144 -0
  35. package/src/debugging.ts +142 -0
  36. package/src/deploy.ts +203 -0
  37. package/src/deployments/health.ts +98 -0
  38. package/src/deployments/retention.ts +44 -0
  39. package/src/deployments/routes.ts +281 -0
  40. package/src/deployments/runner.ts +900 -0
  41. package/src/deployments/store.ts +209 -0
  42. package/src/deployments/submission.ts +78 -0
  43. package/src/discovery.ts +90 -0
  44. package/src/environment.ts +214 -0
  45. package/src/errors.ts +12 -0
  46. package/src/index.ts +36 -0
  47. package/src/instance.ts +51 -0
  48. package/src/login.ts +267 -0
  49. package/src/logs.ts +115 -0
  50. package/src/maintenance.ts +303 -0
  51. package/src/operations.ts +149 -0
  52. package/src/processes.ts +41 -0
  53. package/src/protocol.ts +557 -0
  54. package/src/releases.ts +414 -0
  55. package/src/restarts.ts +96 -0
  56. package/src/routes.ts +128 -0
  57. package/src/secrets.ts +174 -0
  58. package/src/server-process.ts +264 -0
  59. package/src/service.ts +194 -0
  60. package/src/sessions.ts +58 -0
  61. package/src/state.ts +126 -0
  62. package/src/tailscale.ts +112 -0
  63. package/src/terminal.ts +57 -0
  64. package/src/transfer.ts +94 -0
  65. package/src/upgrade.ts +153 -0
package/src/deploy.ts ADDED
@@ -0,0 +1,203 @@
1
+ import {
2
+ controllerBaseline,
3
+ type ResetKind,
4
+ restartWarmController,
5
+ reviewWarmController,
6
+ settleWarmController,
7
+ startWarmController,
8
+ updateWarmController,
9
+ } from "@tsplc/build";
10
+ import {
11
+ type CodesysSettings,
12
+ deployContainer,
13
+ deployedControllerConfig,
14
+ ensureGateway,
15
+ removeContainer,
16
+ requireBuilder,
17
+ } from "./codesys";
18
+ import type { Debugging } from "./debugging";
19
+ import {
20
+ createDeploymentRunner,
21
+ type DeploymentController,
22
+ } from "./deployments/runner";
23
+ import { openDeploymentStore } from "./deployments/store";
24
+ import {
25
+ checkSubmission,
26
+ clientWarnings,
27
+ submissionFrom,
28
+ } from "./deployments/submission";
29
+ import { AgentError, errorMessage } from "./errors";
30
+ import type { Login } from "./login";
31
+ import type { Operations } from "./operations";
32
+ import type { ClientIdentity, ClientRelease, Identity } from "./protocol";
33
+ import type { DeployRequest } from "./releases";
34
+ import { controllerCredentials, readSecrets } from "./secrets";
35
+ import type { ServerSupervisor } from "./server-process";
36
+ import type { AgentState } from "./state";
37
+
38
+ /**
39
+ * Deployments of uploaded releases: a download or online change through the CODESYS that stays
40
+ * running between them, then the release's server once the controller has its program.
41
+ */
42
+ export const createDeployments = async (context: {
43
+ state: AgentState;
44
+ operations: Operations;
45
+ codesys: CodesysSettings;
46
+ server: ServerSupervisor;
47
+ debugging: Debugging;
48
+ login: Pick<Login, "isOpen" | "restart">;
49
+ now: () => Date;
50
+ log: (message: string) => void;
51
+ }) => {
52
+ const { state } = context;
53
+
54
+ /** CODESYS starts for the deployed release in the background, so the first deployment finds it running. */
55
+ const warming = (async () => {
56
+ const config = await deployedControllerConfig(state, context.codesys);
57
+ if (!config) {
58
+ return;
59
+ }
60
+ await requireBuilder();
61
+ await ensureGateway();
62
+ await startWarmController(config, deployContainer);
63
+ })().catch((error: unknown) => {
64
+ context.log(`Starting CODESYS failed: ${errorMessage(error)}`);
65
+ });
66
+
67
+ /** Starts the gateway, and waits for CODESYS to have started for the deployed release. */
68
+ const warmed = async () => {
69
+ await ensureGateway();
70
+ await warming;
71
+ };
72
+
73
+ const controller: DeploymentController = {
74
+ ready: async () => {
75
+ const builder = await requireBuilder();
76
+ if (await context.login.isOpen()) {
77
+ throw new AgentError(
78
+ "A login is open; log out before deploying: tsplc logout",
79
+ 409,
80
+ );
81
+ }
82
+ return builder.kind === "unverified"
83
+ ? [
84
+ `${builder.reason}. Run tsplc-agent setup on the plant PC once to rebuild and label it`,
85
+ ]
86
+ : [];
87
+ },
88
+ settle: (config) => settleWarmController(config, deployContainer),
89
+ baseline: () => controllerBaseline(state.paths.controller),
90
+ review: async (config, options) => {
91
+ await warmed();
92
+ return reviewWarmController(config, deployContainer, options);
93
+ },
94
+ // The previous server keeps running until the controller has the new program, so a failed
95
+ // transfer leaves both as they were.
96
+ apply: async (config, operation, options) => {
97
+ await warmed();
98
+ return updateWarmController(config, deployContainer, operation, options);
99
+ },
100
+ };
101
+
102
+ const runner = createDeploymentRunner({
103
+ store: await openDeploymentStore({
104
+ directory: state.paths.deploymentRecords,
105
+ now: context.now,
106
+ log: context.log,
107
+ }),
108
+ state,
109
+ operations: context.operations,
110
+ codesys: context.codesys,
111
+ server: context.server,
112
+ controller,
113
+ onActivated: () => context.debugging.restart(),
114
+ now: context.now,
115
+ log: context.log,
116
+ });
117
+ await runner.start();
118
+
119
+ return {
120
+ runner,
121
+ /**
122
+ * Resets the deployed application and starts it again, as the agent's one operation: through
123
+ * the open login when there is one, which a deployment would also wait for, else through the
124
+ * CODESYS that stays running for deployments, so it takes seconds and needs no login.
125
+ */
126
+ restart: (reset: ResetKind) =>
127
+ context.operations.exclusive("a controller restart", async () => {
128
+ if (await context.login.isOpen()) {
129
+ return context.login.restart(reset);
130
+ }
131
+ const config = await deployedControllerConfig(state, context.codesys);
132
+ if (!config) {
133
+ throw new AgentError(
134
+ "Nothing is deployed to the controller yet",
135
+ 409,
136
+ );
137
+ }
138
+ await requireBuilder();
139
+ await warmed();
140
+ return restartWarmController(config, deployContainer, reset, {
141
+ credentials: await controllerCredentials(null),
142
+ });
143
+ }),
144
+ /**
145
+ * Stops the warm container once it has committed the last deployment, so an upgraded agent
146
+ * starts one running its own code and none keeps the installed package's files in use.
147
+ */
148
+ retire: async () => {
149
+ await warming;
150
+ const config = await deployedControllerConfig(state, context.codesys);
151
+ if (config) {
152
+ await settleWarmController(config, deployContainer);
153
+ }
154
+ await removeContainer(deployContainer);
155
+ },
156
+ /**
157
+ * `POST /deploy`: runs a deployment at once and streams its progress, as clients from before
158
+ * `/api/deployments` expect. One that needs a download fails, for the client to ask again.
159
+ */
160
+ deploy: async (
161
+ /** Reads the upload once the client's version is checked, so a mismatch is reported before a large body is read. */
162
+ readRequest: () => Promise<DeployRequest>,
163
+ identity: Identity,
164
+ client: ClientIdentity,
165
+ clientTsplc: ClientRelease,
166
+ ) => {
167
+ const warnings = await clientWarnings(clientTsplc);
168
+ context.operations.requireIdle();
169
+ runner.requireIdle();
170
+ await requireBuilder();
171
+ const { settings, upload } = await readRequest();
172
+ await checkSubmission(state, settings.credentials);
173
+ // A missing secret fails before anything stops.
174
+ await readSecrets(upload.manifest.secrets);
175
+ return context.operations.stream(
176
+ "a deployment",
177
+ (emit) =>
178
+ runner.runNow(
179
+ upload,
180
+ // It runs at once, whatever mode the upload asks to be queued in.
181
+ {
182
+ ...submissionFrom(settings, identity, client, warnings),
183
+ mode: "apply",
184
+ },
185
+ (line) => {
186
+ // The failure itself ends the stream as its error.
187
+ if (line.level === "error") {
188
+ return;
189
+ }
190
+ emit({
191
+ kind: "progress",
192
+ message:
193
+ line.level === "warning"
194
+ ? `Warning: ${line.message}`
195
+ : line.message,
196
+ });
197
+ },
198
+ ),
199
+ { reportsRollback: clientTsplc.version !== undefined },
200
+ );
201
+ },
202
+ };
203
+ };
@@ -0,0 +1,98 @@
1
+ import { healthReplySchema } from "@tsplc/server/plant-agent";
2
+ import { errorMessage } from "../errors";
3
+ import type { DeploymentRecord } from "../protocol";
4
+ import type { ServerSupervisor } from "../server-process";
5
+
6
+ type Health = NonNullable<DeploymentRecord["health"]>;
7
+
8
+ /** The server's and the PLC's health, and why the server failed its check. */
9
+ interface ServerHealth extends Pick<Health, "server" | "plc"> {
10
+ failure: string | null;
11
+ }
12
+
13
+ const healthTimeoutMs = 5000;
14
+
15
+ /** Anything but tsPLC's health reply on the server's health route leaves the PLC unknown. */
16
+ const plcHealth = (body: unknown): Health["plc"] => {
17
+ const parsed = healthReplySchema.safeParse(body);
18
+ if (!parsed.success) {
19
+ return "unknown";
20
+ }
21
+ return parsed.data.plcConnected ? "ok" : "failed";
22
+ };
23
+
24
+ const serverHealth = async (
25
+ server: ServerSupervisor,
26
+ ): Promise<ServerHealth> => {
27
+ const { healthUrl } = server;
28
+ if (healthUrl === null) {
29
+ return server.status()?.running
30
+ ? { server: "ok", plc: "unknown", failure: null }
31
+ : {
32
+ server: "failed",
33
+ plc: "unknown",
34
+ failure: "The server isn't running",
35
+ };
36
+ }
37
+ const response = await fetch(healthUrl, {
38
+ signal: AbortSignal.timeout(healthTimeoutMs),
39
+ }).catch((error: unknown) => errorMessage(error));
40
+ if (typeof response === "string") {
41
+ return {
42
+ server: "failed",
43
+ plc: "unknown",
44
+ failure: `The server doesn't answer on ${healthUrl}: ${response}`,
45
+ };
46
+ }
47
+ if (!response.ok) {
48
+ return {
49
+ server: "failed",
50
+ plc: "unknown",
51
+ failure: `The server answers ${response.status} on ${healthUrl}`,
52
+ };
53
+ }
54
+ return {
55
+ server: "ok",
56
+ plc: plcHealth(await response.json().catch(() => null)),
57
+ failure: null,
58
+ };
59
+ };
60
+
61
+ const noServer: ServerHealth = {
62
+ server: "none",
63
+ plc: "unknown",
64
+ failure: null,
65
+ };
66
+
67
+ /**
68
+ * The check after a deployment applied: the controller runs its application, the release's server
69
+ * answers, and the server reaches the PLC.
70
+ */
71
+ export const checkHealth = async (options: {
72
+ /** The application's state in the controller's receipt. */
73
+ controllerState: string;
74
+ /** The release has a server, which the agent started. */
75
+ hasServer: boolean;
76
+ server: ServerSupervisor;
77
+ }): Promise<Health> => {
78
+ const controller = options.controllerState === "run" ? "ok" : "failed";
79
+ const { server, plc, failure } = options.hasServer
80
+ ? await serverHealth(options.server)
81
+ : noServer;
82
+ const problems = [
83
+ controller === "failed" &&
84
+ `The controller's application is in state ${options.controllerState}`,
85
+ failure,
86
+ plc === "failed" && "The server isn't connected to the PLC",
87
+ ].filter((problem) => typeof problem === "string");
88
+ return {
89
+ controller,
90
+ server,
91
+ plc,
92
+ detail: problems.length ? problems.join(". ") : null,
93
+ };
94
+ };
95
+
96
+ /** Whether a deployment with this health counts as ready; a server still connecting to the PLC doesn't fail it. */
97
+ export const healthy = (health: Health) =>
98
+ health.controller === "ok" && health.server !== "failed";
@@ -0,0 +1,44 @@
1
+ import type { Release } from "../protocol";
2
+ import { pruneReleases, serverReleaseId } from "../releases";
3
+ import { activeDeployments, type DeploymentStore, isFinished } from "./store";
4
+
5
+ /** Every deployment created within this long is kept. */
6
+ export const retentionMs = 14 * 24 * 60 * 60 * 1000;
7
+
8
+ /**
9
+ * Deletes the deployments created before the retention window, except the running one, the last
10
+ * healthy one and any not yet finished, then every release that no kept deployment and not the
11
+ * deployed release names. The deployed release's server may be an earlier release's.
12
+ */
13
+ export const pruneDeployments = async (options: {
14
+ store: DeploymentStore;
15
+ releases: string;
16
+ deployed: Release | null;
17
+ now: () => Date;
18
+ }) => {
19
+ const { store } = options;
20
+ const records = store.list();
21
+ const { current, lastGood } = activeDeployments(records);
22
+ const cutoff = options.now().getTime() - retentionMs;
23
+ const expired = records.filter(
24
+ (record) =>
25
+ Date.parse(record.createdAt) < cutoff &&
26
+ record.id !== current &&
27
+ record.id !== lastGood &&
28
+ isFinished(record),
29
+ );
30
+ for (const record of expired) {
31
+ await store.remove(record.id);
32
+ }
33
+ const kept = new Set(store.list().map((record) => record.release));
34
+ if (options.deployed) {
35
+ kept.add(options.deployed.id);
36
+ if (options.deployed.server) {
37
+ kept.add(serverReleaseId(options.deployed.server));
38
+ }
39
+ }
40
+ return {
41
+ deployments: expired.map((record) => record.id),
42
+ releases: await pruneReleases(options.releases, kept),
43
+ };
44
+ };
@@ -0,0 +1,281 @@
1
+ import { z } from "zod";
2
+ import {
3
+ approveSchema,
4
+ clientIdentity,
5
+ clientRelease,
6
+ type DeploymentEvent,
7
+ type DeploymentLogLine,
8
+ type DeploymentRecord,
9
+ type deploymentCreatedSchema,
10
+ type deploymentListSchema,
11
+ deploymentPagePath,
12
+ type deploymentSourceSchema,
13
+ deploymentsApiPath,
14
+ redeploySchema,
15
+ } from "../protocol";
16
+ import { type ReleaseStore, readDeployRequest } from "../releases";
17
+ import type { ApiRoute } from "../routes";
18
+ import type { DeploymentRunner } from "./runner";
19
+ import { isFinished } from "./store";
20
+ import { clientWarnings, requester, submissionFrom } from "./submission";
21
+
22
+ /** Server-sent events stay open through proxies that close a silent connection. */
23
+ const heartbeatMs = 15_000;
24
+
25
+ /** `?after=`, or the `Last-Event-ID` an `EventSource` reconnects with: the last log line it has. */
26
+ const afterSchema = z.coerce.number().int().nonnegative();
27
+
28
+ const after = (request: Request) =>
29
+ afterSchema.parse(
30
+ new URL(request.url).searchParams.get("after") ??
31
+ request.headers.get("last-event-id") ??
32
+ 0,
33
+ );
34
+
35
+ /** An open event stream's progress. */
36
+ interface EventStreamState {
37
+ open: boolean;
38
+ /** The last log line sent. */
39
+ sent: number;
40
+ /** The log is being replayed; changes heard meanwhile wait in `held` until it has been. */
41
+ replaying: boolean;
42
+ held: DeploymentEvent[];
43
+ stop: () => void;
44
+ }
45
+
46
+ /** A param the route's pattern names, which a matched request always has. */
47
+ const param = (params: Readonly<Record<string, string>>, name: string) => {
48
+ const value = params[name];
49
+ if (value === undefined) {
50
+ throw new Error(`The route's pattern has no ${name}`);
51
+ }
52
+ return value;
53
+ };
54
+
55
+ /**
56
+ * The record, then its log after `from`, then each change until the deployment finishes, which
57
+ * ends the stream with the finished record.
58
+ */
59
+ const eventStream = (runner: DeploymentRunner, id: string, from: number) => {
60
+ const initial = runner.get(id);
61
+ const encoder = new TextEncoder();
62
+ const stream: EventStreamState = {
63
+ open: true,
64
+ sent: from,
65
+ replaying: true,
66
+ held: [],
67
+ stop: () => {},
68
+ };
69
+ return new Response(
70
+ new ReadableStream({
71
+ start: async (controller) => {
72
+ const write = (text: string) => {
73
+ if (stream.open) {
74
+ controller.enqueue(encoder.encode(text));
75
+ }
76
+ };
77
+ const sendLine = (line: DeploymentLogLine) => {
78
+ if (line.seq <= stream.sent) {
79
+ return;
80
+ }
81
+ stream.sent = line.seq;
82
+ write(
83
+ `id: ${line.seq}\nevent: log\ndata: ${JSON.stringify(line)}\n\n`,
84
+ );
85
+ };
86
+ const end = () => {
87
+ if (stream.open) {
88
+ stream.stop();
89
+ controller.close();
90
+ }
91
+ };
92
+ const sendRecord = (record: DeploymentRecord) =>
93
+ write(`event: record\ndata: ${JSON.stringify(record)}\n\n`);
94
+ /** Sends the lines still on their way to disk, then the finished record last, and ends. */
95
+ const finish = () =>
96
+ runner.lines(id, stream.sent).then((lines) => {
97
+ lines.forEach(sendLine);
98
+ sendRecord(runner.get(id));
99
+ end();
100
+ }, end);
101
+ const deliver = (event: DeploymentEvent) => {
102
+ if (event.kind === "log") {
103
+ sendLine(event.line);
104
+ return;
105
+ }
106
+ if (isFinished(event.record)) {
107
+ void finish();
108
+ return;
109
+ }
110
+ sendRecord(event.record);
111
+ };
112
+ const unsubscribe = runner.subscribe(id, (event) => {
113
+ if (stream.replaying) {
114
+ stream.held.push(event);
115
+ return;
116
+ }
117
+ deliver(event);
118
+ });
119
+ const heartbeat = setInterval(
120
+ () => write(": heartbeat\n\n"),
121
+ heartbeatMs,
122
+ );
123
+ stream.stop = () => {
124
+ stream.open = false;
125
+ clearInterval(heartbeat);
126
+ unsubscribe();
127
+ };
128
+ // A finished deployment's record comes once, after its log.
129
+ if (!isFinished(initial)) {
130
+ sendRecord(initial);
131
+ }
132
+ (await runner.lines(id, from)).forEach(sendLine);
133
+ stream.replaying = false;
134
+ stream.held.splice(0).forEach(deliver);
135
+ if (isFinished(runner.get(id))) {
136
+ void finish();
137
+ }
138
+ },
139
+ cancel: () => stream.stop(),
140
+ }),
141
+ {
142
+ headers: {
143
+ "Content-Type": "text/event-stream",
144
+ "Cache-Control": "no-cache",
145
+ },
146
+ },
147
+ );
148
+ };
149
+
150
+ /** The deployments API the dashboard and `tsplc deploy` use: `/api/deployments` and below. */
151
+ export const createDeploymentRoutes = (context: {
152
+ runner: DeploymentRunner;
153
+ releases: ReleaseStore;
154
+ }): ApiRoute[] => {
155
+ const { runner } = context;
156
+ const created = (request: Request, record: DeploymentRecord) =>
157
+ Response.json(
158
+ {
159
+ id: record.id,
160
+ url: `${new URL(request.url).origin}${deploymentPagePath(record.id)}`,
161
+ } satisfies z.infer<typeof deploymentCreatedSchema>,
162
+ { status: 202 },
163
+ );
164
+ const id = (params: Readonly<Record<string, string>>) => param(params, "id");
165
+ return [
166
+ {
167
+ method: "POST",
168
+ pattern: deploymentsApiPath,
169
+ role: "deployer",
170
+ handle: async (request, { identity }) => {
171
+ const warnings = await clientWarnings(clientRelease(request));
172
+ const { settings, upload } = await readDeployRequest(
173
+ context.releases,
174
+ request,
175
+ );
176
+ const record = await runner.submit(
177
+ upload,
178
+ submissionFrom(settings, identity, clientIdentity(request), warnings),
179
+ );
180
+ return created(request, record);
181
+ },
182
+ },
183
+ {
184
+ method: "GET",
185
+ pattern: deploymentsApiPath,
186
+ role: "viewer",
187
+ handle: async () =>
188
+ Response.json(
189
+ runner.list() satisfies z.infer<typeof deploymentListSchema>,
190
+ ),
191
+ },
192
+ {
193
+ method: "GET",
194
+ pattern: `${deploymentsApiPath}/:id`,
195
+ role: "viewer",
196
+ handle: async (_request, { params }) =>
197
+ Response.json(runner.get(id(params))),
198
+ },
199
+ {
200
+ method: "GET",
201
+ pattern: `${deploymentsApiPath}/:id/logs`,
202
+ role: "viewer",
203
+ handle: async (request, { params }) =>
204
+ Response.json({
205
+ lines: await runner.lines(id(params), after(request)),
206
+ }),
207
+ },
208
+ {
209
+ method: "GET",
210
+ pattern: `${deploymentsApiPath}/:id/events`,
211
+ role: "viewer",
212
+ handle: async (request, { params }) =>
213
+ eventStream(runner, id(params), after(request)),
214
+ },
215
+ {
216
+ method: "POST",
217
+ pattern: `${deploymentsApiPath}/:id/approve`,
218
+ role: "deployer",
219
+ handle: async (request, { identity, params }) => {
220
+ const { download } = approveSchema.parse(await request.json());
221
+ return Response.json(
222
+ await runner.approve(id(params), { download }, identity.name),
223
+ );
224
+ },
225
+ },
226
+ {
227
+ method: "POST",
228
+ pattern: `${deploymentsApiPath}/:id/cancel`,
229
+ role: "deployer",
230
+ handle: async (_request, { identity, params }) =>
231
+ Response.json(await runner.cancel(id(params), identity.name)),
232
+ },
233
+ {
234
+ method: "POST",
235
+ pattern: `${deploymentsApiPath}/:id/redeploy`,
236
+ role: "deployer",
237
+ handle: async (request, { identity, params }) => {
238
+ const { mode } = redeploySchema.parse(await request.json());
239
+ return created(
240
+ request,
241
+ await runner.redeploy(
242
+ id(params),
243
+ mode,
244
+ requester(identity, clientIdentity(request)),
245
+ ),
246
+ );
247
+ },
248
+ },
249
+ {
250
+ method: "POST",
251
+ pattern: `${deploymentsApiPath}/:id/rollback`,
252
+ role: "deployer",
253
+ handle: async (request, { identity, params }) =>
254
+ created(
255
+ request,
256
+ await runner.rollback(
257
+ id(params),
258
+ requester(identity, clientIdentity(request)),
259
+ ),
260
+ ),
261
+ },
262
+ {
263
+ method: "GET",
264
+ pattern: `${deploymentsApiPath}/:id/source`,
265
+ role: "viewer",
266
+ handle: async (_request, { params }) =>
267
+ Response.json({
268
+ files: await runner.source(id(params)),
269
+ } satisfies z.infer<typeof deploymentSourceSchema>),
270
+ },
271
+ {
272
+ method: "GET",
273
+ pattern: `${deploymentsApiPath}/:id/source/*`,
274
+ role: "viewer",
275
+ handle: async (_request, { params }) =>
276
+ new Response(await runner.sourceFile(id(params), param(params, "*")), {
277
+ headers: { "Content-Type": "text/plain; charset=utf-8" },
278
+ }),
279
+ },
280
+ ];
281
+ };