@radheim/util 0.0.0-stage → 2.4.3
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/dist/abort.d.ts +1 -0
- package/dist/abort.js +8 -0
- package/dist/activity-calendar.d.ts +21 -0
- package/dist/activity-calendar.js +42 -0
- package/dist/artifact.d.ts +4 -0
- package/dist/artifact.js +85 -0
- package/dist/base64.d.ts +4 -0
- package/dist/base64.js +24 -0
- package/dist/binary.d.ts +7 -0
- package/dist/binary.js +34 -0
- package/dist/bom.d.ts +22 -0
- package/dist/bom.js +36 -0
- package/dist/cross-spawn-spawner.d.ts +9 -0
- package/dist/cross-spawn-spawner.js +548 -0
- package/dist/duration.d.ts +2 -0
- package/dist/duration.js +22 -0
- package/dist/effect/app-node-platform.d.ts +13 -0
- package/dist/effect/app-node-platform.js +29 -0
- package/dist/effect/app-node.d.ts +16 -0
- package/dist/effect/app-node.js +8 -0
- package/dist/effect/layer-node.d.ts +178 -0
- package/dist/effect/layer-node.js +248 -0
- package/dist/effect-flock.d.ts +31 -0
- package/dist/effect-flock.js +186 -0
- package/dist/encode.d.ts +4 -0
- package/dist/encode.js +38 -0
- package/dist/execute-output.d.ts +10 -0
- package/dist/execute-output.js +22 -0
- package/dist/flock.d.ts +28 -0
- package/dist/flock.js +267 -0
- package/dist/fs-util.d.ts +54 -0
- package/dist/fs-util.js +200 -0
- package/dist/glob.d.ts +18 -0
- package/dist/glob.js +29 -0
- package/dist/global-roots.d.ts +8 -0
- package/dist/global-roots.js +17 -0
- package/dist/global-roots.workerd.d.ts +7 -0
- package/dist/global-roots.workerd.js +15 -0
- package/dist/global.d.ts +30 -0
- package/dist/global.js +54 -0
- package/dist/hash.d.ts +4 -0
- package/dist/hash.js +12 -0
- package/dist/heap-snapshot.d.ts +19 -0
- package/dist/heap-snapshot.js +38 -0
- package/dist/no-timeout-fetch.d.ts +1 -0
- package/dist/no-timeout-fetch.js +4 -0
- package/dist/npm-config.d.ts +4 -0
- package/dist/npm-config.js +34 -0
- package/dist/npm.d.ts +45 -0
- package/dist/npm.js +441 -0
- package/dist/observability/logging.d.ts +14 -0
- package/dist/observability/logging.js +151 -0
- package/dist/observability/otlp.d.ts +19 -0
- package/dist/observability/otlp.js +63 -0
- package/dist/observability/shared.d.ts +1 -0
- package/dist/observability/shared.js +7 -0
- package/dist/observability/tracing.d.ts +2 -0
- package/dist/observability/tracing.js +3 -0
- package/dist/observability.d.ts +13 -0
- package/dist/observability.js +37 -0
- package/dist/open.d.ts +2 -0
- package/dist/open.js +10 -0
- package/dist/patch.d.ts +43 -0
- package/dist/patch.js +332 -0
- package/dist/path.d.ts +20 -0
- package/dist/path.js +134 -0
- package/dist/process-signal.d.ts +5 -0
- package/dist/process-signal.js +22 -0
- package/dist/process.d.ts +54 -0
- package/dist/process.js +167 -0
- package/dist/qr.d.ts +15 -0
- package/dist/qr.js +295 -0
- package/dist/record.d.ts +2 -0
- package/dist/record.js +2 -0
- package/dist/retry.d.ts +8 -0
- package/dist/retry.js +45 -0
- package/dist/runtime/import.bun.d.ts +2 -0
- package/dist/runtime/import.bun.js +8 -0
- package/dist/runtime/import.node.d.ts +2 -0
- package/dist/runtime/import.node.js +62 -0
- package/dist/runtime/import.workerd.d.ts +2 -0
- package/dist/runtime/import.workerd.js +7 -0
- package/dist/runtime-import.d.ts +1 -0
- package/dist/runtime-import.js +1 -0
- package/dist/session-mention.d.ts +11 -0
- package/dist/session-mention.js +18 -0
- package/dist/session-title-fallback.d.ts +16 -0
- package/dist/session-title-fallback.js +23 -0
- package/dist/session-turn.d.ts +37 -0
- package/dist/session-turn.js +56 -0
- package/dist/teardown.d.ts +8 -0
- package/dist/teardown.js +16 -0
- package/dist/text-boundary.d.ts +11 -0
- package/dist/text-boundary.js +22 -0
- package/dist/uuid.d.ts +1 -0
- package/dist/uuid.js +14 -0
- package/package.json +71 -4
- package/README.md +0 -3
|
@@ -0,0 +1,548 @@
|
|
|
1
|
+
import { isArrayNonEmpty } from "effect/Array";
|
|
2
|
+
import { fromWritable } from "@effect/platform-node/NodeSink";
|
|
3
|
+
import { fromReadable } from "@effect/platform-node/NodeStream";
|
|
4
|
+
import { Deferred, Effect, Exit, FileSystem, Layer, Path, PlatformError, Predicate, Redacted, Sink, Stream, } from "effect";
|
|
5
|
+
import { ChildProcess } from "effect/process";
|
|
6
|
+
import { ChildProcessSpawner, ExitCode, make, makeHandle, ProcessId, } from "effect/process/ChildProcessSpawner";
|
|
7
|
+
// ast-grep-ignore: no-star-import
|
|
8
|
+
import * as NodeChildProcess from "node:child_process";
|
|
9
|
+
import { PassThrough } from "node:stream";
|
|
10
|
+
import launch from "cross-spawn";
|
|
11
|
+
import { makeGlobalNode } from "./effect/app-node.js";
|
|
12
|
+
import { filesystem, path } from "./effect/app-node-platform.js";
|
|
13
|
+
import { Teardown } from "./teardown.js";
|
|
14
|
+
/** Closing a child's scope escalates to SIGKILL after this, unless the command sets its own `forceKillAfter`. */
|
|
15
|
+
export const RELEASE_FORCE_KILL_AFTER = "3 seconds";
|
|
16
|
+
// Process groups of running children. Exiting without stopping them (a shutdown deadline, a second signal, a
|
|
17
|
+
// crash) would orphan them, so a synchronous exit hook kills whatever is left.
|
|
18
|
+
const groups = new Set();
|
|
19
|
+
let hooked = false;
|
|
20
|
+
const killGroups = () => groups.forEach((pid) => {
|
|
21
|
+
try {
|
|
22
|
+
globalThis.process.kill(-pid, "SIGKILL");
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
// Already gone.
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
const unwrap = (value) => Redacted.isRedacted(value) ? Redacted.value(value) : value;
|
|
29
|
+
// Node's own NUL check throws an error that includes the value, so NUL is rejected here to keep Redacted values
|
|
30
|
+
// out of errors.
|
|
31
|
+
const findNulCharacter = (command) => {
|
|
32
|
+
if (command.command.includes("\0"))
|
|
33
|
+
return "The command contains a NUL character";
|
|
34
|
+
const index = command.args.findIndex((arg) => unwrap(arg).includes("\0"));
|
|
35
|
+
if (index !== -1)
|
|
36
|
+
return `Argument ${index + 1} contains a NUL character`;
|
|
37
|
+
for (const [name, value] of Object.entries(command.options.env ?? {})) {
|
|
38
|
+
if (value !== undefined && unwrap(value).includes("\0")) {
|
|
39
|
+
return `The environment variable ${name} contains a NUL character`;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
};
|
|
44
|
+
// Buffered writes can fail after the sink has been interrupted and removed its error listener. Keep a fallback until
|
|
45
|
+
// close, without replacing the sink listener that propagates errors while it is active.
|
|
46
|
+
const handleInputErrors = (writable) => {
|
|
47
|
+
const onError = () => { };
|
|
48
|
+
writable.on("error", onError);
|
|
49
|
+
writable.once("close", () => writable.off("error", onError));
|
|
50
|
+
};
|
|
51
|
+
const toError = (err) => (err instanceof globalThis.Error ? err : new globalThis.Error(String(err)));
|
|
52
|
+
const toTag = (err) => {
|
|
53
|
+
switch (err.code) {
|
|
54
|
+
case "ENOENT":
|
|
55
|
+
return "NotFound";
|
|
56
|
+
case "EACCES":
|
|
57
|
+
return "PermissionDenied";
|
|
58
|
+
case "EEXIST":
|
|
59
|
+
return "AlreadyExists";
|
|
60
|
+
case "EISDIR":
|
|
61
|
+
return "BadResource";
|
|
62
|
+
case "ENOTDIR":
|
|
63
|
+
return "BadResource";
|
|
64
|
+
case "EBUSY":
|
|
65
|
+
return "Busy";
|
|
66
|
+
case "ELOOP":
|
|
67
|
+
return "BadResource";
|
|
68
|
+
default:
|
|
69
|
+
return "Unknown";
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
const flatten = (command) => {
|
|
73
|
+
const commands = [];
|
|
74
|
+
const opts = [];
|
|
75
|
+
const walk = (cmd) => {
|
|
76
|
+
switch (cmd._tag) {
|
|
77
|
+
case "StandardCommand":
|
|
78
|
+
commands.push(cmd);
|
|
79
|
+
return;
|
|
80
|
+
case "PipedCommand":
|
|
81
|
+
walk(cmd.left);
|
|
82
|
+
opts.push(cmd.options);
|
|
83
|
+
walk(cmd.right);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
walk(command);
|
|
88
|
+
if (!isArrayNonEmpty(commands))
|
|
89
|
+
throw new Error("flatten produced empty commands array");
|
|
90
|
+
return {
|
|
91
|
+
commands,
|
|
92
|
+
opts,
|
|
93
|
+
};
|
|
94
|
+
};
|
|
95
|
+
const toPlatformError = (method, err, command) => {
|
|
96
|
+
const cmd = flatten(command)
|
|
97
|
+
.commands.map((x) => `${x.command} ${x.args.join(" ")}`)
|
|
98
|
+
.join(" | ");
|
|
99
|
+
return PlatformError.systemError({
|
|
100
|
+
_tag: toTag(err),
|
|
101
|
+
module: "ChildProcess",
|
|
102
|
+
method,
|
|
103
|
+
pathOrDescriptor: cmd,
|
|
104
|
+
syscall: err.syscall,
|
|
105
|
+
cause: err,
|
|
106
|
+
});
|
|
107
|
+
};
|
|
108
|
+
export class KilledBySignal extends Error {
|
|
109
|
+
signal;
|
|
110
|
+
constructor(signal) {
|
|
111
|
+
super(`Process interrupted due to receipt of signal: '${signal}'`);
|
|
112
|
+
this.signal = signal;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const makeCrossSpawnSpawner = Effect.gen(function* () {
|
|
116
|
+
const fs = yield* FileSystem.FileSystem;
|
|
117
|
+
const path = yield* Path.Path;
|
|
118
|
+
const cwd = Effect.fnUntraced(function* (opts) {
|
|
119
|
+
if (Predicate.isUndefined(opts.cwd))
|
|
120
|
+
return undefined;
|
|
121
|
+
yield* fs.access(opts.cwd);
|
|
122
|
+
return path.resolve(opts.cwd);
|
|
123
|
+
});
|
|
124
|
+
const env = (opts) => {
|
|
125
|
+
if (opts.env === undefined)
|
|
126
|
+
return opts.extendEnv ? globalThis.process.env : undefined;
|
|
127
|
+
const result = opts.extendEnv ? { ...globalThis.process.env } : {};
|
|
128
|
+
for (const [key, value] of Object.entries(opts.env)) {
|
|
129
|
+
if (value === undefined)
|
|
130
|
+
delete result[key];
|
|
131
|
+
else
|
|
132
|
+
result[key] = unwrap(value);
|
|
133
|
+
}
|
|
134
|
+
return result;
|
|
135
|
+
};
|
|
136
|
+
const input = (x) => Stream.isStream(x) ? "pipe" : x;
|
|
137
|
+
const output = (x) => Sink.isSink(x) ? "pipe" : x;
|
|
138
|
+
const stdin = (opts) => {
|
|
139
|
+
const cfg = { stream: "pipe", encoding: "utf-8", endOnDone: true };
|
|
140
|
+
if (Predicate.isUndefined(opts.stdin))
|
|
141
|
+
return cfg;
|
|
142
|
+
if (typeof opts.stdin === "string")
|
|
143
|
+
return { ...cfg, stream: opts.stdin };
|
|
144
|
+
if (Stream.isStream(opts.stdin))
|
|
145
|
+
return { ...cfg, stream: opts.stdin };
|
|
146
|
+
return {
|
|
147
|
+
stream: opts.stdin.stream,
|
|
148
|
+
encoding: opts.stdin.encoding ?? cfg.encoding,
|
|
149
|
+
endOnDone: opts.stdin.endOnDone ?? cfg.endOnDone,
|
|
150
|
+
};
|
|
151
|
+
};
|
|
152
|
+
const stdio = (opts, key) => {
|
|
153
|
+
const cfg = opts[key];
|
|
154
|
+
if (Predicate.isUndefined(cfg))
|
|
155
|
+
return { stream: "pipe" };
|
|
156
|
+
if (typeof cfg === "string")
|
|
157
|
+
return { stream: cfg };
|
|
158
|
+
if (Sink.isSink(cfg))
|
|
159
|
+
return { stream: cfg };
|
|
160
|
+
return { stream: cfg.stream };
|
|
161
|
+
};
|
|
162
|
+
const fds = (opts) => {
|
|
163
|
+
if (Predicate.isUndefined(opts.additionalFds))
|
|
164
|
+
return [];
|
|
165
|
+
return Object.entries(opts.additionalFds)
|
|
166
|
+
.flatMap(([name, config]) => {
|
|
167
|
+
const fd = ChildProcess.parseFdName(name);
|
|
168
|
+
return Predicate.isUndefined(fd) ? [] : [{ fd, config }];
|
|
169
|
+
})
|
|
170
|
+
.toSorted((a, b) => a.fd - b.fd);
|
|
171
|
+
};
|
|
172
|
+
const stdios = (sin, sout, serr, extra) => {
|
|
173
|
+
const pipe = (x) => process.platform === "win32" && x === "pipe" ? "overlapped" : x;
|
|
174
|
+
const arr = [
|
|
175
|
+
pipe(input(sin.stream)),
|
|
176
|
+
pipe(output(sout.stream)),
|
|
177
|
+
pipe(output(serr.stream)),
|
|
178
|
+
];
|
|
179
|
+
if (extra.length === 0)
|
|
180
|
+
return arr;
|
|
181
|
+
const max = extra.reduce((acc, x) => Math.max(acc, x.fd), 2);
|
|
182
|
+
for (let i = 3; i <= max; i++)
|
|
183
|
+
arr[i] = "ignore";
|
|
184
|
+
for (const x of extra)
|
|
185
|
+
arr[x.fd] = pipe("pipe");
|
|
186
|
+
return arr;
|
|
187
|
+
};
|
|
188
|
+
const setupFds = Effect.fnUntraced(function* (command, proc, extra) {
|
|
189
|
+
if (extra.length === 0) {
|
|
190
|
+
return {
|
|
191
|
+
getInputFd: () => Sink.drain,
|
|
192
|
+
getOutputFd: () => Stream.empty,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
const ins = new Map();
|
|
196
|
+
const outs = new Map();
|
|
197
|
+
const setupInput = Effect.fnUntraced(function* (fd, node, source) {
|
|
198
|
+
let sink = Sink.drain;
|
|
199
|
+
if (node && "write" in node) {
|
|
200
|
+
handleInputErrors(node);
|
|
201
|
+
sink = fromWritable({
|
|
202
|
+
evaluate: () => node,
|
|
203
|
+
onError: (err) => toPlatformError(`fromWritable(fd${fd})`, toError(err), command),
|
|
204
|
+
endOnDone: true,
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
if (source)
|
|
208
|
+
yield* Effect.forkScoped(Stream.run(source, sink));
|
|
209
|
+
ins.set(fd, sink);
|
|
210
|
+
});
|
|
211
|
+
const setupOutput = (fd, node, sink) => {
|
|
212
|
+
let stream = Stream.empty;
|
|
213
|
+
if (node && "read" in node) {
|
|
214
|
+
const tap = new PassThrough();
|
|
215
|
+
// Retain errors raised before anyone reads, e.g. a failed write on a duplex fd, so they neither go uncaught
|
|
216
|
+
// nor leave later readers hanging.
|
|
217
|
+
let error = undefined;
|
|
218
|
+
tap.on("error", (cause) => {
|
|
219
|
+
error ??= cause;
|
|
220
|
+
});
|
|
221
|
+
node.on("error", (err) => tap.destroy(toError(err)));
|
|
222
|
+
node.pipe(tap);
|
|
223
|
+
const onError = (err) => toPlatformError(`fromReadable(fd${fd})`, toError(err), command);
|
|
224
|
+
stream = Stream.suspend(() => error === undefined ? fromReadable({ evaluate: () => tap, onError }) : Stream.fail(onError(error)));
|
|
225
|
+
}
|
|
226
|
+
if (sink)
|
|
227
|
+
stream = Stream.transduce(stream, sink);
|
|
228
|
+
outs.set(fd, stream);
|
|
229
|
+
};
|
|
230
|
+
for (const x of extra) {
|
|
231
|
+
const node = proc.stdio[x.fd];
|
|
232
|
+
switch (x.config.type) {
|
|
233
|
+
case "input":
|
|
234
|
+
yield* setupInput(x.fd, node, x.config.stream);
|
|
235
|
+
break;
|
|
236
|
+
case "output":
|
|
237
|
+
setupOutput(x.fd, node, x.config.sink);
|
|
238
|
+
break;
|
|
239
|
+
case "duplex":
|
|
240
|
+
// Keep writing possible after the child closes its write side.
|
|
241
|
+
if (node && "allowHalfOpen" in node)
|
|
242
|
+
node.allowHalfOpen = true;
|
|
243
|
+
setupOutput(x.fd, node, x.config.sink);
|
|
244
|
+
yield* setupInput(x.fd, node, x.config.stream);
|
|
245
|
+
break;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return {
|
|
249
|
+
getInputFd: (fd) => ins.get(fd) ?? Sink.drain,
|
|
250
|
+
getOutputFd: (fd) => outs.get(fd) ?? Stream.empty,
|
|
251
|
+
};
|
|
252
|
+
});
|
|
253
|
+
const setupStdin = (command, proc, cfg) => Effect.suspend(() => {
|
|
254
|
+
let sink = Sink.drain;
|
|
255
|
+
if (Predicate.isNotNull(proc.stdin)) {
|
|
256
|
+
handleInputErrors(proc.stdin);
|
|
257
|
+
sink = fromWritable({
|
|
258
|
+
evaluate: () => proc.stdin,
|
|
259
|
+
onError: (err) => toPlatformError("fromWritable(stdin)", toError(err), command),
|
|
260
|
+
endOnDone: cfg.endOnDone,
|
|
261
|
+
encoding: cfg.encoding,
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
if (Stream.isStream(cfg.stream))
|
|
265
|
+
return Effect.as(Effect.forkScoped(Stream.run(cfg.stream, sink)), sink);
|
|
266
|
+
return Effect.succeed(sink);
|
|
267
|
+
});
|
|
268
|
+
const setupOutput = (command, proc, out, err, stopOutput) => {
|
|
269
|
+
const capture = (readable, name) => {
|
|
270
|
+
if (!readable)
|
|
271
|
+
return Stream.empty;
|
|
272
|
+
// Bun resumes stdio on exit; retain bytes before the lazy Effect reader attaches.
|
|
273
|
+
const buffer = new PassThrough();
|
|
274
|
+
readable.on("error", (cause) => buffer.destroy(toError(cause)));
|
|
275
|
+
readable.pipe(buffer);
|
|
276
|
+
return fromReadable({
|
|
277
|
+
evaluate: () => buffer,
|
|
278
|
+
onError: (cause) => toPlatformError(`fromReadable(${name})`, toError(cause), command),
|
|
279
|
+
}).pipe(Stream.interruptWhen(Deferred.await(stopOutput)), Stream.ensuring(Effect.gen(function* () {
|
|
280
|
+
// Only the capture deadline transfers the reader back to the process scope.
|
|
281
|
+
if (yield* Deferred.isDone(stopOutput))
|
|
282
|
+
return;
|
|
283
|
+
readable.destroy();
|
|
284
|
+
})));
|
|
285
|
+
};
|
|
286
|
+
let stdout = capture(proc.stdout, "stdout");
|
|
287
|
+
let stderr = capture(proc.stderr, "stderr");
|
|
288
|
+
if (Sink.isSink(out.stream))
|
|
289
|
+
stdout = Stream.transduce(stdout, out.stream);
|
|
290
|
+
if (Sink.isSink(err.stream))
|
|
291
|
+
stderr = Stream.transduce(stderr, err.stream);
|
|
292
|
+
return { stdout, stderr, all: Stream.merge(stdout, stderr) };
|
|
293
|
+
};
|
|
294
|
+
// A Microsoft Store app execution alias, such as Store PowerShell 7 in %LOCALAPPDATA%\Microsoft\WindowsApps, is a
|
|
295
|
+
// reparse point that stat rejects with EACCES. cross-spawn then cannot find it and runs it through
|
|
296
|
+
// `cmd.exe /d /s /c`, which drops everything after the first newline of the command line. Launch the target of
|
|
297
|
+
// the link instead, read on every spawn because a Store update moves it.
|
|
298
|
+
const executable = (file) => {
|
|
299
|
+
if (globalThis.process.platform !== "win32" || !path.isAbsolute(file))
|
|
300
|
+
return Effect.succeed(file);
|
|
301
|
+
return fs.readLink(file).pipe(Effect.map((target) => path.resolve(path.dirname(file), target)), Effect.orElseSucceed(() => file));
|
|
302
|
+
};
|
|
303
|
+
const launchProcess = (command, file, opts) => Effect.callback((resume) => {
|
|
304
|
+
const closed = Deferred.makeUnsafe();
|
|
305
|
+
const exited = Deferred.makeUnsafe();
|
|
306
|
+
const proc = launch(file, command.args.map(unwrap), opts);
|
|
307
|
+
let settle = () => { };
|
|
308
|
+
let end = false;
|
|
309
|
+
let exit;
|
|
310
|
+
proc.on("error", (err) => {
|
|
311
|
+
// Node copies the arguments into `spawnargs`.
|
|
312
|
+
if (command.args.some(Redacted.isRedacted)) {
|
|
313
|
+
Object.assign(err, {
|
|
314
|
+
spawnargs: [command.command, ...command.args.map((arg) => (Redacted.isRedacted(arg) ? "<redacted>" : arg))],
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
resume(Effect.fail(toPlatformError("spawn", err, command)));
|
|
318
|
+
});
|
|
319
|
+
proc.on("exit", (...args) => {
|
|
320
|
+
groups.delete(proc.pid);
|
|
321
|
+
exit = args;
|
|
322
|
+
Deferred.doneUnsafe(exited, Exit.succeed(args));
|
|
323
|
+
});
|
|
324
|
+
proc.on("close", (...args) => {
|
|
325
|
+
if (end)
|
|
326
|
+
return;
|
|
327
|
+
end = true;
|
|
328
|
+
settle();
|
|
329
|
+
Deferred.doneUnsafe(exited, Exit.succeed(exit ?? args));
|
|
330
|
+
Deferred.doneUnsafe(closed, Exit.succeed(exit ?? args));
|
|
331
|
+
});
|
|
332
|
+
proc.on("spawn", () => {
|
|
333
|
+
if (opts.detached && globalThis.process.platform !== "win32") {
|
|
334
|
+
if (!hooked)
|
|
335
|
+
globalThis.process.once("exit", killGroups);
|
|
336
|
+
hooked = true;
|
|
337
|
+
groups.add(proc.pid);
|
|
338
|
+
}
|
|
339
|
+
settle = Teardown.track(`child ${proc.pid} running: ${[command.command, ...command.args].join(" ").slice(0, 200)}`);
|
|
340
|
+
resume(Effect.succeed([proc, closed, exited, () => settle()]));
|
|
341
|
+
});
|
|
342
|
+
return Effect.sync(() => {
|
|
343
|
+
proc.kill("SIGTERM");
|
|
344
|
+
});
|
|
345
|
+
});
|
|
346
|
+
const spawn = Effect.fnUntraced(function* (command, opts) {
|
|
347
|
+
yield* Effect.logDebug("spawning process", { command: command.command, args: command.args, cwd: opts.cwd });
|
|
348
|
+
const [proc, closed, exited, settle] = yield* launchProcess(command, yield* executable(command.command), opts);
|
|
349
|
+
const stopOutput = yield* Deferred.make();
|
|
350
|
+
// Register before process release so the deadline remains active during termination.
|
|
351
|
+
yield* Effect.forkScoped(Effect.gen(function* () {
|
|
352
|
+
yield* Deferred.await(exited);
|
|
353
|
+
// Particularly on Windows, some shell calls will cause detached descendants. Inherited stdio can hang the call.
|
|
354
|
+
// Almost every ecosystem has tried to fix this; there's no single "good" answer here.
|
|
355
|
+
// Calls that trigger this are e.g. dotnet build with warmed MSBuild processes, agent-browser, etc.
|
|
356
|
+
// One shared deadline covers stdout and stderr, then the output pump finishes its file.
|
|
357
|
+
if ((yield* Effect.timeoutOption(Deferred.await(closed), "1 second"))._tag === "Some")
|
|
358
|
+
return;
|
|
359
|
+
yield* Deferred.succeed(stopOutput, undefined);
|
|
360
|
+
discard(proc.stdout);
|
|
361
|
+
discard(proc.stderr);
|
|
362
|
+
}));
|
|
363
|
+
return [proc, closed, exited, stopOutput, settle];
|
|
364
|
+
});
|
|
365
|
+
const discard = (readable) => {
|
|
366
|
+
if (!readable || readable.destroyed)
|
|
367
|
+
return;
|
|
368
|
+
readable.unpipe();
|
|
369
|
+
// Discard descendant output without refilling a capture buffer that is no longer consumed.
|
|
370
|
+
const drain = () => {
|
|
371
|
+
while (readable.read() !== null) { }
|
|
372
|
+
};
|
|
373
|
+
readable.on("readable", drain);
|
|
374
|
+
readable.once("error", () => { });
|
|
375
|
+
readable.once("close", () => readable.off("readable", drain));
|
|
376
|
+
drain();
|
|
377
|
+
};
|
|
378
|
+
const killGroup = (command, proc, signal) => {
|
|
379
|
+
if (globalThis.process.platform === "win32") {
|
|
380
|
+
return Effect.callback((resume) => {
|
|
381
|
+
NodeChildProcess.exec(`taskkill /pid ${proc.pid} /T /F`, { windowsHide: true }, (err) => {
|
|
382
|
+
if (err)
|
|
383
|
+
return resume(Effect.fail(toPlatformError("kill", toError(err), command)));
|
|
384
|
+
resume(Effect.void);
|
|
385
|
+
});
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
return Effect.try({
|
|
389
|
+
try: () => {
|
|
390
|
+
globalThis.process.kill(-proc.pid, signal);
|
|
391
|
+
},
|
|
392
|
+
catch: (err) => toPlatformError("kill", toError(err), command),
|
|
393
|
+
});
|
|
394
|
+
};
|
|
395
|
+
const killOne = (command, proc, signal) => Effect.suspend(() => {
|
|
396
|
+
if (proc.kill(signal))
|
|
397
|
+
return Effect.void;
|
|
398
|
+
return Effect.fail(toPlatformError("kill", new Error("Failed to kill child process"), command));
|
|
399
|
+
});
|
|
400
|
+
const stop = (command, proc, closed, stopOutput, opts) => {
|
|
401
|
+
const terminate = (signal) => Effect.catch(killGroup(command, proc, signal), () => killOne(command, proc, signal)).pipe(Effect.andThen(signal === "SIGKILL"
|
|
402
|
+
? Effect.raceFirst(Deferred.await(closed), Deferred.await(stopOutput))
|
|
403
|
+
: Deferred.await(closed)), Effect.asVoid);
|
|
404
|
+
const attempt = terminate(opts?.killSignal ?? "SIGTERM");
|
|
405
|
+
if (opts?.forceKillAfter === undefined)
|
|
406
|
+
return attempt;
|
|
407
|
+
return Effect.timeoutOrElse(attempt, {
|
|
408
|
+
duration: opts.forceKillAfter,
|
|
409
|
+
orElse: () => terminate("SIGKILL"),
|
|
410
|
+
});
|
|
411
|
+
};
|
|
412
|
+
const source = (handle, from) => {
|
|
413
|
+
const opt = from ?? "stdout";
|
|
414
|
+
switch (opt) {
|
|
415
|
+
case "stdout":
|
|
416
|
+
return handle.stdout;
|
|
417
|
+
case "stderr":
|
|
418
|
+
return handle.stderr;
|
|
419
|
+
case "all":
|
|
420
|
+
return handle.all;
|
|
421
|
+
default: {
|
|
422
|
+
const fd = ChildProcess.parseFdName(opt);
|
|
423
|
+
return Predicate.isNotUndefined(fd) ? handle.getOutputFd(fd) : handle.stdout;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
const spawnCommand = Effect.fnUntraced(function* (command) {
|
|
428
|
+
switch (command._tag) {
|
|
429
|
+
case "StandardCommand": {
|
|
430
|
+
const nul = findNulCharacter(command);
|
|
431
|
+
if (nul !== undefined) {
|
|
432
|
+
return yield* Effect.fail(PlatformError.badArgument({ module: "ChildProcess", method: "spawn", description: nul }));
|
|
433
|
+
}
|
|
434
|
+
const sin = stdin(command.options);
|
|
435
|
+
const sout = stdio(command.options, "stdout");
|
|
436
|
+
const serr = stdio(command.options, "stderr");
|
|
437
|
+
const extra = fds(command.options);
|
|
438
|
+
const dir = yield* cwd(command.options);
|
|
439
|
+
const [proc, closed, exited, stopOutput] = yield* Effect.acquireRelease(spawn(command, {
|
|
440
|
+
cwd: dir,
|
|
441
|
+
env: env(command.options),
|
|
442
|
+
stdio: stdios(sin, sout, serr, extra),
|
|
443
|
+
detached: command.options.detached ?? process.platform !== "win32",
|
|
444
|
+
shell: command.options.shell,
|
|
445
|
+
windowsHide: process.platform === "win32",
|
|
446
|
+
}), Effect.fnUntraced(function* ([proc, closed, exited, stopOutput]) {
|
|
447
|
+
const done = (yield* Deferred.isDone(closed)) || (yield* Deferred.isDone(stopOutput));
|
|
448
|
+
if (done) {
|
|
449
|
+
const [code] = yield* Deferred.await(exited);
|
|
450
|
+
if (process.platform === "win32")
|
|
451
|
+
return;
|
|
452
|
+
if (code === 0 || Predicate.isNull(code))
|
|
453
|
+
return;
|
|
454
|
+
if (command.options.forceKillAfter === undefined) {
|
|
455
|
+
return yield* Effect.ignore(killGroup(command, proc, command.options.killSignal ?? "SIGTERM"));
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
yield* Effect.ignore(stop(command, proc, closed, stopOutput, {
|
|
459
|
+
killSignal: command.options.killSignal,
|
|
460
|
+
forceKillAfter: command.options.forceKillAfter ?? RELEASE_FORCE_KILL_AFTER,
|
|
461
|
+
}));
|
|
462
|
+
}, (effect, [proc, , , stopOutput, settle]) => effect.pipe(Effect.ensuring(Effect.gen(function* () {
|
|
463
|
+
// A detached descendant holding the pipes can keep "close" from ever firing.
|
|
464
|
+
settle();
|
|
465
|
+
yield* Deferred.succeed(stopOutput, undefined);
|
|
466
|
+
proc.stdout?.destroy();
|
|
467
|
+
proc.stderr?.destroy();
|
|
468
|
+
})))));
|
|
469
|
+
const completion = Effect.raceFirst(Deferred.await(closed), Deferred.await(stopOutput).pipe(Effect.andThen(Deferred.await(exited))));
|
|
470
|
+
const fd = yield* setupFds(command, proc, extra);
|
|
471
|
+
const out = setupOutput(command, proc, sout, serr, stopOutput);
|
|
472
|
+
let ref = true;
|
|
473
|
+
return makeHandle({
|
|
474
|
+
pid: ProcessId(proc.pid),
|
|
475
|
+
stdin: yield* setupStdin(command, proc, sin),
|
|
476
|
+
stdout: out.stdout,
|
|
477
|
+
stderr: out.stderr,
|
|
478
|
+
all: out.all,
|
|
479
|
+
getInputFd: fd.getInputFd,
|
|
480
|
+
getOutputFd: fd.getOutputFd,
|
|
481
|
+
isRunning: Effect.gen(function* () {
|
|
482
|
+
return !(yield* Deferred.isDone(closed)) && !(yield* Deferred.isDone(stopOutput));
|
|
483
|
+
}),
|
|
484
|
+
exitCode: Effect.flatMap(completion, ([code, signal]) => {
|
|
485
|
+
if (Predicate.isNotNull(code))
|
|
486
|
+
return Effect.succeed(ExitCode(code));
|
|
487
|
+
// Node reports a signal whenever the exit code is null.
|
|
488
|
+
return Effect.fail(toPlatformError("exitCode", new KilledBySignal(signal), command));
|
|
489
|
+
}),
|
|
490
|
+
kill: (opts) => stop(command, proc, closed, stopOutput, opts),
|
|
491
|
+
unref: Effect.sync(() => {
|
|
492
|
+
if (ref) {
|
|
493
|
+
proc.unref();
|
|
494
|
+
ref = false;
|
|
495
|
+
}
|
|
496
|
+
return Effect.sync(() => {
|
|
497
|
+
if (!ref) {
|
|
498
|
+
proc.ref();
|
|
499
|
+
ref = true;
|
|
500
|
+
}
|
|
501
|
+
});
|
|
502
|
+
}),
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
case "PipedCommand": {
|
|
506
|
+
const flat = flatten(command);
|
|
507
|
+
const [head, ...tail] = flat.commands;
|
|
508
|
+
let handle = spawnCommand(head);
|
|
509
|
+
for (let i = 0; i < tail.length; i++) {
|
|
510
|
+
const next = tail[i];
|
|
511
|
+
const opts = flat.opts[i] ?? {};
|
|
512
|
+
const sin = stdin(next.options);
|
|
513
|
+
const stream = Stream.unwrap(Effect.map(handle, (x) => source(x, opts.from)));
|
|
514
|
+
const to = opts.to ?? "stdin";
|
|
515
|
+
if (to === "stdin") {
|
|
516
|
+
handle = spawnCommand(ChildProcess.make(next.command, next.args, {
|
|
517
|
+
...next.options,
|
|
518
|
+
stdin: { ...sin, stream },
|
|
519
|
+
}));
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
const fd = ChildProcess.parseFdName(to);
|
|
523
|
+
if (Predicate.isUndefined(fd)) {
|
|
524
|
+
handle = spawnCommand(ChildProcess.make(next.command, next.args, {
|
|
525
|
+
...next.options,
|
|
526
|
+
stdin: { ...sin, stream },
|
|
527
|
+
}));
|
|
528
|
+
continue;
|
|
529
|
+
}
|
|
530
|
+
const name = ChildProcess.fdName(fd);
|
|
531
|
+
const existing = next.options.additionalFds?.[name];
|
|
532
|
+
handle = spawnCommand(ChildProcess.make(next.command, next.args, {
|
|
533
|
+
...next.options,
|
|
534
|
+
additionalFds: {
|
|
535
|
+
...next.options.additionalFds,
|
|
536
|
+
[name]: existing?.type === "duplex" ? { ...existing, stream } : { type: "input", stream },
|
|
537
|
+
},
|
|
538
|
+
}));
|
|
539
|
+
}
|
|
540
|
+
return yield* handle;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
});
|
|
544
|
+
return make(spawnCommand);
|
|
545
|
+
});
|
|
546
|
+
const layer = Layer.effect(ChildProcessSpawner, makeCrossSpawnSpawner);
|
|
547
|
+
export const node = makeGlobalNode({ service: ChildProcessSpawner, layer, deps: [filesystem, path] });
|
|
548
|
+
export * as CrossSpawnSpawner from "./cross-spawn-spawner.js";
|
package/dist/duration.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Compact elapsed time, e.g. `850ms`, `12.4s`, `3m 5s`, `2h 10m` or `1d 4h`. */
|
|
2
|
+
export function duration(input) {
|
|
3
|
+
if (input < 1000) {
|
|
4
|
+
return `${input}ms`;
|
|
5
|
+
}
|
|
6
|
+
if (input < 60000) {
|
|
7
|
+
return `${(input / 1000).toFixed(1)}s`;
|
|
8
|
+
}
|
|
9
|
+
if (input < 3600000) {
|
|
10
|
+
const minutes = Math.floor(input / 60000);
|
|
11
|
+
const seconds = Math.floor((input % 60000) / 1000);
|
|
12
|
+
return `${minutes}m ${seconds}s`;
|
|
13
|
+
}
|
|
14
|
+
if (input < 86400000) {
|
|
15
|
+
const hours = Math.floor(input / 3600000);
|
|
16
|
+
const minutes = Math.floor((input % 3600000) / 60000);
|
|
17
|
+
return `${hours}h ${minutes}m`;
|
|
18
|
+
}
|
|
19
|
+
const days = Math.floor(input / 86400000);
|
|
20
|
+
const hours = Math.floor((input % 86400000) / 3600000);
|
|
21
|
+
return `${days}d ${hours}h`;
|
|
22
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { FileSystem, Layer, Path } from "effect";
|
|
2
|
+
import { HttpClient } from "effect/http";
|
|
3
|
+
export declare const filesystem: import("./layer-node.js").Provider<FileSystem.FileSystem, never, import("./layer-node.js").Tag<"global">, true>;
|
|
4
|
+
export declare const path: import("./layer-node.js").Provider<Path.Path, never, import("./layer-node.js").Tag<"global">, true>;
|
|
5
|
+
export type Fetch = (input: Request | string | URL, init?: RequestInit) => Promise<Response>;
|
|
6
|
+
/**
|
|
7
|
+
* The fetch behind `httpClient`, AI SDK providers and remote MCP servers: `fetch` when given, so an embedder can route requests through
|
|
8
|
+
* e.g. a Service Binding, otherwise the `FetchHttpClient.Fetch` in scope when the graph is built.
|
|
9
|
+
*/
|
|
10
|
+
export declare const fetchLayer: (fetch?: Fetch) => Layer.Layer<never, never, never>;
|
|
11
|
+
export declare const httpFetch: import("./layer-node.js").Provider<never, never, import("./layer-node.js").Tag<"global">, true>;
|
|
12
|
+
export declare const httpClient: import("./layer-node.js").Provider<HttpClient.HttpClient, never, import("./layer-node.js").Tag<"global">, true>;
|
|
13
|
+
export * as LayerNodePlatform from "./app-node-platform.js";
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Deep imports: the @effect/platform-node barrel eagerly pulls in undici,
|
|
2
|
+
// ioredis, and node:sqlite, which runtimes such as workerd cannot load.
|
|
3
|
+
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
|
|
4
|
+
import * as NodePath from "@effect/platform-node/NodePath";
|
|
5
|
+
import { Effect, FileSystem, Layer, Path } from "effect";
|
|
6
|
+
import { FetchHttpClient, HttpClient } from "effect/http";
|
|
7
|
+
import { makeGlobalNode } from "./app-node.js";
|
|
8
|
+
export const filesystem = makeGlobalNode({ service: FileSystem.FileSystem, layer: NodeFileSystem.layer, deps: [] });
|
|
9
|
+
export const path = makeGlobalNode({ service: Path.Path, layer: NodePath.layer, deps: [] });
|
|
10
|
+
/**
|
|
11
|
+
* The fetch behind `httpClient`, AI SDK providers and remote MCP servers: `fetch` when given, so an embedder can route requests through
|
|
12
|
+
* e.g. a Service Binding, otherwise the `FetchHttpClient.Fetch` in scope when the graph is built.
|
|
13
|
+
*/
|
|
14
|
+
export const fetchLayer = (fetch) => Layer.effect(FetchHttpClient.Fetch, Effect.gen(function* () {
|
|
15
|
+
// Bun's `typeof fetch` adds `preconnect`, which nothing here calls.
|
|
16
|
+
return fetch ? fetch : yield* FetchHttpClient.Fetch;
|
|
17
|
+
}));
|
|
18
|
+
export const httpFetch = makeGlobalNode({ service: FetchHttpClient.Fetch, layer: fetchLayer(), deps: [] });
|
|
19
|
+
// Provided per request, so a caller's context can't swap `httpFetch` for another fetch.
|
|
20
|
+
export const httpClient = makeGlobalNode({
|
|
21
|
+
service: HttpClient.HttpClient,
|
|
22
|
+
layer: Layer.effect(HttpClient.HttpClient, Effect.gen(function* () {
|
|
23
|
+
const fetch = yield* FetchHttpClient.Fetch;
|
|
24
|
+
const client = yield* HttpClient.HttpClient.pipe(Effect.provide(FetchHttpClient.layer));
|
|
25
|
+
return HttpClient.transformResponse(client, Effect.provideService(FetchHttpClient.Fetch, fetch));
|
|
26
|
+
})),
|
|
27
|
+
deps: [httpFetch],
|
|
28
|
+
});
|
|
29
|
+
export * as LayerNodePlatform from "./app-node-platform.js";
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { LayerNode } from "./layer-node.js";
|
|
2
|
+
export declare const tags: LayerNode.Tags<{
|
|
3
|
+
readonly location: readonly ["global"];
|
|
4
|
+
readonly global: readonly [];
|
|
5
|
+
}>;
|
|
6
|
+
export type GlobalGraph<A, E = never> = LayerNode.Graph<A, E, (typeof tags.values)["global"]>;
|
|
7
|
+
export type LocationGraph<A, E = never> = LayerNode.Graph<A, E, (typeof tags.values)["location" | "global"]>;
|
|
8
|
+
export declare const makeGlobalNode: LayerNode.TagMaker<{
|
|
9
|
+
readonly location: readonly ["global"];
|
|
10
|
+
readonly global: readonly [];
|
|
11
|
+
}, "global">;
|
|
12
|
+
export declare const makeLocationNode: LayerNode.TagMaker<{
|
|
13
|
+
readonly location: readonly ["global"];
|
|
14
|
+
readonly global: readonly [];
|
|
15
|
+
}, "location">;
|
|
16
|
+
export * as Node from "./app-node.js";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { LayerNode } from "./layer-node.js";
|
|
2
|
+
export const tags = LayerNode.tags({
|
|
3
|
+
location: ["global"],
|
|
4
|
+
global: [],
|
|
5
|
+
});
|
|
6
|
+
export const makeGlobalNode = tags.make("global");
|
|
7
|
+
export const makeLocationNode = tags.make("location");
|
|
8
|
+
export * as Node from "./app-node.js";
|