@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/dist/client.js ADDED
@@ -0,0 +1,514 @@
1
+ // packages/agent/src/client.ts
2
+ import { hostname, userInfo } from "node:os";
3
+ import {
4
+ loginResultSchema,
5
+ workerScriptsDigest
6
+ } from "@tsplc/build";
7
+ import { plantVariablesSchema } from "@tsplc/config";
8
+ import { parseEventStream } from "@tsplc/debug/api";
9
+ import {
10
+ controllerRestartPath,
11
+ controllerRestartReplySchema,
12
+ refusalMessage
13
+ } from "@tsplc/server/plant-agent";
14
+ import { z as z2 } from "zod";
15
+
16
+ // packages/agent/src/protocol.ts
17
+ import {
18
+ controllerCredentialsSchema,
19
+ controllerIdsSchema,
20
+ loginStateSchema,
21
+ onlineChangeFindingSchema,
22
+ rollbackSchema
23
+ } from "@tsplc/build";
24
+ import { plainValue, secretValue, tsplcConfigSchema } from "@tsplc/config";
25
+ import { envName, releaseConfigSchema, tcpPort } from "@tsplc/config/build";
26
+ import { z } from "zod";
27
+ // packages/agent/package.json
28
+ var version = "0.6.2";
29
+
30
+ // packages/agent/src/protocol.ts
31
+ var tsplcVersion = version;
32
+ var targetSchema = z.strictObject({
33
+ host: z.string().nonempty(),
34
+ port: tcpPort
35
+ });
36
+ var networkInterfaceSchema = z.strictObject({
37
+ name: z.string(),
38
+ address: z.ipv4(),
39
+ prefixLength: z.number().int().min(0).max(32)
40
+ });
41
+ var discoveredControllerSchema = z.strictObject({
42
+ address: z.ipv4(),
43
+ port: z.number().int(),
44
+ hostname: z.string().nullable()
45
+ });
46
+ var discoverSchema = z.strictObject({ name: z.string() });
47
+ var variableSchema = z.strictObject({
48
+ path: z.string(),
49
+ type: z.string()
50
+ });
51
+ var targetValuesSchema = z.record(envName, z.string());
52
+ var releaseManifestSchema = z.strictObject({
53
+ config: z.record(z.string(), z.unknown()).superRefine((config, context) => {
54
+ const release = releaseConfigSchema.safeParse(config);
55
+ if (!release.success) {
56
+ context.addIssue({
57
+ code: "custom",
58
+ message: `Invalid release config: ${z.prettifyError(release.error)}`
59
+ });
60
+ }
61
+ }),
62
+ variables: z.array(variableSchema),
63
+ server: z.string().nonempty().optional(),
64
+ debug: tsplcConfigSchema.shape.debug,
65
+ serverTokenEnv: z.string().nonempty().optional(),
66
+ secrets: tsplcConfigSchema.shape.secrets,
67
+ values: targetValuesSchema.default({})
68
+ });
69
+ var gitSourceSchema = z.strictObject({
70
+ commit: z.string().nonempty(),
71
+ branch: z.string().nullable(),
72
+ dirty: z.boolean(),
73
+ message: z.string().nullable()
74
+ });
75
+ var deploymentModeSchema = z.enum(["apply", "review"]);
76
+ var deploymentRequestSchema = z.strictObject({
77
+ mode: deploymentModeSchema,
78
+ git: gitSourceSchema.nullable()
79
+ });
80
+ var deployOptionsSchema = z.strictObject({
81
+ credentials: controllerCredentialsSchema.nullable(),
82
+ download: z.boolean(),
83
+ initializeUser: z.boolean(),
84
+ deployment: deploymentRequestSchema.optional()
85
+ }).refine((options) => options.credentials || !options.initializeUser, "Initializing the controller's user needs the user's credentials.");
86
+ var releaseBuckets = 256;
87
+ var shortHex = z.string().regex(/^[a-f0-9]{16}$/);
88
+ var compareRequestSchema = z.strictObject({
89
+ buckets: z.array(shortHex).length(releaseBuckets)
90
+ });
91
+ var comparisonSchema = z.strictObject({
92
+ base: shortHex.nullable(),
93
+ changed: z.array(z.strictObject({
94
+ bucket: z.number().int().min(0).max(releaseBuckets - 1),
95
+ files: z.record(z.string(), shortHex)
96
+ }))
97
+ });
98
+ var releaseUploadType = "application/vnd.tsplc.release+zstd";
99
+ var releaseUploadSchema = z.strictObject({
100
+ manifest: releaseManifestSchema,
101
+ options: deployOptionsSchema,
102
+ base: shortHex.nullable(),
103
+ buckets: compareRequestSchema.shape.buckets,
104
+ remove: z.array(z.string())
105
+ });
106
+ var eventSchema = z.discriminatedUnion("kind", [
107
+ z.strictObject({ kind: z.literal("progress"), message: z.string() }),
108
+ z.strictObject({ kind: z.literal("done"), result: z.unknown() }),
109
+ z.strictObject({
110
+ kind: z.literal("error"),
111
+ message: z.string(),
112
+ downloadRequired: z.boolean(),
113
+ rollback: rollbackSchema.optional()
114
+ })
115
+ ]);
116
+ var deployOperationSchema = z.enum(["download", "online-change"]);
117
+ var releaseSchema = z.strictObject({
118
+ id: z.string(),
119
+ deployedAt: z.iso.datetime(),
120
+ operation: deployOperationSchema,
121
+ controllerIds: controllerIdsSchema,
122
+ server: z.string().optional()
123
+ });
124
+ var statusSchema = z.strictObject({
125
+ target: targetSchema.nullable(),
126
+ release: releaseSchema.nullable(),
127
+ server: z.strictObject({ executable: z.string(), running: z.boolean() }).nullable(),
128
+ login: z.union([loginStateSchema, z.strictObject({ error: z.string() })]).nullable(),
129
+ credentialsStored: z.boolean()
130
+ });
131
+ var statusPath = "/status";
132
+ var agentHoldPath = "/agent/hold";
133
+ var agentExitPath = "/agent/exit";
134
+ var exitSchema = z.strictObject({
135
+ server: z.enum(["leave", "stop"]),
136
+ restart: z.boolean()
137
+ });
138
+ var logoutSchema = z.strictObject({ failure: z.string().optional() });
139
+ var clientHeaders = {
140
+ user: "x-tsplc-user",
141
+ host: "x-tsplc-host",
142
+ version: "x-tsplc-version",
143
+ scripts: "x-tsplc-scripts"
144
+ };
145
+ var agentVersionHeader = "x-tsplc-agent-version";
146
+ var atLeast = (version, minimum) => {
147
+ const parts = version.split(/[.+-]/).slice(0, 3).map(Number);
148
+ for (const [index, wanted] of minimum.entries()) {
149
+ const part = parts[index] ?? 0;
150
+ if (part !== wanted) {
151
+ return part > wanted;
152
+ }
153
+ }
154
+ return true;
155
+ };
156
+ var upgradesItself = (version) => version !== null && atLeast(version, [0, 5, 0]);
157
+ var versionMismatch = (versions) => `The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : "a tsPLC older than 0.3.0"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match: on the plant PC, run ${versions.agentUpgrades ? `tsplc-agent upgrade ${versions.client}` : `bun add --global @tsplc/agent@${versions.client}, then restart tsplc-agent serve`}${versions.agent ? `, or deploy with tsPLC ${versions.agent}` : ""}`;
158
+ var deploymentSchema = z.strictObject({
159
+ at: z.iso.datetime(),
160
+ release: z.string(),
161
+ build: z.string().optional(),
162
+ operation: deployOperationSchema,
163
+ credentials: z.enum(["provided", "stored"]).optional(),
164
+ user: z.string().optional(),
165
+ host: z.string().optional()
166
+ });
167
+ var auditSchema = z.strictObject({
168
+ at: z.iso.datetime(),
169
+ command: z.string(),
170
+ values: z.record(z.string(), z.string()),
171
+ previous: z.record(z.string(), z.string()).optional(),
172
+ user: z.string().optional(),
173
+ host: z.string().optional(),
174
+ release: z.string().optional(),
175
+ error: z.string().optional()
176
+ });
177
+ var roles = ["viewer", "deployer", "admin"];
178
+ var roleSchema = z.enum(roles);
179
+ var identitySchema = z.strictObject({
180
+ login: z.string().nullable(),
181
+ name: z.string(),
182
+ role: roleSchema,
183
+ via: z.enum(["tailscale", "token", "local", "server"])
184
+ });
185
+ var deploymentStateSchema = z.enum([
186
+ "queued",
187
+ "building",
188
+ "awaitingApproval",
189
+ "applying",
190
+ "starting",
191
+ "verifying",
192
+ "ready",
193
+ "error",
194
+ "canceled"
195
+ ]);
196
+ var deploymentPhaseNameSchema = z.enum([
197
+ "queue",
198
+ "build",
199
+ "review",
200
+ "apply",
201
+ "server",
202
+ "health"
203
+ ]);
204
+ var deploymentIdSchema = z.string().regex(/^dpl_[a-z0-9]{16,32}$/);
205
+ var deploymentRecordSchema = z.strictObject({
206
+ id: deploymentIdSchema,
207
+ release: z.string(),
208
+ build: z.string().nullable(),
209
+ createdAt: z.iso.datetime(),
210
+ updatedAt: z.iso.datetime(),
211
+ origin: z.discriminatedUnion("kind", [
212
+ z.strictObject({ kind: z.literal("upload") }),
213
+ z.strictObject({ kind: z.literal("redeploy"), from: deploymentIdSchema }),
214
+ z.strictObject({ kind: z.literal("rollback"), from: deploymentIdSchema })
215
+ ]),
216
+ git: gitSourceSchema.nullable(),
217
+ requestedBy: z.strictObject({
218
+ identity: identitySchema.omit({ role: true }),
219
+ user: z.string().nullable(),
220
+ host: z.string().nullable()
221
+ }),
222
+ mode: deploymentModeSchema,
223
+ operation: deployOperationSchema,
224
+ state: deploymentStateSchema,
225
+ phases: z.array(z.strictObject({
226
+ name: deploymentPhaseNameSchema,
227
+ startedAt: z.iso.datetime(),
228
+ finishedAt: z.iso.datetime().nullable(),
229
+ outcome: z.enum(["running", "ok", "failed", "skipped"])
230
+ })),
231
+ findings: z.array(onlineChangeFindingSchema),
232
+ approval: z.strictObject({
233
+ reason: z.enum(["review", "downloadRequired"]),
234
+ message: z.string()
235
+ }).nullable(),
236
+ error: z.strictObject({
237
+ message: z.string(),
238
+ downloadRequired: z.boolean(),
239
+ rollback: rollbackSchema.optional()
240
+ }).nullable(),
241
+ controllerIds: controllerIdsSchema.nullable(),
242
+ health: z.strictObject({
243
+ controller: z.enum(["ok", "failed"]),
244
+ server: z.enum(["ok", "failed", "none"]),
245
+ plc: z.enum(["ok", "failed", "unknown"]),
246
+ detail: z.string().nullable()
247
+ }).nullable(),
248
+ activeFrom: z.iso.datetime().nullable(),
249
+ activeUntil: z.iso.datetime().nullable()
250
+ });
251
+ var deploymentLogLineSchema = z.strictObject({
252
+ seq: z.number().int().positive(),
253
+ at: z.iso.datetime(),
254
+ level: z.enum(["info", "warning", "error"]),
255
+ phase: deploymentPhaseNameSchema.nullable(),
256
+ message: z.string()
257
+ });
258
+ var deploymentsApiPath = "/api/deployments";
259
+ var deploymentApiPath = (id) => `${deploymentsApiPath}/${encodeURIComponent(id)}`;
260
+ var deploymentCreatedSchema = z.strictObject({
261
+ id: deploymentIdSchema,
262
+ url: z.string()
263
+ });
264
+ var deploymentListSchema = z.strictObject({
265
+ deployments: z.array(deploymentRecordSchema),
266
+ current: deploymentIdSchema.nullable(),
267
+ lastGood: deploymentIdSchema.nullable()
268
+ });
269
+ var approveSchema = z.strictObject({ download: z.boolean() });
270
+ var redeploySchema = z.strictObject({ mode: deploymentModeSchema });
271
+ var deploymentSourceSchema = z.strictObject({
272
+ files: z.array(z.strictObject({ path: z.string(), size: z.number().int().nonnegative() }))
273
+ });
274
+ var environmentEntrySchema = z.strictObject({
275
+ name: z.string(),
276
+ declared: z.boolean(),
277
+ set: z.boolean()
278
+ });
279
+ var environmentSchema = z.strictObject({
280
+ values: targetValuesSchema,
281
+ variables: z.record(envName, z.string()),
282
+ secrets: z.array(environmentEntrySchema)
283
+ });
284
+ var accessConfigSchema = z.strictObject({
285
+ roles: z.record(z.string().nonempty(), roleSchema),
286
+ tailnetDefault: roleSchema.nullable()
287
+ });
288
+ var sessionRequestSchema = z.strictObject({ token: z.string() });
289
+ var environmentValueSchema = z.discriminatedUnion("secret", [
290
+ z.strictObject({ secret: z.literal(false), value: plainValue }),
291
+ z.strictObject({ secret: z.literal(true), value: secretValue })
292
+ ]);
293
+
294
+ // packages/agent/src/transfer.ts
295
+ import { createHash } from "node:crypto";
296
+ var shortDigest = (data) => createHash("sha256").update(data).digest("hex").slice(0, 16);
297
+ var fileBucket = (path) => createHash("sha256").update(path).digest().readUInt8(0) % releaseBuckets;
298
+ var bucketDigests = (files) => {
299
+ const buckets = Array.from({ length: releaseBuckets }, () => []);
300
+ for (const { path, digest } of files) {
301
+ buckets[fileBucket(path)]?.push(`${path}\x00${digest}`);
302
+ }
303
+ return buckets.map((entries) => shortDigest(entries.sort().join(`
304
+ `)));
305
+ };
306
+ var lengthBytes = 4;
307
+ var encodeUpload = async (header, files) => {
308
+ const encoder = new TextEncoder;
309
+ const frames = [
310
+ encoder.encode(JSON.stringify(header)),
311
+ ...files.flatMap(({ path, content }) => [encoder.encode(path), content])
312
+ ];
313
+ const body = new Uint8Array(frames.reduce((total, frame) => total + lengthBytes + frame.length, 0));
314
+ const view = new DataView(body.buffer);
315
+ let offset = 0;
316
+ for (const frame of frames) {
317
+ view.setUint32(offset, frame.length);
318
+ body.set(frame, offset + lengthBytes);
319
+ offset += lengthBytes + frame.length;
320
+ }
321
+ return new Uint8Array(await Bun.zstdCompress(body, { level: 12 }));
322
+ };
323
+
324
+ // packages/agent/src/client.ts
325
+ class AgentOperationError extends Error {
326
+ downloadRequired;
327
+ rollback;
328
+ constructor(message, {
329
+ downloadRequired = false,
330
+ rollback
331
+ } = {}) {
332
+ super(message);
333
+ this.downloadRequired = downloadRequired;
334
+ this.rollback = rollback;
335
+ }
336
+ }
337
+
338
+ class AgentUnreachable extends Error {
339
+ }
340
+ async function* bodyText(body) {
341
+ try {
342
+ yield* body.pipeThrough(new TextDecoderStream);
343
+ } catch (cause) {
344
+ throw new AgentUnreachable("The connection to the agent broke", { cause });
345
+ }
346
+ }
347
+ var createAgentClient = (options) => {
348
+ const identity = workerScriptsDigest().then((scripts) => ({ [clientHeaders.scripts]: scripts }), () => ({})).then((scripts) => ({
349
+ [clientHeaders.user]: userInfo().username,
350
+ [clientHeaders.host]: hostname(),
351
+ [clientHeaders.version]: tsplcVersion,
352
+ ...scripts
353
+ }));
354
+ const call = async (path, init = {}) => {
355
+ const response = await fetch(new URL(path, options.url), {
356
+ ...init,
357
+ headers: {
358
+ ...init.headers,
359
+ ...await identity,
360
+ Authorization: `Bearer ${options.token}`
361
+ }
362
+ }).catch((cause) => {
363
+ throw new AgentUnreachable(`Cannot reach the plant agent at ${options.url}`, { cause });
364
+ });
365
+ if (!response.ok) {
366
+ throw new AgentOperationError(await refusalMessage(response));
367
+ }
368
+ return response;
369
+ };
370
+ const get = async (path, schema) => schema.parse(await (await call(path)).json());
371
+ const send = async (method, path, body, schema) => schema.parse(await (await call(path, {
372
+ method,
373
+ headers: { "Content-Type": "application/json" },
374
+ body: JSON.stringify(body)
375
+ })).json());
376
+ const operation = async (response, onProgress) => {
377
+ const reader = response.body?.pipeThrough(new TextDecoderStream).getReader();
378
+ if (!reader) {
379
+ throw new Error("The agent returned no operation stream");
380
+ }
381
+ let buffered = "";
382
+ while (true) {
383
+ const { done, value } = await reader.read();
384
+ if (done) {
385
+ throw new Error("The agent closed the operation without a result");
386
+ }
387
+ buffered += value;
388
+ const lines = buffered.split(`
389
+ `);
390
+ buffered = lines.pop() ?? "";
391
+ for (const line of lines.filter(Boolean)) {
392
+ const event = eventSchema.parse(JSON.parse(line));
393
+ if (event.kind === "progress") {
394
+ onProgress(event.message);
395
+ } else if (event.kind === "done") {
396
+ return event.result;
397
+ } else {
398
+ throw new AgentOperationError(event.message, {
399
+ downloadRequired: event.downloadRequired,
400
+ rollback: event.rollback
401
+ });
402
+ }
403
+ }
404
+ }
405
+ };
406
+ const compare = (buckets) => send("POST", "/releases/compare", { buckets }, comparisonSchema);
407
+ const upload = async (release, settings, onProgress) => {
408
+ const agentVersion = (await call(statusPath)).headers.get(agentVersionHeader);
409
+ if (agentVersion !== tsplcVersion) {
410
+ throw new AgentOperationError(versionMismatch({
411
+ agent: agentVersion,
412
+ client: tsplcVersion,
413
+ agentUpgrades: upgradesItself(agentVersion)
414
+ }));
415
+ }
416
+ const files = await Promise.all(release.files.map(async ({ path, content }) => ({
417
+ path,
418
+ content: await content.bytes()
419
+ })));
420
+ const digests = files.map(({ path, content }) => ({
421
+ path,
422
+ digest: shortDigest(content)
423
+ }));
424
+ const buckets = bucketDigests(digests);
425
+ return releaseUpload({ manifest: release.manifest, options: settings, buckets }, files, await compare(buckets), onProgress);
426
+ };
427
+ return {
428
+ url: options.url,
429
+ status: () => get(statusPath, statusSchema),
430
+ interfaces: () => get("/interfaces", z2.array(networkInterfaceSchema)),
431
+ discover: (name) => send("POST", "/discover", { name }, z2.array(discoveredControllerSchema)),
432
+ setTarget: (target) => send("PUT", "/target", target, targetSchema),
433
+ variables: () => get("/variables", z2.array(variableSchema)),
434
+ deploy: async (release, settings, onProgress) => {
435
+ const body = await upload(release, settings, onProgress);
436
+ return releaseSchema.parse(await operation(await call("/deploy", { method: "POST", ...body }), onProgress));
437
+ },
438
+ queueDeployment: async (release, settings, onProgress) => {
439
+ const body = await upload(release, settings, onProgress);
440
+ return deploymentCreatedSchema.parse(await (await call(deploymentsApiPath, { method: "POST", ...body })).json());
441
+ },
442
+ deployments: () => get(deploymentsApiPath, deploymentListSchema),
443
+ deploymentEvents: async function* (id, after) {
444
+ const response = await call(`${deploymentApiPath(id)}/events?after=${after}`, { headers: { Accept: "text/event-stream" } });
445
+ if (!response.body) {
446
+ throw new AgentUnreachable("The agent returned no event stream");
447
+ }
448
+ for await (const event of parseEventStream(bodyText(response.body))) {
449
+ if (event.event === "record") {
450
+ yield {
451
+ kind: "record",
452
+ record: deploymentRecordSchema.parse(JSON.parse(event.data))
453
+ };
454
+ } else if (event.event === "log") {
455
+ yield {
456
+ kind: "log",
457
+ line: deploymentLogLineSchema.parse(JSON.parse(event.data))
458
+ };
459
+ }
460
+ }
461
+ },
462
+ approve: async (id, approval) => {
463
+ await call(`${deploymentApiPath(id)}/approve`, {
464
+ method: "POST",
465
+ headers: { "Content-Type": "application/json" },
466
+ body: JSON.stringify(approval)
467
+ });
468
+ },
469
+ redeploy: (id, mode) => send("POST", `${deploymentApiPath(id)}/redeploy`, { mode }, deploymentCreatedSchema),
470
+ rollback: (id) => send("POST", `${deploymentApiPath(id)}/rollback`, {}, deploymentCreatedSchema),
471
+ releaseVariables: (service) => get(`/api/environment/release${service === null ? "" : `?${new URLSearchParams({ service })}`}`, plantVariablesSchema),
472
+ restartController: (restart) => send("POST", controllerRestartPath, restart, controllerRestartReplySchema),
473
+ login: async (credentials, onProgress) => loginResultSchema.parse(await operation(await call("/login", {
474
+ method: "POST",
475
+ headers: { "Content-Type": "application/json" },
476
+ body: JSON.stringify(credentials)
477
+ }), onProgress)),
478
+ command: (command) => send("POST", "/login/command", command, loginResultSchema),
479
+ logout: () => send("DELETE", "/login", undefined, logoutSchema),
480
+ hold: async () => {
481
+ await call(agentHoldPath, { method: "POST" });
482
+ },
483
+ releaseHold: async () => {
484
+ await call(agentHoldPath, { method: "DELETE" });
485
+ },
486
+ exit: async (exit) => {
487
+ await call(agentExitPath, {
488
+ method: "POST",
489
+ headers: { "Content-Type": "application/json" },
490
+ body: JSON.stringify(exit)
491
+ });
492
+ }
493
+ };
494
+ };
495
+ var releaseUpload = async (header, files, { base, changed }, onProgress) => {
496
+ const stored = new Map(changed.map(({ bucket, files }) => [bucket, files]));
497
+ const uploaded = base === null ? files : files.filter(({ path, content }) => {
498
+ const held = stored.get(fileBucket(path));
499
+ return held !== undefined && held[path] !== shortDigest(content);
500
+ });
501
+ const paths = new Set(files.map(({ path }) => path));
502
+ const remove = [...stored.values()].flatMap((held) => Object.keys(held).filter((path) => !paths.has(path)));
503
+ const body = await encodeUpload({ ...header, base, remove }, uploaded);
504
+ onProgress(`Uploading ${uploaded.length} of ${files.length} files (${Math.ceil(body.length / 1024)} KB)`);
505
+ return { headers: { "Content-Type": releaseUploadType }, body };
506
+ };
507
+ export {
508
+ AgentOperationError,
509
+ AgentUnreachable,
510
+ createAgentClient
511
+ };
512
+
513
+ //# debugId=A21C4BD3F466B69464756E2164756E21
514
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1,12 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/client.ts", "../src/protocol.ts", "../src/transfer.ts"],
4
+ "sourcesContent": [
5
+ "import { hostname, userInfo } from \"node:os\";\nimport {\n\ttype LoginCommand,\n\tloginResultSchema,\n\ttype Rollback,\n\tworkerScriptsDigest,\n} from \"@tsplc/build\";\nimport { plantVariablesSchema } from \"@tsplc/config\";\nimport { parseEventStream } from \"@tsplc/debug/api\";\nimport {\n\ttype ControllerRestart,\n\tcontrollerRestartPath,\n\tcontrollerRestartReplySchema,\n\trefusalMessage,\n} from \"@tsplc/server/plant-agent\";\nimport { z } from \"zod\";\nimport {\n\ttype AgentExit,\n\tagentExitPath,\n\tagentHoldPath,\n\tagentVersionHeader,\n\ttype Comparison,\n\ttype Credentials,\n\tclientHeaders,\n\tcomparisonSchema,\n\ttype DeploymentEvent,\n\ttype DeploymentMode,\n\ttype DeployOptions,\n\tdeploymentApiPath,\n\tdeploymentCreatedSchema,\n\tdeploymentListSchema,\n\tdeploymentLogLineSchema,\n\tdeploymentRecordSchema,\n\tdeploymentsApiPath,\n\tdiscoveredControllerSchema,\n\teventSchema,\n\tlogoutSchema,\n\tnetworkInterfaceSchema,\n\ttype ReleaseManifest,\n\ttype ReleaseUpload,\n\treleaseSchema,\n\treleaseUploadType,\n\tstatusPath,\n\tstatusSchema,\n\ttype Target,\n\ttargetSchema,\n\ttsplcVersion,\n\tupgradesItself,\n\tvariableSchema,\n\tversionMismatch,\n} from \"./protocol\";\nimport {\n\tbucketDigests,\n\tencodeUpload,\n\tfileBucket,\n\ttype ReleaseContent,\n\tshortDigest,\n} from \"./transfer\";\n\n/**\n * A failed agent operation; `downloadRequired` means only a full download can deploy, and\n * `rollback` what became of the controller after a download failed mid-transfer.\n */\nexport class AgentOperationError extends Error {\n\treadonly downloadRequired: boolean;\n\treadonly rollback: Rollback | undefined;\n\n\tconstructor(\n\t\tmessage: string,\n\t\t{\n\t\t\tdownloadRequired = false,\n\t\t\trollback,\n\t\t}: { downloadRequired?: boolean; rollback?: Rollback } = {},\n\t) {\n\t\tsuper(message);\n\t\tthis.downloadRequired = downloadRequired;\n\t\tthis.rollback = rollback;\n\t}\n}\n\n/** The agent can't be reached, or the connection to it broke; trying again may succeed. */\nexport class AgentUnreachable extends Error {}\n\nexport type { DeploymentEvent };\n\n/** A response body's text as it arrives; a broken connection throws `AgentUnreachable`. */\nasync function* bodyText(body: NonNullable<Response[\"body\"]>) {\n\ttry {\n\t\tyield* body.pipeThrough(new TextDecoderStream());\n\t} catch (cause) {\n\t\tthrow new AgentUnreachable(\"The connection to the agent broke\", { cause });\n\t}\n}\n\n/** A file to upload, at its path in the release. */\nexport interface ReleaseFile {\n\tpath: string;\n\tcontent: Blob;\n}\n\n/** Talks to a plant agent at `url`, such as its Tailscale name and port. */\nexport const createAgentClient = (options: { url: string; token: string }) => {\n\t// The agent records who deployed and who changed the controller, and refuses another tsPLC version.\n\tconst identity = workerScriptsDigest()\n\t\t.then(\n\t\t\t(scripts) => ({ [clientHeaders.scripts]: scripts }),\n\t\t\t// The digest only tells local builds apart; an installation that can't read its scripts still deploys.\n\t\t\t() => ({}),\n\t\t)\n\t\t.then((scripts) => ({\n\t\t\t[clientHeaders.user]: userInfo().username,\n\t\t\t[clientHeaders.host]: hostname(),\n\t\t\t[clientHeaders.version]: tsplcVersion,\n\t\t\t...scripts,\n\t\t}));\n\tconst call = async (path: string, init: RequestInit = {}) => {\n\t\tconst response = await fetch(new URL(path, options.url), {\n\t\t\t...init,\n\t\t\theaders: {\n\t\t\t\t...init.headers,\n\t\t\t\t...(await identity),\n\t\t\t\tAuthorization: `Bearer ${options.token}`,\n\t\t\t},\n\t\t}).catch((cause: unknown) => {\n\t\t\tthrow new AgentUnreachable(\n\t\t\t\t`Cannot reach the plant agent at ${options.url}`,\n\t\t\t\t{ cause },\n\t\t\t);\n\t\t});\n\t\tif (!response.ok) {\n\t\t\tthrow new AgentOperationError(await refusalMessage(response));\n\t\t}\n\t\treturn response;\n\t};\n\tconst get = async <T>(path: string, schema: z.ZodType<T>) =>\n\t\tschema.parse(await (await call(path)).json());\n\tconst send = async <T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody: unknown,\n\t\tschema: z.ZodType<T>,\n\t) =>\n\t\tschema.parse(\n\t\t\tawait (\n\t\t\t\tawait call(path, {\n\t\t\t\t\tmethod,\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\t})\n\t\t\t).json(),\n\t\t);\n\n\t/** Reads a streamed operation, reporting progress, until its result or failure. */\n\tconst operation = async (\n\t\tresponse: Response,\n\t\tonProgress: (message: string) => void,\n\t) => {\n\t\tconst reader = response.body\n\t\t\t?.pipeThrough(new TextDecoderStream())\n\t\t\t.getReader();\n\t\tif (!reader) {\n\t\t\tthrow new Error(\"The agent returned no operation stream\");\n\t\t}\n\t\tlet buffered = \"\";\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tthrow new Error(\"The agent closed the operation without a result\");\n\t\t\t}\n\t\t\tbuffered += value;\n\t\t\tconst lines = buffered.split(\"\\n\");\n\t\t\tbuffered = lines.pop() ?? \"\";\n\t\t\tfor (const line of lines.filter(Boolean)) {\n\t\t\t\tconst event = eventSchema.parse(JSON.parse(line));\n\t\t\t\tif (event.kind === \"progress\") {\n\t\t\t\t\tonProgress(event.message);\n\t\t\t\t} else if (event.kind === \"done\") {\n\t\t\t\t\treturn event.result;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new AgentOperationError(event.message, {\n\t\t\t\t\t\tdownloadRequired: event.downloadRequired,\n\t\t\t\t\t\trollback: event.rollback,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n\t/** What the agent holds of a release with these bucket digests. */\n\tconst compare = (buckets: string[]) =>\n\t\tsend(\"POST\", \"/releases/compare\", { buckets }, comparisonSchema);\n\n\t/**\n\t * The upload body of `release`, built on what the agent already holds. Refuses an agent of\n\t * another version first.\n\t */\n\tconst upload = async (\n\t\trelease: { manifest: ReleaseManifest; files: ReleaseFile[] },\n\t\tsettings: DeployOptions,\n\t\tonProgress: (message: string) => void,\n\t) => {\n\t\t// Before uploading: an agent of another version, including one from before version checks,\n\t\t// would compile the release with scripts this client doesn't expect.\n\t\tconst agentVersion = (await call(statusPath)).headers.get(\n\t\t\tagentVersionHeader,\n\t\t);\n\t\tif (agentVersion !== tsplcVersion) {\n\t\t\tthrow new AgentOperationError(\n\t\t\t\tversionMismatch({\n\t\t\t\t\tagent: agentVersion,\n\t\t\t\t\tclient: tsplcVersion,\n\t\t\t\t\tagentUpgrades: upgradesItself(agentVersion),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\tconst files = await Promise.all(\n\t\t\trelease.files.map(async ({ path, content }) => ({\n\t\t\t\tpath,\n\t\t\t\tcontent: await content.bytes(),\n\t\t\t})),\n\t\t);\n\t\tconst digests = files.map(({ path, content }) => ({\n\t\t\tpath,\n\t\t\tdigest: shortDigest(content),\n\t\t}));\n\t\tconst buckets = bucketDigests(digests);\n\t\treturn releaseUpload(\n\t\t\t{ manifest: release.manifest, options: settings, buckets },\n\t\t\tfiles,\n\t\t\tawait compare(buckets),\n\t\t\tonProgress,\n\t\t);\n\t};\n\n\treturn {\n\t\t/** The agent's address, where its dashboard is. */\n\t\turl: options.url,\n\t\tstatus: () => get(statusPath, statusSchema),\n\t\tinterfaces: () => get(\"/interfaces\", z.array(networkInterfaceSchema)),\n\t\tdiscover: (name: string) =>\n\t\t\tsend(\"POST\", \"/discover\", { name }, z.array(discoveredControllerSchema)),\n\t\tsetTarget: (target: Target) => send(\"PUT\", \"/target\", target, targetSchema),\n\t\tvariables: () => get(\"/variables\", z.array(variableSchema)),\n\t\t/** Deploys `release` at once, streaming its progress: `POST /deploy`. */\n\t\tdeploy: async (\n\t\t\trelease: { manifest: ReleaseManifest; files: ReleaseFile[] },\n\t\t\tsettings: DeployOptions,\n\t\t\tonProgress: (message: string) => void,\n\t\t) => {\n\t\t\tconst body = await upload(release, settings, onProgress);\n\t\t\treturn releaseSchema.parse(\n\t\t\t\tawait operation(\n\t\t\t\t\tawait call(\"/deploy\", { method: \"POST\", ...body }),\n\t\t\t\t\tonProgress,\n\t\t\t\t),\n\t\t\t);\n\t\t},\n\t\t/** Queues `release` as a deployment the agent runs on its own: `POST /api/deployments`. */\n\t\tqueueDeployment: async (\n\t\t\trelease: { manifest: ReleaseManifest; files: ReleaseFile[] },\n\t\t\tsettings: DeployOptions,\n\t\t\tonProgress: (message: string) => void,\n\t\t) => {\n\t\t\tconst body = await upload(release, settings, onProgress);\n\t\t\treturn deploymentCreatedSchema.parse(\n\t\t\t\tawait (\n\t\t\t\t\tawait call(deploymentsApiPath, { method: \"POST\", ...body })\n\t\t\t\t).json(),\n\t\t\t);\n\t\t},\n\t\tdeployments: () => get(deploymentsApiPath, deploymentListSchema),\n\t\t/**\n\t\t * A deployment's events from after log line `after`, until the agent ends the stream once\n\t\t * the deployment finishes. A broken connection throws `AgentUnreachable`.\n\t\t */\n\t\tdeploymentEvents: async function* (\n\t\t\tid: string,\n\t\t\tafter: number,\n\t\t): AsyncGenerator<DeploymentEvent> {\n\t\t\tconst response = await call(\n\t\t\t\t`${deploymentApiPath(id)}/events?after=${after}`,\n\t\t\t\t{ headers: { Accept: \"text/event-stream\" } },\n\t\t\t);\n\t\t\tif (!response.body) {\n\t\t\t\tthrow new AgentUnreachable(\"The agent returned no event stream\");\n\t\t\t}\n\t\t\tfor await (const event of parseEventStream(bodyText(response.body))) {\n\t\t\t\tif (event.event === \"record\") {\n\t\t\t\t\tyield {\n\t\t\t\t\t\tkind: \"record\",\n\t\t\t\t\t\trecord: deploymentRecordSchema.parse(JSON.parse(event.data)),\n\t\t\t\t\t};\n\t\t\t\t} else if (event.event === \"log\") {\n\t\t\t\t\tyield {\n\t\t\t\t\t\tkind: \"log\",\n\t\t\t\t\t\tline: deploymentLogLineSchema.parse(JSON.parse(event.data)),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t/** Approves a deployment that waits on a person, as a full download when `download`. */\n\t\tapprove: async (id: string, approval: { download: boolean }) => {\n\t\t\tawait call(`${deploymentApiPath(id)}/approve`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify(approval),\n\t\t\t});\n\t\t},\n\t\tredeploy: (id: string, mode: DeploymentMode) =>\n\t\t\tsend(\n\t\t\t\t\"POST\",\n\t\t\t\t`${deploymentApiPath(id)}/redeploy`,\n\t\t\t\t{ mode },\n\t\t\t\tdeploymentCreatedSchema,\n\t\t\t),\n\t\trollback: (id: string) =>\n\t\t\tsend(\n\t\t\t\t\"POST\",\n\t\t\t\t`${deploymentApiPath(id)}/rollback`,\n\t\t\t\t{},\n\t\t\t\tdeploymentCreatedSchema,\n\t\t\t),\n\t\t/**\n\t\t * The plant PC's plain variables, and the secrets it holds in `service`, or in the agent's\n\t\t * own service when null: what a release is built with.\n\t\t */\n\t\treleaseVariables: (service: string | null) =>\n\t\t\tget(\n\t\t\t\t`/api/environment/release${service === null ? \"\" : `?${new URLSearchParams({ service })}`}`,\n\t\t\t\tplantVariablesSchema,\n\t\t\t),\n\t\t/** Resets the controller's application and starts it again; answers once it runs. */\n\t\trestartController: (restart: ControllerRestart) =>\n\t\t\tsend(\n\t\t\t\t\"POST\",\n\t\t\t\tcontrollerRestartPath,\n\t\t\t\trestart,\n\t\t\t\tcontrollerRestartReplySchema,\n\t\t\t),\n\t\tlogin: async (\n\t\t\tcredentials: Credentials | null,\n\t\t\tonProgress: (message: string) => void,\n\t\t) =>\n\t\t\tloginResultSchema.parse(\n\t\t\t\tawait operation(\n\t\t\t\t\tawait call(\"/login\", {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\t\tbody: JSON.stringify(credentials),\n\t\t\t\t\t}),\n\t\t\t\t\tonProgress,\n\t\t\t\t),\n\t\t\t),\n\t\tcommand: (command: LoginCommand) =>\n\t\t\tsend(\"POST\", \"/login/command\", command, loginResultSchema),\n\t\tlogout: () => send(\"DELETE\", \"/login\", undefined, logoutSchema),\n\t\t/** Holds the agent for an upgrade, so it takes no operations; fails while one runs or a login is open. */\n\t\thold: async () => {\n\t\t\tawait call(agentHoldPath, { method: \"POST\" });\n\t\t},\n\t\t/** Lets a held agent take operations again. */\n\t\treleaseHold: async () => {\n\t\t\tawait call(agentHoldPath, { method: \"DELETE\" });\n\t\t},\n\t\t/** Makes the held agent exit. */\n\t\texit: async (exit: AgentExit) => {\n\t\t\tawait call(agentExitPath, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify(exit),\n\t\t\t});\n\t\t},\n\t};\n};\nexport type AgentClient = ReturnType<typeof createAgentClient>;\n\n/**\n * A release upload built on the release the agent compared it with: in each bucket that differs,\n * the files the agent lacks and the paths to drop. Without a base, every file.\n */\nconst releaseUpload = async (\n\theader: Pick<ReleaseUpload, \"manifest\" | \"options\" | \"buckets\">,\n\tfiles: readonly ReleaseContent[],\n\t{ base, changed }: Comparison,\n\tonProgress: (message: string) => void,\n) => {\n\tconst stored = new Map(changed.map(({ bucket, files }) => [bucket, files]));\n\tconst uploaded =\n\t\tbase === null\n\t\t\t? files\n\t\t\t: files.filter(({ path, content }) => {\n\t\t\t\t\tconst held = stored.get(fileBucket(path));\n\t\t\t\t\treturn held !== undefined && held[path] !== shortDigest(content);\n\t\t\t\t});\n\tconst paths = new Set(files.map(({ path }) => path));\n\tconst remove = [...stored.values()].flatMap((held) =>\n\t\tObject.keys(held).filter((path) => !paths.has(path)),\n\t);\n\tconst body = await encodeUpload(\n\t\t{ ...header, base, remove } satisfies ReleaseUpload,\n\t\tuploaded,\n\t);\n\tonProgress(\n\t\t`Uploading ${uploaded.length} of ${files.length} files (${Math.ceil(body.length / 1024)} KB)`,\n\t);\n\treturn { headers: { \"Content-Type\": releaseUploadType }, body };\n};\n",
6
+ "import {\n\tcontrollerCredentialsSchema,\n\tcontrollerIdsSchema,\n\tloginStateSchema,\n\tonlineChangeFindingSchema,\n\trollbackSchema,\n} from \"@tsplc/build\";\nimport { plainValue, secretValue, tsplcConfigSchema } from \"@tsplc/config\";\nimport { envName, releaseConfigSchema, tcpPort } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport { version } from \"../package.json\";\n\n/** The tsPLC version a client and the agent it deploys through must share. */\nexport const tsplcVersion = version;\n\n/** The controller the agent deploys to, as its runtime's TCP block driver address. */\nexport const targetSchema = z.strictObject({\n\thost: z.string().nonempty(),\n\tport: tcpPort,\n});\nexport type Target = z.infer<typeof targetSchema>;\n\nexport const networkInterfaceSchema = z.strictObject({\n\tname: z.string(),\n\taddress: z.ipv4(),\n\tprefixLength: z.number().int().min(0).max(32),\n});\nexport type NetworkInterface = z.infer<typeof networkInterfaceSchema>;\n\n/** A host on the scanned subnet that accepts connections on the CODESYS runtime port. */\nexport const discoveredControllerSchema = z.strictObject({\n\taddress: z.ipv4(),\n\tport: z.number().int(),\n\thostname: z.string().nullable(),\n});\nexport type DiscoveredController = z.infer<typeof discoveredControllerSchema>;\n\n/** `POST /discover`: the network interface to scan for controllers. */\nexport const discoverSchema = z.strictObject({ name: z.string() });\n\n/**\n * The controller's user, which the agent passes to CODESYS for one operation. A request sends\n * null instead to use the one stored on the agent's PC.\n */\nexport type Credentials = z.infer<typeof controllerCredentialsSchema>;\n\n/** A published leaf of the deployed program, as CODESYS expressions name it. */\nexport const variableSchema = z.strictObject({\n\tpath: z.string(),\n\ttype: z.string(),\n});\nexport type Variable = z.infer<typeof variableSchema>;\n\n/** A target's plain values, by variable name. */\nconst targetValuesSchema = z.record(envName, z.string());\n\n/**\n * What `tsplc deploy` uploads beside its files. `config` is the build config with paths\n * relative to the release: `st/`, `template.project` and `libraries/`.\n */\nexport const releaseManifestSchema = z.strictObject({\n\t// Checked against the owner's schema but kept as uploaded: the release id hashes the manifest.\n\tconfig: z.record(z.string(), z.unknown()).superRefine((config, context) => {\n\t\tconst release = releaseConfigSchema.safeParse(config);\n\t\tif (!release.success) {\n\t\t\tcontext.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tmessage: `Invalid release config: ${z.prettifyError(release.error)}`,\n\t\t\t});\n\t\t}\n\t}),\n\tvariables: z.array(variableSchema),\n\t/** The server executable's path in the release, when the project builds one. */\n\tserver: z.string().nonempty().optional(),\n\t/** The project's `debug` section; the program's debug manifest is the release's `debug.json`. */\n\tdebug: tsplcConfigSchema.shape.debug,\n\t/** The variable in the agent's environment holding the server's bearer token, for its telemetry and request trace. */\n\tserverTokenEnv: z.string().nonempty().optional(),\n\t/** The project's `secrets`, whose placeholders in the ST the agent fills in from Bun.secrets. */\n\tsecrets: tsplcConfigSchema.shape.secrets,\n\t/** The values of the target it was built for, which its server starts with; none in a release from before 0.5.12. */\n\tvalues: targetValuesSchema.default({}),\n});\nexport type ReleaseManifest = z.infer<typeof releaseManifestSchema>;\n\n/** How `tsplc deploy` compresses each file of a multipart upload, the only form agents without `POST /releases/compare` accept. */\nexport const uploadEncoding = \"gzip\";\n\n/** The commit a deployment was built from, when `tsplc deploy` ran in a git checkout. */\nexport const gitSourceSchema = z.strictObject({\n\tcommit: z.string().nonempty(),\n\tbranch: z.string().nullable(),\n\t/** Uncommitted changes went into the build. */\n\tdirty: z.boolean(),\n\t/** The commit's subject line. */\n\tmessage: z.string().nullable(),\n});\nexport type GitSource = z.infer<typeof gitSourceSchema>;\n\n/**\n * How a deployment applies: `apply` runs it as soon as it is its turn; `review` builds it and\n * checks what an online change would do, then waits for someone to approve it.\n */\nexport const deploymentModeSchema = z.enum([\"apply\", \"review\"]);\nexport type DeploymentMode = z.infer<typeof deploymentModeSchema>;\n\n/**\n * What `tsplc deploy` sends with a release to `POST /api/deployments`, in the upload's `options`\n * beside the existing deploy options.\n */\nexport const deploymentRequestSchema = z.strictObject({\n\tmode: deploymentModeSchema,\n\tgit: gitSourceSchema.nullable(),\n});\n\nexport const deployOptionsSchema = z\n\t.strictObject({\n\t\tcredentials: controllerCredentialsSchema.nullable(),\n\t\t/** A full download stops the application; without it only an online change is applied. */\n\t\tdownload: z.boolean(),\n\t\tinitializeUser: z.boolean(),\n\t\t/** How `POST /api/deployments` queues it; `POST /deploy` runs it at once and ignores this. */\n\t\tdeployment: deploymentRequestSchema.optional(),\n\t})\n\t.refine(\n\t\t(options) => options.credentials || !options.initializeUser,\n\t\t\"Initializing the controller's user needs the user's credentials.\",\n\t);\nexport type DeployOptions = z.infer<typeof deployOptionsSchema>;\n\n/** How many buckets a release's files fall into for `POST /releases/compare`. */\nexport const releaseBuckets = 256;\n\n/** A release id, or the start of a SHA-256 of content: 16 lowercase hex digits. */\nconst shortHex = z.string().regex(/^[a-f0-9]{16}$/);\n\n/** `POST /releases/compare`: the digest of each bucket of the release about to be deployed. */\nexport const compareRequestSchema = z.strictObject({\n\tbuckets: z.array(shortHex).length(releaseBuckets),\n});\n\n/**\n * Its answer: the stored release the upload can build on, and that release's files, by path and\n * digest, in each bucket that differs. Without a base the whole release is uploaded.\n */\nexport const comparisonSchema = z.strictObject({\n\tbase: shortHex.nullable(),\n\tchanged: z.array(\n\t\tz.strictObject({\n\t\t\tbucket: z\n\t\t\t\t.number()\n\t\t\t\t.int()\n\t\t\t\t.min(0)\n\t\t\t\t.max(releaseBuckets - 1),\n\t\t\tfiles: z.record(z.string(), shortHex),\n\t\t}),\n\t),\n});\nexport type Comparison = z.infer<typeof comparisonSchema>;\n\n/** A `POST /deploy` body in this form is one release upload rather than a multipart form. */\nexport const releaseUploadType = \"application/vnd.tsplc.release+zstd\";\n\n/**\n * A release upload's header. The release is `base`'s files without the `remove` paths, with the\n * uploaded files added or replacing theirs; `buckets` are the digests it must then have.\n */\nexport const releaseUploadSchema = z.strictObject({\n\tmanifest: releaseManifestSchema,\n\toptions: deployOptionsSchema,\n\tbase: shortHex.nullable(),\n\tbuckets: compareRequestSchema.shape.buckets,\n\tremove: z.array(z.string()),\n});\nexport type ReleaseUpload = z.infer<typeof releaseUploadSchema>;\n\n/** Long operations stream one of these per line. */\nexport const eventSchema = z.discriminatedUnion(\"kind\", [\n\tz.strictObject({ kind: z.literal(\"progress\"), message: z.string() }),\n\tz.strictObject({ kind: z.literal(\"done\"), result: z.unknown() }),\n\tz.strictObject({\n\t\tkind: z.literal(\"error\"),\n\t\tmessage: z.string(),\n\t\t/** The controller has no application from this agent yet, so only a full download can deploy. */\n\t\tdownloadRequired: z.boolean(),\n\t\t/**\n\t\t * What became of the controller after a download failed mid-transfer. Sent only to clients that\n\t\t * send their version, since earlier clients reject an event with fields they don't know.\n\t\t */\n\t\trollback: rollbackSchema.optional(),\n\t}),\n]);\nexport type AgentEvent = z.infer<typeof eventSchema>;\n\nconst deployOperationSchema = z.enum([\"download\", \"online-change\"]);\n\nexport const releaseSchema = z.strictObject({\n\tid: z.string(),\n\tdeployedAt: z.iso.datetime(),\n\toperation: deployOperationSchema,\n\tcontrollerIds: controllerIdsSchema,\n\t/** The running server executable, relative to the releases directory. */\n\tserver: z.string().optional(),\n});\nexport type Release = z.infer<typeof releaseSchema>;\n\nexport const statusSchema = z.strictObject({\n\ttarget: targetSchema.nullable(),\n\trelease: releaseSchema.nullable(),\n\tserver: z\n\t\t.strictObject({ executable: z.string(), running: z.boolean() })\n\t\t.nullable(),\n\t/** The open login's application state and forced expressions, or why it can't report them. */\n\tlogin: z\n\t\t.union([loginStateSchema, z.strictObject({ error: z.string() })])\n\t\t.nullable(),\n\t/** A controller user is stored on the agent's PC, so requests may leave theirs out. */\n\tcredentialsStored: z.boolean(),\n});\nexport type AgentStatus = z.infer<typeof statusSchema>;\n\n/** The agent's status, which names the agent's version even to a request it refuses. */\nexport const statusPath = \"/status\";\n\n/** `POST` holds the agent for an upgrade, so it takes no operations; `DELETE` lets it take them again. */\nexport const agentHoldPath = \"/agent/hold\";\n\n/** `POST`: a held agent exits, as `exitSchema` asks. */\nexport const agentExitPath = \"/agent/exit\";\n\n/**\n * How a held agent exits: leaving the line's server running for the next agent or stopping it,\n * and whether whatever started it should start it again.\n */\nexport const exitSchema = z.strictObject({\n\tserver: z.enum([\"leave\", \"stop\"]),\n\trestart: z.boolean(),\n});\nexport type AgentExit = z.infer<typeof exitSchema>;\n\n/** A logout's result: why the login couldn't log out, when its container had to be removed instead. */\nexport const logoutSchema = z.strictObject({ failure: z.string().optional() });\n\n/** Who ran a command, and with which tsPLC, as the client reports it in these headers. */\nexport const clientHeaders = {\n\tuser: \"x-tsplc-user\",\n\thost: \"x-tsplc-host\",\n\tversion: \"x-tsplc-version\",\n\t/** The client's `workerScriptsDigest`, which tells a local build from a release of its version. */\n\tscripts: \"x-tsplc-scripts\",\n} as const;\n\n/** The header each agent response names the agent's tsPLC version in; agents before 0.3.0 send none. */\nexport const agentVersionHeader = \"x-tsplc-agent-version\";\n\n/** Whether `version` is at least `minimum`, comparing major, minor and patch. */\nconst atLeast = (version: string, minimum: [number, number, number]) => {\n\tconst parts = version.split(/[.+-]/).slice(0, 3).map(Number);\n\tfor (const [index, wanted] of minimum.entries()) {\n\t\tconst part = parts[index] ?? 0;\n\t\tif (part !== wanted) {\n\t\t\treturn part > wanted;\n\t\t}\n\t}\n\treturn true;\n};\n\n/** Whether an agent of `version` has `tsplc-agent upgrade`, which arrived in 0.5.0. */\nexport const upgradesItself = (version: string | null) =>\n\tversion !== null && atLeast(version, [0, 5, 0]);\n\n/** Why a client and an agent of different tsPLC versions don't deploy, and what to do about it. */\nexport const versionMismatch = (versions: {\n\tagent: string | null;\n\tclient: string;\n\t/** The agent has `tsplc-agent upgrade`. */\n\tagentUpgrades: boolean;\n}) =>\n\t`The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : \"a tsPLC older than 0.3.0\"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match: on the plant PC, run ${versions.agentUpgrades ? `tsplc-agent upgrade ${versions.client}` : `bun add --global @tsplc/agent@${versions.client}, then restart tsplc-agent serve`}${versions.agent ? `, or deploy with tsPLC ${versions.agent}` : \"\"}`;\n\n/** Who sent a request, as the client reports it. */\nexport const clientIdentity = (request: Request) => {\n\tconst header = (name: string) =>\n\t\trequest.headers.get(name)?.slice(0, 200) || undefined;\n\treturn { user: header(clientHeaders.user), host: header(clientHeaders.host) };\n};\nexport type ClientIdentity = ReturnType<typeof clientIdentity>;\n\n/** The tsPLC a request's client runs, as it reports it; clients before 0.3.0 report none. */\nexport const clientRelease = (request: Request) => ({\n\tversion:\n\t\trequest.headers.get(clientHeaders.version)?.slice(0, 50) || undefined,\n\tscripts:\n\t\trequest.headers.get(clientHeaders.scripts)?.slice(0, 100) || undefined,\n});\nexport type ClientRelease = ReturnType<typeof clientRelease>;\n\n/** A line of the agent's `deployments.jsonl`. */\nexport const deploymentSchema = z.strictObject({\n\tat: z.iso.datetime(),\n\trelease: z.string(),\n\t/** The debug manifest's build id, when the release has one. */\n\tbuild: z.string().optional(),\n\toperation: deployOperationSchema,\n\t/** Whether the request sent the controller user or the agent used its stored one; lines from before 0.2.18 lack it. */\n\tcredentials: z.enum([\"provided\", \"stored\"]).optional(),\n\tuser: z.string().optional(),\n\thost: z.string().optional(),\n});\nexport type Deployment = z.infer<typeof deploymentSchema>;\n\n/** A line of the agent's `audit.jsonl`: a login command that changed the controller. */\nexport const auditSchema = z.strictObject({\n\tat: z.iso.datetime(),\n\t/** As typed after `tsplc`, such as `force` or `reset cold`. */\n\tcommand: z.string(),\n\t/** Expressions written or forced, with their values; unforced expressions map to \"\". */\n\tvalues: z.record(z.string(), z.string()),\n\t/** The values read just before the command, when the read succeeded. */\n\tprevious: z.record(z.string(), z.string()).optional(),\n\tuser: z.string().optional(),\n\thost: z.string().optional(),\n\trelease: z.string().optional(),\n\terror: z.string().optional(),\n});\nexport type Audit = z.infer<typeof auditSchema>;\n\n/**\n * Who may do what on the agent's dashboard and API, each role including the ones before it: a\n * viewer reads deployments, logs, the debugger and the audit log; a deployer also deploys,\n * approves, cancels, redeploys, rolls back and restarts the server; an admin also manages the\n * environment's secrets and who has which role.\n */\nexport const roles = [\"viewer\", \"deployer\", \"admin\"] as const;\nexport const roleSchema = z.enum(roles);\nexport type Role = z.infer<typeof roleSchema>;\n\nexport const allows = (role: Role, required: Role) =>\n\troles.indexOf(role) >= roles.indexOf(required);\n\n/** Who made a request, and how the agent knows. */\nexport const identitySchema = z.strictObject({\n\t/** The Tailscale login, or null for a token or a request from the agent's own PC. */\n\tlogin: z.string().nullable(),\n\t/** A name to show: the Tailscale display name, or how the token or PC is known. */\n\tname: z.string(),\n\trole: roleSchema,\n\t/** `server`: the deployed server, with the token the agent started it with. */\n\tvia: z.enum([\"tailscale\", \"token\", \"local\", \"server\"]),\n});\nexport type Identity = z.infer<typeof identitySchema>;\n\n/**\n * Where a deployment is. `awaitingApproval` waits on a person: a review to apply, or a full\n * download that would stop the line. A finished deployment is `ready`, `error` or `canceled`.\n */\nexport const deploymentStateSchema = z.enum([\n\t\"queued\",\n\t\"building\",\n\t\"awaitingApproval\",\n\t\"applying\",\n\t\"starting\",\n\t\"verifying\",\n\t\"ready\",\n\t\"error\",\n\t\"canceled\",\n]);\nexport type DeploymentState = z.infer<typeof deploymentStateSchema>;\n\n/** States a deployment never leaves. */\nexport const finalStates: readonly DeploymentState[] = [\n\t\"ready\",\n\t\"error\",\n\t\"canceled\",\n];\n\n/** States a deployment may still be canceled in: anything before it applies. */\nexport const cancelableStates: readonly DeploymentState[] = [\n\t\"queued\",\n\t\"building\",\n\t\"awaitingApproval\",\n];\n\n/** The steps a deployment goes through, in order; a deployment skips the ones it doesn't need. */\nexport const deploymentPhaseNameSchema = z.enum([\n\t\"queue\",\n\t\"build\",\n\t\"review\",\n\t\"apply\",\n\t\"server\",\n\t\"health\",\n]);\n\nconst deploymentIdSchema = z.string().regex(/^dpl_[a-z0-9]{16,32}$/);\n\n/**\n * A deployment as the agent keeps it, in `deployments/<id>/record.json` of its state directory.\n * Every record of the last 14 days is kept, and always the running one and the last that was\n * healthy, with their releases.\n */\nexport const deploymentRecordSchema = z.strictObject({\n\tid: deploymentIdSchema,\n\trelease: z.string(),\n\t/** The debug manifest's build id, when the release has one. */\n\tbuild: z.string().nullable(),\n\tcreatedAt: z.iso.datetime(),\n\tupdatedAt: z.iso.datetime(),\n\t/** An upload from `tsplc deploy`, or a release the agent already had, deployed again. */\n\torigin: z.discriminatedUnion(\"kind\", [\n\t\tz.strictObject({ kind: z.literal(\"upload\") }),\n\t\tz.strictObject({ kind: z.literal(\"redeploy\"), from: deploymentIdSchema }),\n\t\tz.strictObject({ kind: z.literal(\"rollback\"), from: deploymentIdSchema }),\n\t]),\n\tgit: gitSourceSchema.nullable(),\n\t/** Who asked for it: the identity behind the request, with the deploying machine's user and host. */\n\trequestedBy: z.strictObject({\n\t\tidentity: identitySchema.omit({ role: true }),\n\t\tuser: z.string().nullable(),\n\t\thost: z.string().nullable(),\n\t}),\n\tmode: deploymentModeSchema,\n\t/** What it applies or applied: an online change unless a full download was asked for or approved. */\n\toperation: deployOperationSchema,\n\tstate: deploymentStateSchema,\n\tphases: z.array(\n\t\tz.strictObject({\n\t\t\tname: deploymentPhaseNameSchema,\n\t\t\tstartedAt: z.iso.datetime(),\n\t\t\tfinishedAt: z.iso.datetime().nullable(),\n\t\t\toutcome: z.enum([\"running\", \"ok\", \"failed\", \"skipped\"]),\n\t\t}),\n\t),\n\t/** What the online-change check found: refusals, and what the change restarts. */\n\tfindings: z.array(onlineChangeFindingSchema),\n\t/** What it waits on while `awaitingApproval`. */\n\tapproval: z\n\t\t.strictObject({\n\t\t\treason: z.enum([\"review\", \"downloadRequired\"]),\n\t\t\tmessage: z.string(),\n\t\t})\n\t\t.nullable(),\n\terror: z\n\t\t.strictObject({\n\t\t\tmessage: z.string(),\n\t\t\tdownloadRequired: z.boolean(),\n\t\t\trollback: rollbackSchema.optional(),\n\t\t})\n\t\t.nullable(),\n\tcontrollerIds: controllerIdsSchema.nullable(),\n\t/** What the check after applying found; null until it ran. */\n\thealth: z\n\t\t.strictObject({\n\t\t\tcontroller: z.enum([\"ok\", \"failed\"]),\n\t\t\tserver: z.enum([\"ok\", \"failed\", \"none\"]),\n\t\t\tplc: z.enum([\"ok\", \"failed\", \"unknown\"]),\n\t\t\tdetail: z.string().nullable(),\n\t\t})\n\t\t.nullable(),\n\t/** When it became the running deployment, and when another replaced it; null until and while. */\n\tactiveFrom: z.iso.datetime().nullable(),\n\tactiveUntil: z.iso.datetime().nullable(),\n});\nexport type DeploymentRecord = z.infer<typeof deploymentRecordSchema>;\n\n/** One line of a deployment's log, `deployments/<id>/log.jsonl`. */\nexport const deploymentLogLineSchema = z.strictObject({\n\t/** Counts from 1 within the deployment; `?after=` resumes from it. */\n\tseq: z.number().int().positive(),\n\tat: z.iso.datetime(),\n\tlevel: z.enum([\"info\", \"warning\", \"error\"]),\n\tphase: deploymentPhaseNameSchema.nullable(),\n\tmessage: z.string(),\n});\nexport type DeploymentLogLine = z.infer<typeof deploymentLogLineSchema>;\n\n/** A change to a deployment, as its subscribers and its server-sent events carry it. */\nexport type DeploymentEvent =\n\t| { kind: \"record\"; record: DeploymentRecord }\n\t| { kind: \"log\"; line: DeploymentLogLine };\n\n/** The deployments API: `POST` queues a release, `GET` lists the deployments. */\nexport const deploymentsApiPath = \"/api/deployments\";\n\n/** Deployment `id` in the deployments API; its actions and views are below it. */\nexport const deploymentApiPath = (id: string) =>\n\t`${deploymentsApiPath}/${encodeURIComponent(id)}`;\n\n/** Deployment `id`'s page on the dashboard. */\nexport const deploymentPagePath = (id: string) =>\n\t`/deployments/${encodeURIComponent(id)}`;\n\n/** Where the agent serves the debugger. */\nexport const debuggerMount = \"/debug/\";\n\n/** `POST /api/deployments`'s answer: the queued deployment and the dashboard page that shows it. */\nexport const deploymentCreatedSchema = z.strictObject({\n\tid: deploymentIdSchema,\n\turl: z.string(),\n});\n\n/** `GET /api/deployments`: newest first, with the running and last healthy ones named. */\nexport const deploymentListSchema = z.strictObject({\n\tdeployments: z.array(deploymentRecordSchema),\n\tcurrent: deploymentIdSchema.nullable(),\n\tlastGood: deploymentIdSchema.nullable(),\n});\n\n/** `POST /api/deployments/:id/approve`: apply it, as a full download when one is required. */\nexport const approveSchema = z.strictObject({ download: z.boolean() });\n\n/** `POST /api/deployments/:id/redeploy`: deploy its release again. */\nexport const redeploySchema = z.strictObject({ mode: deploymentModeSchema });\n\n/** `GET /api/deployments/:id/source`: the release's files, by path, with their sizes in bytes. */\nexport const deploymentSourceSchema = z.strictObject({\n\tfiles: z.array(\n\t\tz.strictObject({ path: z.string(), size: z.number().int().nonnegative() }),\n\t),\n});\n\n/** A secret the deployed release's config declares, or one stored without a declaration: never its value. */\nconst environmentEntrySchema = z.strictObject({\n\tname: z.string(),\n\tdeclared: z.boolean(),\n\tset: z.boolean(),\n});\nexport type EnvironmentEntry = z.infer<typeof environmentEntrySchema>;\n\n/** `GET /api/environment`: the plant PC's variables, and what the running release was built with. */\nexport const environmentSchema = z.strictObject({\n\t/** The plain values the running release was built with, from the config's target and this PC. */\n\tvalues: targetValuesSchema,\n\t/** The plain variables stored on this PC, which the next deployment is built with. */\n\tvariables: z.record(envName, z.string()),\n\tsecrets: z.array(environmentEntrySchema),\n});\nexport type EnvironmentListing = z.infer<typeof environmentSchema>;\n\n/**\n * `access.json` in the agent's state directory, and the body of `GET` and `PUT /api/access`: the\n * role of each Tailscale login, and the role a tailnet member without one gets, none by default.\n */\nexport const accessConfigSchema = z.strictObject({\n\troles: z.record(z.string().nonempty(), roleSchema),\n\ttailnetDefault: roleSchema.nullable(),\n});\nexport type AccessConfig = z.infer<typeof accessConfigSchema>;\n\n/** `POST /api/session`: the agent's full or read token, which signs a browser in. */\nexport const sessionRequestSchema = z.strictObject({ token: z.string() });\n\n/** `PUT /api/environment/:name`: a plain variable's new value, shown and built with, or a secret's. */\nexport const environmentValueSchema = z.discriminatedUnion(\"secret\", [\n\tz.strictObject({ secret: z.literal(false), value: plainValue }),\n\tz.strictObject({ secret: z.literal(true), value: secretValue }),\n]);\nexport type EnvironmentValue = z.infer<typeof environmentValueSchema>;\n",
7
+ "import { createHash } from \"node:crypto\";\nimport { releaseBuckets } from \"./protocol\";\n\n/**\n * How `tsplc deploy` sends a release the agent can build from one it already holds. The release's\n * files fall into buckets by path, and each bucket has a digest; the agent answers which buckets\n * differ from a release it stores and that release's files in them, and the client sends only the\n * files the agent lacks, with the release's other parts named rather than sent. The whole upload\n * is one zstd stream: the release's ST files are thousands of small, similar files.\n */\n\n/** A file of a release, at its path in the release. */\nexport interface ReleaseContent {\n\tpath: string;\n\tcontent: Uint8Array<ArrayBuffer>;\n}\n\n/** The first 16 hex digits of a SHA-256: enough to tell a release's files apart, and short on the wire. */\nexport const shortDigest = (data: Uint8Array | string) =>\n\tcreateHash(\"sha256\").update(data).digest(\"hex\").slice(0, 16);\n\n/** The bucket a release path falls in, the same in every release. */\nexport const fileBucket = (path: string) =>\n\tcreateHash(\"sha256\").update(path).digest().readUInt8(0) % releaseBuckets;\n\n/** Each bucket's digest over the paths and contents of its files, from each file's `shortDigest`. */\nexport const bucketDigests = (\n\tfiles: Iterable<{ path: string; digest: string }>,\n): string[] => {\n\tconst buckets = Array.from({ length: releaseBuckets }, (): string[] => []);\n\tfor (const { path, digest } of files) {\n\t\tbuckets[fileBucket(path)]?.push(`${path}\\0${digest}`);\n\t}\n\treturn buckets.map((entries) => shortDigest(entries.sort().join(\"\\n\")));\n};\n\n/** A frame's length prefix: an unsigned 32-bit big-endian byte count. */\nconst lengthBytes = 4;\n\n/** Frames the upload's header and then each file's path and content, and compresses the lot. */\nexport const encodeUpload = async (\n\theader: unknown,\n\tfiles: readonly ReleaseContent[],\n): Promise<Uint8Array<ArrayBuffer>> => {\n\tconst encoder = new TextEncoder();\n\tconst frames = [\n\t\tencoder.encode(JSON.stringify(header)),\n\t\t...files.flatMap(({ path, content }) => [encoder.encode(path), content]),\n\t];\n\tconst body = new Uint8Array(\n\t\tframes.reduce((total, frame) => total + lengthBytes + frame.length, 0),\n\t);\n\tconst view = new DataView(body.buffer);\n\tlet offset = 0;\n\tfor (const frame of frames) {\n\t\tview.setUint32(offset, frame.length);\n\t\tbody.set(frame, offset + lengthBytes);\n\t\toffset += lengthBytes + frame.length;\n\t}\n\treturn new Uint8Array(await Bun.zstdCompress(body, { level: 12 }));\n};\n\n/** An upload's header, still to be validated, and its files. */\nexport const decodeUpload = async (\n\tcompressed: Uint8Array,\n): Promise<{ header: unknown; files: ReleaseContent[] }> => {\n\tconst body = new Uint8Array(await Bun.zstdDecompress(compressed));\n\tconst view = new DataView(body.buffer, body.byteOffset, body.byteLength);\n\tconst frames: Uint8Array<ArrayBuffer>[] = [];\n\tlet offset = 0;\n\twhile (offset < body.length) {\n\t\tif (offset + lengthBytes > body.length) {\n\t\t\tthrow new Error(\"The release upload ends inside a frame\");\n\t\t}\n\t\tconst end = offset + lengthBytes + view.getUint32(offset);\n\t\tif (end > body.length) {\n\t\t\tthrow new Error(\"The release upload ends inside a frame\");\n\t\t}\n\t\tframes.push(body.subarray(offset + lengthBytes, end));\n\t\toffset = end;\n\t}\n\tconst [header, ...rest] = frames;\n\tif (!header || rest.length % 2 !== 0) {\n\t\tthrow new Error(\n\t\t\t\"The release upload has no header or a file without content\",\n\t\t);\n\t}\n\tconst decoder = new TextDecoder();\n\tconst files = Array.from({ length: rest.length / 2 }, (_, index) => ({\n\t\tpath: decoder.decode(rest[2 * index]),\n\t\tcontent: rest[2 * index + 1] ?? new Uint8Array(),\n\t}));\n\treturn { header: JSON.parse(decoder.decode(header)), files };\n};\n"
8
+ ],
9
+ "mappings": ";AAAA;AACA;AAAA;AAAA;AAAA;AAMA;AACA;AACA;AAAA;AAAA;AAAA;AAAA;AAMA,cAAS;;;ACfT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA;AACA;AACA;;;;;AAIO,IAAM,eAAe;AAGrB,IAAM,eAAe,EAAE,aAAa;AAAA,EAC1C,MAAM,EAAE,OAAO,EAAE,SAAS;AAAA,EAC1B,MAAM;AACP,CAAC;AAGM,IAAM,yBAAyB,EAAE,aAAa;AAAA,EACpD,MAAM,EAAE,OAAO;AAAA,EACf,SAAS,EAAE,KAAK;AAAA,EAChB,cAAc,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