@opencode/util 0.0.0-dev-416 → 0.0.0-dev-425

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.
@@ -1,7 +1,7 @@
1
1
  import { isArrayNonEmpty } from "effect/Array";
2
2
  import * as NodeSink from "@effect/platform-node/NodeSink";
3
3
  import * as NodeStream from "@effect/platform-node/NodeStream";
4
- import { Deferred, Effect, Exit, FileSystem, Layer, Path, PlatformError, Predicate, Sink, Stream } from "effect";
4
+ import { Deferred, Effect, Exit, FileSystem, Layer, Path, PlatformError, Predicate, Redacted, Sink, Stream, } from "effect";
5
5
  import { ChildProcess } from "effect/process";
6
6
  import { ChildProcessSpawner, ExitCode, make, makeHandle, ProcessId, } from "effect/process/ChildProcessSpawner";
7
7
  // ast-grep-ignore: no-star-import
@@ -25,6 +25,29 @@ const killGroups = () => groups.forEach((pid) => {
25
25
  // Already gone.
26
26
  }
27
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
+ };
28
51
  const toError = (err) => (err instanceof globalThis.Error ? err : new globalThis.Error(String(err)));
29
52
  const toTag = (err) => {
30
53
  switch (err.code) {
@@ -98,7 +121,18 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
98
121
  yield* fs.access(opts.cwd);
99
122
  return path.resolve(opts.cwd);
100
123
  });
101
- const env = (opts) => opts.extendEnv ? { ...globalThis.process.env, ...opts.env } : opts.env;
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
+ };
102
136
  const input = (x) => Stream.isStream(x) ? "pipe" : x;
103
137
  const output = (x) => Sink.isSink(x) ? "pipe" : x;
104
138
  const stdin = (opts) => {
@@ -160,39 +194,55 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
160
194
  }
161
195
  const ins = new Map();
162
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 = NodeSink.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 ? NodeStream.fromReadable({ evaluate: () => tap, onError }) : Stream.fail(onError(error)));
225
+ }
226
+ if (sink)
227
+ stream = Stream.transduce(stream, sink);
228
+ outs.set(fd, stream);
229
+ };
163
230
  for (const x of extra) {
164
231
  const node = proc.stdio[x.fd];
165
232
  switch (x.config.type) {
166
- case "input": {
167
- let sink = Sink.drain;
168
- if (node && "write" in node) {
169
- sink = NodeSink.fromWritable({
170
- evaluate: () => node,
171
- onError: (err) => toPlatformError(`fromWritable(fd${x.fd})`, toError(err), command),
172
- endOnDone: true,
173
- });
174
- }
175
- if (x.config.stream)
176
- yield* Effect.forkScoped(Stream.run(x.config.stream, sink));
177
- ins.set(x.fd, sink);
233
+ case "input":
234
+ yield* setupInput(x.fd, node, x.config.stream);
178
235
  break;
179
- }
180
- case "output": {
181
- let stream = Stream.empty;
182
- if (node && "read" in node) {
183
- const tap = new PassThrough();
184
- node.on("error", (err) => tap.destroy(toError(err)));
185
- node.pipe(tap);
186
- stream = NodeStream.fromReadable({
187
- evaluate: () => tap,
188
- onError: (err) => toPlatformError(`fromReadable(fd${x.fd})`, toError(err), command),
189
- });
190
- }
191
- if (x.config.sink)
192
- stream = Stream.transduce(stream, x.config.sink);
193
- outs.set(x.fd, stream);
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);
194
245
  break;
195
- }
196
246
  }
197
247
  }
198
248
  return {
@@ -203,6 +253,7 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
203
253
  const setupStdin = (command, proc, cfg) => Effect.suspend(() => {
204
254
  let sink = Sink.drain;
205
255
  if (Predicate.isNotNull(proc.stdin)) {
256
+ handleInputErrors(proc.stdin);
206
257
  sink = NodeSink.fromWritable({
207
258
  evaluate: () => proc.stdin,
208
259
  onError: (err) => toPlatformError("fromWritable(stdin)", toError(err), command),
@@ -243,11 +294,17 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
243
294
  const launchProcess = (command, opts) => Effect.callback((resume) => {
244
295
  const closed = Deferred.makeUnsafe();
245
296
  const exited = Deferred.makeUnsafe();
246
- const proc = launch(command.command, command.args, opts);
297
+ const proc = launch(command.command, command.args.map(unwrap), opts);
247
298
  let settle = () => { };
248
299
  let end = false;
249
300
  let exit;
250
301
  proc.on("error", (err) => {
302
+ // Node copies the arguments into `spawnargs`.
303
+ if (command.args.some(Redacted.isRedacted)) {
304
+ Object.assign(err, {
305
+ spawnargs: [command.command, ...command.args.map((arg) => (Redacted.isRedacted(arg) ? "<redacted>" : arg))],
306
+ });
307
+ }
251
308
  resume(Effect.fail(toPlatformError("spawn", err, command)));
252
309
  });
253
310
  proc.on("exit", (...args) => {
@@ -361,6 +418,10 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
361
418
  const spawnCommand = Effect.fnUntraced(function* (command) {
362
419
  switch (command._tag) {
363
420
  case "StandardCommand": {
421
+ const nul = findNulCharacter(command);
422
+ if (nul !== undefined) {
423
+ return yield* Effect.fail(PlatformError.badArgument({ module: "ChildProcess", method: "spawn", description: nul }));
424
+ }
364
425
  const sin = stdin(command.options);
365
426
  const sout = stdio(command.options, "stdout");
366
427
  const serr = stdio(command.options, "stderr");
@@ -457,11 +518,13 @@ const makeCrossSpawnSpawner = Effect.gen(function* () {
457
518
  }));
458
519
  continue;
459
520
  }
521
+ const name = ChildProcess.fdName(fd);
522
+ const existing = next.options.additionalFds?.[name];
460
523
  handle = spawnCommand(ChildProcess.make(next.command, next.args, {
461
524
  ...next.options,
462
525
  additionalFds: {
463
526
  ...next.options.additionalFds,
464
- [ChildProcess.fdName(fd)]: { type: "input", stream },
527
+ [name]: existing?.type === "duplex" ? { ...existing, stream } : { type: "input", stream },
465
528
  },
466
529
  }));
467
530
  }
package/dist/fs-util.d.ts CHANGED
@@ -10,10 +10,6 @@ export declare namespace FSUtil {
10
10
  get message(): string;
11
11
  }
12
12
  export type Error = PlatformError | FileSystemError;
13
- export interface DirEntry {
14
- readonly name: string;
15
- readonly type: "file" | "directory" | "symlink" | "other";
16
- }
17
13
  export interface UpOptions {
18
14
  readonly targets: string[];
19
15
  readonly start: string;
@@ -31,7 +27,6 @@ export declare namespace FSUtil {
31
27
  readonly writeJson: (path: string, data: unknown, mode?: number) => Effect.Effect<void, Error>;
32
28
  readonly ensureDir: (path: string) => Effect.Effect<void, Error>;
33
29
  readonly writeWithDirs: (path: string, content: string | Uint8Array, mode?: number) => Effect.Effect<void, Error>;
34
- readonly readDirectoryEntries: (path: string) => Effect.Effect<DirEntry[], Error>;
35
30
  readonly resolve: (path: string) => Effect.Effect<string>;
36
31
  readonly findUp: (target: string, start: string, stop?: string) => Effect.Effect<string[], Error>;
37
32
  readonly up: (options: UpOptions) => Effect.Effect<string[], Error>;
package/dist/fs-util.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import path, { dirname, isAbsolute, join, relative, sep } from "path";
2
2
  import { realpathSync } from "fs";
3
- import { readdir } from "fs/promises";
4
3
  import { lookup } from "mime-types";
5
4
  import { Context, Effect, FileSystem, Layer, Schema } from "effect";
6
5
  import { Glob } from "./glob.js";
@@ -23,7 +22,7 @@ export var FSUtil;
23
22
  }
24
23
  FSUtil.Service = Service;
25
24
  // Exported so simulation can wrap this layer and override the methods that
26
- // bypass the injected FileSystem (readDirectoryEntries, scan, globUp).
25
+ // bypass the injected FileSystem (scan, globUp).
27
26
  FSUtil.layer = Layer.effect(Service, Effect.gen(function* () {
28
27
  const fs = yield* FileSystem.FileSystem;
29
28
  const existsSafe = Effect.fn("FileSystem.existsSafe")(function* (path) {
@@ -42,18 +41,6 @@ export var FSUtil;
42
41
  const info = yield* fs.stat(path).pipe(Effect.catch(() => Effect.void));
43
42
  return info?.type === "File";
44
43
  });
45
- const readDirectoryEntries = Effect.fn("FileSystem.readDirectoryEntries")(function* (dirPath) {
46
- return yield* Effect.tryPromise({
47
- try: async () => {
48
- const entries = await readdir(dirPath, { withFileTypes: true });
49
- return entries.map((e) => ({
50
- name: e.name,
51
- type: e.isDirectory() ? "directory" : e.isSymbolicLink() ? "symlink" : e.isFile() ? "file" : "other",
52
- }));
53
- },
54
- catch: (cause) => new FileSystemError({ method: "readDirectoryEntries", cause }),
55
- });
56
- });
57
44
  const resolve = Effect.fn("FileSystem.resolve")(function* (input) {
58
45
  const resolved = path.resolve(windowsPath(input));
59
46
  // Sandboxes deny reads outside granted paths; canonicalize what we can see.
@@ -141,7 +128,6 @@ export var FSUtil;
141
128
  readFileStringSafe,
142
129
  isDir,
143
130
  isFile,
144
- readDirectoryEntries,
145
131
  resolve,
146
132
  readJson,
147
133
  writeJson,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@opencode/util",
4
- "version": "0.0.0-dev-416",
4
+ "version": "0.0.0-dev-425",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -46,9 +46,9 @@
46
46
  "typecheck:dist": "bun run build && bun typecheck --project tsconfig.dist.json"
47
47
  },
48
48
  "dependencies": {
49
- "@effect/opentelemetry": "4.0.6",
50
- "@effect/platform-node": "4.0.6",
51
- "@effect/platform-node-shared": "4.0.6",
49
+ "@effect/opentelemetry": "4.1.0",
50
+ "@effect/platform-node": "4.1.0",
51
+ "@effect/platform-node-shared": "4.1.0",
52
52
  "@npmcli/arborist": "9.4.0",
53
53
  "@npmcli/config": "10.8.1",
54
54
  "@opentelemetry/api": "1.9.0",
@@ -61,7 +61,7 @@
61
61
  "@opentelemetry/sdk-trace-base": "2.8.0",
62
62
  "@opentelemetry/sdk-trace-node": "2.8.0",
63
63
  "cross-spawn": "7.0.6",
64
- "effect": "4.0.6",
64
+ "effect": "4.1.0",
65
65
  "glob": "13.0.5",
66
66
  "mime-types": "3.0.2",
67
67
  "minimatch": "10.2.5",