@basaltkit/deploy 0.4.1 → 0.5.1

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 (53) hide show
  1. package/README.md +284 -23
  2. package/dist/answers.d.ts +70 -0
  3. package/dist/answers.js +196 -0
  4. package/dist/apache.js +11 -2
  5. package/dist/audit.d.ts +20 -0
  6. package/dist/audit.js +26 -0
  7. package/dist/backup.d.ts +17 -1
  8. package/dist/backup.js +56 -1
  9. package/dist/bin.js +9 -1
  10. package/dist/bootstrap.d.ts +68 -18
  11. package/dist/bootstrap.js +177 -45
  12. package/dist/caddy.js +2 -1
  13. package/dist/check.js +18 -5
  14. package/dist/checks.js +1 -1
  15. package/dist/cli.d.ts +22 -1
  16. package/dist/cli.js +498 -57
  17. package/dist/compose.d.ts +1 -1
  18. package/dist/compose.js +6 -1
  19. package/dist/config.d.ts +25 -2
  20. package/dist/config.js +65 -3
  21. package/dist/context.d.ts +43 -13
  22. package/dist/context.js +50 -7
  23. package/dist/detach.d.ts +23 -0
  24. package/dist/detach.js +105 -0
  25. package/dist/env-step.d.ts +16 -1
  26. package/dist/env-step.js +61 -5
  27. package/dist/events.d.ts +168 -0
  28. package/dist/events.js +477 -0
  29. package/dist/host.d.ts +179 -7
  30. package/dist/host.js +317 -42
  31. package/dist/index.d.ts +10 -5
  32. package/dist/index.js +7 -3
  33. package/dist/init.d.ts +2 -0
  34. package/dist/init.js +2 -1
  35. package/dist/install-plan.d.ts +40 -0
  36. package/dist/install-plan.js +437 -0
  37. package/dist/json-host.d.ts +32 -0
  38. package/dist/json-host.js +106 -0
  39. package/dist/lock.d.ts +45 -0
  40. package/dist/lock.js +128 -0
  41. package/dist/pipeline.d.ts +51 -3
  42. package/dist/pipeline.js +339 -173
  43. package/dist/protocol.d.ts +364 -0
  44. package/dist/protocol.js +134 -0
  45. package/dist/runs.d.ts +75 -0
  46. package/dist/runs.js +287 -0
  47. package/dist/state.d.ts +26 -13
  48. package/dist/state.js +68 -4
  49. package/dist/trust.d.ts +63 -0
  50. package/dist/trust.js +159 -0
  51. package/dist/version.d.ts +2 -0
  52. package/dist/version.js +10 -0
  53. package/package.json +5 -1
@@ -0,0 +1,364 @@
1
+ /**
2
+ * The machine protocol of `basalt-deploy` (RFC 0008): the NDJSON events a
3
+ * command writes under `--json`, the answer lines `--answers=stdin` reads,
4
+ * and the parsers for both.
5
+ *
6
+ * This module is pure: types, constants and two parsers, no Node API and no
7
+ * import that runs code. A program that drives the CLI (the phase-2 local UI)
8
+ * imports it as `@basaltkit/deploy/protocol` without loading the CLI.
9
+ */
10
+ export interface Finding {
11
+ /** The RFC 0006 §5 check id (`C1`…`C10`) or a step name. */
12
+ id: string;
13
+ level: 'error' | 'warning';
14
+ message: string;
15
+ /** One line the operator can act on. */
16
+ fix?: string;
17
+ }
18
+ /** Who holds `deploy.lock`. */
19
+ export interface LockHolder {
20
+ pid: number;
21
+ host: string;
22
+ startedAt: string;
23
+ actor: string;
24
+ command: string;
25
+ /** The run this deploy writes its events to (`--json`, RFC 0008 §8.3): what `attach` and `cancel` name. */
26
+ runId?: string;
27
+ }
28
+ /** One line per release in `<stateDir>/releases.json` (RFC 0006 §8). */
29
+ export interface Release {
30
+ sha: string;
31
+ previous?: string;
32
+ at: string;
33
+ user: string;
34
+ /**
35
+ * `aborted`: a signal stopped it before the release (code put back).
36
+ * `failed-migration`: the migration step failed — the database may be
37
+ * part-way; the restore command for `backup` was printed.
38
+ * `rollback-unhealthy`: this commit was released by a rollback and did
39
+ * not answer either — never a rollback target again.
40
+ */
41
+ status: 'ok' | 'rolled-back' | 'failed' | 'failed-migration' | 'public-unreachable' | 'aborted' | 'rollback-unhealthy';
42
+ /** Migration directories this release applied for the first time. */
43
+ migrations: string[];
44
+ backup?: string;
45
+ note?: string;
46
+ /** Who ran it: `--actor`, `$BASALT_DEPLOY_ACTOR` or `$USER` (`user` is always the OS account). */
47
+ actor?: string;
48
+ /** The SSH client address, when run over SSH. */
49
+ client?: string;
50
+ /** `ssh`, `ci`, `terminal` or `batch`. */
51
+ via?: string;
52
+ }
53
+ /**
54
+ * Written by a manual rollback: the commit it left. A scheduled `run` would
55
+ * otherwise fetch and redeploy it at once; it refuses that commit until the
56
+ * branch moves on, or `--unhold`.
57
+ */
58
+ export interface Hold {
59
+ sha: string;
60
+ at: string;
61
+ actor: string;
62
+ note: string;
63
+ }
64
+ export type PlanProxy = {
65
+ kind: 'none';
66
+ } | {
67
+ kind: 'apache';
68
+ managed: boolean;
69
+ vhost: string;
70
+ webRoot: string;
71
+ apiPrefix: string;
72
+ certName?: string;
73
+ root?: string;
74
+ } | {
75
+ kind: 'caddy';
76
+ managed: boolean;
77
+ webRoot: string;
78
+ apiPrefix: string;
79
+ onDemandTls?: {
80
+ ask: string;
81
+ };
82
+ extra?: string;
83
+ root?: string;
84
+ };
85
+ /** What `install` needs, written by `install-plan` as plain JSON (RFC 0006 §11.4): data only, validated again by root. */
86
+ export interface InstallPlan {
87
+ kind: 'basalt-deploy/install-plan';
88
+ version: 1;
89
+ app: string;
90
+ domain: string;
91
+ tenants: 'subdomain' | 'none';
92
+ /** The checkout, absolute. install checks it is the app user's own directory. */
93
+ dir: string;
94
+ /** The upstream port the proxy site points at. */
95
+ port: number;
96
+ proxy: PlanProxy;
97
+ /** The `.env` and mirrors OUTSIDE the checkout — always directly in `/etc/<app>/`. */
98
+ envFiles: string[];
99
+ /** The app uses Docker (dedicated infra or the compose runtime). */
100
+ docker: boolean;
101
+ /** `bootstrap` settings, for `bootstrap` only. */
102
+ bootstrap?: {
103
+ swapGb?: number;
104
+ firewall?: boolean;
105
+ };
106
+ /** The @basaltkit/deploy version that wrote the plan (informational). */
107
+ tool: string;
108
+ }
109
+ /** The protocol version: `--json` and `--json=1`. */
110
+ export declare const PROTOCOL_VERSION = 1;
111
+ /** The steps a command reports, a closed set (`step-start`/`step-end`). */
112
+ export declare const STEP_IDS: readonly ['lock', 'preflight', 'fetch', 'env', 'infra', 'build', 'validate', 'backup', 'migrate', 'release', 'health', 'verify', 'record', 'restore', 'plan', 'check'];
113
+ export type StepId = typeof STEP_IDS[number];
114
+ export declare const ERROR_CODES: readonly ['locked', 'aborted', 'config', 'refused-root', 'preflight', 'held', 'release-failed', 'failed', 'answer-missing', 'answer-invalid', 'answer-unknown', 'answer-timeout', 'protocol', 'protocol-version', 'usage', 'unsupported', 'not-found', 'detach-unconfirmed', 'run-vanished', 'unexpected', 'already-cancelled'];
115
+ export type ErrorCode = typeof ERROR_CODES[number];
116
+ export declare const EVENT_TYPES: readonly ['hello', 'step-start', 'step-end', 'log', 'finding', 'prompt', 'result', 'error', 'done', 'event'];
117
+ export type EventType = typeof EVENT_TYPES[number];
118
+ /** `<UTC yyyymmddThhmmssZ>-<12 hex>`: the id of a run and the name of its log (`<id>.ndjson`). */
119
+ export declare const RUN_ID: RegExp;
120
+ export declare const isStepId: (value: unknown) => value is StepId;
121
+ export declare const isErrorCode: (value: unknown) => value is ErrorCode;
122
+ export interface Envelope {
123
+ v: 1;
124
+ /** ISO-8601 UTC with milliseconds. */
125
+ ts: string;
126
+ /** 0, 1, 2, … per event stream: strictly +1, no gaps. */
127
+ seq: number;
128
+ /** Set when the command writes a run log (run, env, rollback). */
129
+ runId?: string;
130
+ /** True when the redactor replaced something in this event. */
131
+ redacted?: true;
132
+ }
133
+ export interface HelloEvent extends Envelope {
134
+ type: 'hello';
135
+ tool: '@basaltkit/deploy';
136
+ version: string;
137
+ protocol: 1;
138
+ command: string;
139
+ pid: number;
140
+ host: string;
141
+ detached?: true;
142
+ }
143
+ export interface StepStartEvent extends Envelope {
144
+ type: 'step-start';
145
+ id: StepId;
146
+ title: string;
147
+ }
148
+ export type StepStatus = 'ok' | 'failed' | 'skipped' | 'aborted';
149
+ export interface StepEndEvent extends Envelope {
150
+ type: 'step-end';
151
+ id: StepId;
152
+ status: StepStatus;
153
+ durationMs: number;
154
+ }
155
+ export type LogLevel = 'info' | 'ok' | 'warn' | 'error';
156
+ export interface LogEvent extends Omit<Envelope, 'redacted'> {
157
+ type: 'log';
158
+ /** `tool`: this tool's own lines; `child`: a line a child process printed; `foreign`: a stdout write by deploy.config.ts. */
159
+ stream: 'tool' | 'child' | 'foreign';
160
+ level: LogLevel;
161
+ /** Data, never instructions: render as plain text. */
162
+ text: string;
163
+ /** Whether the redactor replaced something in this event. */
164
+ redacted: boolean;
165
+ step?: StepId;
166
+ /** The child's command basename (`pnpm`, `docker`). */
167
+ source?: string;
168
+ truncated?: true;
169
+ }
170
+ export interface FindingEvent extends Envelope, Finding {
171
+ type: 'finding';
172
+ }
173
+ /** A question as `plan --json` lists it and as a `prompt` asks it — never with a value. */
174
+ export interface PromptDescriptor {
175
+ /** `env.<KEY>`: what an answer line names. */
176
+ id: string;
177
+ kind: 'text' | 'secret' | 'confirm' | 'choice';
178
+ message: string;
179
+ key?: string;
180
+ optional: boolean;
181
+ /** `text` only — a secret never carries one. */
182
+ default?: string;
183
+ choices?: string[];
184
+ }
185
+ export interface PromptEvent extends Envelope, PromptDescriptor {
186
+ type: 'prompt';
187
+ attempt: number;
188
+ }
189
+ export interface StatusResult {
190
+ app: string;
191
+ stateDir: string;
192
+ lock: null | {
193
+ holder?: LockHolder;
194
+ stale: boolean;
195
+ corrupt: boolean;
196
+ };
197
+ activeRun?: {
198
+ runId: string;
199
+ pid: number;
200
+ command: string;
201
+ actor: string;
202
+ startedAt: string;
203
+ alive: boolean;
204
+ };
205
+ lastRun?: {
206
+ runId: string;
207
+ command: string;
208
+ exitCode?: number;
209
+ complete: boolean;
210
+ endedAt?: string;
211
+ };
212
+ hold: Hold | null;
213
+ /** The last 10, newest first. */
214
+ releases: Release[];
215
+ process: {
216
+ kind: 'pm2';
217
+ name: string;
218
+ status?: string;
219
+ pid?: number;
220
+ running: boolean;
221
+ } | {
222
+ kind: 'compose';
223
+ lines: string[];
224
+ };
225
+ }
226
+ export interface CheckResult {
227
+ file: string;
228
+ app: string;
229
+ runtime: 'pm2' | 'compose';
230
+ proxy?: string;
231
+ types: 'ok' | 'failed' | 'not-typescript' | 'no-tsc';
232
+ }
233
+ export interface PlanResult {
234
+ findings: Finding[];
235
+ /** The lines `plan` prints, split at the first ': '. */
236
+ lines: Array<{
237
+ step: string;
238
+ text: string;
239
+ }>;
240
+ /** What `env`/`run` would ask now: send the answers with `--answers=stdin`. */
241
+ questions: PromptDescriptor[];
242
+ /** `plan` exits 1. */
243
+ blocking: boolean;
244
+ }
245
+ export interface RunResult {
246
+ sha: string;
247
+ previous: string;
248
+ status: Release['status'];
249
+ migrations: string[];
250
+ backup?: string;
251
+ url?: string;
252
+ heldOverride?: true;
253
+ /** Why it did not end `ok` (a key or a step, never a value). */
254
+ note?: string;
255
+ }
256
+ export interface RollbackResult {
257
+ from: string;
258
+ to: string;
259
+ status: 'ok' | 'rollback-unhealthy';
260
+ held: string;
261
+ }
262
+ export interface EnvResult {
263
+ file: string;
264
+ changes: Array<{
265
+ kind: 'set' | 'remove';
266
+ key: string;
267
+ reason: string;
268
+ }>;
269
+ port?: number;
270
+ }
271
+ export interface DetachResult {
272
+ runId: string;
273
+ pid: number;
274
+ log: string;
275
+ }
276
+ export interface CancelResult {
277
+ runId: string;
278
+ pid: number;
279
+ signal: 'SIGTERM';
280
+ second: boolean;
281
+ }
282
+ export interface InstallPlanResult {
283
+ plan: InstallPlan;
284
+ path?: string;
285
+ rootCommand: string;
286
+ }
287
+ export interface ResultPayloads {
288
+ status: StatusResult;
289
+ check: CheckResult;
290
+ plan: PlanResult;
291
+ run: RunResult | DetachResult;
292
+ rollback: RollbackResult | DetachResult;
293
+ env: EnvResult;
294
+ cancel: CancelResult;
295
+ 'install-plan': InstallPlanResult;
296
+ }
297
+ export type ResultCommand = keyof ResultPayloads;
298
+ export type ResultEvent = Envelope & {
299
+ type: 'result';
300
+ } & {
301
+ [C in ResultCommand]: {
302
+ command: C;
303
+ data: ResultPayloads[C];
304
+ };
305
+ }[ResultCommand];
306
+ export interface ErrorEvent extends Envelope {
307
+ type: 'error';
308
+ code: ErrorCode;
309
+ message: string;
310
+ hint?: string;
311
+ /** `locked` only: who holds the lock. */
312
+ holder?: LockHolder;
313
+ /** The blocking findings (`preflight`). */
314
+ findings?: Finding[];
315
+ }
316
+ export interface DoneEvent extends Envelope {
317
+ type: 'done';
318
+ exitCode: number;
319
+ }
320
+ /** `attach`: one event of the run, as the run wrote it (`event.seq` is the resume key). */
321
+ export interface AttachedEvent extends Envelope {
322
+ type: 'event';
323
+ event: DeployEvent;
324
+ }
325
+ export type DeployEvent = HelloEvent | StepStartEvent | StepEndEvent | LogEvent | FindingEvent | PromptEvent | ResultEvent | ErrorEvent | DoneEvent | AttachedEvent;
326
+ /** What the writer sets (`redacted` too, which a body may leave out). */
327
+ type EnvelopeKey = 'v' | 'ts' | 'seq' | 'runId';
328
+ type Body<E> = E extends unknown ? Omit<E, EnvelopeKey> : never;
329
+ /** An event as a command emits it; the writer adds the envelope. */
330
+ export type EventBody = Body<DeployEvent>;
331
+ export type Parsed<T> = {
332
+ ok: true;
333
+ value: T;
334
+ } | {
335
+ ok: false;
336
+ error: string;
337
+ };
338
+ /**
339
+ * One NDJSON line of `--json` output, checked: the envelope, the version and
340
+ * the fields of each known type. A line that does not pass is not an event —
341
+ * a reader treats the stream as corrupt and stops. A type it does not know is
342
+ * returned as is (`known: false`), to be skipped.
343
+ */
344
+ export declare function parseEvent(line: string): Parsed<DeployEvent> & {
345
+ known?: boolean;
346
+ };
347
+ export interface AnswerLine {
348
+ v: 1;
349
+ type: 'answer';
350
+ /** `env.<KEY>`. */
351
+ id: string;
352
+ value: string;
353
+ }
354
+ /** Per line, and in all. */
355
+ export declare const MAX_ANSWER_LINE_BYTES: number;
356
+ export declare const MAX_ANSWER_LINES = 256;
357
+ export declare const ANSWER_ID: RegExp;
358
+ /**
359
+ * One answer line, strictly: `v` 1, `type` `answer`, an `env.<KEY>` id and a
360
+ * string value without NUL. Only these fields are read; others are ignored.
361
+ * The error never quotes the value.
362
+ */
363
+ export declare function parseAnswerLine(line: string): Parsed<AnswerLine>;
364
+ export {};
@@ -0,0 +1,134 @@
1
+ /**
2
+ * The machine protocol of `basalt-deploy` (RFC 0008): the NDJSON events a
3
+ * command writes under `--json`, the answer lines `--answers=stdin` reads,
4
+ * and the parsers for both.
5
+ *
6
+ * This module is pure: types, constants and two parsers, no Node API and no
7
+ * import that runs code. A program that drives the CLI (the phase-2 local UI)
8
+ * imports it as `@basaltkit/deploy/protocol` without loading the CLI.
9
+ */
10
+ /** The protocol version: `--json` and `--json=1`. */
11
+ export const PROTOCOL_VERSION = 1;
12
+ /** The steps a command reports, a closed set (`step-start`/`step-end`). */
13
+ export const STEP_IDS = [
14
+ 'lock', 'preflight', 'fetch', 'env', 'infra', 'build', 'validate', 'backup', 'migrate',
15
+ 'release', 'health', 'verify', 'record', 'restore', 'plan', 'check',
16
+ ];
17
+ export const ERROR_CODES = [
18
+ 'locked', 'aborted', 'config', 'refused-root', 'preflight', 'held', 'release-failed', 'failed',
19
+ 'answer-missing', 'answer-invalid', 'answer-unknown', 'answer-timeout',
20
+ 'protocol', 'protocol-version', 'usage', 'unsupported',
21
+ 'not-found', 'detach-unconfirmed', 'run-vanished', 'unexpected', 'already-cancelled',
22
+ ];
23
+ export const EVENT_TYPES = ['hello', 'step-start', 'step-end', 'log', 'finding', 'prompt', 'result', 'error', 'done', 'event'];
24
+ /** `<UTC yyyymmddThhmmssZ>-<12 hex>`: the id of a run and the name of its log (`<id>.ndjson`). */
25
+ export const RUN_ID = /^\d{8}T\d{6}Z-[0-9a-f]{12}$/;
26
+ export const isStepId = (value) => typeof value === 'string' && STEP_IDS.includes(value);
27
+ export const isErrorCode = (value) => typeof value === 'string' && ERROR_CODES.includes(value);
28
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
29
+ const isString = (value) => typeof value === 'string';
30
+ const isCount = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
31
+ const optional = (value, check) => value === undefined || check(value);
32
+ const LEVELS = ['info', 'ok', 'warn', 'error'];
33
+ const STATUSES = ['ok', 'failed', 'skipped', 'aborted'];
34
+ function findingShape(e) {
35
+ return isString(e['id']) && (e['level'] === 'error' || e['level'] === 'warning') && isString(e['message']) && optional(e['fix'], isString);
36
+ }
37
+ /** The fields each known type must have, with their types. Unknown fields are allowed (additive within v1). */
38
+ const SHAPES = {
39
+ hello: (e) => e['tool'] === '@basaltkit/deploy' && isString(e['version']) && e['protocol'] === 1 && isString(e['command']) && isCount(e['pid']) && isString(e['host']),
40
+ 'step-start': (e) => isStepId(e['id']) && isString(e['title']),
41
+ 'step-end': (e) => isStepId(e['id']) && STATUSES.includes(e['status']) && isCount(e['durationMs']),
42
+ log: (e) => ['tool', 'child', 'foreign'].includes(e['stream']) && LEVELS.includes(e['level']) && isString(e['text'])
43
+ && typeof e['redacted'] === 'boolean' && optional(e['step'], isStepId) && optional(e['source'], isString),
44
+ finding: findingShape,
45
+ prompt: (e) => isString(e['id']) && ['text', 'secret', 'confirm', 'choice'].includes(e['kind']) && isString(e['message'])
46
+ && typeof e['optional'] === 'boolean' && isCount(e['attempt']) && (e['kind'] !== 'secret' || e['default'] === undefined),
47
+ result: (e) => isString(e['command']) && isObject(e['data']),
48
+ error: (e) => isErrorCode(e['code']) && isString(e['message']) && optional(e['hint'], isString)
49
+ && optional(e['findings'], (f) => Array.isArray(f) && f.every((x) => isObject(x) && findingShape(x))),
50
+ done: (e) => isCount(e['exitCode']),
51
+ event: (e) => isObject(e['event']) && checkEvent(e['event'], false).ok,
52
+ };
53
+ function checkEvent(value, allowWrapper) {
54
+ if (!isObject(value))
55
+ return { ok: false, error: 'not a JSON object' };
56
+ if (value['v'] !== PROTOCOL_VERSION)
57
+ return { ok: false, error: `v is ${JSON.stringify(value['v'])}, not ${PROTOCOL_VERSION}` };
58
+ if (!isString(value['type']))
59
+ return { ok: false, error: 'no type' };
60
+ if (!isString(value['ts']))
61
+ return { ok: false, error: 'no ts' };
62
+ if (!isCount(value['seq']))
63
+ return { ok: false, error: 'seq is not a whole number' };
64
+ if (!optional(value['runId'], (r) => isString(r) && RUN_ID.test(r)))
65
+ return { ok: false, error: 'runId is malformed' };
66
+ // `redacted` is `true` or absent — except in a log event, where it is always a boolean.
67
+ if (value['type'] !== 'log' && !optional(value['redacted'], (r) => r === true))
68
+ return { ok: false, error: 'redacted is not true' };
69
+ const type = value['type'];
70
+ const shape = SHAPES[type];
71
+ // A type this reader does not know: valid, skipped by the caller (additive within v1).
72
+ if (!shape)
73
+ return { ok: true, value: value };
74
+ // An attached event never nests another one.
75
+ if (!allowWrapper && type === 'event')
76
+ return { ok: false, error: 'nested event' };
77
+ if (!shape(value))
78
+ return { ok: false, error: `malformed ${type} event` };
79
+ return { ok: true, value: value };
80
+ }
81
+ /**
82
+ * One NDJSON line of `--json` output, checked: the envelope, the version and
83
+ * the fields of each known type. A line that does not pass is not an event —
84
+ * a reader treats the stream as corrupt and stops. A type it does not know is
85
+ * returned as is (`known: false`), to be skipped.
86
+ */
87
+ export function parseEvent(line) {
88
+ let value;
89
+ try {
90
+ value = JSON.parse(line);
91
+ }
92
+ catch {
93
+ return { ok: false, error: 'not JSON' };
94
+ }
95
+ const checked = checkEvent(value, true);
96
+ if (!checked.ok)
97
+ return checked;
98
+ return { ...checked, known: EVENT_TYPES.includes(checked.value.type) };
99
+ }
100
+ /** Per line, and in all. */
101
+ export const MAX_ANSWER_LINE_BYTES = 64 * 1024;
102
+ export const MAX_ANSWER_LINES = 256;
103
+ export const ANSWER_ID = /^env\.[A-Z_][A-Z0-9_]*$/;
104
+ /**
105
+ * One answer line, strictly: `v` 1, `type` `answer`, an `env.<KEY>` id and a
106
+ * string value without NUL. Only these fields are read; others are ignored.
107
+ * The error never quotes the value.
108
+ */
109
+ export function parseAnswerLine(line) {
110
+ if (new TextEncoder().encode(line).length > MAX_ANSWER_LINE_BYTES)
111
+ return { ok: false, error: `an answer line is larger than ${MAX_ANSWER_LINE_BYTES} bytes` };
112
+ let value;
113
+ try {
114
+ value = JSON.parse(line);
115
+ }
116
+ catch {
117
+ return { ok: false, error: 'an answer line is not JSON' };
118
+ }
119
+ if (!isObject(value))
120
+ return { ok: false, error: 'an answer line is not a JSON object' };
121
+ if (value['v'] !== PROTOCOL_VERSION)
122
+ return { ok: false, error: `an answer line has v ${JSON.stringify(value['v']) ?? 'missing'}, not ${PROTOCOL_VERSION}` };
123
+ if (value['type'] !== 'answer')
124
+ return { ok: false, error: 'an answer line\'s type is not "answer"' };
125
+ const id = value['id'];
126
+ if (!isString(id) || !ANSWER_ID.test(id))
127
+ return { ok: false, error: 'an answer line\'s id is not env.<KEY>' };
128
+ const answer = value['value'];
129
+ if (!isString(answer))
130
+ return { ok: false, error: `the answer for ${id} is not a string` };
131
+ if (answer.includes('\u0000'))
132
+ return { ok: false, error: `the answer for ${id} contains NUL` };
133
+ return { ok: true, value: { v: 1, type: 'answer', id, value: answer } };
134
+ }
package/dist/runs.d.ts ADDED
@@ -0,0 +1,75 @@
1
+ import type { Host, LogHandle } from './host.js';
2
+ import { type LockState } from './lock.js';
3
+ import { type DeployEvent, type StatusResult } from './protocol.js';
4
+ /**
5
+ * Run logs (RFC 0008 §8): `<stateDir>/runs/<runId>.ndjson`, one per
6
+ * JSON-mode locked command (`run`, `env`, `rollback`), holding its events —
7
+ * what `attach` replays, what `status` reports as the last run.
8
+ *
9
+ * The directory is 0700 and the deploy user's; a log is 0600, created
10
+ * O_EXCL|O_NOFOLLOW and read O_NOFOLLOW with its owner and mode checked.
11
+ * They protect it from other users, not from the app user itself (§10).
12
+ */
13
+ export declare const runsDir: (stateDir: string) => string;
14
+ export declare const runLogPath: (stateDir: string, runId: string) => string;
15
+ /** Retention (RFC 0008 §8.7). */
16
+ export declare const KEEP_RUN_LOGS = 50;
17
+ export declare const KEEP_RUN_DAYS = 30;
18
+ /** `<UTC yyyymmddThhmmssZ>-<12 hex>`. */
19
+ export declare function newRunId(host: Host): string;
20
+ /** Creates the runs directory (0700) or checks it: a directory, the deploy user's, nobody else's. */
21
+ export declare function ensureRunsDir(host: Host, stateDir: string): Promise<string>;
22
+ /** A new run log, 0600, created exclusively (a link or file already there is an error). */
23
+ export declare function createRunLog(host: Host, stateDir: string, runId: string): Promise<{
24
+ path: string;
25
+ handle: LogHandle;
26
+ }>;
27
+ /**
28
+ * Keeps the newest {@link KEEP_RUN_LOGS} logs and none older than
29
+ * {@link KEEP_RUN_DAYS} days; never `keep` (the run holding the lock). Only
30
+ * names this package writes, by unlink(2) — never recursive.
31
+ */
32
+ export declare function pruneRunLogs(host: Host, stateDir: string, keep: string | undefined): Promise<string[]>;
33
+ /** The run named by a live lock holder (`status --json`). */
34
+ export declare function activeRun(host: Host, lock: LockState | undefined): StatusResult['activeRun'];
35
+ /** The newest run log: its command, and how it ended — from its first and last 64 KiB. */
36
+ export declare function lastRun(host: Host, stateDir: string): Promise<StatusResult['lastRun']>;
37
+ export declare const ATTACH_POLL_MS = 250;
38
+ export declare const VANISH_GRACE_MS = 2000;
39
+ /**
40
+ * Without `--follow`: how long a run that released its lock gets to write
41
+ * its last events (`error`, `done`) before it is called vanished.
42
+ */
43
+ export declare const LAST_EVENTS_GRACE_MS = 500;
44
+ export interface AttachOptions {
45
+ fromSeq: number;
46
+ follow: boolean;
47
+ /** One run event, checked, in order. */
48
+ emit: (event: DeployEvent) => void;
49
+ }
50
+ /**
51
+ * Replays a run log (RFC 0008 §8.4): every line checked — the envelope, a
52
+ * known shape, `seq` exactly one more than the line before — then handed on.
53
+ * A bad line ends the replay; raw text is never passed through. Returns the
54
+ * run's exit code once its `done` is read, else (without `--follow`, a run
55
+ * still alive) `undefined`.
56
+ */
57
+ export declare function attach(host: Host, stateDir: string, runId: string, options: AttachOptions): Promise<number | undefined>;
58
+ /**
59
+ * SIGTERM to the deploy holding the lock for `runId` (RFC 0008 §8.5) — only
60
+ * when its runId, host, a live pid and its own argv (`--run-id=<id>`, from
61
+ * /proc) all say it is that run: a recycled pid is never signalled. Where the
62
+ * argv cannot be read (not Linux), refused. A second cancel is the second
63
+ * signal: the run stops at once. With `firstOnly`, a run already cancelled
64
+ * once (from anywhere: the marker is on the server) is refused
65
+ * (`already-cancelled`) and not signalled — a client that asked only for the
66
+ * mild first cancel never sends the immediate second one by surprise.
67
+ */
68
+ export declare function cancel(host: Host, stateDir: string, runId: string, options?: {
69
+ firstOnly?: boolean;
70
+ }): Promise<{
71
+ pid: number;
72
+ second: boolean;
73
+ }>;
74
+ /** The complete, valid events a run log holds now (up to 1 MiB): what the detaching parent waits on. */
75
+ export declare function scanRunLog(host: Host, path: string): Promise<DeployEvent[]>;