@zukhruf/process 0.0.0-stage → 0.8.153

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ezzabuzaid
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,334 @@
1
- # Temporary Holding Version
1
+ # @zukhruf/process
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **In build (backlog #6077).** `Command#run` is built. `Command#start`, `NodeCommand` and `Coprocess` follow, in that order; until then, this README describes them as decided in the ADRs.
4
+
5
+ Start a process of this machine and know how it ends. A `Command` says what to run: the file, its arguments, the environment, the folder. `command.run()` runs it to its end and gives its exit code or signal and its output, with no throw at a non-zero exit. `command.start()` gives a started process: it resolves when the process is ready, it stops the process group with SIGTERM and then SIGKILL, and the process ends with its parent, also when the parent is killed. A `Coprocess` talks to a started process in JSON lines, and a `NodeCommand` runs JavaScript source in its own Node.js with messages.
6
+
7
+ The package replaces `@zukhruf/coprocess` and the `process` area of `@zukhruf/testing`, which move here ([ADR 0001](./docs/adr/0001-one-package-starts-a-process-for-a-run-and-for-a-started-process-and-coprocess-and-the-test-worker-move-into-it.md)).
8
+
9
+ The words in these documents have one meaning each. See the glossary in [CONTEXT.md](./CONTEXT.md).
10
+
11
+ ## Use it
12
+
13
+ ```sh
14
+ npm install @zukhruf/process
15
+ ```
16
+
17
+ ```ts
18
+ import { Command } from '@zukhruf/process';
19
+
20
+ const lint = await new Command('npx', ['eslint', 'src'], {
21
+ env: process.env,
22
+ clock: globalThis,
23
+ }).run();
24
+ if (lint.exitCode !== 0) console.error(lint.output);
25
+ ```
26
+
27
+ ## Say what to run
28
+
29
+ `new Command(file, args, options)` holds what to run, and starts nothing. `options` are `env` and `clock` (both required), `cwd`, `grace` and `name`. The clock runs the grace, as [root ADR 0004](../../docs/adr/0004-a-library-that-waits-takes-the-clock-as-an-input.md) asks of each library that waits: an app gives `globalThis`, and a test can give the clock of `@sinonjs/fake-timers`. A command can run or start more than once, as a pool does when it replaces a worker. What belongs to one call, the `signal`, the `input` and the ready line, goes to `run()` or `start()` ([ADR 0010](./docs/adr/0010-a-command-says-what-to-run-and-run-and-start-are-its-methods.md)).
30
+
31
+ ## Run a command to its end
32
+
33
+ `command.run({ input, signal })` resolves when the process has ended and its streams have closed. It gives the end and the output ([ADR 0002](./docs/adr/0002-a-run-gives-its-end-as-a-value-an-exit-code-or-a-signal-and-rejects-only-when-the-process-cannot-start-or-its-signal-aborts.md)).
34
+
35
+ ```ts
36
+ const status = new Command('git', ['status', '--porcelain'], {
37
+ env: process.env,
38
+ cwd: repository,
39
+ });
40
+ const run = await status.run();
41
+ // run.exitCode is 0, or run.signal names the signal that ended it.
42
+ // run.stdout, run.stderr, and run.output with both in the order written.
43
+ ```
44
+
45
+ - The end is `{ exitCode }` or `{ signal }`. A non-zero exit code is a value, not a rejection.
46
+ - The text is not trimmed. `stdout` keeps its last newline.
47
+ - `input` goes to stdin, and then stdin ends. Without `input`, stdin ends at once.
48
+ - `env` is required, and it is the whole environment of the process. Write `env: process.env` to pass your own ([ADR 0003](./docs/adr/0003-the-environment-is-a-required-input-and-the-process-gets-only-what-the-caller-names.md)).
49
+ - An abort of `signal` stops the process and rejects with the reason of the signal.
50
+
51
+ ## Start a process and wait until it is ready
52
+
53
+ `command.start({ ready, signal, stdin, stdout, stderr })` starts the process and resolves when it is ready: at the first line of stdout that `ready.line` names ([ADR 0006](./docs/adr/0006-a-started-process-is-ready-at-a-line-or-a-message-that-the-caller-names-and-an-end-before-it-rejects.md)). Without `ready`, it resolves after the start.
54
+
55
+ ```ts
56
+ const owner = new Command(process.execPath, ['owner.js', path], {
57
+ name: 'owner',
58
+ env: process.env,
59
+ });
60
+ await using holding = await owner.start({
61
+ ready: { line: 'holding' },
62
+ signal: t.signal,
63
+ });
64
+ ```
65
+
66
+ - `line` is a string that a whole line equals, or a regular expression that a line matches.
67
+ - When the process ends before it is ready, the start rejects with `EndedBeforeReadyError`, which holds the end and the stderr tail.
68
+ - The wait has no time limit of its own. The `signal` is its limit; in a test, give `t.signal`.
69
+ - `lines()` of the started process gives the lines of stdout from the first one, also those that came before the call. After the ready line, the package reads stdout only while a caller iterates `lines()`. A process that writes much to stdout that nobody reads waits at its write, as with a pipe in a shell; give `stdout: 'ignore'` for such a process.
70
+ - `stdin` and `stdout` can also be a `net.Socket` that the process gets as its own, as `sshd -i` needs for each connection. A ready line needs `stdout: 'pipe'`, the default, and the type allows `ready` only then.
71
+
72
+ ## The end of a started process
73
+
74
+ `ended` settles once, with the end, when the process has ended. A pool or a supervisor awaits it; there is no property to read, because a read and an end can race ([coprocess ADR 0001](../coprocess/docs/adr/0001-the-exit-is-an-event-and-the-package-uses-execa.md)).
75
+
76
+ A started process ends when this program ends, also when this program is killed with SIGKILL ([ADR 0004](./docs/adr/0004-a-started-process-ends-with-its-parent-also-when-the-parent-is-killed.md)). On macOS and Linux, each process starts under a keeper in POSIX `sh`: it leads the process group, and it stops the group when the pipe from this program closes. It costs about 5 ms at the start and 2 to 4 MB while the process runs. A process that must outlive this program is not a started process of this package.
77
+
78
+ - On Windows a process does not end yet with a parent that is killed. A job object, as .NET 11 uses, is on the map as later.
79
+ - `sh` cannot tell an exit code above 128 from a signal, so a process that exits with 130 ends as `{ signal: 'SIGINT' }`.
80
+ - A child of the process that leaves the group (`setsid`, `detached: true`) does not end with it.
81
+
82
+ ## Stop a started process
83
+
84
+ `stop()` sends SIGTERM to the process group. When the group is still alive after the grace, 5 seconds unless the caller gives `grace`, it sends SIGKILL to the group. It resolves with the end ([ADR 0005](./docs/adr/0005-a-stop-sends-sigterm-to-the-process-group-and-sigkill-after-a-grace-of-5-seconds.md)). An abort of `signal` is a stop. The disposal (`await using`) is a stop that also waits until the streams have closed.
85
+
86
+ ## Talk to a coprocess in JSON lines
87
+
88
+ `new Coprocess(process)` talks to a started process that reads one JSON value on each line of stdin and writes one on each line of stdout. `request(value)` sends a value and receives the next one. `send` and `receive` do each half. `close()` ends stdin and waits for the end ([ADR 0007](./docs/adr/0007-json-lines-and-messages-are-views-of-a-started-process-and-only-a-node-process-has-messages.md)). The process must have its stdin and stdout piped, the default of `start()`, and the type allows only such a process.
89
+
90
+ ```ts
91
+ const worker = new Command('/path/to/vision-worker', [], {
92
+ name: 'Vision worker',
93
+ env: process.env,
94
+ });
95
+ await using ocr = new Coprocess(await worker.start());
96
+ const answer = await ocr.request({ path: '/tmp/receipt.png' });
97
+ ```
98
+
99
+ `exited()` settles once, with the error that each later `receive` gets, as in `@zukhruf/coprocess` today, and `coprocess.process` is the started process.
100
+
101
+ ## Run JavaScript source in its own Node.js
102
+
103
+ `new NodeCommand(source, options)` says to run `source` as an ES module in a new Node.js, with an IPC channel back to this process. `options` are those of `Command` and `nodeOptions`, the Node.js flags before the source. `start()` gives a `NodeProcess`: `next(match, { signal })` resolves with the first message that `match` selects, sent before or after the call, a `type` or a function of the message, and `send(message)` sends one. Its `ready` also takes `{ message }`, and `admit` gets the child before it can send. `run()` runs the source to its end and gives what `Command#run` gives.
104
+
105
+ ```ts
106
+ const holder = new NodeCommand(
107
+ `
108
+ import { connect } from 'node:net';
109
+ // ... take the lock, then:
110
+ process.send({ type: 'held' });
111
+ `,
112
+ { name: 'holder', env: process.env },
113
+ );
114
+ await using held = await holder.start({
115
+ ready: { message: 'held' },
116
+ signal: t.signal,
117
+ });
118
+ ```
119
+
120
+ Only a `NodeProcess` has messages, because only a Node.js child can use the channel.
121
+
122
+ ## Errors
123
+
124
+ | Error | When |
125
+ | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
126
+ | `StartError` | The process could not start, for example because the file does not exist. Its `cause` is the error of the start (`ENOENT`, `EACCES`). `run()` and `start()` reject with it. |
127
+ | `EndedBeforeReadyError` | A started process ended before it was ready. It has `end` and `stderr` (the stderr tail). Its message names the process and the end, never the command line, because arguments can hold prompts or secrets. |
128
+ | the reason of `signal` | The signal aborted. The process is stopped first. |
129
+ | `<name> exited (<exit code or signal>): <stderr>` | A coprocess ended. `exited()` settles with it, and each `receive` rejects with it (from `@zukhruf/coprocess`). |
130
+ | `<name> gave a line that is not JSON` | A coprocess wrote a line that `JSON.parse` refuses. Only the `receive` of that line fails (from `@zukhruf/coprocess`). |
131
+
132
+ A non-zero exit code of a run is not an error.
133
+
134
+ ## What the package does not do
135
+
136
+ - **A shell.** It starts a file with arguments, never a command line through a shell, so no argument is read by a shell. zx's `$` is a shell language; this is not.
137
+ - **A process that outlives this program.** Start it detached with `node:child_process` and unref it.
138
+ - **A pool of processes.** That is `@zukhruf/pool`, which keeps started processes.
139
+ - **Retries.** A caller that retries a run calls `run()` of its command again.
140
+ - **Later, on the map:** a ready wait for a listening port and for HTTP; the end with the parent through job objects on Windows; a pseudo-terminal; the resource usage of a run; a first stop signal other than SIGTERM.
141
+
142
+ ## Who uses it
143
+
144
+ | Consumer | How | Record |
145
+ | ------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- | ------------------ |
146
+ | `@zukhruf/pool` workers, elt `VisionWorker` and `TranscriptionWorker` | `Coprocess`, today from `@zukhruf/coprocess` | coprocess ADR 0001 |
147
+ | the tests of mutex, single-flight and election | `NodeCommand`, today `startWorker` of `@zukhruf/testing/process` | testing ADR 0021 |
148
+ | shipped code of git-hooks, nx, ssh, tcc, mteb, sqlite-open, the tools | `Command#run` and `Command#start`, today `node:child_process` | backlog #6077 |
149
+ | the `sshd.ts` copies of docker, ssh and testing | `Command#start` with a socket as stdio, and the stop of the group | backlog #6077 |
150
+ | `runNode` of sdk-it, `cli` and `started` of context-compiler, `run` of text2sql, `collectOutput` of deepagents, `shell` of elt | `Command#run`, `Command#start`, `NodeCommand#run` | backlog #6077 |
151
+
152
+ ## The same concepts in other systems
153
+
154
+ | Concept | Other systems |
155
+ | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
156
+ | A run and its end as a value | .NET 11 `Process.RunAndCaptureTextAsync` and `ProcessExitStatus`, Python `subprocess.run` and `CompletedProcess`, Go `Cmd.Output`, Deno `Command.output()`, Rust `Command::output` |
157
+ | A started process | .NET `Process.Start`, Python `Popen`, Go `Cmd.Start`, Deno `Command.spawn()`, Rust `Command::spawn` |
158
+ | The step from SIGTERM to SIGKILL | Go `Cmd.Cancel` and `WaitDelay`, CliWrap's graceful and forceful tokens, execa `forceKillAfterDelay`, Kubernetes `terminationGracePeriodSeconds`, systemd `TimeoutStopSec` |
159
+ | The end with the parent | .NET 11 `ProcessStartInfo.KillOnParentExit` (Windows, Linux), Go `SysProcAttr.Pdeathsig` (Linux) |
160
+ | Ready | Testcontainers `waitingFor` (log message, listening port, HTTP, health check) |
161
+ | A disposal that stops | Deno `ChildProcess[Symbol.asyncDispose]`, tokio `kill_on_drop` |
162
+ | A coprocess | bash `coproc`, ksh `\|&` |
163
+
164
+ ## Why not a package of npm
165
+
166
+ The probes of 2026-11-27 are in [ADR 0008](./docs/adr/0008-execa-starts-the-process-and-keeps-its-output-and-the-package-stops-it-and-reads-its-lines-and-messages.md). No candidate (execa 10.2.1, nano-spawn 3.0.0, tinyexec 1.4.0, zx 8.8.5) ends a child with its parent at a SIGKILL, and none has a disposal. execa does the start and the stop, and this package uses it for them.
167
+
168
+ ## API
169
+
170
+ ```ts
171
+ import type { ChildProcess } from 'node:child_process';
172
+ import type { Socket } from 'node:net';
173
+ import type { Writable } from 'node:stream';
174
+
175
+ import type { Clock } from '@zukhruf/async';
176
+
177
+ /** The whole environment of the process. A value of undefined is left out. */
178
+ export type Environment = Readonly<Record<string, string | undefined>>;
179
+
180
+ /** How a process ended: an exit code, or the signal that ended it. */
181
+ export type End =
182
+ | { readonly exitCode: number; readonly signal?: undefined }
183
+ | { readonly signal: NodeJS.Signals; readonly exitCode?: undefined };
184
+
185
+ export interface Output {
186
+ readonly stdout: string;
187
+ readonly stderr: string;
188
+ /** stdout and stderr in the order that the process wrote them. */
189
+ readonly output: string;
190
+ }
191
+
192
+ export type Completed = End & Output;
193
+
194
+ export interface CommandOptions {
195
+ /** The whole environment of the process. */
196
+ readonly env: Environment;
197
+ /** Runs the grace (root ADR 0004). An app gives globalThis. */
198
+ readonly clock: Clock;
199
+ readonly cwd?: string;
200
+ /** Milliseconds from SIGTERM to SIGKILL. Default 5000. */
201
+ readonly grace?: number;
202
+ /** Names the process in each error. Default: the file. */
203
+ readonly name?: string;
204
+ }
205
+
206
+ export interface RunOptions {
207
+ /** Written to stdin, and then stdin ends. */
208
+ readonly input?: string | Uint8Array;
209
+ /** An abort stops the process and rejects with the reason. */
210
+ readonly signal?: AbortSignal;
211
+ }
212
+
213
+ interface Starting {
214
+ readonly signal?: AbortSignal;
215
+ readonly stderr?: 'pipe' | 'ignore';
216
+ }
217
+
218
+ /** The default: stdin and stdout piped. Only this start gives a piped process. */
219
+ export type PipedStartOptions = Starting & {
220
+ readonly stdin?: 'pipe';
221
+ readonly stdout?: 'pipe';
222
+ readonly ready?: { readonly line: string | RegExp };
223
+ };
224
+
225
+ export type StartOptions =
226
+ | PipedStartOptions
227
+ | (Starting & {
228
+ readonly stdin: 'ignore' | Socket;
229
+ readonly stdout?: 'pipe';
230
+ readonly ready?: { readonly line: string | RegExp };
231
+ })
232
+ | (Starting & {
233
+ readonly stdin?: 'pipe' | 'ignore' | Socket;
234
+ readonly stdout: 'ignore' | Socket;
235
+ readonly ready?: never;
236
+ });
237
+
238
+ /** What to run. It starts nothing until run() or start(). */
239
+ export class Command {
240
+ constructor(file: string, args: readonly string[], options: CommandOptions);
241
+ readonly file: string;
242
+ readonly args: readonly string[];
243
+ run(options?: RunOptions): Promise<Completed>;
244
+ start(options?: PipedStartOptions): Promise<PipedProcess>;
245
+ start(options: StartOptions): Promise<Process>;
246
+ }
247
+
248
+ /** A started process. Only start() of a command gives one. */
249
+ export interface Process extends AsyncDisposable {
250
+ readonly name: string;
251
+ readonly pid: number;
252
+ /** null when stdin is 'ignore' or a socket. */
253
+ readonly stdin: Writable | null;
254
+ /** Settles once, with the end. */
255
+ readonly ended: Promise<End>;
256
+ /** The lines of stdout from the first one, also those before the call. */
257
+ lines(): AsyncIterable<string>;
258
+ /** The last 16 KiB of stderr. */
259
+ stderrTail(): string;
260
+ /** SIGTERM to the group, SIGKILL to the group after the grace. */
261
+ stop(): Promise<End>;
262
+ }
263
+
264
+ /** A started process with its stdin and stdout piped. */
265
+ export interface PipedProcess extends Process {
266
+ readonly stdin: Writable;
267
+ }
268
+
269
+ export interface Message {
270
+ readonly type: string;
271
+ readonly [field: string]: unknown;
272
+ }
273
+
274
+ /** A type, or a function that selects a message. */
275
+ export type MessageMatch = string | ((message: Message) => boolean);
276
+
277
+ export interface NodeCommandOptions extends CommandOptions {
278
+ /** Node.js flags before the source. */
279
+ readonly nodeOptions?: readonly string[];
280
+ }
281
+
282
+ export interface NodeStartOptions extends Starting {
283
+ /** Gets the child before it can send, for example to join it to a coordinator. */
284
+ readonly admit?: (child: ChildProcess) => void;
285
+ readonly ready?:
286
+ { readonly line: string | RegExp } | { readonly message: MessageMatch };
287
+ }
288
+
289
+ /** JavaScript source to run as a module in its own Node.js, with an IPC channel. */
290
+ export class NodeCommand {
291
+ constructor(source: string, options: NodeCommandOptions);
292
+ run(options?: RunOptions): Promise<Completed>;
293
+ start(options?: NodeStartOptions): Promise<NodeProcess>;
294
+ }
295
+
296
+ export interface NodeProcess extends AsyncDisposable {
297
+ readonly process: PipedProcess;
298
+ /** Each message so far, in order. */
299
+ readonly messages: readonly Message[];
300
+ send(message: Message): void;
301
+ next(
302
+ match: MessageMatch,
303
+ options: { readonly signal: AbortSignal },
304
+ ): Promise<Message>;
305
+ [Symbol.asyncDispose](): Promise<void>;
306
+ }
307
+
308
+ /** The JSON-lines view of a started process. */
309
+ export class Coprocess implements AsyncDisposable {
310
+ constructor(process: PipedProcess);
311
+ readonly process: PipedProcess;
312
+ send(value: unknown): void;
313
+ receive(): Promise<unknown>;
314
+ request(value: unknown): Promise<unknown>;
315
+ /** Settles once, with the error that each later receive gets. */
316
+ exited(): Promise<Error>;
317
+ /** Ends stdin and waits for the end. */
318
+ close(): Promise<End>;
319
+ [Symbol.asyncDispose](): Promise<void>;
320
+ }
321
+
322
+ export class StartError extends Error {}
323
+
324
+ export class EndedBeforeReadyError extends Error {
325
+ readonly end: End;
326
+ /** The stderr tail. */
327
+ readonly stderr: string;
328
+ }
329
+ ```
330
+
331
+ ## Documentation
332
+
333
+ - The glossary: [CONTEXT.md](./CONTEXT.md).
334
+ - The decisions: [docs/adr](./docs/adr).
@@ -0,0 +1,29 @@
1
+ import type { Clock } from '@zukhruf/async';
2
+ import type { Completed, Environment } from './end.ts';
3
+ export interface CommandOptions {
4
+ /** The whole environment of the process (ADR 0003). */
5
+ readonly env: Environment;
6
+ /** The clock of each wait, such as the grace (root ADR 0004). An app gives `globalThis`. */
7
+ readonly clock: Clock;
8
+ readonly cwd?: string;
9
+ /** Milliseconds from SIGTERM to SIGKILL. Default 5000. */
10
+ readonly grace?: number;
11
+ /** Names the process in each error. Default: the file. */
12
+ readonly name?: string;
13
+ }
14
+ export interface RunOptions {
15
+ /** Written to stdin, and then stdin ends. */
16
+ readonly input?: string | Uint8Array;
17
+ /** An abort stops the process and rejects with the reason. */
18
+ readonly signal?: AbortSignal;
19
+ }
20
+ /** What to run. It starts nothing until `run()` or `start()` (ADR 0010). */
21
+ export declare class Command {
22
+ #private;
23
+ readonly file: string;
24
+ readonly args: readonly string[];
25
+ constructor(file: string, args: readonly string[], options: CommandOptions);
26
+ /** Runs the command to its end, and gives its end and its output. */
27
+ run({ input, signal }?: RunOptions): Promise<Completed>;
28
+ }
29
+ //# sourceMappingURL=command.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command.d.ts","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAE5C,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAMvD,MAAM,WAAW,cAAc;IAC7B,uDAAuD;IACvD,QAAQ,CAAC,GAAG,EAAE,WAAW,CAAC;IAC1B,4FAA4F;IAC5F,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,0DAA0D;IAC1D,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,0DAA0D;IAC1D,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,UAAU;IACzB,6CAA6C;IAC7C,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,UAAU,CAAC;IACrC,8DAA8D;IAC9D,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC/B;AAED,4EAA4E;AAC5E,qBAAa,OAAO;;IAClB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;IAKjC,YAAY,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,EAAE,cAAc,EAKzE;IAED,qEAAqE;IAC/D,GAAG,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,GAAE,UAAe,GAAG,OAAO,CAAC,SAAS,CAAC,CAkEhE;CAqBF"}
@@ -0,0 +1,92 @@
1
+ import { execa } from 'execa';
2
+ import { findFile } from './file.js';
3
+ import { KEEPER, environmentFixes } from './keeper.js';
4
+ import { StartError } from './start-error.js';
5
+ import { stopGroup } from './stop.js';
6
+ /** What to run. It starts nothing until `run()` or `start()` (ADR 0010). */
7
+ export class Command {
8
+ file;
9
+ args;
10
+ #options;
11
+ /** Milliseconds from SIGTERM to SIGKILL: of the keeper and of a stop. */
12
+ #grace;
13
+ constructor(file, args, options) {
14
+ this.file = file;
15
+ this.args = args;
16
+ this.#options = options;
17
+ this.#grace = options.grace ?? 5000;
18
+ }
19
+ /** Runs the command to its end, and gives its end and its output. */
20
+ async run({ input, signal } = {}) {
21
+ signal?.throwIfAborted();
22
+ const env = Object.fromEntries(Object.entries(this.#options.env).filter((entry) => entry[1] !== undefined));
23
+ const cwd = this.#options.cwd ?? process.cwd();
24
+ let path;
25
+ try {
26
+ path = await findFile(this.file, env, cwd);
27
+ }
28
+ catch (cause) {
29
+ throw new StartError(`${this.#options.name ?? this.file} could not start`, { cause });
30
+ }
31
+ const fixes = environmentFixes(env);
32
+ const subprocess = execa('/bin/sh', [
33
+ '-c',
34
+ KEEPER,
35
+ 'keeper',
36
+ String(this.#grace / 1000),
37
+ '/usr/bin/env',
38
+ ...fixes,
39
+ path,
40
+ ...this.args,
41
+ ], {
42
+ env,
43
+ extendEnv: false,
44
+ cwd,
45
+ detached: true,
46
+ cleanup: false,
47
+ stdio: [
48
+ input === undefined ? 'ignore' : 'pipe',
49
+ 'pipe',
50
+ 'pipe',
51
+ 'pipe',
52
+ ],
53
+ ...(input === undefined ? {} : { input }),
54
+ reject: false,
55
+ all: true,
56
+ stripFinalNewline: false,
57
+ });
58
+ const stopped = signal === undefined || subprocess.pid === undefined
59
+ ? undefined
60
+ : this.#stopOnAbort(subprocess.pid, subprocess, signal);
61
+ const result = await subprocess;
62
+ if (signal?.aborted) {
63
+ await stopped?.promise;
64
+ throw signal.reason;
65
+ }
66
+ stopped?.[Symbol.dispose]();
67
+ const output = {
68
+ stdout: result.stdout,
69
+ stderr: result.stderr,
70
+ output: result.all,
71
+ };
72
+ return result.signal === undefined
73
+ ? { exitCode: result.exitCode ?? 0, ...output }
74
+ : { signal: result.signal, ...output };
75
+ }
76
+ /** Stops the group of the keeper at an abort of `signal`. */
77
+ #stopOnAbort(pgid, keeperEnded, signal) {
78
+ const stop = Promise.withResolvers();
79
+ const listener = () => {
80
+ stopGroup(pgid, keeperEnded, {
81
+ grace: this.#grace,
82
+ clock: this.#options.clock,
83
+ }).then(stop.resolve, stop.reject);
84
+ };
85
+ signal.addEventListener('abort', listener, { once: true });
86
+ return {
87
+ promise: stop.promise,
88
+ [Symbol.dispose]: () => signal.removeEventListener('abort', listener),
89
+ };
90
+ }
91
+ }
92
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC;AAK9B,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAqBtC,4EAA4E;AAC5E,MAAM,OAAO,OAAO;IACT,IAAI,CAAS;IACb,IAAI,CAAoB;IACxB,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,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;IAC3C,CAAC;IAED,6DAA6D;IAC7D,YAAY,CACV,IAAY,EACZ,WAA6B,EAC7B,MAAmB;QAEnB,MAAM,IAAI,GAAG,OAAO,CAAC,aAAa,EAAQ,CAAC;QAC3C,MAAM,QAAQ,GAAG,GAAG,EAAE;YACpB,SAAS,CAAC,IAAI,EAAE,WAAW,EAAE;gBAC3B,KAAK,EAAE,IAAI,CAAC,MAAM;gBAClB,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,KAAK;aAC3B,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QACrC,CAAC,CAAC;QACF,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3D,OAAO;YACL,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,QAAQ,CAAC;SACtE,CAAC;IACJ,CAAC;CACF"}
package/dist/end.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ /** The whole environment of a process. A value of undefined is left out. */
2
+ export type Environment = Readonly<Record<string, string | undefined>>;
3
+ /** How a process ended: an exit code, or the signal that ended it. */
4
+ export type End = {
5
+ readonly exitCode: number;
6
+ readonly signal?: undefined;
7
+ } | {
8
+ readonly signal: NodeJS.Signals;
9
+ readonly exitCode?: undefined;
10
+ };
11
+ /** What a run printed. The text keeps its last newline. */
12
+ export interface Output {
13
+ readonly stdout: string;
14
+ readonly stderr: string;
15
+ /** stdout and stderr in the order that the process wrote them. */
16
+ readonly output: string;
17
+ }
18
+ export type Completed = End & Output;
19
+ //# sourceMappingURL=end.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"end.d.ts","sourceRoot":"","sources":["../src/end.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,MAAM,MAAM,WAAW,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;AAEvE,sEAAsE;AACtE,MAAM,MAAM,GAAG,GACX;IAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,CAAA;CAAE,GAC1D;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,OAAO,CAAC;IAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAA;CAAE,CAAC;AAEvE,2DAA2D;AAC3D,MAAM,WAAW,MAAM;IACrB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,kEAAkE;IAClE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,MAAM,SAAS,GAAG,GAAG,GAAG,MAAM,CAAC"}
package/dist/end.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=end.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"end.js","sourceRoot":"","sources":["../src/end.ts"],"names":[],"mappings":""}
package/dist/file.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { Environment } from './end.ts';
2
+ /**
3
+ * The path that the process starts from: a name without a slash on the `PATH`
4
+ * of `env`, any other name at its path from `cwd`.
5
+ *
6
+ * This predicts the start instead of trying it (ADR 0002). Under the keeper,
7
+ * `sh` always starts, and a failed `exec` ends with 126 or 127, the codes that
8
+ * a process can also give itself, so the trial cannot tell a missing file from
9
+ * an exit. A file that goes away between this check and the start ends with
10
+ * 127.
11
+ */
12
+ export declare function findFile(file: string, env: Environment, cwd: string): Promise<string>;
13
+ //# sourceMappingURL=file.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file.d.ts","sourceRoot":"","sources":["../src/file.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAE5C;;;;;;;;;GASG;AACH,wBAAsB,QAAQ,CAC5B,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,WAAW,EAChB,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,MAAM,CAAC,CAyBjB"}
package/dist/file.js ADDED
@@ -0,0 +1,51 @@
1
+ import { constants } from 'node:fs';
2
+ import { access, stat } from 'node:fs/promises';
3
+ import { delimiter, join, resolve } from 'node:path';
4
+ /**
5
+ * The path that the process starts from: a name without a slash on the `PATH`
6
+ * of `env`, any other name at its path from `cwd`.
7
+ *
8
+ * This predicts the start instead of trying it (ADR 0002). Under the keeper,
9
+ * `sh` always starts, and a failed `exec` ends with 126 or 127, the codes that
10
+ * a process can also give itself, so the trial cannot tell a missing file from
11
+ * an exit. A file that goes away between this check and the start ends with
12
+ * 127.
13
+ */
14
+ export async function findFile(file, env, cwd) {
15
+ if (file.includes('/')) {
16
+ const path = resolve(cwd, file);
17
+ await executable(path);
18
+ return path;
19
+ }
20
+ let refused;
21
+ for (const folder of (env['PATH'] ?? '').split(delimiter)) {
22
+ if (folder === '')
23
+ continue;
24
+ const path = join(folder, file);
25
+ try {
26
+ await executable(path);
27
+ return path;
28
+ }
29
+ catch (error) {
30
+ if (code(error) === 'EACCES' && Error.isError(error))
31
+ refused ??= error;
32
+ else if (code(error) !== 'ENOENT' && code(error) !== 'ENOTDIR')
33
+ throw error;
34
+ }
35
+ }
36
+ throw (refused ??
37
+ Object.assign(new Error(`${file} is not on the PATH of the environment`), {
38
+ code: 'ENOENT',
39
+ }));
40
+ }
41
+ async function executable(path) {
42
+ await access(path, constants.X_OK);
43
+ if (!(await stat(path)).isFile())
44
+ throw Object.assign(new Error(`${path} is not a file`), {
45
+ code: 'EACCES',
46
+ });
47
+ }
48
+ function code(error) {
49
+ return Reflect.get(Object(error), 'code');
50
+ }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IACD,MAAM,CACJ,OAAO;QACP,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,GAAG,IAAI,wCAAwC,CAAC,EAAE;YACxE,IAAI,EAAE,QAAQ;SACf,CAAC,CACH,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,UAAU,CAAC,IAAY;IACpC,MAAM,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC;IACnC,IAAI,CAAC,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE;QAC9B,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,GAAG,IAAI,gBAAgB,CAAC,EAAE;YACtD,IAAI,EAAE,QAAQ;SACf,CAAC,CAAC;AACP,CAAC;AAED,SAAS,IAAI,CAAC,KAAc;IAC1B,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,CAAC;AAC5C,CAAC"}
@@ -0,0 +1,4 @@
1
+ export { Command, type CommandOptions, type RunOptions } from './command.ts';
2
+ export type { Completed, End, Environment, Output } from './end.ts';
3
+ export { StartError } from './start-error.ts';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,UAAU,EAAE,MAAM,cAAc,CAAC;AAC7E,YAAY,EAAE,SAAS,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACpE,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { Command } from './command.js';
2
+ export { StartError } from './start-error.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAwC,MAAM,cAAc,CAAC;AAE7E,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The keeper of ADR 0004, run as
3
+ * `/bin/sh -c KEEPER keeper <grace in seconds> /usr/bin/env <fix>... <file> <arg>...`.
4
+ *
5
+ * The parent starts it detached, so it leads its own process group, and gives
6
+ * it a lifeline at fd 3 that the parent never writes. A watcher reads fd 3; at
7
+ * its end (the parent ended, in any way) it sends SIGTERM to the group, and
8
+ * SIGKILL after the grace. The target runs in the foreground of the group, so
9
+ * it keeps its stdin and its signals, and the keeper ends as the target ended.
10
+ *
11
+ * `/usr/bin/env` makes the last exec, with `-u NAME` for each variable that
12
+ * `sh` adds and the caller did not give, and `NAME=value` for each that the
13
+ * caller gave, so the target gets the caller's environment and nothing else
14
+ * (ADR 0003). The shell cannot do it itself: the `exec` of bash rewrites
15
+ * SHLVL (an unset SHLVL arrives as 0, a given 7 as 6; probed 2026-11-27). A
16
+ * file whose path holds `=` would be read by env as an assignment. The
17
+ * watcher closes fd 4, which a Node.js target uses as its IPC channel.
18
+ *
19
+ * Each line was probed on bash 3.2 as /bin/sh, dash, zsh and busybox ash
20
+ * (2026-11-27): only `kill -SIG -N` reads the same in all four, and the
21
+ * shell's own job notices ("Killed: 9") go to /dev/null, not to the target.
22
+ */
23
+ export declare const KEEPER = "\nkill -0 -$$ 2>/dev/null || { echo 'keeper: start me detached' >&2; exit 126; }\ngrace=$1; shift\n(\n trap '' TERM\n while read -r _; do :; done <&3\n kill -TERM -$$; sleep \"$grace\"; kill -KILL -$$\n) </dev/null >/dev/null 2>&1 4>&- &\nwpid=$!\nexec 3<&-\ntrap : TERM INT HUP\n{ (exec 2>&9 9>&-; exec \"$@\"); st=$?; } 9>&2 2>/dev/null\nkill -KILL \"$wpid\" 2>/dev/null\ntrap - TERM INT HUP\n[ \"$st\" -gt 128 ] && kill -\"$((st - 128))\" $$\nexit \"$st\"\n";
24
+ /** The operands of `/usr/bin/env` that undo what `sh` adds to `env`. */
25
+ export declare function environmentFixes(env: Readonly<Record<string, string>>): string[];
26
+ //# sourceMappingURL=keeper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keeper.d.ts","sourceRoot":"","sources":["../src/keeper.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,MAAM,odAgBlB,CAAC;AAKF,wEAAwE;AACxE,wBAAgB,gBAAgB,CAC9B,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GACpC,MAAM,EAAE,CASV"}
package/dist/keeper.js ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The keeper of ADR 0004, run as
3
+ * `/bin/sh -c KEEPER keeper <grace in seconds> /usr/bin/env <fix>... <file> <arg>...`.
4
+ *
5
+ * The parent starts it detached, so it leads its own process group, and gives
6
+ * it a lifeline at fd 3 that the parent never writes. A watcher reads fd 3; at
7
+ * its end (the parent ended, in any way) it sends SIGTERM to the group, and
8
+ * SIGKILL after the grace. The target runs in the foreground of the group, so
9
+ * it keeps its stdin and its signals, and the keeper ends as the target ended.
10
+ *
11
+ * `/usr/bin/env` makes the last exec, with `-u NAME` for each variable that
12
+ * `sh` adds and the caller did not give, and `NAME=value` for each that the
13
+ * caller gave, so the target gets the caller's environment and nothing else
14
+ * (ADR 0003). The shell cannot do it itself: the `exec` of bash rewrites
15
+ * SHLVL (an unset SHLVL arrives as 0, a given 7 as 6; probed 2026-11-27). A
16
+ * file whose path holds `=` would be read by env as an assignment. The
17
+ * watcher closes fd 4, which a Node.js target uses as its IPC channel.
18
+ *
19
+ * Each line was probed on bash 3.2 as /bin/sh, dash, zsh and busybox ash
20
+ * (2026-11-27): only `kill -SIG -N` reads the same in all four, and the
21
+ * shell's own job notices ("Killed: 9") go to /dev/null, not to the target.
22
+ */
23
+ export const KEEPER = `
24
+ kill -0 -$$ 2>/dev/null || { echo 'keeper: start me detached' >&2; exit 126; }
25
+ grace=$1; shift
26
+ (
27
+ trap '' TERM
28
+ while read -r _; do :; done <&3
29
+ kill -TERM -$$; sleep "$grace"; kill -KILL -$$
30
+ ) </dev/null >/dev/null 2>&1 4>&- &
31
+ wpid=$!
32
+ exec 3<&-
33
+ trap : TERM INT HUP
34
+ { (exec 2>&9 9>&-; exec "$@"); st=$?; } 9>&2 2>/dev/null
35
+ kill -KILL "$wpid" 2>/dev/null
36
+ trap - TERM INT HUP
37
+ [ "$st" -gt 128 ] && kill -"$((st - 128))" $$
38
+ exit "$st"
39
+ `;
40
+ /** The variables that `sh` adds to the environment of its children. */
41
+ const SHELL_VARIABLES = ['PWD', 'SHLVL'];
42
+ /** The operands of `/usr/bin/env` that undo what `sh` adds to `env`. */
43
+ export function environmentFixes(env) {
44
+ const given = SHELL_VARIABLES.filter((name) => name in env);
45
+ return [
46
+ ...SHELL_VARIABLES.filter((name) => !(name in env)).flatMap((name) => [
47
+ '-u',
48
+ name,
49
+ ]),
50
+ ...given.map((name) => `${name}=${env[name]}`),
51
+ ];
52
+ }
53
+ //# sourceMappingURL=keeper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keeper.js","sourceRoot":"","sources":["../src/keeper.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG;;;;;;;;;;;;;;;;CAgBrB,CAAC;AAEF,uEAAuE;AACvE,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,OAAO,CAAU,CAAC;AAElD,wEAAwE;AACxE,MAAM,UAAU,gBAAgB,CAC9B,GAAqC;IAErC,MAAM,KAAK,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,GAAG,CAAC,CAAC;IAC5D,OAAO;QACL,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;YACpE,IAAI;YACJ,IAAI;SACL,CAAC;QACF,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,IAAI,IAAI,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;KAC/C,CAAC;AACJ,CAAC"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The process could not start: its file is not there, or it is not
3
+ * executable. The `cause` is the error of the file, with its `code` (`ENOENT`,
4
+ * `EACCES`). The message names the file and never the arguments, because
5
+ * arguments can hold prompts or secrets.
6
+ */
7
+ export declare class StartError extends Error {
8
+ readonly name = "StartError";
9
+ }
10
+ //# sourceMappingURL=start-error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"start-error.d.ts","sourceRoot":"","sources":["../src/start-error.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,qBAAa,UAAW,SAAQ,KAAK;IACnC,SAAkB,IAAI,gBAAgB;CACvC"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The process could not start: its file is not there, or it is not
3
+ * executable. The `cause` is the error of the file, with its `code` (`ENOENT`,
4
+ * `EACCES`). The message names the file and never the arguments, because
5
+ * arguments can hold prompts or secrets.
6
+ */
7
+ export class StartError extends Error {
8
+ name = 'StartError';
9
+ }
10
+ //# sourceMappingURL=start-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"start-error.js","sourceRoot":"","sources":["../src/start-error.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,OAAO,UAAW,SAAQ,KAAK;IACjB,IAAI,GAAG,YAAY,CAAC;CACvC"}
package/dist/stop.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { type Clock } from '@zukhruf/async';
2
+ /**
3
+ * Stops the process group of a keeper (ADR 0005): SIGTERM to the group, and
4
+ * SIGKILL to the group when it still runs after `grace` on `clock`. Resolves
5
+ * when the keeper has ended and no member of the group is left.
6
+ *
7
+ * After the keeper ends, a member that SIGTERM ended can still be in the group
8
+ * for a moment, until its new parent reaps it, so the group is polled until it
9
+ * is empty. After the SIGKILL nothing in the group can run, so nothing is
10
+ * polled then.
11
+ */
12
+ export declare function stopGroup(pgid: number, keeperEnded: Promise<unknown>, { grace, clock }: {
13
+ grace: number;
14
+ clock: Clock;
15
+ }): Promise<void>;
16
+ //# sourceMappingURL=stop.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stop.d.ts","sourceRoot":"","sources":["../src/stop.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,KAAK,EAAQ,MAAM,gBAAgB,CAAC;AAElD;;;;;;;;;GASG;AACH,wBAAsB,SAAS,CAC7B,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,OAAO,CAAC,OAAO,CAAC,EAC7B,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,KAAK,CAAA;CAAE,GAChD,OAAO,CAAC,IAAI,CAAC,CA0Bf"}
package/dist/stop.js ADDED
@@ -0,0 +1,62 @@
1
+ import { poll } from '@zukhruf/async';
2
+ /**
3
+ * Stops the process group of a keeper (ADR 0005): SIGTERM to the group, and
4
+ * SIGKILL to the group when it still runs after `grace` on `clock`. Resolves
5
+ * when the keeper has ended and no member of the group is left.
6
+ *
7
+ * After the keeper ends, a member that SIGTERM ended can still be in the group
8
+ * for a moment, until its new parent reaps it, so the group is polled until it
9
+ * is empty. After the SIGKILL nothing in the group can run, so nothing is
10
+ * polled then.
11
+ */
12
+ export async function stopGroup(pgid, keeperEnded, { grace, clock }) {
13
+ signalGroup(pgid, 'SIGTERM');
14
+ const killed = Promise.withResolvers();
15
+ const timer = clock.setTimeout(() => {
16
+ signalGroup(pgid, 'SIGKILL');
17
+ killed.resolve();
18
+ }, grace);
19
+ const settled = new AbortController();
20
+ try {
21
+ const killedFirst = await Promise.race([
22
+ keeperEnded.then(() => false),
23
+ killed.promise.then(() => true),
24
+ ]);
25
+ if (killedFirst)
26
+ return;
27
+ const emptied = poll(async () => (groupIsEmpty(pgid) ? true : undefined), {
28
+ interval: 10,
29
+ clock,
30
+ signal: settled.signal,
31
+ }).catch((error) => {
32
+ if (!settled.signal.aborted)
33
+ throw error;
34
+ });
35
+ await Promise.race([killed.promise, emptied]);
36
+ }
37
+ finally {
38
+ settled.abort();
39
+ clock.clearTimeout(timer);
40
+ }
41
+ }
42
+ function signalGroup(pgid, signal) {
43
+ try {
44
+ process.kill(-pgid, signal);
45
+ }
46
+ catch (error) {
47
+ if (Reflect.get(Object(error), 'code') !== 'ESRCH')
48
+ throw error;
49
+ }
50
+ }
51
+ function groupIsEmpty(pgid) {
52
+ try {
53
+ process.kill(-pgid, 0);
54
+ return false;
55
+ }
56
+ catch (error) {
57
+ if (Reflect.get(Object(error), 'code') === 'ESRCH')
58
+ return true;
59
+ throw error;
60
+ }
61
+ }
62
+ //# sourceMappingURL=stop.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stop.js","sourceRoot":"","sources":["../src/stop.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAElD;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,IAAY,EACZ,WAA6B,EAC7B,EAAE,KAAK,EAAE,KAAK,EAAmC;IAEjD,WAAW,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;IAC7B,MAAM,MAAM,GAAG,OAAO,CAAC,aAAa,EAAQ,CAAC;IAC7C,MAAM,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,GAAG,EAAE;QAClC,WAAW,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;QAC7B,MAAM,CAAC,OAAO,EAAE,CAAC;IACnB,CAAC,EAAE,KAAK,CAAC,CAAC;IACV,MAAM,OAAO,GAAG,IAAI,eA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IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QACvB,OAAO,KAAK,CAAC;IACf,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,KAAK,OAAO;YAAE,OAAO,IAAI,CAAC;QAChE,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@zukhruf/process",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.8.153",
4
+ "description": "Start a process and know how it ends: a run gives its exit code or signal and its output with no throw; a started process is ready at a line or a message, stops its group with SIGTERM then SIGKILL, and ends with its parent.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/JanuaryLabs/zukhruf",
9
+ "directory": "packages/process"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/JanuaryLabs/zukhruf/issues"
13
+ },
14
+ "homepage": "https://github.com/JanuaryLabs/zukhruf/tree/main/packages/process#readme",
15
+ "keywords": [
16
+ "process",
17
+ "child-process",
18
+ "subprocess",
19
+ "spawn",
20
+ "exec",
21
+ "coprocess",
22
+ "process-group",
23
+ "sigterm",
24
+ "ipc"
25
+ ],
26
+ "type": "module",
27
+ "exports": {
28
+ "./package.json": "./package.json",
29
+ ".": {
30
+ "@zukhruf/source": "./src/index.ts",
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js",
33
+ "default": "./dist/index.js"
34
+ }
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "!dist/spec/**",
39
+ "!**/*.tsbuildinfo",
40
+ "!**/*.test.*"
41
+ ],
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "dependencies": {
46
+ "@zukhruf/async": "^0.8.153",
47
+ "execa": "10.2.1"
48
+ },
49
+ "devDependencies": {
50
+ "@sinonjs/fake-timers": "15.5.0",
51
+ "@zukhruf/fs": "^0.8.153"
52
+ }
53
+ }