@zyro-sec/util 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/layer-node.md +155 -0
- package/package.json +12 -19
- package/script/build.ts +9 -0
- package/script/pack.ts +5 -0
- package/src/abort.test.ts +16 -0
- package/src/abort.ts +9 -0
- package/src/activity-calendar.test.ts +136 -0
- package/src/activity-calendar.ts +50 -0
- package/src/artifact.test.ts +29 -0
- package/src/artifact.ts +95 -0
- package/src/base64.test.ts +12 -0
- package/src/base64.ts +29 -0
- package/src/binary.test.ts +19 -0
- package/src/binary.ts +30 -0
- package/src/bom.test.ts +21 -0
- package/src/bom.ts +46 -0
- package/src/cross-spawn-spawner.ts +694 -0
- package/src/duration.ts +22 -0
- package/src/effect/app-node-platform.ts +40 -0
- package/src/effect/app-node.ts +14 -0
- package/src/effect/layer-node.ts +360 -0
- package/src/effect-flock.ts +313 -0
- package/src/encode.test.ts +32 -0
- package/src/encode.ts +39 -0
- package/src/execute-output.test.ts +36 -0
- package/src/execute-output.ts +23 -0
- package/src/flock.ts +346 -0
- package/src/fs-util.ts +271 -0
- package/src/glob.ts +38 -0
- package/src/global-roots.ts +19 -0
- package/src/global-roots.workerd.ts +16 -0
- package/src/global.ts +88 -0
- package/src/hash.ts +11 -0
- package/src/heap-snapshot.ts +44 -0
- package/src/no-timeout-fetch.test.ts +33 -0
- package/src/no-timeout-fetch.ts +5 -0
- package/src/npm-config.ts +41 -0
- package/src/npm.ts +557 -0
- package/src/observability/logging.ts +179 -0
- package/src/observability/otlp.ts +109 -0
- package/src/observability/shared.ts +8 -0
- package/src/observability.ts +60 -0
- package/src/open.test.ts +16 -0
- package/src/open.ts +12 -0
- package/src/patch.ts +382 -0
- package/src/path.test.ts +89 -0
- package/src/path.ts +149 -0
- package/src/process-signal.test.ts +38 -0
- package/src/process-signal.ts +23 -0
- package/src/process.ts +270 -0
- package/src/qr.ts +323 -0
- package/src/record.ts +3 -0
- package/src/retry.test.ts +87 -0
- package/src/retry.ts +51 -0
- package/src/runtime/import.bun.ts +10 -0
- package/src/runtime/import.node.ts +61 -0
- package/src/runtime/import.workerd.ts +9 -0
- package/src/runtime-import.ts +1 -0
- package/src/session-mention.test.ts +19 -0
- package/src/session-mention.ts +24 -0
- package/src/session-title-fallback.ts +36 -0
- package/src/session-turn.test.ts +131 -0
- package/src/session-turn.ts +82 -0
- package/src/teardown.ts +19 -0
- package/src/text-boundary.test.ts +39 -0
- package/src/text-boundary.ts +36 -0
- package/src/uuid.test.ts +80 -0
- package/src/uuid.ts +15 -0
- package/test/fixtures/qr.json +625 -0
- package/test/glob.test.ts +11 -0
- package/test/global-roots.test.ts +62 -0
- package/test/global.test.ts +99 -0
- package/test/observability-otlp.test.ts +45 -0
- package/test/qr.test.ts +113 -0
- package/test/session-title-fallback.test.ts +49 -0
- package/tsconfig.build.json +12 -0
- package/tsconfig.dist.json +10 -0
- package/tsconfig.json +14 -0
|
@@ -0,0 +1,694 @@
|
|
|
1
|
+
import { isArrayNonEmpty } from "effect/Array"
|
|
2
|
+
import * as NodeSink from "@effect/platform-node/NodeSink"
|
|
3
|
+
import * as NodeStream from "@effect/platform-node/NodeStream"
|
|
4
|
+
import {
|
|
5
|
+
Deferred,
|
|
6
|
+
Effect,
|
|
7
|
+
Exit,
|
|
8
|
+
FileSystem,
|
|
9
|
+
Layer,
|
|
10
|
+
Path,
|
|
11
|
+
PlatformError,
|
|
12
|
+
Predicate,
|
|
13
|
+
Redacted,
|
|
14
|
+
Sink,
|
|
15
|
+
Stream,
|
|
16
|
+
} from "effect"
|
|
17
|
+
import type { Scope } from "effect"
|
|
18
|
+
import { ChildProcess } from "effect/process"
|
|
19
|
+
import {
|
|
20
|
+
ChildProcessSpawner,
|
|
21
|
+
ExitCode,
|
|
22
|
+
make,
|
|
23
|
+
makeHandle,
|
|
24
|
+
ProcessId,
|
|
25
|
+
type ChildProcessHandle,
|
|
26
|
+
} from "effect/process/ChildProcessSpawner"
|
|
27
|
+
// ast-grep-ignore: no-star-import
|
|
28
|
+
import * as NodeChildProcess from "node:child_process"
|
|
29
|
+
import { PassThrough } from "node:stream"
|
|
30
|
+
import launch from "cross-spawn"
|
|
31
|
+
import { makeGlobalNode } from "./effect/app-node.js"
|
|
32
|
+
import { filesystem, path } from "./effect/app-node-platform.js"
|
|
33
|
+
import { Teardown } from "./teardown.js"
|
|
34
|
+
|
|
35
|
+
/** Closing a child's scope escalates to SIGKILL after this, unless the command sets its own `forceKillAfter`. */
|
|
36
|
+
export const RELEASE_FORCE_KILL_AFTER = "3 seconds"
|
|
37
|
+
|
|
38
|
+
// Process groups of running children. Exiting without stopping them (a shutdown deadline, a second signal, a
|
|
39
|
+
// crash) would orphan them, so a synchronous exit hook kills whatever is left.
|
|
40
|
+
const groups = new Set<number>()
|
|
41
|
+
let hooked = false
|
|
42
|
+
const killGroups = () =>
|
|
43
|
+
groups.forEach((pid) => {
|
|
44
|
+
try {
|
|
45
|
+
globalThis.process.kill(-pid, "SIGKILL")
|
|
46
|
+
} catch {
|
|
47
|
+
// Already gone.
|
|
48
|
+
}
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
const unwrap = (value: string | Redacted.Redacted<string>): string =>
|
|
52
|
+
Redacted.isRedacted(value) ? Redacted.value(value) : value
|
|
53
|
+
|
|
54
|
+
// Node's own NUL check throws an error that includes the value, so NUL is rejected here to keep Redacted values
|
|
55
|
+
// out of errors.
|
|
56
|
+
const findNulCharacter = (command: ChildProcess.StandardCommand): string | undefined => {
|
|
57
|
+
if (command.command.includes("\0")) return "The command contains a NUL character"
|
|
58
|
+
const index = command.args.findIndex((arg) => unwrap(arg).includes("\0"))
|
|
59
|
+
if (index !== -1) return `Argument ${index + 1} contains a NUL character`
|
|
60
|
+
for (const [name, value] of Object.entries(command.options.env ?? {})) {
|
|
61
|
+
if (value !== undefined && unwrap(value).includes("\0")) {
|
|
62
|
+
return `The environment variable ${name} contains a NUL character`
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return undefined
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Buffered writes can fail after the sink has been interrupted and removed its error listener. Keep a fallback until
|
|
69
|
+
// close, without replacing the sink listener that propagates errors while it is active.
|
|
70
|
+
const handleInputErrors = (writable: NodeJS.WritableStream) => {
|
|
71
|
+
const onError = () => {}
|
|
72
|
+
writable.on("error", onError)
|
|
73
|
+
writable.once("close", () => writable.off("error", onError))
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const toError = (err: unknown): Error => (err instanceof globalThis.Error ? err : new globalThis.Error(String(err)))
|
|
77
|
+
|
|
78
|
+
const toTag = (err: NodeJS.ErrnoException): PlatformError.SystemErrorTag => {
|
|
79
|
+
switch (err.code) {
|
|
80
|
+
case "ENOENT":
|
|
81
|
+
return "NotFound"
|
|
82
|
+
case "EACCES":
|
|
83
|
+
return "PermissionDenied"
|
|
84
|
+
case "EEXIST":
|
|
85
|
+
return "AlreadyExists"
|
|
86
|
+
case "EISDIR":
|
|
87
|
+
return "BadResource"
|
|
88
|
+
case "ENOTDIR":
|
|
89
|
+
return "BadResource"
|
|
90
|
+
case "EBUSY":
|
|
91
|
+
return "Busy"
|
|
92
|
+
case "ELOOP":
|
|
93
|
+
return "BadResource"
|
|
94
|
+
default:
|
|
95
|
+
return "Unknown"
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const flatten = (command: ChildProcess.Command) => {
|
|
100
|
+
const commands: Array<ChildProcess.StandardCommand> = []
|
|
101
|
+
const opts: Array<ChildProcess.PipeOptions> = []
|
|
102
|
+
|
|
103
|
+
const walk = (cmd: ChildProcess.Command): void => {
|
|
104
|
+
switch (cmd._tag) {
|
|
105
|
+
case "StandardCommand":
|
|
106
|
+
commands.push(cmd)
|
|
107
|
+
return
|
|
108
|
+
case "PipedCommand":
|
|
109
|
+
walk(cmd.left)
|
|
110
|
+
opts.push(cmd.options)
|
|
111
|
+
walk(cmd.right)
|
|
112
|
+
return
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
walk(command)
|
|
117
|
+
if (!isArrayNonEmpty(commands)) throw new Error("flatten produced empty commands array")
|
|
118
|
+
return {
|
|
119
|
+
commands,
|
|
120
|
+
opts,
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const toPlatformError = (
|
|
125
|
+
method: string,
|
|
126
|
+
err: NodeJS.ErrnoException,
|
|
127
|
+
command: ChildProcess.Command,
|
|
128
|
+
): PlatformError.PlatformError => {
|
|
129
|
+
const cmd = flatten(command)
|
|
130
|
+
.commands.map((x) => `${x.command} ${x.args.join(" ")}`)
|
|
131
|
+
.join(" | ")
|
|
132
|
+
return PlatformError.systemError({
|
|
133
|
+
_tag: toTag(err),
|
|
134
|
+
module: "ChildProcess",
|
|
135
|
+
method,
|
|
136
|
+
pathOrDescriptor: cmd,
|
|
137
|
+
syscall: err.syscall,
|
|
138
|
+
cause: err,
|
|
139
|
+
})
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export class KilledBySignal extends Error {
|
|
143
|
+
readonly signal: NodeJS.Signals
|
|
144
|
+
|
|
145
|
+
constructor(signal: NodeJS.Signals) {
|
|
146
|
+
super(`Process interrupted due to receipt of signal: '${signal}'`)
|
|
147
|
+
this.signal = signal
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
type ExitSignal = Deferred.Deferred<readonly [code: number | null, signal: NodeJS.Signals | null]>
|
|
152
|
+
type Spawned = readonly [
|
|
153
|
+
process: NodeChildProcess.ChildProcess,
|
|
154
|
+
closed: ExitSignal,
|
|
155
|
+
exited: ExitSignal,
|
|
156
|
+
settle: () => void,
|
|
157
|
+
]
|
|
158
|
+
|
|
159
|
+
const makeCrossSpawnSpawner = Effect.gen(function* () {
|
|
160
|
+
const fs = yield* FileSystem.FileSystem
|
|
161
|
+
const path = yield* Path.Path
|
|
162
|
+
|
|
163
|
+
const cwd = Effect.fnUntraced(function* (opts: ChildProcess.CommandOptions) {
|
|
164
|
+
if (Predicate.isUndefined(opts.cwd)) return undefined
|
|
165
|
+
yield* fs.access(opts.cwd)
|
|
166
|
+
return path.resolve(opts.cwd)
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
const env = (opts: ChildProcess.CommandOptions) => {
|
|
170
|
+
if (opts.env === undefined) return opts.extendEnv ? globalThis.process.env : undefined
|
|
171
|
+
const result: Record<string, string | undefined> = opts.extendEnv ? { ...globalThis.process.env } : {}
|
|
172
|
+
for (const [key, value] of Object.entries(opts.env)) {
|
|
173
|
+
if (value === undefined) delete result[key]
|
|
174
|
+
else result[key] = unwrap(value)
|
|
175
|
+
}
|
|
176
|
+
return result
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const input = (x: ChildProcess.CommandInput | undefined): NodeChildProcess.IOType | undefined =>
|
|
180
|
+
Stream.isStream(x) ? "pipe" : x
|
|
181
|
+
|
|
182
|
+
const output = (x: ChildProcess.CommandOutput | undefined): NodeChildProcess.IOType | undefined =>
|
|
183
|
+
Sink.isSink(x) ? "pipe" : x
|
|
184
|
+
|
|
185
|
+
const stdin = (opts: ChildProcess.CommandOptions): ChildProcess.StdinConfig => {
|
|
186
|
+
const cfg: ChildProcess.StdinConfig = { stream: "pipe", encoding: "utf-8", endOnDone: true }
|
|
187
|
+
if (Predicate.isUndefined(opts.stdin)) return cfg
|
|
188
|
+
if (typeof opts.stdin === "string") return { ...cfg, stream: opts.stdin }
|
|
189
|
+
if (Stream.isStream(opts.stdin)) return { ...cfg, stream: opts.stdin }
|
|
190
|
+
return {
|
|
191
|
+
stream: opts.stdin.stream,
|
|
192
|
+
encoding: opts.stdin.encoding ?? cfg.encoding,
|
|
193
|
+
endOnDone: opts.stdin.endOnDone ?? cfg.endOnDone,
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const stdio = (opts: ChildProcess.CommandOptions, key: "stdout" | "stderr"): ChildProcess.StdoutConfig => {
|
|
198
|
+
const cfg = opts[key]
|
|
199
|
+
if (Predicate.isUndefined(cfg)) return { stream: "pipe" }
|
|
200
|
+
if (typeof cfg === "string") return { stream: cfg }
|
|
201
|
+
if (Sink.isSink(cfg)) return { stream: cfg }
|
|
202
|
+
return { stream: cfg.stream }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const fds = (opts: ChildProcess.CommandOptions) => {
|
|
206
|
+
if (Predicate.isUndefined(opts.additionalFds)) return []
|
|
207
|
+
return Object.entries(opts.additionalFds)
|
|
208
|
+
.flatMap(([name, config]) => {
|
|
209
|
+
const fd = ChildProcess.parseFdName(name)
|
|
210
|
+
return Predicate.isUndefined(fd) ? [] : [{ fd, config }]
|
|
211
|
+
})
|
|
212
|
+
.toSorted((a, b) => a.fd - b.fd)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const stdios = (
|
|
216
|
+
sin: ChildProcess.StdinConfig,
|
|
217
|
+
sout: ChildProcess.StdoutConfig,
|
|
218
|
+
serr: ChildProcess.StderrConfig,
|
|
219
|
+
extra: ReadonlyArray<{ fd: number; config: ChildProcess.AdditionalFdConfig }>,
|
|
220
|
+
): NodeChildProcess.StdioOptions => {
|
|
221
|
+
const pipe = (x: NodeChildProcess.IOType | undefined) =>
|
|
222
|
+
process.platform === "win32" && x === "pipe" ? "overlapped" : x
|
|
223
|
+
const arr: Array<NodeChildProcess.IOType | undefined> = [
|
|
224
|
+
pipe(input(sin.stream)),
|
|
225
|
+
pipe(output(sout.stream)),
|
|
226
|
+
pipe(output(serr.stream)),
|
|
227
|
+
]
|
|
228
|
+
if (extra.length === 0) return arr as NodeChildProcess.StdioOptions
|
|
229
|
+
const max = extra.reduce((acc, x) => Math.max(acc, x.fd), 2)
|
|
230
|
+
for (let i = 3; i <= max; i++) arr[i] = "ignore"
|
|
231
|
+
for (const x of extra) arr[x.fd] = pipe("pipe")
|
|
232
|
+
return arr as NodeChildProcess.StdioOptions
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const setupFds = Effect.fnUntraced(function* (
|
|
236
|
+
command: ChildProcess.StandardCommand,
|
|
237
|
+
proc: NodeChildProcess.ChildProcess,
|
|
238
|
+
extra: ReadonlyArray<{ fd: number; config: ChildProcess.AdditionalFdConfig }>,
|
|
239
|
+
) {
|
|
240
|
+
if (extra.length === 0) {
|
|
241
|
+
return {
|
|
242
|
+
getInputFd: () => Sink.drain,
|
|
243
|
+
getOutputFd: () => Stream.empty,
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const ins = new Map<number, Sink.Sink<void, Uint8Array, never, PlatformError.PlatformError>>()
|
|
248
|
+
const outs = new Map<number, Stream.Stream<Uint8Array, PlatformError.PlatformError>>()
|
|
249
|
+
|
|
250
|
+
const setupInput = Effect.fnUntraced(function* (
|
|
251
|
+
fd: number,
|
|
252
|
+
node: NodeChildProcess.ChildProcess["stdio"][number],
|
|
253
|
+
source: Stream.Stream<Uint8Array, PlatformError.PlatformError> | undefined,
|
|
254
|
+
) {
|
|
255
|
+
let sink: Sink.Sink<void, Uint8Array, never, PlatformError.PlatformError> = Sink.drain
|
|
256
|
+
if (node && "write" in node) {
|
|
257
|
+
handleInputErrors(node)
|
|
258
|
+
sink = NodeSink.fromWritable({
|
|
259
|
+
evaluate: () => node,
|
|
260
|
+
onError: (err) => toPlatformError(`fromWritable(fd${fd})`, toError(err), command),
|
|
261
|
+
endOnDone: true,
|
|
262
|
+
})
|
|
263
|
+
}
|
|
264
|
+
if (source) yield* Effect.forkScoped(Stream.run(source, sink))
|
|
265
|
+
ins.set(fd, sink)
|
|
266
|
+
})
|
|
267
|
+
|
|
268
|
+
const setupOutput = (
|
|
269
|
+
fd: number,
|
|
270
|
+
node: NodeChildProcess.ChildProcess["stdio"][number],
|
|
271
|
+
sink: Sink.Sink<Uint8Array, Uint8Array, never, PlatformError.PlatformError> | undefined,
|
|
272
|
+
) => {
|
|
273
|
+
let stream: Stream.Stream<Uint8Array, PlatformError.PlatformError> = Stream.empty
|
|
274
|
+
if (node && "read" in node) {
|
|
275
|
+
const tap = new PassThrough()
|
|
276
|
+
// Retain errors raised before anyone reads, e.g. a failed write on a duplex fd, so they neither go uncaught
|
|
277
|
+
// nor leave later readers hanging.
|
|
278
|
+
let error: unknown = undefined
|
|
279
|
+
tap.on("error", (cause) => {
|
|
280
|
+
error ??= cause
|
|
281
|
+
})
|
|
282
|
+
node.on("error", (err) => tap.destroy(toError(err)))
|
|
283
|
+
node.pipe(tap)
|
|
284
|
+
const onError = (err: unknown) => toPlatformError(`fromReadable(fd${fd})`, toError(err), command)
|
|
285
|
+
stream = Stream.suspend(() =>
|
|
286
|
+
error === undefined ? NodeStream.fromReadable({ evaluate: () => tap, onError }) : Stream.fail(onError(error)),
|
|
287
|
+
)
|
|
288
|
+
}
|
|
289
|
+
if (sink) stream = Stream.transduce(stream, sink)
|
|
290
|
+
outs.set(fd, stream)
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
for (const x of extra) {
|
|
294
|
+
const node = proc.stdio[x.fd]
|
|
295
|
+
switch (x.config.type) {
|
|
296
|
+
case "input":
|
|
297
|
+
yield* setupInput(x.fd, node, x.config.stream)
|
|
298
|
+
break
|
|
299
|
+
case "output":
|
|
300
|
+
setupOutput(x.fd, node, x.config.sink)
|
|
301
|
+
break
|
|
302
|
+
case "duplex":
|
|
303
|
+
// Keep writing possible after the child closes its write side.
|
|
304
|
+
if (node && "allowHalfOpen" in node) node.allowHalfOpen = true
|
|
305
|
+
setupOutput(x.fd, node, x.config.sink)
|
|
306
|
+
yield* setupInput(x.fd, node, x.config.stream)
|
|
307
|
+
break
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
return {
|
|
312
|
+
getInputFd: (fd: number) => ins.get(fd) ?? Sink.drain,
|
|
313
|
+
getOutputFd: (fd: number) => outs.get(fd) ?? Stream.empty,
|
|
314
|
+
}
|
|
315
|
+
})
|
|
316
|
+
|
|
317
|
+
const setupStdin = (
|
|
318
|
+
command: ChildProcess.StandardCommand,
|
|
319
|
+
proc: NodeChildProcess.ChildProcess,
|
|
320
|
+
cfg: ChildProcess.StdinConfig,
|
|
321
|
+
) =>
|
|
322
|
+
Effect.suspend(() => {
|
|
323
|
+
let sink: Sink.Sink<void, unknown, never, PlatformError.PlatformError> = Sink.drain
|
|
324
|
+
if (Predicate.isNotNull(proc.stdin)) {
|
|
325
|
+
handleInputErrors(proc.stdin)
|
|
326
|
+
sink = NodeSink.fromWritable({
|
|
327
|
+
evaluate: () => proc.stdin!,
|
|
328
|
+
onError: (err) => toPlatformError("fromWritable(stdin)", toError(err), command),
|
|
329
|
+
endOnDone: cfg.endOnDone,
|
|
330
|
+
encoding: cfg.encoding,
|
|
331
|
+
})
|
|
332
|
+
}
|
|
333
|
+
if (Stream.isStream(cfg.stream)) return Effect.as(Effect.forkScoped(Stream.run(cfg.stream, sink)), sink)
|
|
334
|
+
return Effect.succeed(sink)
|
|
335
|
+
})
|
|
336
|
+
|
|
337
|
+
const setupOutput = (
|
|
338
|
+
command: ChildProcess.StandardCommand,
|
|
339
|
+
proc: NodeChildProcess.ChildProcess,
|
|
340
|
+
out: ChildProcess.StdoutConfig,
|
|
341
|
+
err: ChildProcess.StderrConfig,
|
|
342
|
+
stopOutput: Deferred.Deferred<void>,
|
|
343
|
+
) => {
|
|
344
|
+
const capture = (readable: NodeChildProcess.ChildProcess["stdout"], name: string) => {
|
|
345
|
+
if (!readable) return Stream.empty
|
|
346
|
+
// Bun resumes stdio on exit; retain bytes before the lazy Effect reader attaches.
|
|
347
|
+
const buffer = new PassThrough()
|
|
348
|
+
readable.on("error", (cause) => buffer.destroy(toError(cause)))
|
|
349
|
+
readable.pipe(buffer)
|
|
350
|
+
return NodeStream.fromReadable({
|
|
351
|
+
evaluate: () => buffer,
|
|
352
|
+
onError: (cause) => toPlatformError(`fromReadable(${name})`, toError(cause), command),
|
|
353
|
+
}).pipe(
|
|
354
|
+
Stream.interruptWhen(Deferred.await(stopOutput)),
|
|
355
|
+
Stream.ensuring(
|
|
356
|
+
Effect.gen(function* () {
|
|
357
|
+
// Only the capture deadline transfers the reader back to the process scope.
|
|
358
|
+
if (yield* Deferred.isDone(stopOutput)) return
|
|
359
|
+
readable.destroy()
|
|
360
|
+
}),
|
|
361
|
+
),
|
|
362
|
+
)
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
let stdout = capture(proc.stdout, "stdout")
|
|
366
|
+
let stderr = capture(proc.stderr, "stderr")
|
|
367
|
+
if (Sink.isSink(out.stream)) stdout = Stream.transduce(stdout, out.stream)
|
|
368
|
+
if (Sink.isSink(err.stream)) stderr = Stream.transduce(stderr, err.stream)
|
|
369
|
+
|
|
370
|
+
return { stdout, stderr, all: Stream.merge(stdout, stderr) }
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// A Microsoft Store app execution alias, such as Store PowerShell 7 in %LOCALAPPDATA%\Microsoft\WindowsApps, is a
|
|
374
|
+
// reparse point that stat rejects with EACCES. cross-spawn then cannot find it and runs it through
|
|
375
|
+
// `cmd.exe /d /s /c`, which drops everything after the first newline of the command line. Launch the target of
|
|
376
|
+
// the link instead, read on every spawn because a Store update moves it.
|
|
377
|
+
const executable = (file: string) => {
|
|
378
|
+
if (globalThis.process.platform !== "win32" || !path.isAbsolute(file)) return Effect.succeed(file)
|
|
379
|
+
return fs.readLink(file).pipe(
|
|
380
|
+
Effect.map((target) => path.resolve(path.dirname(file), target)),
|
|
381
|
+
Effect.orElseSucceed(() => file),
|
|
382
|
+
)
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
const launchProcess = (command: ChildProcess.StandardCommand, file: string, opts: NodeChildProcess.SpawnOptions) =>
|
|
386
|
+
Effect.callback<Spawned, PlatformError.PlatformError>((resume) => {
|
|
387
|
+
const closed = Deferred.makeUnsafe<readonly [code: number | null, signal: NodeJS.Signals | null]>()
|
|
388
|
+
const exited = Deferred.makeUnsafe<readonly [code: number | null, signal: NodeJS.Signals | null]>()
|
|
389
|
+
const proc = launch(file, command.args.map(unwrap), opts)
|
|
390
|
+
let settle = () => {}
|
|
391
|
+
let end = false
|
|
392
|
+
let exit: readonly [code: number | null, signal: NodeJS.Signals | null] | undefined
|
|
393
|
+
proc.on("error", (err) => {
|
|
394
|
+
// Node copies the arguments into `spawnargs`.
|
|
395
|
+
if (command.args.some(Redacted.isRedacted)) {
|
|
396
|
+
Object.assign(err, {
|
|
397
|
+
spawnargs: [command.command, ...command.args.map((arg) => (Redacted.isRedacted(arg) ? "<redacted>" : arg))],
|
|
398
|
+
})
|
|
399
|
+
}
|
|
400
|
+
resume(Effect.fail(toPlatformError("spawn", err, command)))
|
|
401
|
+
})
|
|
402
|
+
proc.on("exit", (...args) => {
|
|
403
|
+
groups.delete(proc.pid!)
|
|
404
|
+
exit = args
|
|
405
|
+
Deferred.doneUnsafe(exited, Exit.succeed(args))
|
|
406
|
+
})
|
|
407
|
+
proc.on("close", (...args) => {
|
|
408
|
+
if (end) return
|
|
409
|
+
end = true
|
|
410
|
+
settle()
|
|
411
|
+
Deferred.doneUnsafe(exited, Exit.succeed(exit ?? args))
|
|
412
|
+
Deferred.doneUnsafe(closed, Exit.succeed(exit ?? args))
|
|
413
|
+
})
|
|
414
|
+
proc.on("spawn", () => {
|
|
415
|
+
if (opts.detached && globalThis.process.platform !== "win32") {
|
|
416
|
+
if (!hooked) globalThis.process.once("exit", killGroups)
|
|
417
|
+
hooked = true
|
|
418
|
+
groups.add(proc.pid!)
|
|
419
|
+
}
|
|
420
|
+
settle = Teardown.track(
|
|
421
|
+
`child ${proc.pid} running: ${[command.command, ...command.args].join(" ").slice(0, 200)}`,
|
|
422
|
+
)
|
|
423
|
+
resume(Effect.succeed([proc, closed, exited, () => settle()]))
|
|
424
|
+
})
|
|
425
|
+
return Effect.sync(() => {
|
|
426
|
+
proc.kill("SIGTERM")
|
|
427
|
+
})
|
|
428
|
+
})
|
|
429
|
+
|
|
430
|
+
const spawn = Effect.fnUntraced(function* (
|
|
431
|
+
command: ChildProcess.StandardCommand,
|
|
432
|
+
opts: NodeChildProcess.SpawnOptions,
|
|
433
|
+
) {
|
|
434
|
+
yield* Effect.logDebug("spawning process", { command: command.command, args: command.args, cwd: opts.cwd })
|
|
435
|
+
const [proc, closed, exited, settle] = yield* launchProcess(command, yield* executable(command.command), opts)
|
|
436
|
+
const stopOutput = yield* Deferred.make<void>()
|
|
437
|
+
// Register before process release so the deadline remains active during termination.
|
|
438
|
+
yield* Effect.forkScoped(
|
|
439
|
+
Effect.gen(function* () {
|
|
440
|
+
yield* Deferred.await(exited)
|
|
441
|
+
// Particularly on Windows, some shell calls will cause detached descendants. Inherited stdio can hang the call.
|
|
442
|
+
// Almost every ecosystem has tried to fix this; there's no single "good" answer here.
|
|
443
|
+
// Calls that trigger this are e.g. dotnet build with warmed MSBuild processes, agent-browser, etc.
|
|
444
|
+
// One shared deadline covers stdout and stderr, then the output pump finishes its file.
|
|
445
|
+
if ((yield* Effect.timeoutOption(Deferred.await(closed), "1 second"))._tag === "Some") return
|
|
446
|
+
yield* Deferred.succeed(stopOutput, undefined)
|
|
447
|
+
discard(proc.stdout)
|
|
448
|
+
discard(proc.stderr)
|
|
449
|
+
}),
|
|
450
|
+
)
|
|
451
|
+
return [proc, closed, exited, stopOutput, settle] as const
|
|
452
|
+
})
|
|
453
|
+
|
|
454
|
+
const discard = (readable: NodeChildProcess.ChildProcess["stdout"]) => {
|
|
455
|
+
if (!readable || readable.destroyed) return
|
|
456
|
+
readable.unpipe()
|
|
457
|
+
// Discard descendant output without refilling a capture buffer that is no longer consumed.
|
|
458
|
+
const drain = () => {
|
|
459
|
+
while (readable.read() !== null) {}
|
|
460
|
+
}
|
|
461
|
+
readable.on("readable", drain)
|
|
462
|
+
readable.once("error", () => {})
|
|
463
|
+
readable.once("close", () => readable.off("readable", drain))
|
|
464
|
+
drain()
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const killGroup = (
|
|
468
|
+
command: ChildProcess.StandardCommand,
|
|
469
|
+
proc: NodeChildProcess.ChildProcess,
|
|
470
|
+
signal: NodeJS.Signals,
|
|
471
|
+
) => {
|
|
472
|
+
if (globalThis.process.platform === "win32") {
|
|
473
|
+
return Effect.callback<void, PlatformError.PlatformError>((resume) => {
|
|
474
|
+
NodeChildProcess.exec(`taskkill /pid ${proc.pid} /T /F`, { windowsHide: true }, (err) => {
|
|
475
|
+
if (err) return resume(Effect.fail(toPlatformError("kill", toError(err), command)))
|
|
476
|
+
resume(Effect.void)
|
|
477
|
+
})
|
|
478
|
+
})
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
return Effect.try({
|
|
482
|
+
try: () => {
|
|
483
|
+
globalThis.process.kill(-proc.pid!, signal)
|
|
484
|
+
},
|
|
485
|
+
catch: (err) => toPlatformError("kill", toError(err), command),
|
|
486
|
+
})
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
const killOne = (
|
|
490
|
+
command: ChildProcess.StandardCommand,
|
|
491
|
+
proc: NodeChildProcess.ChildProcess,
|
|
492
|
+
signal: NodeJS.Signals,
|
|
493
|
+
) =>
|
|
494
|
+
Effect.suspend(() => {
|
|
495
|
+
if (proc.kill(signal)) return Effect.void
|
|
496
|
+
return Effect.fail(toPlatformError("kill", new Error("Failed to kill child process"), command))
|
|
497
|
+
})
|
|
498
|
+
|
|
499
|
+
const stop = (
|
|
500
|
+
command: ChildProcess.StandardCommand,
|
|
501
|
+
proc: NodeChildProcess.ChildProcess,
|
|
502
|
+
closed: ExitSignal,
|
|
503
|
+
stopOutput: Deferred.Deferred<void>,
|
|
504
|
+
opts: ChildProcess.KillOptions | undefined,
|
|
505
|
+
) => {
|
|
506
|
+
const terminate = (signal: NodeJS.Signals) =>
|
|
507
|
+
Effect.catch(killGroup(command, proc, signal), () => killOne(command, proc, signal)).pipe(
|
|
508
|
+
Effect.andThen(
|
|
509
|
+
signal === "SIGKILL"
|
|
510
|
+
? Effect.raceFirst(Deferred.await(closed), Deferred.await(stopOutput))
|
|
511
|
+
: Deferred.await(closed),
|
|
512
|
+
),
|
|
513
|
+
Effect.asVoid,
|
|
514
|
+
)
|
|
515
|
+
const attempt = terminate(opts?.killSignal ?? "SIGTERM")
|
|
516
|
+
if (opts?.forceKillAfter === undefined) return attempt
|
|
517
|
+
return Effect.timeoutOrElse(attempt, {
|
|
518
|
+
duration: opts.forceKillAfter,
|
|
519
|
+
orElse: () => terminate("SIGKILL"),
|
|
520
|
+
})
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const source = (handle: ChildProcessHandle, from: ChildProcess.PipeFromOption | undefined) => {
|
|
524
|
+
const opt = from ?? "stdout"
|
|
525
|
+
switch (opt) {
|
|
526
|
+
case "stdout":
|
|
527
|
+
return handle.stdout
|
|
528
|
+
case "stderr":
|
|
529
|
+
return handle.stderr
|
|
530
|
+
case "all":
|
|
531
|
+
return handle.all
|
|
532
|
+
default: {
|
|
533
|
+
const fd = ChildProcess.parseFdName(opt)
|
|
534
|
+
return Predicate.isNotUndefined(fd) ? handle.getOutputFd(fd) : handle.stdout
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const spawnCommand: (
|
|
540
|
+
command: ChildProcess.Command,
|
|
541
|
+
) => Effect.Effect<ChildProcessHandle, PlatformError.PlatformError, Scope.Scope> = Effect.fnUntraced(
|
|
542
|
+
function* (command) {
|
|
543
|
+
switch (command._tag) {
|
|
544
|
+
case "StandardCommand": {
|
|
545
|
+
const nul = findNulCharacter(command)
|
|
546
|
+
if (nul !== undefined) {
|
|
547
|
+
return yield* Effect.fail(
|
|
548
|
+
PlatformError.badArgument({ module: "ChildProcess", method: "spawn", description: nul }),
|
|
549
|
+
)
|
|
550
|
+
}
|
|
551
|
+
const sin = stdin(command.options)
|
|
552
|
+
const sout = stdio(command.options, "stdout")
|
|
553
|
+
const serr = stdio(command.options, "stderr")
|
|
554
|
+
const extra = fds(command.options)
|
|
555
|
+
const dir = yield* cwd(command.options)
|
|
556
|
+
|
|
557
|
+
const [proc, closed, exited, stopOutput] = yield* Effect.acquireRelease(
|
|
558
|
+
spawn(command, {
|
|
559
|
+
cwd: dir,
|
|
560
|
+
env: env(command.options),
|
|
561
|
+
stdio: stdios(sin, sout, serr, extra),
|
|
562
|
+
detached: command.options.detached ?? process.platform !== "win32",
|
|
563
|
+
shell: command.options.shell,
|
|
564
|
+
windowsHide: process.platform === "win32",
|
|
565
|
+
}),
|
|
566
|
+
Effect.fnUntraced(
|
|
567
|
+
function* ([proc, closed, exited, stopOutput]) {
|
|
568
|
+
const done = (yield* Deferred.isDone(closed)) || (yield* Deferred.isDone(stopOutput))
|
|
569
|
+
if (done) {
|
|
570
|
+
const [code] = yield* Deferred.await(exited)
|
|
571
|
+
if (process.platform === "win32") return
|
|
572
|
+
if (code === 0 || Predicate.isNull(code)) return
|
|
573
|
+
if (command.options.forceKillAfter === undefined) {
|
|
574
|
+
return yield* Effect.ignore(killGroup(command, proc, command.options.killSignal ?? "SIGTERM"))
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
yield* Effect.ignore(
|
|
578
|
+
stop(command, proc, closed, stopOutput, {
|
|
579
|
+
killSignal: command.options.killSignal,
|
|
580
|
+
forceKillAfter: command.options.forceKillAfter ?? RELEASE_FORCE_KILL_AFTER,
|
|
581
|
+
}),
|
|
582
|
+
)
|
|
583
|
+
},
|
|
584
|
+
(effect, [proc, , , stopOutput, settle]) =>
|
|
585
|
+
effect.pipe(
|
|
586
|
+
Effect.ensuring(
|
|
587
|
+
Effect.gen(function* () {
|
|
588
|
+
// A detached descendant holding the pipes can keep "close" from ever firing.
|
|
589
|
+
settle()
|
|
590
|
+
yield* Deferred.succeed(stopOutput, undefined)
|
|
591
|
+
proc.stdout?.destroy()
|
|
592
|
+
proc.stderr?.destroy()
|
|
593
|
+
}),
|
|
594
|
+
),
|
|
595
|
+
),
|
|
596
|
+
),
|
|
597
|
+
)
|
|
598
|
+
|
|
599
|
+
const completion = Effect.raceFirst(
|
|
600
|
+
Deferred.await(closed),
|
|
601
|
+
Deferred.await(stopOutput).pipe(Effect.andThen(Deferred.await(exited))),
|
|
602
|
+
)
|
|
603
|
+
const fd = yield* setupFds(command, proc, extra)
|
|
604
|
+
const out = setupOutput(command, proc, sout, serr, stopOutput)
|
|
605
|
+
let ref = true
|
|
606
|
+
return makeHandle({
|
|
607
|
+
pid: ProcessId(proc.pid!),
|
|
608
|
+
stdin: yield* setupStdin(command, proc, sin),
|
|
609
|
+
stdout: out.stdout,
|
|
610
|
+
stderr: out.stderr,
|
|
611
|
+
all: out.all,
|
|
612
|
+
getInputFd: fd.getInputFd,
|
|
613
|
+
getOutputFd: fd.getOutputFd,
|
|
614
|
+
isRunning: Effect.gen(function* () {
|
|
615
|
+
return !(yield* Deferred.isDone(closed)) && !(yield* Deferred.isDone(stopOutput))
|
|
616
|
+
}),
|
|
617
|
+
exitCode: Effect.flatMap(completion, ([code, signal]) => {
|
|
618
|
+
if (Predicate.isNotNull(code)) return Effect.succeed(ExitCode(code))
|
|
619
|
+
// Node reports a signal whenever the exit code is null.
|
|
620
|
+
return Effect.fail(toPlatformError("exitCode", new KilledBySignal(signal!), command))
|
|
621
|
+
}),
|
|
622
|
+
kill: (opts?: ChildProcess.KillOptions) => stop(command, proc, closed, stopOutput, opts),
|
|
623
|
+
unref: Effect.sync(() => {
|
|
624
|
+
if (ref) {
|
|
625
|
+
proc.unref()
|
|
626
|
+
ref = false
|
|
627
|
+
}
|
|
628
|
+
return Effect.sync(() => {
|
|
629
|
+
if (!ref) {
|
|
630
|
+
proc.ref()
|
|
631
|
+
ref = true
|
|
632
|
+
}
|
|
633
|
+
})
|
|
634
|
+
}),
|
|
635
|
+
})
|
|
636
|
+
}
|
|
637
|
+
case "PipedCommand": {
|
|
638
|
+
const flat = flatten(command)
|
|
639
|
+
const [head, ...tail] = flat.commands
|
|
640
|
+
let handle = spawnCommand(head)
|
|
641
|
+
for (let i = 0; i < tail.length; i++) {
|
|
642
|
+
const next = tail[i]
|
|
643
|
+
const opts = flat.opts[i] ?? {}
|
|
644
|
+
const sin = stdin(next.options)
|
|
645
|
+
const stream = Stream.unwrap(Effect.map(handle, (x) => source(x, opts.from)))
|
|
646
|
+
const to = opts.to ?? "stdin"
|
|
647
|
+
if (to === "stdin") {
|
|
648
|
+
handle = spawnCommand(
|
|
649
|
+
ChildProcess.make(next.command, next.args, {
|
|
650
|
+
...next.options,
|
|
651
|
+
stdin: { ...sin, stream },
|
|
652
|
+
}),
|
|
653
|
+
)
|
|
654
|
+
continue
|
|
655
|
+
}
|
|
656
|
+
const fd = ChildProcess.parseFdName(to)
|
|
657
|
+
if (Predicate.isUndefined(fd)) {
|
|
658
|
+
handle = spawnCommand(
|
|
659
|
+
ChildProcess.make(next.command, next.args, {
|
|
660
|
+
...next.options,
|
|
661
|
+
stdin: { ...sin, stream },
|
|
662
|
+
}),
|
|
663
|
+
)
|
|
664
|
+
continue
|
|
665
|
+
}
|
|
666
|
+
const name = ChildProcess.fdName(fd) as `fd${number}`
|
|
667
|
+
const existing = next.options.additionalFds?.[name]
|
|
668
|
+
handle = spawnCommand(
|
|
669
|
+
ChildProcess.make(next.command, next.args, {
|
|
670
|
+
...next.options,
|
|
671
|
+
additionalFds: {
|
|
672
|
+
...next.options.additionalFds,
|
|
673
|
+
[name]: existing?.type === "duplex" ? { ...existing, stream } : { type: "input", stream },
|
|
674
|
+
},
|
|
675
|
+
}),
|
|
676
|
+
)
|
|
677
|
+
}
|
|
678
|
+
return yield* handle
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
},
|
|
682
|
+
)
|
|
683
|
+
|
|
684
|
+
return make(spawnCommand)
|
|
685
|
+
})
|
|
686
|
+
|
|
687
|
+
const layer: Layer.Layer<ChildProcessSpawner, never, FileSystem.FileSystem | Path.Path> = Layer.effect(
|
|
688
|
+
ChildProcessSpawner,
|
|
689
|
+
makeCrossSpawnSpawner,
|
|
690
|
+
)
|
|
691
|
+
|
|
692
|
+
export const node = makeGlobalNode({ service: ChildProcessSpawner, layer, deps: [filesystem, path] })
|
|
693
|
+
|
|
694
|
+
export * as CrossSpawnSpawner from "./cross-spawn-spawner.js"
|