@vouchington/server-utils 0.0.0-stage → 0.0.0
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 +9 -0
- package/README.md +56 -2
- package/dist/api-errors.d.mts +29 -0
- package/dist/api-errors.mjs +95 -0
- package/dist/child-process-error.d.mts +13 -0
- package/dist/child-process-error.mjs +19 -0
- package/dist/child-process-process.d.mts +30 -0
- package/dist/child-process-process.mjs +135 -0
- package/dist/child-process-run.d.mts +18 -0
- package/dist/child-process-run.mjs +132 -0
- package/dist/child-process.d.mts +2 -0
- package/dist/child-process.mjs +1 -0
- package/dist/error-tree.d.mts +8 -0
- package/dist/error-tree.mjs +94 -0
- package/dist/graceful-shutdown-one-off.d.mts +15 -0
- package/dist/graceful-shutdown-one-off.mjs +20 -0
- package/dist/graceful-shutdown-registry.d.mts +27 -0
- package/dist/graceful-shutdown-registry.mjs +29 -0
- package/dist/graceful-shutdown-run.d.mts +32 -0
- package/dist/graceful-shutdown-run.mjs +61 -0
- package/dist/graceful-shutdown.d.mts +3 -0
- package/dist/graceful-shutdown.mjs +3 -0
- package/dist/http-signatures-digest.d.mts +3 -0
- package/dist/http-signatures-digest.mjs +20 -0
- package/dist/http-signatures-keys.d.mts +7 -0
- package/dist/http-signatures-keys.mjs +27 -0
- package/dist/http-signatures-sign.d.mts +17 -0
- package/dist/http-signatures-sign.mjs +35 -0
- package/dist/http-signatures-string.d.mts +12 -0
- package/dist/http-signatures-string.mjs +40 -0
- package/dist/http-signatures-verify.d.mts +21 -0
- package/dist/http-signatures-verify.mjs +88 -0
- package/dist/http-signatures.d.mts +4 -0
- package/dist/http-signatures.mjs +4 -0
- package/dist/jsonl-partition-writer.d.mts +20 -0
- package/dist/jsonl-partition-writer.mjs +86 -0
- package/dist/token-secrets.d.mts +14 -0
- package/dist/token-secrets.mjs +102 -0
- package/dist/url-signing-hosts.d.mts +18 -0
- package/dist/url-signing-hosts.mjs +61 -0
- package/dist/url-signing-keys.d.mts +23 -0
- package/dist/url-signing-keys.mjs +66 -0
- package/dist/url-signing-proxy.d.mts +19 -0
- package/dist/url-signing-proxy.mjs +36 -0
- package/dist/url-signing.d.mts +3 -0
- package/dist/url-signing.mjs +3 -0
- package/dist/web-push-vapid.d.mts +26 -0
- package/dist/web-push-vapid.mjs +107 -0
- package/package.json +74 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jonathan Ong
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,57 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @vouchington/server-utils
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Dependency-free server-only utilities that run on both Node.js 24 and Bun. Code here may import
|
|
4
|
+
Node built-ins that both runtimes implement (`node:crypto`, `node:child_process`,
|
|
5
|
+
`node:fs/promises`, `node:stream`, `node:util`, `node:http`, `node:path`); it has no third-party
|
|
6
|
+
runtime dependencies. Portable code that imports no Node built-in belongs in
|
|
7
|
+
`@vouchington/utils`. Every export entry is bundled with Bun and compared with Node by
|
|
8
|
+
`pnpm run test:bun-bundles`. This package deliberately has no root export: import the capability
|
|
9
|
+
you use from an explicit subpath.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { createTokenSecrets } from '@vouchington/server-utils/token-secrets'
|
|
13
|
+
import { buildSignatureHeaders, verifySignature } from '@vouchington/server-utils/http-signatures'
|
|
14
|
+
import { runCommand } from '@vouchington/server-utils/child-process'
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Subpaths
|
|
18
|
+
|
|
19
|
+
- `api-errors`: the house JSON error envelope (`message`, optional `code`, `request_id`, `stack`),
|
|
20
|
+
status/message/code extraction helpers, and `buildApiErrorEnvelope`, which redacts 5xx details
|
|
21
|
+
unless the caller sets `exposeDetails`. Callers own serialization, logging, and environment policy.
|
|
22
|
+
- `child-process`: `runCommand({ command, args, stdin, stdout, signal,
|
|
23
|
+
timeoutMs, stderrCapBytes, env })` spawns an explicit argv with no shell, streams stdin and stdout,
|
|
24
|
+
keeps stderr up to a byte cap, and SIGKILLs on abort or timeout. By default the child sees only
|
|
25
|
+
`PATH`, `TMPDIR`, and `LC_ALL=C`; `env` replaces that. Non-zero exit, signal, abort, and timeout
|
|
26
|
+
reject with `CommandFailedError` (`reason`, `exitCode`, `signal`, `stderr`).
|
|
27
|
+
- `error-tree`: `formatErrorTree(error, { maxDepth?, maxNested? })` renders an error with its
|
|
28
|
+
`errors[]` and `cause` chain, marks circular references, and reports how many nested errors the
|
|
29
|
+
depth and count limits omitted (defaults 5 and 20).
|
|
30
|
+
- `graceful-shutdown`: `createGracefulShutdown({ gracePeriodMs, onError, closeResources, flush,
|
|
31
|
+
log, logError, process, forceExit })` runs callbacks, then drain callbacks, then `closeResources`,
|
|
32
|
+
then `flush`, once, with an unref'd force-exit fallback (code 0 after success, 1 on timeout);
|
|
33
|
+
`installSignalHandlers()` wires SIGTERM and SIGINT. `createShutdownRegistry()` is a late-binding
|
|
34
|
+
`register(name, shutdown)` / `close({ shutdowns, log })` registry that returns failures instead of
|
|
35
|
+
throwing, and `shutdownForOneOffCommand({ gracePeriodMs, close })` bounds a short-lived command's
|
|
36
|
+
close and throws an `AggregateError`. The grace period, resource names, error reporting, and
|
|
37
|
+
signal-registration policy are all injected.
|
|
38
|
+
- `http-signatures`: Cavage-12 HTTP Signatures. Callers pass signed
|
|
39
|
+
headers, allowed algorithms, and `maxAgeSeconds` on both sign and verify. The package has no
|
|
40
|
+
default header set or product keyId policy.
|
|
41
|
+
- `jsonl-partition-writer`: `createJsonlPartitionWriter({ directory, partition, onError })` buffers
|
|
42
|
+
records and appends them to per-partition JSON Lines files on count, size, or time (defaults 500
|
|
43
|
+
records, 4 MiB, 1 s). `partition(record)` returns the relative file path, which must stay inside
|
|
44
|
+
`directory`; background failures go to `onError`, explicit `flush()` rejects with the first one.
|
|
45
|
+
- `token-secrets`: purpose-bound HMAC and AES-256-GCM encryption.
|
|
46
|
+
`createTokenSecrets({ hashSecret, encryptionKeys })` throws for invalid keys or ciphertext.
|
|
47
|
+
- `url-signing`: HMAC SHA-256 path signing (`signPathWithKey`, `signPath`,
|
|
48
|
+
`verifyPathSignature` with rotation, `signExpiringPath`/`verifyExpiringPath` with an injectable
|
|
49
|
+
clock), `parseSigningKeys`, `buildSignedProxyUrl` (caller-owned origin, route prefix, query, and
|
|
50
|
+
skip predicate), and `createProtectedHostPolicy` (Unicode bare hosts are
|
|
51
|
+
canonicalized to punycode), and `matchRouteSegment`.
|
|
52
|
+
Prefixes, hosts, and keys are injected; verification fails closed with no keys unless
|
|
53
|
+
`allowUnsignedWhenNoKeys` is set.
|
|
54
|
+
- `web-push-vapid`: VAPID key generation/matching and ES256 JWT/`Authorization` builders.
|
|
55
|
+
Applications own key storage, subject, and delivery.
|
|
56
|
+
|
|
57
|
+
Applications supply all product identifiers, policy, keys, and persistence.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** House JSON error envelope. `code`, `request_id`, and `stack` are omitted when absent. */
|
|
2
|
+
export interface ApiErrorEnvelope {
|
|
3
|
+
readonly message: string;
|
|
4
|
+
readonly code?: string;
|
|
5
|
+
readonly request_id?: string;
|
|
6
|
+
readonly stack?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface BuildApiErrorEnvelopeOptions {
|
|
9
|
+
/** Request correlation id echoed as `request_id`. */
|
|
10
|
+
readonly requestId?: string | null;
|
|
11
|
+
/** When false, 5xx errors are redacted to the status text and stacks are omitted. */
|
|
12
|
+
readonly exposeDetails: boolean;
|
|
13
|
+
}
|
|
14
|
+
export declare function getErrorStatus(error: unknown): number;
|
|
15
|
+
/** Stamps `status` on 5xx errors so loggers and reporters classify them consistently. */
|
|
16
|
+
export declare function normalizeErrorForLogging(error: Error): Error;
|
|
17
|
+
export declare function getErrorResponseMessage(error: unknown, status: number): string;
|
|
18
|
+
export declare function getErrorResponseCode(error: unknown, status: number): string | undefined;
|
|
19
|
+
export declare function getErrorResponseStack(error: unknown): string | undefined;
|
|
20
|
+
export declare function getStatusMessage(status: number): string;
|
|
21
|
+
/**
|
|
22
|
+
* Builds the house error envelope. With `exposeDetails: false`, 5xx errors collapse to the HTTP
|
|
23
|
+
* status text with code `INTERNAL_ERROR` and never leak messages or stacks; 4xx messages and
|
|
24
|
+
* codes are still returned. Callers own serialization, logging, and environment policy.
|
|
25
|
+
*/
|
|
26
|
+
export declare function buildApiErrorEnvelope(error: unknown, options: BuildApiErrorEnvelopeOptions): {
|
|
27
|
+
readonly status: number;
|
|
28
|
+
readonly body: ApiErrorEnvelope;
|
|
29
|
+
};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { STATUS_CODES } from 'node:http';
|
|
2
|
+
export function getErrorStatus(error) {
|
|
3
|
+
if (!isObjectLike(error))
|
|
4
|
+
return 500;
|
|
5
|
+
return (getValidHttpStatus(safeRead(error, 'status')) ??
|
|
6
|
+
getValidHttpStatus(safeRead(error, 'statusCode')) ??
|
|
7
|
+
500);
|
|
8
|
+
}
|
|
9
|
+
/** Stamps `status` on 5xx errors so loggers and reporters classify them consistently. */
|
|
10
|
+
export function normalizeErrorForLogging(error) {
|
|
11
|
+
const status = getErrorStatus(error);
|
|
12
|
+
if (status >= 500)
|
|
13
|
+
Object.assign(error, { status });
|
|
14
|
+
return error;
|
|
15
|
+
}
|
|
16
|
+
export function getErrorResponseMessage(error, status) {
|
|
17
|
+
if (isObjectLike(error)) {
|
|
18
|
+
const message = safeRead(error, 'message');
|
|
19
|
+
if (message !== undefined && message !== null) {
|
|
20
|
+
return safeString(message) ?? getStatusMessage(status);
|
|
21
|
+
}
|
|
22
|
+
return getStatusMessage(status);
|
|
23
|
+
}
|
|
24
|
+
if (error === null || error === undefined)
|
|
25
|
+
return getStatusMessage(status);
|
|
26
|
+
// Only primitives reach here, and String() cannot throw for them.
|
|
27
|
+
return String(error);
|
|
28
|
+
}
|
|
29
|
+
export function getErrorResponseCode(error, status) {
|
|
30
|
+
const code = safeRead(error, 'code');
|
|
31
|
+
if (typeof code === 'string')
|
|
32
|
+
return code;
|
|
33
|
+
return status >= 500 ? 'INTERNAL_ERROR' : undefined;
|
|
34
|
+
}
|
|
35
|
+
export function getErrorResponseStack(error) {
|
|
36
|
+
const stack = safeRead(error, 'stack');
|
|
37
|
+
return typeof stack === 'string' ? stack : undefined;
|
|
38
|
+
}
|
|
39
|
+
export function getStatusMessage(status) {
|
|
40
|
+
return STATUS_CODES[status] ?? 'Internal Server Error';
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Builds the house error envelope. With `exposeDetails: false`, 5xx errors collapse to the HTTP
|
|
44
|
+
* status text with code `INTERNAL_ERROR` and never leak messages or stacks; 4xx messages and
|
|
45
|
+
* codes are still returned. Callers own serialization, logging, and environment policy.
|
|
46
|
+
*/
|
|
47
|
+
export function buildApiErrorEnvelope(error, options) {
|
|
48
|
+
const status = getErrorStatus(error);
|
|
49
|
+
const requestId = options.requestId ? { request_id: options.requestId } : {};
|
|
50
|
+
if (!options.exposeDetails && status >= 500) {
|
|
51
|
+
return {
|
|
52
|
+
status,
|
|
53
|
+
body: { message: getStatusMessage(status), code: 'INTERNAL_ERROR', ...requestId },
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
const code = getErrorResponseCode(error, status);
|
|
57
|
+
const stack = options.exposeDetails ? getErrorResponseStack(error) : undefined;
|
|
58
|
+
return {
|
|
59
|
+
status,
|
|
60
|
+
body: {
|
|
61
|
+
message: getErrorResponseMessage(error, status),
|
|
62
|
+
...(code ? { code } : {}),
|
|
63
|
+
...requestId,
|
|
64
|
+
...(stack ? { stack } : {}),
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function getValidHttpStatus(status) {
|
|
69
|
+
if (typeof status === 'number' && Number.isInteger(status) && status >= 400 && status <= 599) {
|
|
70
|
+
return status;
|
|
71
|
+
}
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
function isObjectLike(value) {
|
|
75
|
+
return typeof value === 'object' && value !== null;
|
|
76
|
+
}
|
|
77
|
+
function safeString(value) {
|
|
78
|
+
try {
|
|
79
|
+
return String(value);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** Reads a property of a thrown value; hostile getters and Proxy traps yield undefined. */
|
|
86
|
+
function safeRead(value, key) {
|
|
87
|
+
if (!isObjectLike(value))
|
|
88
|
+
return undefined;
|
|
89
|
+
try {
|
|
90
|
+
return value[key];
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export type CommandFailureReason = 'exit' | 'signal' | 'abort' | 'timeout';
|
|
2
|
+
export declare class CommandFailedError extends Error {
|
|
3
|
+
readonly reason: CommandFailureReason;
|
|
4
|
+
readonly exitCode: number | null;
|
|
5
|
+
readonly signal: NodeJS.Signals | null;
|
|
6
|
+
readonly stderr: Buffer;
|
|
7
|
+
constructor(command: string, details: {
|
|
8
|
+
reason: CommandFailureReason;
|
|
9
|
+
exitCode: number | null;
|
|
10
|
+
signal: NodeJS.Signals | null;
|
|
11
|
+
stderr: Buffer;
|
|
12
|
+
});
|
|
13
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export class CommandFailedError extends Error {
|
|
2
|
+
reason;
|
|
3
|
+
exitCode;
|
|
4
|
+
signal;
|
|
5
|
+
stderr;
|
|
6
|
+
constructor(command, details) {
|
|
7
|
+
super(formatCommandFailure(command, details));
|
|
8
|
+
this.name = 'CommandFailedError';
|
|
9
|
+
this.reason = details.reason;
|
|
10
|
+
this.exitCode = details.exitCode;
|
|
11
|
+
this.signal = details.signal;
|
|
12
|
+
this.stderr = details.stderr;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function formatCommandFailure(command, details) {
|
|
16
|
+
const stderrText = details.stderr.toString('utf8').trim();
|
|
17
|
+
const suffix = stderrText.length > 0 ? `: ${stderrText}` : '';
|
|
18
|
+
return `command ${details.reason} (${command}) exit=${details.exitCode ?? 'null'} signal=${details.signal ?? 'null'}${suffix}`;
|
|
19
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { ChildProcess } from 'node:child_process';
|
|
2
|
+
import type { Readable, Writable } from 'node:stream';
|
|
3
|
+
import { CommandFailedError } from './child-process-error.mts';
|
|
4
|
+
export declare function destroyChildPipes(child: ChildProcess): void;
|
|
5
|
+
export declare function killChild(child: ChildProcess): void;
|
|
6
|
+
export declare function isSharedOutput(stdout: Writable): boolean;
|
|
7
|
+
export declare function pipeStdin(child: ChildProcess, stdin: Readable | Uint8Array | string | undefined, onError: (err: Error) => void): void;
|
|
8
|
+
export declare function pipeStdout(child: ChildProcess, stdout: Writable | undefined, onError: (err: Error) => void): () => void;
|
|
9
|
+
export declare function collectCappedStderr(child: ChildProcess, cap: number): {
|
|
10
|
+
bytes: () => Buffer;
|
|
11
|
+
};
|
|
12
|
+
export type ChildOutcome = {
|
|
13
|
+
kind: 'close';
|
|
14
|
+
exitCode: number | null;
|
|
15
|
+
signal: NodeJS.Signals | null;
|
|
16
|
+
} | {
|
|
17
|
+
kind: 'error';
|
|
18
|
+
error: Error;
|
|
19
|
+
};
|
|
20
|
+
export declare function waitForChild(child: ChildProcess): Promise<ChildOutcome>;
|
|
21
|
+
export declare function classifyFailure(input: {
|
|
22
|
+
command: string;
|
|
23
|
+
aborted: boolean;
|
|
24
|
+
timedOut: boolean;
|
|
25
|
+
stdinError: Error | undefined;
|
|
26
|
+
stdoutError: Error | undefined;
|
|
27
|
+
exitCode: number | null;
|
|
28
|
+
signal: NodeJS.Signals | null;
|
|
29
|
+
stderr: Buffer;
|
|
30
|
+
}): CommandFailedError | Error | undefined;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { CommandFailedError } from './child-process-error.mjs';
|
|
2
|
+
const ignoreLateError = () => { };
|
|
3
|
+
export function destroyChildPipes(child) {
|
|
4
|
+
child.stdin?.destroy();
|
|
5
|
+
child.stdout?.destroy();
|
|
6
|
+
child.stderr?.destroy();
|
|
7
|
+
}
|
|
8
|
+
export function killChild(child) {
|
|
9
|
+
if (child.exitCode !== null || child.signalCode !== null)
|
|
10
|
+
return;
|
|
11
|
+
child.kill('SIGKILL');
|
|
12
|
+
}
|
|
13
|
+
export function isSharedOutput(stdout) {
|
|
14
|
+
return stdout === process.stdout || stdout === process.stderr;
|
|
15
|
+
}
|
|
16
|
+
export function pipeStdin(child, stdin, onError) {
|
|
17
|
+
const input = child.stdin;
|
|
18
|
+
if (!input)
|
|
19
|
+
throw new Error('child stdin is not a pipe');
|
|
20
|
+
input.on('error', (err) => {
|
|
21
|
+
const code = err.code;
|
|
22
|
+
if (code === 'EPIPE' || code === 'ERR_STREAM_PREMATURE_CLOSE')
|
|
23
|
+
return;
|
|
24
|
+
onError(err);
|
|
25
|
+
killChild(child);
|
|
26
|
+
});
|
|
27
|
+
if (stdin === undefined) {
|
|
28
|
+
input.end();
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (typeof stdin === 'string' || stdin instanceof Uint8Array) {
|
|
32
|
+
input.end(stdin);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const onSourceError = (err) => {
|
|
36
|
+
onError(err);
|
|
37
|
+
killChild(child);
|
|
38
|
+
};
|
|
39
|
+
stdin.on('error', onSourceError);
|
|
40
|
+
// A child that exits first leaves a Readable paused with its descriptor open.
|
|
41
|
+
let released = false;
|
|
42
|
+
const releaseStdin = () => {
|
|
43
|
+
if (released)
|
|
44
|
+
return;
|
|
45
|
+
released = true;
|
|
46
|
+
stdin.removeListener('error', onSourceError);
|
|
47
|
+
// Destroying can still fail asynchronously; an unhandled 'error' would crash the process.
|
|
48
|
+
stdin.on('error', ignoreLateError);
|
|
49
|
+
if (!stdin.readableEnded)
|
|
50
|
+
stdin.destroy();
|
|
51
|
+
};
|
|
52
|
+
child.once('close', releaseStdin);
|
|
53
|
+
child.once('error', releaseStdin);
|
|
54
|
+
stdin.pipe(input);
|
|
55
|
+
}
|
|
56
|
+
export function pipeStdout(child, stdout, onError) {
|
|
57
|
+
const output = child.stdout;
|
|
58
|
+
if (!output)
|
|
59
|
+
throw new Error('child stdout is not a pipe');
|
|
60
|
+
if (!stdout) {
|
|
61
|
+
output.resume();
|
|
62
|
+
return () => { };
|
|
63
|
+
}
|
|
64
|
+
output.on('error', (err) => {
|
|
65
|
+
onError(err);
|
|
66
|
+
// pipe() does not end its destination when the source errors.
|
|
67
|
+
if (!isSharedOutput(stdout))
|
|
68
|
+
stdout.destroy(err);
|
|
69
|
+
killChild(child);
|
|
70
|
+
});
|
|
71
|
+
const onDestinationError = (err) => onError(err);
|
|
72
|
+
stdout.on('error', onDestinationError);
|
|
73
|
+
output.pipe(stdout);
|
|
74
|
+
// Shared streams outlive the command; the caller removes this once writes settle.
|
|
75
|
+
return () => {
|
|
76
|
+
if (isSharedOutput(stdout))
|
|
77
|
+
stdout.removeListener('error', onDestinationError);
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
export function collectCappedStderr(child, cap) {
|
|
81
|
+
let chunks = [];
|
|
82
|
+
let length = 0;
|
|
83
|
+
const output = child.stderr;
|
|
84
|
+
if (!output)
|
|
85
|
+
throw new Error('child stderr is not a pipe');
|
|
86
|
+
output.on('data', (chunk) => {
|
|
87
|
+
if (length >= cap)
|
|
88
|
+
return;
|
|
89
|
+
const remaining = cap - length;
|
|
90
|
+
const slice = chunk.byteLength > remaining ? chunk.subarray(0, remaining) : chunk;
|
|
91
|
+
chunks = [...chunks, slice];
|
|
92
|
+
length += slice.byteLength;
|
|
93
|
+
});
|
|
94
|
+
return {
|
|
95
|
+
bytes() {
|
|
96
|
+
return Buffer.concat(chunks);
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
export function waitForChild(child) {
|
|
101
|
+
return new Promise((resolve) => {
|
|
102
|
+
child.once('error', (err) => {
|
|
103
|
+
resolve({
|
|
104
|
+
kind: 'error',
|
|
105
|
+
error: err,
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
child.once('close', (exitCode, signal) => {
|
|
109
|
+
resolve({ kind: 'close', exitCode, signal });
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
export function classifyFailure(input) {
|
|
114
|
+
const details = {
|
|
115
|
+
exitCode: input.exitCode,
|
|
116
|
+
signal: input.signal,
|
|
117
|
+
stderr: input.stderr,
|
|
118
|
+
};
|
|
119
|
+
if (input.aborted)
|
|
120
|
+
return failure(input.command, 'abort', details);
|
|
121
|
+
if (input.timedOut)
|
|
122
|
+
return failure(input.command, 'timeout', details);
|
|
123
|
+
if (input.stdoutError)
|
|
124
|
+
return input.stdoutError;
|
|
125
|
+
if (input.stdinError)
|
|
126
|
+
return input.stdinError;
|
|
127
|
+
if (input.signal)
|
|
128
|
+
return failure(input.command, 'signal', details);
|
|
129
|
+
if (input.exitCode !== 0)
|
|
130
|
+
return failure(input.command, 'exit', details);
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
function failure(command, reason, details) {
|
|
134
|
+
return new CommandFailedError(command, { reason, ...details });
|
|
135
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Writable } from 'node:stream';
|
|
2
|
+
export type { CommandFailureReason } from './child-process-error.mts';
|
|
3
|
+
export { CommandFailedError } from './child-process-error.mts';
|
|
4
|
+
export type RunCommandOptions = {
|
|
5
|
+
command: string;
|
|
6
|
+
args?: readonly string[];
|
|
7
|
+
stdin?: ReadableStreamInput;
|
|
8
|
+
stdout?: Writable;
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
timeoutMs: number;
|
|
11
|
+
stderrCapBytes?: number;
|
|
12
|
+
/** Replaces the default child environment (PATH, TMPDIR, and `LC_ALL=C` only). */
|
|
13
|
+
env?: NodeJS.ProcessEnv;
|
|
14
|
+
};
|
|
15
|
+
type ReadableStreamInput = import('node:stream').Readable | Uint8Array | string;
|
|
16
|
+
export declare function runCommand(options: RunCommandOptions): Promise<{
|
|
17
|
+
stderr: Buffer;
|
|
18
|
+
}>;
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { Writable } from 'node:stream';
|
|
3
|
+
import { finished } from 'node:stream/promises';
|
|
4
|
+
import { CommandFailedError } from './child-process-error.mjs';
|
|
5
|
+
import { classifyFailure, collectCappedStderr, destroyChildPipes, isSharedOutput, killChild, pipeStdin, pipeStdout, waitForChild, } from './child-process-process.mjs';
|
|
6
|
+
const DEFAULT_STDERR_CAP_BYTES = 65_536;
|
|
7
|
+
export { CommandFailedError } from './child-process-error.mjs';
|
|
8
|
+
// Spawns `command` with an explicit argv and no shell. Stdin and stdout stay
|
|
9
|
+
// streams. Stderr is retained only up to a byte cap. By default the child receives
|
|
10
|
+
// PATH, TMPDIR, and `LC_ALL=C` only. Abort and the timeout both SIGKILL the child;
|
|
11
|
+
// a non-zero exit or a signal rejects.
|
|
12
|
+
export async function runCommand(options) {
|
|
13
|
+
if (options.command.length === 0)
|
|
14
|
+
throw new Error('command must not be empty');
|
|
15
|
+
if (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0) {
|
|
16
|
+
throw new Error('timeoutMs must be a positive finite number');
|
|
17
|
+
}
|
|
18
|
+
if (options.signal?.aborted) {
|
|
19
|
+
throw new CommandFailedError(options.command, {
|
|
20
|
+
reason: 'abort',
|
|
21
|
+
exitCode: null,
|
|
22
|
+
signal: null,
|
|
23
|
+
stderr: Buffer.alloc(0),
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
const child = spawn(options.command, [...(options.args ?? [])], {
|
|
27
|
+
shell: false,
|
|
28
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
29
|
+
env: options.env ?? childEnvironment(),
|
|
30
|
+
});
|
|
31
|
+
let aborted = false;
|
|
32
|
+
let timedOut = false;
|
|
33
|
+
let stdinError;
|
|
34
|
+
let stdoutError;
|
|
35
|
+
const outputCancellation = new AbortController();
|
|
36
|
+
const stderr = collectCappedStderr(child, options.stderrCapBytes ?? DEFAULT_STDERR_CAP_BYTES);
|
|
37
|
+
pipeStdin(child, options.stdin, (err) => {
|
|
38
|
+
stdinError = err;
|
|
39
|
+
});
|
|
40
|
+
const releaseStdout = pipeStdout(child, options.stdout, (err) => {
|
|
41
|
+
stdoutError = err;
|
|
42
|
+
killChild(child);
|
|
43
|
+
});
|
|
44
|
+
const destroyStdout = () => {
|
|
45
|
+
if (options.stdout && !isSharedOutput(options.stdout) && !options.stdout.writableFinished)
|
|
46
|
+
options.stdout.destroy();
|
|
47
|
+
};
|
|
48
|
+
// Destroying the child's pipes lets `close` fire even when a grandchild holds them open.
|
|
49
|
+
const cancel = () => {
|
|
50
|
+
killChild(child);
|
|
51
|
+
destroyChildPipes(child);
|
|
52
|
+
outputCancellation.abort();
|
|
53
|
+
destroyStdout();
|
|
54
|
+
};
|
|
55
|
+
const onAbort = () => {
|
|
56
|
+
aborted = true;
|
|
57
|
+
cancel();
|
|
58
|
+
};
|
|
59
|
+
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
60
|
+
// Stream setup hooks may have aborted before the listener existed; abort events are not replayed.
|
|
61
|
+
if (options.signal?.aborted)
|
|
62
|
+
onAbort();
|
|
63
|
+
const timer = setTimeout(() => {
|
|
64
|
+
timedOut = true;
|
|
65
|
+
cancel();
|
|
66
|
+
}, options.timeoutMs);
|
|
67
|
+
timer.unref();
|
|
68
|
+
try {
|
|
69
|
+
const outcome = await waitForChild(child);
|
|
70
|
+
if (outcome.kind === 'error') {
|
|
71
|
+
destroyStdout();
|
|
72
|
+
throw outcome.error;
|
|
73
|
+
}
|
|
74
|
+
// The child can close before an async stdout destination finishes its writes.
|
|
75
|
+
await settleStdout(options.stdout, outputCancellation.signal, (err) => {
|
|
76
|
+
if (!stdoutError)
|
|
77
|
+
stdoutError = err;
|
|
78
|
+
});
|
|
79
|
+
const failure = classifyFailure({
|
|
80
|
+
command: options.command,
|
|
81
|
+
aborted,
|
|
82
|
+
timedOut,
|
|
83
|
+
stdinError,
|
|
84
|
+
stdoutError,
|
|
85
|
+
exitCode: outcome.exitCode,
|
|
86
|
+
signal: outcome.signal,
|
|
87
|
+
stderr: stderr.bytes(),
|
|
88
|
+
});
|
|
89
|
+
if (failure)
|
|
90
|
+
throw failure;
|
|
91
|
+
return { stderr: stderr.bytes() };
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
clearTimeout(timer);
|
|
95
|
+
releaseStdout();
|
|
96
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function childEnvironment() {
|
|
100
|
+
const env = { LC_ALL: 'C' };
|
|
101
|
+
const path = process.env.PATH;
|
|
102
|
+
const tempDir = process.env.TMPDIR;
|
|
103
|
+
if (path !== undefined)
|
|
104
|
+
env.PATH = path;
|
|
105
|
+
if (tempDir !== undefined)
|
|
106
|
+
env.TMPDIR = tempDir;
|
|
107
|
+
return env;
|
|
108
|
+
}
|
|
109
|
+
async function settleStdout(stdout, cancellation, onError) {
|
|
110
|
+
if (!stdout || cancellation.aborted)
|
|
111
|
+
return;
|
|
112
|
+
const settled = isSharedOutput(stdout)
|
|
113
|
+
? new Promise((resolve, reject) => {
|
|
114
|
+
stdout.write('', (err) => (err ? reject(err) : resolve()));
|
|
115
|
+
})
|
|
116
|
+
: finished(stdout, { readable: false });
|
|
117
|
+
let onCancel;
|
|
118
|
+
const cancelled = new Promise((resolve) => {
|
|
119
|
+
onCancel = resolve;
|
|
120
|
+
cancellation.addEventListener('abort', onCancel, { once: true });
|
|
121
|
+
});
|
|
122
|
+
try {
|
|
123
|
+
// Cancellation wins so a destination with slow cleanup cannot outlive the timeout.
|
|
124
|
+
await Promise.race([settled, cancelled]);
|
|
125
|
+
}
|
|
126
|
+
catch (err) {
|
|
127
|
+
onError(err);
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
cancellation.removeEventListener('abort', onCancel);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { CommandFailedError, runCommand } from './child-process-run.mjs';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export interface FormatErrorTreeOptions {
|
|
2
|
+
/** Deepest nesting level rendered; deeper errors are counted as omitted. Default 5. */
|
|
3
|
+
maxDepth?: number;
|
|
4
|
+
/** Total nested errors rendered across the tree. Default 20. */
|
|
5
|
+
maxNested?: number;
|
|
6
|
+
}
|
|
7
|
+
/** Formats an error and its nested `errors[]` and `cause` chain without util.format's shallow output. */
|
|
8
|
+
export declare function formatErrorTree(error: unknown, options?: FormatErrorTreeOptions): string;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { inspect } from 'node:util';
|
|
2
|
+
/** Formats an error and its nested `errors[]` and `cause` chain without util.format's shallow output. */
|
|
3
|
+
export function formatErrorTree(error, options = {}) {
|
|
4
|
+
const maxDepth = options.maxDepth ?? 5;
|
|
5
|
+
const maxNested = options.maxNested ?? 20;
|
|
6
|
+
const seen = new Set();
|
|
7
|
+
// Nodes visited only while counting omitted subtrees; kept apart from `seen` so a hidden
|
|
8
|
+
// occurrence never turns a later visible occurrence into `[circular]`.
|
|
9
|
+
const omittedSeen = new Set();
|
|
10
|
+
let nestedCount = 0;
|
|
11
|
+
let omittedCount = 0;
|
|
12
|
+
const render = (value, depth, label) => {
|
|
13
|
+
if (isObject(value)) {
|
|
14
|
+
if (seen.has(value))
|
|
15
|
+
return indentLines('[circular]', depth, label);
|
|
16
|
+
seen.add(value);
|
|
17
|
+
}
|
|
18
|
+
const lines = indentLines(formatValue(value), depth, label);
|
|
19
|
+
for (const child of getChildren(value)) {
|
|
20
|
+
if (depth >= maxDepth || nestedCount >= maxNested) {
|
|
21
|
+
omittedCount += countOmitted(child.value, seen, omittedSeen);
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
nestedCount += 1;
|
|
25
|
+
lines.push(...render(child.value, depth + 1, child.label));
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return lines;
|
|
29
|
+
};
|
|
30
|
+
const lines = render(error, 0);
|
|
31
|
+
if (omittedCount > 0)
|
|
32
|
+
lines.push(`… ${omittedCount} more nested errors omitted`);
|
|
33
|
+
return lines.join('\n');
|
|
34
|
+
}
|
|
35
|
+
function formatValue(value) {
|
|
36
|
+
if (!(value instanceof Error))
|
|
37
|
+
return inspect(withoutChildren(value), { depth: 2 });
|
|
38
|
+
if (typeof value.stack === 'string' && value.stack.length > 0)
|
|
39
|
+
return value.stack;
|
|
40
|
+
return `${value.name || 'Error'}: ${value.message}`;
|
|
41
|
+
}
|
|
42
|
+
// Child errors are traversed separately under the limits, so inspect must not print them too.
|
|
43
|
+
function withoutChildren(value) {
|
|
44
|
+
if (!isObject(value) || Array.isArray(value) || getChildren(value).length === 0)
|
|
45
|
+
return value;
|
|
46
|
+
const copy = { ...value };
|
|
47
|
+
if (Array.isArray(copy.errors))
|
|
48
|
+
delete copy.errors;
|
|
49
|
+
if (copy.cause !== undefined)
|
|
50
|
+
delete copy.cause;
|
|
51
|
+
return copy;
|
|
52
|
+
}
|
|
53
|
+
function getChildren(value) {
|
|
54
|
+
if (!isObject(value))
|
|
55
|
+
return [];
|
|
56
|
+
const children = [];
|
|
57
|
+
const properties = value;
|
|
58
|
+
const errors = properties.errors;
|
|
59
|
+
if (Array.isArray(errors)) {
|
|
60
|
+
errors.forEach((nested, index) => children.push({ label: `errors[${index}]:`, value: nested }));
|
|
61
|
+
}
|
|
62
|
+
if (properties.cause !== undefined)
|
|
63
|
+
children.push({ label: 'cause:', value: properties.cause });
|
|
64
|
+
return children;
|
|
65
|
+
}
|
|
66
|
+
function countOmitted(value, seen, omittedSeen) {
|
|
67
|
+
const pending = [value];
|
|
68
|
+
let count = 0;
|
|
69
|
+
while (pending.length > 0) {
|
|
70
|
+
const current = pending.pop();
|
|
71
|
+
if (isObject(current)) {
|
|
72
|
+
if (seen.has(current) || omittedSeen.has(current)) {
|
|
73
|
+
count += 1;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
omittedSeen.add(current);
|
|
77
|
+
}
|
|
78
|
+
count += 1;
|
|
79
|
+
const children = getChildren(current);
|
|
80
|
+
for (let index = children.length - 1; index >= 0; index -= 1) {
|
|
81
|
+
pending.push(children[index].value);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return count;
|
|
85
|
+
}
|
|
86
|
+
function indentLines(value, depth, label) {
|
|
87
|
+
const indentation = ' '.repeat(depth);
|
|
88
|
+
return value
|
|
89
|
+
.split(/\r?\n/)
|
|
90
|
+
.map((line, index) => `${indentation}${index === 0 && label ? `${label} ` : ''}${line}`);
|
|
91
|
+
}
|
|
92
|
+
function isObject(value) {
|
|
93
|
+
return (typeof value === 'object' && value !== null) || typeof value === 'function';
|
|
94
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { GracefulShutdownProcess } from './graceful-shutdown-run.mts';
|
|
2
|
+
export interface OneOffShutdownOptions {
|
|
3
|
+
gracePeriodMs: number;
|
|
4
|
+
/** Closes resources and returns the failures, as `ShutdownRegistry.close` does. */
|
|
5
|
+
close: () => Promise<Error[]>;
|
|
6
|
+
logError?: (...args: unknown[]) => void;
|
|
7
|
+
/** Defaults to the global `process`. */
|
|
8
|
+
process?: Pick<GracefulShutdownProcess, 'exit'>;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Closes resources for a short-lived command. A timer force-exits with code 1 if the close never
|
|
12
|
+
* settles; once it settles the timer is unref'd, so only a leaked handle can still trigger it.
|
|
13
|
+
* Throws an `AggregateError` when any close failed.
|
|
14
|
+
*/
|
|
15
|
+
export declare function shutdownForOneOffCommand(options: OneOffShutdownOptions): Promise<void>;
|